httplib.h 259 KB

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