httplib.h 333 KB

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