httplib.h 282 KB

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