httplib.h 400 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065
  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.27.0"
  10. #define CPPHTTPLIB_VERSION_NUM "0x001B00"
  11. /*
  12. * Platform compatibility check
  13. */
  14. #if defined(_WIN32) && !defined(_WIN64)
  15. #if defined(_MSC_VER)
  16. #pragma message( \
  17. "cpp-httplib doesn't support 32-bit Windows. Please use a 64-bit compiler.")
  18. #else
  19. #warning \
  20. "cpp-httplib doesn't support 32-bit Windows. Please use a 64-bit compiler."
  21. #endif
  22. #elif defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ < 8
  23. #warning \
  24. "cpp-httplib doesn't support 32-bit platforms. Please use a 64-bit compiler."
  25. #elif defined(__SIZEOF_SIZE_T__) && __SIZEOF_SIZE_T__ < 8
  26. #warning \
  27. "cpp-httplib doesn't support platforms where size_t is less than 64 bits."
  28. #endif
  29. #ifdef _WIN32
  30. #if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00
  31. #error \
  32. "cpp-httplib doesn't support Windows 8 or lower. Please use Windows 10 or later."
  33. #endif
  34. #endif
  35. /*
  36. * Configuration
  37. */
  38. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  39. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  40. #endif
  41. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND
  42. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000
  43. #endif
  44. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  45. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100
  46. #endif
  47. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
  48. #define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
  49. #endif
  50. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
  51. #define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
  52. #endif
  53. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND
  54. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5
  55. #endif
  56. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND
  57. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0
  58. #endif
  59. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND
  60. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5
  61. #endif
  62. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND
  63. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0
  64. #endif
  65. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND
  66. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300
  67. #endif
  68. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND
  69. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0
  70. #endif
  71. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND
  72. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5
  73. #endif
  74. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND
  75. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0
  76. #endif
  77. #ifndef CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND
  78. #define CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND 0
  79. #endif
  80. #ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
  81. #define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
  82. #endif
  83. #ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
  84. #ifdef _WIN32
  85. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 1000
  86. #else
  87. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
  88. #endif
  89. #endif
  90. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  91. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  92. #endif
  93. #ifndef CPPHTTPLIB_HEADER_MAX_LENGTH
  94. #define CPPHTTPLIB_HEADER_MAX_LENGTH 8192
  95. #endif
  96. #ifndef CPPHTTPLIB_HEADER_MAX_COUNT
  97. #define CPPHTTPLIB_HEADER_MAX_COUNT 100
  98. #endif
  99. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  100. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  101. #endif
  102. #ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT
  103. #define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024
  104. #endif
  105. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  106. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH ((std::numeric_limits<size_t>::max)())
  107. #endif
  108. #ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH
  109. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192
  110. #endif
  111. #ifndef CPPHTTPLIB_RANGE_MAX_COUNT
  112. #define CPPHTTPLIB_RANGE_MAX_COUNT 1024
  113. #endif
  114. #ifndef CPPHTTPLIB_TCP_NODELAY
  115. #define CPPHTTPLIB_TCP_NODELAY false
  116. #endif
  117. #ifndef CPPHTTPLIB_IPV6_V6ONLY
  118. #define CPPHTTPLIB_IPV6_V6ONLY false
  119. #endif
  120. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  121. #define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u)
  122. #endif
  123. #ifndef CPPHTTPLIB_SEND_BUFSIZ
  124. #define CPPHTTPLIB_SEND_BUFSIZ size_t(16384u)
  125. #endif
  126. #ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
  127. #define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
  128. #endif
  129. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  130. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  131. ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
  132. ? std::thread::hardware_concurrency() - 1 \
  133. : 0))
  134. #endif
  135. #ifndef CPPHTTPLIB_RECV_FLAGS
  136. #define CPPHTTPLIB_RECV_FLAGS 0
  137. #endif
  138. #ifndef CPPHTTPLIB_SEND_FLAGS
  139. #define CPPHTTPLIB_SEND_FLAGS 0
  140. #endif
  141. #ifndef CPPHTTPLIB_LISTEN_BACKLOG
  142. #define CPPHTTPLIB_LISTEN_BACKLOG 5
  143. #endif
  144. #ifndef CPPHTTPLIB_MAX_LINE_LENGTH
  145. #define CPPHTTPLIB_MAX_LINE_LENGTH 32768
  146. #endif
  147. /*
  148. * Headers
  149. */
  150. #ifdef _WIN32
  151. #ifndef _CRT_SECURE_NO_WARNINGS
  152. #define _CRT_SECURE_NO_WARNINGS
  153. #endif //_CRT_SECURE_NO_WARNINGS
  154. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  155. #define _CRT_NONSTDC_NO_DEPRECATE
  156. #endif //_CRT_NONSTDC_NO_DEPRECATE
  157. #if defined(_MSC_VER)
  158. #if _MSC_VER < 1900
  159. #error Sorry, Visual Studio versions prior to 2015 are not supported
  160. #endif
  161. #pragma comment(lib, "ws2_32.lib")
  162. using ssize_t = __int64;
  163. #endif // _MSC_VER
  164. #ifndef S_ISREG
  165. #define S_ISREG(m) (((m) & S_IFREG) == S_IFREG)
  166. #endif // S_ISREG
  167. #ifndef S_ISDIR
  168. #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR)
  169. #endif // S_ISDIR
  170. #ifndef NOMINMAX
  171. #define NOMINMAX
  172. #endif // NOMINMAX
  173. #include <io.h>
  174. #include <winsock2.h>
  175. #include <ws2tcpip.h>
  176. #if defined(__has_include)
  177. #if __has_include(<afunix.h>)
  178. // afunix.h uses types declared in winsock2.h, so has to be included after it.
  179. #include <afunix.h>
  180. #define CPPHTTPLIB_HAVE_AFUNIX_H 1
  181. #endif
  182. #endif
  183. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  184. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  185. #endif
  186. using nfds_t = unsigned long;
  187. using socket_t = SOCKET;
  188. using socklen_t = int;
  189. #else // not _WIN32
  190. #include <arpa/inet.h>
  191. #if !defined(_AIX) && !defined(__MVS__)
  192. #include <ifaddrs.h>
  193. #endif
  194. #ifdef __MVS__
  195. #include <strings.h>
  196. #ifndef NI_MAXHOST
  197. #define NI_MAXHOST 1025
  198. #endif
  199. #endif
  200. #include <net/if.h>
  201. #include <netdb.h>
  202. #include <netinet/in.h>
  203. #ifdef __linux__
  204. #include <resolv.h>
  205. #endif
  206. #include <csignal>
  207. #include <netinet/tcp.h>
  208. #include <poll.h>
  209. #include <pthread.h>
  210. #include <sys/mman.h>
  211. #include <sys/socket.h>
  212. #include <sys/un.h>
  213. #include <unistd.h>
  214. using socket_t = int;
  215. #ifndef INVALID_SOCKET
  216. #define INVALID_SOCKET (-1)
  217. #endif
  218. #endif //_WIN32
  219. #if defined(__APPLE__)
  220. #include <TargetConditionals.h>
  221. #endif
  222. #include <algorithm>
  223. #include <array>
  224. #include <atomic>
  225. #include <cassert>
  226. #include <cctype>
  227. #include <climits>
  228. #include <condition_variable>
  229. #include <cstring>
  230. #include <errno.h>
  231. #include <exception>
  232. #include <fcntl.h>
  233. #include <functional>
  234. #include <iomanip>
  235. #include <iostream>
  236. #include <list>
  237. #include <map>
  238. #include <memory>
  239. #include <mutex>
  240. #include <random>
  241. #include <regex>
  242. #include <set>
  243. #include <sstream>
  244. #include <string>
  245. #include <sys/stat.h>
  246. #include <thread>
  247. #include <unordered_map>
  248. #include <unordered_set>
  249. #include <utility>
  250. #if defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO) || \
  251. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  252. #if TARGET_OS_MAC
  253. #include <CFNetwork/CFHost.h>
  254. #include <CoreFoundation/CoreFoundation.h>
  255. #endif
  256. #endif // CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO or
  257. // CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  258. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  259. #ifdef _WIN32
  260. #include <wincrypt.h>
  261. // these are defined in wincrypt.h and it breaks compilation if BoringSSL is
  262. // used
  263. #undef X509_NAME
  264. #undef X509_CERT_PAIR
  265. #undef X509_EXTENSIONS
  266. #undef PKCS7_SIGNER_INFO
  267. #ifdef _MSC_VER
  268. #pragma comment(lib, "crypt32.lib")
  269. #endif
  270. #endif // _WIN32
  271. #if defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  272. #if TARGET_OS_MAC
  273. #include <Security/Security.h>
  274. #endif
  275. #endif // CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  276. #include <openssl/err.h>
  277. #include <openssl/evp.h>
  278. #include <openssl/ssl.h>
  279. #include <openssl/x509v3.h>
  280. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  281. #include <openssl/applink.c>
  282. #endif
  283. #include <iostream>
  284. #include <sstream>
  285. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  286. #if OPENSSL_VERSION_NUMBER < 0x1010107f
  287. #error Please use OpenSSL or a current version of BoringSSL
  288. #endif
  289. #define SSL_get1_peer_certificate SSL_get_peer_certificate
  290. #elif OPENSSL_VERSION_NUMBER < 0x30000000L
  291. #error Sorry, OpenSSL versions prior to 3.0.0 are not supported
  292. #endif
  293. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  294. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  295. #include <zlib.h>
  296. #endif
  297. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  298. #include <brotli/decode.h>
  299. #include <brotli/encode.h>
  300. #endif
  301. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  302. #include <zstd.h>
  303. #endif
  304. /*
  305. * Declaration
  306. */
  307. namespace httplib {
  308. namespace detail {
  309. /*
  310. * Backport std::make_unique from C++14.
  311. *
  312. * NOTE: This code came up with the following stackoverflow post:
  313. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  314. *
  315. */
  316. template <class T, class... Args>
  317. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  318. make_unique(Args &&...args) {
  319. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  320. }
  321. template <class T>
  322. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  323. make_unique(std::size_t n) {
  324. typedef typename std::remove_extent<T>::type RT;
  325. return std::unique_ptr<T>(new RT[n]);
  326. }
  327. namespace case_ignore {
  328. inline unsigned char to_lower(int c) {
  329. const static unsigned char table[256] = {
  330. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  331. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  332. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  333. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  334. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  335. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  336. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  337. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  338. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  339. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  340. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  341. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  342. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  343. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  344. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  345. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  346. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  347. 255,
  348. };
  349. return table[(unsigned char)(char)c];
  350. }
  351. inline bool equal(const std::string &a, const std::string &b) {
  352. return a.size() == b.size() &&
  353. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  354. return to_lower(ca) == to_lower(cb);
  355. });
  356. }
  357. struct equal_to {
  358. bool operator()(const std::string &a, const std::string &b) const {
  359. return equal(a, b);
  360. }
  361. };
  362. struct hash {
  363. size_t operator()(const std::string &key) const {
  364. return hash_core(key.data(), key.size(), 0);
  365. }
  366. size_t hash_core(const char *s, size_t l, size_t h) const {
  367. return (l == 0) ? h
  368. : hash_core(s + 1, l - 1,
  369. // Unsets the 6 high bits of h, therefore no
  370. // overflow happens
  371. (((std::numeric_limits<size_t>::max)() >> 6) &
  372. h * 33) ^
  373. static_cast<unsigned char>(to_lower(*s)));
  374. }
  375. };
  376. template <typename T>
  377. using unordered_set = std::unordered_set<T, detail::case_ignore::hash,
  378. detail::case_ignore::equal_to>;
  379. } // namespace case_ignore
  380. // This is based on
  381. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  382. struct scope_exit {
  383. explicit scope_exit(std::function<void(void)> &&f)
  384. : exit_function(std::move(f)), execute_on_destruction{true} {}
  385. scope_exit(scope_exit &&rhs) noexcept
  386. : exit_function(std::move(rhs.exit_function)),
  387. execute_on_destruction{rhs.execute_on_destruction} {
  388. rhs.release();
  389. }
  390. ~scope_exit() {
  391. if (execute_on_destruction) { this->exit_function(); }
  392. }
  393. void release() { this->execute_on_destruction = false; }
  394. private:
  395. scope_exit(const scope_exit &) = delete;
  396. void operator=(const scope_exit &) = delete;
  397. scope_exit &operator=(scope_exit &&) = delete;
  398. std::function<void(void)> exit_function;
  399. bool execute_on_destruction;
  400. };
  401. } // namespace detail
  402. enum SSLVerifierResponse {
  403. // no decision has been made, use the built-in certificate verifier
  404. NoDecisionMade,
  405. // connection certificate is verified and accepted
  406. CertificateAccepted,
  407. // connection certificate was processed but is rejected
  408. CertificateRejected
  409. };
  410. enum StatusCode {
  411. // Information responses
  412. Continue_100 = 100,
  413. SwitchingProtocol_101 = 101,
  414. Processing_102 = 102,
  415. EarlyHints_103 = 103,
  416. // Successful responses
  417. OK_200 = 200,
  418. Created_201 = 201,
  419. Accepted_202 = 202,
  420. NonAuthoritativeInformation_203 = 203,
  421. NoContent_204 = 204,
  422. ResetContent_205 = 205,
  423. PartialContent_206 = 206,
  424. MultiStatus_207 = 207,
  425. AlreadyReported_208 = 208,
  426. IMUsed_226 = 226,
  427. // Redirection messages
  428. MultipleChoices_300 = 300,
  429. MovedPermanently_301 = 301,
  430. Found_302 = 302,
  431. SeeOther_303 = 303,
  432. NotModified_304 = 304,
  433. UseProxy_305 = 305,
  434. unused_306 = 306,
  435. TemporaryRedirect_307 = 307,
  436. PermanentRedirect_308 = 308,
  437. // Client error responses
  438. BadRequest_400 = 400,
  439. Unauthorized_401 = 401,
  440. PaymentRequired_402 = 402,
  441. Forbidden_403 = 403,
  442. NotFound_404 = 404,
  443. MethodNotAllowed_405 = 405,
  444. NotAcceptable_406 = 406,
  445. ProxyAuthenticationRequired_407 = 407,
  446. RequestTimeout_408 = 408,
  447. Conflict_409 = 409,
  448. Gone_410 = 410,
  449. LengthRequired_411 = 411,
  450. PreconditionFailed_412 = 412,
  451. PayloadTooLarge_413 = 413,
  452. UriTooLong_414 = 414,
  453. UnsupportedMediaType_415 = 415,
  454. RangeNotSatisfiable_416 = 416,
  455. ExpectationFailed_417 = 417,
  456. ImATeapot_418 = 418,
  457. MisdirectedRequest_421 = 421,
  458. UnprocessableContent_422 = 422,
  459. Locked_423 = 423,
  460. FailedDependency_424 = 424,
  461. TooEarly_425 = 425,
  462. UpgradeRequired_426 = 426,
  463. PreconditionRequired_428 = 428,
  464. TooManyRequests_429 = 429,
  465. RequestHeaderFieldsTooLarge_431 = 431,
  466. UnavailableForLegalReasons_451 = 451,
  467. // Server error responses
  468. InternalServerError_500 = 500,
  469. NotImplemented_501 = 501,
  470. BadGateway_502 = 502,
  471. ServiceUnavailable_503 = 503,
  472. GatewayTimeout_504 = 504,
  473. HttpVersionNotSupported_505 = 505,
  474. VariantAlsoNegotiates_506 = 506,
  475. InsufficientStorage_507 = 507,
  476. LoopDetected_508 = 508,
  477. NotExtended_510 = 510,
  478. NetworkAuthenticationRequired_511 = 511,
  479. };
  480. using Headers =
  481. std::unordered_multimap<std::string, std::string, detail::case_ignore::hash,
  482. detail::case_ignore::equal_to>;
  483. using Params = std::multimap<std::string, std::string>;
  484. using Match = std::smatch;
  485. using DownloadProgress = std::function<bool(size_t current, size_t total)>;
  486. using UploadProgress = std::function<bool(size_t current, size_t total)>;
  487. struct Response;
  488. using ResponseHandler = std::function<bool(const Response &response)>;
  489. struct FormData {
  490. std::string name;
  491. std::string content;
  492. std::string filename;
  493. std::string content_type;
  494. Headers headers;
  495. };
  496. struct FormField {
  497. std::string name;
  498. std::string content;
  499. Headers headers;
  500. };
  501. using FormFields = std::multimap<std::string, FormField>;
  502. using FormFiles = std::multimap<std::string, FormData>;
  503. struct MultipartFormData {
  504. FormFields fields; // Text fields from multipart
  505. FormFiles files; // Files from multipart
  506. // Text field access
  507. std::string get_field(const std::string &key, size_t id = 0) const;
  508. std::vector<std::string> get_fields(const std::string &key) const;
  509. bool has_field(const std::string &key) const;
  510. size_t get_field_count(const std::string &key) const;
  511. // File access
  512. FormData get_file(const std::string &key, size_t id = 0) const;
  513. std::vector<FormData> get_files(const std::string &key) const;
  514. bool has_file(const std::string &key) const;
  515. size_t get_file_count(const std::string &key) const;
  516. };
  517. struct UploadFormData {
  518. std::string name;
  519. std::string content;
  520. std::string filename;
  521. std::string content_type;
  522. };
  523. using UploadFormDataItems = std::vector<UploadFormData>;
  524. class DataSink {
  525. public:
  526. DataSink() : os(&sb_), sb_(*this) {}
  527. DataSink(const DataSink &) = delete;
  528. DataSink &operator=(const DataSink &) = delete;
  529. DataSink(DataSink &&) = delete;
  530. DataSink &operator=(DataSink &&) = delete;
  531. std::function<bool(const char *data, size_t data_len)> write;
  532. std::function<bool()> is_writable;
  533. std::function<void()> done;
  534. std::function<void(const Headers &trailer)> done_with_trailer;
  535. std::ostream os;
  536. private:
  537. class data_sink_streambuf final : public std::streambuf {
  538. public:
  539. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  540. protected:
  541. std::streamsize xsputn(const char *s, std::streamsize n) override {
  542. sink_.write(s, static_cast<size_t>(n));
  543. return n;
  544. }
  545. private:
  546. DataSink &sink_;
  547. };
  548. data_sink_streambuf sb_;
  549. };
  550. using ContentProvider =
  551. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  552. using ContentProviderWithoutLength =
  553. std::function<bool(size_t offset, DataSink &sink)>;
  554. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  555. struct FormDataProvider {
  556. std::string name;
  557. ContentProviderWithoutLength provider;
  558. std::string filename;
  559. std::string content_type;
  560. };
  561. using FormDataProviderItems = std::vector<FormDataProvider>;
  562. using ContentReceiverWithProgress = std::function<bool(
  563. const char *data, size_t data_length, size_t offset, size_t total_length)>;
  564. using ContentReceiver =
  565. std::function<bool(const char *data, size_t data_length)>;
  566. using FormDataHeader = std::function<bool(const FormData &file)>;
  567. class ContentReader {
  568. public:
  569. using Reader = std::function<bool(ContentReceiver receiver)>;
  570. using FormDataReader =
  571. std::function<bool(FormDataHeader header, ContentReceiver receiver)>;
  572. ContentReader(Reader reader, FormDataReader multipart_reader)
  573. : reader_(std::move(reader)),
  574. formdata_reader_(std::move(multipart_reader)) {}
  575. bool operator()(FormDataHeader header, ContentReceiver receiver) const {
  576. return formdata_reader_(std::move(header), std::move(receiver));
  577. }
  578. bool operator()(ContentReceiver receiver) const {
  579. return reader_(std::move(receiver));
  580. }
  581. Reader reader_;
  582. FormDataReader formdata_reader_;
  583. };
  584. using Range = std::pair<ssize_t, ssize_t>;
  585. using Ranges = std::vector<Range>;
  586. struct Request {
  587. std::string method;
  588. std::string path;
  589. std::string matched_route;
  590. Params params;
  591. Headers headers;
  592. Headers trailers;
  593. std::string body;
  594. std::string remote_addr;
  595. int remote_port = -1;
  596. std::string local_addr;
  597. int local_port = -1;
  598. // for server
  599. std::string version;
  600. std::string target;
  601. MultipartFormData form;
  602. Ranges ranges;
  603. Match matches;
  604. std::unordered_map<std::string, std::string> path_params;
  605. std::function<bool()> is_connection_closed = []() { return true; };
  606. // for client
  607. std::vector<std::string> accept_content_types;
  608. ResponseHandler response_handler;
  609. ContentReceiverWithProgress content_receiver;
  610. DownloadProgress download_progress;
  611. UploadProgress upload_progress;
  612. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  613. const SSL *ssl = nullptr;
  614. #endif
  615. bool has_header(const std::string &key) const;
  616. std::string get_header_value(const std::string &key, const char *def = "",
  617. size_t id = 0) const;
  618. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  619. size_t id = 0) const;
  620. size_t get_header_value_count(const std::string &key) const;
  621. void set_header(const std::string &key, const std::string &val);
  622. bool has_trailer(const std::string &key) const;
  623. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  624. size_t get_trailer_value_count(const std::string &key) const;
  625. bool has_param(const std::string &key) const;
  626. std::string get_param_value(const std::string &key, size_t id = 0) const;
  627. size_t get_param_value_count(const std::string &key) const;
  628. bool is_multipart_form_data() const;
  629. // private members...
  630. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  631. size_t content_length_ = 0;
  632. ContentProvider content_provider_;
  633. bool is_chunked_content_provider_ = false;
  634. size_t authorization_count_ = 0;
  635. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  636. (std::chrono::steady_clock::time_point::min)();
  637. };
  638. struct Response {
  639. std::string version;
  640. int status = -1;
  641. std::string reason;
  642. Headers headers;
  643. Headers trailers;
  644. std::string body;
  645. std::string location; // Redirect location
  646. bool has_header(const std::string &key) const;
  647. std::string get_header_value(const std::string &key, const char *def = "",
  648. size_t id = 0) const;
  649. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  650. size_t id = 0) const;
  651. size_t get_header_value_count(const std::string &key) const;
  652. void set_header(const std::string &key, const std::string &val);
  653. bool has_trailer(const std::string &key) const;
  654. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  655. size_t get_trailer_value_count(const std::string &key) const;
  656. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  657. void set_content(const char *s, size_t n, const std::string &content_type);
  658. void set_content(const std::string &s, const std::string &content_type);
  659. void set_content(std::string &&s, const std::string &content_type);
  660. void set_content_provider(
  661. size_t length, const std::string &content_type, ContentProvider provider,
  662. ContentProviderResourceReleaser resource_releaser = nullptr);
  663. void set_content_provider(
  664. const std::string &content_type, ContentProviderWithoutLength provider,
  665. ContentProviderResourceReleaser resource_releaser = nullptr);
  666. void set_chunked_content_provider(
  667. const std::string &content_type, ContentProviderWithoutLength provider,
  668. ContentProviderResourceReleaser resource_releaser = nullptr);
  669. void set_file_content(const std::string &path,
  670. const std::string &content_type);
  671. void set_file_content(const std::string &path);
  672. Response() = default;
  673. Response(const Response &) = default;
  674. Response &operator=(const Response &) = default;
  675. Response(Response &&) = default;
  676. Response &operator=(Response &&) = default;
  677. ~Response() {
  678. if (content_provider_resource_releaser_) {
  679. content_provider_resource_releaser_(content_provider_success_);
  680. }
  681. }
  682. // private members...
  683. size_t content_length_ = 0;
  684. ContentProvider content_provider_;
  685. ContentProviderResourceReleaser content_provider_resource_releaser_;
  686. bool is_chunked_content_provider_ = false;
  687. bool content_provider_success_ = false;
  688. std::string file_content_path_;
  689. std::string file_content_content_type_;
  690. };
  691. class Stream {
  692. public:
  693. virtual ~Stream() = default;
  694. virtual bool is_readable() const = 0;
  695. virtual bool wait_readable() const = 0;
  696. virtual bool wait_writable() const = 0;
  697. virtual ssize_t read(char *ptr, size_t size) = 0;
  698. virtual ssize_t write(const char *ptr, size_t size) = 0;
  699. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  700. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  701. virtual socket_t socket() const = 0;
  702. virtual time_t duration() const = 0;
  703. ssize_t write(const char *ptr);
  704. ssize_t write(const std::string &s);
  705. };
  706. class TaskQueue {
  707. public:
  708. TaskQueue() = default;
  709. virtual ~TaskQueue() = default;
  710. virtual bool enqueue(std::function<void()> fn) = 0;
  711. virtual void shutdown() = 0;
  712. virtual void on_idle() {}
  713. };
  714. class ThreadPool final : public TaskQueue {
  715. public:
  716. explicit ThreadPool(size_t n, size_t mqr = 0)
  717. : shutdown_(false), max_queued_requests_(mqr) {
  718. while (n) {
  719. threads_.emplace_back(worker(*this));
  720. n--;
  721. }
  722. }
  723. ThreadPool(const ThreadPool &) = delete;
  724. ~ThreadPool() override = default;
  725. bool enqueue(std::function<void()> fn) override {
  726. {
  727. std::unique_lock<std::mutex> lock(mutex_);
  728. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  729. return false;
  730. }
  731. jobs_.push_back(std::move(fn));
  732. }
  733. cond_.notify_one();
  734. return true;
  735. }
  736. void shutdown() override {
  737. // Stop all worker threads...
  738. {
  739. std::unique_lock<std::mutex> lock(mutex_);
  740. shutdown_ = true;
  741. }
  742. cond_.notify_all();
  743. // Join...
  744. for (auto &t : threads_) {
  745. t.join();
  746. }
  747. }
  748. private:
  749. struct worker {
  750. explicit worker(ThreadPool &pool) : pool_(pool) {}
  751. void operator()() {
  752. for (;;) {
  753. std::function<void()> fn;
  754. {
  755. std::unique_lock<std::mutex> lock(pool_.mutex_);
  756. pool_.cond_.wait(
  757. lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; });
  758. if (pool_.shutdown_ && pool_.jobs_.empty()) { break; }
  759. fn = pool_.jobs_.front();
  760. pool_.jobs_.pop_front();
  761. }
  762. assert(true == static_cast<bool>(fn));
  763. fn();
  764. }
  765. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  766. !defined(LIBRESSL_VERSION_NUMBER)
  767. OPENSSL_thread_stop();
  768. #endif
  769. }
  770. ThreadPool &pool_;
  771. };
  772. friend struct worker;
  773. std::vector<std::thread> threads_;
  774. std::list<std::function<void()>> jobs_;
  775. bool shutdown_;
  776. size_t max_queued_requests_ = 0;
  777. std::condition_variable cond_;
  778. std::mutex mutex_;
  779. };
  780. using Logger = std::function<void(const Request &, const Response &)>;
  781. // Forward declaration for Error type
  782. enum class Error;
  783. using ErrorLogger = std::function<void(const Error &, const Request *)>;
  784. using SocketOptions = std::function<void(socket_t sock)>;
  785. namespace detail {
  786. bool set_socket_opt_impl(socket_t sock, int level, int optname,
  787. const void *optval, socklen_t optlen);
  788. bool set_socket_opt(socket_t sock, int level, int optname, int opt);
  789. bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec,
  790. time_t usec);
  791. } // namespace detail
  792. void default_socket_options(socket_t sock);
  793. const char *status_message(int status);
  794. std::string get_bearer_token_auth(const Request &req);
  795. namespace detail {
  796. class MatcherBase {
  797. public:
  798. MatcherBase(std::string pattern) : pattern_(pattern) {}
  799. virtual ~MatcherBase() = default;
  800. const std::string &pattern() const { return pattern_; }
  801. // Match request path and populate its matches and
  802. virtual bool match(Request &request) const = 0;
  803. private:
  804. std::string pattern_;
  805. };
  806. /**
  807. * Captures parameters in request path and stores them in Request::path_params
  808. *
  809. * Capture name is a substring of a pattern from : to /.
  810. * The rest of the pattern is matched against the request path directly
  811. * Parameters are captured starting from the next character after
  812. * the end of the last matched static pattern fragment until the next /.
  813. *
  814. * Example pattern:
  815. * "/path/fragments/:capture/more/fragments/:second_capture"
  816. * Static fragments:
  817. * "/path/fragments/", "more/fragments/"
  818. *
  819. * Given the following request path:
  820. * "/path/fragments/:1/more/fragments/:2"
  821. * the resulting capture will be
  822. * {{"capture", "1"}, {"second_capture", "2"}}
  823. */
  824. class PathParamsMatcher final : public MatcherBase {
  825. public:
  826. PathParamsMatcher(const std::string &pattern);
  827. bool match(Request &request) const override;
  828. private:
  829. // Treat segment separators as the end of path parameter capture
  830. // Does not need to handle query parameters as they are parsed before path
  831. // matching
  832. static constexpr char separator = '/';
  833. // Contains static path fragments to match against, excluding the '/' after
  834. // path params
  835. // Fragments are separated by path params
  836. std::vector<std::string> static_fragments_;
  837. // Stores the names of the path parameters to be used as keys in the
  838. // Request::path_params map
  839. std::vector<std::string> param_names_;
  840. };
  841. /**
  842. * Performs std::regex_match on request path
  843. * and stores the result in Request::matches
  844. *
  845. * Note that regex match is performed directly on the whole request.
  846. * This means that wildcard patterns may match multiple path segments with /:
  847. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  848. */
  849. class RegexMatcher final : public MatcherBase {
  850. public:
  851. RegexMatcher(const std::string &pattern)
  852. : MatcherBase(pattern), regex_(pattern) {}
  853. bool match(Request &request) const override;
  854. private:
  855. std::regex regex_;
  856. };
  857. ssize_t write_headers(Stream &strm, const Headers &headers);
  858. std::string make_host_and_port_string(const std::string &host, int port,
  859. bool is_ssl);
  860. } // namespace detail
  861. class Server {
  862. public:
  863. using Handler = std::function<void(const Request &, Response &)>;
  864. using ExceptionHandler =
  865. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  866. enum class HandlerResponse {
  867. Handled,
  868. Unhandled,
  869. };
  870. using HandlerWithResponse =
  871. std::function<HandlerResponse(const Request &, Response &)>;
  872. using HandlerWithContentReader = std::function<void(
  873. const Request &, Response &, const ContentReader &content_reader)>;
  874. using Expect100ContinueHandler =
  875. std::function<int(const Request &, Response &)>;
  876. Server();
  877. virtual ~Server();
  878. virtual bool is_valid() const;
  879. Server &Get(const std::string &pattern, Handler handler);
  880. Server &Post(const std::string &pattern, Handler handler);
  881. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  882. Server &Put(const std::string &pattern, Handler handler);
  883. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  884. Server &Patch(const std::string &pattern, Handler handler);
  885. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  886. Server &Delete(const std::string &pattern, Handler handler);
  887. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  888. Server &Options(const std::string &pattern, Handler handler);
  889. bool set_base_dir(const std::string &dir,
  890. const std::string &mount_point = std::string());
  891. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  892. Headers headers = Headers());
  893. bool remove_mount_point(const std::string &mount_point);
  894. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  895. const std::string &mime);
  896. Server &set_default_file_mimetype(const std::string &mime);
  897. Server &set_file_request_handler(Handler handler);
  898. template <class ErrorHandlerFunc>
  899. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  900. return set_error_handler_core(
  901. std::forward<ErrorHandlerFunc>(handler),
  902. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  903. }
  904. Server &set_exception_handler(ExceptionHandler handler);
  905. Server &set_pre_routing_handler(HandlerWithResponse handler);
  906. Server &set_post_routing_handler(Handler handler);
  907. Server &set_pre_request_handler(HandlerWithResponse handler);
  908. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  909. Server &set_logger(Logger logger);
  910. Server &set_pre_compression_logger(Logger logger);
  911. Server &set_error_logger(ErrorLogger error_logger);
  912. Server &set_address_family(int family);
  913. Server &set_tcp_nodelay(bool on);
  914. Server &set_ipv6_v6only(bool on);
  915. Server &set_socket_options(SocketOptions socket_options);
  916. Server &set_default_headers(Headers headers);
  917. Server &
  918. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  919. Server &set_trusted_proxies(const std::vector<std::string> &proxies);
  920. Server &set_keep_alive_max_count(size_t count);
  921. Server &set_keep_alive_timeout(time_t sec);
  922. Server &set_read_timeout(time_t sec, time_t usec = 0);
  923. template <class Rep, class Period>
  924. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  925. Server &set_write_timeout(time_t sec, time_t usec = 0);
  926. template <class Rep, class Period>
  927. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  928. Server &set_idle_interval(time_t sec, time_t usec = 0);
  929. template <class Rep, class Period>
  930. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  931. Server &set_payload_max_length(size_t length);
  932. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  933. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  934. bool listen_after_bind();
  935. bool listen(const std::string &host, int port, int socket_flags = 0);
  936. bool is_running() const;
  937. void wait_until_ready() const;
  938. void stop();
  939. void decommission();
  940. std::function<TaskQueue *(void)> new_task_queue;
  941. protected:
  942. bool process_request(Stream &strm, const std::string &remote_addr,
  943. int remote_port, const std::string &local_addr,
  944. int local_port, bool close_connection,
  945. bool &connection_closed,
  946. const std::function<void(Request &)> &setup_request);
  947. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  948. std::vector<std::string> trusted_proxies_;
  949. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  950. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  951. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  952. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  953. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  954. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  955. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  956. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  957. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  958. private:
  959. using Handlers =
  960. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  961. using HandlersForContentReader =
  962. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  963. HandlerWithContentReader>>;
  964. static std::unique_ptr<detail::MatcherBase>
  965. make_matcher(const std::string &pattern);
  966. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  967. Server &set_error_handler_core(Handler handler, std::false_type);
  968. socket_t create_server_socket(const std::string &host, int port,
  969. int socket_flags,
  970. SocketOptions socket_options) const;
  971. int bind_internal(const std::string &host, int port, int socket_flags);
  972. bool listen_internal();
  973. bool routing(Request &req, Response &res, Stream &strm);
  974. bool handle_file_request(const Request &req, Response &res);
  975. bool dispatch_request(Request &req, Response &res,
  976. const Handlers &handlers) const;
  977. bool dispatch_request_for_content_reader(
  978. Request &req, Response &res, ContentReader content_reader,
  979. const HandlersForContentReader &handlers) const;
  980. bool parse_request_line(const char *s, Request &req) const;
  981. void apply_ranges(const Request &req, Response &res,
  982. std::string &content_type, std::string &boundary) const;
  983. bool write_response(Stream &strm, bool close_connection, Request &req,
  984. Response &res);
  985. bool write_response_with_content(Stream &strm, bool close_connection,
  986. const Request &req, Response &res);
  987. bool write_response_core(Stream &strm, bool close_connection,
  988. const Request &req, Response &res,
  989. bool need_apply_ranges);
  990. bool write_content_with_provider(Stream &strm, const Request &req,
  991. Response &res, const std::string &boundary,
  992. const std::string &content_type);
  993. bool read_content(Stream &strm, Request &req, Response &res);
  994. bool read_content_with_content_receiver(Stream &strm, Request &req,
  995. Response &res,
  996. ContentReceiver receiver,
  997. FormDataHeader multipart_header,
  998. ContentReceiver multipart_receiver);
  999. bool read_content_core(Stream &strm, Request &req, Response &res,
  1000. ContentReceiver receiver,
  1001. FormDataHeader multipart_header,
  1002. ContentReceiver multipart_receiver) const;
  1003. virtual bool process_and_close_socket(socket_t sock);
  1004. void output_log(const Request &req, const Response &res) const;
  1005. void output_pre_compression_log(const Request &req,
  1006. const Response &res) const;
  1007. void output_error_log(const Error &err, const Request *req) const;
  1008. std::atomic<bool> is_running_{false};
  1009. std::atomic<bool> is_decommissioned{false};
  1010. struct MountPointEntry {
  1011. std::string mount_point;
  1012. std::string base_dir;
  1013. Headers headers;
  1014. };
  1015. std::vector<MountPointEntry> base_dirs_;
  1016. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  1017. std::string default_file_mimetype_ = "application/octet-stream";
  1018. Handler file_request_handler_;
  1019. Handlers get_handlers_;
  1020. Handlers post_handlers_;
  1021. HandlersForContentReader post_handlers_for_content_reader_;
  1022. Handlers put_handlers_;
  1023. HandlersForContentReader put_handlers_for_content_reader_;
  1024. Handlers patch_handlers_;
  1025. HandlersForContentReader patch_handlers_for_content_reader_;
  1026. Handlers delete_handlers_;
  1027. HandlersForContentReader delete_handlers_for_content_reader_;
  1028. Handlers options_handlers_;
  1029. HandlerWithResponse error_handler_;
  1030. ExceptionHandler exception_handler_;
  1031. HandlerWithResponse pre_routing_handler_;
  1032. Handler post_routing_handler_;
  1033. HandlerWithResponse pre_request_handler_;
  1034. Expect100ContinueHandler expect_100_continue_handler_;
  1035. mutable std::mutex logger_mutex_;
  1036. Logger logger_;
  1037. Logger pre_compression_logger_;
  1038. ErrorLogger error_logger_;
  1039. int address_family_ = AF_UNSPEC;
  1040. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1041. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1042. SocketOptions socket_options_ = default_socket_options;
  1043. Headers default_headers_;
  1044. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1045. detail::write_headers;
  1046. };
  1047. enum class Error {
  1048. Success = 0,
  1049. Unknown,
  1050. Connection,
  1051. BindIPAddress,
  1052. Read,
  1053. Write,
  1054. ExceedRedirectCount,
  1055. Canceled,
  1056. SSLConnection,
  1057. SSLLoadingCerts,
  1058. SSLServerVerification,
  1059. SSLServerHostnameVerification,
  1060. UnsupportedMultipartBoundaryChars,
  1061. Compression,
  1062. ConnectionTimeout,
  1063. ProxyConnection,
  1064. ResourceExhaustion,
  1065. TooManyFormDataFiles,
  1066. ExceedMaxPayloadSize,
  1067. ExceedUriMaxLength,
  1068. ExceedMaxSocketDescriptorCount,
  1069. InvalidRequestLine,
  1070. InvalidHTTPMethod,
  1071. InvalidHTTPVersion,
  1072. InvalidHeaders,
  1073. MultipartParsing,
  1074. OpenFile,
  1075. Listen,
  1076. GetSockName,
  1077. UnsupportedAddressFamily,
  1078. HTTPParsing,
  1079. InvalidRangeHeader,
  1080. // For internal use only
  1081. SSLPeerCouldBeClosed_,
  1082. };
  1083. std::string to_string(Error error);
  1084. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1085. class Result {
  1086. public:
  1087. Result() = default;
  1088. Result(std::unique_ptr<Response> &&res, Error err,
  1089. Headers &&request_headers = Headers{})
  1090. : res_(std::move(res)), err_(err),
  1091. request_headers_(std::move(request_headers)) {}
  1092. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1093. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1094. int ssl_error)
  1095. : res_(std::move(res)), err_(err),
  1096. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  1097. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1098. int ssl_error, unsigned long ssl_openssl_error)
  1099. : res_(std::move(res)), err_(err),
  1100. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  1101. ssl_openssl_error_(ssl_openssl_error) {}
  1102. #endif
  1103. // Response
  1104. operator bool() const { return res_ != nullptr; }
  1105. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  1106. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  1107. const Response &value() const { return *res_; }
  1108. Response &value() { return *res_; }
  1109. const Response &operator*() const { return *res_; }
  1110. Response &operator*() { return *res_; }
  1111. const Response *operator->() const { return res_.get(); }
  1112. Response *operator->() { return res_.get(); }
  1113. // Error
  1114. Error error() const { return err_; }
  1115. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1116. // SSL Error
  1117. int ssl_error() const { return ssl_error_; }
  1118. // OpenSSL Error
  1119. unsigned long ssl_openssl_error() const { return ssl_openssl_error_; }
  1120. #endif
  1121. // Request Headers
  1122. bool has_request_header(const std::string &key) const;
  1123. std::string get_request_header_value(const std::string &key,
  1124. const char *def = "",
  1125. size_t id = 0) const;
  1126. size_t get_request_header_value_u64(const std::string &key, size_t def = 0,
  1127. size_t id = 0) const;
  1128. size_t get_request_header_value_count(const std::string &key) const;
  1129. private:
  1130. std::unique_ptr<Response> res_;
  1131. Error err_ = Error::Unknown;
  1132. Headers request_headers_;
  1133. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1134. int ssl_error_ = 0;
  1135. unsigned long ssl_openssl_error_ = 0;
  1136. #endif
  1137. };
  1138. class ClientImpl {
  1139. public:
  1140. explicit ClientImpl(const std::string &host);
  1141. explicit ClientImpl(const std::string &host, int port);
  1142. explicit ClientImpl(const std::string &host, int port,
  1143. const std::string &client_cert_path,
  1144. const std::string &client_key_path);
  1145. virtual ~ClientImpl();
  1146. virtual bool is_valid() const;
  1147. // clang-format off
  1148. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1149. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1150. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1151. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1152. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1153. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1154. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1155. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1156. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1157. Result Head(const std::string &path);
  1158. Result Head(const std::string &path, const Headers &headers);
  1159. Result Post(const std::string &path);
  1160. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1161. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1162. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1163. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1164. Result Post(const std::string &path, const Params &params);
  1165. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1166. Result Post(const std::string &path, const Headers &headers);
  1167. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1168. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1169. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1170. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1171. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1172. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1173. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1174. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1175. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1176. Result Put(const std::string &path);
  1177. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1178. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1179. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1180. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1181. Result Put(const std::string &path, const Params &params);
  1182. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1183. Result Put(const std::string &path, const Headers &headers);
  1184. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1185. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1186. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1187. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1188. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1189. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1190. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1191. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1192. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1193. Result Patch(const std::string &path);
  1194. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1195. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1196. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1197. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1198. Result Patch(const std::string &path, const Params &params);
  1199. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1200. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1201. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1202. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1203. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1204. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1205. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1206. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1207. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1208. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1209. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1210. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1211. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1212. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1213. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1214. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1215. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1216. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1217. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1218. Result Options(const std::string &path);
  1219. Result Options(const std::string &path, const Headers &headers);
  1220. // clang-format on
  1221. bool send(Request &req, Response &res, Error &error);
  1222. Result send(const Request &req);
  1223. void stop();
  1224. std::string host() const;
  1225. int port() const;
  1226. size_t is_socket_open() const;
  1227. socket_t socket() const;
  1228. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1229. void set_default_headers(Headers headers);
  1230. void
  1231. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1232. void set_address_family(int family);
  1233. void set_tcp_nodelay(bool on);
  1234. void set_ipv6_v6only(bool on);
  1235. void set_socket_options(SocketOptions socket_options);
  1236. void set_connection_timeout(time_t sec, time_t usec = 0);
  1237. template <class Rep, class Period>
  1238. void
  1239. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1240. void set_read_timeout(time_t sec, time_t usec = 0);
  1241. template <class Rep, class Period>
  1242. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1243. void set_write_timeout(time_t sec, time_t usec = 0);
  1244. template <class Rep, class Period>
  1245. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1246. void set_max_timeout(time_t msec);
  1247. template <class Rep, class Period>
  1248. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1249. void set_basic_auth(const std::string &username, const std::string &password);
  1250. void set_bearer_token_auth(const std::string &token);
  1251. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1252. void set_digest_auth(const std::string &username,
  1253. const std::string &password);
  1254. #endif
  1255. void set_keep_alive(bool on);
  1256. void set_follow_location(bool on);
  1257. void set_path_encode(bool on);
  1258. void set_compress(bool on);
  1259. void set_decompress(bool on);
  1260. void set_interface(const std::string &intf);
  1261. void set_proxy(const std::string &host, int port);
  1262. void set_proxy_basic_auth(const std::string &username,
  1263. const std::string &password);
  1264. void set_proxy_bearer_token_auth(const std::string &token);
  1265. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1266. void set_proxy_digest_auth(const std::string &username,
  1267. const std::string &password);
  1268. #endif
  1269. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1270. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1271. const std::string &ca_cert_dir_path = std::string());
  1272. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1273. X509_STORE *create_ca_cert_store(const char *ca_cert, std::size_t size) const;
  1274. #endif
  1275. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1276. void enable_server_certificate_verification(bool enabled);
  1277. void enable_server_hostname_verification(bool enabled);
  1278. void set_server_certificate_verifier(
  1279. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1280. #endif
  1281. void set_logger(Logger logger);
  1282. void set_error_logger(ErrorLogger error_logger);
  1283. protected:
  1284. struct Socket {
  1285. socket_t sock = INVALID_SOCKET;
  1286. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1287. SSL *ssl = nullptr;
  1288. #endif
  1289. bool is_open() const { return sock != INVALID_SOCKET; }
  1290. };
  1291. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  1292. // All of:
  1293. // shutdown_ssl
  1294. // shutdown_socket
  1295. // close_socket
  1296. // should ONLY be called when socket_mutex_ is locked.
  1297. // Also, shutdown_ssl and close_socket should also NOT be called concurrently
  1298. // with a DIFFERENT thread sending requests using that socket.
  1299. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  1300. void shutdown_socket(Socket &socket) const;
  1301. void close_socket(Socket &socket);
  1302. bool process_request(Stream &strm, Request &req, Response &res,
  1303. bool close_connection, Error &error);
  1304. bool write_content_with_provider(Stream &strm, const Request &req,
  1305. Error &error) const;
  1306. void copy_settings(const ClientImpl &rhs);
  1307. void output_log(const Request &req, const Response &res) const;
  1308. void output_error_log(const Error &err, const Request *req) const;
  1309. // Socket endpoint information
  1310. const std::string host_;
  1311. const int port_;
  1312. const std::string host_and_port_;
  1313. // Current open socket
  1314. Socket socket_;
  1315. mutable std::mutex socket_mutex_;
  1316. std::recursive_mutex request_mutex_;
  1317. // These are all protected under socket_mutex
  1318. size_t socket_requests_in_flight_ = 0;
  1319. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  1320. bool socket_should_be_closed_when_request_is_done_ = false;
  1321. // Hostname-IP map
  1322. std::map<std::string, std::string> addr_map_;
  1323. // Default headers
  1324. Headers default_headers_;
  1325. // Header writer
  1326. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1327. detail::write_headers;
  1328. // Settings
  1329. std::string client_cert_path_;
  1330. std::string client_key_path_;
  1331. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  1332. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  1333. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  1334. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  1335. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  1336. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  1337. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  1338. std::string basic_auth_username_;
  1339. std::string basic_auth_password_;
  1340. std::string bearer_token_auth_token_;
  1341. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1342. std::string digest_auth_username_;
  1343. std::string digest_auth_password_;
  1344. #endif
  1345. bool keep_alive_ = false;
  1346. bool follow_location_ = false;
  1347. bool path_encode_ = true;
  1348. int address_family_ = AF_UNSPEC;
  1349. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1350. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1351. SocketOptions socket_options_ = nullptr;
  1352. bool compress_ = false;
  1353. bool decompress_ = true;
  1354. std::string interface_;
  1355. std::string proxy_host_;
  1356. int proxy_port_ = -1;
  1357. std::string proxy_basic_auth_username_;
  1358. std::string proxy_basic_auth_password_;
  1359. std::string proxy_bearer_token_auth_token_;
  1360. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1361. std::string proxy_digest_auth_username_;
  1362. std::string proxy_digest_auth_password_;
  1363. #endif
  1364. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1365. std::string ca_cert_file_path_;
  1366. std::string ca_cert_dir_path_;
  1367. X509_STORE *ca_cert_store_ = nullptr;
  1368. #endif
  1369. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1370. bool server_certificate_verification_ = true;
  1371. bool server_hostname_verification_ = true;
  1372. std::function<SSLVerifierResponse(SSL *ssl)> server_certificate_verifier_;
  1373. #endif
  1374. mutable std::mutex logger_mutex_;
  1375. Logger logger_;
  1376. ErrorLogger error_logger_;
  1377. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1378. int last_ssl_error_ = 0;
  1379. unsigned long last_openssl_error_ = 0;
  1380. #endif
  1381. private:
  1382. bool send_(Request &req, Response &res, Error &error);
  1383. Result send_(Request &&req);
  1384. socket_t create_client_socket(Error &error) const;
  1385. bool read_response_line(Stream &strm, const Request &req,
  1386. Response &res) const;
  1387. bool write_request(Stream &strm, Request &req, bool close_connection,
  1388. Error &error);
  1389. bool redirect(Request &req, Response &res, Error &error);
  1390. bool create_redirect_client(const std::string &scheme,
  1391. const std::string &host, int port, Request &req,
  1392. Response &res, const std::string &path,
  1393. const std::string &location, Error &error);
  1394. template <typename ClientType> void setup_redirect_client(ClientType &client);
  1395. bool handle_request(Stream &strm, Request &req, Response &res,
  1396. bool close_connection, Error &error);
  1397. std::unique_ptr<Response> send_with_content_provider(
  1398. Request &req, const char *body, size_t content_length,
  1399. ContentProvider content_provider,
  1400. ContentProviderWithoutLength content_provider_without_length,
  1401. const std::string &content_type, Error &error);
  1402. Result send_with_content_provider(
  1403. const std::string &method, const std::string &path,
  1404. const Headers &headers, const char *body, size_t content_length,
  1405. ContentProvider content_provider,
  1406. ContentProviderWithoutLength content_provider_without_length,
  1407. const std::string &content_type, UploadProgress progress);
  1408. ContentProviderWithoutLength get_multipart_content_provider(
  1409. const std::string &boundary, const UploadFormDataItems &items,
  1410. const FormDataProviderItems &provider_items) const;
  1411. virtual bool
  1412. process_socket(const Socket &socket,
  1413. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1414. std::function<bool(Stream &strm)> callback);
  1415. virtual bool is_ssl() const;
  1416. };
  1417. class Client {
  1418. public:
  1419. // Universal interface
  1420. explicit Client(const std::string &scheme_host_port);
  1421. explicit Client(const std::string &scheme_host_port,
  1422. const std::string &client_cert_path,
  1423. const std::string &client_key_path);
  1424. // HTTP only interface
  1425. explicit Client(const std::string &host, int port);
  1426. explicit Client(const std::string &host, int port,
  1427. const std::string &client_cert_path,
  1428. const std::string &client_key_path);
  1429. Client(Client &&) = default;
  1430. Client &operator=(Client &&) = default;
  1431. ~Client();
  1432. bool is_valid() const;
  1433. // clang-format off
  1434. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1435. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1436. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1437. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1438. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1439. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1440. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1441. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1442. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1443. Result Head(const std::string &path);
  1444. Result Head(const std::string &path, const Headers &headers);
  1445. Result Post(const std::string &path);
  1446. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1447. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1448. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1449. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1450. Result Post(const std::string &path, const Params &params);
  1451. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1452. Result Post(const std::string &path, const Headers &headers);
  1453. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1454. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1455. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1456. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1457. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1458. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1459. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1460. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1461. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1462. Result Put(const std::string &path);
  1463. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1464. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1465. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1466. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1467. Result Put(const std::string &path, const Params &params);
  1468. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1469. Result Put(const std::string &path, const Headers &headers);
  1470. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1471. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1472. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1473. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1474. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1475. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1476. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1477. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1478. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1479. Result Patch(const std::string &path);
  1480. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1481. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1482. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1483. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1484. Result Patch(const std::string &path, const Params &params);
  1485. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1486. Result Patch(const std::string &path, const Headers &headers);
  1487. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1488. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1489. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1490. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1491. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1492. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1493. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1494. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1495. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1496. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1497. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1498. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1499. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1500. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1501. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1502. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1503. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1504. Result Options(const std::string &path);
  1505. Result Options(const std::string &path, const Headers &headers);
  1506. // clang-format on
  1507. bool send(Request &req, Response &res, Error &error);
  1508. Result send(const Request &req);
  1509. void stop();
  1510. std::string host() const;
  1511. int port() const;
  1512. size_t is_socket_open() const;
  1513. socket_t socket() const;
  1514. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1515. void set_default_headers(Headers headers);
  1516. void
  1517. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1518. void set_address_family(int family);
  1519. void set_tcp_nodelay(bool on);
  1520. void set_socket_options(SocketOptions socket_options);
  1521. void set_connection_timeout(time_t sec, time_t usec = 0);
  1522. template <class Rep, class Period>
  1523. void
  1524. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1525. void set_read_timeout(time_t sec, time_t usec = 0);
  1526. template <class Rep, class Period>
  1527. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1528. void set_write_timeout(time_t sec, time_t usec = 0);
  1529. template <class Rep, class Period>
  1530. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1531. void set_max_timeout(time_t msec);
  1532. template <class Rep, class Period>
  1533. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1534. void set_basic_auth(const std::string &username, const std::string &password);
  1535. void set_bearer_token_auth(const std::string &token);
  1536. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1537. void set_digest_auth(const std::string &username,
  1538. const std::string &password);
  1539. #endif
  1540. void set_keep_alive(bool on);
  1541. void set_follow_location(bool on);
  1542. void set_path_encode(bool on);
  1543. void set_url_encode(bool on);
  1544. void set_compress(bool on);
  1545. void set_decompress(bool on);
  1546. void set_interface(const std::string &intf);
  1547. void set_proxy(const std::string &host, int port);
  1548. void set_proxy_basic_auth(const std::string &username,
  1549. const std::string &password);
  1550. void set_proxy_bearer_token_auth(const std::string &token);
  1551. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1552. void set_proxy_digest_auth(const std::string &username,
  1553. const std::string &password);
  1554. #endif
  1555. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1556. void enable_server_certificate_verification(bool enabled);
  1557. void enable_server_hostname_verification(bool enabled);
  1558. void set_server_certificate_verifier(
  1559. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1560. #endif
  1561. void set_logger(Logger logger);
  1562. void set_error_logger(ErrorLogger error_logger);
  1563. // SSL
  1564. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1565. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1566. const std::string &ca_cert_dir_path = std::string());
  1567. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1568. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1569. long get_openssl_verify_result() const;
  1570. SSL_CTX *ssl_context() const;
  1571. #endif
  1572. private:
  1573. std::unique_ptr<ClientImpl> cli_;
  1574. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1575. bool is_ssl_ = false;
  1576. #endif
  1577. };
  1578. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1579. class SSLServer : public Server {
  1580. public:
  1581. SSLServer(const char *cert_path, const char *private_key_path,
  1582. const char *client_ca_cert_file_path = nullptr,
  1583. const char *client_ca_cert_dir_path = nullptr,
  1584. const char *private_key_password = nullptr);
  1585. SSLServer(X509 *cert, EVP_PKEY *private_key,
  1586. X509_STORE *client_ca_cert_store = nullptr);
  1587. SSLServer(
  1588. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback);
  1589. ~SSLServer() override;
  1590. bool is_valid() const override;
  1591. SSL_CTX *ssl_context() const;
  1592. void update_certs(X509 *cert, EVP_PKEY *private_key,
  1593. X509_STORE *client_ca_cert_store = nullptr);
  1594. int ssl_last_error() const { return last_ssl_error_; }
  1595. private:
  1596. bool process_and_close_socket(socket_t sock) override;
  1597. STACK_OF(X509_NAME) * extract_ca_names_from_x509_store(X509_STORE *store);
  1598. SSL_CTX *ctx_;
  1599. std::mutex ctx_mutex_;
  1600. int last_ssl_error_ = 0;
  1601. };
  1602. class SSLClient final : public ClientImpl {
  1603. public:
  1604. explicit SSLClient(const std::string &host);
  1605. explicit SSLClient(const std::string &host, int port);
  1606. explicit SSLClient(const std::string &host, int port,
  1607. const std::string &client_cert_path,
  1608. const std::string &client_key_path,
  1609. const std::string &private_key_password = std::string());
  1610. explicit SSLClient(const std::string &host, int port, X509 *client_cert,
  1611. EVP_PKEY *client_key,
  1612. const std::string &private_key_password = std::string());
  1613. ~SSLClient() override;
  1614. bool is_valid() const override;
  1615. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1616. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1617. long get_openssl_verify_result() const;
  1618. SSL_CTX *ssl_context() const;
  1619. private:
  1620. bool create_and_connect_socket(Socket &socket, Error &error) override;
  1621. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  1622. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  1623. bool
  1624. process_socket(const Socket &socket,
  1625. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1626. std::function<bool(Stream &strm)> callback) override;
  1627. bool is_ssl() const override;
  1628. bool connect_with_proxy(
  1629. Socket &sock,
  1630. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1631. Response &res, bool &success, Error &error);
  1632. bool initialize_ssl(Socket &socket, Error &error);
  1633. bool load_certs();
  1634. bool verify_host(X509 *server_cert) const;
  1635. bool verify_host_with_subject_alt_name(X509 *server_cert) const;
  1636. bool verify_host_with_common_name(X509 *server_cert) const;
  1637. bool check_host_name(const char *pattern, size_t pattern_len) const;
  1638. SSL_CTX *ctx_;
  1639. std::mutex ctx_mutex_;
  1640. std::once_flag initialize_cert_;
  1641. std::vector<std::string> host_components_;
  1642. long verify_result_ = 0;
  1643. friend class ClientImpl;
  1644. };
  1645. #endif
  1646. /*
  1647. * Implementation of template methods.
  1648. */
  1649. namespace detail {
  1650. template <typename T, typename U>
  1651. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  1652. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  1653. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  1654. duration - std::chrono::seconds(sec))
  1655. .count();
  1656. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  1657. }
  1658. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  1659. return N - 1;
  1660. }
  1661. inline bool is_numeric(const std::string &str) {
  1662. return !str.empty() &&
  1663. std::all_of(str.cbegin(), str.cend(),
  1664. [](unsigned char c) { return std::isdigit(c); });
  1665. }
  1666. inline size_t get_header_value_u64(const Headers &headers,
  1667. const std::string &key, size_t def,
  1668. size_t id, bool &is_invalid_value) {
  1669. is_invalid_value = false;
  1670. auto rng = headers.equal_range(key);
  1671. auto it = rng.first;
  1672. std::advance(it, static_cast<ssize_t>(id));
  1673. if (it != rng.second) {
  1674. if (is_numeric(it->second)) {
  1675. return std::strtoull(it->second.data(), nullptr, 10);
  1676. } else {
  1677. is_invalid_value = true;
  1678. }
  1679. }
  1680. return def;
  1681. }
  1682. inline size_t get_header_value_u64(const Headers &headers,
  1683. const std::string &key, size_t def,
  1684. size_t id) {
  1685. auto dummy = false;
  1686. return get_header_value_u64(headers, key, def, id, dummy);
  1687. }
  1688. } // namespace detail
  1689. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  1690. size_t id) const {
  1691. return detail::get_header_value_u64(headers, key, def, id);
  1692. }
  1693. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  1694. size_t id) const {
  1695. return detail::get_header_value_u64(headers, key, def, id);
  1696. }
  1697. namespace detail {
  1698. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  1699. const void *optval, socklen_t optlen) {
  1700. return setsockopt(sock, level, optname,
  1701. #ifdef _WIN32
  1702. reinterpret_cast<const char *>(optval),
  1703. #else
  1704. optval,
  1705. #endif
  1706. optlen) == 0;
  1707. }
  1708. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  1709. return set_socket_opt_impl(sock, level, optname, &optval, sizeof(optval));
  1710. }
  1711. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  1712. time_t sec, time_t usec) {
  1713. #ifdef _WIN32
  1714. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  1715. #else
  1716. timeval timeout;
  1717. timeout.tv_sec = static_cast<long>(sec);
  1718. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  1719. #endif
  1720. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  1721. }
  1722. } // namespace detail
  1723. inline void default_socket_options(socket_t sock) {
  1724. detail::set_socket_opt(sock, SOL_SOCKET,
  1725. #ifdef SO_REUSEPORT
  1726. SO_REUSEPORT,
  1727. #else
  1728. SO_REUSEADDR,
  1729. #endif
  1730. 1);
  1731. }
  1732. inline const char *status_message(int status) {
  1733. switch (status) {
  1734. case StatusCode::Continue_100: return "Continue";
  1735. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  1736. case StatusCode::Processing_102: return "Processing";
  1737. case StatusCode::EarlyHints_103: return "Early Hints";
  1738. case StatusCode::OK_200: return "OK";
  1739. case StatusCode::Created_201: return "Created";
  1740. case StatusCode::Accepted_202: return "Accepted";
  1741. case StatusCode::NonAuthoritativeInformation_203:
  1742. return "Non-Authoritative Information";
  1743. case StatusCode::NoContent_204: return "No Content";
  1744. case StatusCode::ResetContent_205: return "Reset Content";
  1745. case StatusCode::PartialContent_206: return "Partial Content";
  1746. case StatusCode::MultiStatus_207: return "Multi-Status";
  1747. case StatusCode::AlreadyReported_208: return "Already Reported";
  1748. case StatusCode::IMUsed_226: return "IM Used";
  1749. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  1750. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  1751. case StatusCode::Found_302: return "Found";
  1752. case StatusCode::SeeOther_303: return "See Other";
  1753. case StatusCode::NotModified_304: return "Not Modified";
  1754. case StatusCode::UseProxy_305: return "Use Proxy";
  1755. case StatusCode::unused_306: return "unused";
  1756. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  1757. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  1758. case StatusCode::BadRequest_400: return "Bad Request";
  1759. case StatusCode::Unauthorized_401: return "Unauthorized";
  1760. case StatusCode::PaymentRequired_402: return "Payment Required";
  1761. case StatusCode::Forbidden_403: return "Forbidden";
  1762. case StatusCode::NotFound_404: return "Not Found";
  1763. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  1764. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  1765. case StatusCode::ProxyAuthenticationRequired_407:
  1766. return "Proxy Authentication Required";
  1767. case StatusCode::RequestTimeout_408: return "Request Timeout";
  1768. case StatusCode::Conflict_409: return "Conflict";
  1769. case StatusCode::Gone_410: return "Gone";
  1770. case StatusCode::LengthRequired_411: return "Length Required";
  1771. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  1772. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  1773. case StatusCode::UriTooLong_414: return "URI Too Long";
  1774. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  1775. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  1776. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  1777. case StatusCode::ImATeapot_418: return "I'm a teapot";
  1778. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  1779. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  1780. case StatusCode::Locked_423: return "Locked";
  1781. case StatusCode::FailedDependency_424: return "Failed Dependency";
  1782. case StatusCode::TooEarly_425: return "Too Early";
  1783. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  1784. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  1785. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  1786. case StatusCode::RequestHeaderFieldsTooLarge_431:
  1787. return "Request Header Fields Too Large";
  1788. case StatusCode::UnavailableForLegalReasons_451:
  1789. return "Unavailable For Legal Reasons";
  1790. case StatusCode::NotImplemented_501: return "Not Implemented";
  1791. case StatusCode::BadGateway_502: return "Bad Gateway";
  1792. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  1793. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  1794. case StatusCode::HttpVersionNotSupported_505:
  1795. return "HTTP Version Not Supported";
  1796. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  1797. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  1798. case StatusCode::LoopDetected_508: return "Loop Detected";
  1799. case StatusCode::NotExtended_510: return "Not Extended";
  1800. case StatusCode::NetworkAuthenticationRequired_511:
  1801. return "Network Authentication Required";
  1802. default:
  1803. case StatusCode::InternalServerError_500: return "Internal Server Error";
  1804. }
  1805. }
  1806. inline std::string get_bearer_token_auth(const Request &req) {
  1807. if (req.has_header("Authorization")) {
  1808. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  1809. return req.get_header_value("Authorization")
  1810. .substr(bearer_header_prefix_len);
  1811. }
  1812. return "";
  1813. }
  1814. template <class Rep, class Period>
  1815. inline Server &
  1816. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1817. detail::duration_to_sec_and_usec(
  1818. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  1819. return *this;
  1820. }
  1821. template <class Rep, class Period>
  1822. inline Server &
  1823. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1824. detail::duration_to_sec_and_usec(
  1825. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  1826. return *this;
  1827. }
  1828. template <class Rep, class Period>
  1829. inline Server &
  1830. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  1831. detail::duration_to_sec_and_usec(
  1832. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  1833. return *this;
  1834. }
  1835. inline std::string to_string(const Error error) {
  1836. switch (error) {
  1837. case Error::Success: return "Success (no error)";
  1838. case Error::Unknown: return "Unknown";
  1839. case Error::Connection: return "Could not establish connection";
  1840. case Error::BindIPAddress: return "Failed to bind IP address";
  1841. case Error::Read: return "Failed to read connection";
  1842. case Error::Write: return "Failed to write connection";
  1843. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  1844. case Error::Canceled: return "Connection handling canceled";
  1845. case Error::SSLConnection: return "SSL connection failed";
  1846. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  1847. case Error::SSLServerVerification: return "SSL server verification failed";
  1848. case Error::SSLServerHostnameVerification:
  1849. return "SSL server hostname verification failed";
  1850. case Error::UnsupportedMultipartBoundaryChars:
  1851. return "Unsupported HTTP multipart boundary characters";
  1852. case Error::Compression: return "Compression failed";
  1853. case Error::ConnectionTimeout: return "Connection timed out";
  1854. case Error::ProxyConnection: return "Proxy connection failed";
  1855. case Error::ResourceExhaustion: return "Resource exhaustion";
  1856. case Error::TooManyFormDataFiles: return "Too many form data files";
  1857. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  1858. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  1859. case Error::ExceedMaxSocketDescriptorCount:
  1860. return "Exceeded maximum socket descriptor count";
  1861. case Error::InvalidRequestLine: return "Invalid request line";
  1862. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  1863. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  1864. case Error::InvalidHeaders: return "Invalid headers";
  1865. case Error::MultipartParsing: return "Multipart parsing failed";
  1866. case Error::OpenFile: return "Failed to open file";
  1867. case Error::Listen: return "Failed to listen on socket";
  1868. case Error::GetSockName: return "Failed to get socket name";
  1869. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  1870. case Error::HTTPParsing: return "HTTP parsing failed";
  1871. case Error::InvalidRangeHeader: return "Invalid Range header";
  1872. default: break;
  1873. }
  1874. return "Invalid";
  1875. }
  1876. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  1877. os << to_string(obj);
  1878. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  1879. return os;
  1880. }
  1881. inline size_t Result::get_request_header_value_u64(const std::string &key,
  1882. size_t def,
  1883. size_t id) const {
  1884. return detail::get_header_value_u64(request_headers_, key, def, id);
  1885. }
  1886. template <class Rep, class Period>
  1887. inline void ClientImpl::set_connection_timeout(
  1888. const std::chrono::duration<Rep, Period> &duration) {
  1889. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  1890. set_connection_timeout(sec, usec);
  1891. });
  1892. }
  1893. template <class Rep, class Period>
  1894. inline void ClientImpl::set_read_timeout(
  1895. const std::chrono::duration<Rep, Period> &duration) {
  1896. detail::duration_to_sec_and_usec(
  1897. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  1898. }
  1899. template <class Rep, class Period>
  1900. inline void ClientImpl::set_write_timeout(
  1901. const std::chrono::duration<Rep, Period> &duration) {
  1902. detail::duration_to_sec_and_usec(
  1903. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  1904. }
  1905. template <class Rep, class Period>
  1906. inline void ClientImpl::set_max_timeout(
  1907. const std::chrono::duration<Rep, Period> &duration) {
  1908. auto msec =
  1909. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  1910. set_max_timeout(msec);
  1911. }
  1912. template <class Rep, class Period>
  1913. inline void Client::set_connection_timeout(
  1914. const std::chrono::duration<Rep, Period> &duration) {
  1915. cli_->set_connection_timeout(duration);
  1916. }
  1917. template <class Rep, class Period>
  1918. inline void
  1919. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1920. cli_->set_read_timeout(duration);
  1921. }
  1922. template <class Rep, class Period>
  1923. inline void
  1924. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1925. cli_->set_write_timeout(duration);
  1926. }
  1927. inline void Client::set_max_timeout(time_t msec) {
  1928. cli_->set_max_timeout(msec);
  1929. }
  1930. template <class Rep, class Period>
  1931. inline void
  1932. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1933. cli_->set_max_timeout(duration);
  1934. }
  1935. /*
  1936. * Forward declarations and types that will be part of the .h file if split into
  1937. * .h + .cc.
  1938. */
  1939. std::string hosted_at(const std::string &hostname);
  1940. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  1941. // JavaScript-style URL encoding/decoding functions
  1942. std::string encode_uri_component(const std::string &value);
  1943. std::string encode_uri(const std::string &value);
  1944. std::string decode_uri_component(const std::string &value);
  1945. std::string decode_uri(const std::string &value);
  1946. // RFC 3986 compliant URL component encoding/decoding functions
  1947. std::string encode_path_component(const std::string &component);
  1948. std::string decode_path_component(const std::string &component);
  1949. std::string encode_query_component(const std::string &component,
  1950. bool space_as_plus = true);
  1951. std::string decode_query_component(const std::string &component,
  1952. bool plus_as_space = true);
  1953. std::string append_query_params(const std::string &path, const Params &params);
  1954. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  1955. std::pair<std::string, std::string>
  1956. make_basic_authentication_header(const std::string &username,
  1957. const std::string &password,
  1958. bool is_proxy = false);
  1959. namespace detail {
  1960. #if defined(_WIN32)
  1961. inline std::wstring u8string_to_wstring(const char *s) {
  1962. std::wstring ws;
  1963. auto len = static_cast<int>(strlen(s));
  1964. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  1965. if (wlen > 0) {
  1966. ws.resize(wlen);
  1967. wlen = ::MultiByteToWideChar(
  1968. CP_UTF8, 0, s, len,
  1969. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  1970. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  1971. }
  1972. return ws;
  1973. }
  1974. #endif
  1975. struct FileStat {
  1976. FileStat(const std::string &path);
  1977. bool is_file() const;
  1978. bool is_dir() const;
  1979. private:
  1980. #if defined(_WIN32)
  1981. struct _stat st_;
  1982. #else
  1983. struct stat st_;
  1984. #endif
  1985. int ret_ = -1;
  1986. };
  1987. std::string trim_copy(const std::string &s);
  1988. void divide(
  1989. const char *data, std::size_t size, char d,
  1990. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  1991. fn);
  1992. void divide(
  1993. const std::string &str, char d,
  1994. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  1995. fn);
  1996. void split(const char *b, const char *e, char d,
  1997. std::function<void(const char *, const char *)> fn);
  1998. void split(const char *b, const char *e, char d, size_t m,
  1999. std::function<void(const char *, const char *)> fn);
  2000. bool process_client_socket(
  2001. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2002. time_t write_timeout_sec, time_t write_timeout_usec,
  2003. time_t max_timeout_msec,
  2004. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2005. std::function<bool(Stream &)> callback);
  2006. socket_t create_client_socket(const std::string &host, const std::string &ip,
  2007. int port, int address_family, bool tcp_nodelay,
  2008. bool ipv6_v6only, SocketOptions socket_options,
  2009. time_t connection_timeout_sec,
  2010. time_t connection_timeout_usec,
  2011. time_t read_timeout_sec, time_t read_timeout_usec,
  2012. time_t write_timeout_sec,
  2013. time_t write_timeout_usec,
  2014. const std::string &intf, Error &error);
  2015. const char *get_header_value(const Headers &headers, const std::string &key,
  2016. const char *def, size_t id);
  2017. std::string params_to_query_str(const Params &params);
  2018. void parse_query_text(const char *data, std::size_t size, Params &params);
  2019. void parse_query_text(const std::string &s, Params &params);
  2020. bool parse_multipart_boundary(const std::string &content_type,
  2021. std::string &boundary);
  2022. bool parse_range_header(const std::string &s, Ranges &ranges);
  2023. bool parse_accept_header(const std::string &s,
  2024. std::vector<std::string> &content_types);
  2025. int close_socket(socket_t sock);
  2026. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  2027. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  2028. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  2029. EncodingType encoding_type(const Request &req, const Response &res);
  2030. class BufferStream final : public Stream {
  2031. public:
  2032. BufferStream() = default;
  2033. ~BufferStream() override = default;
  2034. bool is_readable() const override;
  2035. bool wait_readable() const override;
  2036. bool wait_writable() const override;
  2037. ssize_t read(char *ptr, size_t size) override;
  2038. ssize_t write(const char *ptr, size_t size) override;
  2039. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2040. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2041. socket_t socket() const override;
  2042. time_t duration() const override;
  2043. const std::string &get_buffer() const;
  2044. private:
  2045. std::string buffer;
  2046. size_t position = 0;
  2047. };
  2048. class compressor {
  2049. public:
  2050. virtual ~compressor() = default;
  2051. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2052. virtual bool compress(const char *data, size_t data_length, bool last,
  2053. Callback callback) = 0;
  2054. };
  2055. class decompressor {
  2056. public:
  2057. virtual ~decompressor() = default;
  2058. virtual bool is_valid() const = 0;
  2059. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2060. virtual bool decompress(const char *data, size_t data_length,
  2061. Callback callback) = 0;
  2062. };
  2063. class nocompressor final : public compressor {
  2064. public:
  2065. ~nocompressor() override = default;
  2066. bool compress(const char *data, size_t data_length, bool /*last*/,
  2067. Callback callback) override;
  2068. };
  2069. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2070. class gzip_compressor final : public compressor {
  2071. public:
  2072. gzip_compressor();
  2073. ~gzip_compressor() override;
  2074. bool compress(const char *data, size_t data_length, bool last,
  2075. Callback callback) override;
  2076. private:
  2077. bool is_valid_ = false;
  2078. z_stream strm_;
  2079. };
  2080. class gzip_decompressor final : public decompressor {
  2081. public:
  2082. gzip_decompressor();
  2083. ~gzip_decompressor() override;
  2084. bool is_valid() const override;
  2085. bool decompress(const char *data, size_t data_length,
  2086. Callback callback) override;
  2087. private:
  2088. bool is_valid_ = false;
  2089. z_stream strm_;
  2090. };
  2091. #endif
  2092. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2093. class brotli_compressor final : public compressor {
  2094. public:
  2095. brotli_compressor();
  2096. ~brotli_compressor();
  2097. bool compress(const char *data, size_t data_length, bool last,
  2098. Callback callback) override;
  2099. private:
  2100. BrotliEncoderState *state_ = nullptr;
  2101. };
  2102. class brotli_decompressor final : public decompressor {
  2103. public:
  2104. brotli_decompressor();
  2105. ~brotli_decompressor();
  2106. bool is_valid() const override;
  2107. bool decompress(const char *data, size_t data_length,
  2108. Callback callback) override;
  2109. private:
  2110. BrotliDecoderResult decoder_r;
  2111. BrotliDecoderState *decoder_s = nullptr;
  2112. };
  2113. #endif
  2114. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  2115. class zstd_compressor : public compressor {
  2116. public:
  2117. zstd_compressor();
  2118. ~zstd_compressor();
  2119. bool compress(const char *data, size_t data_length, bool last,
  2120. Callback callback) override;
  2121. private:
  2122. ZSTD_CCtx *ctx_ = nullptr;
  2123. };
  2124. class zstd_decompressor : public decompressor {
  2125. public:
  2126. zstd_decompressor();
  2127. ~zstd_decompressor();
  2128. bool is_valid() const override;
  2129. bool decompress(const char *data, size_t data_length,
  2130. Callback callback) override;
  2131. private:
  2132. ZSTD_DCtx *ctx_ = nullptr;
  2133. };
  2134. #endif
  2135. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  2136. // to store data. The call can set memory on stack for performance.
  2137. class stream_line_reader {
  2138. public:
  2139. stream_line_reader(Stream &strm, char *fixed_buffer,
  2140. size_t fixed_buffer_size);
  2141. const char *ptr() const;
  2142. size_t size() const;
  2143. bool end_with_crlf() const;
  2144. bool getline();
  2145. private:
  2146. void append(char c);
  2147. Stream &strm_;
  2148. char *fixed_buffer_;
  2149. const size_t fixed_buffer_size_;
  2150. size_t fixed_buffer_used_size_ = 0;
  2151. std::string growable_buffer_;
  2152. };
  2153. class mmap {
  2154. public:
  2155. mmap(const char *path);
  2156. ~mmap();
  2157. bool open(const char *path);
  2158. void close();
  2159. bool is_open() const;
  2160. size_t size() const;
  2161. const char *data() const;
  2162. private:
  2163. #if defined(_WIN32)
  2164. HANDLE hFile_ = NULL;
  2165. HANDLE hMapping_ = NULL;
  2166. #else
  2167. int fd_ = -1;
  2168. #endif
  2169. size_t size_ = 0;
  2170. void *addr_ = nullptr;
  2171. bool is_open_empty_file = false;
  2172. };
  2173. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  2174. namespace fields {
  2175. inline bool is_token_char(char c) {
  2176. return std::isalnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  2177. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  2178. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  2179. }
  2180. inline bool is_token(const std::string &s) {
  2181. if (s.empty()) { return false; }
  2182. for (auto c : s) {
  2183. if (!is_token_char(c)) { return false; }
  2184. }
  2185. return true;
  2186. }
  2187. inline bool is_field_name(const std::string &s) { return is_token(s); }
  2188. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  2189. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  2190. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  2191. inline bool is_field_content(const std::string &s) {
  2192. if (s.empty()) { return true; }
  2193. if (s.size() == 1) {
  2194. return is_field_vchar(s[0]);
  2195. } else if (s.size() == 2) {
  2196. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  2197. } else {
  2198. size_t i = 0;
  2199. if (!is_field_vchar(s[i])) { return false; }
  2200. i++;
  2201. while (i < s.size() - 1) {
  2202. auto c = s[i++];
  2203. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  2204. } else {
  2205. return false;
  2206. }
  2207. }
  2208. return is_field_vchar(s[i]);
  2209. }
  2210. }
  2211. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  2212. } // namespace fields
  2213. } // namespace detail
  2214. // ----------------------------------------------------------------------------
  2215. /*
  2216. * Implementation that will be part of the .cc file if split into .h + .cc.
  2217. */
  2218. namespace detail {
  2219. inline bool is_hex(char c, int &v) {
  2220. if (0x20 <= c && isdigit(c)) {
  2221. v = c - '0';
  2222. return true;
  2223. } else if ('A' <= c && c <= 'F') {
  2224. v = c - 'A' + 10;
  2225. return true;
  2226. } else if ('a' <= c && c <= 'f') {
  2227. v = c - 'a' + 10;
  2228. return true;
  2229. }
  2230. return false;
  2231. }
  2232. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  2233. int &val) {
  2234. if (i >= s.size()) { return false; }
  2235. val = 0;
  2236. for (; cnt; i++, cnt--) {
  2237. if (!s[i]) { return false; }
  2238. auto v = 0;
  2239. if (is_hex(s[i], v)) {
  2240. val = val * 16 + v;
  2241. } else {
  2242. return false;
  2243. }
  2244. }
  2245. return true;
  2246. }
  2247. inline std::string from_i_to_hex(size_t n) {
  2248. static const auto charset = "0123456789abcdef";
  2249. std::string ret;
  2250. do {
  2251. ret = charset[n & 15] + ret;
  2252. n >>= 4;
  2253. } while (n > 0);
  2254. return ret;
  2255. }
  2256. inline size_t to_utf8(int code, char *buff) {
  2257. if (code < 0x0080) {
  2258. buff[0] = static_cast<char>(code & 0x7F);
  2259. return 1;
  2260. } else if (code < 0x0800) {
  2261. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  2262. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  2263. return 2;
  2264. } else if (code < 0xD800) {
  2265. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  2266. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  2267. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  2268. return 3;
  2269. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  2270. return 0;
  2271. } else if (code < 0x10000) {
  2272. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  2273. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  2274. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  2275. return 3;
  2276. } else if (code < 0x110000) {
  2277. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  2278. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  2279. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  2280. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  2281. return 4;
  2282. }
  2283. // NOTREACHED
  2284. return 0;
  2285. }
  2286. // NOTE: This code came up with the following stackoverflow post:
  2287. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  2288. inline std::string base64_encode(const std::string &in) {
  2289. static const auto lookup =
  2290. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  2291. std::string out;
  2292. out.reserve(in.size());
  2293. auto val = 0;
  2294. auto valb = -6;
  2295. for (auto c : in) {
  2296. val = (val << 8) + static_cast<uint8_t>(c);
  2297. valb += 8;
  2298. while (valb >= 0) {
  2299. out.push_back(lookup[(val >> valb) & 0x3F]);
  2300. valb -= 6;
  2301. }
  2302. }
  2303. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  2304. while (out.size() % 4) {
  2305. out.push_back('=');
  2306. }
  2307. return out;
  2308. }
  2309. inline bool is_valid_path(const std::string &path) {
  2310. size_t level = 0;
  2311. size_t i = 0;
  2312. // Skip slash
  2313. while (i < path.size() && path[i] == '/') {
  2314. i++;
  2315. }
  2316. while (i < path.size()) {
  2317. // Read component
  2318. auto beg = i;
  2319. while (i < path.size() && path[i] != '/') {
  2320. if (path[i] == '\0') {
  2321. return false;
  2322. } else if (path[i] == '\\') {
  2323. return false;
  2324. }
  2325. i++;
  2326. }
  2327. auto len = i - beg;
  2328. assert(len > 0);
  2329. if (!path.compare(beg, len, ".")) {
  2330. ;
  2331. } else if (!path.compare(beg, len, "..")) {
  2332. if (level == 0) { return false; }
  2333. level--;
  2334. } else {
  2335. level++;
  2336. }
  2337. // Skip slash
  2338. while (i < path.size() && path[i] == '/') {
  2339. i++;
  2340. }
  2341. }
  2342. return true;
  2343. }
  2344. inline FileStat::FileStat(const std::string &path) {
  2345. #if defined(_WIN32)
  2346. auto wpath = u8string_to_wstring(path.c_str());
  2347. ret_ = _wstat(wpath.c_str(), &st_);
  2348. #else
  2349. ret_ = stat(path.c_str(), &st_);
  2350. #endif
  2351. }
  2352. inline bool FileStat::is_file() const {
  2353. return ret_ >= 0 && S_ISREG(st_.st_mode);
  2354. }
  2355. inline bool FileStat::is_dir() const {
  2356. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  2357. }
  2358. inline std::string encode_path(const std::string &s) {
  2359. std::string result;
  2360. result.reserve(s.size());
  2361. for (size_t i = 0; s[i]; i++) {
  2362. switch (s[i]) {
  2363. case ' ': result += "%20"; break;
  2364. case '+': result += "%2B"; break;
  2365. case '\r': result += "%0D"; break;
  2366. case '\n': result += "%0A"; break;
  2367. case '\'': result += "%27"; break;
  2368. case ',': result += "%2C"; break;
  2369. // case ':': result += "%3A"; break; // ok? probably...
  2370. case ';': result += "%3B"; break;
  2371. default:
  2372. auto c = static_cast<uint8_t>(s[i]);
  2373. if (c >= 0x80) {
  2374. result += '%';
  2375. char hex[4];
  2376. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  2377. assert(len == 2);
  2378. result.append(hex, static_cast<size_t>(len));
  2379. } else {
  2380. result += s[i];
  2381. }
  2382. break;
  2383. }
  2384. }
  2385. return result;
  2386. }
  2387. inline std::string file_extension(const std::string &path) {
  2388. std::smatch m;
  2389. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  2390. if (std::regex_search(path, m, re)) { return m[1].str(); }
  2391. return std::string();
  2392. }
  2393. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  2394. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  2395. size_t right) {
  2396. while (b + left < e && is_space_or_tab(b[left])) {
  2397. left++;
  2398. }
  2399. while (right > 0 && is_space_or_tab(b[right - 1])) {
  2400. right--;
  2401. }
  2402. return std::make_pair(left, right);
  2403. }
  2404. inline std::string trim_copy(const std::string &s) {
  2405. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  2406. return s.substr(r.first, r.second - r.first);
  2407. }
  2408. inline std::string trim_double_quotes_copy(const std::string &s) {
  2409. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  2410. return s.substr(1, s.size() - 2);
  2411. }
  2412. return s;
  2413. }
  2414. inline void
  2415. divide(const char *data, std::size_t size, char d,
  2416. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2417. fn) {
  2418. const auto it = std::find(data, data + size, d);
  2419. const auto found = static_cast<std::size_t>(it != data + size);
  2420. const auto lhs_data = data;
  2421. const auto lhs_size = static_cast<std::size_t>(it - data);
  2422. const auto rhs_data = it + found;
  2423. const auto rhs_size = size - lhs_size - found;
  2424. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  2425. }
  2426. inline void
  2427. divide(const std::string &str, char d,
  2428. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2429. fn) {
  2430. divide(str.data(), str.size(), d, std::move(fn));
  2431. }
  2432. inline void split(const char *b, const char *e, char d,
  2433. std::function<void(const char *, const char *)> fn) {
  2434. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  2435. }
  2436. inline void split(const char *b, const char *e, char d, size_t m,
  2437. std::function<void(const char *, const char *)> fn) {
  2438. size_t i = 0;
  2439. size_t beg = 0;
  2440. size_t count = 1;
  2441. while (e ? (b + i < e) : (b[i] != '\0')) {
  2442. if (b[i] == d && count < m) {
  2443. auto r = trim(b, e, beg, i);
  2444. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  2445. beg = i + 1;
  2446. count++;
  2447. }
  2448. i++;
  2449. }
  2450. if (i) {
  2451. auto r = trim(b, e, beg, i);
  2452. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  2453. }
  2454. }
  2455. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  2456. size_t fixed_buffer_size)
  2457. : strm_(strm), fixed_buffer_(fixed_buffer),
  2458. fixed_buffer_size_(fixed_buffer_size) {}
  2459. inline const char *stream_line_reader::ptr() const {
  2460. if (growable_buffer_.empty()) {
  2461. return fixed_buffer_;
  2462. } else {
  2463. return growable_buffer_.data();
  2464. }
  2465. }
  2466. inline size_t stream_line_reader::size() const {
  2467. if (growable_buffer_.empty()) {
  2468. return fixed_buffer_used_size_;
  2469. } else {
  2470. return growable_buffer_.size();
  2471. }
  2472. }
  2473. inline bool stream_line_reader::end_with_crlf() const {
  2474. auto end = ptr() + size();
  2475. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  2476. }
  2477. inline bool stream_line_reader::getline() {
  2478. fixed_buffer_used_size_ = 0;
  2479. growable_buffer_.clear();
  2480. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  2481. char prev_byte = 0;
  2482. #endif
  2483. for (size_t i = 0;; i++) {
  2484. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  2485. // Treat exceptionally long lines as an error to
  2486. // prevent infinite loops/memory exhaustion
  2487. return false;
  2488. }
  2489. char byte;
  2490. auto n = strm_.read(&byte, 1);
  2491. if (n < 0) {
  2492. return false;
  2493. } else if (n == 0) {
  2494. if (i == 0) {
  2495. return false;
  2496. } else {
  2497. break;
  2498. }
  2499. }
  2500. append(byte);
  2501. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  2502. if (byte == '\n') { break; }
  2503. #else
  2504. if (prev_byte == '\r' && byte == '\n') { break; }
  2505. prev_byte = byte;
  2506. #endif
  2507. }
  2508. return true;
  2509. }
  2510. inline void stream_line_reader::append(char c) {
  2511. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  2512. fixed_buffer_[fixed_buffer_used_size_++] = c;
  2513. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  2514. } else {
  2515. if (growable_buffer_.empty()) {
  2516. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  2517. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  2518. }
  2519. growable_buffer_ += c;
  2520. }
  2521. }
  2522. inline mmap::mmap(const char *path) { open(path); }
  2523. inline mmap::~mmap() { close(); }
  2524. inline bool mmap::open(const char *path) {
  2525. close();
  2526. #if defined(_WIN32)
  2527. auto wpath = u8string_to_wstring(path);
  2528. if (wpath.empty()) { return false; }
  2529. hFile_ = ::CreateFile2(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ,
  2530. OPEN_EXISTING, NULL);
  2531. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  2532. LARGE_INTEGER size{};
  2533. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  2534. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  2535. // See:
  2536. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  2537. if (static_cast<ULONGLONG>(size.QuadPart) >
  2538. (std::numeric_limits<decltype(size_)>::max)()) {
  2539. // `size_t` might be 32-bits, on 32-bits Windows.
  2540. return false;
  2541. }
  2542. size_ = static_cast<size_t>(size.QuadPart);
  2543. hMapping_ =
  2544. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  2545. // Special treatment for an empty file...
  2546. if (hMapping_ == NULL && size_ == 0) {
  2547. close();
  2548. is_open_empty_file = true;
  2549. return true;
  2550. }
  2551. if (hMapping_ == NULL) {
  2552. close();
  2553. return false;
  2554. }
  2555. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  2556. if (addr_ == nullptr) {
  2557. close();
  2558. return false;
  2559. }
  2560. #else
  2561. fd_ = ::open(path, O_RDONLY);
  2562. if (fd_ == -1) { return false; }
  2563. struct stat sb;
  2564. if (fstat(fd_, &sb) == -1) {
  2565. close();
  2566. return false;
  2567. }
  2568. size_ = static_cast<size_t>(sb.st_size);
  2569. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  2570. // Special treatment for an empty file...
  2571. if (addr_ == MAP_FAILED && size_ == 0) {
  2572. close();
  2573. is_open_empty_file = true;
  2574. return false;
  2575. }
  2576. #endif
  2577. return true;
  2578. }
  2579. inline bool mmap::is_open() const {
  2580. return is_open_empty_file ? true : addr_ != nullptr;
  2581. }
  2582. inline size_t mmap::size() const { return size_; }
  2583. inline const char *mmap::data() const {
  2584. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  2585. }
  2586. inline void mmap::close() {
  2587. #if defined(_WIN32)
  2588. if (addr_) {
  2589. ::UnmapViewOfFile(addr_);
  2590. addr_ = nullptr;
  2591. }
  2592. if (hMapping_) {
  2593. ::CloseHandle(hMapping_);
  2594. hMapping_ = NULL;
  2595. }
  2596. if (hFile_ != INVALID_HANDLE_VALUE) {
  2597. ::CloseHandle(hFile_);
  2598. hFile_ = INVALID_HANDLE_VALUE;
  2599. }
  2600. is_open_empty_file = false;
  2601. #else
  2602. if (addr_ != nullptr) {
  2603. munmap(addr_, size_);
  2604. addr_ = nullptr;
  2605. }
  2606. if (fd_ != -1) {
  2607. ::close(fd_);
  2608. fd_ = -1;
  2609. }
  2610. #endif
  2611. size_ = 0;
  2612. }
  2613. inline int close_socket(socket_t sock) {
  2614. #ifdef _WIN32
  2615. return closesocket(sock);
  2616. #else
  2617. return close(sock);
  2618. #endif
  2619. }
  2620. template <typename T> inline ssize_t handle_EINTR(T fn) {
  2621. ssize_t res = 0;
  2622. while (true) {
  2623. res = fn();
  2624. if (res < 0 && errno == EINTR) {
  2625. std::this_thread::sleep_for(std::chrono::microseconds{1});
  2626. continue;
  2627. }
  2628. break;
  2629. }
  2630. return res;
  2631. }
  2632. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  2633. return handle_EINTR([&]() {
  2634. return recv(sock,
  2635. #ifdef _WIN32
  2636. static_cast<char *>(ptr), static_cast<int>(size),
  2637. #else
  2638. ptr, size,
  2639. #endif
  2640. flags);
  2641. });
  2642. }
  2643. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  2644. int flags) {
  2645. return handle_EINTR([&]() {
  2646. return send(sock,
  2647. #ifdef _WIN32
  2648. static_cast<const char *>(ptr), static_cast<int>(size),
  2649. #else
  2650. ptr, size,
  2651. #endif
  2652. flags);
  2653. });
  2654. }
  2655. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  2656. #ifdef _WIN32
  2657. return ::WSAPoll(fds, nfds, timeout);
  2658. #else
  2659. return ::poll(fds, nfds, timeout);
  2660. #endif
  2661. }
  2662. template <bool Read>
  2663. inline ssize_t select_impl(socket_t sock, time_t sec, time_t usec) {
  2664. #ifdef __APPLE__
  2665. if (sock >= FD_SETSIZE) { return -1; }
  2666. fd_set fds, *rfds, *wfds;
  2667. FD_ZERO(&fds);
  2668. FD_SET(sock, &fds);
  2669. rfds = (Read ? &fds : nullptr);
  2670. wfds = (Read ? nullptr : &fds);
  2671. timeval tv;
  2672. tv.tv_sec = static_cast<long>(sec);
  2673. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  2674. return handle_EINTR([&]() {
  2675. return select(static_cast<int>(sock + 1), rfds, wfds, nullptr, &tv);
  2676. });
  2677. #else
  2678. struct pollfd pfd;
  2679. pfd.fd = sock;
  2680. pfd.events = (Read ? POLLIN : POLLOUT);
  2681. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  2682. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  2683. #endif
  2684. }
  2685. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  2686. return select_impl<true>(sock, sec, usec);
  2687. }
  2688. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  2689. return select_impl<false>(sock, sec, usec);
  2690. }
  2691. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  2692. time_t usec) {
  2693. #ifdef __APPLE__
  2694. if (sock >= FD_SETSIZE) { return Error::Connection; }
  2695. fd_set fdsr, fdsw;
  2696. FD_ZERO(&fdsr);
  2697. FD_ZERO(&fdsw);
  2698. FD_SET(sock, &fdsr);
  2699. FD_SET(sock, &fdsw);
  2700. timeval tv;
  2701. tv.tv_sec = static_cast<long>(sec);
  2702. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  2703. auto ret = handle_EINTR([&]() {
  2704. return select(static_cast<int>(sock + 1), &fdsr, &fdsw, nullptr, &tv);
  2705. });
  2706. if (ret == 0) { return Error::ConnectionTimeout; }
  2707. if (ret > 0 && (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) {
  2708. auto error = 0;
  2709. socklen_t len = sizeof(error);
  2710. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  2711. reinterpret_cast<char *>(&error), &len);
  2712. auto successful = res >= 0 && !error;
  2713. return successful ? Error::Success : Error::Connection;
  2714. }
  2715. return Error::Connection;
  2716. #else
  2717. struct pollfd pfd_read;
  2718. pfd_read.fd = sock;
  2719. pfd_read.events = POLLIN | POLLOUT;
  2720. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  2721. auto poll_res =
  2722. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  2723. if (poll_res == 0) { return Error::ConnectionTimeout; }
  2724. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  2725. auto error = 0;
  2726. socklen_t len = sizeof(error);
  2727. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  2728. reinterpret_cast<char *>(&error), &len);
  2729. auto successful = res >= 0 && !error;
  2730. return successful ? Error::Success : Error::Connection;
  2731. }
  2732. return Error::Connection;
  2733. #endif
  2734. }
  2735. inline bool is_socket_alive(socket_t sock) {
  2736. const auto val = detail::select_read(sock, 0, 0);
  2737. if (val == 0) {
  2738. return true;
  2739. } else if (val < 0 && errno == EBADF) {
  2740. return false;
  2741. }
  2742. char buf[1];
  2743. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  2744. }
  2745. class SocketStream final : public Stream {
  2746. public:
  2747. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2748. time_t write_timeout_sec, time_t write_timeout_usec,
  2749. time_t max_timeout_msec = 0,
  2750. std::chrono::time_point<std::chrono::steady_clock> start_time =
  2751. (std::chrono::steady_clock::time_point::min)());
  2752. ~SocketStream() override;
  2753. bool is_readable() const override;
  2754. bool wait_readable() const override;
  2755. bool wait_writable() const override;
  2756. ssize_t read(char *ptr, size_t size) override;
  2757. ssize_t write(const char *ptr, size_t size) override;
  2758. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2759. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2760. socket_t socket() const override;
  2761. time_t duration() const override;
  2762. private:
  2763. socket_t sock_;
  2764. time_t read_timeout_sec_;
  2765. time_t read_timeout_usec_;
  2766. time_t write_timeout_sec_;
  2767. time_t write_timeout_usec_;
  2768. time_t max_timeout_msec_;
  2769. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  2770. std::vector<char> read_buff_;
  2771. size_t read_buff_off_ = 0;
  2772. size_t read_buff_content_size_ = 0;
  2773. static const size_t read_buff_size_ = 1024l * 4;
  2774. };
  2775. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2776. class SSLSocketStream final : public Stream {
  2777. public:
  2778. SSLSocketStream(
  2779. socket_t sock, SSL *ssl, time_t read_timeout_sec,
  2780. time_t read_timeout_usec, time_t write_timeout_sec,
  2781. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  2782. std::chrono::time_point<std::chrono::steady_clock> start_time =
  2783. (std::chrono::steady_clock::time_point::min)());
  2784. ~SSLSocketStream() override;
  2785. bool is_readable() const override;
  2786. bool wait_readable() const override;
  2787. bool wait_writable() const override;
  2788. ssize_t read(char *ptr, size_t size) override;
  2789. ssize_t write(const char *ptr, size_t size) override;
  2790. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2791. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2792. socket_t socket() const override;
  2793. time_t duration() const override;
  2794. private:
  2795. socket_t sock_;
  2796. SSL *ssl_;
  2797. time_t read_timeout_sec_;
  2798. time_t read_timeout_usec_;
  2799. time_t write_timeout_sec_;
  2800. time_t write_timeout_usec_;
  2801. time_t max_timeout_msec_;
  2802. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  2803. };
  2804. #endif
  2805. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  2806. time_t keep_alive_timeout_sec) {
  2807. using namespace std::chrono;
  2808. const auto interval_usec =
  2809. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  2810. // Avoid expensive `steady_clock::now()` call for the first time
  2811. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  2812. const auto start = steady_clock::now() - microseconds{interval_usec};
  2813. const auto timeout = seconds{keep_alive_timeout_sec};
  2814. while (true) {
  2815. if (svr_sock == INVALID_SOCKET) {
  2816. break; // Server socket is closed
  2817. }
  2818. auto val = select_read(sock, 0, interval_usec);
  2819. if (val < 0) {
  2820. break; // Ssocket error
  2821. } else if (val == 0) {
  2822. if (steady_clock::now() - start > timeout) {
  2823. break; // Timeout
  2824. }
  2825. } else {
  2826. return true; // Ready for read
  2827. }
  2828. }
  2829. return false;
  2830. }
  2831. template <typename T>
  2832. inline bool
  2833. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  2834. size_t keep_alive_max_count,
  2835. time_t keep_alive_timeout_sec, T callback) {
  2836. assert(keep_alive_max_count > 0);
  2837. auto ret = false;
  2838. auto count = keep_alive_max_count;
  2839. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  2840. auto close_connection = count == 1;
  2841. auto connection_closed = false;
  2842. ret = callback(close_connection, connection_closed);
  2843. if (!ret || connection_closed) { break; }
  2844. count--;
  2845. }
  2846. return ret;
  2847. }
  2848. template <typename T>
  2849. inline bool
  2850. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  2851. size_t keep_alive_max_count,
  2852. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  2853. time_t read_timeout_usec, time_t write_timeout_sec,
  2854. time_t write_timeout_usec, T callback) {
  2855. return process_server_socket_core(
  2856. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  2857. [&](bool close_connection, bool &connection_closed) {
  2858. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  2859. write_timeout_sec, write_timeout_usec);
  2860. return callback(strm, close_connection, connection_closed);
  2861. });
  2862. }
  2863. inline bool process_client_socket(
  2864. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2865. time_t write_timeout_sec, time_t write_timeout_usec,
  2866. time_t max_timeout_msec,
  2867. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2868. std::function<bool(Stream &)> callback) {
  2869. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  2870. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  2871. start_time);
  2872. return callback(strm);
  2873. }
  2874. inline int shutdown_socket(socket_t sock) {
  2875. #ifdef _WIN32
  2876. return shutdown(sock, SD_BOTH);
  2877. #else
  2878. return shutdown(sock, SHUT_RDWR);
  2879. #endif
  2880. }
  2881. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  2882. if (s.size() > 1 && s[0] == '\0') {
  2883. auto ret = s;
  2884. ret[0] = '@';
  2885. return ret;
  2886. }
  2887. return s;
  2888. }
  2889. inline std::string
  2890. unescape_abstract_namespace_unix_domain(const std::string &s) {
  2891. if (s.size() > 1 && s[0] == '@') {
  2892. auto ret = s;
  2893. ret[0] = '\0';
  2894. return ret;
  2895. }
  2896. return s;
  2897. }
  2898. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  2899. const struct addrinfo *hints,
  2900. struct addrinfo **res, time_t timeout_sec) {
  2901. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2902. if (timeout_sec <= 0) {
  2903. // No timeout specified, use standard getaddrinfo
  2904. return getaddrinfo(node, service, hints, res);
  2905. }
  2906. #ifdef _WIN32
  2907. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  2908. OVERLAPPED overlapped = {0};
  2909. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  2910. if (!event) { return EAI_FAIL; }
  2911. overlapped.hEvent = event;
  2912. PADDRINFOEXW result_addrinfo = nullptr;
  2913. HANDLE cancel_handle = nullptr;
  2914. ADDRINFOEXW hints_ex = {0};
  2915. if (hints) {
  2916. hints_ex.ai_flags = hints->ai_flags;
  2917. hints_ex.ai_family = hints->ai_family;
  2918. hints_ex.ai_socktype = hints->ai_socktype;
  2919. hints_ex.ai_protocol = hints->ai_protocol;
  2920. }
  2921. auto wnode = u8string_to_wstring(node);
  2922. auto wservice = u8string_to_wstring(service);
  2923. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  2924. hints ? &hints_ex : nullptr, &result_addrinfo,
  2925. nullptr, &overlapped, nullptr, &cancel_handle);
  2926. if (ret == WSA_IO_PENDING) {
  2927. auto wait_result =
  2928. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  2929. if (wait_result == WAIT_TIMEOUT) {
  2930. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  2931. ::CloseHandle(event);
  2932. return EAI_AGAIN;
  2933. }
  2934. DWORD bytes_returned;
  2935. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  2936. &bytes_returned, FALSE)) {
  2937. ::CloseHandle(event);
  2938. return ::WSAGetLastError();
  2939. }
  2940. }
  2941. ::CloseHandle(event);
  2942. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  2943. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  2944. return 0;
  2945. }
  2946. return ret;
  2947. #elif TARGET_OS_MAC
  2948. // macOS implementation using CFHost API for asynchronous DNS resolution
  2949. CFStringRef hostname_ref = CFStringCreateWithCString(
  2950. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  2951. if (!hostname_ref) { return EAI_MEMORY; }
  2952. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  2953. CFRelease(hostname_ref);
  2954. if (!host_ref) { return EAI_MEMORY; }
  2955. // Set up context for callback
  2956. struct CFHostContext {
  2957. bool completed = false;
  2958. bool success = false;
  2959. CFArrayRef addresses = nullptr;
  2960. std::mutex mutex;
  2961. std::condition_variable cv;
  2962. } context;
  2963. CFHostClientContext client_context;
  2964. memset(&client_context, 0, sizeof(client_context));
  2965. client_context.info = &context;
  2966. // Set callback
  2967. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  2968. const CFStreamError *error, void *info) {
  2969. auto ctx = static_cast<CFHostContext *>(info);
  2970. std::lock_guard<std::mutex> lock(ctx->mutex);
  2971. if (error && error->error != 0) {
  2972. ctx->success = false;
  2973. } else {
  2974. Boolean hasBeenResolved;
  2975. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  2976. if (ctx->addresses && hasBeenResolved) {
  2977. CFRetain(ctx->addresses);
  2978. ctx->success = true;
  2979. } else {
  2980. ctx->success = false;
  2981. }
  2982. }
  2983. ctx->completed = true;
  2984. ctx->cv.notify_one();
  2985. };
  2986. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  2987. CFRelease(host_ref);
  2988. return EAI_SYSTEM;
  2989. }
  2990. // Schedule on run loop
  2991. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  2992. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  2993. // Start resolution
  2994. CFStreamError stream_error;
  2995. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  2996. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  2997. CFRelease(host_ref);
  2998. return EAI_FAIL;
  2999. }
  3000. // Wait for completion with timeout
  3001. auto timeout_time =
  3002. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  3003. bool timed_out = false;
  3004. {
  3005. std::unique_lock<std::mutex> lock(context.mutex);
  3006. while (!context.completed) {
  3007. auto now = std::chrono::steady_clock::now();
  3008. if (now >= timeout_time) {
  3009. timed_out = true;
  3010. break;
  3011. }
  3012. // Run the runloop for a short time
  3013. lock.unlock();
  3014. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  3015. lock.lock();
  3016. }
  3017. }
  3018. // Clean up
  3019. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  3020. CFHostSetClient(host_ref, nullptr, nullptr);
  3021. if (timed_out || !context.completed) {
  3022. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  3023. CFRelease(host_ref);
  3024. return EAI_AGAIN;
  3025. }
  3026. if (!context.success || !context.addresses) {
  3027. CFRelease(host_ref);
  3028. return EAI_NODATA;
  3029. }
  3030. // Convert CFArray to addrinfo
  3031. CFIndex count = CFArrayGetCount(context.addresses);
  3032. if (count == 0) {
  3033. CFRelease(context.addresses);
  3034. CFRelease(host_ref);
  3035. return EAI_NODATA;
  3036. }
  3037. struct addrinfo *result_addrinfo = nullptr;
  3038. struct addrinfo **current = &result_addrinfo;
  3039. for (CFIndex i = 0; i < count; i++) {
  3040. CFDataRef addr_data =
  3041. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  3042. if (!addr_data) continue;
  3043. const struct sockaddr *sockaddr_ptr =
  3044. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  3045. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  3046. // Allocate addrinfo structure
  3047. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  3048. if (!*current) {
  3049. freeaddrinfo(result_addrinfo);
  3050. CFRelease(context.addresses);
  3051. CFRelease(host_ref);
  3052. return EAI_MEMORY;
  3053. }
  3054. memset(*current, 0, sizeof(struct addrinfo));
  3055. // Set up addrinfo fields
  3056. (*current)->ai_family = sockaddr_ptr->sa_family;
  3057. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  3058. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  3059. (*current)->ai_addrlen = sockaddr_len;
  3060. // Copy sockaddr
  3061. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  3062. if (!(*current)->ai_addr) {
  3063. freeaddrinfo(result_addrinfo);
  3064. CFRelease(context.addresses);
  3065. CFRelease(host_ref);
  3066. return EAI_MEMORY;
  3067. }
  3068. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  3069. // Set port if service is specified
  3070. if (service && strlen(service) > 0) {
  3071. int port = atoi(service);
  3072. if (port > 0) {
  3073. if (sockaddr_ptr->sa_family == AF_INET) {
  3074. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  3075. ->sin_port = htons(static_cast<uint16_t>(port));
  3076. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  3077. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  3078. ->sin6_port = htons(static_cast<uint16_t>(port));
  3079. }
  3080. }
  3081. }
  3082. current = &((*current)->ai_next);
  3083. }
  3084. CFRelease(context.addresses);
  3085. CFRelease(host_ref);
  3086. *res = result_addrinfo;
  3087. return 0;
  3088. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  3089. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  3090. // Linux implementation using getaddrinfo_a for asynchronous DNS resolution
  3091. struct gaicb request;
  3092. struct gaicb *requests[1] = {&request};
  3093. struct sigevent sevp;
  3094. struct timespec timeout;
  3095. // Initialize the request structure
  3096. memset(&request, 0, sizeof(request));
  3097. request.ar_name = node;
  3098. request.ar_service = service;
  3099. request.ar_request = hints;
  3100. // Set up timeout
  3101. timeout.tv_sec = timeout_sec;
  3102. timeout.tv_nsec = 0;
  3103. // Initialize sigevent structure (not used, but required)
  3104. memset(&sevp, 0, sizeof(sevp));
  3105. sevp.sigev_notify = SIGEV_NONE;
  3106. // Start asynchronous resolution
  3107. int start_result = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  3108. if (start_result != 0) { return start_result; }
  3109. // Wait for completion with timeout
  3110. int wait_result =
  3111. gai_suspend((const struct gaicb *const *)requests, 1, &timeout);
  3112. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  3113. // Completed successfully, get the result
  3114. int gai_result = gai_error(&request);
  3115. if (gai_result == 0) {
  3116. *res = request.ar_result;
  3117. return 0;
  3118. } else {
  3119. // Clean up on error
  3120. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  3121. return gai_result;
  3122. }
  3123. } else if (wait_result == EAI_AGAIN) {
  3124. // Timeout occurred, cancel the request
  3125. gai_cancel(&request);
  3126. return EAI_AGAIN;
  3127. } else {
  3128. // Other error occurred
  3129. gai_cancel(&request);
  3130. return wait_result;
  3131. }
  3132. #else
  3133. // Fallback implementation using thread-based timeout for other Unix systems
  3134. struct GetAddrInfoState {
  3135. std::mutex mutex;
  3136. std::condition_variable result_cv;
  3137. bool completed = false;
  3138. int result = EAI_SYSTEM;
  3139. std::string node = node;
  3140. std::string service = service;
  3141. struct addrinfo hints = hints;
  3142. struct addrinfo *info = nullptr;
  3143. };
  3144. // Allocate on the heap, so the resolver thread can keep using the data.
  3145. auto state = std::make_shared<GetAddrInfoState>();
  3146. std::thread resolve_thread([=]() {
  3147. auto thread_result = getaddrinfo(
  3148. state->node.c_str(), state->service.c_str(), hints, &state->info);
  3149. std::lock_guard<std::mutex> lock(state->mutex);
  3150. state->result = thread_result;
  3151. state->completed = true;
  3152. state->result_cv.notify_one();
  3153. });
  3154. // Wait for completion or timeout
  3155. std::unique_lock<std::mutex> lock(state->mutex);
  3156. auto finished =
  3157. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  3158. [&] { return state->completed; });
  3159. if (finished) {
  3160. // Operation completed within timeout
  3161. resolve_thread.join();
  3162. *res = state->info;
  3163. return state->result;
  3164. } else {
  3165. // Timeout occurred
  3166. resolve_thread.detach(); // Let the thread finish in background
  3167. return EAI_AGAIN; // Return timeout error
  3168. }
  3169. #endif
  3170. #else
  3171. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  3172. return getaddrinfo(node, service, hints, res);
  3173. #endif
  3174. }
  3175. template <typename BindOrConnect>
  3176. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  3177. int address_family, int socket_flags, bool tcp_nodelay,
  3178. bool ipv6_v6only, SocketOptions socket_options,
  3179. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  3180. // Get address info
  3181. const char *node = nullptr;
  3182. struct addrinfo hints;
  3183. struct addrinfo *result;
  3184. memset(&hints, 0, sizeof(struct addrinfo));
  3185. hints.ai_socktype = SOCK_STREAM;
  3186. hints.ai_protocol = IPPROTO_IP;
  3187. if (!ip.empty()) {
  3188. node = ip.c_str();
  3189. // Ask getaddrinfo to convert IP in c-string to address
  3190. hints.ai_family = AF_UNSPEC;
  3191. hints.ai_flags = AI_NUMERICHOST;
  3192. } else {
  3193. if (!host.empty()) { node = host.c_str(); }
  3194. hints.ai_family = address_family;
  3195. hints.ai_flags = socket_flags;
  3196. }
  3197. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  3198. if (hints.ai_family == AF_UNIX) {
  3199. const auto addrlen = host.length();
  3200. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  3201. #ifdef SOCK_CLOEXEC
  3202. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  3203. hints.ai_protocol);
  3204. #else
  3205. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  3206. #endif
  3207. if (sock != INVALID_SOCKET) {
  3208. sockaddr_un addr{};
  3209. addr.sun_family = AF_UNIX;
  3210. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  3211. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  3212. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  3213. hints.ai_addrlen = static_cast<socklen_t>(
  3214. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  3215. #ifndef SOCK_CLOEXEC
  3216. #ifndef _WIN32
  3217. fcntl(sock, F_SETFD, FD_CLOEXEC);
  3218. #endif
  3219. #endif
  3220. if (socket_options) { socket_options(sock); }
  3221. #ifdef _WIN32
  3222. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  3223. // remove the option.
  3224. detail::set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  3225. #endif
  3226. bool dummy;
  3227. if (!bind_or_connect(sock, hints, dummy)) {
  3228. close_socket(sock);
  3229. sock = INVALID_SOCKET;
  3230. }
  3231. }
  3232. return sock;
  3233. }
  3234. #endif
  3235. auto service = std::to_string(port);
  3236. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  3237. timeout_sec)) {
  3238. #if defined __linux__ && !defined __ANDROID__
  3239. res_init();
  3240. #endif
  3241. return INVALID_SOCKET;
  3242. }
  3243. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  3244. for (auto rp = result; rp; rp = rp->ai_next) {
  3245. // Create a socket
  3246. #ifdef _WIN32
  3247. auto sock =
  3248. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  3249. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  3250. /**
  3251. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  3252. * and above the socket creation fails on older Windows Systems.
  3253. *
  3254. * Let's try to create a socket the old way in this case.
  3255. *
  3256. * Reference:
  3257. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  3258. *
  3259. * WSA_FLAG_NO_HANDLE_INHERIT:
  3260. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  3261. * SP1, and later
  3262. *
  3263. */
  3264. if (sock == INVALID_SOCKET) {
  3265. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  3266. }
  3267. #else
  3268. #ifdef SOCK_CLOEXEC
  3269. auto sock =
  3270. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  3271. #else
  3272. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  3273. #endif
  3274. #endif
  3275. if (sock == INVALID_SOCKET) { continue; }
  3276. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  3277. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  3278. close_socket(sock);
  3279. continue;
  3280. }
  3281. #endif
  3282. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  3283. if (rp->ai_family == AF_INET6) {
  3284. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  3285. }
  3286. if (socket_options) { socket_options(sock); }
  3287. // bind or connect
  3288. auto quit = false;
  3289. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  3290. close_socket(sock);
  3291. if (quit) { break; }
  3292. }
  3293. return INVALID_SOCKET;
  3294. }
  3295. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  3296. #ifdef _WIN32
  3297. auto flags = nonblocking ? 1UL : 0UL;
  3298. ioctlsocket(sock, FIONBIO, &flags);
  3299. #else
  3300. auto flags = fcntl(sock, F_GETFL, 0);
  3301. fcntl(sock, F_SETFL,
  3302. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  3303. #endif
  3304. }
  3305. inline bool is_connection_error() {
  3306. #ifdef _WIN32
  3307. return WSAGetLastError() != WSAEWOULDBLOCK;
  3308. #else
  3309. return errno != EINPROGRESS;
  3310. #endif
  3311. }
  3312. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  3313. struct addrinfo hints;
  3314. struct addrinfo *result;
  3315. memset(&hints, 0, sizeof(struct addrinfo));
  3316. hints.ai_family = AF_UNSPEC;
  3317. hints.ai_socktype = SOCK_STREAM;
  3318. hints.ai_protocol = 0;
  3319. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  3320. return false;
  3321. }
  3322. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  3323. auto ret = false;
  3324. for (auto rp = result; rp; rp = rp->ai_next) {
  3325. const auto &ai = *rp;
  3326. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  3327. ret = true;
  3328. break;
  3329. }
  3330. }
  3331. return ret;
  3332. }
  3333. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  3334. #define USE_IF2IP
  3335. #endif
  3336. #ifdef USE_IF2IP
  3337. inline std::string if2ip(int address_family, const std::string &ifn) {
  3338. struct ifaddrs *ifap;
  3339. getifaddrs(&ifap);
  3340. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  3341. std::string addr_candidate;
  3342. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  3343. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  3344. (AF_UNSPEC == address_family ||
  3345. ifa->ifa_addr->sa_family == address_family)) {
  3346. if (ifa->ifa_addr->sa_family == AF_INET) {
  3347. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  3348. char buf[INET_ADDRSTRLEN];
  3349. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  3350. return std::string(buf, INET_ADDRSTRLEN);
  3351. }
  3352. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  3353. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  3354. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  3355. char buf[INET6_ADDRSTRLEN] = {};
  3356. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  3357. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  3358. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  3359. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  3360. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  3361. } else {
  3362. return std::string(buf, INET6_ADDRSTRLEN);
  3363. }
  3364. }
  3365. }
  3366. }
  3367. }
  3368. }
  3369. return addr_candidate;
  3370. }
  3371. #endif
  3372. inline socket_t create_client_socket(
  3373. const std::string &host, const std::string &ip, int port,
  3374. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  3375. SocketOptions socket_options, time_t connection_timeout_sec,
  3376. time_t connection_timeout_usec, time_t read_timeout_sec,
  3377. time_t read_timeout_usec, time_t write_timeout_sec,
  3378. time_t write_timeout_usec, const std::string &intf, Error &error) {
  3379. auto sock = create_socket(
  3380. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  3381. std::move(socket_options),
  3382. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  3383. if (!intf.empty()) {
  3384. #ifdef USE_IF2IP
  3385. auto ip_from_if = if2ip(address_family, intf);
  3386. if (ip_from_if.empty()) { ip_from_if = intf; }
  3387. if (!bind_ip_address(sock2, ip_from_if)) {
  3388. error = Error::BindIPAddress;
  3389. return false;
  3390. }
  3391. #endif
  3392. }
  3393. set_nonblocking(sock2, true);
  3394. auto ret =
  3395. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  3396. if (ret < 0) {
  3397. if (is_connection_error()) {
  3398. error = Error::Connection;
  3399. return false;
  3400. }
  3401. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  3402. connection_timeout_usec);
  3403. if (error != Error::Success) {
  3404. if (error == Error::ConnectionTimeout) { quit = true; }
  3405. return false;
  3406. }
  3407. }
  3408. set_nonblocking(sock2, false);
  3409. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  3410. read_timeout_usec);
  3411. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  3412. write_timeout_usec);
  3413. error = Error::Success;
  3414. return true;
  3415. },
  3416. connection_timeout_sec); // Pass DNS timeout
  3417. if (sock != INVALID_SOCKET) {
  3418. error = Error::Success;
  3419. } else {
  3420. if (error == Error::Success) { error = Error::Connection; }
  3421. }
  3422. return sock;
  3423. }
  3424. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  3425. socklen_t addr_len, std::string &ip, int &port) {
  3426. if (addr.ss_family == AF_INET) {
  3427. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  3428. } else if (addr.ss_family == AF_INET6) {
  3429. port =
  3430. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  3431. } else {
  3432. return false;
  3433. }
  3434. std::array<char, NI_MAXHOST> ipstr{};
  3435. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  3436. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  3437. 0, NI_NUMERICHOST)) {
  3438. return false;
  3439. }
  3440. ip = ipstr.data();
  3441. return true;
  3442. }
  3443. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  3444. struct sockaddr_storage addr;
  3445. socklen_t addr_len = sizeof(addr);
  3446. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  3447. &addr_len)) {
  3448. get_ip_and_port(addr, addr_len, ip, port);
  3449. }
  3450. }
  3451. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  3452. struct sockaddr_storage addr;
  3453. socklen_t addr_len = sizeof(addr);
  3454. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  3455. &addr_len)) {
  3456. #ifndef _WIN32
  3457. if (addr.ss_family == AF_UNIX) {
  3458. #if defined(__linux__)
  3459. struct ucred ucred;
  3460. socklen_t len = sizeof(ucred);
  3461. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  3462. port = ucred.pid;
  3463. }
  3464. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  3465. pid_t pid;
  3466. socklen_t len = sizeof(pid);
  3467. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  3468. port = pid;
  3469. }
  3470. #endif
  3471. return;
  3472. }
  3473. #endif
  3474. get_ip_and_port(addr, addr_len, ip, port);
  3475. }
  3476. }
  3477. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  3478. unsigned int h) {
  3479. return (l == 0)
  3480. ? h
  3481. : str2tag_core(
  3482. s + 1, l - 1,
  3483. // Unsets the 6 high bits of h, therefore no overflow happens
  3484. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  3485. h * 33) ^
  3486. static_cast<unsigned char>(*s));
  3487. }
  3488. inline unsigned int str2tag(const std::string &s) {
  3489. return str2tag_core(s.data(), s.size(), 0);
  3490. }
  3491. namespace udl {
  3492. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  3493. return str2tag_core(s, l, 0);
  3494. }
  3495. } // namespace udl
  3496. inline std::string
  3497. find_content_type(const std::string &path,
  3498. const std::map<std::string, std::string> &user_data,
  3499. const std::string &default_content_type) {
  3500. auto ext = file_extension(path);
  3501. auto it = user_data.find(ext);
  3502. if (it != user_data.end()) { return it->second; }
  3503. using udl::operator""_t;
  3504. switch (str2tag(ext)) {
  3505. default: return default_content_type;
  3506. case "css"_t: return "text/css";
  3507. case "csv"_t: return "text/csv";
  3508. case "htm"_t:
  3509. case "html"_t: return "text/html";
  3510. case "js"_t:
  3511. case "mjs"_t: return "text/javascript";
  3512. case "txt"_t: return "text/plain";
  3513. case "vtt"_t: return "text/vtt";
  3514. case "apng"_t: return "image/apng";
  3515. case "avif"_t: return "image/avif";
  3516. case "bmp"_t: return "image/bmp";
  3517. case "gif"_t: return "image/gif";
  3518. case "png"_t: return "image/png";
  3519. case "svg"_t: return "image/svg+xml";
  3520. case "webp"_t: return "image/webp";
  3521. case "ico"_t: return "image/x-icon";
  3522. case "tif"_t: return "image/tiff";
  3523. case "tiff"_t: return "image/tiff";
  3524. case "jpg"_t:
  3525. case "jpeg"_t: return "image/jpeg";
  3526. case "mp4"_t: return "video/mp4";
  3527. case "mpeg"_t: return "video/mpeg";
  3528. case "webm"_t: return "video/webm";
  3529. case "mp3"_t: return "audio/mp3";
  3530. case "mpga"_t: return "audio/mpeg";
  3531. case "weba"_t: return "audio/webm";
  3532. case "wav"_t: return "audio/wave";
  3533. case "otf"_t: return "font/otf";
  3534. case "ttf"_t: return "font/ttf";
  3535. case "woff"_t: return "font/woff";
  3536. case "woff2"_t: return "font/woff2";
  3537. case "7z"_t: return "application/x-7z-compressed";
  3538. case "atom"_t: return "application/atom+xml";
  3539. case "pdf"_t: return "application/pdf";
  3540. case "json"_t: return "application/json";
  3541. case "rss"_t: return "application/rss+xml";
  3542. case "tar"_t: return "application/x-tar";
  3543. case "xht"_t:
  3544. case "xhtml"_t: return "application/xhtml+xml";
  3545. case "xslt"_t: return "application/xslt+xml";
  3546. case "xml"_t: return "application/xml";
  3547. case "gz"_t: return "application/gzip";
  3548. case "zip"_t: return "application/zip";
  3549. case "wasm"_t: return "application/wasm";
  3550. }
  3551. }
  3552. inline bool can_compress_content_type(const std::string &content_type) {
  3553. using udl::operator""_t;
  3554. auto tag = str2tag(content_type);
  3555. switch (tag) {
  3556. case "image/svg+xml"_t:
  3557. case "application/javascript"_t:
  3558. case "application/json"_t:
  3559. case "application/xml"_t:
  3560. case "application/protobuf"_t:
  3561. case "application/xhtml+xml"_t: return true;
  3562. case "text/event-stream"_t: return false;
  3563. default: return !content_type.rfind("text/", 0);
  3564. }
  3565. }
  3566. inline EncodingType encoding_type(const Request &req, const Response &res) {
  3567. auto ret =
  3568. detail::can_compress_content_type(res.get_header_value("Content-Type"));
  3569. if (!ret) { return EncodingType::None; }
  3570. const auto &s = req.get_header_value("Accept-Encoding");
  3571. (void)(s);
  3572. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3573. // TODO: 'Accept-Encoding' has br, not br;q=0
  3574. ret = s.find("br") != std::string::npos;
  3575. if (ret) { return EncodingType::Brotli; }
  3576. #endif
  3577. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3578. // TODO: 'Accept-Encoding' has gzip, not gzip;q=0
  3579. ret = s.find("gzip") != std::string::npos;
  3580. if (ret) { return EncodingType::Gzip; }
  3581. #endif
  3582. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  3583. // TODO: 'Accept-Encoding' has zstd, not zstd;q=0
  3584. ret = s.find("zstd") != std::string::npos;
  3585. if (ret) { return EncodingType::Zstd; }
  3586. #endif
  3587. return EncodingType::None;
  3588. }
  3589. inline bool nocompressor::compress(const char *data, size_t data_length,
  3590. bool /*last*/, Callback callback) {
  3591. if (!data_length) { return true; }
  3592. return callback(data, data_length);
  3593. }
  3594. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3595. inline gzip_compressor::gzip_compressor() {
  3596. std::memset(&strm_, 0, sizeof(strm_));
  3597. strm_.zalloc = Z_NULL;
  3598. strm_.zfree = Z_NULL;
  3599. strm_.opaque = Z_NULL;
  3600. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  3601. Z_DEFAULT_STRATEGY) == Z_OK;
  3602. }
  3603. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  3604. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  3605. bool last, Callback callback) {
  3606. assert(is_valid_);
  3607. do {
  3608. constexpr size_t max_avail_in =
  3609. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  3610. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  3611. (std::min)(data_length, max_avail_in));
  3612. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  3613. data_length -= strm_.avail_in;
  3614. data += strm_.avail_in;
  3615. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  3616. auto ret = Z_OK;
  3617. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3618. do {
  3619. strm_.avail_out = static_cast<uInt>(buff.size());
  3620. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  3621. ret = deflate(&strm_, flush);
  3622. if (ret == Z_STREAM_ERROR) { return false; }
  3623. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  3624. return false;
  3625. }
  3626. } while (strm_.avail_out == 0);
  3627. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  3628. (flush == Z_NO_FLUSH && ret == Z_OK));
  3629. assert(strm_.avail_in == 0);
  3630. } while (data_length > 0);
  3631. return true;
  3632. }
  3633. inline gzip_decompressor::gzip_decompressor() {
  3634. std::memset(&strm_, 0, sizeof(strm_));
  3635. strm_.zalloc = Z_NULL;
  3636. strm_.zfree = Z_NULL;
  3637. strm_.opaque = Z_NULL;
  3638. // 15 is the value of wbits, which should be at the maximum possible value
  3639. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  3640. // that the stream type should be automatically detected either gzip or
  3641. // deflate.
  3642. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  3643. }
  3644. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  3645. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  3646. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  3647. Callback callback) {
  3648. assert(is_valid_);
  3649. auto ret = Z_OK;
  3650. do {
  3651. constexpr size_t max_avail_in =
  3652. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  3653. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  3654. (std::min)(data_length, max_avail_in));
  3655. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  3656. data_length -= strm_.avail_in;
  3657. data += strm_.avail_in;
  3658. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3659. while (strm_.avail_in > 0 && ret == Z_OK) {
  3660. strm_.avail_out = static_cast<uInt>(buff.size());
  3661. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  3662. ret = inflate(&strm_, Z_NO_FLUSH);
  3663. assert(ret != Z_STREAM_ERROR);
  3664. switch (ret) {
  3665. case Z_NEED_DICT:
  3666. case Z_DATA_ERROR:
  3667. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  3668. }
  3669. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  3670. return false;
  3671. }
  3672. }
  3673. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  3674. } while (data_length > 0);
  3675. return true;
  3676. }
  3677. #endif
  3678. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3679. inline brotli_compressor::brotli_compressor() {
  3680. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  3681. }
  3682. inline brotli_compressor::~brotli_compressor() {
  3683. BrotliEncoderDestroyInstance(state_);
  3684. }
  3685. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  3686. bool last, Callback callback) {
  3687. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3688. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  3689. auto available_in = data_length;
  3690. auto next_in = reinterpret_cast<const uint8_t *>(data);
  3691. for (;;) {
  3692. if (last) {
  3693. if (BrotliEncoderIsFinished(state_)) { break; }
  3694. } else {
  3695. if (!available_in) { break; }
  3696. }
  3697. auto available_out = buff.size();
  3698. auto next_out = buff.data();
  3699. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  3700. &available_out, &next_out, nullptr)) {
  3701. return false;
  3702. }
  3703. auto output_bytes = buff.size() - available_out;
  3704. if (output_bytes) {
  3705. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  3706. }
  3707. }
  3708. return true;
  3709. }
  3710. inline brotli_decompressor::brotli_decompressor() {
  3711. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  3712. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  3713. : BROTLI_DECODER_RESULT_ERROR;
  3714. }
  3715. inline brotli_decompressor::~brotli_decompressor() {
  3716. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  3717. }
  3718. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  3719. inline bool brotli_decompressor::decompress(const char *data,
  3720. size_t data_length,
  3721. Callback callback) {
  3722. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  3723. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  3724. return 0;
  3725. }
  3726. auto next_in = reinterpret_cast<const uint8_t *>(data);
  3727. size_t avail_in = data_length;
  3728. size_t total_out;
  3729. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  3730. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3731. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  3732. char *next_out = buff.data();
  3733. size_t avail_out = buff.size();
  3734. decoder_r = BrotliDecoderDecompressStream(
  3735. decoder_s, &avail_in, &next_in, &avail_out,
  3736. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  3737. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  3738. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  3739. }
  3740. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  3741. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  3742. }
  3743. #endif
  3744. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  3745. inline zstd_compressor::zstd_compressor() {
  3746. ctx_ = ZSTD_createCCtx();
  3747. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  3748. }
  3749. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  3750. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  3751. bool last, Callback callback) {
  3752. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3753. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  3754. ZSTD_inBuffer input = {data, data_length, 0};
  3755. bool finished;
  3756. do {
  3757. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  3758. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  3759. if (ZSTD_isError(remaining)) { return false; }
  3760. if (!callback(buff.data(), output.pos)) { return false; }
  3761. finished = last ? (remaining == 0) : (input.pos == input.size);
  3762. } while (!finished);
  3763. return true;
  3764. }
  3765. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  3766. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  3767. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  3768. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  3769. Callback callback) {
  3770. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3771. ZSTD_inBuffer input = {data, data_length, 0};
  3772. while (input.pos < input.size) {
  3773. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  3774. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  3775. if (ZSTD_isError(remaining)) { return false; }
  3776. if (!callback(buff.data(), output.pos)) { return false; }
  3777. }
  3778. return true;
  3779. }
  3780. #endif
  3781. inline bool is_prohibited_header_name(const std::string &name) {
  3782. using udl::operator""_t;
  3783. switch (str2tag(name)) {
  3784. case "REMOTE_ADDR"_t:
  3785. case "REMOTE_PORT"_t:
  3786. case "LOCAL_ADDR"_t:
  3787. case "LOCAL_PORT"_t: return true;
  3788. default: return false;
  3789. }
  3790. }
  3791. inline bool has_header(const Headers &headers, const std::string &key) {
  3792. if (is_prohibited_header_name(key)) { return false; }
  3793. return headers.find(key) != headers.end();
  3794. }
  3795. inline const char *get_header_value(const Headers &headers,
  3796. const std::string &key, const char *def,
  3797. size_t id) {
  3798. if (is_prohibited_header_name(key)) {
  3799. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3800. std::string msg = "Prohibited header name '" + key + "' is specified.";
  3801. throw std::invalid_argument(msg);
  3802. #else
  3803. return "";
  3804. #endif
  3805. }
  3806. auto rng = headers.equal_range(key);
  3807. auto it = rng.first;
  3808. std::advance(it, static_cast<ssize_t>(id));
  3809. if (it != rng.second) { return it->second.c_str(); }
  3810. return def;
  3811. }
  3812. template <typename T>
  3813. inline bool parse_header(const char *beg, const char *end, T fn) {
  3814. // Skip trailing spaces and tabs.
  3815. while (beg < end && is_space_or_tab(end[-1])) {
  3816. end--;
  3817. }
  3818. auto p = beg;
  3819. while (p < end && *p != ':') {
  3820. p++;
  3821. }
  3822. auto name = std::string(beg, p);
  3823. if (!detail::fields::is_field_name(name)) { return false; }
  3824. if (p == end) { return false; }
  3825. auto key_end = p;
  3826. if (*p++ != ':') { return false; }
  3827. while (p < end && is_space_or_tab(*p)) {
  3828. p++;
  3829. }
  3830. if (p <= end) {
  3831. auto key_len = key_end - beg;
  3832. if (!key_len) { return false; }
  3833. auto key = std::string(beg, key_end);
  3834. auto val = std::string(p, end);
  3835. if (!detail::fields::is_field_value(val)) { return false; }
  3836. if (case_ignore::equal(key, "Location") ||
  3837. case_ignore::equal(key, "Referer")) {
  3838. fn(key, val);
  3839. } else {
  3840. fn(key, decode_path_component(val));
  3841. }
  3842. return true;
  3843. }
  3844. return false;
  3845. }
  3846. inline bool read_headers(Stream &strm, Headers &headers) {
  3847. const auto bufsiz = 2048;
  3848. char buf[bufsiz];
  3849. stream_line_reader line_reader(strm, buf, bufsiz);
  3850. size_t header_count = 0;
  3851. for (;;) {
  3852. if (!line_reader.getline()) { return false; }
  3853. // Check if the line ends with CRLF.
  3854. auto line_terminator_len = 2;
  3855. if (line_reader.end_with_crlf()) {
  3856. // Blank line indicates end of headers.
  3857. if (line_reader.size() == 2) { break; }
  3858. } else {
  3859. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  3860. // Blank line indicates end of headers.
  3861. if (line_reader.size() == 1) { break; }
  3862. line_terminator_len = 1;
  3863. #else
  3864. continue; // Skip invalid line.
  3865. #endif
  3866. }
  3867. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  3868. // Check header count limit
  3869. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  3870. // Exclude line terminator
  3871. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  3872. if (!parse_header(line_reader.ptr(), end,
  3873. [&](const std::string &key, const std::string &val) {
  3874. headers.emplace(key, val);
  3875. })) {
  3876. return false;
  3877. }
  3878. header_count++;
  3879. }
  3880. return true;
  3881. }
  3882. inline bool read_content_with_length(Stream &strm, size_t len,
  3883. DownloadProgress progress,
  3884. ContentReceiverWithProgress out) {
  3885. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  3886. size_t r = 0;
  3887. while (r < len) {
  3888. auto read_len = static_cast<size_t>(len - r);
  3889. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  3890. if (n <= 0) { return false; }
  3891. if (!out(buf, static_cast<size_t>(n), r, len)) { return false; }
  3892. r += static_cast<size_t>(n);
  3893. if (progress) {
  3894. if (!progress(r, len)) { return false; }
  3895. }
  3896. }
  3897. return true;
  3898. }
  3899. inline void skip_content_with_length(Stream &strm, size_t len) {
  3900. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  3901. size_t r = 0;
  3902. while (r < len) {
  3903. auto read_len = static_cast<size_t>(len - r);
  3904. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  3905. if (n <= 0) { return; }
  3906. r += static_cast<size_t>(n);
  3907. }
  3908. }
  3909. enum class ReadContentResult {
  3910. Success, // Successfully read the content
  3911. PayloadTooLarge, // The content exceeds the specified payload limit
  3912. Error // An error occurred while reading the content
  3913. };
  3914. inline ReadContentResult
  3915. read_content_without_length(Stream &strm, size_t payload_max_length,
  3916. ContentReceiverWithProgress out) {
  3917. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  3918. size_t r = 0;
  3919. for (;;) {
  3920. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  3921. if (n == 0) { return ReadContentResult::Success; }
  3922. if (n < 0) { return ReadContentResult::Error; }
  3923. // Check if adding this data would exceed the payload limit
  3924. if (r > payload_max_length ||
  3925. payload_max_length - r < static_cast<size_t>(n)) {
  3926. return ReadContentResult::PayloadTooLarge;
  3927. }
  3928. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  3929. return ReadContentResult::Error;
  3930. }
  3931. r += static_cast<size_t>(n);
  3932. }
  3933. return ReadContentResult::Success;
  3934. }
  3935. template <typename T>
  3936. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  3937. size_t payload_max_length,
  3938. ContentReceiverWithProgress out) {
  3939. const auto bufsiz = 16;
  3940. char buf[bufsiz];
  3941. stream_line_reader line_reader(strm, buf, bufsiz);
  3942. if (!line_reader.getline()) { return ReadContentResult::Error; }
  3943. unsigned long chunk_len;
  3944. size_t total_len = 0;
  3945. while (true) {
  3946. char *end_ptr;
  3947. chunk_len = std::strtoul(line_reader.ptr(), &end_ptr, 16);
  3948. if (end_ptr == line_reader.ptr()) { return ReadContentResult::Error; }
  3949. if (chunk_len == ULONG_MAX) { return ReadContentResult::Error; }
  3950. if (chunk_len == 0) { break; }
  3951. // Check if adding this chunk would exceed the payload limit
  3952. if (total_len > payload_max_length ||
  3953. payload_max_length - total_len < chunk_len) {
  3954. return ReadContentResult::PayloadTooLarge;
  3955. }
  3956. total_len += chunk_len;
  3957. if (!read_content_with_length(strm, chunk_len, nullptr, out)) {
  3958. return ReadContentResult::Error;
  3959. }
  3960. if (!line_reader.getline()) { return ReadContentResult::Error; }
  3961. if (strcmp(line_reader.ptr(), "\r\n") != 0) {
  3962. return ReadContentResult::Error;
  3963. }
  3964. if (!line_reader.getline()) { return ReadContentResult::Error; }
  3965. }
  3966. assert(chunk_len == 0);
  3967. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  3968. // transfer coding is complete when a chunk with a chunk-size of zero is
  3969. // received, possibly followed by a trailer section, and finally terminated by
  3970. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  3971. //
  3972. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  3973. // does't care for the existence of the final CRLF. In other words, it seems
  3974. // to be ok whether the final CRLF exists or not in the chunked data.
  3975. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  3976. //
  3977. // According to the reference code in RFC 9112, cpp-httplib now allows
  3978. // chunked transfer coding data without the final CRLF.
  3979. if (!line_reader.getline()) { return ReadContentResult::Success; }
  3980. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  3981. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  3982. // Message framing
  3983. "transfer-encoding", "content-length",
  3984. // Routing
  3985. "host",
  3986. // Authentication
  3987. "authorization", "www-authenticate", "proxy-authenticate",
  3988. "proxy-authorization", "cookie", "set-cookie",
  3989. // Request modifiers
  3990. "cache-control", "expect", "max-forwards", "pragma", "range", "te",
  3991. // Response control
  3992. "age", "expires", "date", "location", "retry-after", "vary", "warning",
  3993. // Payload processing
  3994. "content-encoding", "content-type", "content-range", "trailer"};
  3995. // Parse declared trailer headers once for performance
  3996. case_ignore::unordered_set<std::string> declared_trailers;
  3997. if (has_header(x.headers, "Trailer")) {
  3998. auto trailer_header = get_header_value(x.headers, "Trailer", "", 0);
  3999. auto len = std::strlen(trailer_header);
  4000. split(trailer_header, trailer_header + len, ',',
  4001. [&](const char *b, const char *e) {
  4002. std::string key(b, e);
  4003. if (prohibited_trailers.find(key) == prohibited_trailers.end()) {
  4004. declared_trailers.insert(key);
  4005. }
  4006. });
  4007. }
  4008. size_t trailer_header_count = 0;
  4009. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  4010. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) {
  4011. return ReadContentResult::Error;
  4012. }
  4013. // Check trailer header count limit
  4014. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) {
  4015. return ReadContentResult::Error;
  4016. }
  4017. // Exclude line terminator
  4018. constexpr auto line_terminator_len = 2;
  4019. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  4020. parse_header(line_reader.ptr(), end,
  4021. [&](const std::string &key, const std::string &val) {
  4022. if (declared_trailers.find(key) != declared_trailers.end()) {
  4023. x.trailers.emplace(key, val);
  4024. trailer_header_count++;
  4025. }
  4026. });
  4027. if (!line_reader.getline()) { return ReadContentResult::Error; }
  4028. }
  4029. return ReadContentResult::Success;
  4030. }
  4031. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  4032. return case_ignore::equal(
  4033. get_header_value(headers, "Transfer-Encoding", "", 0), "chunked");
  4034. }
  4035. template <typename T, typename U>
  4036. bool prepare_content_receiver(T &x, int &status,
  4037. ContentReceiverWithProgress receiver,
  4038. bool decompress, U callback) {
  4039. if (decompress) {
  4040. std::string encoding = x.get_header_value("Content-Encoding");
  4041. std::unique_ptr<decompressor> decompressor;
  4042. if (encoding == "gzip" || encoding == "deflate") {
  4043. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4044. decompressor = detail::make_unique<gzip_decompressor>();
  4045. #else
  4046. status = StatusCode::UnsupportedMediaType_415;
  4047. return false;
  4048. #endif
  4049. } else if (encoding.find("br") != std::string::npos) {
  4050. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4051. decompressor = detail::make_unique<brotli_decompressor>();
  4052. #else
  4053. status = StatusCode::UnsupportedMediaType_415;
  4054. return false;
  4055. #endif
  4056. } else if (encoding == "zstd") {
  4057. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4058. decompressor = detail::make_unique<zstd_decompressor>();
  4059. #else
  4060. status = StatusCode::UnsupportedMediaType_415;
  4061. return false;
  4062. #endif
  4063. }
  4064. if (decompressor) {
  4065. if (decompressor->is_valid()) {
  4066. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  4067. size_t off, size_t len) {
  4068. return decompressor->decompress(buf, n,
  4069. [&](const char *buf2, size_t n2) {
  4070. return receiver(buf2, n2, off, len);
  4071. });
  4072. };
  4073. return callback(std::move(out));
  4074. } else {
  4075. status = StatusCode::InternalServerError_500;
  4076. return false;
  4077. }
  4078. }
  4079. }
  4080. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  4081. size_t len) {
  4082. return receiver(buf, n, off, len);
  4083. };
  4084. return callback(std::move(out));
  4085. }
  4086. template <typename T>
  4087. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  4088. DownloadProgress progress,
  4089. ContentReceiverWithProgress receiver, bool decompress) {
  4090. return prepare_content_receiver(
  4091. x, status, std::move(receiver), decompress,
  4092. [&](const ContentReceiverWithProgress &out) {
  4093. auto ret = true;
  4094. auto exceed_payload_max_length = false;
  4095. if (is_chunked_transfer_encoding(x.headers)) {
  4096. auto result = read_content_chunked(strm, x, payload_max_length, out);
  4097. if (result == ReadContentResult::Success) {
  4098. ret = true;
  4099. } else if (result == ReadContentResult::PayloadTooLarge) {
  4100. exceed_payload_max_length = true;
  4101. ret = false;
  4102. } else {
  4103. ret = false;
  4104. }
  4105. } else if (!has_header(x.headers, "Content-Length")) {
  4106. auto result =
  4107. read_content_without_length(strm, payload_max_length, out);
  4108. if (result == ReadContentResult::Success) {
  4109. ret = true;
  4110. } else if (result == ReadContentResult::PayloadTooLarge) {
  4111. exceed_payload_max_length = true;
  4112. ret = false;
  4113. } else {
  4114. ret = false;
  4115. }
  4116. } else {
  4117. auto is_invalid_value = false;
  4118. auto len = get_header_value_u64(x.headers, "Content-Length",
  4119. (std::numeric_limits<size_t>::max)(),
  4120. 0, is_invalid_value);
  4121. if (is_invalid_value) {
  4122. ret = false;
  4123. } else if (len > payload_max_length) {
  4124. exceed_payload_max_length = true;
  4125. skip_content_with_length(strm, len);
  4126. ret = false;
  4127. } else if (len > 0) {
  4128. ret = read_content_with_length(strm, len, std::move(progress), out);
  4129. }
  4130. }
  4131. if (!ret) {
  4132. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  4133. : StatusCode::BadRequest_400;
  4134. }
  4135. return ret;
  4136. });
  4137. }
  4138. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  4139. const std::string &path) {
  4140. std::string s = method;
  4141. s += " ";
  4142. s += path;
  4143. s += " HTTP/1.1\r\n";
  4144. return strm.write(s.data(), s.size());
  4145. }
  4146. inline ssize_t write_response_line(Stream &strm, int status) {
  4147. std::string s = "HTTP/1.1 ";
  4148. s += std::to_string(status);
  4149. s += " ";
  4150. s += httplib::status_message(status);
  4151. s += "\r\n";
  4152. return strm.write(s.data(), s.size());
  4153. }
  4154. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  4155. ssize_t write_len = 0;
  4156. for (const auto &x : headers) {
  4157. std::string s;
  4158. s = x.first;
  4159. s += ": ";
  4160. s += x.second;
  4161. s += "\r\n";
  4162. auto len = strm.write(s.data(), s.size());
  4163. if (len < 0) { return len; }
  4164. write_len += len;
  4165. }
  4166. auto len = strm.write("\r\n");
  4167. if (len < 0) { return len; }
  4168. write_len += len;
  4169. return write_len;
  4170. }
  4171. inline bool write_data(Stream &strm, const char *d, size_t l) {
  4172. size_t offset = 0;
  4173. while (offset < l) {
  4174. auto length = strm.write(d + offset, l - offset);
  4175. if (length < 0) { return false; }
  4176. offset += static_cast<size_t>(length);
  4177. }
  4178. return true;
  4179. }
  4180. template <typename T>
  4181. inline bool write_content_with_progress(Stream &strm,
  4182. const ContentProvider &content_provider,
  4183. size_t offset, size_t length,
  4184. T is_shutting_down,
  4185. const UploadProgress &upload_progress,
  4186. Error &error) {
  4187. size_t end_offset = offset + length;
  4188. size_t start_offset = offset;
  4189. auto ok = true;
  4190. DataSink data_sink;
  4191. data_sink.write = [&](const char *d, size_t l) -> bool {
  4192. if (ok) {
  4193. if (write_data(strm, d, l)) {
  4194. offset += l;
  4195. if (upload_progress && length > 0) {
  4196. size_t current_written = offset - start_offset;
  4197. if (!upload_progress(current_written, length)) {
  4198. ok = false;
  4199. return false;
  4200. }
  4201. }
  4202. } else {
  4203. ok = false;
  4204. }
  4205. }
  4206. return ok;
  4207. };
  4208. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  4209. while (offset < end_offset && !is_shutting_down()) {
  4210. if (!strm.wait_writable()) {
  4211. error = Error::Write;
  4212. return false;
  4213. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  4214. error = Error::Canceled;
  4215. return false;
  4216. } else if (!ok) {
  4217. error = Error::Write;
  4218. return false;
  4219. }
  4220. }
  4221. error = Error::Success;
  4222. return true;
  4223. }
  4224. template <typename T>
  4225. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  4226. size_t offset, size_t length, T is_shutting_down,
  4227. Error &error) {
  4228. return write_content_with_progress<T>(strm, content_provider, offset, length,
  4229. is_shutting_down, nullptr, error);
  4230. }
  4231. template <typename T>
  4232. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  4233. size_t offset, size_t length,
  4234. const T &is_shutting_down) {
  4235. auto error = Error::Success;
  4236. return write_content(strm, content_provider, offset, length, is_shutting_down,
  4237. error);
  4238. }
  4239. template <typename T>
  4240. inline bool
  4241. write_content_without_length(Stream &strm,
  4242. const ContentProvider &content_provider,
  4243. const T &is_shutting_down) {
  4244. size_t offset = 0;
  4245. auto data_available = true;
  4246. auto ok = true;
  4247. DataSink data_sink;
  4248. data_sink.write = [&](const char *d, size_t l) -> bool {
  4249. if (ok) {
  4250. offset += l;
  4251. if (!write_data(strm, d, l)) { ok = false; }
  4252. }
  4253. return ok;
  4254. };
  4255. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  4256. data_sink.done = [&](void) { data_available = false; };
  4257. while (data_available && !is_shutting_down()) {
  4258. if (!strm.wait_writable()) {
  4259. return false;
  4260. } else if (!content_provider(offset, 0, data_sink)) {
  4261. return false;
  4262. } else if (!ok) {
  4263. return false;
  4264. }
  4265. }
  4266. return true;
  4267. }
  4268. template <typename T, typename U>
  4269. inline bool
  4270. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  4271. const T &is_shutting_down, U &compressor, Error &error) {
  4272. size_t offset = 0;
  4273. auto data_available = true;
  4274. auto ok = true;
  4275. DataSink data_sink;
  4276. data_sink.write = [&](const char *d, size_t l) -> bool {
  4277. if (ok) {
  4278. data_available = l > 0;
  4279. offset += l;
  4280. std::string payload;
  4281. if (compressor.compress(d, l, false,
  4282. [&](const char *data, size_t data_len) {
  4283. payload.append(data, data_len);
  4284. return true;
  4285. })) {
  4286. if (!payload.empty()) {
  4287. // Emit chunked response header and footer for each chunk
  4288. auto chunk =
  4289. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  4290. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  4291. }
  4292. } else {
  4293. ok = false;
  4294. }
  4295. }
  4296. return ok;
  4297. };
  4298. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  4299. auto done_with_trailer = [&](const Headers *trailer) {
  4300. if (!ok) { return; }
  4301. data_available = false;
  4302. std::string payload;
  4303. if (!compressor.compress(nullptr, 0, true,
  4304. [&](const char *data, size_t data_len) {
  4305. payload.append(data, data_len);
  4306. return true;
  4307. })) {
  4308. ok = false;
  4309. return;
  4310. }
  4311. if (!payload.empty()) {
  4312. // Emit chunked response header and footer for each chunk
  4313. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  4314. if (!write_data(strm, chunk.data(), chunk.size())) {
  4315. ok = false;
  4316. return;
  4317. }
  4318. }
  4319. constexpr const char done_marker[] = "0\r\n";
  4320. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  4321. // Trailer
  4322. if (trailer) {
  4323. for (const auto &kv : *trailer) {
  4324. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  4325. if (!write_data(strm, field_line.data(), field_line.size())) {
  4326. ok = false;
  4327. }
  4328. }
  4329. }
  4330. constexpr const char crlf[] = "\r\n";
  4331. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  4332. };
  4333. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  4334. data_sink.done_with_trailer = [&](const Headers &trailer) {
  4335. done_with_trailer(&trailer);
  4336. };
  4337. while (data_available && !is_shutting_down()) {
  4338. if (!strm.wait_writable()) {
  4339. error = Error::Write;
  4340. return false;
  4341. } else if (!content_provider(offset, 0, data_sink)) {
  4342. error = Error::Canceled;
  4343. return false;
  4344. } else if (!ok) {
  4345. error = Error::Write;
  4346. return false;
  4347. }
  4348. }
  4349. error = Error::Success;
  4350. return true;
  4351. }
  4352. template <typename T, typename U>
  4353. inline bool write_content_chunked(Stream &strm,
  4354. const ContentProvider &content_provider,
  4355. const T &is_shutting_down, U &compressor) {
  4356. auto error = Error::Success;
  4357. return write_content_chunked(strm, content_provider, is_shutting_down,
  4358. compressor, error);
  4359. }
  4360. template <typename T>
  4361. inline bool redirect(T &cli, Request &req, Response &res,
  4362. const std::string &path, const std::string &location,
  4363. Error &error) {
  4364. Request new_req = req;
  4365. new_req.path = path;
  4366. new_req.redirect_count_ -= 1;
  4367. if (res.status == StatusCode::SeeOther_303 &&
  4368. (req.method != "GET" && req.method != "HEAD")) {
  4369. new_req.method = "GET";
  4370. new_req.body.clear();
  4371. new_req.headers.clear();
  4372. }
  4373. Response new_res;
  4374. auto ret = cli.send(new_req, new_res, error);
  4375. if (ret) {
  4376. req = new_req;
  4377. res = new_res;
  4378. if (res.location.empty()) { res.location = location; }
  4379. }
  4380. return ret;
  4381. }
  4382. inline std::string params_to_query_str(const Params &params) {
  4383. std::string query;
  4384. for (auto it = params.begin(); it != params.end(); ++it) {
  4385. if (it != params.begin()) { query += "&"; }
  4386. query += encode_query_component(it->first);
  4387. query += "=";
  4388. query += encode_query_component(it->second);
  4389. }
  4390. return query;
  4391. }
  4392. inline void parse_query_text(const char *data, std::size_t size,
  4393. Params &params) {
  4394. std::set<std::string> cache;
  4395. split(data, data + size, '&', [&](const char *b, const char *e) {
  4396. std::string kv(b, e);
  4397. if (cache.find(kv) != cache.end()) { return; }
  4398. cache.insert(std::move(kv));
  4399. std::string key;
  4400. std::string val;
  4401. divide(b, static_cast<std::size_t>(e - b), '=',
  4402. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  4403. std::size_t rhs_size) {
  4404. key.assign(lhs_data, lhs_size);
  4405. val.assign(rhs_data, rhs_size);
  4406. });
  4407. if (!key.empty()) {
  4408. params.emplace(decode_query_component(key), decode_query_component(val));
  4409. }
  4410. });
  4411. }
  4412. inline void parse_query_text(const std::string &s, Params &params) {
  4413. parse_query_text(s.data(), s.size(), params);
  4414. }
  4415. inline bool parse_multipart_boundary(const std::string &content_type,
  4416. std::string &boundary) {
  4417. auto boundary_keyword = "boundary=";
  4418. auto pos = content_type.find(boundary_keyword);
  4419. if (pos == std::string::npos) { return false; }
  4420. auto end = content_type.find(';', pos);
  4421. auto beg = pos + strlen(boundary_keyword);
  4422. boundary = trim_double_quotes_copy(content_type.substr(beg, end - beg));
  4423. return !boundary.empty();
  4424. }
  4425. inline void parse_disposition_params(const std::string &s, Params &params) {
  4426. std::set<std::string> cache;
  4427. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  4428. std::string kv(b, e);
  4429. if (cache.find(kv) != cache.end()) { return; }
  4430. cache.insert(kv);
  4431. std::string key;
  4432. std::string val;
  4433. split(b, e, '=', [&](const char *b2, const char *e2) {
  4434. if (key.empty()) {
  4435. key.assign(b2, e2);
  4436. } else {
  4437. val.assign(b2, e2);
  4438. }
  4439. });
  4440. if (!key.empty()) {
  4441. params.emplace(trim_double_quotes_copy((key)),
  4442. trim_double_quotes_copy((val)));
  4443. }
  4444. });
  4445. }
  4446. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  4447. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  4448. #else
  4449. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  4450. #endif
  4451. auto is_valid = [](const std::string &str) {
  4452. return std::all_of(str.cbegin(), str.cend(),
  4453. [](unsigned char c) { return std::isdigit(c); });
  4454. };
  4455. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  4456. const auto pos = static_cast<size_t>(6);
  4457. const auto len = static_cast<size_t>(s.size() - 6);
  4458. auto all_valid_ranges = true;
  4459. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  4460. if (!all_valid_ranges) { return; }
  4461. const auto it = std::find(b, e, '-');
  4462. if (it == e) {
  4463. all_valid_ranges = false;
  4464. return;
  4465. }
  4466. const auto lhs = std::string(b, it);
  4467. const auto rhs = std::string(it + 1, e);
  4468. if (!is_valid(lhs) || !is_valid(rhs)) {
  4469. all_valid_ranges = false;
  4470. return;
  4471. }
  4472. const auto first =
  4473. static_cast<ssize_t>(lhs.empty() ? -1 : std::stoll(lhs));
  4474. const auto last =
  4475. static_cast<ssize_t>(rhs.empty() ? -1 : std::stoll(rhs));
  4476. if ((first == -1 && last == -1) ||
  4477. (first != -1 && last != -1 && first > last)) {
  4478. all_valid_ranges = false;
  4479. return;
  4480. }
  4481. ranges.emplace_back(first, last);
  4482. });
  4483. return all_valid_ranges && !ranges.empty();
  4484. }
  4485. return false;
  4486. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  4487. }
  4488. #else
  4489. } catch (...) { return false; }
  4490. #endif
  4491. inline bool parse_accept_header(const std::string &s,
  4492. std::vector<std::string> &content_types) {
  4493. content_types.clear();
  4494. // Empty string is considered valid (no preference)
  4495. if (s.empty()) { return true; }
  4496. // Check for invalid patterns: leading/trailing commas or consecutive commas
  4497. if (s.front() == ',' || s.back() == ',' ||
  4498. s.find(",,") != std::string::npos) {
  4499. return false;
  4500. }
  4501. struct AcceptEntry {
  4502. std::string media_type;
  4503. double quality;
  4504. int order; // Original order in header
  4505. };
  4506. std::vector<AcceptEntry> entries;
  4507. int order = 0;
  4508. bool has_invalid_entry = false;
  4509. // Split by comma and parse each entry
  4510. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  4511. std::string entry(b, e);
  4512. entry = trim_copy(entry);
  4513. if (entry.empty()) {
  4514. has_invalid_entry = true;
  4515. return;
  4516. }
  4517. AcceptEntry accept_entry;
  4518. accept_entry.quality = 1.0; // Default quality
  4519. accept_entry.order = order++;
  4520. // Find q= parameter
  4521. auto q_pos = entry.find(";q=");
  4522. if (q_pos == std::string::npos) { q_pos = entry.find("; q="); }
  4523. if (q_pos != std::string::npos) {
  4524. // Extract media type (before q parameter)
  4525. accept_entry.media_type = trim_copy(entry.substr(0, q_pos));
  4526. // Extract quality value
  4527. auto q_start = entry.find('=', q_pos) + 1;
  4528. auto q_end = entry.find(';', q_start);
  4529. if (q_end == std::string::npos) { q_end = entry.length(); }
  4530. std::string quality_str =
  4531. trim_copy(entry.substr(q_start, q_end - q_start));
  4532. if (quality_str.empty()) {
  4533. has_invalid_entry = true;
  4534. return;
  4535. }
  4536. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  4537. {
  4538. std::istringstream iss(quality_str);
  4539. iss >> accept_entry.quality;
  4540. // Check if conversion was successful and entire string was consumed
  4541. if (iss.fail() || !iss.eof()) {
  4542. has_invalid_entry = true;
  4543. return;
  4544. }
  4545. }
  4546. #else
  4547. try {
  4548. accept_entry.quality = std::stod(quality_str);
  4549. } catch (...) {
  4550. has_invalid_entry = true;
  4551. return;
  4552. }
  4553. #endif
  4554. // Check if quality is in valid range [0.0, 1.0]
  4555. if (accept_entry.quality < 0.0 || accept_entry.quality > 1.0) {
  4556. has_invalid_entry = true;
  4557. return;
  4558. }
  4559. } else {
  4560. // No quality parameter, use entire entry as media type
  4561. accept_entry.media_type = entry;
  4562. }
  4563. // Remove additional parameters from media type
  4564. auto param_pos = accept_entry.media_type.find(';');
  4565. if (param_pos != std::string::npos) {
  4566. accept_entry.media_type =
  4567. trim_copy(accept_entry.media_type.substr(0, param_pos));
  4568. }
  4569. // Basic validation of media type format
  4570. if (accept_entry.media_type.empty()) {
  4571. has_invalid_entry = true;
  4572. return;
  4573. }
  4574. // Check for basic media type format (should contain '/' or be '*')
  4575. if (accept_entry.media_type != "*" &&
  4576. accept_entry.media_type.find('/') == std::string::npos) {
  4577. has_invalid_entry = true;
  4578. return;
  4579. }
  4580. entries.push_back(accept_entry);
  4581. });
  4582. // Return false if any invalid entry was found
  4583. if (has_invalid_entry) { return false; }
  4584. // Sort by quality (descending), then by original order (ascending)
  4585. std::sort(entries.begin(), entries.end(),
  4586. [](const AcceptEntry &a, const AcceptEntry &b) {
  4587. if (a.quality != b.quality) {
  4588. return a.quality > b.quality; // Higher quality first
  4589. }
  4590. return a.order < b.order; // Earlier order first for same quality
  4591. });
  4592. // Extract sorted media types
  4593. content_types.reserve(entries.size());
  4594. for (const auto &entry : entries) {
  4595. content_types.push_back(entry.media_type);
  4596. }
  4597. return true;
  4598. }
  4599. class FormDataParser {
  4600. public:
  4601. FormDataParser() = default;
  4602. void set_boundary(std::string &&boundary) {
  4603. boundary_ = boundary;
  4604. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  4605. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  4606. }
  4607. bool is_valid() const { return is_valid_; }
  4608. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  4609. const ContentReceiver &content_callback) {
  4610. buf_append(buf, n);
  4611. while (buf_size() > 0) {
  4612. switch (state_) {
  4613. case 0: { // Initial boundary
  4614. auto pos = buf_find(dash_boundary_crlf_);
  4615. if (pos == buf_size()) { return true; }
  4616. buf_erase(pos + dash_boundary_crlf_.size());
  4617. state_ = 1;
  4618. break;
  4619. }
  4620. case 1: { // New entry
  4621. clear_file_info();
  4622. state_ = 2;
  4623. break;
  4624. }
  4625. case 2: { // Headers
  4626. auto pos = buf_find(crlf_);
  4627. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4628. while (pos < buf_size()) {
  4629. // Empty line
  4630. if (pos == 0) {
  4631. if (!header_callback(file_)) {
  4632. is_valid_ = false;
  4633. return false;
  4634. }
  4635. buf_erase(crlf_.size());
  4636. state_ = 3;
  4637. break;
  4638. }
  4639. const auto header = buf_head(pos);
  4640. if (!parse_header(header.data(), header.data() + header.size(),
  4641. [&](const std::string &, const std::string &) {})) {
  4642. is_valid_ = false;
  4643. return false;
  4644. }
  4645. // Parse and emplace space trimmed headers into a map
  4646. if (!parse_header(
  4647. header.data(), header.data() + header.size(),
  4648. [&](const std::string &key, const std::string &val) {
  4649. file_.headers.emplace(key, val);
  4650. })) {
  4651. is_valid_ = false;
  4652. return false;
  4653. }
  4654. constexpr const char header_content_type[] = "Content-Type:";
  4655. if (start_with_case_ignore(header, header_content_type)) {
  4656. file_.content_type =
  4657. trim_copy(header.substr(str_len(header_content_type)));
  4658. } else {
  4659. thread_local const std::regex re_content_disposition(
  4660. R"~(^Content-Disposition:\s*form-data;\s*(.*)$)~",
  4661. std::regex_constants::icase);
  4662. std::smatch m;
  4663. if (std::regex_match(header, m, re_content_disposition)) {
  4664. Params params;
  4665. parse_disposition_params(m[1], params);
  4666. auto it = params.find("name");
  4667. if (it != params.end()) {
  4668. file_.name = it->second;
  4669. } else {
  4670. is_valid_ = false;
  4671. return false;
  4672. }
  4673. it = params.find("filename");
  4674. if (it != params.end()) { file_.filename = it->second; }
  4675. it = params.find("filename*");
  4676. if (it != params.end()) {
  4677. // Only allow UTF-8 encoding...
  4678. thread_local const std::regex re_rfc5987_encoding(
  4679. R"~(^UTF-8''(.+?)$)~", std::regex_constants::icase);
  4680. std::smatch m2;
  4681. if (std::regex_match(it->second, m2, re_rfc5987_encoding)) {
  4682. file_.filename = decode_path_component(m2[1]); // override...
  4683. } else {
  4684. is_valid_ = false;
  4685. return false;
  4686. }
  4687. }
  4688. }
  4689. }
  4690. buf_erase(pos + crlf_.size());
  4691. pos = buf_find(crlf_);
  4692. }
  4693. if (state_ != 3) { return true; }
  4694. break;
  4695. }
  4696. case 3: { // Body
  4697. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  4698. auto pos = buf_find(crlf_dash_boundary_);
  4699. if (pos < buf_size()) {
  4700. if (!content_callback(buf_data(), pos)) {
  4701. is_valid_ = false;
  4702. return false;
  4703. }
  4704. buf_erase(pos + crlf_dash_boundary_.size());
  4705. state_ = 4;
  4706. } else {
  4707. auto len = buf_size() - crlf_dash_boundary_.size();
  4708. if (len > 0) {
  4709. if (!content_callback(buf_data(), len)) {
  4710. is_valid_ = false;
  4711. return false;
  4712. }
  4713. buf_erase(len);
  4714. }
  4715. return true;
  4716. }
  4717. break;
  4718. }
  4719. case 4: { // Boundary
  4720. if (crlf_.size() > buf_size()) { return true; }
  4721. if (buf_start_with(crlf_)) {
  4722. buf_erase(crlf_.size());
  4723. state_ = 1;
  4724. } else {
  4725. if (dash_.size() > buf_size()) { return true; }
  4726. if (buf_start_with(dash_)) {
  4727. buf_erase(dash_.size());
  4728. is_valid_ = true;
  4729. buf_erase(buf_size()); // Remove epilogue
  4730. } else {
  4731. return true;
  4732. }
  4733. }
  4734. break;
  4735. }
  4736. }
  4737. }
  4738. return true;
  4739. }
  4740. private:
  4741. void clear_file_info() {
  4742. file_.name.clear();
  4743. file_.filename.clear();
  4744. file_.content_type.clear();
  4745. file_.headers.clear();
  4746. }
  4747. bool start_with_case_ignore(const std::string &a, const char *b) const {
  4748. const auto b_len = strlen(b);
  4749. if (a.size() < b_len) { return false; }
  4750. for (size_t i = 0; i < b_len; i++) {
  4751. if (case_ignore::to_lower(a[i]) != case_ignore::to_lower(b[i])) {
  4752. return false;
  4753. }
  4754. }
  4755. return true;
  4756. }
  4757. const std::string dash_ = "--";
  4758. const std::string crlf_ = "\r\n";
  4759. std::string boundary_;
  4760. std::string dash_boundary_crlf_;
  4761. std::string crlf_dash_boundary_;
  4762. size_t state_ = 0;
  4763. bool is_valid_ = false;
  4764. FormData file_;
  4765. // Buffer
  4766. bool start_with(const std::string &a, size_t spos, size_t epos,
  4767. const std::string &b) const {
  4768. if (epos - spos < b.size()) { return false; }
  4769. for (size_t i = 0; i < b.size(); i++) {
  4770. if (a[i + spos] != b[i]) { return false; }
  4771. }
  4772. return true;
  4773. }
  4774. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  4775. const char *buf_data() const { return &buf_[buf_spos_]; }
  4776. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  4777. bool buf_start_with(const std::string &s) const {
  4778. return start_with(buf_, buf_spos_, buf_epos_, s);
  4779. }
  4780. size_t buf_find(const std::string &s) const {
  4781. auto c = s.front();
  4782. size_t off = buf_spos_;
  4783. while (off < buf_epos_) {
  4784. auto pos = off;
  4785. while (true) {
  4786. if (pos == buf_epos_) { return buf_size(); }
  4787. if (buf_[pos] == c) { break; }
  4788. pos++;
  4789. }
  4790. auto remaining_size = buf_epos_ - pos;
  4791. if (s.size() > remaining_size) { return buf_size(); }
  4792. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  4793. off = pos + 1;
  4794. }
  4795. return buf_size();
  4796. }
  4797. void buf_append(const char *data, size_t n) {
  4798. auto remaining_size = buf_size();
  4799. if (remaining_size > 0 && buf_spos_ > 0) {
  4800. for (size_t i = 0; i < remaining_size; i++) {
  4801. buf_[i] = buf_[buf_spos_ + i];
  4802. }
  4803. }
  4804. buf_spos_ = 0;
  4805. buf_epos_ = remaining_size;
  4806. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  4807. for (size_t i = 0; i < n; i++) {
  4808. buf_[buf_epos_ + i] = data[i];
  4809. }
  4810. buf_epos_ += n;
  4811. }
  4812. void buf_erase(size_t size) { buf_spos_ += size; }
  4813. std::string buf_;
  4814. size_t buf_spos_ = 0;
  4815. size_t buf_epos_ = 0;
  4816. };
  4817. inline std::string random_string(size_t length) {
  4818. constexpr const char data[] =
  4819. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  4820. thread_local auto engine([]() {
  4821. // std::random_device might actually be deterministic on some
  4822. // platforms, but due to lack of support in the c++ standard library,
  4823. // doing better requires either some ugly hacks or breaking portability.
  4824. std::random_device seed_gen;
  4825. // Request 128 bits of entropy for initialization
  4826. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  4827. return std::mt19937(seed_sequence);
  4828. }());
  4829. std::string result;
  4830. for (size_t i = 0; i < length; i++) {
  4831. result += data[engine() % (sizeof(data) - 1)];
  4832. }
  4833. return result;
  4834. }
  4835. inline std::string make_multipart_data_boundary() {
  4836. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  4837. }
  4838. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  4839. auto valid = true;
  4840. for (size_t i = 0; i < boundary.size(); i++) {
  4841. auto c = boundary[i];
  4842. if (!std::isalnum(c) && c != '-' && c != '_') {
  4843. valid = false;
  4844. break;
  4845. }
  4846. }
  4847. return valid;
  4848. }
  4849. template <typename T>
  4850. inline std::string
  4851. serialize_multipart_formdata_item_begin(const T &item,
  4852. const std::string &boundary) {
  4853. std::string body = "--" + boundary + "\r\n";
  4854. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4855. if (!item.filename.empty()) {
  4856. body += "; filename=\"" + item.filename + "\"";
  4857. }
  4858. body += "\r\n";
  4859. if (!item.content_type.empty()) {
  4860. body += "Content-Type: " + item.content_type + "\r\n";
  4861. }
  4862. body += "\r\n";
  4863. return body;
  4864. }
  4865. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  4866. inline std::string
  4867. serialize_multipart_formdata_finish(const std::string &boundary) {
  4868. return "--" + boundary + "--\r\n";
  4869. }
  4870. inline std::string
  4871. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  4872. return "multipart/form-data; boundary=" + boundary;
  4873. }
  4874. inline std::string
  4875. serialize_multipart_formdata(const UploadFormDataItems &items,
  4876. const std::string &boundary, bool finish = true) {
  4877. std::string body;
  4878. for (const auto &item : items) {
  4879. body += serialize_multipart_formdata_item_begin(item, boundary);
  4880. body += item.content + serialize_multipart_formdata_item_end();
  4881. }
  4882. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  4883. return body;
  4884. }
  4885. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  4886. if (ranges.size() <= 1) return;
  4887. // Sort ranges by start position
  4888. std::sort(ranges.begin(), ranges.end(),
  4889. [](const Range &a, const Range &b) { return a.first < b.first; });
  4890. Ranges coalesced;
  4891. coalesced.reserve(ranges.size());
  4892. for (auto &r : ranges) {
  4893. auto first_pos = r.first;
  4894. auto last_pos = r.second;
  4895. // Handle special cases like in range_error
  4896. if (first_pos == -1 && last_pos == -1) {
  4897. first_pos = 0;
  4898. last_pos = static_cast<ssize_t>(content_length);
  4899. }
  4900. if (first_pos == -1) {
  4901. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  4902. last_pos = static_cast<ssize_t>(content_length) - 1;
  4903. }
  4904. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  4905. last_pos = static_cast<ssize_t>(content_length) - 1;
  4906. }
  4907. // Skip invalid ranges
  4908. if (!(0 <= first_pos && first_pos <= last_pos &&
  4909. last_pos < static_cast<ssize_t>(content_length))) {
  4910. continue;
  4911. }
  4912. // Coalesce with previous range if overlapping or adjacent (but not
  4913. // identical)
  4914. if (!coalesced.empty()) {
  4915. auto &prev = coalesced.back();
  4916. // Check if current range overlaps or is adjacent to previous range
  4917. // but don't coalesce identical ranges (allow duplicates)
  4918. if (first_pos <= prev.second + 1 &&
  4919. !(first_pos == prev.first && last_pos == prev.second)) {
  4920. // Extend the previous range
  4921. prev.second = (std::max)(prev.second, last_pos);
  4922. continue;
  4923. }
  4924. }
  4925. // Add new range
  4926. coalesced.emplace_back(first_pos, last_pos);
  4927. }
  4928. ranges = std::move(coalesced);
  4929. }
  4930. inline bool range_error(Request &req, Response &res) {
  4931. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  4932. ssize_t content_len = static_cast<ssize_t>(
  4933. res.content_length_ ? res.content_length_ : res.body.size());
  4934. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  4935. size_t overwrapping_count = 0;
  4936. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  4937. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  4938. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  4939. // Too many ranges
  4940. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  4941. for (auto &r : req.ranges) {
  4942. auto &first_pos = r.first;
  4943. auto &last_pos = r.second;
  4944. if (first_pos == -1 && last_pos == -1) {
  4945. first_pos = 0;
  4946. last_pos = content_len;
  4947. }
  4948. if (first_pos == -1) {
  4949. first_pos = content_len - last_pos;
  4950. last_pos = content_len - 1;
  4951. }
  4952. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  4953. // A client can limit the number of bytes requested without knowing the
  4954. // size of the selected representation. If the last-pos value is absent,
  4955. // or if the value is greater than or equal to the current length of the
  4956. // representation data, the byte range is interpreted as the remainder of
  4957. // the representation (i.e., the server replaces the value of last-pos
  4958. // with a value that is one less than the current length of the selected
  4959. // representation).
  4960. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  4961. if (last_pos == -1 || last_pos >= content_len) {
  4962. last_pos = content_len - 1;
  4963. }
  4964. // Range must be within content length
  4965. if (!(0 <= first_pos && first_pos <= last_pos &&
  4966. last_pos <= content_len - 1)) {
  4967. return true;
  4968. }
  4969. // Request must not have more than two overlapping ranges
  4970. for (const auto &processed_range : processed_ranges) {
  4971. if (!(last_pos < processed_range.first ||
  4972. first_pos > processed_range.second)) {
  4973. overwrapping_count++;
  4974. if (overwrapping_count > 2) { return true; }
  4975. break; // Only count once per range
  4976. }
  4977. }
  4978. processed_ranges.emplace_back(first_pos, last_pos);
  4979. }
  4980. // After validation, coalesce overlapping ranges as per RFC 9110
  4981. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  4982. }
  4983. return false;
  4984. }
  4985. inline std::pair<size_t, size_t>
  4986. get_range_offset_and_length(Range r, size_t content_length) {
  4987. assert(r.first != -1 && r.second != -1);
  4988. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  4989. assert(r.first <= r.second &&
  4990. r.second < static_cast<ssize_t>(content_length));
  4991. (void)(content_length);
  4992. return std::make_pair(r.first, static_cast<size_t>(r.second - r.first) + 1);
  4993. }
  4994. inline std::string make_content_range_header_field(
  4995. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  4996. auto st = offset_and_length.first;
  4997. auto ed = st + offset_and_length.second - 1;
  4998. std::string field = "bytes ";
  4999. field += std::to_string(st);
  5000. field += "-";
  5001. field += std::to_string(ed);
  5002. field += "/";
  5003. field += std::to_string(content_length);
  5004. return field;
  5005. }
  5006. template <typename SToken, typename CToken, typename Content>
  5007. bool process_multipart_ranges_data(const Request &req,
  5008. const std::string &boundary,
  5009. const std::string &content_type,
  5010. size_t content_length, SToken stoken,
  5011. CToken ctoken, Content content) {
  5012. for (size_t i = 0; i < req.ranges.size(); i++) {
  5013. ctoken("--");
  5014. stoken(boundary);
  5015. ctoken("\r\n");
  5016. if (!content_type.empty()) {
  5017. ctoken("Content-Type: ");
  5018. stoken(content_type);
  5019. ctoken("\r\n");
  5020. }
  5021. auto offset_and_length =
  5022. get_range_offset_and_length(req.ranges[i], content_length);
  5023. ctoken("Content-Range: ");
  5024. stoken(make_content_range_header_field(offset_and_length, content_length));
  5025. ctoken("\r\n");
  5026. ctoken("\r\n");
  5027. if (!content(offset_and_length.first, offset_and_length.second)) {
  5028. return false;
  5029. }
  5030. ctoken("\r\n");
  5031. }
  5032. ctoken("--");
  5033. stoken(boundary);
  5034. ctoken("--");
  5035. return true;
  5036. }
  5037. inline void make_multipart_ranges_data(const Request &req, Response &res,
  5038. const std::string &boundary,
  5039. const std::string &content_type,
  5040. size_t content_length,
  5041. std::string &data) {
  5042. process_multipart_ranges_data(
  5043. req, boundary, content_type, content_length,
  5044. [&](const std::string &token) { data += token; },
  5045. [&](const std::string &token) { data += token; },
  5046. [&](size_t offset, size_t length) {
  5047. assert(offset + length <= content_length);
  5048. data += res.body.substr(offset, length);
  5049. return true;
  5050. });
  5051. }
  5052. inline size_t get_multipart_ranges_data_length(const Request &req,
  5053. const std::string &boundary,
  5054. const std::string &content_type,
  5055. size_t content_length) {
  5056. size_t data_length = 0;
  5057. process_multipart_ranges_data(
  5058. req, boundary, content_type, content_length,
  5059. [&](const std::string &token) { data_length += token.size(); },
  5060. [&](const std::string &token) { data_length += token.size(); },
  5061. [&](size_t /*offset*/, size_t length) {
  5062. data_length += length;
  5063. return true;
  5064. });
  5065. return data_length;
  5066. }
  5067. template <typename T>
  5068. inline bool
  5069. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  5070. const std::string &boundary,
  5071. const std::string &content_type,
  5072. size_t content_length, const T &is_shutting_down) {
  5073. return process_multipart_ranges_data(
  5074. req, boundary, content_type, content_length,
  5075. [&](const std::string &token) { strm.write(token); },
  5076. [&](const std::string &token) { strm.write(token); },
  5077. [&](size_t offset, size_t length) {
  5078. return write_content(strm, res.content_provider_, offset, length,
  5079. is_shutting_down);
  5080. });
  5081. }
  5082. inline bool expect_content(const Request &req) {
  5083. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  5084. req.method == "DELETE") {
  5085. return true;
  5086. }
  5087. if (req.has_header("Content-Length") &&
  5088. req.get_header_value_u64("Content-Length") > 0) {
  5089. return true;
  5090. }
  5091. if (is_chunked_transfer_encoding(req.headers)) { return true; }
  5092. return false;
  5093. }
  5094. inline bool has_crlf(const std::string &s) {
  5095. auto p = s.c_str();
  5096. while (*p) {
  5097. if (*p == '\r' || *p == '\n') { return true; }
  5098. p++;
  5099. }
  5100. return false;
  5101. }
  5102. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5103. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  5104. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  5105. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  5106. unsigned int hash_length = 0;
  5107. unsigned char hash[EVP_MAX_MD_SIZE];
  5108. EVP_DigestInit_ex(context.get(), algo, nullptr);
  5109. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  5110. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  5111. std::stringstream ss;
  5112. for (auto i = 0u; i < hash_length; ++i) {
  5113. ss << std::hex << std::setw(2) << std::setfill('0')
  5114. << static_cast<unsigned int>(hash[i]);
  5115. }
  5116. return ss.str();
  5117. }
  5118. inline std::string MD5(const std::string &s) {
  5119. return message_digest(s, EVP_md5());
  5120. }
  5121. inline std::string SHA_256(const std::string &s) {
  5122. return message_digest(s, EVP_sha256());
  5123. }
  5124. inline std::string SHA_512(const std::string &s) {
  5125. return message_digest(s, EVP_sha512());
  5126. }
  5127. inline std::pair<std::string, std::string> make_digest_authentication_header(
  5128. const Request &req, const std::map<std::string, std::string> &auth,
  5129. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  5130. const std::string &password, bool is_proxy = false) {
  5131. std::string nc;
  5132. {
  5133. std::stringstream ss;
  5134. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  5135. nc = ss.str();
  5136. }
  5137. std::string qop;
  5138. if (auth.find("qop") != auth.end()) {
  5139. qop = auth.at("qop");
  5140. if (qop.find("auth-int") != std::string::npos) {
  5141. qop = "auth-int";
  5142. } else if (qop.find("auth") != std::string::npos) {
  5143. qop = "auth";
  5144. } else {
  5145. qop.clear();
  5146. }
  5147. }
  5148. std::string algo = "MD5";
  5149. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  5150. std::string response;
  5151. {
  5152. auto H = algo == "SHA-256" ? detail::SHA_256
  5153. : algo == "SHA-512" ? detail::SHA_512
  5154. : detail::MD5;
  5155. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  5156. auto A2 = req.method + ":" + req.path;
  5157. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  5158. if (qop.empty()) {
  5159. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  5160. } else {
  5161. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  5162. ":" + qop + ":" + H(A2));
  5163. }
  5164. }
  5165. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  5166. auto field = "Digest username=\"" + username + "\", realm=\"" +
  5167. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  5168. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  5169. (qop.empty() ? ", response=\""
  5170. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  5171. cnonce + "\", response=\"") +
  5172. response + "\"" +
  5173. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  5174. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  5175. return std::make_pair(key, field);
  5176. }
  5177. inline bool is_ssl_peer_could_be_closed(SSL *ssl, socket_t sock) {
  5178. detail::set_nonblocking(sock, true);
  5179. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  5180. char buf[1];
  5181. return !SSL_peek(ssl, buf, 1) &&
  5182. SSL_get_error(ssl, 0) == SSL_ERROR_ZERO_RETURN;
  5183. }
  5184. #ifdef _WIN32
  5185. // NOTE: This code came up with the following stackoverflow post:
  5186. // https://stackoverflow.com/questions/9507184/can-openssl-on-windows-use-the-system-certificate-store
  5187. inline bool load_system_certs_on_windows(X509_STORE *store) {
  5188. auto hStore = CertOpenSystemStoreW((HCRYPTPROV_LEGACY)NULL, L"ROOT");
  5189. if (!hStore) { return false; }
  5190. auto result = false;
  5191. PCCERT_CONTEXT pContext = NULL;
  5192. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  5193. nullptr) {
  5194. auto encoded_cert =
  5195. static_cast<const unsigned char *>(pContext->pbCertEncoded);
  5196. auto x509 = d2i_X509(NULL, &encoded_cert, pContext->cbCertEncoded);
  5197. if (x509) {
  5198. X509_STORE_add_cert(store, x509);
  5199. X509_free(x509);
  5200. result = true;
  5201. }
  5202. }
  5203. CertFreeCertificateContext(pContext);
  5204. CertCloseStore(hStore, 0);
  5205. return result;
  5206. }
  5207. #elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && TARGET_OS_MAC
  5208. template <typename T>
  5209. using CFObjectPtr =
  5210. std::unique_ptr<typename std::remove_pointer<T>::type, void (*)(CFTypeRef)>;
  5211. inline void cf_object_ptr_deleter(CFTypeRef obj) {
  5212. if (obj) { CFRelease(obj); }
  5213. }
  5214. inline bool retrieve_certs_from_keychain(CFObjectPtr<CFArrayRef> &certs) {
  5215. CFStringRef keys[] = {kSecClass, kSecMatchLimit, kSecReturnRef};
  5216. CFTypeRef values[] = {kSecClassCertificate, kSecMatchLimitAll,
  5217. kCFBooleanTrue};
  5218. CFObjectPtr<CFDictionaryRef> query(
  5219. CFDictionaryCreate(nullptr, reinterpret_cast<const void **>(keys), values,
  5220. sizeof(keys) / sizeof(keys[0]),
  5221. &kCFTypeDictionaryKeyCallBacks,
  5222. &kCFTypeDictionaryValueCallBacks),
  5223. cf_object_ptr_deleter);
  5224. if (!query) { return false; }
  5225. CFTypeRef security_items = nullptr;
  5226. if (SecItemCopyMatching(query.get(), &security_items) != errSecSuccess ||
  5227. CFArrayGetTypeID() != CFGetTypeID(security_items)) {
  5228. return false;
  5229. }
  5230. certs.reset(reinterpret_cast<CFArrayRef>(security_items));
  5231. return true;
  5232. }
  5233. inline bool retrieve_root_certs_from_keychain(CFObjectPtr<CFArrayRef> &certs) {
  5234. CFArrayRef root_security_items = nullptr;
  5235. if (SecTrustCopyAnchorCertificates(&root_security_items) != errSecSuccess) {
  5236. return false;
  5237. }
  5238. certs.reset(root_security_items);
  5239. return true;
  5240. }
  5241. inline bool add_certs_to_x509_store(CFArrayRef certs, X509_STORE *store) {
  5242. auto result = false;
  5243. for (auto i = 0; i < CFArrayGetCount(certs); ++i) {
  5244. const auto cert = reinterpret_cast<const __SecCertificate *>(
  5245. CFArrayGetValueAtIndex(certs, i));
  5246. if (SecCertificateGetTypeID() != CFGetTypeID(cert)) { continue; }
  5247. CFDataRef cert_data = nullptr;
  5248. if (SecItemExport(cert, kSecFormatX509Cert, 0, nullptr, &cert_data) !=
  5249. errSecSuccess) {
  5250. continue;
  5251. }
  5252. CFObjectPtr<CFDataRef> cert_data_ptr(cert_data, cf_object_ptr_deleter);
  5253. auto encoded_cert = static_cast<const unsigned char *>(
  5254. CFDataGetBytePtr(cert_data_ptr.get()));
  5255. auto x509 =
  5256. d2i_X509(NULL, &encoded_cert, CFDataGetLength(cert_data_ptr.get()));
  5257. if (x509) {
  5258. X509_STORE_add_cert(store, x509);
  5259. X509_free(x509);
  5260. result = true;
  5261. }
  5262. }
  5263. return result;
  5264. }
  5265. inline bool load_system_certs_on_macos(X509_STORE *store) {
  5266. auto result = false;
  5267. CFObjectPtr<CFArrayRef> certs(nullptr, cf_object_ptr_deleter);
  5268. if (retrieve_certs_from_keychain(certs) && certs) {
  5269. result = add_certs_to_x509_store(certs.get(), store);
  5270. }
  5271. if (retrieve_root_certs_from_keychain(certs) && certs) {
  5272. result = add_certs_to_x509_store(certs.get(), store) || result;
  5273. }
  5274. return result;
  5275. }
  5276. #endif // _WIN32
  5277. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  5278. #ifdef _WIN32
  5279. class WSInit {
  5280. public:
  5281. WSInit() {
  5282. WSADATA wsaData;
  5283. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  5284. }
  5285. ~WSInit() {
  5286. if (is_valid_) WSACleanup();
  5287. }
  5288. bool is_valid_ = false;
  5289. };
  5290. static WSInit wsinit_;
  5291. #endif
  5292. inline bool parse_www_authenticate(const Response &res,
  5293. std::map<std::string, std::string> &auth,
  5294. bool is_proxy) {
  5295. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  5296. if (res.has_header(auth_key)) {
  5297. thread_local auto re =
  5298. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  5299. auto s = res.get_header_value(auth_key);
  5300. auto pos = s.find(' ');
  5301. if (pos != std::string::npos) {
  5302. auto type = s.substr(0, pos);
  5303. if (type == "Basic") {
  5304. return false;
  5305. } else if (type == "Digest") {
  5306. s = s.substr(pos + 1);
  5307. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  5308. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  5309. const auto &m = *i;
  5310. auto key = s.substr(static_cast<size_t>(m.position(1)),
  5311. static_cast<size_t>(m.length(1)));
  5312. auto val = m.length(2) > 0
  5313. ? s.substr(static_cast<size_t>(m.position(2)),
  5314. static_cast<size_t>(m.length(2)))
  5315. : s.substr(static_cast<size_t>(m.position(3)),
  5316. static_cast<size_t>(m.length(3)));
  5317. auth[key] = val;
  5318. }
  5319. return true;
  5320. }
  5321. }
  5322. }
  5323. return false;
  5324. }
  5325. class ContentProviderAdapter {
  5326. public:
  5327. explicit ContentProviderAdapter(
  5328. ContentProviderWithoutLength &&content_provider)
  5329. : content_provider_(content_provider) {}
  5330. bool operator()(size_t offset, size_t, DataSink &sink) {
  5331. return content_provider_(offset, sink);
  5332. }
  5333. private:
  5334. ContentProviderWithoutLength content_provider_;
  5335. };
  5336. } // namespace detail
  5337. inline std::string hosted_at(const std::string &hostname) {
  5338. std::vector<std::string> addrs;
  5339. hosted_at(hostname, addrs);
  5340. if (addrs.empty()) { return std::string(); }
  5341. return addrs[0];
  5342. }
  5343. inline void hosted_at(const std::string &hostname,
  5344. std::vector<std::string> &addrs) {
  5345. struct addrinfo hints;
  5346. struct addrinfo *result;
  5347. memset(&hints, 0, sizeof(struct addrinfo));
  5348. hints.ai_family = AF_UNSPEC;
  5349. hints.ai_socktype = SOCK_STREAM;
  5350. hints.ai_protocol = 0;
  5351. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  5352. &result, 0)) {
  5353. #if defined __linux__ && !defined __ANDROID__
  5354. res_init();
  5355. #endif
  5356. return;
  5357. }
  5358. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5359. for (auto rp = result; rp; rp = rp->ai_next) {
  5360. const auto &addr =
  5361. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  5362. std::string ip;
  5363. auto dummy = -1;
  5364. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  5365. dummy)) {
  5366. addrs.push_back(ip);
  5367. }
  5368. }
  5369. }
  5370. inline std::string encode_uri_component(const std::string &value) {
  5371. std::ostringstream escaped;
  5372. escaped.fill('0');
  5373. escaped << std::hex;
  5374. for (auto c : value) {
  5375. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  5376. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  5377. c == ')') {
  5378. escaped << c;
  5379. } else {
  5380. escaped << std::uppercase;
  5381. escaped << '%' << std::setw(2)
  5382. << static_cast<int>(static_cast<unsigned char>(c));
  5383. escaped << std::nouppercase;
  5384. }
  5385. }
  5386. return escaped.str();
  5387. }
  5388. inline std::string encode_uri(const std::string &value) {
  5389. std::ostringstream escaped;
  5390. escaped.fill('0');
  5391. escaped << std::hex;
  5392. for (auto c : value) {
  5393. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  5394. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  5395. c == ')' || c == ';' || c == '/' || c == '?' || c == ':' || c == '@' ||
  5396. c == '&' || c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  5397. escaped << c;
  5398. } else {
  5399. escaped << std::uppercase;
  5400. escaped << '%' << std::setw(2)
  5401. << static_cast<int>(static_cast<unsigned char>(c));
  5402. escaped << std::nouppercase;
  5403. }
  5404. }
  5405. return escaped.str();
  5406. }
  5407. inline std::string decode_uri_component(const std::string &value) {
  5408. std::string result;
  5409. for (size_t i = 0; i < value.size(); i++) {
  5410. if (value[i] == '%' && i + 2 < value.size()) {
  5411. auto val = 0;
  5412. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  5413. result += static_cast<char>(val);
  5414. i += 2;
  5415. } else {
  5416. result += value[i];
  5417. }
  5418. } else {
  5419. result += value[i];
  5420. }
  5421. }
  5422. return result;
  5423. }
  5424. inline std::string decode_uri(const std::string &value) {
  5425. std::string result;
  5426. for (size_t i = 0; i < value.size(); i++) {
  5427. if (value[i] == '%' && i + 2 < value.size()) {
  5428. auto val = 0;
  5429. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  5430. result += static_cast<char>(val);
  5431. i += 2;
  5432. } else {
  5433. result += value[i];
  5434. }
  5435. } else {
  5436. result += value[i];
  5437. }
  5438. }
  5439. return result;
  5440. }
  5441. inline std::string encode_path_component(const std::string &component) {
  5442. std::string result;
  5443. result.reserve(component.size() * 3);
  5444. for (size_t i = 0; i < component.size(); i++) {
  5445. auto c = static_cast<unsigned char>(component[i]);
  5446. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  5447. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  5448. result += static_cast<char>(c);
  5449. }
  5450. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  5451. // "," / ";" / "="
  5452. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  5453. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  5454. c == '=') {
  5455. result += static_cast<char>(c);
  5456. }
  5457. // Colon is allowed in path segments except first segment
  5458. else if (c == ':') {
  5459. result += static_cast<char>(c);
  5460. }
  5461. // @ is allowed in path
  5462. else if (c == '@') {
  5463. result += static_cast<char>(c);
  5464. } else {
  5465. result += '%';
  5466. char hex[3];
  5467. snprintf(hex, sizeof(hex), "%02X", c);
  5468. result.append(hex, 2);
  5469. }
  5470. }
  5471. return result;
  5472. }
  5473. inline std::string decode_path_component(const std::string &component) {
  5474. std::string result;
  5475. result.reserve(component.size());
  5476. for (size_t i = 0; i < component.size(); i++) {
  5477. if (component[i] == '%' && i + 1 < component.size()) {
  5478. if (component[i + 1] == 'u') {
  5479. // Unicode %uXXXX encoding
  5480. auto val = 0;
  5481. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  5482. // 4 digits Unicode codes
  5483. char buff[4];
  5484. size_t len = detail::to_utf8(val, buff);
  5485. if (len > 0) { result.append(buff, len); }
  5486. i += 5; // 'u0000'
  5487. } else {
  5488. result += component[i];
  5489. }
  5490. } else {
  5491. // Standard %XX encoding
  5492. auto val = 0;
  5493. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  5494. // 2 digits hex codes
  5495. result += static_cast<char>(val);
  5496. i += 2; // 'XX'
  5497. } else {
  5498. result += component[i];
  5499. }
  5500. }
  5501. } else {
  5502. result += component[i];
  5503. }
  5504. }
  5505. return result;
  5506. }
  5507. inline std::string encode_query_component(const std::string &component,
  5508. bool space_as_plus) {
  5509. std::string result;
  5510. result.reserve(component.size() * 3);
  5511. for (size_t i = 0; i < component.size(); i++) {
  5512. auto c = static_cast<unsigned char>(component[i]);
  5513. // Unreserved characters per RFC 3986
  5514. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  5515. result += static_cast<char>(c);
  5516. }
  5517. // Space handling
  5518. else if (c == ' ') {
  5519. if (space_as_plus) {
  5520. result += '+';
  5521. } else {
  5522. result += "%20";
  5523. }
  5524. }
  5525. // Plus sign handling
  5526. else if (c == '+') {
  5527. if (space_as_plus) {
  5528. result += "%2B";
  5529. } else {
  5530. result += static_cast<char>(c);
  5531. }
  5532. }
  5533. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  5534. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  5535. c == '*' || c == ',' || c == ';') {
  5536. result += static_cast<char>(c);
  5537. }
  5538. // Colon and @ are allowed in query
  5539. else if (c == ':' || c == '@') {
  5540. result += static_cast<char>(c);
  5541. }
  5542. // Forward slash is allowed in query values
  5543. else if (c == '/') {
  5544. result += static_cast<char>(c);
  5545. }
  5546. // Question mark is allowed in query values (after first ?)
  5547. else if (c == '?') {
  5548. result += static_cast<char>(c);
  5549. } else {
  5550. result += '%';
  5551. char hex[3];
  5552. snprintf(hex, sizeof(hex), "%02X", c);
  5553. result.append(hex, 2);
  5554. }
  5555. }
  5556. return result;
  5557. }
  5558. inline std::string decode_query_component(const std::string &component,
  5559. bool plus_as_space) {
  5560. std::string result;
  5561. result.reserve(component.size());
  5562. for (size_t i = 0; i < component.size(); i++) {
  5563. if (component[i] == '%' && i + 2 < component.size()) {
  5564. std::string hex = component.substr(i + 1, 2);
  5565. char *end;
  5566. unsigned long value = std::strtoul(hex.c_str(), &end, 16);
  5567. if (end == hex.c_str() + 2) {
  5568. result += static_cast<char>(value);
  5569. i += 2;
  5570. } else {
  5571. result += component[i];
  5572. }
  5573. } else if (component[i] == '+' && plus_as_space) {
  5574. result += ' '; // + becomes space in form-urlencoded
  5575. } else {
  5576. result += component[i];
  5577. }
  5578. }
  5579. return result;
  5580. }
  5581. inline std::string append_query_params(const std::string &path,
  5582. const Params &params) {
  5583. std::string path_with_query = path;
  5584. thread_local const std::regex re("[^?]+\\?.*");
  5585. auto delm = std::regex_match(path, re) ? '&' : '?';
  5586. path_with_query += delm + detail::params_to_query_str(params);
  5587. return path_with_query;
  5588. }
  5589. // Header utilities
  5590. inline std::pair<std::string, std::string>
  5591. make_range_header(const Ranges &ranges) {
  5592. std::string field = "bytes=";
  5593. auto i = 0;
  5594. for (const auto &r : ranges) {
  5595. if (i != 0) { field += ", "; }
  5596. if (r.first != -1) { field += std::to_string(r.first); }
  5597. field += '-';
  5598. if (r.second != -1) { field += std::to_string(r.second); }
  5599. i++;
  5600. }
  5601. return std::make_pair("Range", std::move(field));
  5602. }
  5603. inline std::pair<std::string, std::string>
  5604. make_basic_authentication_header(const std::string &username,
  5605. const std::string &password, bool is_proxy) {
  5606. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  5607. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  5608. return std::make_pair(key, std::move(field));
  5609. }
  5610. inline std::pair<std::string, std::string>
  5611. make_bearer_token_authentication_header(const std::string &token,
  5612. bool is_proxy = false) {
  5613. auto field = "Bearer " + token;
  5614. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  5615. return std::make_pair(key, std::move(field));
  5616. }
  5617. // Request implementation
  5618. inline bool Request::has_header(const std::string &key) const {
  5619. return detail::has_header(headers, key);
  5620. }
  5621. inline std::string Request::get_header_value(const std::string &key,
  5622. const char *def, size_t id) const {
  5623. return detail::get_header_value(headers, key, def, id);
  5624. }
  5625. inline size_t Request::get_header_value_count(const std::string &key) const {
  5626. auto r = headers.equal_range(key);
  5627. return static_cast<size_t>(std::distance(r.first, r.second));
  5628. }
  5629. inline void Request::set_header(const std::string &key,
  5630. const std::string &val) {
  5631. if (detail::fields::is_field_name(key) &&
  5632. detail::fields::is_field_value(val)) {
  5633. headers.emplace(key, val);
  5634. }
  5635. }
  5636. inline bool Request::has_trailer(const std::string &key) const {
  5637. return trailers.find(key) != trailers.end();
  5638. }
  5639. inline std::string Request::get_trailer_value(const std::string &key,
  5640. size_t id) const {
  5641. auto rng = trailers.equal_range(key);
  5642. auto it = rng.first;
  5643. std::advance(it, static_cast<ssize_t>(id));
  5644. if (it != rng.second) { return it->second; }
  5645. return std::string();
  5646. }
  5647. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  5648. auto r = trailers.equal_range(key);
  5649. return static_cast<size_t>(std::distance(r.first, r.second));
  5650. }
  5651. inline bool Request::has_param(const std::string &key) const {
  5652. return params.find(key) != params.end();
  5653. }
  5654. inline std::string Request::get_param_value(const std::string &key,
  5655. size_t id) const {
  5656. auto rng = params.equal_range(key);
  5657. auto it = rng.first;
  5658. std::advance(it, static_cast<ssize_t>(id));
  5659. if (it != rng.second) { return it->second; }
  5660. return std::string();
  5661. }
  5662. inline size_t Request::get_param_value_count(const std::string &key) const {
  5663. auto r = params.equal_range(key);
  5664. return static_cast<size_t>(std::distance(r.first, r.second));
  5665. }
  5666. inline bool Request::is_multipart_form_data() const {
  5667. const auto &content_type = get_header_value("Content-Type");
  5668. return !content_type.rfind("multipart/form-data", 0);
  5669. }
  5670. // Multipart FormData implementation
  5671. inline std::string MultipartFormData::get_field(const std::string &key,
  5672. size_t id) const {
  5673. auto rng = fields.equal_range(key);
  5674. auto it = rng.first;
  5675. std::advance(it, static_cast<ssize_t>(id));
  5676. if (it != rng.second) { return it->second.content; }
  5677. return std::string();
  5678. }
  5679. inline std::vector<std::string>
  5680. MultipartFormData::get_fields(const std::string &key) const {
  5681. std::vector<std::string> values;
  5682. auto rng = fields.equal_range(key);
  5683. for (auto it = rng.first; it != rng.second; it++) {
  5684. values.push_back(it->second.content);
  5685. }
  5686. return values;
  5687. }
  5688. inline bool MultipartFormData::has_field(const std::string &key) const {
  5689. return fields.find(key) != fields.end();
  5690. }
  5691. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  5692. auto r = fields.equal_range(key);
  5693. return static_cast<size_t>(std::distance(r.first, r.second));
  5694. }
  5695. inline FormData MultipartFormData::get_file(const std::string &key,
  5696. size_t id) const {
  5697. auto rng = files.equal_range(key);
  5698. auto it = rng.first;
  5699. std::advance(it, static_cast<ssize_t>(id));
  5700. if (it != rng.second) { return it->second; }
  5701. return FormData();
  5702. }
  5703. inline std::vector<FormData>
  5704. MultipartFormData::get_files(const std::string &key) const {
  5705. std::vector<FormData> values;
  5706. auto rng = files.equal_range(key);
  5707. for (auto it = rng.first; it != rng.second; it++) {
  5708. values.push_back(it->second);
  5709. }
  5710. return values;
  5711. }
  5712. inline bool MultipartFormData::has_file(const std::string &key) const {
  5713. return files.find(key) != files.end();
  5714. }
  5715. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  5716. auto r = files.equal_range(key);
  5717. return static_cast<size_t>(std::distance(r.first, r.second));
  5718. }
  5719. // Response implementation
  5720. inline bool Response::has_header(const std::string &key) const {
  5721. return headers.find(key) != headers.end();
  5722. }
  5723. inline std::string Response::get_header_value(const std::string &key,
  5724. const char *def,
  5725. size_t id) const {
  5726. return detail::get_header_value(headers, key, def, id);
  5727. }
  5728. inline size_t Response::get_header_value_count(const std::string &key) const {
  5729. auto r = headers.equal_range(key);
  5730. return static_cast<size_t>(std::distance(r.first, r.second));
  5731. }
  5732. inline void Response::set_header(const std::string &key,
  5733. const std::string &val) {
  5734. if (detail::fields::is_field_name(key) &&
  5735. detail::fields::is_field_value(val)) {
  5736. headers.emplace(key, val);
  5737. }
  5738. }
  5739. inline bool Response::has_trailer(const std::string &key) const {
  5740. return trailers.find(key) != trailers.end();
  5741. }
  5742. inline std::string Response::get_trailer_value(const std::string &key,
  5743. size_t id) const {
  5744. auto rng = trailers.equal_range(key);
  5745. auto it = rng.first;
  5746. std::advance(it, static_cast<ssize_t>(id));
  5747. if (it != rng.second) { return it->second; }
  5748. return std::string();
  5749. }
  5750. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  5751. auto r = trailers.equal_range(key);
  5752. return static_cast<size_t>(std::distance(r.first, r.second));
  5753. }
  5754. inline void Response::set_redirect(const std::string &url, int stat) {
  5755. if (detail::fields::is_field_value(url)) {
  5756. set_header("Location", url);
  5757. if (300 <= stat && stat < 400) {
  5758. this->status = stat;
  5759. } else {
  5760. this->status = StatusCode::Found_302;
  5761. }
  5762. }
  5763. }
  5764. inline void Response::set_content(const char *s, size_t n,
  5765. const std::string &content_type) {
  5766. body.assign(s, n);
  5767. auto rng = headers.equal_range("Content-Type");
  5768. headers.erase(rng.first, rng.second);
  5769. set_header("Content-Type", content_type);
  5770. }
  5771. inline void Response::set_content(const std::string &s,
  5772. const std::string &content_type) {
  5773. set_content(s.data(), s.size(), content_type);
  5774. }
  5775. inline void Response::set_content(std::string &&s,
  5776. const std::string &content_type) {
  5777. body = std::move(s);
  5778. auto rng = headers.equal_range("Content-Type");
  5779. headers.erase(rng.first, rng.second);
  5780. set_header("Content-Type", content_type);
  5781. }
  5782. inline void Response::set_content_provider(
  5783. size_t in_length, const std::string &content_type, ContentProvider provider,
  5784. ContentProviderResourceReleaser resource_releaser) {
  5785. set_header("Content-Type", content_type);
  5786. content_length_ = in_length;
  5787. if (in_length > 0) { content_provider_ = std::move(provider); }
  5788. content_provider_resource_releaser_ = std::move(resource_releaser);
  5789. is_chunked_content_provider_ = false;
  5790. }
  5791. inline void Response::set_content_provider(
  5792. const std::string &content_type, ContentProviderWithoutLength provider,
  5793. ContentProviderResourceReleaser resource_releaser) {
  5794. set_header("Content-Type", content_type);
  5795. content_length_ = 0;
  5796. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  5797. content_provider_resource_releaser_ = std::move(resource_releaser);
  5798. is_chunked_content_provider_ = false;
  5799. }
  5800. inline void Response::set_chunked_content_provider(
  5801. const std::string &content_type, ContentProviderWithoutLength provider,
  5802. ContentProviderResourceReleaser resource_releaser) {
  5803. set_header("Content-Type", content_type);
  5804. content_length_ = 0;
  5805. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  5806. content_provider_resource_releaser_ = std::move(resource_releaser);
  5807. is_chunked_content_provider_ = true;
  5808. }
  5809. inline void Response::set_file_content(const std::string &path,
  5810. const std::string &content_type) {
  5811. file_content_path_ = path;
  5812. file_content_content_type_ = content_type;
  5813. }
  5814. inline void Response::set_file_content(const std::string &path) {
  5815. file_content_path_ = path;
  5816. }
  5817. // Result implementation
  5818. inline bool Result::has_request_header(const std::string &key) const {
  5819. return request_headers_.find(key) != request_headers_.end();
  5820. }
  5821. inline std::string Result::get_request_header_value(const std::string &key,
  5822. const char *def,
  5823. size_t id) const {
  5824. return detail::get_header_value(request_headers_, key, def, id);
  5825. }
  5826. inline size_t
  5827. Result::get_request_header_value_count(const std::string &key) const {
  5828. auto r = request_headers_.equal_range(key);
  5829. return static_cast<size_t>(std::distance(r.first, r.second));
  5830. }
  5831. // Stream implementation
  5832. inline ssize_t Stream::write(const char *ptr) {
  5833. return write(ptr, strlen(ptr));
  5834. }
  5835. inline ssize_t Stream::write(const std::string &s) {
  5836. return write(s.data(), s.size());
  5837. }
  5838. namespace detail {
  5839. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  5840. time_t timeout_sec, time_t timeout_usec,
  5841. time_t &actual_timeout_sec,
  5842. time_t &actual_timeout_usec) {
  5843. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  5844. auto actual_timeout_msec =
  5845. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  5846. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  5847. actual_timeout_sec = actual_timeout_msec / 1000;
  5848. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  5849. }
  5850. // Socket stream implementation
  5851. inline SocketStream::SocketStream(
  5852. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  5853. time_t write_timeout_sec, time_t write_timeout_usec,
  5854. time_t max_timeout_msec,
  5855. std::chrono::time_point<std::chrono::steady_clock> start_time)
  5856. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  5857. read_timeout_usec_(read_timeout_usec),
  5858. write_timeout_sec_(write_timeout_sec),
  5859. write_timeout_usec_(write_timeout_usec),
  5860. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  5861. read_buff_(read_buff_size_, 0) {}
  5862. inline SocketStream::~SocketStream() = default;
  5863. inline bool SocketStream::is_readable() const {
  5864. return read_buff_off_ < read_buff_content_size_;
  5865. }
  5866. inline bool SocketStream::wait_readable() const {
  5867. if (max_timeout_msec_ <= 0) {
  5868. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  5869. }
  5870. time_t read_timeout_sec;
  5871. time_t read_timeout_usec;
  5872. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  5873. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  5874. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  5875. }
  5876. inline bool SocketStream::wait_writable() const {
  5877. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  5878. is_socket_alive(sock_);
  5879. }
  5880. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  5881. #ifdef _WIN32
  5882. size =
  5883. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  5884. #else
  5885. size = (std::min)(size,
  5886. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  5887. #endif
  5888. if (read_buff_off_ < read_buff_content_size_) {
  5889. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  5890. if (size <= remaining_size) {
  5891. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  5892. read_buff_off_ += size;
  5893. return static_cast<ssize_t>(size);
  5894. } else {
  5895. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  5896. read_buff_off_ += remaining_size;
  5897. return static_cast<ssize_t>(remaining_size);
  5898. }
  5899. }
  5900. if (!wait_readable()) { return -1; }
  5901. read_buff_off_ = 0;
  5902. read_buff_content_size_ = 0;
  5903. if (size < read_buff_size_) {
  5904. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  5905. CPPHTTPLIB_RECV_FLAGS);
  5906. if (n <= 0) {
  5907. return n;
  5908. } else if (n <= static_cast<ssize_t>(size)) {
  5909. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  5910. return n;
  5911. } else {
  5912. memcpy(ptr, read_buff_.data(), size);
  5913. read_buff_off_ = size;
  5914. read_buff_content_size_ = static_cast<size_t>(n);
  5915. return static_cast<ssize_t>(size);
  5916. }
  5917. } else {
  5918. return read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  5919. }
  5920. }
  5921. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  5922. if (!wait_writable()) { return -1; }
  5923. #if defined(_WIN32) && !defined(_WIN64)
  5924. size =
  5925. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  5926. #endif
  5927. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  5928. }
  5929. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  5930. int &port) const {
  5931. return detail::get_remote_ip_and_port(sock_, ip, port);
  5932. }
  5933. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  5934. int &port) const {
  5935. return detail::get_local_ip_and_port(sock_, ip, port);
  5936. }
  5937. inline socket_t SocketStream::socket() const { return sock_; }
  5938. inline time_t SocketStream::duration() const {
  5939. return std::chrono::duration_cast<std::chrono::milliseconds>(
  5940. std::chrono::steady_clock::now() - start_time_)
  5941. .count();
  5942. }
  5943. // Buffer stream implementation
  5944. inline bool BufferStream::is_readable() const { return true; }
  5945. inline bool BufferStream::wait_readable() const { return true; }
  5946. inline bool BufferStream::wait_writable() const { return true; }
  5947. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  5948. #if defined(_MSC_VER) && _MSC_VER < 1910
  5949. auto len_read = buffer._Copy_s(ptr, size, size, position);
  5950. #else
  5951. auto len_read = buffer.copy(ptr, size, position);
  5952. #endif
  5953. position += static_cast<size_t>(len_read);
  5954. return static_cast<ssize_t>(len_read);
  5955. }
  5956. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  5957. buffer.append(ptr, size);
  5958. return static_cast<ssize_t>(size);
  5959. }
  5960. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  5961. int & /*port*/) const {}
  5962. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  5963. int & /*port*/) const {}
  5964. inline socket_t BufferStream::socket() const { return 0; }
  5965. inline time_t BufferStream::duration() const { return 0; }
  5966. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  5967. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  5968. : MatcherBase(pattern) {
  5969. constexpr const char marker[] = "/:";
  5970. // One past the last ending position of a path param substring
  5971. std::size_t last_param_end = 0;
  5972. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5973. // Needed to ensure that parameter names are unique during matcher
  5974. // construction
  5975. // If exceptions are disabled, only last duplicate path
  5976. // parameter will be set
  5977. std::unordered_set<std::string> param_name_set;
  5978. #endif
  5979. while (true) {
  5980. const auto marker_pos = pattern.find(
  5981. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  5982. if (marker_pos == std::string::npos) { break; }
  5983. static_fragments_.push_back(
  5984. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  5985. const auto param_name_start = marker_pos + str_len(marker);
  5986. auto sep_pos = pattern.find(separator, param_name_start);
  5987. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  5988. auto param_name =
  5989. pattern.substr(param_name_start, sep_pos - param_name_start);
  5990. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5991. if (param_name_set.find(param_name) != param_name_set.cend()) {
  5992. std::string msg = "Encountered path parameter '" + param_name +
  5993. "' multiple times in route pattern '" + pattern + "'.";
  5994. throw std::invalid_argument(msg);
  5995. }
  5996. #endif
  5997. param_names_.push_back(std::move(param_name));
  5998. last_param_end = sep_pos + 1;
  5999. }
  6000. if (last_param_end < pattern.length()) {
  6001. static_fragments_.push_back(pattern.substr(last_param_end));
  6002. }
  6003. }
  6004. inline bool PathParamsMatcher::match(Request &request) const {
  6005. request.matches = std::smatch();
  6006. request.path_params.clear();
  6007. request.path_params.reserve(param_names_.size());
  6008. // One past the position at which the path matched the pattern last time
  6009. std::size_t starting_pos = 0;
  6010. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  6011. const auto &fragment = static_fragments_[i];
  6012. if (starting_pos + fragment.length() > request.path.length()) {
  6013. return false;
  6014. }
  6015. // Avoid unnecessary allocation by using strncmp instead of substr +
  6016. // comparison
  6017. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  6018. fragment.length()) != 0) {
  6019. return false;
  6020. }
  6021. starting_pos += fragment.length();
  6022. // Should only happen when we have a static fragment after a param
  6023. // Example: '/users/:id/subscriptions'
  6024. // The 'subscriptions' fragment here does not have a corresponding param
  6025. if (i >= param_names_.size()) { continue; }
  6026. auto sep_pos = request.path.find(separator, starting_pos);
  6027. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  6028. const auto &param_name = param_names_[i];
  6029. request.path_params.emplace(
  6030. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  6031. // Mark everything up to '/' as matched
  6032. starting_pos = sep_pos + 1;
  6033. }
  6034. // Returns false if the path is longer than the pattern
  6035. return starting_pos >= request.path.length();
  6036. }
  6037. inline bool RegexMatcher::match(Request &request) const {
  6038. request.path_params.clear();
  6039. return std::regex_match(request.path, request.matches, regex_);
  6040. }
  6041. inline std::string make_host_and_port_string(const std::string &host, int port,
  6042. bool is_ssl) {
  6043. std::string result;
  6044. // Enclose IPv6 address in brackets (but not if already enclosed)
  6045. if (host.find(':') == std::string::npos ||
  6046. (!host.empty() && host[0] == '[')) {
  6047. // IPv4, hostname, or already bracketed IPv6
  6048. result = host;
  6049. } else {
  6050. // IPv6 address without brackets
  6051. result = "[" + host + "]";
  6052. }
  6053. // Append port if not default
  6054. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  6055. ; // do nothing
  6056. } else {
  6057. result += ":" + std::to_string(port);
  6058. }
  6059. return result;
  6060. }
  6061. } // namespace detail
  6062. // HTTP server implementation
  6063. inline Server::Server()
  6064. : new_task_queue(
  6065. [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }) {
  6066. #ifndef _WIN32
  6067. signal(SIGPIPE, SIG_IGN);
  6068. #endif
  6069. }
  6070. inline Server::~Server() = default;
  6071. inline std::unique_ptr<detail::MatcherBase>
  6072. Server::make_matcher(const std::string &pattern) {
  6073. if (pattern.find("/:") != std::string::npos) {
  6074. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  6075. } else {
  6076. return detail::make_unique<detail::RegexMatcher>(pattern);
  6077. }
  6078. }
  6079. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  6080. get_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  6081. return *this;
  6082. }
  6083. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  6084. post_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  6085. return *this;
  6086. }
  6087. inline Server &Server::Post(const std::string &pattern,
  6088. HandlerWithContentReader handler) {
  6089. post_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  6090. std::move(handler));
  6091. return *this;
  6092. }
  6093. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  6094. put_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  6095. return *this;
  6096. }
  6097. inline Server &Server::Put(const std::string &pattern,
  6098. HandlerWithContentReader handler) {
  6099. put_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  6100. std::move(handler));
  6101. return *this;
  6102. }
  6103. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  6104. patch_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  6105. return *this;
  6106. }
  6107. inline Server &Server::Patch(const std::string &pattern,
  6108. HandlerWithContentReader handler) {
  6109. patch_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  6110. std::move(handler));
  6111. return *this;
  6112. }
  6113. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  6114. delete_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  6115. return *this;
  6116. }
  6117. inline Server &Server::Delete(const std::string &pattern,
  6118. HandlerWithContentReader handler) {
  6119. delete_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  6120. std::move(handler));
  6121. return *this;
  6122. }
  6123. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  6124. options_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  6125. return *this;
  6126. }
  6127. inline bool Server::set_base_dir(const std::string &dir,
  6128. const std::string &mount_point) {
  6129. return set_mount_point(mount_point, dir);
  6130. }
  6131. inline bool Server::set_mount_point(const std::string &mount_point,
  6132. const std::string &dir, Headers headers) {
  6133. detail::FileStat stat(dir);
  6134. if (stat.is_dir()) {
  6135. std::string mnt = !mount_point.empty() ? mount_point : "/";
  6136. if (!mnt.empty() && mnt[0] == '/') {
  6137. base_dirs_.push_back({mnt, dir, std::move(headers)});
  6138. return true;
  6139. }
  6140. }
  6141. return false;
  6142. }
  6143. inline bool Server::remove_mount_point(const std::string &mount_point) {
  6144. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  6145. if (it->mount_point == mount_point) {
  6146. base_dirs_.erase(it);
  6147. return true;
  6148. }
  6149. }
  6150. return false;
  6151. }
  6152. inline Server &
  6153. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  6154. const std::string &mime) {
  6155. file_extension_and_mimetype_map_[ext] = mime;
  6156. return *this;
  6157. }
  6158. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  6159. default_file_mimetype_ = mime;
  6160. return *this;
  6161. }
  6162. inline Server &Server::set_file_request_handler(Handler handler) {
  6163. file_request_handler_ = std::move(handler);
  6164. return *this;
  6165. }
  6166. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  6167. std::true_type) {
  6168. error_handler_ = std::move(handler);
  6169. return *this;
  6170. }
  6171. inline Server &Server::set_error_handler_core(Handler handler,
  6172. std::false_type) {
  6173. error_handler_ = [handler](const Request &req, Response &res) {
  6174. handler(req, res);
  6175. return HandlerResponse::Handled;
  6176. };
  6177. return *this;
  6178. }
  6179. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  6180. exception_handler_ = std::move(handler);
  6181. return *this;
  6182. }
  6183. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  6184. pre_routing_handler_ = std::move(handler);
  6185. return *this;
  6186. }
  6187. inline Server &Server::set_post_routing_handler(Handler handler) {
  6188. post_routing_handler_ = std::move(handler);
  6189. return *this;
  6190. }
  6191. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  6192. pre_request_handler_ = std::move(handler);
  6193. return *this;
  6194. }
  6195. inline Server &Server::set_logger(Logger logger) {
  6196. logger_ = std::move(logger);
  6197. return *this;
  6198. }
  6199. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  6200. error_logger_ = std::move(error_logger);
  6201. return *this;
  6202. }
  6203. inline Server &Server::set_pre_compression_logger(Logger logger) {
  6204. pre_compression_logger_ = std::move(logger);
  6205. return *this;
  6206. }
  6207. inline Server &
  6208. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  6209. expect_100_continue_handler_ = std::move(handler);
  6210. return *this;
  6211. }
  6212. inline Server &Server::set_address_family(int family) {
  6213. address_family_ = family;
  6214. return *this;
  6215. }
  6216. inline Server &Server::set_tcp_nodelay(bool on) {
  6217. tcp_nodelay_ = on;
  6218. return *this;
  6219. }
  6220. inline Server &Server::set_ipv6_v6only(bool on) {
  6221. ipv6_v6only_ = on;
  6222. return *this;
  6223. }
  6224. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  6225. socket_options_ = std::move(socket_options);
  6226. return *this;
  6227. }
  6228. inline Server &Server::set_default_headers(Headers headers) {
  6229. default_headers_ = std::move(headers);
  6230. return *this;
  6231. }
  6232. inline Server &Server::set_header_writer(
  6233. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  6234. header_writer_ = writer;
  6235. return *this;
  6236. }
  6237. inline Server &
  6238. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  6239. trusted_proxies_ = proxies;
  6240. return *this;
  6241. }
  6242. inline Server &Server::set_keep_alive_max_count(size_t count) {
  6243. keep_alive_max_count_ = count;
  6244. return *this;
  6245. }
  6246. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  6247. keep_alive_timeout_sec_ = sec;
  6248. return *this;
  6249. }
  6250. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  6251. read_timeout_sec_ = sec;
  6252. read_timeout_usec_ = usec;
  6253. return *this;
  6254. }
  6255. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  6256. write_timeout_sec_ = sec;
  6257. write_timeout_usec_ = usec;
  6258. return *this;
  6259. }
  6260. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  6261. idle_interval_sec_ = sec;
  6262. idle_interval_usec_ = usec;
  6263. return *this;
  6264. }
  6265. inline Server &Server::set_payload_max_length(size_t length) {
  6266. payload_max_length_ = length;
  6267. return *this;
  6268. }
  6269. inline bool Server::bind_to_port(const std::string &host, int port,
  6270. int socket_flags) {
  6271. auto ret = bind_internal(host, port, socket_flags);
  6272. if (ret == -1) { is_decommissioned = true; }
  6273. return ret >= 0;
  6274. }
  6275. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  6276. auto ret = bind_internal(host, 0, socket_flags);
  6277. if (ret == -1) { is_decommissioned = true; }
  6278. return ret;
  6279. }
  6280. inline bool Server::listen_after_bind() { return listen_internal(); }
  6281. inline bool Server::listen(const std::string &host, int port,
  6282. int socket_flags) {
  6283. return bind_to_port(host, port, socket_flags) && listen_internal();
  6284. }
  6285. inline bool Server::is_running() const { return is_running_; }
  6286. inline void Server::wait_until_ready() const {
  6287. while (!is_running_ && !is_decommissioned) {
  6288. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  6289. }
  6290. }
  6291. inline void Server::stop() {
  6292. if (is_running_) {
  6293. assert(svr_sock_ != INVALID_SOCKET);
  6294. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  6295. detail::shutdown_socket(sock);
  6296. detail::close_socket(sock);
  6297. }
  6298. is_decommissioned = false;
  6299. }
  6300. inline void Server::decommission() { is_decommissioned = true; }
  6301. inline bool Server::parse_request_line(const char *s, Request &req) const {
  6302. auto len = strlen(s);
  6303. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  6304. len -= 2;
  6305. {
  6306. size_t count = 0;
  6307. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  6308. switch (count) {
  6309. case 0: req.method = std::string(b, e); break;
  6310. case 1: req.target = std::string(b, e); break;
  6311. case 2: req.version = std::string(b, e); break;
  6312. default: break;
  6313. }
  6314. count++;
  6315. });
  6316. if (count != 3) { return false; }
  6317. }
  6318. thread_local const std::set<std::string> methods{
  6319. "GET", "HEAD", "POST", "PUT", "DELETE",
  6320. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  6321. if (methods.find(req.method) == methods.end()) {
  6322. output_error_log(Error::InvalidHTTPMethod, &req);
  6323. return false;
  6324. }
  6325. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  6326. output_error_log(Error::InvalidHTTPVersion, &req);
  6327. return false;
  6328. }
  6329. {
  6330. // Skip URL fragment
  6331. for (size_t i = 0; i < req.target.size(); i++) {
  6332. if (req.target[i] == '#') {
  6333. req.target.erase(i);
  6334. break;
  6335. }
  6336. }
  6337. detail::divide(req.target, '?',
  6338. [&](const char *lhs_data, std::size_t lhs_size,
  6339. const char *rhs_data, std::size_t rhs_size) {
  6340. req.path =
  6341. decode_path_component(std::string(lhs_data, lhs_size));
  6342. detail::parse_query_text(rhs_data, rhs_size, req.params);
  6343. });
  6344. }
  6345. return true;
  6346. }
  6347. inline bool Server::write_response(Stream &strm, bool close_connection,
  6348. Request &req, Response &res) {
  6349. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  6350. // incorrectly to the error content.
  6351. req.ranges.clear();
  6352. return write_response_core(strm, close_connection, req, res, false);
  6353. }
  6354. inline bool Server::write_response_with_content(Stream &strm,
  6355. bool close_connection,
  6356. const Request &req,
  6357. Response &res) {
  6358. return write_response_core(strm, close_connection, req, res, true);
  6359. }
  6360. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  6361. const Request &req, Response &res,
  6362. bool need_apply_ranges) {
  6363. assert(res.status != -1);
  6364. if (400 <= res.status && error_handler_ &&
  6365. error_handler_(req, res) == HandlerResponse::Handled) {
  6366. need_apply_ranges = true;
  6367. }
  6368. std::string content_type;
  6369. std::string boundary;
  6370. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  6371. // Prepare additional headers
  6372. if (close_connection || req.get_header_value("Connection") == "close") {
  6373. res.set_header("Connection", "close");
  6374. } else {
  6375. std::string s = "timeout=";
  6376. s += std::to_string(keep_alive_timeout_sec_);
  6377. s += ", max=";
  6378. s += std::to_string(keep_alive_max_count_);
  6379. res.set_header("Keep-Alive", s);
  6380. }
  6381. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  6382. !res.has_header("Content-Type")) {
  6383. res.set_header("Content-Type", "text/plain");
  6384. }
  6385. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  6386. !res.has_header("Content-Length")) {
  6387. res.set_header("Content-Length", "0");
  6388. }
  6389. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  6390. res.set_header("Accept-Ranges", "bytes");
  6391. }
  6392. if (post_routing_handler_) { post_routing_handler_(req, res); }
  6393. // Response line and headers
  6394. {
  6395. detail::BufferStream bstrm;
  6396. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  6397. if (!header_writer_(bstrm, res.headers)) { return false; }
  6398. // Flush buffer
  6399. auto &data = bstrm.get_buffer();
  6400. detail::write_data(strm, data.data(), data.size());
  6401. }
  6402. // Body
  6403. auto ret = true;
  6404. if (req.method != "HEAD") {
  6405. if (!res.body.empty()) {
  6406. if (!detail::write_data(strm, res.body.data(), res.body.size())) {
  6407. ret = false;
  6408. }
  6409. } else if (res.content_provider_) {
  6410. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  6411. res.content_provider_success_ = true;
  6412. } else {
  6413. ret = false;
  6414. }
  6415. }
  6416. }
  6417. // Log
  6418. output_log(req, res);
  6419. return ret;
  6420. }
  6421. inline bool
  6422. Server::write_content_with_provider(Stream &strm, const Request &req,
  6423. Response &res, const std::string &boundary,
  6424. const std::string &content_type) {
  6425. auto is_shutting_down = [this]() {
  6426. return this->svr_sock_ == INVALID_SOCKET;
  6427. };
  6428. if (res.content_length_ > 0) {
  6429. if (req.ranges.empty()) {
  6430. return detail::write_content(strm, res.content_provider_, 0,
  6431. res.content_length_, is_shutting_down);
  6432. } else if (req.ranges.size() == 1) {
  6433. auto offset_and_length = detail::get_range_offset_and_length(
  6434. req.ranges[0], res.content_length_);
  6435. return detail::write_content(strm, res.content_provider_,
  6436. offset_and_length.first,
  6437. offset_and_length.second, is_shutting_down);
  6438. } else {
  6439. return detail::write_multipart_ranges_data(
  6440. strm, req, res, boundary, content_type, res.content_length_,
  6441. is_shutting_down);
  6442. }
  6443. } else {
  6444. if (res.is_chunked_content_provider_) {
  6445. auto type = detail::encoding_type(req, res);
  6446. std::unique_ptr<detail::compressor> compressor;
  6447. if (type == detail::EncodingType::Gzip) {
  6448. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6449. compressor = detail::make_unique<detail::gzip_compressor>();
  6450. #endif
  6451. } else if (type == detail::EncodingType::Brotli) {
  6452. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6453. compressor = detail::make_unique<detail::brotli_compressor>();
  6454. #endif
  6455. } else if (type == detail::EncodingType::Zstd) {
  6456. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6457. compressor = detail::make_unique<detail::zstd_compressor>();
  6458. #endif
  6459. } else {
  6460. compressor = detail::make_unique<detail::nocompressor>();
  6461. }
  6462. assert(compressor != nullptr);
  6463. return detail::write_content_chunked(strm, res.content_provider_,
  6464. is_shutting_down, *compressor);
  6465. } else {
  6466. return detail::write_content_without_length(strm, res.content_provider_,
  6467. is_shutting_down);
  6468. }
  6469. }
  6470. }
  6471. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  6472. FormFields::iterator cur_field;
  6473. FormFiles::iterator cur_file;
  6474. auto is_text_field = false;
  6475. size_t count = 0;
  6476. if (read_content_core(
  6477. strm, req, res,
  6478. // Regular
  6479. [&](const char *buf, size_t n) {
  6480. if (req.body.size() + n > req.body.max_size()) { return false; }
  6481. req.body.append(buf, n);
  6482. return true;
  6483. },
  6484. // Multipart FormData
  6485. [&](const FormData &file) {
  6486. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  6487. output_error_log(Error::TooManyFormDataFiles, &req);
  6488. return false;
  6489. }
  6490. if (file.filename.empty()) {
  6491. cur_field = req.form.fields.emplace(
  6492. file.name, FormField{file.name, file.content, file.headers});
  6493. is_text_field = true;
  6494. } else {
  6495. cur_file = req.form.files.emplace(file.name, file);
  6496. is_text_field = false;
  6497. }
  6498. return true;
  6499. },
  6500. [&](const char *buf, size_t n) {
  6501. if (is_text_field) {
  6502. auto &content = cur_field->second.content;
  6503. if (content.size() + n > content.max_size()) { return false; }
  6504. content.append(buf, n);
  6505. } else {
  6506. auto &content = cur_file->second.content;
  6507. if (content.size() + n > content.max_size()) { return false; }
  6508. content.append(buf, n);
  6509. }
  6510. return true;
  6511. })) {
  6512. const auto &content_type = req.get_header_value("Content-Type");
  6513. if (!content_type.find("application/x-www-form-urlencoded")) {
  6514. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  6515. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  6516. output_error_log(Error::ExceedMaxPayloadSize, &req);
  6517. return false;
  6518. }
  6519. detail::parse_query_text(req.body, req.params);
  6520. }
  6521. return true;
  6522. }
  6523. return false;
  6524. }
  6525. inline bool Server::read_content_with_content_receiver(
  6526. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  6527. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  6528. return read_content_core(strm, req, res, std::move(receiver),
  6529. std::move(multipart_header),
  6530. std::move(multipart_receiver));
  6531. }
  6532. inline bool Server::read_content_core(
  6533. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  6534. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  6535. detail::FormDataParser multipart_form_data_parser;
  6536. ContentReceiverWithProgress out;
  6537. if (req.is_multipart_form_data()) {
  6538. const auto &content_type = req.get_header_value("Content-Type");
  6539. std::string boundary;
  6540. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  6541. res.status = StatusCode::BadRequest_400;
  6542. output_error_log(Error::MultipartParsing, &req);
  6543. return false;
  6544. }
  6545. multipart_form_data_parser.set_boundary(std::move(boundary));
  6546. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  6547. return multipart_form_data_parser.parse(buf, n, multipart_header,
  6548. multipart_receiver);
  6549. };
  6550. } else {
  6551. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  6552. size_t /*len*/) { return receiver(buf, n); };
  6553. }
  6554. if (req.method == "DELETE" && !req.has_header("Content-Length")) {
  6555. return true;
  6556. }
  6557. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  6558. out, true)) {
  6559. return false;
  6560. }
  6561. if (req.is_multipart_form_data()) {
  6562. if (!multipart_form_data_parser.is_valid()) {
  6563. res.status = StatusCode::BadRequest_400;
  6564. output_error_log(Error::MultipartParsing, &req);
  6565. return false;
  6566. }
  6567. }
  6568. return true;
  6569. }
  6570. inline bool Server::handle_file_request(const Request &req, Response &res) {
  6571. for (const auto &entry : base_dirs_) {
  6572. // Prefix match
  6573. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  6574. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  6575. if (detail::is_valid_path(sub_path)) {
  6576. auto path = entry.base_dir + sub_path;
  6577. if (path.back() == '/') { path += "index.html"; }
  6578. detail::FileStat stat(path);
  6579. if (stat.is_dir()) {
  6580. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  6581. return true;
  6582. }
  6583. if (stat.is_file()) {
  6584. for (const auto &kv : entry.headers) {
  6585. res.set_header(kv.first, kv.second);
  6586. }
  6587. auto mm = std::make_shared<detail::mmap>(path.c_str());
  6588. if (!mm->is_open()) {
  6589. output_error_log(Error::OpenFile, &req);
  6590. return false;
  6591. }
  6592. res.set_content_provider(
  6593. mm->size(),
  6594. detail::find_content_type(path, file_extension_and_mimetype_map_,
  6595. default_file_mimetype_),
  6596. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  6597. sink.write(mm->data() + offset, length);
  6598. return true;
  6599. });
  6600. if (req.method != "HEAD" && file_request_handler_) {
  6601. file_request_handler_(req, res);
  6602. }
  6603. return true;
  6604. } else {
  6605. output_error_log(Error::OpenFile, &req);
  6606. }
  6607. }
  6608. }
  6609. }
  6610. return false;
  6611. }
  6612. inline socket_t
  6613. Server::create_server_socket(const std::string &host, int port,
  6614. int socket_flags,
  6615. SocketOptions socket_options) const {
  6616. return detail::create_socket(
  6617. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  6618. ipv6_v6only_, std::move(socket_options),
  6619. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  6620. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  6621. output_error_log(Error::BindIPAddress, nullptr);
  6622. return false;
  6623. }
  6624. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  6625. output_error_log(Error::Listen, nullptr);
  6626. return false;
  6627. }
  6628. return true;
  6629. });
  6630. }
  6631. inline int Server::bind_internal(const std::string &host, int port,
  6632. int socket_flags) {
  6633. if (is_decommissioned) { return -1; }
  6634. if (!is_valid()) { return -1; }
  6635. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  6636. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  6637. if (port == 0) {
  6638. struct sockaddr_storage addr;
  6639. socklen_t addr_len = sizeof(addr);
  6640. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  6641. &addr_len) == -1) {
  6642. output_error_log(Error::GetSockName, nullptr);
  6643. return -1;
  6644. }
  6645. if (addr.ss_family == AF_INET) {
  6646. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  6647. } else if (addr.ss_family == AF_INET6) {
  6648. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  6649. } else {
  6650. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  6651. return -1;
  6652. }
  6653. } else {
  6654. return port;
  6655. }
  6656. }
  6657. inline bool Server::listen_internal() {
  6658. if (is_decommissioned) { return false; }
  6659. auto ret = true;
  6660. is_running_ = true;
  6661. auto se = detail::scope_exit([&]() { is_running_ = false; });
  6662. {
  6663. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  6664. while (svr_sock_ != INVALID_SOCKET) {
  6665. #ifndef _WIN32
  6666. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  6667. #endif
  6668. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  6669. idle_interval_usec_);
  6670. if (val == 0) { // Timeout
  6671. task_queue->on_idle();
  6672. continue;
  6673. }
  6674. #ifndef _WIN32
  6675. }
  6676. #endif
  6677. #if defined _WIN32
  6678. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  6679. // OVERLAPPED
  6680. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  6681. #elif defined SOCK_CLOEXEC
  6682. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  6683. #else
  6684. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  6685. #endif
  6686. if (sock == INVALID_SOCKET) {
  6687. if (errno == EMFILE) {
  6688. // The per-process limit of open file descriptors has been reached.
  6689. // Try to accept new connections after a short sleep.
  6690. std::this_thread::sleep_for(std::chrono::microseconds{1});
  6691. continue;
  6692. } else if (errno == EINTR || errno == EAGAIN) {
  6693. continue;
  6694. }
  6695. if (svr_sock_ != INVALID_SOCKET) {
  6696. detail::close_socket(svr_sock_);
  6697. ret = false;
  6698. output_error_log(Error::Connection, nullptr);
  6699. } else {
  6700. ; // The server socket was closed by user.
  6701. }
  6702. break;
  6703. }
  6704. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  6705. read_timeout_sec_, read_timeout_usec_);
  6706. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  6707. write_timeout_sec_, write_timeout_usec_);
  6708. if (!task_queue->enqueue(
  6709. [this, sock]() { process_and_close_socket(sock); })) {
  6710. output_error_log(Error::ResourceExhaustion, nullptr);
  6711. detail::shutdown_socket(sock);
  6712. detail::close_socket(sock);
  6713. }
  6714. }
  6715. task_queue->shutdown();
  6716. }
  6717. is_decommissioned = !ret;
  6718. return ret;
  6719. }
  6720. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  6721. if (pre_routing_handler_ &&
  6722. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  6723. return true;
  6724. }
  6725. // File handler
  6726. if ((req.method == "GET" || req.method == "HEAD") &&
  6727. handle_file_request(req, res)) {
  6728. return true;
  6729. }
  6730. if (detail::expect_content(req)) {
  6731. // Content reader handler
  6732. {
  6733. ContentReader reader(
  6734. [&](ContentReceiver receiver) {
  6735. auto result = read_content_with_content_receiver(
  6736. strm, req, res, std::move(receiver), nullptr, nullptr);
  6737. if (!result) { output_error_log(Error::Read, &req); }
  6738. return result;
  6739. },
  6740. [&](FormDataHeader header, ContentReceiver receiver) {
  6741. auto result = read_content_with_content_receiver(
  6742. strm, req, res, nullptr, std::move(header),
  6743. std::move(receiver));
  6744. if (!result) { output_error_log(Error::Read, &req); }
  6745. return result;
  6746. });
  6747. if (req.method == "POST") {
  6748. if (dispatch_request_for_content_reader(
  6749. req, res, std::move(reader),
  6750. post_handlers_for_content_reader_)) {
  6751. return true;
  6752. }
  6753. } else if (req.method == "PUT") {
  6754. if (dispatch_request_for_content_reader(
  6755. req, res, std::move(reader),
  6756. put_handlers_for_content_reader_)) {
  6757. return true;
  6758. }
  6759. } else if (req.method == "PATCH") {
  6760. if (dispatch_request_for_content_reader(
  6761. req, res, std::move(reader),
  6762. patch_handlers_for_content_reader_)) {
  6763. return true;
  6764. }
  6765. } else if (req.method == "DELETE") {
  6766. if (dispatch_request_for_content_reader(
  6767. req, res, std::move(reader),
  6768. delete_handlers_for_content_reader_)) {
  6769. return true;
  6770. }
  6771. }
  6772. }
  6773. // Read content into `req.body`
  6774. if (!read_content(strm, req, res)) {
  6775. output_error_log(Error::Read, &req);
  6776. return false;
  6777. }
  6778. }
  6779. // Regular handler
  6780. if (req.method == "GET" || req.method == "HEAD") {
  6781. return dispatch_request(req, res, get_handlers_);
  6782. } else if (req.method == "POST") {
  6783. return dispatch_request(req, res, post_handlers_);
  6784. } else if (req.method == "PUT") {
  6785. return dispatch_request(req, res, put_handlers_);
  6786. } else if (req.method == "DELETE") {
  6787. return dispatch_request(req, res, delete_handlers_);
  6788. } else if (req.method == "OPTIONS") {
  6789. return dispatch_request(req, res, options_handlers_);
  6790. } else if (req.method == "PATCH") {
  6791. return dispatch_request(req, res, patch_handlers_);
  6792. }
  6793. res.status = StatusCode::BadRequest_400;
  6794. return false;
  6795. }
  6796. inline bool Server::dispatch_request(Request &req, Response &res,
  6797. const Handlers &handlers) const {
  6798. for (const auto &x : handlers) {
  6799. const auto &matcher = x.first;
  6800. const auto &handler = x.second;
  6801. if (matcher->match(req)) {
  6802. req.matched_route = matcher->pattern();
  6803. if (!pre_request_handler_ ||
  6804. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  6805. handler(req, res);
  6806. }
  6807. return true;
  6808. }
  6809. }
  6810. return false;
  6811. }
  6812. inline void Server::apply_ranges(const Request &req, Response &res,
  6813. std::string &content_type,
  6814. std::string &boundary) const {
  6815. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  6816. auto it = res.headers.find("Content-Type");
  6817. if (it != res.headers.end()) {
  6818. content_type = it->second;
  6819. res.headers.erase(it);
  6820. }
  6821. boundary = detail::make_multipart_data_boundary();
  6822. res.set_header("Content-Type",
  6823. "multipart/byteranges; boundary=" + boundary);
  6824. }
  6825. auto type = detail::encoding_type(req, res);
  6826. if (res.body.empty()) {
  6827. if (res.content_length_ > 0) {
  6828. size_t length = 0;
  6829. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  6830. length = res.content_length_;
  6831. } else if (req.ranges.size() == 1) {
  6832. auto offset_and_length = detail::get_range_offset_and_length(
  6833. req.ranges[0], res.content_length_);
  6834. length = offset_and_length.second;
  6835. auto content_range = detail::make_content_range_header_field(
  6836. offset_and_length, res.content_length_);
  6837. res.set_header("Content-Range", content_range);
  6838. } else {
  6839. length = detail::get_multipart_ranges_data_length(
  6840. req, boundary, content_type, res.content_length_);
  6841. }
  6842. res.set_header("Content-Length", std::to_string(length));
  6843. } else {
  6844. if (res.content_provider_) {
  6845. if (res.is_chunked_content_provider_) {
  6846. res.set_header("Transfer-Encoding", "chunked");
  6847. if (type == detail::EncodingType::Gzip) {
  6848. res.set_header("Content-Encoding", "gzip");
  6849. } else if (type == detail::EncodingType::Brotli) {
  6850. res.set_header("Content-Encoding", "br");
  6851. } else if (type == detail::EncodingType::Zstd) {
  6852. res.set_header("Content-Encoding", "zstd");
  6853. }
  6854. }
  6855. }
  6856. }
  6857. } else {
  6858. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  6859. ;
  6860. } else if (req.ranges.size() == 1) {
  6861. auto offset_and_length =
  6862. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  6863. auto offset = offset_and_length.first;
  6864. auto length = offset_and_length.second;
  6865. auto content_range = detail::make_content_range_header_field(
  6866. offset_and_length, res.body.size());
  6867. res.set_header("Content-Range", content_range);
  6868. assert(offset + length <= res.body.size());
  6869. res.body = res.body.substr(offset, length);
  6870. } else {
  6871. std::string data;
  6872. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  6873. res.body.size(), data);
  6874. res.body.swap(data);
  6875. }
  6876. if (type != detail::EncodingType::None) {
  6877. output_pre_compression_log(req, res);
  6878. std::unique_ptr<detail::compressor> compressor;
  6879. std::string content_encoding;
  6880. if (type == detail::EncodingType::Gzip) {
  6881. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6882. compressor = detail::make_unique<detail::gzip_compressor>();
  6883. content_encoding = "gzip";
  6884. #endif
  6885. } else if (type == detail::EncodingType::Brotli) {
  6886. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6887. compressor = detail::make_unique<detail::brotli_compressor>();
  6888. content_encoding = "br";
  6889. #endif
  6890. } else if (type == detail::EncodingType::Zstd) {
  6891. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6892. compressor = detail::make_unique<detail::zstd_compressor>();
  6893. content_encoding = "zstd";
  6894. #endif
  6895. }
  6896. if (compressor) {
  6897. std::string compressed;
  6898. if (compressor->compress(res.body.data(), res.body.size(), true,
  6899. [&](const char *data, size_t data_len) {
  6900. compressed.append(data, data_len);
  6901. return true;
  6902. })) {
  6903. res.body.swap(compressed);
  6904. res.set_header("Content-Encoding", content_encoding);
  6905. }
  6906. }
  6907. }
  6908. auto length = std::to_string(res.body.size());
  6909. res.set_header("Content-Length", length);
  6910. }
  6911. }
  6912. inline bool Server::dispatch_request_for_content_reader(
  6913. Request &req, Response &res, ContentReader content_reader,
  6914. const HandlersForContentReader &handlers) const {
  6915. for (const auto &x : handlers) {
  6916. const auto &matcher = x.first;
  6917. const auto &handler = x.second;
  6918. if (matcher->match(req)) {
  6919. req.matched_route = matcher->pattern();
  6920. if (!pre_request_handler_ ||
  6921. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  6922. handler(req, res, content_reader);
  6923. }
  6924. return true;
  6925. }
  6926. }
  6927. return false;
  6928. }
  6929. inline std::string
  6930. get_client_ip(const std::string &x_forwarded_for,
  6931. const std::vector<std::string> &trusted_proxies) {
  6932. // X-Forwarded-For is a comma-separated list per RFC 7239
  6933. std::vector<std::string> ip_list;
  6934. detail::split(x_forwarded_for.data(),
  6935. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  6936. [&](const char *b, const char *e) {
  6937. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  6938. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  6939. });
  6940. for (size_t i = 0; i < ip_list.size(); ++i) {
  6941. auto ip = ip_list[i];
  6942. auto is_trusted_proxy =
  6943. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  6944. [&](const std::string &proxy) { return ip == proxy; });
  6945. if (is_trusted_proxy) {
  6946. if (i == 0) {
  6947. // If the trusted proxy is the first IP, there's no preceding client IP
  6948. return ip;
  6949. } else {
  6950. // Return the IP immediately before the trusted proxy
  6951. return ip_list[i - 1];
  6952. }
  6953. }
  6954. }
  6955. // If no trusted proxy is found, return the first IP in the list
  6956. return ip_list.front();
  6957. }
  6958. inline bool
  6959. Server::process_request(Stream &strm, const std::string &remote_addr,
  6960. int remote_port, const std::string &local_addr,
  6961. int local_port, bool close_connection,
  6962. bool &connection_closed,
  6963. const std::function<void(Request &)> &setup_request) {
  6964. std::array<char, 2048> buf{};
  6965. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  6966. // Connection has been closed on client
  6967. if (!line_reader.getline()) { return false; }
  6968. Request req;
  6969. req.start_time_ = std::chrono::steady_clock::now();
  6970. Response res;
  6971. res.version = "HTTP/1.1";
  6972. res.headers = default_headers_;
  6973. #ifdef __APPLE__
  6974. // Socket file descriptor exceeded FD_SETSIZE...
  6975. if (strm.socket() >= FD_SETSIZE) {
  6976. Headers dummy;
  6977. detail::read_headers(strm, dummy);
  6978. res.status = StatusCode::InternalServerError_500;
  6979. output_error_log(Error::ExceedMaxSocketDescriptorCount, &req);
  6980. return write_response(strm, close_connection, req, res);
  6981. }
  6982. #endif
  6983. // Request line and headers
  6984. if (!parse_request_line(line_reader.ptr(), req)) {
  6985. res.status = StatusCode::BadRequest_400;
  6986. output_error_log(Error::InvalidRequestLine, &req);
  6987. return write_response(strm, close_connection, req, res);
  6988. }
  6989. // Request headers
  6990. if (!detail::read_headers(strm, req.headers)) {
  6991. res.status = StatusCode::BadRequest_400;
  6992. output_error_log(Error::InvalidHeaders, &req);
  6993. return write_response(strm, close_connection, req, res);
  6994. }
  6995. // Check if the request URI doesn't exceed the limit
  6996. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  6997. Headers dummy;
  6998. detail::read_headers(strm, dummy);
  6999. res.status = StatusCode::UriTooLong_414;
  7000. output_error_log(Error::ExceedUriMaxLength, &req);
  7001. return write_response(strm, close_connection, req, res);
  7002. }
  7003. if (req.get_header_value("Connection") == "close") {
  7004. connection_closed = true;
  7005. }
  7006. if (req.version == "HTTP/1.0" &&
  7007. req.get_header_value("Connection") != "Keep-Alive") {
  7008. connection_closed = true;
  7009. }
  7010. if (!trusted_proxies_.empty() && req.has_header("X-Forwarded-For")) {
  7011. auto x_forwarded_for = req.get_header_value("X-Forwarded-For");
  7012. req.remote_addr = get_client_ip(x_forwarded_for, trusted_proxies_);
  7013. } else {
  7014. req.remote_addr = remote_addr;
  7015. }
  7016. req.remote_port = remote_port;
  7017. req.local_addr = local_addr;
  7018. req.local_port = local_port;
  7019. if (req.has_header("Accept")) {
  7020. const auto &accept_header = req.get_header_value("Accept");
  7021. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  7022. res.status = StatusCode::BadRequest_400;
  7023. output_error_log(Error::HTTPParsing, &req);
  7024. return write_response(strm, close_connection, req, res);
  7025. }
  7026. }
  7027. if (req.has_header("Range")) {
  7028. const auto &range_header_value = req.get_header_value("Range");
  7029. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  7030. res.status = StatusCode::RangeNotSatisfiable_416;
  7031. output_error_log(Error::InvalidRangeHeader, &req);
  7032. return write_response(strm, close_connection, req, res);
  7033. }
  7034. }
  7035. if (setup_request) { setup_request(req); }
  7036. if (req.get_header_value("Expect") == "100-continue") {
  7037. int status = StatusCode::Continue_100;
  7038. if (expect_100_continue_handler_) {
  7039. status = expect_100_continue_handler_(req, res);
  7040. }
  7041. switch (status) {
  7042. case StatusCode::Continue_100:
  7043. case StatusCode::ExpectationFailed_417:
  7044. detail::write_response_line(strm, status);
  7045. strm.write("\r\n");
  7046. break;
  7047. default:
  7048. connection_closed = true;
  7049. return write_response(strm, true, req, res);
  7050. }
  7051. }
  7052. // Setup `is_connection_closed` method
  7053. auto sock = strm.socket();
  7054. req.is_connection_closed = [sock]() {
  7055. return !detail::is_socket_alive(sock);
  7056. };
  7057. // Routing
  7058. auto routed = false;
  7059. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  7060. routed = routing(req, res, strm);
  7061. #else
  7062. try {
  7063. routed = routing(req, res, strm);
  7064. } catch (std::exception &e) {
  7065. if (exception_handler_) {
  7066. auto ep = std::current_exception();
  7067. exception_handler_(req, res, ep);
  7068. routed = true;
  7069. } else {
  7070. res.status = StatusCode::InternalServerError_500;
  7071. std::string val;
  7072. auto s = e.what();
  7073. for (size_t i = 0; s[i]; i++) {
  7074. switch (s[i]) {
  7075. case '\r': val += "\\r"; break;
  7076. case '\n': val += "\\n"; break;
  7077. default: val += s[i]; break;
  7078. }
  7079. }
  7080. res.set_header("EXCEPTION_WHAT", val);
  7081. }
  7082. } catch (...) {
  7083. if (exception_handler_) {
  7084. auto ep = std::current_exception();
  7085. exception_handler_(req, res, ep);
  7086. routed = true;
  7087. } else {
  7088. res.status = StatusCode::InternalServerError_500;
  7089. res.set_header("EXCEPTION_WHAT", "UNKNOWN");
  7090. }
  7091. }
  7092. #endif
  7093. if (routed) {
  7094. if (res.status == -1) {
  7095. res.status = req.ranges.empty() ? StatusCode::OK_200
  7096. : StatusCode::PartialContent_206;
  7097. }
  7098. // Serve file content by using a content provider
  7099. if (!res.file_content_path_.empty()) {
  7100. const auto &path = res.file_content_path_;
  7101. auto mm = std::make_shared<detail::mmap>(path.c_str());
  7102. if (!mm->is_open()) {
  7103. res.body.clear();
  7104. res.content_length_ = 0;
  7105. res.content_provider_ = nullptr;
  7106. res.status = StatusCode::NotFound_404;
  7107. output_error_log(Error::OpenFile, &req);
  7108. return write_response(strm, close_connection, req, res);
  7109. }
  7110. auto content_type = res.file_content_content_type_;
  7111. if (content_type.empty()) {
  7112. content_type = detail::find_content_type(
  7113. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  7114. }
  7115. res.set_content_provider(
  7116. mm->size(), content_type,
  7117. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  7118. sink.write(mm->data() + offset, length);
  7119. return true;
  7120. });
  7121. }
  7122. if (detail::range_error(req, res)) {
  7123. res.body.clear();
  7124. res.content_length_ = 0;
  7125. res.content_provider_ = nullptr;
  7126. res.status = StatusCode::RangeNotSatisfiable_416;
  7127. return write_response(strm, close_connection, req, res);
  7128. }
  7129. return write_response_with_content(strm, close_connection, req, res);
  7130. } else {
  7131. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  7132. return write_response(strm, close_connection, req, res);
  7133. }
  7134. }
  7135. inline bool Server::is_valid() const { return true; }
  7136. inline bool Server::process_and_close_socket(socket_t sock) {
  7137. std::string remote_addr;
  7138. int remote_port = 0;
  7139. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  7140. std::string local_addr;
  7141. int local_port = 0;
  7142. detail::get_local_ip_and_port(sock, local_addr, local_port);
  7143. auto ret = detail::process_server_socket(
  7144. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  7145. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  7146. write_timeout_usec_,
  7147. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  7148. return process_request(strm, remote_addr, remote_port, local_addr,
  7149. local_port, close_connection, connection_closed,
  7150. nullptr);
  7151. });
  7152. detail::shutdown_socket(sock);
  7153. detail::close_socket(sock);
  7154. return ret;
  7155. }
  7156. inline void Server::output_log(const Request &req, const Response &res) const {
  7157. if (logger_) {
  7158. std::lock_guard<std::mutex> guard(logger_mutex_);
  7159. logger_(req, res);
  7160. }
  7161. }
  7162. inline void Server::output_pre_compression_log(const Request &req,
  7163. const Response &res) const {
  7164. if (pre_compression_logger_) {
  7165. std::lock_guard<std::mutex> guard(logger_mutex_);
  7166. pre_compression_logger_(req, res);
  7167. }
  7168. }
  7169. inline void Server::output_error_log(const Error &err,
  7170. const Request *req) const {
  7171. if (error_logger_) {
  7172. std::lock_guard<std::mutex> guard(logger_mutex_);
  7173. error_logger_(err, req);
  7174. }
  7175. }
  7176. // HTTP client implementation
  7177. inline ClientImpl::ClientImpl(const std::string &host)
  7178. : ClientImpl(host, 80, std::string(), std::string()) {}
  7179. inline ClientImpl::ClientImpl(const std::string &host, int port)
  7180. : ClientImpl(host, port, std::string(), std::string()) {}
  7181. inline ClientImpl::ClientImpl(const std::string &host, int port,
  7182. const std::string &client_cert_path,
  7183. const std::string &client_key_path)
  7184. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  7185. host_and_port_(detail::make_host_and_port_string(host_, port, is_ssl())),
  7186. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  7187. inline ClientImpl::~ClientImpl() {
  7188. // Wait until all the requests in flight are handled.
  7189. size_t retry_count = 10;
  7190. while (retry_count-- > 0) {
  7191. {
  7192. std::lock_guard<std::mutex> guard(socket_mutex_);
  7193. if (socket_requests_in_flight_ == 0) { break; }
  7194. }
  7195. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  7196. }
  7197. std::lock_guard<std::mutex> guard(socket_mutex_);
  7198. shutdown_socket(socket_);
  7199. close_socket(socket_);
  7200. }
  7201. inline bool ClientImpl::is_valid() const { return true; }
  7202. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  7203. client_cert_path_ = rhs.client_cert_path_;
  7204. client_key_path_ = rhs.client_key_path_;
  7205. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  7206. read_timeout_sec_ = rhs.read_timeout_sec_;
  7207. read_timeout_usec_ = rhs.read_timeout_usec_;
  7208. write_timeout_sec_ = rhs.write_timeout_sec_;
  7209. write_timeout_usec_ = rhs.write_timeout_usec_;
  7210. max_timeout_msec_ = rhs.max_timeout_msec_;
  7211. basic_auth_username_ = rhs.basic_auth_username_;
  7212. basic_auth_password_ = rhs.basic_auth_password_;
  7213. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  7214. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7215. digest_auth_username_ = rhs.digest_auth_username_;
  7216. digest_auth_password_ = rhs.digest_auth_password_;
  7217. #endif
  7218. keep_alive_ = rhs.keep_alive_;
  7219. follow_location_ = rhs.follow_location_;
  7220. path_encode_ = rhs.path_encode_;
  7221. address_family_ = rhs.address_family_;
  7222. tcp_nodelay_ = rhs.tcp_nodelay_;
  7223. ipv6_v6only_ = rhs.ipv6_v6only_;
  7224. socket_options_ = rhs.socket_options_;
  7225. compress_ = rhs.compress_;
  7226. decompress_ = rhs.decompress_;
  7227. interface_ = rhs.interface_;
  7228. proxy_host_ = rhs.proxy_host_;
  7229. proxy_port_ = rhs.proxy_port_;
  7230. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  7231. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  7232. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  7233. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7234. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  7235. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  7236. #endif
  7237. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7238. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  7239. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  7240. ca_cert_store_ = rhs.ca_cert_store_;
  7241. #endif
  7242. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7243. server_certificate_verification_ = rhs.server_certificate_verification_;
  7244. server_hostname_verification_ = rhs.server_hostname_verification_;
  7245. server_certificate_verifier_ = rhs.server_certificate_verifier_;
  7246. #endif
  7247. logger_ = rhs.logger_;
  7248. error_logger_ = rhs.error_logger_;
  7249. }
  7250. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  7251. if (!proxy_host_.empty() && proxy_port_ != -1) {
  7252. return detail::create_client_socket(
  7253. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  7254. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  7255. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  7256. write_timeout_sec_, write_timeout_usec_, interface_, error);
  7257. }
  7258. // Check is custom IP specified for host_
  7259. std::string ip;
  7260. auto it = addr_map_.find(host_);
  7261. if (it != addr_map_.end()) { ip = it->second; }
  7262. return detail::create_client_socket(
  7263. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  7264. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  7265. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  7266. write_timeout_usec_, interface_, error);
  7267. }
  7268. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  7269. Error &error) {
  7270. auto sock = create_client_socket(error);
  7271. if (sock == INVALID_SOCKET) { return false; }
  7272. socket.sock = sock;
  7273. return true;
  7274. }
  7275. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  7276. bool /*shutdown_gracefully*/) {
  7277. // If there are any requests in flight from threads other than us, then it's
  7278. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  7279. assert(socket_requests_in_flight_ == 0 ||
  7280. socket_requests_are_from_thread_ == std::this_thread::get_id());
  7281. }
  7282. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  7283. if (socket.sock == INVALID_SOCKET) { return; }
  7284. detail::shutdown_socket(socket.sock);
  7285. }
  7286. inline void ClientImpl::close_socket(Socket &socket) {
  7287. // If there are requests in flight in another thread, usually closing
  7288. // the socket will be fine and they will simply receive an error when
  7289. // using the closed socket, but it is still a bug since rarely the OS
  7290. // may reassign the socket id to be used for a new socket, and then
  7291. // suddenly they will be operating on a live socket that is different
  7292. // than the one they intended!
  7293. assert(socket_requests_in_flight_ == 0 ||
  7294. socket_requests_are_from_thread_ == std::this_thread::get_id());
  7295. // It is also a bug if this happens while SSL is still active
  7296. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7297. assert(socket.ssl == nullptr);
  7298. #endif
  7299. if (socket.sock == INVALID_SOCKET) { return; }
  7300. detail::close_socket(socket.sock);
  7301. socket.sock = INVALID_SOCKET;
  7302. }
  7303. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  7304. Response &res) const {
  7305. std::array<char, 2048> buf{};
  7306. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  7307. if (!line_reader.getline()) { return false; }
  7308. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  7309. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  7310. #else
  7311. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  7312. #endif
  7313. std::cmatch m;
  7314. if (!std::regex_match(line_reader.ptr(), m, re)) {
  7315. return req.method == "CONNECT";
  7316. }
  7317. res.version = std::string(m[1]);
  7318. res.status = std::stoi(std::string(m[2]));
  7319. res.reason = std::string(m[3]);
  7320. // Ignore '100 Continue'
  7321. while (res.status == StatusCode::Continue_100) {
  7322. if (!line_reader.getline()) { return false; } // CRLF
  7323. if (!line_reader.getline()) { return false; } // next response line
  7324. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  7325. res.version = std::string(m[1]);
  7326. res.status = std::stoi(std::string(m[2]));
  7327. res.reason = std::string(m[3]);
  7328. }
  7329. return true;
  7330. }
  7331. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  7332. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  7333. auto ret = send_(req, res, error);
  7334. if (error == Error::SSLPeerCouldBeClosed_) {
  7335. assert(!ret);
  7336. ret = send_(req, res, error);
  7337. }
  7338. return ret;
  7339. }
  7340. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  7341. {
  7342. std::lock_guard<std::mutex> guard(socket_mutex_);
  7343. // Set this to false immediately - if it ever gets set to true by the end
  7344. // of the request, we know another thread instructed us to close the
  7345. // socket.
  7346. socket_should_be_closed_when_request_is_done_ = false;
  7347. auto is_alive = false;
  7348. if (socket_.is_open()) {
  7349. is_alive = detail::is_socket_alive(socket_.sock);
  7350. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7351. if (is_alive && is_ssl()) {
  7352. if (detail::is_ssl_peer_could_be_closed(socket_.ssl, socket_.sock)) {
  7353. is_alive = false;
  7354. }
  7355. }
  7356. #endif
  7357. if (!is_alive) {
  7358. // Attempt to avoid sigpipe by shutting down non-gracefully if it
  7359. // seems like the other side has already closed the connection Also,
  7360. // there cannot be any requests in flight from other threads since we
  7361. // locked request_mutex_, so safe to close everything immediately
  7362. const bool shutdown_gracefully = false;
  7363. shutdown_ssl(socket_, shutdown_gracefully);
  7364. shutdown_socket(socket_);
  7365. close_socket(socket_);
  7366. }
  7367. }
  7368. if (!is_alive) {
  7369. if (!create_and_connect_socket(socket_, error)) {
  7370. output_error_log(error, &req);
  7371. return false;
  7372. }
  7373. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7374. // TODO: refactoring
  7375. if (is_ssl()) {
  7376. auto &scli = static_cast<SSLClient &>(*this);
  7377. if (!proxy_host_.empty() && proxy_port_ != -1) {
  7378. auto success = false;
  7379. if (!scli.connect_with_proxy(socket_, req.start_time_, res, success,
  7380. error)) {
  7381. if (!success) { output_error_log(error, &req); }
  7382. return success;
  7383. }
  7384. }
  7385. if (!scli.initialize_ssl(socket_, error)) {
  7386. output_error_log(error, &req);
  7387. return false;
  7388. }
  7389. }
  7390. #endif
  7391. }
  7392. // Mark the current socket as being in use so that it cannot be closed by
  7393. // anyone else while this request is ongoing, even though we will be
  7394. // releasing the mutex.
  7395. if (socket_requests_in_flight_ > 1) {
  7396. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  7397. }
  7398. socket_requests_in_flight_ += 1;
  7399. socket_requests_are_from_thread_ = std::this_thread::get_id();
  7400. }
  7401. for (const auto &header : default_headers_) {
  7402. if (req.headers.find(header.first) == req.headers.end()) {
  7403. req.headers.insert(header);
  7404. }
  7405. }
  7406. auto ret = false;
  7407. auto close_connection = !keep_alive_;
  7408. auto se = detail::scope_exit([&]() {
  7409. // Briefly lock mutex in order to mark that a request is no longer ongoing
  7410. std::lock_guard<std::mutex> guard(socket_mutex_);
  7411. socket_requests_in_flight_ -= 1;
  7412. if (socket_requests_in_flight_ <= 0) {
  7413. assert(socket_requests_in_flight_ == 0);
  7414. socket_requests_are_from_thread_ = std::thread::id();
  7415. }
  7416. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  7417. !ret) {
  7418. shutdown_ssl(socket_, true);
  7419. shutdown_socket(socket_);
  7420. close_socket(socket_);
  7421. }
  7422. });
  7423. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  7424. return handle_request(strm, req, res, close_connection, error);
  7425. });
  7426. if (!ret) {
  7427. if (error == Error::Success) {
  7428. error = Error::Unknown;
  7429. output_error_log(error, &req);
  7430. }
  7431. }
  7432. return ret;
  7433. }
  7434. inline Result ClientImpl::send(const Request &req) {
  7435. auto req2 = req;
  7436. return send_(std::move(req2));
  7437. }
  7438. inline Result ClientImpl::send_(Request &&req) {
  7439. auto res = detail::make_unique<Response>();
  7440. auto error = Error::Success;
  7441. auto ret = send(req, *res, error);
  7442. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7443. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  7444. last_ssl_error_, last_openssl_error_};
  7445. #else
  7446. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  7447. #endif
  7448. }
  7449. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  7450. Response &res, bool close_connection,
  7451. Error &error) {
  7452. if (req.path.empty()) {
  7453. error = Error::Connection;
  7454. output_error_log(error, &req);
  7455. return false;
  7456. }
  7457. auto req_save = req;
  7458. bool ret;
  7459. if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) {
  7460. auto req2 = req;
  7461. req2.path = "http://" + host_and_port_ + req.path;
  7462. ret = process_request(strm, req2, res, close_connection, error);
  7463. req = req2;
  7464. req.path = req_save.path;
  7465. } else {
  7466. ret = process_request(strm, req, res, close_connection, error);
  7467. }
  7468. if (!ret) { return false; }
  7469. if (res.get_header_value("Connection") == "close" ||
  7470. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  7471. // TODO this requires a not-entirely-obvious chain of calls to be correct
  7472. // for this to be safe.
  7473. // This is safe to call because handle_request is only called by send_
  7474. // which locks the request mutex during the process. It would be a bug
  7475. // to call it from a different thread since it's a thread-safety issue
  7476. // to do these things to the socket if another thread is using the socket.
  7477. std::lock_guard<std::mutex> guard(socket_mutex_);
  7478. shutdown_ssl(socket_, true);
  7479. shutdown_socket(socket_);
  7480. close_socket(socket_);
  7481. }
  7482. if (300 < res.status && res.status < 400 && follow_location_) {
  7483. req = req_save;
  7484. ret = redirect(req, res, error);
  7485. }
  7486. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7487. if ((res.status == StatusCode::Unauthorized_401 ||
  7488. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  7489. req.authorization_count_ < 5) {
  7490. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  7491. const auto &username =
  7492. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  7493. const auto &password =
  7494. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  7495. if (!username.empty() && !password.empty()) {
  7496. std::map<std::string, std::string> auth;
  7497. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  7498. Request new_req = req;
  7499. new_req.authorization_count_ += 1;
  7500. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  7501. : "Authorization");
  7502. new_req.headers.insert(detail::make_digest_authentication_header(
  7503. req, auth, new_req.authorization_count_, detail::random_string(10),
  7504. username, password, is_proxy));
  7505. Response new_res;
  7506. ret = send(new_req, new_res, error);
  7507. if (ret) { res = new_res; }
  7508. }
  7509. }
  7510. }
  7511. #endif
  7512. return ret;
  7513. }
  7514. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  7515. if (req.redirect_count_ == 0) {
  7516. error = Error::ExceedRedirectCount;
  7517. output_error_log(error, &req);
  7518. return false;
  7519. }
  7520. auto location = res.get_header_value("location");
  7521. if (location.empty()) { return false; }
  7522. thread_local const std::regex re(
  7523. R"((?:(https?):)?(?://(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*)(\?[^#]*)?(?:#.*)?)");
  7524. std::smatch m;
  7525. if (!std::regex_match(location, m, re)) { return false; }
  7526. auto scheme = is_ssl() ? "https" : "http";
  7527. auto next_scheme = m[1].str();
  7528. auto next_host = m[2].str();
  7529. if (next_host.empty()) { next_host = m[3].str(); }
  7530. auto port_str = m[4].str();
  7531. auto next_path = m[5].str();
  7532. auto next_query = m[6].str();
  7533. auto next_port = port_;
  7534. if (!port_str.empty()) {
  7535. next_port = std::stoi(port_str);
  7536. } else if (!next_scheme.empty()) {
  7537. next_port = next_scheme == "https" ? 443 : 80;
  7538. }
  7539. if (next_scheme.empty()) { next_scheme = scheme; }
  7540. if (next_host.empty()) { next_host = host_; }
  7541. if (next_path.empty()) { next_path = "/"; }
  7542. auto path = decode_query_component(next_path, true) + next_query;
  7543. // Same host redirect - use current client
  7544. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  7545. return detail::redirect(*this, req, res, path, location, error);
  7546. }
  7547. // Cross-host/scheme redirect - create new client with robust setup
  7548. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  7549. path, location, error);
  7550. }
  7551. // New method for robust redirect client creation
  7552. inline bool ClientImpl::create_redirect_client(
  7553. const std::string &scheme, const std::string &host, int port, Request &req,
  7554. Response &res, const std::string &path, const std::string &location,
  7555. Error &error) {
  7556. // Determine if we need SSL
  7557. auto need_ssl = (scheme == "https");
  7558. // Clean up request headers that are host/client specific
  7559. // Remove headers that should not be carried over to new host
  7560. auto headers_to_remove =
  7561. std::vector<std::string>{"Host", "Proxy-Authorization", "Authorization"};
  7562. for (const auto &header_name : headers_to_remove) {
  7563. auto it = req.headers.find(header_name);
  7564. while (it != req.headers.end()) {
  7565. it = req.headers.erase(it);
  7566. it = req.headers.find(header_name);
  7567. }
  7568. }
  7569. // Create appropriate client type and handle redirect
  7570. if (need_ssl) {
  7571. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7572. // Create SSL client for HTTPS redirect
  7573. SSLClient redirect_client(host, port);
  7574. // Setup basic client configuration first
  7575. setup_redirect_client(redirect_client);
  7576. // SSL-specific configuration for proxy environments
  7577. if (!proxy_host_.empty() && proxy_port_ != -1) {
  7578. // Critical: Disable SSL verification for proxy environments
  7579. redirect_client.enable_server_certificate_verification(false);
  7580. redirect_client.enable_server_hostname_verification(false);
  7581. } else {
  7582. // For direct SSL connections, copy SSL verification settings
  7583. redirect_client.enable_server_certificate_verification(
  7584. server_certificate_verification_);
  7585. redirect_client.enable_server_hostname_verification(
  7586. server_hostname_verification_);
  7587. }
  7588. // Handle CA certificate store and paths if available
  7589. if (ca_cert_store_ && X509_STORE_up_ref(ca_cert_store_)) {
  7590. redirect_client.set_ca_cert_store(ca_cert_store_);
  7591. }
  7592. if (!ca_cert_file_path_.empty()) {
  7593. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  7594. }
  7595. // Client certificates are set through constructor for SSLClient
  7596. // NOTE: SSLClient constructor already takes client_cert_path and
  7597. // client_key_path so we need to create it properly if client certs are
  7598. // needed
  7599. // Execute the redirect
  7600. return detail::redirect(redirect_client, req, res, path, location, error);
  7601. #else
  7602. // SSL not supported - set appropriate error
  7603. error = Error::SSLConnection;
  7604. output_error_log(error, &req);
  7605. return false;
  7606. #endif
  7607. } else {
  7608. // HTTP redirect
  7609. ClientImpl redirect_client(host, port);
  7610. // Setup client with robust configuration
  7611. setup_redirect_client(redirect_client);
  7612. // Execute the redirect
  7613. return detail::redirect(redirect_client, req, res, path, location, error);
  7614. }
  7615. }
  7616. // New method for robust client setup (based on basic_manual_redirect.cpp
  7617. // logic)
  7618. template <typename ClientType>
  7619. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  7620. // Copy basic settings first
  7621. client.set_connection_timeout(connection_timeout_sec_);
  7622. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  7623. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  7624. client.set_keep_alive(keep_alive_);
  7625. client.set_follow_location(
  7626. true); // Enable redirects to handle multi-step redirects
  7627. client.set_path_encode(path_encode_);
  7628. client.set_compress(compress_);
  7629. client.set_decompress(decompress_);
  7630. // Copy authentication settings BEFORE proxy setup
  7631. if (!basic_auth_username_.empty()) {
  7632. client.set_basic_auth(basic_auth_username_, basic_auth_password_);
  7633. }
  7634. if (!bearer_token_auth_token_.empty()) {
  7635. client.set_bearer_token_auth(bearer_token_auth_token_);
  7636. }
  7637. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7638. if (!digest_auth_username_.empty()) {
  7639. client.set_digest_auth(digest_auth_username_, digest_auth_password_);
  7640. }
  7641. #endif
  7642. // Setup proxy configuration (CRITICAL ORDER - proxy must be set
  7643. // before proxy auth)
  7644. if (!proxy_host_.empty() && proxy_port_ != -1) {
  7645. // First set proxy host and port
  7646. client.set_proxy(proxy_host_, proxy_port_);
  7647. // Then set proxy authentication (order matters!)
  7648. if (!proxy_basic_auth_username_.empty()) {
  7649. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  7650. proxy_basic_auth_password_);
  7651. }
  7652. if (!proxy_bearer_token_auth_token_.empty()) {
  7653. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  7654. }
  7655. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7656. if (!proxy_digest_auth_username_.empty()) {
  7657. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  7658. proxy_digest_auth_password_);
  7659. }
  7660. #endif
  7661. }
  7662. // Copy network and socket settings
  7663. client.set_address_family(address_family_);
  7664. client.set_tcp_nodelay(tcp_nodelay_);
  7665. client.set_ipv6_v6only(ipv6_v6only_);
  7666. if (socket_options_) { client.set_socket_options(socket_options_); }
  7667. if (!interface_.empty()) { client.set_interface(interface_); }
  7668. // Copy logging and headers
  7669. if (logger_) { client.set_logger(logger_); }
  7670. if (error_logger_) { client.set_error_logger(error_logger_); }
  7671. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  7672. // Each new client should generate its own headers based on its target host
  7673. }
  7674. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  7675. const Request &req,
  7676. Error &error) const {
  7677. auto is_shutting_down = []() { return false; };
  7678. if (req.is_chunked_content_provider_) {
  7679. // TODO: Brotli support
  7680. std::unique_ptr<detail::compressor> compressor;
  7681. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7682. if (compress_) {
  7683. compressor = detail::make_unique<detail::gzip_compressor>();
  7684. } else
  7685. #endif
  7686. {
  7687. compressor = detail::make_unique<detail::nocompressor>();
  7688. }
  7689. return detail::write_content_chunked(strm, req.content_provider_,
  7690. is_shutting_down, *compressor, error);
  7691. } else {
  7692. return detail::write_content_with_progress(
  7693. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  7694. req.upload_progress, error);
  7695. }
  7696. }
  7697. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  7698. bool close_connection, Error &error) {
  7699. // Prepare additional headers
  7700. if (close_connection) {
  7701. if (!req.has_header("Connection")) {
  7702. req.set_header("Connection", "close");
  7703. }
  7704. }
  7705. if (!req.has_header("Host")) {
  7706. // For Unix socket connections, use "localhost" as Host header (similar to
  7707. // curl behavior)
  7708. if (address_family_ == AF_UNIX) {
  7709. req.set_header("Host", "localhost");
  7710. } else {
  7711. req.set_header("Host", host_and_port_);
  7712. }
  7713. }
  7714. if (!req.has_header("Accept")) { req.set_header("Accept", "*/*"); }
  7715. if (!req.content_receiver) {
  7716. if (!req.has_header("Accept-Encoding")) {
  7717. std::string accept_encoding;
  7718. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7719. accept_encoding = "br";
  7720. #endif
  7721. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7722. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  7723. accept_encoding += "gzip, deflate";
  7724. #endif
  7725. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7726. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  7727. accept_encoding += "zstd";
  7728. #endif
  7729. req.set_header("Accept-Encoding", accept_encoding);
  7730. }
  7731. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  7732. if (!req.has_header("User-Agent")) {
  7733. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  7734. req.set_header("User-Agent", agent);
  7735. }
  7736. #endif
  7737. };
  7738. if (req.body.empty()) {
  7739. if (req.content_provider_) {
  7740. if (!req.is_chunked_content_provider_) {
  7741. if (!req.has_header("Content-Length")) {
  7742. auto length = std::to_string(req.content_length_);
  7743. req.set_header("Content-Length", length);
  7744. }
  7745. }
  7746. } else {
  7747. if (req.method == "POST" || req.method == "PUT" ||
  7748. req.method == "PATCH") {
  7749. req.set_header("Content-Length", "0");
  7750. }
  7751. }
  7752. } else {
  7753. if (!req.has_header("Content-Type")) {
  7754. req.set_header("Content-Type", "text/plain");
  7755. }
  7756. if (!req.has_header("Content-Length")) {
  7757. auto length = std::to_string(req.body.size());
  7758. req.set_header("Content-Length", length);
  7759. }
  7760. }
  7761. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  7762. if (!req.has_header("Authorization")) {
  7763. req.headers.insert(make_basic_authentication_header(
  7764. basic_auth_username_, basic_auth_password_, false));
  7765. }
  7766. }
  7767. if (!proxy_basic_auth_username_.empty() &&
  7768. !proxy_basic_auth_password_.empty()) {
  7769. if (!req.has_header("Proxy-Authorization")) {
  7770. req.headers.insert(make_basic_authentication_header(
  7771. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  7772. }
  7773. }
  7774. if (!bearer_token_auth_token_.empty()) {
  7775. if (!req.has_header("Authorization")) {
  7776. req.headers.insert(make_bearer_token_authentication_header(
  7777. bearer_token_auth_token_, false));
  7778. }
  7779. }
  7780. if (!proxy_bearer_token_auth_token_.empty()) {
  7781. if (!req.has_header("Proxy-Authorization")) {
  7782. req.headers.insert(make_bearer_token_authentication_header(
  7783. proxy_bearer_token_auth_token_, true));
  7784. }
  7785. }
  7786. // Request line and headers
  7787. {
  7788. detail::BufferStream bstrm;
  7789. // Extract path and query from req.path
  7790. std::string path_part, query_part;
  7791. auto query_pos = req.path.find('?');
  7792. if (query_pos != std::string::npos) {
  7793. path_part = req.path.substr(0, query_pos);
  7794. query_part = req.path.substr(query_pos + 1);
  7795. } else {
  7796. path_part = req.path;
  7797. query_part = "";
  7798. }
  7799. // Encode path and query
  7800. auto path_with_query =
  7801. path_encode_ ? detail::encode_path(path_part) : path_part;
  7802. detail::parse_query_text(query_part, req.params);
  7803. if (!req.params.empty()) {
  7804. path_with_query = append_query_params(path_with_query, req.params);
  7805. }
  7806. // Write request line and headers
  7807. detail::write_request_line(bstrm, req.method, path_with_query);
  7808. header_writer_(bstrm, req.headers);
  7809. // Flush buffer
  7810. auto &data = bstrm.get_buffer();
  7811. if (!detail::write_data(strm, data.data(), data.size())) {
  7812. error = Error::Write;
  7813. output_error_log(error, &req);
  7814. return false;
  7815. }
  7816. }
  7817. // Body
  7818. if (req.body.empty()) {
  7819. return write_content_with_provider(strm, req, error);
  7820. }
  7821. if (req.upload_progress) {
  7822. auto body_size = req.body.size();
  7823. size_t written = 0;
  7824. auto data = req.body.data();
  7825. while (written < body_size) {
  7826. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  7827. if (!detail::write_data(strm, data + written, to_write)) {
  7828. error = Error::Write;
  7829. output_error_log(error, &req);
  7830. return false;
  7831. }
  7832. written += to_write;
  7833. if (!req.upload_progress(written, body_size)) {
  7834. error = Error::Canceled;
  7835. output_error_log(error, &req);
  7836. return false;
  7837. }
  7838. }
  7839. } else {
  7840. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  7841. error = Error::Write;
  7842. output_error_log(error, &req);
  7843. return false;
  7844. }
  7845. }
  7846. return true;
  7847. }
  7848. inline std::unique_ptr<Response> ClientImpl::send_with_content_provider(
  7849. Request &req, const char *body, size_t content_length,
  7850. ContentProvider content_provider,
  7851. ContentProviderWithoutLength content_provider_without_length,
  7852. const std::string &content_type, Error &error) {
  7853. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  7854. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7855. if (compress_) { req.set_header("Content-Encoding", "gzip"); }
  7856. #endif
  7857. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7858. if (compress_ && !content_provider_without_length) {
  7859. // TODO: Brotli support
  7860. detail::gzip_compressor compressor;
  7861. if (content_provider) {
  7862. auto ok = true;
  7863. size_t offset = 0;
  7864. DataSink data_sink;
  7865. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  7866. if (ok) {
  7867. auto last = offset + data_len == content_length;
  7868. auto ret = compressor.compress(
  7869. data, data_len, last,
  7870. [&](const char *compressed_data, size_t compressed_data_len) {
  7871. req.body.append(compressed_data, compressed_data_len);
  7872. return true;
  7873. });
  7874. if (ret) {
  7875. offset += data_len;
  7876. } else {
  7877. ok = false;
  7878. }
  7879. }
  7880. return ok;
  7881. };
  7882. while (ok && offset < content_length) {
  7883. if (!content_provider(offset, content_length - offset, data_sink)) {
  7884. error = Error::Canceled;
  7885. output_error_log(error, &req);
  7886. return nullptr;
  7887. }
  7888. }
  7889. } else {
  7890. if (!compressor.compress(body, content_length, true,
  7891. [&](const char *data, size_t data_len) {
  7892. req.body.append(data, data_len);
  7893. return true;
  7894. })) {
  7895. error = Error::Compression;
  7896. output_error_log(error, &req);
  7897. return nullptr;
  7898. }
  7899. }
  7900. } else
  7901. #endif
  7902. {
  7903. if (content_provider) {
  7904. req.content_length_ = content_length;
  7905. req.content_provider_ = std::move(content_provider);
  7906. req.is_chunked_content_provider_ = false;
  7907. } else if (content_provider_without_length) {
  7908. req.content_length_ = 0;
  7909. req.content_provider_ = detail::ContentProviderAdapter(
  7910. std::move(content_provider_without_length));
  7911. req.is_chunked_content_provider_ = true;
  7912. req.set_header("Transfer-Encoding", "chunked");
  7913. } else {
  7914. req.body.assign(body, content_length);
  7915. }
  7916. }
  7917. auto res = detail::make_unique<Response>();
  7918. return send(req, *res, error) ? std::move(res) : nullptr;
  7919. }
  7920. inline Result ClientImpl::send_with_content_provider(
  7921. const std::string &method, const std::string &path, const Headers &headers,
  7922. const char *body, size_t content_length, ContentProvider content_provider,
  7923. ContentProviderWithoutLength content_provider_without_length,
  7924. const std::string &content_type, UploadProgress progress) {
  7925. Request req;
  7926. req.method = method;
  7927. req.headers = headers;
  7928. req.path = path;
  7929. req.upload_progress = std::move(progress);
  7930. if (max_timeout_msec_ > 0) {
  7931. req.start_time_ = std::chrono::steady_clock::now();
  7932. }
  7933. auto error = Error::Success;
  7934. auto res = send_with_content_provider(
  7935. req, body, content_length, std::move(content_provider),
  7936. std::move(content_provider_without_length), content_type, error);
  7937. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7938. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  7939. last_openssl_error_};
  7940. #else
  7941. return Result{std::move(res), error, std::move(req.headers)};
  7942. #endif
  7943. }
  7944. inline void ClientImpl::output_log(const Request &req,
  7945. const Response &res) const {
  7946. if (logger_) {
  7947. std::lock_guard<std::mutex> guard(logger_mutex_);
  7948. logger_(req, res);
  7949. }
  7950. }
  7951. inline void ClientImpl::output_error_log(const Error &err,
  7952. const Request *req) const {
  7953. if (error_logger_) {
  7954. std::lock_guard<std::mutex> guard(logger_mutex_);
  7955. error_logger_(err, req);
  7956. }
  7957. }
  7958. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  7959. Response &res, bool close_connection,
  7960. Error &error) {
  7961. // Send request
  7962. if (!write_request(strm, req, close_connection, error)) { return false; }
  7963. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7964. if (is_ssl()) {
  7965. auto is_proxy_enabled = !proxy_host_.empty() && proxy_port_ != -1;
  7966. if (!is_proxy_enabled) {
  7967. if (detail::is_ssl_peer_could_be_closed(socket_.ssl, socket_.sock)) {
  7968. error = Error::SSLPeerCouldBeClosed_;
  7969. output_error_log(error, &req);
  7970. return false;
  7971. }
  7972. }
  7973. }
  7974. #endif
  7975. // Receive response and headers
  7976. if (!read_response_line(strm, req, res) ||
  7977. !detail::read_headers(strm, res.headers)) {
  7978. error = Error::Read;
  7979. output_error_log(error, &req);
  7980. return false;
  7981. }
  7982. // Body
  7983. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  7984. req.method != "CONNECT") {
  7985. auto redirect = 300 < res.status && res.status < 400 &&
  7986. res.status != StatusCode::NotModified_304 &&
  7987. follow_location_;
  7988. if (req.response_handler && !redirect) {
  7989. if (!req.response_handler(res)) {
  7990. error = Error::Canceled;
  7991. output_error_log(error, &req);
  7992. return false;
  7993. }
  7994. }
  7995. auto out =
  7996. req.content_receiver
  7997. ? static_cast<ContentReceiverWithProgress>(
  7998. [&](const char *buf, size_t n, size_t off, size_t len) {
  7999. if (redirect) { return true; }
  8000. auto ret = req.content_receiver(buf, n, off, len);
  8001. if (!ret) {
  8002. error = Error::Canceled;
  8003. output_error_log(error, &req);
  8004. }
  8005. return ret;
  8006. })
  8007. : static_cast<ContentReceiverWithProgress>(
  8008. [&](const char *buf, size_t n, size_t /*off*/,
  8009. size_t /*len*/) {
  8010. assert(res.body.size() + n <= res.body.max_size());
  8011. res.body.append(buf, n);
  8012. return true;
  8013. });
  8014. auto progress = [&](size_t current, size_t total) {
  8015. if (!req.download_progress || redirect) { return true; }
  8016. auto ret = req.download_progress(current, total);
  8017. if (!ret) {
  8018. error = Error::Canceled;
  8019. output_error_log(error, &req);
  8020. }
  8021. return ret;
  8022. };
  8023. if (res.has_header("Content-Length")) {
  8024. if (!req.content_receiver) {
  8025. auto len = res.get_header_value_u64("Content-Length");
  8026. if (len > res.body.max_size()) {
  8027. error = Error::Read;
  8028. output_error_log(error, &req);
  8029. return false;
  8030. }
  8031. res.body.reserve(static_cast<size_t>(len));
  8032. }
  8033. }
  8034. if (res.status != StatusCode::NotModified_304) {
  8035. int dummy_status;
  8036. if (!detail::read_content(strm, res, (std::numeric_limits<size_t>::max)(),
  8037. dummy_status, std::move(progress),
  8038. std::move(out), decompress_)) {
  8039. if (error != Error::Canceled) { error = Error::Read; }
  8040. output_error_log(error, &req);
  8041. return false;
  8042. }
  8043. }
  8044. }
  8045. // Log
  8046. output_log(req, res);
  8047. return true;
  8048. }
  8049. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  8050. const std::string &boundary, const UploadFormDataItems &items,
  8051. const FormDataProviderItems &provider_items) const {
  8052. size_t cur_item = 0;
  8053. size_t cur_start = 0;
  8054. // cur_item and cur_start are copied to within the std::function and
  8055. // maintain state between successive calls
  8056. return [&, cur_item, cur_start](size_t offset,
  8057. DataSink &sink) mutable -> bool {
  8058. if (!offset && !items.empty()) {
  8059. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  8060. return true;
  8061. } else if (cur_item < provider_items.size()) {
  8062. if (!cur_start) {
  8063. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  8064. provider_items[cur_item], boundary);
  8065. offset += begin.size();
  8066. cur_start = offset;
  8067. sink.os << begin;
  8068. }
  8069. DataSink cur_sink;
  8070. auto has_data = true;
  8071. cur_sink.write = sink.write;
  8072. cur_sink.done = [&]() { has_data = false; };
  8073. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  8074. return false;
  8075. }
  8076. if (!has_data) {
  8077. sink.os << detail::serialize_multipart_formdata_item_end();
  8078. cur_item++;
  8079. cur_start = 0;
  8080. }
  8081. return true;
  8082. } else {
  8083. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  8084. sink.done();
  8085. return true;
  8086. }
  8087. };
  8088. }
  8089. inline bool ClientImpl::process_socket(
  8090. const Socket &socket,
  8091. std::chrono::time_point<std::chrono::steady_clock> start_time,
  8092. std::function<bool(Stream &strm)> callback) {
  8093. return detail::process_client_socket(
  8094. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  8095. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  8096. }
  8097. inline bool ClientImpl::is_ssl() const { return false; }
  8098. inline Result ClientImpl::Get(const std::string &path,
  8099. DownloadProgress progress) {
  8100. return Get(path, Headers(), std::move(progress));
  8101. }
  8102. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  8103. const Headers &headers,
  8104. DownloadProgress progress) {
  8105. if (params.empty()) { return Get(path, headers); }
  8106. std::string path_with_query = append_query_params(path, params);
  8107. return Get(path_with_query, headers, std::move(progress));
  8108. }
  8109. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  8110. DownloadProgress progress) {
  8111. Request req;
  8112. req.method = "GET";
  8113. req.path = path;
  8114. req.headers = headers;
  8115. req.download_progress = std::move(progress);
  8116. if (max_timeout_msec_ > 0) {
  8117. req.start_time_ = std::chrono::steady_clock::now();
  8118. }
  8119. return send_(std::move(req));
  8120. }
  8121. inline Result ClientImpl::Get(const std::string &path,
  8122. ContentReceiver content_receiver,
  8123. DownloadProgress progress) {
  8124. return Get(path, Headers(), nullptr, std::move(content_receiver),
  8125. std::move(progress));
  8126. }
  8127. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  8128. ContentReceiver content_receiver,
  8129. DownloadProgress progress) {
  8130. return Get(path, headers, nullptr, std::move(content_receiver),
  8131. std::move(progress));
  8132. }
  8133. inline Result ClientImpl::Get(const std::string &path,
  8134. ResponseHandler response_handler,
  8135. ContentReceiver content_receiver,
  8136. DownloadProgress progress) {
  8137. return Get(path, Headers(), std::move(response_handler),
  8138. std::move(content_receiver), std::move(progress));
  8139. }
  8140. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  8141. ResponseHandler response_handler,
  8142. ContentReceiver content_receiver,
  8143. DownloadProgress progress) {
  8144. Request req;
  8145. req.method = "GET";
  8146. req.path = path;
  8147. req.headers = headers;
  8148. req.response_handler = std::move(response_handler);
  8149. req.content_receiver =
  8150. [content_receiver](const char *data, size_t data_length,
  8151. size_t /*offset*/, size_t /*total_length*/) {
  8152. return content_receiver(data, data_length);
  8153. };
  8154. req.download_progress = std::move(progress);
  8155. if (max_timeout_msec_ > 0) {
  8156. req.start_time_ = std::chrono::steady_clock::now();
  8157. }
  8158. return send_(std::move(req));
  8159. }
  8160. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  8161. const Headers &headers,
  8162. ContentReceiver content_receiver,
  8163. DownloadProgress progress) {
  8164. return Get(path, params, headers, nullptr, std::move(content_receiver),
  8165. std::move(progress));
  8166. }
  8167. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  8168. const Headers &headers,
  8169. ResponseHandler response_handler,
  8170. ContentReceiver content_receiver,
  8171. DownloadProgress progress) {
  8172. if (params.empty()) {
  8173. return Get(path, headers, std::move(response_handler),
  8174. std::move(content_receiver), std::move(progress));
  8175. }
  8176. std::string path_with_query = append_query_params(path, params);
  8177. return Get(path_with_query, headers, std::move(response_handler),
  8178. std::move(content_receiver), std::move(progress));
  8179. }
  8180. inline Result ClientImpl::Head(const std::string &path) {
  8181. return Head(path, Headers());
  8182. }
  8183. inline Result ClientImpl::Head(const std::string &path,
  8184. const Headers &headers) {
  8185. Request req;
  8186. req.method = "HEAD";
  8187. req.headers = headers;
  8188. req.path = path;
  8189. if (max_timeout_msec_ > 0) {
  8190. req.start_time_ = std::chrono::steady_clock::now();
  8191. }
  8192. return send_(std::move(req));
  8193. }
  8194. inline Result ClientImpl::Post(const std::string &path) {
  8195. return Post(path, std::string(), std::string());
  8196. }
  8197. inline Result ClientImpl::Post(const std::string &path,
  8198. const Headers &headers) {
  8199. return Post(path, headers, nullptr, 0, std::string());
  8200. }
  8201. inline Result ClientImpl::Post(const std::string &path, const char *body,
  8202. size_t content_length,
  8203. const std::string &content_type,
  8204. UploadProgress progress) {
  8205. return Post(path, Headers(), body, content_length, content_type, progress);
  8206. }
  8207. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  8208. const std::string &content_type,
  8209. UploadProgress progress) {
  8210. return Post(path, Headers(), body, content_type, progress);
  8211. }
  8212. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  8213. return Post(path, Headers(), params);
  8214. }
  8215. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  8216. ContentProvider content_provider,
  8217. const std::string &content_type,
  8218. UploadProgress progress) {
  8219. return Post(path, Headers(), content_length, std::move(content_provider),
  8220. content_type, progress);
  8221. }
  8222. inline Result ClientImpl::Post(const std::string &path,
  8223. ContentProviderWithoutLength content_provider,
  8224. const std::string &content_type,
  8225. UploadProgress progress) {
  8226. return Post(path, Headers(), std::move(content_provider), content_type,
  8227. progress);
  8228. }
  8229. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  8230. const Params &params) {
  8231. auto query = detail::params_to_query_str(params);
  8232. return Post(path, headers, query, "application/x-www-form-urlencoded");
  8233. }
  8234. inline Result ClientImpl::Post(const std::string &path,
  8235. const UploadFormDataItems &items,
  8236. UploadProgress progress) {
  8237. return Post(path, Headers(), items, progress);
  8238. }
  8239. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  8240. const UploadFormDataItems &items,
  8241. UploadProgress progress) {
  8242. const auto &boundary = detail::make_multipart_data_boundary();
  8243. const auto &content_type =
  8244. detail::serialize_multipart_formdata_get_content_type(boundary);
  8245. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  8246. return Post(path, headers, body, content_type, progress);
  8247. }
  8248. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  8249. const UploadFormDataItems &items,
  8250. const std::string &boundary,
  8251. UploadProgress progress) {
  8252. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  8253. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  8254. }
  8255. const auto &content_type =
  8256. detail::serialize_multipart_formdata_get_content_type(boundary);
  8257. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  8258. return Post(path, headers, body, content_type, progress);
  8259. }
  8260. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  8261. const char *body, size_t content_length,
  8262. const std::string &content_type,
  8263. UploadProgress progress) {
  8264. return send_with_content_provider("POST", path, headers, body, content_length,
  8265. nullptr, nullptr, content_type, progress);
  8266. }
  8267. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  8268. const std::string &body,
  8269. const std::string &content_type,
  8270. UploadProgress progress) {
  8271. return send_with_content_provider("POST", path, headers, body.data(),
  8272. body.size(), nullptr, nullptr, content_type,
  8273. progress);
  8274. }
  8275. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  8276. size_t content_length,
  8277. ContentProvider content_provider,
  8278. const std::string &content_type,
  8279. UploadProgress progress) {
  8280. return send_with_content_provider("POST", path, headers, nullptr,
  8281. content_length, std::move(content_provider),
  8282. nullptr, content_type, progress);
  8283. }
  8284. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  8285. ContentProviderWithoutLength content_provider,
  8286. const std::string &content_type,
  8287. UploadProgress progress) {
  8288. return send_with_content_provider("POST", path, headers, nullptr, 0, nullptr,
  8289. std::move(content_provider), content_type,
  8290. progress);
  8291. }
  8292. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  8293. const UploadFormDataItems &items,
  8294. const FormDataProviderItems &provider_items,
  8295. UploadProgress progress) {
  8296. const auto &boundary = detail::make_multipart_data_boundary();
  8297. const auto &content_type =
  8298. detail::serialize_multipart_formdata_get_content_type(boundary);
  8299. return send_with_content_provider(
  8300. "POST", path, headers, nullptr, 0, nullptr,
  8301. get_multipart_content_provider(boundary, items, provider_items),
  8302. content_type, progress);
  8303. }
  8304. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  8305. const std::string &body,
  8306. const std::string &content_type,
  8307. ContentReceiver content_receiver,
  8308. DownloadProgress progress) {
  8309. Request req;
  8310. req.method = "POST";
  8311. req.path = path;
  8312. req.headers = headers;
  8313. req.body = body;
  8314. req.content_receiver =
  8315. [content_receiver](const char *data, size_t data_length,
  8316. size_t /*offset*/, size_t /*total_length*/) {
  8317. return content_receiver(data, data_length);
  8318. };
  8319. req.download_progress = std::move(progress);
  8320. if (max_timeout_msec_ > 0) {
  8321. req.start_time_ = std::chrono::steady_clock::now();
  8322. }
  8323. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  8324. return send_(std::move(req));
  8325. }
  8326. inline Result ClientImpl::Put(const std::string &path) {
  8327. return Put(path, std::string(), std::string());
  8328. }
  8329. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  8330. return Put(path, headers, nullptr, 0, std::string());
  8331. }
  8332. inline Result ClientImpl::Put(const std::string &path, const char *body,
  8333. size_t content_length,
  8334. const std::string &content_type,
  8335. UploadProgress progress) {
  8336. return Put(path, Headers(), body, content_length, content_type, progress);
  8337. }
  8338. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  8339. const std::string &content_type,
  8340. UploadProgress progress) {
  8341. return Put(path, Headers(), body, content_type, progress);
  8342. }
  8343. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  8344. return Put(path, Headers(), params);
  8345. }
  8346. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  8347. ContentProvider content_provider,
  8348. const std::string &content_type,
  8349. UploadProgress progress) {
  8350. return Put(path, Headers(), content_length, std::move(content_provider),
  8351. content_type, progress);
  8352. }
  8353. inline Result ClientImpl::Put(const std::string &path,
  8354. ContentProviderWithoutLength content_provider,
  8355. const std::string &content_type,
  8356. UploadProgress progress) {
  8357. return Put(path, Headers(), std::move(content_provider), content_type,
  8358. progress);
  8359. }
  8360. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  8361. const Params &params) {
  8362. auto query = detail::params_to_query_str(params);
  8363. return Put(path, headers, query, "application/x-www-form-urlencoded");
  8364. }
  8365. inline Result ClientImpl::Put(const std::string &path,
  8366. const UploadFormDataItems &items,
  8367. UploadProgress progress) {
  8368. return Put(path, Headers(), items, progress);
  8369. }
  8370. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  8371. const UploadFormDataItems &items,
  8372. UploadProgress progress) {
  8373. const auto &boundary = detail::make_multipart_data_boundary();
  8374. const auto &content_type =
  8375. detail::serialize_multipart_formdata_get_content_type(boundary);
  8376. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  8377. return Put(path, headers, body, content_type, progress);
  8378. }
  8379. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  8380. const UploadFormDataItems &items,
  8381. const std::string &boundary,
  8382. UploadProgress progress) {
  8383. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  8384. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  8385. }
  8386. const auto &content_type =
  8387. detail::serialize_multipart_formdata_get_content_type(boundary);
  8388. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  8389. return Put(path, headers, body, content_type, progress);
  8390. }
  8391. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  8392. const char *body, size_t content_length,
  8393. const std::string &content_type,
  8394. UploadProgress progress) {
  8395. return send_with_content_provider("PUT", path, headers, body, content_length,
  8396. nullptr, nullptr, content_type, progress);
  8397. }
  8398. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  8399. const std::string &body,
  8400. const std::string &content_type,
  8401. UploadProgress progress) {
  8402. return send_with_content_provider("PUT", path, headers, body.data(),
  8403. body.size(), nullptr, nullptr, content_type,
  8404. progress);
  8405. }
  8406. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  8407. size_t content_length,
  8408. ContentProvider content_provider,
  8409. const std::string &content_type,
  8410. UploadProgress progress) {
  8411. return send_with_content_provider("PUT", path, headers, nullptr,
  8412. content_length, std::move(content_provider),
  8413. nullptr, content_type, progress);
  8414. }
  8415. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  8416. ContentProviderWithoutLength content_provider,
  8417. const std::string &content_type,
  8418. UploadProgress progress) {
  8419. return send_with_content_provider("PUT", path, headers, nullptr, 0, nullptr,
  8420. std::move(content_provider), content_type,
  8421. progress);
  8422. }
  8423. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  8424. const UploadFormDataItems &items,
  8425. const FormDataProviderItems &provider_items,
  8426. UploadProgress progress) {
  8427. const auto &boundary = detail::make_multipart_data_boundary();
  8428. const auto &content_type =
  8429. detail::serialize_multipart_formdata_get_content_type(boundary);
  8430. return send_with_content_provider(
  8431. "PUT", path, headers, nullptr, 0, nullptr,
  8432. get_multipart_content_provider(boundary, items, provider_items),
  8433. content_type, progress);
  8434. }
  8435. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  8436. const std::string &body,
  8437. const std::string &content_type,
  8438. ContentReceiver content_receiver,
  8439. DownloadProgress progress) {
  8440. Request req;
  8441. req.method = "PUT";
  8442. req.path = path;
  8443. req.headers = headers;
  8444. req.body = body;
  8445. req.content_receiver =
  8446. [content_receiver](const char *data, size_t data_length,
  8447. size_t /*offset*/, size_t /*total_length*/) {
  8448. return content_receiver(data, data_length);
  8449. };
  8450. req.download_progress = std::move(progress);
  8451. if (max_timeout_msec_ > 0) {
  8452. req.start_time_ = std::chrono::steady_clock::now();
  8453. }
  8454. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  8455. return send_(std::move(req));
  8456. }
  8457. inline Result ClientImpl::Patch(const std::string &path) {
  8458. return Patch(path, std::string(), std::string());
  8459. }
  8460. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8461. UploadProgress progress) {
  8462. return Patch(path, headers, nullptr, 0, std::string(), progress);
  8463. }
  8464. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  8465. size_t content_length,
  8466. const std::string &content_type,
  8467. UploadProgress progress) {
  8468. return Patch(path, Headers(), body, content_length, content_type, progress);
  8469. }
  8470. inline Result ClientImpl::Patch(const std::string &path,
  8471. const std::string &body,
  8472. const std::string &content_type,
  8473. UploadProgress progress) {
  8474. return Patch(path, Headers(), body, content_type, progress);
  8475. }
  8476. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  8477. return Patch(path, Headers(), params);
  8478. }
  8479. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  8480. ContentProvider content_provider,
  8481. const std::string &content_type,
  8482. UploadProgress progress) {
  8483. return Patch(path, Headers(), content_length, std::move(content_provider),
  8484. content_type, progress);
  8485. }
  8486. inline Result ClientImpl::Patch(const std::string &path,
  8487. ContentProviderWithoutLength content_provider,
  8488. const std::string &content_type,
  8489. UploadProgress progress) {
  8490. return Patch(path, Headers(), std::move(content_provider), content_type,
  8491. progress);
  8492. }
  8493. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8494. const Params &params) {
  8495. auto query = detail::params_to_query_str(params);
  8496. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  8497. }
  8498. inline Result ClientImpl::Patch(const std::string &path,
  8499. const UploadFormDataItems &items,
  8500. UploadProgress progress) {
  8501. return Patch(path, Headers(), items, progress);
  8502. }
  8503. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8504. const UploadFormDataItems &items,
  8505. UploadProgress progress) {
  8506. const auto &boundary = detail::make_multipart_data_boundary();
  8507. const auto &content_type =
  8508. detail::serialize_multipart_formdata_get_content_type(boundary);
  8509. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  8510. return Patch(path, headers, body, content_type, progress);
  8511. }
  8512. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8513. const UploadFormDataItems &items,
  8514. const std::string &boundary,
  8515. UploadProgress progress) {
  8516. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  8517. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  8518. }
  8519. const auto &content_type =
  8520. detail::serialize_multipart_formdata_get_content_type(boundary);
  8521. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  8522. return Patch(path, headers, body, content_type, progress);
  8523. }
  8524. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8525. const char *body, size_t content_length,
  8526. const std::string &content_type,
  8527. UploadProgress progress) {
  8528. return send_with_content_provider("PATCH", path, headers, body,
  8529. content_length, nullptr, nullptr,
  8530. content_type, progress);
  8531. }
  8532. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8533. const std::string &body,
  8534. const std::string &content_type,
  8535. UploadProgress progress) {
  8536. return send_with_content_provider("PATCH", path, headers, body.data(),
  8537. body.size(), nullptr, nullptr, content_type,
  8538. progress);
  8539. }
  8540. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8541. size_t content_length,
  8542. ContentProvider content_provider,
  8543. const std::string &content_type,
  8544. UploadProgress progress) {
  8545. return send_with_content_provider("PATCH", path, headers, nullptr,
  8546. content_length, std::move(content_provider),
  8547. nullptr, content_type, progress);
  8548. }
  8549. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8550. ContentProviderWithoutLength content_provider,
  8551. const std::string &content_type,
  8552. UploadProgress progress) {
  8553. return send_with_content_provider("PATCH", path, headers, nullptr, 0, nullptr,
  8554. std::move(content_provider), content_type,
  8555. progress);
  8556. }
  8557. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8558. const UploadFormDataItems &items,
  8559. const FormDataProviderItems &provider_items,
  8560. UploadProgress progress) {
  8561. const auto &boundary = detail::make_multipart_data_boundary();
  8562. const auto &content_type =
  8563. detail::serialize_multipart_formdata_get_content_type(boundary);
  8564. return send_with_content_provider(
  8565. "PATCH", path, headers, nullptr, 0, nullptr,
  8566. get_multipart_content_provider(boundary, items, provider_items),
  8567. content_type, progress);
  8568. }
  8569. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8570. const std::string &body,
  8571. const std::string &content_type,
  8572. ContentReceiver content_receiver,
  8573. DownloadProgress progress) {
  8574. Request req;
  8575. req.method = "PATCH";
  8576. req.path = path;
  8577. req.headers = headers;
  8578. req.body = body;
  8579. req.content_receiver =
  8580. [content_receiver](const char *data, size_t data_length,
  8581. size_t /*offset*/, size_t /*total_length*/) {
  8582. return content_receiver(data, data_length);
  8583. };
  8584. req.download_progress = std::move(progress);
  8585. if (max_timeout_msec_ > 0) {
  8586. req.start_time_ = std::chrono::steady_clock::now();
  8587. }
  8588. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  8589. return send_(std::move(req));
  8590. }
  8591. inline Result ClientImpl::Delete(const std::string &path,
  8592. DownloadProgress progress) {
  8593. return Delete(path, Headers(), std::string(), std::string(), progress);
  8594. }
  8595. inline Result ClientImpl::Delete(const std::string &path,
  8596. const Headers &headers,
  8597. DownloadProgress progress) {
  8598. return Delete(path, headers, std::string(), std::string(), progress);
  8599. }
  8600. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  8601. size_t content_length,
  8602. const std::string &content_type,
  8603. DownloadProgress progress) {
  8604. return Delete(path, Headers(), body, content_length, content_type, progress);
  8605. }
  8606. inline Result ClientImpl::Delete(const std::string &path,
  8607. const std::string &body,
  8608. const std::string &content_type,
  8609. DownloadProgress progress) {
  8610. return Delete(path, Headers(), body.data(), body.size(), content_type,
  8611. progress);
  8612. }
  8613. inline Result ClientImpl::Delete(const std::string &path,
  8614. const Headers &headers,
  8615. const std::string &body,
  8616. const std::string &content_type,
  8617. DownloadProgress progress) {
  8618. return Delete(path, headers, body.data(), body.size(), content_type,
  8619. progress);
  8620. }
  8621. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  8622. DownloadProgress progress) {
  8623. return Delete(path, Headers(), params, progress);
  8624. }
  8625. inline Result ClientImpl::Delete(const std::string &path,
  8626. const Headers &headers, const Params &params,
  8627. DownloadProgress progress) {
  8628. auto query = detail::params_to_query_str(params);
  8629. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  8630. progress);
  8631. }
  8632. inline Result ClientImpl::Delete(const std::string &path,
  8633. const Headers &headers, const char *body,
  8634. size_t content_length,
  8635. const std::string &content_type,
  8636. DownloadProgress progress) {
  8637. Request req;
  8638. req.method = "DELETE";
  8639. req.headers = headers;
  8640. req.path = path;
  8641. req.download_progress = std::move(progress);
  8642. if (max_timeout_msec_ > 0) {
  8643. req.start_time_ = std::chrono::steady_clock::now();
  8644. }
  8645. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  8646. req.body.assign(body, content_length);
  8647. return send_(std::move(req));
  8648. }
  8649. inline Result ClientImpl::Options(const std::string &path) {
  8650. return Options(path, Headers());
  8651. }
  8652. inline Result ClientImpl::Options(const std::string &path,
  8653. const Headers &headers) {
  8654. Request req;
  8655. req.method = "OPTIONS";
  8656. req.headers = headers;
  8657. req.path = path;
  8658. if (max_timeout_msec_ > 0) {
  8659. req.start_time_ = std::chrono::steady_clock::now();
  8660. }
  8661. return send_(std::move(req));
  8662. }
  8663. inline void ClientImpl::stop() {
  8664. std::lock_guard<std::mutex> guard(socket_mutex_);
  8665. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  8666. // do is to shutdown_socket, so that threads using this socket suddenly
  8667. // discover they can't read/write any more and error out. Everything else
  8668. // (closing the socket, shutting ssl down) is unsafe because these actions
  8669. // are not thread-safe.
  8670. if (socket_requests_in_flight_ > 0) {
  8671. shutdown_socket(socket_);
  8672. // Aside from that, we set a flag for the socket to be closed when we're
  8673. // done.
  8674. socket_should_be_closed_when_request_is_done_ = true;
  8675. return;
  8676. }
  8677. // Otherwise, still holding the mutex, we can shut everything down ourselves
  8678. shutdown_ssl(socket_, true);
  8679. shutdown_socket(socket_);
  8680. close_socket(socket_);
  8681. }
  8682. inline std::string ClientImpl::host() const { return host_; }
  8683. inline int ClientImpl::port() const { return port_; }
  8684. inline size_t ClientImpl::is_socket_open() const {
  8685. std::lock_guard<std::mutex> guard(socket_mutex_);
  8686. return socket_.is_open();
  8687. }
  8688. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  8689. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  8690. connection_timeout_sec_ = sec;
  8691. connection_timeout_usec_ = usec;
  8692. }
  8693. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  8694. read_timeout_sec_ = sec;
  8695. read_timeout_usec_ = usec;
  8696. }
  8697. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  8698. write_timeout_sec_ = sec;
  8699. write_timeout_usec_ = usec;
  8700. }
  8701. inline void ClientImpl::set_max_timeout(time_t msec) {
  8702. max_timeout_msec_ = msec;
  8703. }
  8704. inline void ClientImpl::set_basic_auth(const std::string &username,
  8705. const std::string &password) {
  8706. basic_auth_username_ = username;
  8707. basic_auth_password_ = password;
  8708. }
  8709. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  8710. bearer_token_auth_token_ = token;
  8711. }
  8712. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8713. inline void ClientImpl::set_digest_auth(const std::string &username,
  8714. const std::string &password) {
  8715. digest_auth_username_ = username;
  8716. digest_auth_password_ = password;
  8717. }
  8718. #endif
  8719. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  8720. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  8721. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  8722. inline void
  8723. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  8724. addr_map_ = std::move(addr_map);
  8725. }
  8726. inline void ClientImpl::set_default_headers(Headers headers) {
  8727. default_headers_ = std::move(headers);
  8728. }
  8729. inline void ClientImpl::set_header_writer(
  8730. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  8731. header_writer_ = writer;
  8732. }
  8733. inline void ClientImpl::set_address_family(int family) {
  8734. address_family_ = family;
  8735. }
  8736. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  8737. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  8738. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  8739. socket_options_ = std::move(socket_options);
  8740. }
  8741. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  8742. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  8743. inline void ClientImpl::set_interface(const std::string &intf) {
  8744. interface_ = intf;
  8745. }
  8746. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  8747. proxy_host_ = host;
  8748. proxy_port_ = port;
  8749. }
  8750. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  8751. const std::string &password) {
  8752. proxy_basic_auth_username_ = username;
  8753. proxy_basic_auth_password_ = password;
  8754. }
  8755. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  8756. proxy_bearer_token_auth_token_ = token;
  8757. }
  8758. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8759. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  8760. const std::string &password) {
  8761. proxy_digest_auth_username_ = username;
  8762. proxy_digest_auth_password_ = password;
  8763. }
  8764. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  8765. const std::string &ca_cert_dir_path) {
  8766. ca_cert_file_path_ = ca_cert_file_path;
  8767. ca_cert_dir_path_ = ca_cert_dir_path;
  8768. }
  8769. inline void ClientImpl::set_ca_cert_store(X509_STORE *ca_cert_store) {
  8770. if (ca_cert_store && ca_cert_store != ca_cert_store_) {
  8771. ca_cert_store_ = ca_cert_store;
  8772. }
  8773. }
  8774. inline X509_STORE *ClientImpl::create_ca_cert_store(const char *ca_cert,
  8775. std::size_t size) const {
  8776. auto mem = BIO_new_mem_buf(ca_cert, static_cast<int>(size));
  8777. auto se = detail::scope_exit([&] { BIO_free_all(mem); });
  8778. if (!mem) { return nullptr; }
  8779. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  8780. if (!inf) { return nullptr; }
  8781. auto cts = X509_STORE_new();
  8782. if (cts) {
  8783. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  8784. auto itmp = sk_X509_INFO_value(inf, i);
  8785. if (!itmp) { continue; }
  8786. if (itmp->x509) { X509_STORE_add_cert(cts, itmp->x509); }
  8787. if (itmp->crl) { X509_STORE_add_crl(cts, itmp->crl); }
  8788. }
  8789. }
  8790. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  8791. return cts;
  8792. }
  8793. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  8794. server_certificate_verification_ = enabled;
  8795. }
  8796. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  8797. server_hostname_verification_ = enabled;
  8798. }
  8799. inline void ClientImpl::set_server_certificate_verifier(
  8800. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  8801. server_certificate_verifier_ = verifier;
  8802. }
  8803. #endif
  8804. inline void ClientImpl::set_logger(Logger logger) {
  8805. logger_ = std::move(logger);
  8806. }
  8807. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  8808. error_logger_ = std::move(error_logger);
  8809. }
  8810. /*
  8811. * SSL Implementation
  8812. */
  8813. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8814. namespace detail {
  8815. inline bool is_ip_address(const std::string &host) {
  8816. struct in_addr addr4;
  8817. struct in6_addr addr6;
  8818. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  8819. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  8820. }
  8821. template <typename U, typename V>
  8822. inline SSL *ssl_new(socket_t sock, SSL_CTX *ctx, std::mutex &ctx_mutex,
  8823. U SSL_connect_or_accept, V setup) {
  8824. SSL *ssl = nullptr;
  8825. {
  8826. std::lock_guard<std::mutex> guard(ctx_mutex);
  8827. ssl = SSL_new(ctx);
  8828. }
  8829. if (ssl) {
  8830. set_nonblocking(sock, true);
  8831. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  8832. BIO_set_nbio(bio, 1);
  8833. SSL_set_bio(ssl, bio, bio);
  8834. if (!setup(ssl) || SSL_connect_or_accept(ssl) != 1) {
  8835. SSL_shutdown(ssl);
  8836. {
  8837. std::lock_guard<std::mutex> guard(ctx_mutex);
  8838. SSL_free(ssl);
  8839. }
  8840. set_nonblocking(sock, false);
  8841. return nullptr;
  8842. }
  8843. BIO_set_nbio(bio, 0);
  8844. set_nonblocking(sock, false);
  8845. }
  8846. return ssl;
  8847. }
  8848. inline void ssl_delete(std::mutex &ctx_mutex, SSL *ssl, socket_t sock,
  8849. bool shutdown_gracefully) {
  8850. // sometimes we may want to skip this to try to avoid SIGPIPE if we know
  8851. // the remote has closed the network connection
  8852. // Note that it is not always possible to avoid SIGPIPE, this is merely a
  8853. // best-efforts.
  8854. if (shutdown_gracefully) {
  8855. (void)(sock);
  8856. // SSL_shutdown() returns 0 on first call (indicating close_notify alert
  8857. // sent) and 1 on subsequent call (indicating close_notify alert received)
  8858. if (SSL_shutdown(ssl) == 0) {
  8859. // Expected to return 1, but even if it doesn't, we free ssl
  8860. SSL_shutdown(ssl);
  8861. }
  8862. }
  8863. std::lock_guard<std::mutex> guard(ctx_mutex);
  8864. SSL_free(ssl);
  8865. }
  8866. template <typename U>
  8867. bool ssl_connect_or_accept_nonblocking(socket_t sock, SSL *ssl,
  8868. U ssl_connect_or_accept,
  8869. time_t timeout_sec, time_t timeout_usec,
  8870. int *ssl_error) {
  8871. auto res = 0;
  8872. while ((res = ssl_connect_or_accept(ssl)) != 1) {
  8873. auto err = SSL_get_error(ssl, res);
  8874. switch (err) {
  8875. case SSL_ERROR_WANT_READ:
  8876. if (select_read(sock, timeout_sec, timeout_usec) > 0) { continue; }
  8877. break;
  8878. case SSL_ERROR_WANT_WRITE:
  8879. if (select_write(sock, timeout_sec, timeout_usec) > 0) { continue; }
  8880. break;
  8881. default: break;
  8882. }
  8883. if (ssl_error) { *ssl_error = err; }
  8884. return false;
  8885. }
  8886. return true;
  8887. }
  8888. template <typename T>
  8889. inline bool process_server_socket_ssl(
  8890. const std::atomic<socket_t> &svr_sock, SSL *ssl, socket_t sock,
  8891. size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  8892. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  8893. time_t write_timeout_usec, T callback) {
  8894. return process_server_socket_core(
  8895. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  8896. [&](bool close_connection, bool &connection_closed) {
  8897. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
  8898. write_timeout_sec, write_timeout_usec);
  8899. return callback(strm, close_connection, connection_closed);
  8900. });
  8901. }
  8902. template <typename T>
  8903. inline bool process_client_socket_ssl(
  8904. SSL *ssl, socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  8905. time_t write_timeout_sec, time_t write_timeout_usec,
  8906. time_t max_timeout_msec,
  8907. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  8908. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
  8909. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  8910. start_time);
  8911. return callback(strm);
  8912. }
  8913. // SSL socket stream implementation
  8914. inline SSLSocketStream::SSLSocketStream(
  8915. socket_t sock, SSL *ssl, time_t read_timeout_sec, time_t read_timeout_usec,
  8916. time_t write_timeout_sec, time_t write_timeout_usec,
  8917. time_t max_timeout_msec,
  8918. std::chrono::time_point<std::chrono::steady_clock> start_time)
  8919. : sock_(sock), ssl_(ssl), read_timeout_sec_(read_timeout_sec),
  8920. read_timeout_usec_(read_timeout_usec),
  8921. write_timeout_sec_(write_timeout_sec),
  8922. write_timeout_usec_(write_timeout_usec),
  8923. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  8924. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  8925. }
  8926. inline SSLSocketStream::~SSLSocketStream() = default;
  8927. inline bool SSLSocketStream::is_readable() const {
  8928. return SSL_pending(ssl_) > 0;
  8929. }
  8930. inline bool SSLSocketStream::wait_readable() const {
  8931. if (max_timeout_msec_ <= 0) {
  8932. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  8933. }
  8934. time_t read_timeout_sec;
  8935. time_t read_timeout_usec;
  8936. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  8937. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  8938. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  8939. }
  8940. inline bool SSLSocketStream::wait_writable() const {
  8941. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  8942. is_socket_alive(sock_) && !is_ssl_peer_could_be_closed(ssl_, sock_);
  8943. }
  8944. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  8945. if (SSL_pending(ssl_) > 0) {
  8946. return SSL_read(ssl_, ptr, static_cast<int>(size));
  8947. } else if (wait_readable()) {
  8948. auto ret = SSL_read(ssl_, ptr, static_cast<int>(size));
  8949. if (ret < 0) {
  8950. auto err = SSL_get_error(ssl_, ret);
  8951. auto n = 1000;
  8952. #ifdef _WIN32
  8953. while (--n >= 0 && (err == SSL_ERROR_WANT_READ ||
  8954. (err == SSL_ERROR_SYSCALL &&
  8955. WSAGetLastError() == WSAETIMEDOUT))) {
  8956. #else
  8957. while (--n >= 0 && err == SSL_ERROR_WANT_READ) {
  8958. #endif
  8959. if (SSL_pending(ssl_) > 0) {
  8960. return SSL_read(ssl_, ptr, static_cast<int>(size));
  8961. } else if (wait_readable()) {
  8962. std::this_thread::sleep_for(std::chrono::microseconds{10});
  8963. ret = SSL_read(ssl_, ptr, static_cast<int>(size));
  8964. if (ret >= 0) { return ret; }
  8965. err = SSL_get_error(ssl_, ret);
  8966. } else {
  8967. break;
  8968. }
  8969. }
  8970. assert(ret < 0);
  8971. }
  8972. return ret;
  8973. } else {
  8974. return -1;
  8975. }
  8976. }
  8977. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  8978. if (wait_writable()) {
  8979. auto handle_size = static_cast<int>(
  8980. std::min<size_t>(size, (std::numeric_limits<int>::max)()));
  8981. auto ret = SSL_write(ssl_, ptr, static_cast<int>(handle_size));
  8982. if (ret < 0) {
  8983. auto err = SSL_get_error(ssl_, ret);
  8984. auto n = 1000;
  8985. #ifdef _WIN32
  8986. while (--n >= 0 && (err == SSL_ERROR_WANT_WRITE ||
  8987. (err == SSL_ERROR_SYSCALL &&
  8988. WSAGetLastError() == WSAETIMEDOUT))) {
  8989. #else
  8990. while (--n >= 0 && err == SSL_ERROR_WANT_WRITE) {
  8991. #endif
  8992. if (wait_writable()) {
  8993. std::this_thread::sleep_for(std::chrono::microseconds{10});
  8994. ret = SSL_write(ssl_, ptr, static_cast<int>(handle_size));
  8995. if (ret >= 0) { return ret; }
  8996. err = SSL_get_error(ssl_, ret);
  8997. } else {
  8998. break;
  8999. }
  9000. }
  9001. assert(ret < 0);
  9002. }
  9003. return ret;
  9004. }
  9005. return -1;
  9006. }
  9007. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  9008. int &port) const {
  9009. detail::get_remote_ip_and_port(sock_, ip, port);
  9010. }
  9011. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  9012. int &port) const {
  9013. detail::get_local_ip_and_port(sock_, ip, port);
  9014. }
  9015. inline socket_t SSLSocketStream::socket() const { return sock_; }
  9016. inline time_t SSLSocketStream::duration() const {
  9017. return std::chrono::duration_cast<std::chrono::milliseconds>(
  9018. std::chrono::steady_clock::now() - start_time_)
  9019. .count();
  9020. }
  9021. } // namespace detail
  9022. // SSL HTTP server implementation
  9023. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  9024. const char *client_ca_cert_file_path,
  9025. const char *client_ca_cert_dir_path,
  9026. const char *private_key_password) {
  9027. ctx_ = SSL_CTX_new(TLS_server_method());
  9028. if (ctx_) {
  9029. SSL_CTX_set_options(ctx_,
  9030. SSL_OP_NO_COMPRESSION |
  9031. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  9032. SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  9033. if (private_key_password != nullptr && (private_key_password[0] != '\0')) {
  9034. SSL_CTX_set_default_passwd_cb_userdata(
  9035. ctx_,
  9036. reinterpret_cast<void *>(const_cast<char *>(private_key_password)));
  9037. }
  9038. if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 ||
  9039. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) !=
  9040. 1 ||
  9041. SSL_CTX_check_private_key(ctx_) != 1) {
  9042. last_ssl_error_ = static_cast<int>(ERR_get_error());
  9043. SSL_CTX_free(ctx_);
  9044. ctx_ = nullptr;
  9045. } else if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  9046. SSL_CTX_load_verify_locations(ctx_, client_ca_cert_file_path,
  9047. client_ca_cert_dir_path);
  9048. // Set client CA list to be sent to clients during TLS handshake
  9049. if (client_ca_cert_file_path) {
  9050. auto ca_list = SSL_load_client_CA_file(client_ca_cert_file_path);
  9051. if (ca_list != nullptr) {
  9052. SSL_CTX_set_client_CA_list(ctx_, ca_list);
  9053. } else {
  9054. // Failed to load client CA list, but we continue since
  9055. // SSL_CTX_load_verify_locations already succeeded and
  9056. // certificate verification will still work
  9057. last_ssl_error_ = static_cast<int>(ERR_get_error());
  9058. }
  9059. }
  9060. SSL_CTX_set_verify(
  9061. ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
  9062. }
  9063. }
  9064. }
  9065. inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key,
  9066. X509_STORE *client_ca_cert_store) {
  9067. ctx_ = SSL_CTX_new(TLS_server_method());
  9068. if (ctx_) {
  9069. SSL_CTX_set_options(ctx_,
  9070. SSL_OP_NO_COMPRESSION |
  9071. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  9072. SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  9073. if (SSL_CTX_use_certificate(ctx_, cert) != 1 ||
  9074. SSL_CTX_use_PrivateKey(ctx_, private_key) != 1) {
  9075. SSL_CTX_free(ctx_);
  9076. ctx_ = nullptr;
  9077. } else if (client_ca_cert_store) {
  9078. SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
  9079. // Extract CA names from the store and set them as the client CA list
  9080. auto ca_list = extract_ca_names_from_x509_store(client_ca_cert_store);
  9081. if (ca_list) {
  9082. SSL_CTX_set_client_CA_list(ctx_, ca_list);
  9083. } else {
  9084. // Failed to extract CA names, record the error
  9085. last_ssl_error_ = static_cast<int>(ERR_get_error());
  9086. }
  9087. SSL_CTX_set_verify(
  9088. ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
  9089. }
  9090. }
  9091. }
  9092. inline SSLServer::SSLServer(
  9093. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback) {
  9094. ctx_ = SSL_CTX_new(TLS_method());
  9095. if (ctx_) {
  9096. if (!setup_ssl_ctx_callback(*ctx_)) {
  9097. SSL_CTX_free(ctx_);
  9098. ctx_ = nullptr;
  9099. }
  9100. }
  9101. }
  9102. inline SSLServer::~SSLServer() {
  9103. if (ctx_) { SSL_CTX_free(ctx_); }
  9104. }
  9105. inline bool SSLServer::is_valid() const { return ctx_; }
  9106. inline SSL_CTX *SSLServer::ssl_context() const { return ctx_; }
  9107. inline void SSLServer::update_certs(X509 *cert, EVP_PKEY *private_key,
  9108. X509_STORE *client_ca_cert_store) {
  9109. std::lock_guard<std::mutex> guard(ctx_mutex_);
  9110. SSL_CTX_use_certificate(ctx_, cert);
  9111. SSL_CTX_use_PrivateKey(ctx_, private_key);
  9112. if (client_ca_cert_store != nullptr) {
  9113. SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
  9114. }
  9115. }
  9116. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  9117. auto ssl = detail::ssl_new(
  9118. sock, ctx_, ctx_mutex_,
  9119. [&](SSL *ssl2) {
  9120. return detail::ssl_connect_or_accept_nonblocking(
  9121. sock, ssl2, SSL_accept, read_timeout_sec_, read_timeout_usec_,
  9122. &last_ssl_error_);
  9123. },
  9124. [](SSL * /*ssl2*/) { return true; });
  9125. auto ret = false;
  9126. if (ssl) {
  9127. std::string remote_addr;
  9128. int remote_port = 0;
  9129. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  9130. std::string local_addr;
  9131. int local_port = 0;
  9132. detail::get_local_ip_and_port(sock, local_addr, local_port);
  9133. ret = detail::process_server_socket_ssl(
  9134. svr_sock_, ssl, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  9135. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  9136. write_timeout_usec_,
  9137. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  9138. return process_request(strm, remote_addr, remote_port, local_addr,
  9139. local_port, close_connection,
  9140. connection_closed,
  9141. [&](Request &req) { req.ssl = ssl; });
  9142. });
  9143. // Shutdown gracefully if the result seemed successful, non-gracefully if
  9144. // the connection appeared to be closed.
  9145. const bool shutdown_gracefully = ret;
  9146. detail::ssl_delete(ctx_mutex_, ssl, sock, shutdown_gracefully);
  9147. }
  9148. detail::shutdown_socket(sock);
  9149. detail::close_socket(sock);
  9150. return ret;
  9151. }
  9152. inline STACK_OF(X509_NAME) * SSLServer::extract_ca_names_from_x509_store(
  9153. X509_STORE *store) {
  9154. if (!store) { return nullptr; }
  9155. auto ca_list = sk_X509_NAME_new_null();
  9156. if (!ca_list) { return nullptr; }
  9157. // Get all objects from the store
  9158. auto objs = X509_STORE_get0_objects(store);
  9159. if (!objs) {
  9160. sk_X509_NAME_free(ca_list);
  9161. return nullptr;
  9162. }
  9163. // Iterate through objects and extract certificate subject names
  9164. for (int i = 0; i < sk_X509_OBJECT_num(objs); i++) {
  9165. auto obj = sk_X509_OBJECT_value(objs, i);
  9166. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  9167. auto cert = X509_OBJECT_get0_X509(obj);
  9168. if (cert) {
  9169. auto subject = X509_get_subject_name(cert);
  9170. if (subject) {
  9171. auto name_dup = X509_NAME_dup(subject);
  9172. if (name_dup) { sk_X509_NAME_push(ca_list, name_dup); }
  9173. }
  9174. }
  9175. }
  9176. }
  9177. // If no names were extracted, free the list and return nullptr
  9178. if (sk_X509_NAME_num(ca_list) == 0) {
  9179. sk_X509_NAME_free(ca_list);
  9180. return nullptr;
  9181. }
  9182. return ca_list;
  9183. }
  9184. // SSL HTTP client implementation
  9185. inline SSLClient::SSLClient(const std::string &host)
  9186. : SSLClient(host, 443, std::string(), std::string()) {}
  9187. inline SSLClient::SSLClient(const std::string &host, int port)
  9188. : SSLClient(host, port, std::string(), std::string()) {}
  9189. inline SSLClient::SSLClient(const std::string &host, int port,
  9190. const std::string &client_cert_path,
  9191. const std::string &client_key_path,
  9192. const std::string &private_key_password)
  9193. : ClientImpl(host, port, client_cert_path, client_key_path) {
  9194. ctx_ = SSL_CTX_new(TLS_client_method());
  9195. SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  9196. detail::split(&host_[0], &host_[host_.size()], '.',
  9197. [&](const char *b, const char *e) {
  9198. host_components_.emplace_back(b, e);
  9199. });
  9200. if (!client_cert_path.empty() && !client_key_path.empty()) {
  9201. if (!private_key_password.empty()) {
  9202. SSL_CTX_set_default_passwd_cb_userdata(
  9203. ctx_, reinterpret_cast<void *>(
  9204. const_cast<char *>(private_key_password.c_str())));
  9205. }
  9206. if (SSL_CTX_use_certificate_file(ctx_, client_cert_path.c_str(),
  9207. SSL_FILETYPE_PEM) != 1 ||
  9208. SSL_CTX_use_PrivateKey_file(ctx_, client_key_path.c_str(),
  9209. SSL_FILETYPE_PEM) != 1) {
  9210. last_openssl_error_ = ERR_get_error();
  9211. SSL_CTX_free(ctx_);
  9212. ctx_ = nullptr;
  9213. }
  9214. }
  9215. }
  9216. inline SSLClient::SSLClient(const std::string &host, int port,
  9217. X509 *client_cert, EVP_PKEY *client_key,
  9218. const std::string &private_key_password)
  9219. : ClientImpl(host, port) {
  9220. ctx_ = SSL_CTX_new(TLS_client_method());
  9221. detail::split(&host_[0], &host_[host_.size()], '.',
  9222. [&](const char *b, const char *e) {
  9223. host_components_.emplace_back(b, e);
  9224. });
  9225. if (client_cert != nullptr && client_key != nullptr) {
  9226. if (!private_key_password.empty()) {
  9227. SSL_CTX_set_default_passwd_cb_userdata(
  9228. ctx_, reinterpret_cast<void *>(
  9229. const_cast<char *>(private_key_password.c_str())));
  9230. }
  9231. if (SSL_CTX_use_certificate(ctx_, client_cert) != 1 ||
  9232. SSL_CTX_use_PrivateKey(ctx_, client_key) != 1) {
  9233. last_openssl_error_ = ERR_get_error();
  9234. SSL_CTX_free(ctx_);
  9235. ctx_ = nullptr;
  9236. }
  9237. }
  9238. }
  9239. inline SSLClient::~SSLClient() {
  9240. if (ctx_) { SSL_CTX_free(ctx_); }
  9241. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  9242. // base function rather than the derived function once we get to the
  9243. // base class destructor, and won't free the SSL (causing a leak).
  9244. shutdown_ssl_impl(socket_, true);
  9245. }
  9246. inline bool SSLClient::is_valid() const { return ctx_; }
  9247. inline void SSLClient::set_ca_cert_store(X509_STORE *ca_cert_store) {
  9248. if (ca_cert_store) {
  9249. if (ctx_) {
  9250. if (SSL_CTX_get_cert_store(ctx_) != ca_cert_store) {
  9251. // Free memory allocated for old cert and use new store
  9252. // `ca_cert_store`
  9253. SSL_CTX_set_cert_store(ctx_, ca_cert_store);
  9254. ca_cert_store_ = ca_cert_store;
  9255. }
  9256. } else {
  9257. X509_STORE_free(ca_cert_store);
  9258. }
  9259. }
  9260. }
  9261. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  9262. std::size_t size) {
  9263. set_ca_cert_store(ClientImpl::create_ca_cert_store(ca_cert, size));
  9264. }
  9265. inline long SSLClient::get_openssl_verify_result() const {
  9266. return verify_result_;
  9267. }
  9268. inline SSL_CTX *SSLClient::ssl_context() const { return ctx_; }
  9269. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  9270. if (!is_valid()) {
  9271. error = Error::SSLConnection;
  9272. return false;
  9273. }
  9274. return ClientImpl::create_and_connect_socket(socket, error);
  9275. }
  9276. // Assumes that socket_mutex_ is locked and that there are no requests in
  9277. // flight
  9278. inline bool SSLClient::connect_with_proxy(
  9279. Socket &socket,
  9280. std::chrono::time_point<std::chrono::steady_clock> start_time,
  9281. Response &res, bool &success, Error &error) {
  9282. success = true;
  9283. Response proxy_res;
  9284. if (!detail::process_client_socket(
  9285. socket.sock, read_timeout_sec_, read_timeout_usec_,
  9286. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  9287. start_time, [&](Stream &strm) {
  9288. Request req2;
  9289. req2.method = "CONNECT";
  9290. req2.path = host_and_port_;
  9291. if (max_timeout_msec_ > 0) {
  9292. req2.start_time_ = std::chrono::steady_clock::now();
  9293. }
  9294. return process_request(strm, req2, proxy_res, false, error);
  9295. })) {
  9296. // Thread-safe to close everything because we are assuming there are no
  9297. // requests in flight
  9298. shutdown_ssl(socket, true);
  9299. shutdown_socket(socket);
  9300. close_socket(socket);
  9301. success = false;
  9302. return false;
  9303. }
  9304. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  9305. if (!proxy_digest_auth_username_.empty() &&
  9306. !proxy_digest_auth_password_.empty()) {
  9307. std::map<std::string, std::string> auth;
  9308. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  9309. // Close the current socket and create a new one for the authenticated
  9310. // request
  9311. shutdown_ssl(socket, true);
  9312. shutdown_socket(socket);
  9313. close_socket(socket);
  9314. // Create a new socket for the authenticated CONNECT request
  9315. if (!create_and_connect_socket(socket, error)) {
  9316. success = false;
  9317. output_error_log(error, nullptr);
  9318. return false;
  9319. }
  9320. proxy_res = Response();
  9321. if (!detail::process_client_socket(
  9322. socket.sock, read_timeout_sec_, read_timeout_usec_,
  9323. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  9324. start_time, [&](Stream &strm) {
  9325. Request req3;
  9326. req3.method = "CONNECT";
  9327. req3.path = host_and_port_;
  9328. req3.headers.insert(detail::make_digest_authentication_header(
  9329. req3, auth, 1, detail::random_string(10),
  9330. proxy_digest_auth_username_, proxy_digest_auth_password_,
  9331. true));
  9332. if (max_timeout_msec_ > 0) {
  9333. req3.start_time_ = std::chrono::steady_clock::now();
  9334. }
  9335. return process_request(strm, req3, proxy_res, false, error);
  9336. })) {
  9337. // Thread-safe to close everything because we are assuming there are
  9338. // no requests in flight
  9339. shutdown_ssl(socket, true);
  9340. shutdown_socket(socket);
  9341. close_socket(socket);
  9342. success = false;
  9343. return false;
  9344. }
  9345. }
  9346. }
  9347. }
  9348. // If status code is not 200, proxy request is failed.
  9349. // Set error to ProxyConnection and return proxy response
  9350. // as the response of the request
  9351. if (proxy_res.status != StatusCode::OK_200) {
  9352. error = Error::ProxyConnection;
  9353. output_error_log(error, nullptr);
  9354. res = std::move(proxy_res);
  9355. // Thread-safe to close everything because we are assuming there are
  9356. // no requests in flight
  9357. shutdown_ssl(socket, true);
  9358. shutdown_socket(socket);
  9359. close_socket(socket);
  9360. return false;
  9361. }
  9362. return true;
  9363. }
  9364. inline bool SSLClient::load_certs() {
  9365. auto ret = true;
  9366. std::call_once(initialize_cert_, [&]() {
  9367. std::lock_guard<std::mutex> guard(ctx_mutex_);
  9368. if (!ca_cert_file_path_.empty()) {
  9369. if (!SSL_CTX_load_verify_locations(ctx_, ca_cert_file_path_.c_str(),
  9370. nullptr)) {
  9371. last_openssl_error_ = ERR_get_error();
  9372. ret = false;
  9373. }
  9374. } else if (!ca_cert_dir_path_.empty()) {
  9375. if (!SSL_CTX_load_verify_locations(ctx_, nullptr,
  9376. ca_cert_dir_path_.c_str())) {
  9377. last_openssl_error_ = ERR_get_error();
  9378. ret = false;
  9379. }
  9380. } else {
  9381. auto loaded = false;
  9382. #ifdef _WIN32
  9383. loaded =
  9384. detail::load_system_certs_on_windows(SSL_CTX_get_cert_store(ctx_));
  9385. #elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && TARGET_OS_MAC
  9386. loaded = detail::load_system_certs_on_macos(SSL_CTX_get_cert_store(ctx_));
  9387. #endif // _WIN32
  9388. if (!loaded) { SSL_CTX_set_default_verify_paths(ctx_); }
  9389. }
  9390. });
  9391. return ret;
  9392. }
  9393. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  9394. auto ssl = detail::ssl_new(
  9395. socket.sock, ctx_, ctx_mutex_,
  9396. [&](SSL *ssl2) {
  9397. if (server_certificate_verification_) {
  9398. if (!load_certs()) {
  9399. error = Error::SSLLoadingCerts;
  9400. output_error_log(error, nullptr);
  9401. return false;
  9402. }
  9403. SSL_set_verify(ssl2, SSL_VERIFY_NONE, nullptr);
  9404. }
  9405. if (!detail::ssl_connect_or_accept_nonblocking(
  9406. socket.sock, ssl2, SSL_connect, connection_timeout_sec_,
  9407. connection_timeout_usec_, &last_ssl_error_)) {
  9408. error = Error::SSLConnection;
  9409. output_error_log(error, nullptr);
  9410. return false;
  9411. }
  9412. if (server_certificate_verification_) {
  9413. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  9414. if (server_certificate_verifier_) {
  9415. verification_status = server_certificate_verifier_(ssl2);
  9416. }
  9417. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  9418. last_openssl_error_ = ERR_get_error();
  9419. error = Error::SSLServerVerification;
  9420. output_error_log(error, nullptr);
  9421. return false;
  9422. }
  9423. if (verification_status == SSLVerifierResponse::NoDecisionMade) {
  9424. verify_result_ = SSL_get_verify_result(ssl2);
  9425. if (verify_result_ != X509_V_OK) {
  9426. last_openssl_error_ = static_cast<unsigned long>(verify_result_);
  9427. error = Error::SSLServerVerification;
  9428. output_error_log(error, nullptr);
  9429. return false;
  9430. }
  9431. auto server_cert = SSL_get1_peer_certificate(ssl2);
  9432. auto se = detail::scope_exit([&] { X509_free(server_cert); });
  9433. if (server_cert == nullptr) {
  9434. last_openssl_error_ = ERR_get_error();
  9435. error = Error::SSLServerVerification;
  9436. output_error_log(error, nullptr);
  9437. return false;
  9438. }
  9439. if (server_hostname_verification_) {
  9440. if (!verify_host(server_cert)) {
  9441. last_openssl_error_ = X509_V_ERR_HOSTNAME_MISMATCH;
  9442. error = Error::SSLServerHostnameVerification;
  9443. output_error_log(error, nullptr);
  9444. return false;
  9445. }
  9446. }
  9447. }
  9448. }
  9449. return true;
  9450. },
  9451. [&](SSL *ssl2) {
  9452. // Set SNI only if host is not IP address
  9453. if (!detail::is_ip_address(host_)) {
  9454. #if defined(OPENSSL_IS_BORINGSSL)
  9455. SSL_set_tlsext_host_name(ssl2, host_.c_str());
  9456. #else
  9457. // NOTE: Direct call instead of using the OpenSSL macro to suppress
  9458. // -Wold-style-cast warning
  9459. SSL_ctrl(ssl2, SSL_CTRL_SET_TLSEXT_HOSTNAME,
  9460. TLSEXT_NAMETYPE_host_name,
  9461. static_cast<void *>(const_cast<char *>(host_.c_str())));
  9462. #endif
  9463. }
  9464. return true;
  9465. });
  9466. if (ssl) {
  9467. socket.ssl = ssl;
  9468. return true;
  9469. }
  9470. if (ctx_ == nullptr) {
  9471. error = Error::SSLConnection;
  9472. last_openssl_error_ = ERR_get_error();
  9473. }
  9474. shutdown_socket(socket);
  9475. close_socket(socket);
  9476. return false;
  9477. }
  9478. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  9479. shutdown_ssl_impl(socket, shutdown_gracefully);
  9480. }
  9481. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  9482. bool shutdown_gracefully) {
  9483. if (socket.sock == INVALID_SOCKET) {
  9484. assert(socket.ssl == nullptr);
  9485. return;
  9486. }
  9487. if (socket.ssl) {
  9488. detail::ssl_delete(ctx_mutex_, socket.ssl, socket.sock,
  9489. shutdown_gracefully);
  9490. socket.ssl = nullptr;
  9491. }
  9492. assert(socket.ssl == nullptr);
  9493. }
  9494. inline bool SSLClient::process_socket(
  9495. const Socket &socket,
  9496. std::chrono::time_point<std::chrono::steady_clock> start_time,
  9497. std::function<bool(Stream &strm)> callback) {
  9498. assert(socket.ssl);
  9499. return detail::process_client_socket_ssl(
  9500. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  9501. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  9502. std::move(callback));
  9503. }
  9504. inline bool SSLClient::is_ssl() const { return true; }
  9505. inline bool SSLClient::verify_host(X509 *server_cert) const {
  9506. /* Quote from RFC2818 section 3.1 "Server Identity"
  9507. If a subjectAltName extension of type dNSName is present, that MUST
  9508. be used as the identity. Otherwise, the (most specific) Common Name
  9509. field in the Subject field of the certificate MUST be used. Although
  9510. the use of the Common Name is existing practice, it is deprecated and
  9511. Certification Authorities are encouraged to use the dNSName instead.
  9512. Matching is performed using the matching rules specified by
  9513. [RFC2459]. If more than one identity of a given type is present in
  9514. the certificate (e.g., more than one dNSName name, a match in any one
  9515. of the set is considered acceptable.) Names may contain the wildcard
  9516. character * which is considered to match any single domain name
  9517. component or component fragment. E.g., *.a.com matches foo.a.com but
  9518. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  9519. In some cases, the URI is specified as an IP address rather than a
  9520. hostname. In this case, the iPAddress subjectAltName must be present
  9521. in the certificate and must exactly match the IP in the URI.
  9522. */
  9523. return verify_host_with_subject_alt_name(server_cert) ||
  9524. verify_host_with_common_name(server_cert);
  9525. }
  9526. inline bool
  9527. SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
  9528. auto ret = false;
  9529. auto type = GEN_DNS;
  9530. struct in6_addr addr6 = {};
  9531. struct in_addr addr = {};
  9532. size_t addr_len = 0;
  9533. #ifndef __MINGW32__
  9534. if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
  9535. type = GEN_IPADD;
  9536. addr_len = sizeof(struct in6_addr);
  9537. } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
  9538. type = GEN_IPADD;
  9539. addr_len = sizeof(struct in_addr);
  9540. }
  9541. #endif
  9542. auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
  9543. X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
  9544. if (alt_names) {
  9545. auto dsn_matched = false;
  9546. auto ip_matched = false;
  9547. auto count = sk_GENERAL_NAME_num(alt_names);
  9548. for (decltype(count) i = 0; i < count && !dsn_matched; i++) {
  9549. auto val = sk_GENERAL_NAME_value(alt_names, i);
  9550. if (!val || val->type != type) { continue; }
  9551. auto name =
  9552. reinterpret_cast<const char *>(ASN1_STRING_get0_data(val->d.ia5));
  9553. if (name == nullptr) { continue; }
  9554. auto name_len = static_cast<size_t>(ASN1_STRING_length(val->d.ia5));
  9555. switch (type) {
  9556. case GEN_DNS: dsn_matched = check_host_name(name, name_len); break;
  9557. case GEN_IPADD:
  9558. if (!memcmp(&addr6, name, addr_len) || !memcmp(&addr, name, addr_len)) {
  9559. ip_matched = true;
  9560. }
  9561. break;
  9562. }
  9563. }
  9564. if (dsn_matched || ip_matched) { ret = true; }
  9565. }
  9566. GENERAL_NAMES_free(const_cast<STACK_OF(GENERAL_NAME) *>(
  9567. reinterpret_cast<const STACK_OF(GENERAL_NAME) *>(alt_names)));
  9568. return ret;
  9569. }
  9570. inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
  9571. const auto subject_name = X509_get_subject_name(server_cert);
  9572. if (subject_name != nullptr) {
  9573. char name[BUFSIZ];
  9574. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  9575. name, sizeof(name));
  9576. if (name_len != -1) {
  9577. return check_host_name(name, static_cast<size_t>(name_len));
  9578. }
  9579. }
  9580. return false;
  9581. }
  9582. inline bool SSLClient::check_host_name(const char *pattern,
  9583. size_t pattern_len) const {
  9584. if (host_.size() == pattern_len && host_ == pattern) { return true; }
  9585. // Wildcard match
  9586. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  9587. std::vector<std::string> pattern_components;
  9588. detail::split(&pattern[0], &pattern[pattern_len], '.',
  9589. [&](const char *b, const char *e) {
  9590. pattern_components.emplace_back(b, e);
  9591. });
  9592. if (host_components_.size() != pattern_components.size()) { return false; }
  9593. auto itr = pattern_components.begin();
  9594. for (const auto &h : host_components_) {
  9595. auto &p = *itr;
  9596. if (p != h && p != "*") {
  9597. auto partial_match = (p.size() > 0 && p[p.size() - 1] == '*' &&
  9598. !p.compare(0, p.size() - 1, h));
  9599. if (!partial_match) { return false; }
  9600. }
  9601. ++itr;
  9602. }
  9603. return true;
  9604. }
  9605. #endif
  9606. // Universal client implementation
  9607. inline Client::Client(const std::string &scheme_host_port)
  9608. : Client(scheme_host_port, std::string(), std::string()) {}
  9609. inline Client::Client(const std::string &scheme_host_port,
  9610. const std::string &client_cert_path,
  9611. const std::string &client_key_path) {
  9612. const static std::regex re(
  9613. R"((?:([a-z]+):\/\/)?(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)");
  9614. std::smatch m;
  9615. if (std::regex_match(scheme_host_port, m, re)) {
  9616. auto scheme = m[1].str();
  9617. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9618. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  9619. #else
  9620. if (!scheme.empty() && scheme != "http") {
  9621. #endif
  9622. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9623. std::string msg = "'" + scheme + "' scheme is not supported.";
  9624. throw std::invalid_argument(msg);
  9625. #endif
  9626. return;
  9627. }
  9628. auto is_ssl = scheme == "https";
  9629. auto host = m[2].str();
  9630. if (host.empty()) { host = m[3].str(); }
  9631. auto port_str = m[4].str();
  9632. auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80);
  9633. if (is_ssl) {
  9634. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9635. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  9636. client_key_path);
  9637. is_ssl_ = is_ssl;
  9638. #endif
  9639. } else {
  9640. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  9641. client_key_path);
  9642. }
  9643. } else {
  9644. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  9645. // if port param below changes.
  9646. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  9647. client_cert_path, client_key_path);
  9648. }
  9649. } // namespace detail
  9650. inline Client::Client(const std::string &host, int port)
  9651. : cli_(detail::make_unique<ClientImpl>(host, port)) {}
  9652. inline Client::Client(const std::string &host, int port,
  9653. const std::string &client_cert_path,
  9654. const std::string &client_key_path)
  9655. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  9656. client_key_path)) {}
  9657. inline Client::~Client() = default;
  9658. inline bool Client::is_valid() const {
  9659. return cli_ != nullptr && cli_->is_valid();
  9660. }
  9661. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  9662. return cli_->Get(path, std::move(progress));
  9663. }
  9664. inline Result Client::Get(const std::string &path, const Headers &headers,
  9665. DownloadProgress progress) {
  9666. return cli_->Get(path, headers, std::move(progress));
  9667. }
  9668. inline Result Client::Get(const std::string &path,
  9669. ContentReceiver content_receiver,
  9670. DownloadProgress progress) {
  9671. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  9672. }
  9673. inline Result Client::Get(const std::string &path, const Headers &headers,
  9674. ContentReceiver content_receiver,
  9675. DownloadProgress progress) {
  9676. return cli_->Get(path, headers, std::move(content_receiver),
  9677. std::move(progress));
  9678. }
  9679. inline Result Client::Get(const std::string &path,
  9680. ResponseHandler response_handler,
  9681. ContentReceiver content_receiver,
  9682. DownloadProgress progress) {
  9683. return cli_->Get(path, std::move(response_handler),
  9684. std::move(content_receiver), std::move(progress));
  9685. }
  9686. inline Result Client::Get(const std::string &path, const Headers &headers,
  9687. ResponseHandler response_handler,
  9688. ContentReceiver content_receiver,
  9689. DownloadProgress progress) {
  9690. return cli_->Get(path, headers, std::move(response_handler),
  9691. std::move(content_receiver), std::move(progress));
  9692. }
  9693. inline Result Client::Get(const std::string &path, const Params &params,
  9694. const Headers &headers, DownloadProgress progress) {
  9695. return cli_->Get(path, params, headers, std::move(progress));
  9696. }
  9697. inline Result Client::Get(const std::string &path, const Params &params,
  9698. const Headers &headers,
  9699. ContentReceiver content_receiver,
  9700. DownloadProgress progress) {
  9701. return cli_->Get(path, params, headers, std::move(content_receiver),
  9702. std::move(progress));
  9703. }
  9704. inline Result Client::Get(const std::string &path, const Params &params,
  9705. const Headers &headers,
  9706. ResponseHandler response_handler,
  9707. ContentReceiver content_receiver,
  9708. DownloadProgress progress) {
  9709. return cli_->Get(path, params, headers, std::move(response_handler),
  9710. std::move(content_receiver), std::move(progress));
  9711. }
  9712. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  9713. inline Result Client::Head(const std::string &path, const Headers &headers) {
  9714. return cli_->Head(path, headers);
  9715. }
  9716. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  9717. inline Result Client::Post(const std::string &path, const Headers &headers) {
  9718. return cli_->Post(path, headers);
  9719. }
  9720. inline Result Client::Post(const std::string &path, const char *body,
  9721. size_t content_length,
  9722. const std::string &content_type,
  9723. UploadProgress progress) {
  9724. return cli_->Post(path, body, content_length, content_type, progress);
  9725. }
  9726. inline Result Client::Post(const std::string &path, const Headers &headers,
  9727. const char *body, size_t content_length,
  9728. const std::string &content_type,
  9729. UploadProgress progress) {
  9730. return cli_->Post(path, headers, body, content_length, content_type,
  9731. progress);
  9732. }
  9733. inline Result Client::Post(const std::string &path, const std::string &body,
  9734. const std::string &content_type,
  9735. UploadProgress progress) {
  9736. return cli_->Post(path, body, content_type, progress);
  9737. }
  9738. inline Result Client::Post(const std::string &path, const Headers &headers,
  9739. const std::string &body,
  9740. const std::string &content_type,
  9741. UploadProgress progress) {
  9742. return cli_->Post(path, headers, body, content_type, progress);
  9743. }
  9744. inline Result Client::Post(const std::string &path, size_t content_length,
  9745. ContentProvider content_provider,
  9746. const std::string &content_type,
  9747. UploadProgress progress) {
  9748. return cli_->Post(path, content_length, std::move(content_provider),
  9749. content_type, progress);
  9750. }
  9751. inline Result Client::Post(const std::string &path,
  9752. ContentProviderWithoutLength content_provider,
  9753. const std::string &content_type,
  9754. UploadProgress progress) {
  9755. return cli_->Post(path, std::move(content_provider), content_type, progress);
  9756. }
  9757. inline Result Client::Post(const std::string &path, const Headers &headers,
  9758. size_t content_length,
  9759. ContentProvider content_provider,
  9760. const std::string &content_type,
  9761. UploadProgress progress) {
  9762. return cli_->Post(path, headers, content_length, std::move(content_provider),
  9763. content_type, progress);
  9764. }
  9765. inline Result Client::Post(const std::string &path, const Headers &headers,
  9766. ContentProviderWithoutLength content_provider,
  9767. const std::string &content_type,
  9768. UploadProgress progress) {
  9769. return cli_->Post(path, headers, std::move(content_provider), content_type,
  9770. progress);
  9771. }
  9772. inline Result Client::Post(const std::string &path, const Params &params) {
  9773. return cli_->Post(path, params);
  9774. }
  9775. inline Result Client::Post(const std::string &path, const Headers &headers,
  9776. const Params &params) {
  9777. return cli_->Post(path, headers, params);
  9778. }
  9779. inline Result Client::Post(const std::string &path,
  9780. const UploadFormDataItems &items,
  9781. UploadProgress progress) {
  9782. return cli_->Post(path, items, progress);
  9783. }
  9784. inline Result Client::Post(const std::string &path, const Headers &headers,
  9785. const UploadFormDataItems &items,
  9786. UploadProgress progress) {
  9787. return cli_->Post(path, headers, items, progress);
  9788. }
  9789. inline Result Client::Post(const std::string &path, const Headers &headers,
  9790. const UploadFormDataItems &items,
  9791. const std::string &boundary,
  9792. UploadProgress progress) {
  9793. return cli_->Post(path, headers, items, boundary, progress);
  9794. }
  9795. inline Result Client::Post(const std::string &path, const Headers &headers,
  9796. const UploadFormDataItems &items,
  9797. const FormDataProviderItems &provider_items,
  9798. UploadProgress progress) {
  9799. return cli_->Post(path, headers, items, provider_items, progress);
  9800. }
  9801. inline Result Client::Post(const std::string &path, const Headers &headers,
  9802. const std::string &body,
  9803. const std::string &content_type,
  9804. ContentReceiver content_receiver,
  9805. DownloadProgress progress) {
  9806. return cli_->Post(path, headers, body, content_type, content_receiver,
  9807. progress);
  9808. }
  9809. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  9810. inline Result Client::Put(const std::string &path, const Headers &headers) {
  9811. return cli_->Put(path, headers);
  9812. }
  9813. inline Result Client::Put(const std::string &path, const char *body,
  9814. size_t content_length,
  9815. const std::string &content_type,
  9816. UploadProgress progress) {
  9817. return cli_->Put(path, body, content_length, content_type, progress);
  9818. }
  9819. inline Result Client::Put(const std::string &path, const Headers &headers,
  9820. const char *body, size_t content_length,
  9821. const std::string &content_type,
  9822. UploadProgress progress) {
  9823. return cli_->Put(path, headers, body, content_length, content_type, progress);
  9824. }
  9825. inline Result Client::Put(const std::string &path, const std::string &body,
  9826. const std::string &content_type,
  9827. UploadProgress progress) {
  9828. return cli_->Put(path, body, content_type, progress);
  9829. }
  9830. inline Result Client::Put(const std::string &path, const Headers &headers,
  9831. const std::string &body,
  9832. const std::string &content_type,
  9833. UploadProgress progress) {
  9834. return cli_->Put(path, headers, body, content_type, progress);
  9835. }
  9836. inline Result Client::Put(const std::string &path, size_t content_length,
  9837. ContentProvider content_provider,
  9838. const std::string &content_type,
  9839. UploadProgress progress) {
  9840. return cli_->Put(path, content_length, std::move(content_provider),
  9841. content_type, progress);
  9842. }
  9843. inline Result Client::Put(const std::string &path,
  9844. ContentProviderWithoutLength content_provider,
  9845. const std::string &content_type,
  9846. UploadProgress progress) {
  9847. return cli_->Put(path, std::move(content_provider), content_type, progress);
  9848. }
  9849. inline Result Client::Put(const std::string &path, const Headers &headers,
  9850. size_t content_length,
  9851. ContentProvider content_provider,
  9852. const std::string &content_type,
  9853. UploadProgress progress) {
  9854. return cli_->Put(path, headers, content_length, std::move(content_provider),
  9855. content_type, progress);
  9856. }
  9857. inline Result Client::Put(const std::string &path, const Headers &headers,
  9858. ContentProviderWithoutLength content_provider,
  9859. const std::string &content_type,
  9860. UploadProgress progress) {
  9861. return cli_->Put(path, headers, std::move(content_provider), content_type,
  9862. progress);
  9863. }
  9864. inline Result Client::Put(const std::string &path, const Params &params) {
  9865. return cli_->Put(path, params);
  9866. }
  9867. inline Result Client::Put(const std::string &path, const Headers &headers,
  9868. const Params &params) {
  9869. return cli_->Put(path, headers, params);
  9870. }
  9871. inline Result Client::Put(const std::string &path,
  9872. const UploadFormDataItems &items,
  9873. UploadProgress progress) {
  9874. return cli_->Put(path, items, progress);
  9875. }
  9876. inline Result Client::Put(const std::string &path, const Headers &headers,
  9877. const UploadFormDataItems &items,
  9878. UploadProgress progress) {
  9879. return cli_->Put(path, headers, items, progress);
  9880. }
  9881. inline Result Client::Put(const std::string &path, const Headers &headers,
  9882. const UploadFormDataItems &items,
  9883. const std::string &boundary,
  9884. UploadProgress progress) {
  9885. return cli_->Put(path, headers, items, boundary, progress);
  9886. }
  9887. inline Result Client::Put(const std::string &path, const Headers &headers,
  9888. const UploadFormDataItems &items,
  9889. const FormDataProviderItems &provider_items,
  9890. UploadProgress progress) {
  9891. return cli_->Put(path, headers, items, provider_items, progress);
  9892. }
  9893. inline Result Client::Put(const std::string &path, const Headers &headers,
  9894. const std::string &body,
  9895. const std::string &content_type,
  9896. ContentReceiver content_receiver,
  9897. DownloadProgress progress) {
  9898. return cli_->Put(path, headers, body, content_type, content_receiver,
  9899. progress);
  9900. }
  9901. inline Result Client::Patch(const std::string &path) {
  9902. return cli_->Patch(path);
  9903. }
  9904. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  9905. return cli_->Patch(path, headers);
  9906. }
  9907. inline Result Client::Patch(const std::string &path, const char *body,
  9908. size_t content_length,
  9909. const std::string &content_type,
  9910. UploadProgress progress) {
  9911. return cli_->Patch(path, body, content_length, content_type, progress);
  9912. }
  9913. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9914. const char *body, size_t content_length,
  9915. const std::string &content_type,
  9916. UploadProgress progress) {
  9917. return cli_->Patch(path, headers, body, content_length, content_type,
  9918. progress);
  9919. }
  9920. inline Result Client::Patch(const std::string &path, const std::string &body,
  9921. const std::string &content_type,
  9922. UploadProgress progress) {
  9923. return cli_->Patch(path, body, content_type, progress);
  9924. }
  9925. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9926. const std::string &body,
  9927. const std::string &content_type,
  9928. UploadProgress progress) {
  9929. return cli_->Patch(path, headers, body, content_type, progress);
  9930. }
  9931. inline Result Client::Patch(const std::string &path, size_t content_length,
  9932. ContentProvider content_provider,
  9933. const std::string &content_type,
  9934. UploadProgress progress) {
  9935. return cli_->Patch(path, content_length, std::move(content_provider),
  9936. content_type, progress);
  9937. }
  9938. inline Result Client::Patch(const std::string &path,
  9939. ContentProviderWithoutLength content_provider,
  9940. const std::string &content_type,
  9941. UploadProgress progress) {
  9942. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  9943. }
  9944. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9945. size_t content_length,
  9946. ContentProvider content_provider,
  9947. const std::string &content_type,
  9948. UploadProgress progress) {
  9949. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  9950. content_type, progress);
  9951. }
  9952. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9953. ContentProviderWithoutLength content_provider,
  9954. const std::string &content_type,
  9955. UploadProgress progress) {
  9956. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  9957. progress);
  9958. }
  9959. inline Result Client::Patch(const std::string &path, const Params &params) {
  9960. return cli_->Patch(path, params);
  9961. }
  9962. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9963. const Params &params) {
  9964. return cli_->Patch(path, headers, params);
  9965. }
  9966. inline Result Client::Patch(const std::string &path,
  9967. const UploadFormDataItems &items,
  9968. UploadProgress progress) {
  9969. return cli_->Patch(path, items, progress);
  9970. }
  9971. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9972. const UploadFormDataItems &items,
  9973. UploadProgress progress) {
  9974. return cli_->Patch(path, headers, items, progress);
  9975. }
  9976. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9977. const UploadFormDataItems &items,
  9978. const std::string &boundary,
  9979. UploadProgress progress) {
  9980. return cli_->Patch(path, headers, items, boundary, progress);
  9981. }
  9982. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9983. const UploadFormDataItems &items,
  9984. const FormDataProviderItems &provider_items,
  9985. UploadProgress progress) {
  9986. return cli_->Patch(path, headers, items, provider_items, progress);
  9987. }
  9988. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9989. const std::string &body,
  9990. const std::string &content_type,
  9991. ContentReceiver content_receiver,
  9992. DownloadProgress progress) {
  9993. return cli_->Patch(path, headers, body, content_type, content_receiver,
  9994. progress);
  9995. }
  9996. inline Result Client::Delete(const std::string &path,
  9997. DownloadProgress progress) {
  9998. return cli_->Delete(path, progress);
  9999. }
  10000. inline Result Client::Delete(const std::string &path, const Headers &headers,
  10001. DownloadProgress progress) {
  10002. return cli_->Delete(path, headers, progress);
  10003. }
  10004. inline Result Client::Delete(const std::string &path, const char *body,
  10005. size_t content_length,
  10006. const std::string &content_type,
  10007. DownloadProgress progress) {
  10008. return cli_->Delete(path, body, content_length, content_type, progress);
  10009. }
  10010. inline Result Client::Delete(const std::string &path, const Headers &headers,
  10011. const char *body, size_t content_length,
  10012. const std::string &content_type,
  10013. DownloadProgress progress) {
  10014. return cli_->Delete(path, headers, body, content_length, content_type,
  10015. progress);
  10016. }
  10017. inline Result Client::Delete(const std::string &path, const std::string &body,
  10018. const std::string &content_type,
  10019. DownloadProgress progress) {
  10020. return cli_->Delete(path, body, content_type, progress);
  10021. }
  10022. inline Result Client::Delete(const std::string &path, const Headers &headers,
  10023. const std::string &body,
  10024. const std::string &content_type,
  10025. DownloadProgress progress) {
  10026. return cli_->Delete(path, headers, body, content_type, progress);
  10027. }
  10028. inline Result Client::Delete(const std::string &path, const Params &params,
  10029. DownloadProgress progress) {
  10030. return cli_->Delete(path, params, progress);
  10031. }
  10032. inline Result Client::Delete(const std::string &path, const Headers &headers,
  10033. const Params &params, DownloadProgress progress) {
  10034. return cli_->Delete(path, headers, params, progress);
  10035. }
  10036. inline Result Client::Options(const std::string &path) {
  10037. return cli_->Options(path);
  10038. }
  10039. inline Result Client::Options(const std::string &path, const Headers &headers) {
  10040. return cli_->Options(path, headers);
  10041. }
  10042. inline bool Client::send(Request &req, Response &res, Error &error) {
  10043. return cli_->send(req, res, error);
  10044. }
  10045. inline Result Client::send(const Request &req) { return cli_->send(req); }
  10046. inline void Client::stop() { cli_->stop(); }
  10047. inline std::string Client::host() const { return cli_->host(); }
  10048. inline int Client::port() const { return cli_->port(); }
  10049. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  10050. inline socket_t Client::socket() const { return cli_->socket(); }
  10051. inline void
  10052. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  10053. cli_->set_hostname_addr_map(std::move(addr_map));
  10054. }
  10055. inline void Client::set_default_headers(Headers headers) {
  10056. cli_->set_default_headers(std::move(headers));
  10057. }
  10058. inline void Client::set_header_writer(
  10059. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  10060. cli_->set_header_writer(writer);
  10061. }
  10062. inline void Client::set_address_family(int family) {
  10063. cli_->set_address_family(family);
  10064. }
  10065. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  10066. inline void Client::set_socket_options(SocketOptions socket_options) {
  10067. cli_->set_socket_options(std::move(socket_options));
  10068. }
  10069. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  10070. cli_->set_connection_timeout(sec, usec);
  10071. }
  10072. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  10073. cli_->set_read_timeout(sec, usec);
  10074. }
  10075. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  10076. cli_->set_write_timeout(sec, usec);
  10077. }
  10078. inline void Client::set_basic_auth(const std::string &username,
  10079. const std::string &password) {
  10080. cli_->set_basic_auth(username, password);
  10081. }
  10082. inline void Client::set_bearer_token_auth(const std::string &token) {
  10083. cli_->set_bearer_token_auth(token);
  10084. }
  10085. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10086. inline void Client::set_digest_auth(const std::string &username,
  10087. const std::string &password) {
  10088. cli_->set_digest_auth(username, password);
  10089. }
  10090. #endif
  10091. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  10092. inline void Client::set_follow_location(bool on) {
  10093. cli_->set_follow_location(on);
  10094. }
  10095. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  10096. [[deprecated("Use set_path_encode instead")]]
  10097. inline void Client::set_url_encode(bool on) {
  10098. cli_->set_path_encode(on);
  10099. }
  10100. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  10101. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  10102. inline void Client::set_interface(const std::string &intf) {
  10103. cli_->set_interface(intf);
  10104. }
  10105. inline void Client::set_proxy(const std::string &host, int port) {
  10106. cli_->set_proxy(host, port);
  10107. }
  10108. inline void Client::set_proxy_basic_auth(const std::string &username,
  10109. const std::string &password) {
  10110. cli_->set_proxy_basic_auth(username, password);
  10111. }
  10112. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  10113. cli_->set_proxy_bearer_token_auth(token);
  10114. }
  10115. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10116. inline void Client::set_proxy_digest_auth(const std::string &username,
  10117. const std::string &password) {
  10118. cli_->set_proxy_digest_auth(username, password);
  10119. }
  10120. #endif
  10121. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10122. inline void Client::enable_server_certificate_verification(bool enabled) {
  10123. cli_->enable_server_certificate_verification(enabled);
  10124. }
  10125. inline void Client::enable_server_hostname_verification(bool enabled) {
  10126. cli_->enable_server_hostname_verification(enabled);
  10127. }
  10128. inline void Client::set_server_certificate_verifier(
  10129. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  10130. cli_->set_server_certificate_verifier(verifier);
  10131. }
  10132. #endif
  10133. inline void Client::set_logger(Logger logger) {
  10134. cli_->set_logger(std::move(logger));
  10135. }
  10136. inline void Client::set_error_logger(ErrorLogger error_logger) {
  10137. cli_->set_error_logger(std::move(error_logger));
  10138. }
  10139. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10140. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  10141. const std::string &ca_cert_dir_path) {
  10142. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  10143. }
  10144. inline void Client::set_ca_cert_store(X509_STORE *ca_cert_store) {
  10145. if (is_ssl_) {
  10146. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  10147. } else {
  10148. cli_->set_ca_cert_store(ca_cert_store);
  10149. }
  10150. }
  10151. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  10152. set_ca_cert_store(cli_->create_ca_cert_store(ca_cert, size));
  10153. }
  10154. inline long Client::get_openssl_verify_result() const {
  10155. if (is_ssl_) {
  10156. return static_cast<SSLClient &>(*cli_).get_openssl_verify_result();
  10157. }
  10158. return -1; // NOTE: -1 doesn't match any of X509_V_ERR_???
  10159. }
  10160. inline SSL_CTX *Client::ssl_context() const {
  10161. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).ssl_context(); }
  10162. return nullptr;
  10163. }
  10164. #endif
  10165. // ----------------------------------------------------------------------------
  10166. } // namespace httplib
  10167. #endif // CPPHTTPLIB_HTTPLIB_H