httplib.h 303 KB

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