httplib.cpp 343 KB

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