httplib.h 171 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2020 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #ifndef CPPHTTPLIB_HTTPLIB_H
  8. #define CPPHTTPLIB_HTTPLIB_H
  9. /*
  10. * Configuration
  11. */
  12. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  13. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  14. #endif
  15. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND
  16. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND 0
  17. #endif
  18. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  19. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 5
  20. #endif
  21. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
  22. #define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
  23. #endif
  24. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
  25. #define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
  26. #endif
  27. #ifndef CPPHTTPLIB_READ_TIMEOUT_SECOND
  28. #define CPPHTTPLIB_READ_TIMEOUT_SECOND 5
  29. #endif
  30. #ifndef CPPHTTPLIB_READ_TIMEOUT_USECOND
  31. #define CPPHTTPLIB_READ_TIMEOUT_USECOND 0
  32. #endif
  33. #ifndef CPPHTTPLIB_WRITE_TIMEOUT_SECOND
  34. #define CPPHTTPLIB_WRITE_TIMEOUT_SECOND 5
  35. #endif
  36. #ifndef CPPHTTPLIB_WRITE_TIMEOUT_USECOND
  37. #define CPPHTTPLIB_WRITE_TIMEOUT_USECOND 0
  38. #endif
  39. #ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
  40. #define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
  41. #endif
  42. #ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
  43. #ifdef _WIN32
  44. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 10000
  45. #else
  46. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
  47. #endif
  48. #endif
  49. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  50. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  51. #endif
  52. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  53. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  54. #endif
  55. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  56. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH ((std::numeric_limits<size_t>::max)())
  57. #endif
  58. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  59. #define CPPHTTPLIB_RECV_BUFSIZ size_t(4096u)
  60. #endif
  61. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  62. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  63. ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
  64. ? std::thread::hardware_concurrency() - 1 \
  65. : 0))
  66. #endif
  67. // Prefer gnu::deprecated, otherwise gcc complains if we use
  68. // [[deprecated]] together with pedantic.
  69. #ifndef CPPHTTPLIB_DEPRECATED
  70. #if defined(__has_cpp_attribute)
  71. #if __has_cpp_attribute(gnu::deprecated)
  72. #define CPPHTTPLIB_DEPRECATED [[gnu::deprecated]]
  73. #else
  74. #if __has_cpp_attribute(deprecated)
  75. #define CPPHTTPLIB_DEPRECATED [[deprecated]]
  76. #else
  77. #define CPPHTTPLIB_DEPRECATED
  78. #endif
  79. #endif
  80. #else
  81. #define CPPHTTPLIB_DEPRECATED
  82. #endif
  83. #endif
  84. /*
  85. * Headers
  86. */
  87. #ifdef _WIN32
  88. #ifndef _CRT_SECURE_NO_WARNINGS
  89. #define _CRT_SECURE_NO_WARNINGS
  90. #endif //_CRT_SECURE_NO_WARNINGS
  91. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  92. #define _CRT_NONSTDC_NO_DEPRECATE
  93. #endif //_CRT_NONSTDC_NO_DEPRECATE
  94. #if defined(_MSC_VER)
  95. #ifdef _WIN64
  96. using ssize_t = __int64;
  97. #else
  98. using ssize_t = int;
  99. #endif
  100. #if _MSC_VER < 1900
  101. #define snprintf _snprintf_s
  102. #endif
  103. #endif // _MSC_VER
  104. #ifndef S_ISREG
  105. #define S_ISREG(m) (((m)&S_IFREG) == S_IFREG)
  106. #endif // S_ISREG
  107. #ifndef S_ISDIR
  108. #define S_ISDIR(m) (((m)&S_IFDIR) == S_IFDIR)
  109. #endif // S_ISDIR
  110. #ifndef NOMINMAX
  111. #define NOMINMAX
  112. #endif // NOMINMAX
  113. #include <io.h>
  114. #include <winsock2.h>
  115. #include <ws2tcpip.h>
  116. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  117. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  118. #endif
  119. #ifdef _MSC_VER
  120. #pragma comment(lib, "ws2_32.lib")
  121. #endif
  122. #ifndef strcasecmp
  123. #define strcasecmp _stricmp
  124. #endif // strcasecmp
  125. using socket_t = SOCKET;
  126. #ifdef CPPHTTPLIB_USE_POLL
  127. #define poll(fds, nfds, timeout) WSAPoll(fds, nfds, timeout)
  128. #endif
  129. #else // not _WIN32
  130. #include <arpa/inet.h>
  131. #include <cstring>
  132. #include <ifaddrs.h>
  133. #include <netdb.h>
  134. #include <netinet/in.h>
  135. #ifdef CPPHTTPLIB_USE_POLL
  136. #include <poll.h>
  137. #endif
  138. #include <csignal>
  139. #include <pthread.h>
  140. #include <sys/select.h>
  141. #include <sys/socket.h>
  142. #include <unistd.h>
  143. using socket_t = int;
  144. #define INVALID_SOCKET (-1)
  145. #endif //_WIN32
  146. #include <array>
  147. #include <atomic>
  148. #include <cassert>
  149. #include <climits>
  150. #include <condition_variable>
  151. #include <errno.h>
  152. #include <fcntl.h>
  153. #include <fstream>
  154. #include <functional>
  155. #include <list>
  156. #include <map>
  157. #include <memory>
  158. #include <mutex>
  159. #include <random>
  160. #include <regex>
  161. #include <string>
  162. #include <sys/stat.h>
  163. #include <thread>
  164. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  165. #include <openssl/err.h>
  166. #include <openssl/md5.h>
  167. #include <openssl/ssl.h>
  168. #include <openssl/x509v3.h>
  169. #include <iomanip>
  170. #include <iostream>
  171. #include <sstream>
  172. // #if OPENSSL_VERSION_NUMBER < 0x1010100fL
  173. // #error Sorry, OpenSSL versions prior to 1.1.1 are not supported
  174. // #endif
  175. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  176. #include <openssl/crypto.h>
  177. inline const unsigned char *ASN1_STRING_get0_data(const ASN1_STRING *asn1) {
  178. return M_ASN1_STRING_data(asn1);
  179. }
  180. #endif
  181. #endif
  182. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  183. #include <zlib.h>
  184. #endif
  185. /*
  186. * Declaration
  187. */
  188. namespace httplib {
  189. namespace detail {
  190. struct ci {
  191. bool operator()(const std::string &s1, const std::string &s2) const {
  192. return std::lexicographical_compare(
  193. s1.begin(), s1.end(), s2.begin(), s2.end(),
  194. [](char c1, char c2) { return ::tolower(c1) < ::tolower(c2); });
  195. }
  196. };
  197. } // namespace detail
  198. using Headers = std::multimap<std::string, std::string, detail::ci>;
  199. using Params = std::multimap<std::string, std::string>;
  200. using Match = std::smatch;
  201. using Progress = std::function<bool(uint64_t current, uint64_t total)>;
  202. struct Response;
  203. using ResponseHandler = std::function<bool(const Response &response)>;
  204. struct MultipartFormData {
  205. std::string name;
  206. std::string content;
  207. std::string filename;
  208. std::string content_type;
  209. };
  210. using MultipartFormDataItems = std::vector<MultipartFormData>;
  211. using MultipartFormDataMap = std::multimap<std::string, MultipartFormData>;
  212. class DataSink {
  213. public:
  214. DataSink() : os(&sb_), sb_(*this) {}
  215. DataSink(const DataSink &) = delete;
  216. DataSink &operator=(const DataSink &) = delete;
  217. DataSink(DataSink &&) = delete;
  218. DataSink &operator=(DataSink &&) = delete;
  219. std::function<void(const char *data, size_t data_len)> write;
  220. std::function<void()> done;
  221. std::function<bool()> is_writable;
  222. std::ostream os;
  223. private:
  224. class data_sink_streambuf : public std::streambuf {
  225. public:
  226. data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  227. protected:
  228. std::streamsize xsputn(const char *s, std::streamsize n) {
  229. sink_.write(s, static_cast<size_t>(n));
  230. return n;
  231. }
  232. private:
  233. DataSink &sink_;
  234. };
  235. data_sink_streambuf sb_;
  236. };
  237. using ContentProvider =
  238. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  239. using ChunkedContentProvider =
  240. std::function<bool(size_t offset, DataSink &sink)>;
  241. using ContentReceiver =
  242. std::function<bool(const char *data, size_t data_length)>;
  243. using MultipartContentHeader =
  244. std::function<bool(const MultipartFormData &file)>;
  245. class ContentReader {
  246. public:
  247. using Reader = std::function<bool(ContentReceiver receiver)>;
  248. using MultipartReader = std::function<bool(MultipartContentHeader header,
  249. ContentReceiver receiver)>;
  250. ContentReader(Reader reader, MultipartReader multipart_reader)
  251. : reader_(reader), multipart_reader_(multipart_reader) {}
  252. bool operator()(MultipartContentHeader header,
  253. ContentReceiver receiver) const {
  254. return multipart_reader_(header, receiver);
  255. }
  256. bool operator()(ContentReceiver receiver) const { return reader_(receiver); }
  257. Reader reader_;
  258. MultipartReader multipart_reader_;
  259. };
  260. using Range = std::pair<ssize_t, ssize_t>;
  261. using Ranges = std::vector<Range>;
  262. struct Request {
  263. std::string method;
  264. std::string path;
  265. Headers headers;
  266. std::string body;
  267. std::string remote_addr;
  268. int remote_port = -1;
  269. // for server
  270. std::string version;
  271. std::string target;
  272. Params params;
  273. MultipartFormDataMap files;
  274. Ranges ranges;
  275. Match matches;
  276. // for client
  277. size_t redirect_count = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  278. ResponseHandler response_handler;
  279. ContentReceiver content_receiver;
  280. size_t content_length = 0;
  281. ContentProvider content_provider;
  282. Progress progress;
  283. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  284. const SSL *ssl;
  285. #endif
  286. bool has_header(const char *key) const;
  287. std::string get_header_value(const char *key, size_t id = 0) const;
  288. size_t get_header_value_count(const char *key) const;
  289. void set_header(const char *key, const char *val);
  290. void set_header(const char *key, const std::string &val);
  291. bool has_param(const char *key) const;
  292. std::string get_param_value(const char *key, size_t id = 0) const;
  293. size_t get_param_value_count(const char *key) const;
  294. bool is_multipart_form_data() const;
  295. bool has_file(const char *key) const;
  296. MultipartFormData get_file_value(const char *key) const;
  297. // private members...
  298. size_t authorization_count_ = 0;
  299. };
  300. struct Response {
  301. std::string version;
  302. int status = -1;
  303. Headers headers;
  304. std::string body;
  305. bool has_header(const char *key) const;
  306. std::string get_header_value(const char *key, size_t id = 0) const;
  307. size_t get_header_value_count(const char *key) const;
  308. void set_header(const char *key, const char *val);
  309. void set_header(const char *key, const std::string &val);
  310. void set_redirect(const char *url, int status = 302);
  311. void set_content(const char *s, size_t n, const char *content_type);
  312. void set_content(std::string s, const char *content_type);
  313. void set_content_provider(
  314. size_t length, ContentProvider provider,
  315. std::function<void()> resource_releaser = [] {});
  316. void set_chunked_content_provider(
  317. ChunkedContentProvider provider,
  318. std::function<void()> resource_releaser = [] {});
  319. Response() = default;
  320. Response(const Response &) = default;
  321. Response &operator=(const Response &) = default;
  322. Response(Response &&) = default;
  323. Response &operator=(Response &&) = default;
  324. ~Response() {
  325. if (content_provider_resource_releaser_) {
  326. content_provider_resource_releaser_();
  327. }
  328. }
  329. // private members...
  330. size_t content_length_ = 0;
  331. ContentProvider content_provider_;
  332. std::function<void()> content_provider_resource_releaser_;
  333. };
  334. class Stream {
  335. public:
  336. virtual ~Stream() = default;
  337. virtual bool is_readable() const = 0;
  338. virtual bool is_writable() const = 0;
  339. virtual ssize_t read(char *ptr, size_t size) = 0;
  340. virtual ssize_t write(const char *ptr, size_t size) = 0;
  341. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  342. template <typename... Args>
  343. ssize_t write_format(const char *fmt, const Args &... args);
  344. ssize_t write(const char *ptr);
  345. ssize_t write(const std::string &s);
  346. };
  347. class TaskQueue {
  348. public:
  349. TaskQueue() = default;
  350. virtual ~TaskQueue() = default;
  351. virtual void enqueue(std::function<void()> fn) = 0;
  352. virtual void shutdown() = 0;
  353. virtual void on_idle(){};
  354. };
  355. class ThreadPool : public TaskQueue {
  356. public:
  357. explicit ThreadPool(size_t n) : shutdown_(false) {
  358. while (n) {
  359. threads_.emplace_back(worker(*this));
  360. n--;
  361. }
  362. }
  363. ThreadPool(const ThreadPool &) = delete;
  364. ~ThreadPool() override = default;
  365. void enqueue(std::function<void()> fn) override {
  366. std::unique_lock<std::mutex> lock(mutex_);
  367. jobs_.push_back(fn);
  368. cond_.notify_one();
  369. }
  370. void shutdown() override {
  371. // Stop all worker threads...
  372. {
  373. std::unique_lock<std::mutex> lock(mutex_);
  374. shutdown_ = true;
  375. }
  376. cond_.notify_all();
  377. // Join...
  378. for (auto &t : threads_) {
  379. t.join();
  380. }
  381. }
  382. private:
  383. struct worker {
  384. explicit worker(ThreadPool &pool) : pool_(pool) {}
  385. void operator()() {
  386. for (;;) {
  387. std::function<void()> fn;
  388. {
  389. std::unique_lock<std::mutex> lock(pool_.mutex_);
  390. pool_.cond_.wait(
  391. lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; });
  392. if (pool_.shutdown_ && pool_.jobs_.empty()) { break; }
  393. fn = pool_.jobs_.front();
  394. pool_.jobs_.pop_front();
  395. }
  396. assert(true == static_cast<bool>(fn));
  397. fn();
  398. }
  399. }
  400. ThreadPool &pool_;
  401. };
  402. friend struct worker;
  403. std::vector<std::thread> threads_;
  404. std::list<std::function<void()>> jobs_;
  405. bool shutdown_;
  406. std::condition_variable cond_;
  407. std::mutex mutex_;
  408. };
  409. using Logger = std::function<void(const Request &, const Response &)>;
  410. using SocketOptions = std::function<void(socket_t sock)>;
  411. inline void default_socket_options(socket_t sock) {
  412. int yes = 1;
  413. #ifdef _WIN32
  414. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char *>(&yes),
  415. sizeof(yes));
  416. setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
  417. reinterpret_cast<char *>(&yes), sizeof(yes));
  418. #else
  419. #ifdef SO_REUSEPORT
  420. setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, reinterpret_cast<void *>(&yes),
  421. sizeof(yes));
  422. #else
  423. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<void *>(&yes),
  424. sizeof(yes));
  425. #endif
  426. #endif
  427. }
  428. class Server {
  429. public:
  430. using Handler = std::function<void(const Request &, Response &)>;
  431. using HandlerWithContentReader = std::function<void(
  432. const Request &, Response &, const ContentReader &content_reader)>;
  433. using Expect100ContinueHandler =
  434. std::function<int(const Request &, Response &)>;
  435. Server();
  436. virtual ~Server();
  437. virtual bool is_valid() const;
  438. Server &Get(const char *pattern, Handler handler);
  439. Server &Post(const char *pattern, Handler handler);
  440. Server &Post(const char *pattern, HandlerWithContentReader handler);
  441. Server &Put(const char *pattern, Handler handler);
  442. Server &Put(const char *pattern, HandlerWithContentReader handler);
  443. Server &Patch(const char *pattern, Handler handler);
  444. Server &Patch(const char *pattern, HandlerWithContentReader handler);
  445. Server &Delete(const char *pattern, Handler handler);
  446. Server &Delete(const char *pattern, HandlerWithContentReader handler);
  447. Server &Options(const char *pattern, Handler handler);
  448. CPPHTTPLIB_DEPRECATED bool set_base_dir(const char *dir,
  449. const char *mount_point = nullptr);
  450. bool set_mount_point(const char *mount_point, const char *dir);
  451. bool remove_mount_point(const char *mount_point);
  452. void set_file_extension_and_mimetype_mapping(const char *ext,
  453. const char *mime);
  454. void set_file_request_handler(Handler handler);
  455. void set_error_handler(Handler handler);
  456. void set_expect_100_continue_handler(Expect100ContinueHandler handler);
  457. void set_logger(Logger logger);
  458. void set_socket_options(SocketOptions socket_options);
  459. void set_keep_alive_max_count(size_t count);
  460. void set_read_timeout(time_t sec, time_t usec = 0);
  461. void set_write_timeout(time_t sec, time_t usec = 0);
  462. void set_idle_interval(time_t sec, time_t usec = 0);
  463. void set_payload_max_length(size_t length);
  464. bool bind_to_port(const char *host, int port, int socket_flags = 0);
  465. int bind_to_any_port(const char *host, int socket_flags = 0);
  466. bool listen_after_bind();
  467. bool listen(const char *host, int port, int socket_flags = 0);
  468. bool is_running() const;
  469. void stop();
  470. std::function<TaskQueue *(void)> new_task_queue;
  471. protected:
  472. bool process_request(Stream &strm, bool last_connection,
  473. bool &connection_close,
  474. const std::function<void(Request &)> &setup_request);
  475. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  476. time_t read_timeout_sec_ = CPPHTTPLIB_READ_TIMEOUT_SECOND;
  477. time_t read_timeout_usec_ = CPPHTTPLIB_READ_TIMEOUT_USECOND;
  478. time_t write_timeout_sec_ = CPPHTTPLIB_WRITE_TIMEOUT_SECOND;
  479. time_t write_timeout_usec_ = CPPHTTPLIB_WRITE_TIMEOUT_USECOND;
  480. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  481. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  482. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  483. private:
  484. using Handlers = std::vector<std::pair<std::regex, Handler>>;
  485. using HandlersForContentReader =
  486. std::vector<std::pair<std::regex, HandlerWithContentReader>>;
  487. socket_t create_server_socket(const char *host, int port, int socket_flags,
  488. SocketOptions socket_options) const;
  489. int bind_internal(const char *host, int port, int socket_flags);
  490. bool listen_internal();
  491. bool routing(Request &req, Response &res, Stream &strm);
  492. bool handle_file_request(Request &req, Response &res, bool head = false);
  493. bool dispatch_request(Request &req, Response &res, Handlers &handlers);
  494. bool dispatch_request_for_content_reader(Request &req, Response &res,
  495. ContentReader content_reader,
  496. HandlersForContentReader &handlers);
  497. bool parse_request_line(const char *s, Request &req);
  498. bool write_response(Stream &strm, bool last_connection, const Request &req,
  499. Response &res);
  500. bool write_content_with_provider(Stream &strm, const Request &req,
  501. Response &res, const std::string &boundary,
  502. const std::string &content_type);
  503. bool read_content(Stream &strm, Request &req, Response &res);
  504. bool
  505. read_content_with_content_receiver(Stream &strm, Request &req, Response &res,
  506. ContentReceiver receiver,
  507. MultipartContentHeader multipart_header,
  508. ContentReceiver multipart_receiver);
  509. bool read_content_core(Stream &strm, Request &req, Response &res,
  510. ContentReceiver receiver,
  511. MultipartContentHeader mulitpart_header,
  512. ContentReceiver multipart_receiver);
  513. virtual bool process_and_close_socket(socket_t sock);
  514. std::atomic<bool> is_running_;
  515. std::atomic<socket_t> svr_sock_;
  516. std::vector<std::pair<std::string, std::string>> base_dirs_;
  517. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  518. Handler file_request_handler_;
  519. Handlers get_handlers_;
  520. Handlers post_handlers_;
  521. HandlersForContentReader post_handlers_for_content_reader_;
  522. Handlers put_handlers_;
  523. HandlersForContentReader put_handlers_for_content_reader_;
  524. Handlers patch_handlers_;
  525. HandlersForContentReader patch_handlers_for_content_reader_;
  526. Handlers delete_handlers_;
  527. HandlersForContentReader delete_handlers_for_content_reader_;
  528. Handlers options_handlers_;
  529. Handler error_handler_;
  530. Logger logger_;
  531. Expect100ContinueHandler expect_100_continue_handler_;
  532. SocketOptions socket_options_ = default_socket_options;
  533. };
  534. class Client {
  535. public:
  536. explicit Client(const std::string &host);
  537. explicit Client(const std::string &host, int port);
  538. explicit Client(const std::string &host, int port,
  539. const std::string &client_cert_path,
  540. const std::string &client_key_path);
  541. virtual ~Client();
  542. virtual bool is_valid() const;
  543. std::shared_ptr<Response> Get(const char *path);
  544. std::shared_ptr<Response> Get(const char *path, const Headers &headers);
  545. std::shared_ptr<Response> Get(const char *path, Progress progress);
  546. std::shared_ptr<Response> Get(const char *path, const Headers &headers,
  547. Progress progress);
  548. std::shared_ptr<Response> Get(const char *path,
  549. ContentReceiver content_receiver);
  550. std::shared_ptr<Response> Get(const char *path, const Headers &headers,
  551. ContentReceiver content_receiver);
  552. std::shared_ptr<Response>
  553. Get(const char *path, ContentReceiver content_receiver, Progress progress);
  554. std::shared_ptr<Response> Get(const char *path, const Headers &headers,
  555. ContentReceiver content_receiver,
  556. Progress progress);
  557. std::shared_ptr<Response> Get(const char *path, const Headers &headers,
  558. ResponseHandler response_handler,
  559. ContentReceiver content_receiver);
  560. std::shared_ptr<Response> Get(const char *path, const Headers &headers,
  561. ResponseHandler response_handler,
  562. ContentReceiver content_receiver,
  563. Progress progress);
  564. std::shared_ptr<Response> Head(const char *path);
  565. std::shared_ptr<Response> Head(const char *path, const Headers &headers);
  566. std::shared_ptr<Response> Post(const char *path);
  567. std::shared_ptr<Response> Post(const char *path, const std::string &body,
  568. const char *content_type);
  569. std::shared_ptr<Response> Post(const char *path, const Headers &headers,
  570. const std::string &body,
  571. const char *content_type);
  572. std::shared_ptr<Response> Post(const char *path, size_t content_length,
  573. ContentProvider content_provider,
  574. const char *content_type);
  575. std::shared_ptr<Response> Post(const char *path, const Headers &headers,
  576. size_t content_length,
  577. ContentProvider content_provider,
  578. const char *content_type);
  579. std::shared_ptr<Response> Post(const char *path, const Params &params);
  580. std::shared_ptr<Response> Post(const char *path, const Headers &headers,
  581. const Params &params);
  582. std::shared_ptr<Response> Post(const char *path,
  583. const MultipartFormDataItems &items);
  584. std::shared_ptr<Response> Post(const char *path, const Headers &headers,
  585. const MultipartFormDataItems &items);
  586. std::shared_ptr<Response> Put(const char *path);
  587. std::shared_ptr<Response> Put(const char *path, const std::string &body,
  588. const char *content_type);
  589. std::shared_ptr<Response> Put(const char *path, const Headers &headers,
  590. const std::string &body,
  591. const char *content_type);
  592. std::shared_ptr<Response> Put(const char *path, size_t content_length,
  593. ContentProvider content_provider,
  594. const char *content_type);
  595. std::shared_ptr<Response> Put(const char *path, const Headers &headers,
  596. size_t content_length,
  597. ContentProvider content_provider,
  598. const char *content_type);
  599. std::shared_ptr<Response> Put(const char *path, const Params &params);
  600. std::shared_ptr<Response> Put(const char *path, const Headers &headers,
  601. const Params &params);
  602. std::shared_ptr<Response> Patch(const char *path, const std::string &body,
  603. const char *content_type);
  604. std::shared_ptr<Response> Patch(const char *path, const Headers &headers,
  605. const std::string &body,
  606. const char *content_type);
  607. std::shared_ptr<Response> Patch(const char *path, size_t content_length,
  608. ContentProvider content_provider,
  609. const char *content_type);
  610. std::shared_ptr<Response> Patch(const char *path, const Headers &headers,
  611. size_t content_length,
  612. ContentProvider content_provider,
  613. const char *content_type);
  614. std::shared_ptr<Response> Delete(const char *path);
  615. std::shared_ptr<Response> Delete(const char *path, const std::string &body,
  616. const char *content_type);
  617. std::shared_ptr<Response> Delete(const char *path, const Headers &headers);
  618. std::shared_ptr<Response> Delete(const char *path, const Headers &headers,
  619. const std::string &body,
  620. const char *content_type);
  621. std::shared_ptr<Response> Options(const char *path);
  622. std::shared_ptr<Response> Options(const char *path, const Headers &headers);
  623. bool send(const Request &req, Response &res);
  624. bool send(const std::vector<Request> &requests,
  625. std::vector<Response> &responses);
  626. size_t is_socket_open() const;
  627. void stop();
  628. CPPHTTPLIB_DEPRECATED void set_timeout_sec(time_t timeout_sec);
  629. void set_connection_timeout(time_t sec, time_t usec = 0);
  630. void set_read_timeout(time_t sec, time_t usec = 0);
  631. void set_write_timeout(time_t sec, time_t usec = 0);
  632. void set_keep_alive_max_count(size_t count);
  633. void set_basic_auth(const char *username, const char *password);
  634. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  635. void set_digest_auth(const char *username, const char *password);
  636. #endif
  637. void set_follow_location(bool on);
  638. void set_compress(bool on);
  639. void set_decompress(bool on);
  640. void set_interface(const char *intf);
  641. void set_proxy(const char *host, int port);
  642. void set_proxy_basic_auth(const char *username, const char *password);
  643. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  644. void set_proxy_digest_auth(const char *username, const char *password);
  645. #endif
  646. void set_logger(Logger logger);
  647. protected:
  648. struct Socket {
  649. socket_t sock = INVALID_SOCKET;
  650. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  651. SSL *ssl = nullptr;
  652. #endif
  653. bool is_open() const { return sock != INVALID_SOCKET; }
  654. };
  655. virtual bool create_and_connect_socket(Socket &socket);
  656. virtual void close_socket(Socket &socket, bool process_socket_ret);
  657. bool process_request(Stream &strm, const Request &req, Response &res,
  658. bool &connection_close);
  659. // Socket endoint information
  660. const std::string host_;
  661. const int port_;
  662. const std::string host_and_port_;
  663. // Current open socket
  664. Socket socket_;
  665. mutable std::mutex socket_mutex_;
  666. std::recursive_mutex request_mutex_;
  667. // Settings
  668. std::string client_cert_path_;
  669. std::string client_key_path_;
  670. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  671. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  672. time_t read_timeout_sec_ = CPPHTTPLIB_READ_TIMEOUT_SECOND;
  673. time_t read_timeout_usec_ = CPPHTTPLIB_READ_TIMEOUT_USECOND;
  674. time_t write_timeout_sec_ = CPPHTTPLIB_WRITE_TIMEOUT_SECOND;
  675. time_t write_timeout_usec_ = CPPHTTPLIB_WRITE_TIMEOUT_USECOND;
  676. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  677. std::string basic_auth_username_;
  678. std::string basic_auth_password_;
  679. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  680. std::string digest_auth_username_;
  681. std::string digest_auth_password_;
  682. #endif
  683. bool follow_location_ = false;
  684. bool compress_ = false;
  685. bool decompress_ = true;
  686. std::string interface_;
  687. std::string proxy_host_;
  688. int proxy_port_;
  689. std::string proxy_basic_auth_username_;
  690. std::string proxy_basic_auth_password_;
  691. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  692. std::string proxy_digest_auth_username_;
  693. std::string proxy_digest_auth_password_;
  694. #endif
  695. Logger logger_;
  696. void copy_settings(const Client &rhs) {
  697. client_cert_path_ = rhs.client_cert_path_;
  698. client_key_path_ = rhs.client_key_path_;
  699. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  700. read_timeout_sec_ = rhs.read_timeout_sec_;
  701. read_timeout_usec_ = rhs.read_timeout_usec_;
  702. write_timeout_sec_ = rhs.write_timeout_sec_;
  703. write_timeout_usec_ = rhs.write_timeout_usec_;
  704. keep_alive_max_count_ = rhs.keep_alive_max_count_;
  705. basic_auth_username_ = rhs.basic_auth_username_;
  706. basic_auth_password_ = rhs.basic_auth_password_;
  707. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  708. digest_auth_username_ = rhs.digest_auth_username_;
  709. digest_auth_password_ = rhs.digest_auth_password_;
  710. #endif
  711. follow_location_ = rhs.follow_location_;
  712. compress_ = rhs.compress_;
  713. decompress_ = rhs.decompress_;
  714. interface_ = rhs.interface_;
  715. proxy_host_ = rhs.proxy_host_;
  716. proxy_port_ = rhs.proxy_port_;
  717. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  718. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  719. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  720. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  721. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  722. #endif
  723. logger_ = rhs.logger_;
  724. }
  725. private:
  726. socket_t create_client_socket() const;
  727. bool read_response_line(Stream &strm, Response &res);
  728. bool write_request(Stream &strm, const Request &req);
  729. bool redirect(const Request &req, Response &res);
  730. bool handle_request(Stream &strm, const Request &req, Response &res,
  731. bool &connection_close);
  732. std::shared_ptr<Response> send_with_content_provider(
  733. const char *method, const char *path, const Headers &headers,
  734. const std::string &body, size_t content_length,
  735. ContentProvider content_provider, const char *content_type);
  736. virtual bool
  737. process_socket(Socket &socket, size_t request_count,
  738. std::function<bool(Stream &strm, bool last_connection,
  739. bool &connection_close)>
  740. callback);
  741. virtual bool is_ssl() const;
  742. };
  743. inline void Get(std::vector<Request> &requests, const char *path,
  744. const Headers &headers) {
  745. Request req;
  746. req.method = "GET";
  747. req.path = path;
  748. req.headers = headers;
  749. requests.emplace_back(std::move(req));
  750. }
  751. inline void Get(std::vector<Request> &requests, const char *path) {
  752. Get(requests, path, Headers());
  753. }
  754. inline void Post(std::vector<Request> &requests, const char *path,
  755. const Headers &headers, const std::string &body,
  756. const char *content_type) {
  757. Request req;
  758. req.method = "POST";
  759. req.path = path;
  760. req.headers = headers;
  761. if (content_type) { req.headers.emplace("Content-Type", content_type); }
  762. req.body = body;
  763. requests.emplace_back(std::move(req));
  764. }
  765. inline void Post(std::vector<Request> &requests, const char *path,
  766. const std::string &body, const char *content_type) {
  767. Post(requests, path, Headers(), body, content_type);
  768. }
  769. inline void Post(std::vector<Request> &requests, const char *path,
  770. size_t content_length, ContentProvider content_provider,
  771. const char *content_type) {
  772. Request req;
  773. req.method = "POST";
  774. req.headers = Headers();
  775. req.path = path;
  776. req.content_length = content_length;
  777. req.content_provider = content_provider;
  778. if (content_type) { req.headers.emplace("Content-Type", content_type); }
  779. requests.emplace_back(std::move(req));
  780. }
  781. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  782. class SSLServer : public Server {
  783. public:
  784. SSLServer(const char *cert_path, const char *private_key_path,
  785. const char *client_ca_cert_file_path = nullptr,
  786. const char *client_ca_cert_dir_path = nullptr);
  787. SSLServer(X509 *cert, EVP_PKEY *private_key,
  788. X509_STORE *client_ca_cert_store = nullptr);
  789. ~SSLServer() override;
  790. bool is_valid() const override;
  791. private:
  792. bool process_and_close_socket(socket_t sock) override;
  793. SSL_CTX *ctx_;
  794. std::mutex ctx_mutex_;
  795. };
  796. class SSLClient : public Client {
  797. public:
  798. explicit SSLClient(const std::string &host);
  799. explicit SSLClient(const std::string &host, int port);
  800. explicit SSLClient(const std::string &host, int port,
  801. const std::string &client_cert_path,
  802. const std::string &client_key_path);
  803. explicit SSLClient(const std::string &host, int port, X509 *client_cert,
  804. EVP_PKEY *client_key);
  805. ~SSLClient() override;
  806. bool is_valid() const override;
  807. void set_ca_cert_path(const char *ca_cert_file_path,
  808. const char *ca_cert_dir_path = nullptr);
  809. void set_ca_cert_store(X509_STORE *ca_cert_store);
  810. void enable_server_certificate_verification(bool enabled);
  811. long get_openssl_verify_result() const;
  812. SSL_CTX *ssl_context() const;
  813. private:
  814. bool create_and_connect_socket(Socket &socket) override;
  815. bool connect_with_proxy(Socket &sock, bool &error);
  816. void close_socket(Socket &socket, bool process_socket_ret) override;
  817. bool process_socket(Socket &socket, size_t request_count,
  818. std::function<bool(Stream &strm, bool last_connection,
  819. bool &connection_close)>
  820. callback) override;
  821. bool is_ssl() const override;
  822. bool initialize_ssl(Socket &socket);
  823. bool verify_host(X509 *server_cert) const;
  824. bool verify_host_with_subject_alt_name(X509 *server_cert) const;
  825. bool verify_host_with_common_name(X509 *server_cert) const;
  826. bool check_host_name(const char *pattern, size_t pattern_len) const;
  827. SSL_CTX *ctx_;
  828. std::mutex ctx_mutex_;
  829. std::vector<std::string> host_components_;
  830. std::string ca_cert_file_path_;
  831. std::string ca_cert_dir_path_;
  832. X509_STORE *ca_cert_store_ = nullptr;
  833. bool server_certificate_verification_ = false;
  834. long verify_result_ = 0;
  835. };
  836. #endif
  837. class Client2 {
  838. public:
  839. explicit Client2(const char *scheme_host_port)
  840. : Client2(scheme_host_port, std::string(), std::string()) {}
  841. explicit Client2(const char *scheme_host_port,
  842. const std::string &client_cert_path,
  843. const std::string &client_key_path) {
  844. const static std::regex re(R"(^(https?)://([^:/?#]+)(?::(\d+))?)");
  845. std::cmatch m;
  846. if (std::regex_match(scheme_host_port, m, re)) {
  847. auto scheme = m[1].str();
  848. auto host = m[2].str();
  849. auto port_str = m[3].str();
  850. auto port = !port_str.empty() ? std::stoi(port_str)
  851. : (scheme == "https" ? 443 : 80);
  852. if (scheme == "https") {
  853. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  854. is_ssl_ = true;
  855. cli_ = std::make_shared<SSLClient>(host.c_str(), port, client_cert_path,
  856. client_key_path);
  857. #endif
  858. } else {
  859. cli_ = std::make_shared<Client>(host.c_str(), port, client_cert_path,
  860. client_key_path);
  861. }
  862. }
  863. }
  864. ~Client2() {}
  865. bool is_valid() const { return cli_ != nullptr; }
  866. std::shared_ptr<Response> Get(const char *path) { return cli_->Get(path); }
  867. std::shared_ptr<Response> Get(const char *path, const Headers &headers) {
  868. return cli_->Get(path, headers);
  869. }
  870. std::shared_ptr<Response> Get(const char *path, Progress progress) {
  871. return cli_->Get(path, progress);
  872. }
  873. std::shared_ptr<Response> Get(const char *path, const Headers &headers,
  874. Progress progress) {
  875. return cli_->Get(path, headers, progress);
  876. }
  877. std::shared_ptr<Response> Get(const char *path,
  878. ContentReceiver content_receiver) {
  879. return cli_->Get(path, content_receiver);
  880. }
  881. std::shared_ptr<Response> Get(const char *path, const Headers &headers,
  882. ContentReceiver content_receiver) {
  883. return cli_->Get(path, headers, content_receiver);
  884. }
  885. std::shared_ptr<Response>
  886. Get(const char *path, ContentReceiver content_receiver, Progress progress) {
  887. return cli_->Get(path, content_receiver, progress);
  888. }
  889. std::shared_ptr<Response> Get(const char *path, const Headers &headers,
  890. ContentReceiver content_receiver,
  891. Progress progress) {
  892. return cli_->Get(path, headers, content_receiver, progress);
  893. }
  894. std::shared_ptr<Response> Get(const char *path, const Headers &headers,
  895. ResponseHandler response_handler,
  896. ContentReceiver content_receiver) {
  897. return cli_->Get(path, headers, response_handler, content_receiver);
  898. }
  899. std::shared_ptr<Response> Get(const char *path, const Headers &headers,
  900. ResponseHandler response_handler,
  901. ContentReceiver content_receiver,
  902. Progress progress) {
  903. return cli_->Get(path, headers, response_handler, content_receiver,
  904. progress);
  905. }
  906. std::shared_ptr<Response> Head(const char *path) { return cli_->Head(path); }
  907. std::shared_ptr<Response> Head(const char *path, const Headers &headers) {
  908. return cli_->Head(path, headers);
  909. }
  910. std::shared_ptr<Response> Post(const char *path) { return cli_->Post(path); }
  911. std::shared_ptr<Response> Post(const char *path, const std::string &body,
  912. const char *content_type) {
  913. return cli_->Post(path, body, content_type);
  914. }
  915. std::shared_ptr<Response> Post(const char *path, const Headers &headers,
  916. const std::string &body,
  917. const char *content_type) {
  918. return cli_->Post(path, headers, body, content_type);
  919. }
  920. std::shared_ptr<Response> Post(const char *path, size_t content_length,
  921. ContentProvider content_provider,
  922. const char *content_type) {
  923. return cli_->Post(path, content_length, content_provider, content_type);
  924. }
  925. std::shared_ptr<Response> Post(const char *path, const Headers &headers,
  926. size_t content_length,
  927. ContentProvider content_provider,
  928. const char *content_type) {
  929. return cli_->Post(path, headers, content_length, content_provider,
  930. content_type);
  931. }
  932. std::shared_ptr<Response> Post(const char *path, const Params &params) {
  933. return cli_->Post(path, params);
  934. }
  935. std::shared_ptr<Response> Post(const char *path, const Headers &headers,
  936. const Params &params) {
  937. return cli_->Post(path, headers, params);
  938. }
  939. std::shared_ptr<Response> Post(const char *path,
  940. const MultipartFormDataItems &items) {
  941. return cli_->Post(path, items);
  942. }
  943. std::shared_ptr<Response> Post(const char *path, const Headers &headers,
  944. const MultipartFormDataItems &items) {
  945. return cli_->Post(path, headers, items);
  946. }
  947. std::shared_ptr<Response> Put(const char *path) { return cli_->Put(path); }
  948. std::shared_ptr<Response> Put(const char *path, const std::string &body,
  949. const char *content_type) {
  950. return cli_->Put(path, body, content_type);
  951. }
  952. std::shared_ptr<Response> Put(const char *path, const Headers &headers,
  953. const std::string &body,
  954. const char *content_type) {
  955. return cli_->Put(path, headers, body, content_type);
  956. }
  957. std::shared_ptr<Response> Put(const char *path, size_t content_length,
  958. ContentProvider content_provider,
  959. const char *content_type) {
  960. return cli_->Put(path, content_length, content_provider, content_type);
  961. }
  962. std::shared_ptr<Response> Put(const char *path, const Headers &headers,
  963. size_t content_length,
  964. ContentProvider content_provider,
  965. const char *content_type) {
  966. return cli_->Put(path, headers, content_length, content_provider,
  967. content_type);
  968. }
  969. std::shared_ptr<Response> Put(const char *path, const Params &params) {
  970. return cli_->Put(path, params);
  971. }
  972. std::shared_ptr<Response> Put(const char *path, const Headers &headers,
  973. const Params &params) {
  974. return cli_->Put(path, headers, params);
  975. }
  976. std::shared_ptr<Response> Patch(const char *path, const std::string &body,
  977. const char *content_type) {
  978. return cli_->Patch(path, body, content_type);
  979. }
  980. std::shared_ptr<Response> Patch(const char *path, const Headers &headers,
  981. const std::string &body,
  982. const char *content_type) {
  983. return cli_->Patch(path, headers, body, content_type);
  984. }
  985. std::shared_ptr<Response> Patch(const char *path, size_t content_length,
  986. ContentProvider content_provider,
  987. const char *content_type) {
  988. return cli_->Patch(path, content_length, content_provider, content_type);
  989. }
  990. std::shared_ptr<Response> Patch(const char *path, const Headers &headers,
  991. size_t content_length,
  992. ContentProvider content_provider,
  993. const char *content_type) {
  994. return cli_->Patch(path, headers, content_length, content_provider,
  995. content_type);
  996. }
  997. std::shared_ptr<Response> Delete(const char *path) {
  998. return cli_->Delete(path);
  999. }
  1000. std::shared_ptr<Response> Delete(const char *path, const std::string &body,
  1001. const char *content_type) {
  1002. return cli_->Delete(path, body, content_type);
  1003. }
  1004. std::shared_ptr<Response> Delete(const char *path, const Headers &headers) {
  1005. return cli_->Delete(path, headers);
  1006. }
  1007. std::shared_ptr<Response> Delete(const char *path, const Headers &headers,
  1008. const std::string &body,
  1009. const char *content_type) {
  1010. return cli_->Delete(path, headers, body, content_type);
  1011. }
  1012. std::shared_ptr<Response> Options(const char *path) {
  1013. return cli_->Options(path);
  1014. }
  1015. std::shared_ptr<Response> Options(const char *path, const Headers &headers) {
  1016. return cli_->Options(path, headers);
  1017. }
  1018. bool send(const Request &req, Response &res) { return cli_->send(req, res); }
  1019. bool send(const std::vector<Request> &requests,
  1020. std::vector<Response> &responses) {
  1021. return cli_->send(requests, responses);
  1022. }
  1023. bool is_socket_open() { return cli_->is_socket_open(); }
  1024. void stop() { cli_->stop(); }
  1025. Client2 &set_connection_timeout(time_t sec, time_t usec) {
  1026. cli_->set_connection_timeout(sec, usec);
  1027. return *this;
  1028. }
  1029. Client2 &set_read_timeout(time_t sec, time_t usec) {
  1030. cli_->set_read_timeout(sec, usec);
  1031. return *this;
  1032. }
  1033. Client2 &set_keep_alive_max_count(size_t count) {
  1034. cli_->set_keep_alive_max_count(count);
  1035. return *this;
  1036. }
  1037. Client2 &set_basic_auth(const char *username, const char *password) {
  1038. cli_->set_basic_auth(username, password);
  1039. return *this;
  1040. }
  1041. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1042. Client2 &set_digest_auth(const char *username, const char *password) {
  1043. cli_->set_digest_auth(username, password);
  1044. return *this;
  1045. }
  1046. #endif
  1047. Client2 &set_follow_location(bool on) {
  1048. cli_->set_follow_location(on);
  1049. return *this;
  1050. }
  1051. Client2 &set_compress(bool on) {
  1052. cli_->set_compress(on);
  1053. return *this;
  1054. }
  1055. Client2 &set_decompress(bool on) {
  1056. cli_->set_decompress(on);
  1057. return *this;
  1058. }
  1059. Client2 &set_interface(const char *intf) {
  1060. cli_->set_interface(intf);
  1061. return *this;
  1062. }
  1063. Client2 &set_proxy(const char *host, int port) {
  1064. cli_->set_proxy(host, port);
  1065. return *this;
  1066. }
  1067. Client2 &set_proxy_basic_auth(const char *username, const char *password) {
  1068. cli_->set_proxy_basic_auth(username, password);
  1069. return *this;
  1070. }
  1071. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1072. Client2 &set_proxy_digest_auth(const char *username, const char *password) {
  1073. cli_->set_proxy_digest_auth(username, password);
  1074. return *this;
  1075. }
  1076. #endif
  1077. Client2 &set_logger(Logger logger) {
  1078. cli_->set_logger(logger);
  1079. return *this;
  1080. }
  1081. // SSL
  1082. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1083. Client2 &set_ca_cert_path(const char *ca_cert_file_path,
  1084. const char *ca_cert_dir_path = nullptr) {
  1085. if (is_ssl_) {
  1086. static_cast<SSLClient &>(*cli_).set_ca_cert_path(ca_cert_file_path,
  1087. ca_cert_dir_path);
  1088. }
  1089. return *this;
  1090. }
  1091. Client2 &set_ca_cert_store(X509_STORE *ca_cert_store) {
  1092. if (is_ssl_) {
  1093. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  1094. }
  1095. return *this;
  1096. }
  1097. Client2 &enable_server_certificate_verification(bool enabled) {
  1098. if (is_ssl_) {
  1099. static_cast<SSLClient &>(*cli_).enable_server_certificate_verification(
  1100. enabled);
  1101. }
  1102. return *this;
  1103. }
  1104. long get_openssl_verify_result() const {
  1105. if (is_ssl_) {
  1106. return static_cast<SSLClient &>(*cli_).get_openssl_verify_result();
  1107. }
  1108. return -1; // NOTE: -1 doesn't match any of X509_V_ERR_???
  1109. }
  1110. SSL_CTX *ssl_context() const {
  1111. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).ssl_context(); }
  1112. return nullptr;
  1113. }
  1114. #endif
  1115. private:
  1116. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1117. bool is_ssl_ = false;
  1118. #endif
  1119. std::shared_ptr<Client> cli_;
  1120. };
  1121. // ----------------------------------------------------------------------------
  1122. /*
  1123. * Implementation
  1124. */
  1125. namespace detail {
  1126. inline bool is_hex(char c, int &v) {
  1127. if (0x20 <= c && isdigit(c)) {
  1128. v = c - '0';
  1129. return true;
  1130. } else if ('A' <= c && c <= 'F') {
  1131. v = c - 'A' + 10;
  1132. return true;
  1133. } else if ('a' <= c && c <= 'f') {
  1134. v = c - 'a' + 10;
  1135. return true;
  1136. }
  1137. return false;
  1138. }
  1139. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  1140. int &val) {
  1141. if (i >= s.size()) { return false; }
  1142. val = 0;
  1143. for (; cnt; i++, cnt--) {
  1144. if (!s[i]) { return false; }
  1145. int v = 0;
  1146. if (is_hex(s[i], v)) {
  1147. val = val * 16 + v;
  1148. } else {
  1149. return false;
  1150. }
  1151. }
  1152. return true;
  1153. }
  1154. inline std::string from_i_to_hex(size_t n) {
  1155. const char *charset = "0123456789abcdef";
  1156. std::string ret;
  1157. do {
  1158. ret = charset[n & 15] + ret;
  1159. n >>= 4;
  1160. } while (n > 0);
  1161. return ret;
  1162. }
  1163. inline size_t to_utf8(int code, char *buff) {
  1164. if (code < 0x0080) {
  1165. buff[0] = (code & 0x7F);
  1166. return 1;
  1167. } else if (code < 0x0800) {
  1168. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  1169. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  1170. return 2;
  1171. } else if (code < 0xD800) {
  1172. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  1173. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  1174. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  1175. return 3;
  1176. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  1177. return 0;
  1178. } else if (code < 0x10000) {
  1179. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  1180. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  1181. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  1182. return 3;
  1183. } else if (code < 0x110000) {
  1184. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  1185. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  1186. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  1187. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  1188. return 4;
  1189. }
  1190. // NOTREACHED
  1191. return 0;
  1192. }
  1193. // NOTE: This code came up with the following stackoverflow post:
  1194. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  1195. inline std::string base64_encode(const std::string &in) {
  1196. static const auto lookup =
  1197. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  1198. std::string out;
  1199. out.reserve(in.size());
  1200. int val = 0;
  1201. int valb = -6;
  1202. for (auto c : in) {
  1203. val = (val << 8) + static_cast<uint8_t>(c);
  1204. valb += 8;
  1205. while (valb >= 0) {
  1206. out.push_back(lookup[(val >> valb) & 0x3F]);
  1207. valb -= 6;
  1208. }
  1209. }
  1210. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  1211. while (out.size() % 4) {
  1212. out.push_back('=');
  1213. }
  1214. return out;
  1215. }
  1216. inline bool is_file(const std::string &path) {
  1217. struct stat st;
  1218. return stat(path.c_str(), &st) >= 0 && S_ISREG(st.st_mode);
  1219. }
  1220. inline bool is_dir(const std::string &path) {
  1221. struct stat st;
  1222. return stat(path.c_str(), &st) >= 0 && S_ISDIR(st.st_mode);
  1223. }
  1224. inline bool is_valid_path(const std::string &path) {
  1225. size_t level = 0;
  1226. size_t i = 0;
  1227. // Skip slash
  1228. while (i < path.size() && path[i] == '/') {
  1229. i++;
  1230. }
  1231. while (i < path.size()) {
  1232. // Read component
  1233. auto beg = i;
  1234. while (i < path.size() && path[i] != '/') {
  1235. i++;
  1236. }
  1237. auto len = i - beg;
  1238. assert(len > 0);
  1239. if (!path.compare(beg, len, ".")) {
  1240. ;
  1241. } else if (!path.compare(beg, len, "..")) {
  1242. if (level == 0) { return false; }
  1243. level--;
  1244. } else {
  1245. level++;
  1246. }
  1247. // Skip slash
  1248. while (i < path.size() && path[i] == '/') {
  1249. i++;
  1250. }
  1251. }
  1252. return true;
  1253. }
  1254. inline void read_file(const std::string &path, std::string &out) {
  1255. std::ifstream fs(path, std::ios_base::binary);
  1256. fs.seekg(0, std::ios_base::end);
  1257. auto size = fs.tellg();
  1258. fs.seekg(0);
  1259. out.resize(static_cast<size_t>(size));
  1260. fs.read(&out[0], static_cast<std::streamsize>(size));
  1261. }
  1262. inline std::string file_extension(const std::string &path) {
  1263. std::smatch m;
  1264. static auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  1265. if (std::regex_search(path, m, re)) { return m[1].str(); }
  1266. return std::string();
  1267. }
  1268. template <class Fn> void split(const char *b, const char *e, char d, Fn fn) {
  1269. int i = 0;
  1270. int beg = 0;
  1271. while (e ? (b + i != e) : (b[i] != '\0')) {
  1272. if (b[i] == d) {
  1273. fn(&b[beg], &b[i]);
  1274. beg = i + 1;
  1275. }
  1276. i++;
  1277. }
  1278. if (i) { fn(&b[beg], &b[i]); }
  1279. }
  1280. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  1281. // to store data. The call can set memory on stack for performance.
  1282. class stream_line_reader {
  1283. public:
  1284. stream_line_reader(Stream &strm, char *fixed_buffer, size_t fixed_buffer_size)
  1285. : strm_(strm), fixed_buffer_(fixed_buffer),
  1286. fixed_buffer_size_(fixed_buffer_size) {}
  1287. const char *ptr() const {
  1288. if (glowable_buffer_.empty()) {
  1289. return fixed_buffer_;
  1290. } else {
  1291. return glowable_buffer_.data();
  1292. }
  1293. }
  1294. size_t size() const {
  1295. if (glowable_buffer_.empty()) {
  1296. return fixed_buffer_used_size_;
  1297. } else {
  1298. return glowable_buffer_.size();
  1299. }
  1300. }
  1301. bool end_with_crlf() const {
  1302. auto end = ptr() + size();
  1303. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  1304. }
  1305. bool getline() {
  1306. fixed_buffer_used_size_ = 0;
  1307. glowable_buffer_.clear();
  1308. for (size_t i = 0;; i++) {
  1309. char byte;
  1310. auto n = strm_.read(&byte, 1);
  1311. if (n < 0) {
  1312. return false;
  1313. } else if (n == 0) {
  1314. if (i == 0) {
  1315. return false;
  1316. } else {
  1317. break;
  1318. }
  1319. }
  1320. append(byte);
  1321. if (byte == '\n') { break; }
  1322. }
  1323. return true;
  1324. }
  1325. private:
  1326. void append(char c) {
  1327. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  1328. fixed_buffer_[fixed_buffer_used_size_++] = c;
  1329. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  1330. } else {
  1331. if (glowable_buffer_.empty()) {
  1332. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  1333. glowable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  1334. }
  1335. glowable_buffer_ += c;
  1336. }
  1337. }
  1338. Stream &strm_;
  1339. char *fixed_buffer_;
  1340. const size_t fixed_buffer_size_;
  1341. size_t fixed_buffer_used_size_ = 0;
  1342. std::string glowable_buffer_;
  1343. };
  1344. inline int close_socket(socket_t sock) {
  1345. #ifdef _WIN32
  1346. return closesocket(sock);
  1347. #else
  1348. return close(sock);
  1349. #endif
  1350. }
  1351. template <typename T> inline ssize_t handle_EINTR(T fn) {
  1352. ssize_t res = false;
  1353. while (true) {
  1354. res = fn();
  1355. if (res < 0 && errno == EINTR) { continue; }
  1356. break;
  1357. }
  1358. return res;
  1359. }
  1360. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  1361. #ifdef CPPHTTPLIB_USE_POLL
  1362. struct pollfd pfd_read;
  1363. pfd_read.fd = sock;
  1364. pfd_read.events = POLLIN;
  1365. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  1366. return handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); });
  1367. #else
  1368. fd_set fds;
  1369. FD_ZERO(&fds);
  1370. FD_SET(sock, &fds);
  1371. timeval tv;
  1372. tv.tv_sec = static_cast<long>(sec);
  1373. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  1374. return handle_EINTR([&]() {
  1375. return select(static_cast<int>(sock + 1), &fds, nullptr, nullptr, &tv);
  1376. });
  1377. #endif
  1378. }
  1379. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  1380. #ifdef CPPHTTPLIB_USE_POLL
  1381. struct pollfd pfd_read;
  1382. pfd_read.fd = sock;
  1383. pfd_read.events = POLLOUT;
  1384. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  1385. return handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); });
  1386. #else
  1387. fd_set fds;
  1388. FD_ZERO(&fds);
  1389. FD_SET(sock, &fds);
  1390. timeval tv;
  1391. tv.tv_sec = static_cast<long>(sec);
  1392. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  1393. return handle_EINTR([&]() {
  1394. return select(static_cast<int>(sock + 1), nullptr, &fds, nullptr, &tv);
  1395. });
  1396. #endif
  1397. }
  1398. inline bool wait_until_socket_is_ready(socket_t sock, time_t sec, time_t usec) {
  1399. #ifdef CPPHTTPLIB_USE_POLL
  1400. struct pollfd pfd_read;
  1401. pfd_read.fd = sock;
  1402. pfd_read.events = POLLIN | POLLOUT;
  1403. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  1404. auto poll_res = handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); });
  1405. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  1406. int error = 0;
  1407. socklen_t len = sizeof(error);
  1408. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  1409. reinterpret_cast<char *>(&error), &len);
  1410. return res >= 0 && !error;
  1411. }
  1412. return false;
  1413. #else
  1414. fd_set fdsr;
  1415. FD_ZERO(&fdsr);
  1416. FD_SET(sock, &fdsr);
  1417. auto fdsw = fdsr;
  1418. auto fdse = fdsr;
  1419. timeval tv;
  1420. tv.tv_sec = static_cast<long>(sec);
  1421. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  1422. auto ret = handle_EINTR([&]() {
  1423. return select(static_cast<int>(sock + 1), &fdsr, &fdsw, &fdse, &tv);
  1424. });
  1425. if (ret > 0 && (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) {
  1426. int error = 0;
  1427. socklen_t len = sizeof(error);
  1428. return getsockopt(sock, SOL_SOCKET, SO_ERROR,
  1429. reinterpret_cast<char *>(&error), &len) >= 0 &&
  1430. !error;
  1431. }
  1432. return false;
  1433. #endif
  1434. }
  1435. class SocketStream : public Stream {
  1436. public:
  1437. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  1438. time_t write_timeout_sec, time_t write_timeout_usec);
  1439. ~SocketStream() override;
  1440. bool is_readable() const override;
  1441. bool is_writable() const override;
  1442. ssize_t read(char *ptr, size_t size) override;
  1443. ssize_t write(const char *ptr, size_t size) override;
  1444. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  1445. private:
  1446. socket_t sock_;
  1447. time_t read_timeout_sec_;
  1448. time_t read_timeout_usec_;
  1449. time_t write_timeout_sec_;
  1450. time_t write_timeout_usec_;
  1451. };
  1452. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1453. class SSLSocketStream : public Stream {
  1454. public:
  1455. SSLSocketStream(socket_t sock, SSL *ssl, time_t read_timeout_sec,
  1456. time_t read_timeout_usec, time_t write_timeout_sec,
  1457. time_t write_timeout_usec);
  1458. ~SSLSocketStream() override;
  1459. bool is_readable() const override;
  1460. bool is_writable() const override;
  1461. ssize_t read(char *ptr, size_t size) override;
  1462. ssize_t write(const char *ptr, size_t size) override;
  1463. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  1464. private:
  1465. socket_t sock_;
  1466. SSL *ssl_;
  1467. time_t read_timeout_sec_;
  1468. time_t read_timeout_usec_;
  1469. time_t write_timeout_sec_;
  1470. time_t write_timeout_usec_;
  1471. };
  1472. #endif
  1473. class BufferStream : public Stream {
  1474. public:
  1475. BufferStream() = default;
  1476. ~BufferStream() override = default;
  1477. bool is_readable() const override;
  1478. bool is_writable() const override;
  1479. ssize_t read(char *ptr, size_t size) override;
  1480. ssize_t write(const char *ptr, size_t size) override;
  1481. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  1482. const std::string &get_buffer() const;
  1483. private:
  1484. std::string buffer;
  1485. size_t position = 0;
  1486. };
  1487. template <typename T>
  1488. inline bool process_socket_core(bool is_client_request, socket_t sock,
  1489. size_t keep_alive_max_count, T callback) {
  1490. assert(keep_alive_max_count > 0);
  1491. auto ret = false;
  1492. if (keep_alive_max_count > 1) {
  1493. auto count = keep_alive_max_count;
  1494. while (count > 0 &&
  1495. (is_client_request ||
  1496. select_read(sock, CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND,
  1497. CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND) > 0)) {
  1498. auto last_connection = count == 1;
  1499. auto connection_close = false;
  1500. ret = callback(last_connection, connection_close);
  1501. if (!ret || connection_close) { break; }
  1502. count--;
  1503. }
  1504. } else { // keep_alive_max_count is 0 or 1
  1505. auto dummy_connection_close = false;
  1506. ret = callback(true, dummy_connection_close);
  1507. }
  1508. return ret;
  1509. }
  1510. template <typename T>
  1511. inline bool process_socket(bool is_client_request, socket_t sock,
  1512. size_t keep_alive_max_count, time_t read_timeout_sec,
  1513. time_t read_timeout_usec, time_t write_timeout_sec,
  1514. time_t write_timeout_usec, T callback) {
  1515. return process_socket_core(
  1516. is_client_request, sock, keep_alive_max_count,
  1517. [&](bool last_connection, bool connection_close) {
  1518. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  1519. write_timeout_sec, write_timeout_usec);
  1520. return callback(strm, last_connection, connection_close);
  1521. });
  1522. }
  1523. inline int shutdown_socket(socket_t sock) {
  1524. #ifdef _WIN32
  1525. return shutdown(sock, SD_BOTH);
  1526. #else
  1527. return shutdown(sock, SHUT_RDWR);
  1528. #endif
  1529. }
  1530. template <typename BindOrConnect>
  1531. socket_t create_socket(const char *host, int port, int socket_flags,
  1532. SocketOptions socket_options,
  1533. BindOrConnect bind_or_connect) {
  1534. // Get address info
  1535. struct addrinfo hints;
  1536. struct addrinfo *result;
  1537. memset(&hints, 0, sizeof(struct addrinfo));
  1538. hints.ai_family = AF_UNSPEC;
  1539. hints.ai_socktype = SOCK_STREAM;
  1540. hints.ai_flags = socket_flags;
  1541. hints.ai_protocol = 0;
  1542. auto service = std::to_string(port);
  1543. if (getaddrinfo(host, service.c_str(), &hints, &result)) {
  1544. return INVALID_SOCKET;
  1545. }
  1546. for (auto rp = result; rp; rp = rp->ai_next) {
  1547. // Create a socket
  1548. #ifdef _WIN32
  1549. auto sock = WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol,
  1550. nullptr, 0, WSA_FLAG_NO_HANDLE_INHERIT);
  1551. /**
  1552. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  1553. * and above the socket creation fails on older Windows Systems.
  1554. *
  1555. * Let's try to create a socket the old way in this case.
  1556. *
  1557. * Reference:
  1558. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  1559. *
  1560. * WSA_FLAG_NO_HANDLE_INHERIT:
  1561. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  1562. * SP1, and later
  1563. *
  1564. */
  1565. if (sock == INVALID_SOCKET) {
  1566. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  1567. }
  1568. #else
  1569. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  1570. #endif
  1571. if (sock == INVALID_SOCKET) { continue; }
  1572. #ifndef _WIN32
  1573. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) { continue; }
  1574. #endif
  1575. if (socket_options) { socket_options(sock); }
  1576. // Make 'reuse address' option available
  1577. int yes = 1;
  1578. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char *>(&yes),
  1579. sizeof(yes));
  1580. #ifdef SO_REUSEPORT
  1581. setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, reinterpret_cast<char *>(&yes),
  1582. sizeof(yes));
  1583. #endif
  1584. if (rp->ai_family == AF_INET6) {
  1585. int no = 0;
  1586. setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<char *>(&no),
  1587. sizeof(no));
  1588. }
  1589. // bind or connect
  1590. if (bind_or_connect(sock, *rp)) {
  1591. freeaddrinfo(result);
  1592. return sock;
  1593. }
  1594. close_socket(sock);
  1595. }
  1596. freeaddrinfo(result);
  1597. return INVALID_SOCKET;
  1598. }
  1599. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  1600. #ifdef _WIN32
  1601. auto flags = nonblocking ? 1UL : 0UL;
  1602. ioctlsocket(sock, FIONBIO, &flags);
  1603. #else
  1604. auto flags = fcntl(sock, F_GETFL, 0);
  1605. fcntl(sock, F_SETFL,
  1606. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  1607. #endif
  1608. }
  1609. inline bool is_connection_error() {
  1610. #ifdef _WIN32
  1611. return WSAGetLastError() != WSAEWOULDBLOCK;
  1612. #else
  1613. return errno != EINPROGRESS;
  1614. #endif
  1615. }
  1616. inline bool bind_ip_address(socket_t sock, const char *host) {
  1617. struct addrinfo hints;
  1618. struct addrinfo *result;
  1619. memset(&hints, 0, sizeof(struct addrinfo));
  1620. hints.ai_family = AF_UNSPEC;
  1621. hints.ai_socktype = SOCK_STREAM;
  1622. hints.ai_protocol = 0;
  1623. if (getaddrinfo(host, "0", &hints, &result)) { return false; }
  1624. auto ret = false;
  1625. for (auto rp = result; rp; rp = rp->ai_next) {
  1626. const auto &ai = *rp;
  1627. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  1628. ret = true;
  1629. break;
  1630. }
  1631. }
  1632. freeaddrinfo(result);
  1633. return ret;
  1634. }
  1635. #ifndef _WIN32
  1636. inline std::string if2ip(const std::string &ifn) {
  1637. struct ifaddrs *ifap;
  1638. getifaddrs(&ifap);
  1639. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  1640. if (ifa->ifa_addr && ifn == ifa->ifa_name) {
  1641. if (ifa->ifa_addr->sa_family == AF_INET) {
  1642. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  1643. char buf[INET_ADDRSTRLEN];
  1644. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  1645. freeifaddrs(ifap);
  1646. return std::string(buf, INET_ADDRSTRLEN);
  1647. }
  1648. }
  1649. }
  1650. }
  1651. freeifaddrs(ifap);
  1652. return std::string();
  1653. }
  1654. #endif
  1655. inline socket_t create_client_socket(const char *host, int port,
  1656. SocketOptions socket_options,
  1657. time_t timeout_sec, time_t timeout_usec,
  1658. const std::string &intf) {
  1659. return create_socket(
  1660. host, port, 0, socket_options,
  1661. [&](socket_t sock, struct addrinfo &ai) -> bool {
  1662. if (!intf.empty()) {
  1663. #ifndef _WIN32
  1664. auto ip = if2ip(intf);
  1665. if (ip.empty()) { ip = intf; }
  1666. if (!bind_ip_address(sock, ip.c_str())) { return false; }
  1667. #endif
  1668. }
  1669. set_nonblocking(sock, true);
  1670. auto ret =
  1671. ::connect(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  1672. if (ret < 0) {
  1673. if (is_connection_error() ||
  1674. !wait_until_socket_is_ready(sock, timeout_sec, timeout_usec)) {
  1675. close_socket(sock);
  1676. return false;
  1677. }
  1678. }
  1679. set_nonblocking(sock, false);
  1680. return true;
  1681. });
  1682. }
  1683. inline void get_remote_ip_and_port(const struct sockaddr_storage &addr,
  1684. socklen_t addr_len, std::string &ip,
  1685. int &port) {
  1686. if (addr.ss_family == AF_INET) {
  1687. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  1688. } else if (addr.ss_family == AF_INET6) {
  1689. port =
  1690. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  1691. }
  1692. std::array<char, NI_MAXHOST> ipstr{};
  1693. if (!getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  1694. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  1695. 0, NI_NUMERICHOST)) {
  1696. ip = ipstr.data();
  1697. }
  1698. }
  1699. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  1700. struct sockaddr_storage addr;
  1701. socklen_t addr_len = sizeof(addr);
  1702. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  1703. &addr_len)) {
  1704. get_remote_ip_and_port(addr, addr_len, ip, port);
  1705. }
  1706. }
  1707. inline const char *
  1708. find_content_type(const std::string &path,
  1709. const std::map<std::string, std::string> &user_data) {
  1710. auto ext = file_extension(path);
  1711. auto it = user_data.find(ext);
  1712. if (it != user_data.end()) { return it->second.c_str(); }
  1713. if (ext == "txt") {
  1714. return "text/plain";
  1715. } else if (ext == "html" || ext == "htm") {
  1716. return "text/html";
  1717. } else if (ext == "css") {
  1718. return "text/css";
  1719. } else if (ext == "jpeg" || ext == "jpg") {
  1720. return "image/jpg";
  1721. } else if (ext == "png") {
  1722. return "image/png";
  1723. } else if (ext == "gif") {
  1724. return "image/gif";
  1725. } else if (ext == "svg") {
  1726. return "image/svg+xml";
  1727. } else if (ext == "ico") {
  1728. return "image/x-icon";
  1729. } else if (ext == "json") {
  1730. return "application/json";
  1731. } else if (ext == "pdf") {
  1732. return "application/pdf";
  1733. } else if (ext == "js") {
  1734. return "application/javascript";
  1735. } else if (ext == "wasm") {
  1736. return "application/wasm";
  1737. } else if (ext == "xml") {
  1738. return "application/xml";
  1739. } else if (ext == "xhtml") {
  1740. return "application/xhtml+xml";
  1741. }
  1742. return nullptr;
  1743. }
  1744. inline const char *status_message(int status) {
  1745. switch (status) {
  1746. case 100: return "Continue";
  1747. case 101: return "Switching Protocol";
  1748. case 102: return "Processing";
  1749. case 103: return "Early Hints";
  1750. case 200: return "OK";
  1751. case 201: return "Created";
  1752. case 202: return "Accepted";
  1753. case 203: return "Non-Authoritative Information";
  1754. case 204: return "No Content";
  1755. case 205: return "Reset Content";
  1756. case 206: return "Partial Content";
  1757. case 207: return "Multi-Status";
  1758. case 208: return "Already Reported";
  1759. case 226: return "IM Used";
  1760. case 300: return "Multiple Choice";
  1761. case 301: return "Moved Permanently";
  1762. case 302: return "Found";
  1763. case 303: return "See Other";
  1764. case 304: return "Not Modified";
  1765. case 305: return "Use Proxy";
  1766. case 306: return "unused";
  1767. case 307: return "Temporary Redirect";
  1768. case 308: return "Permanent Redirect";
  1769. case 400: return "Bad Request";
  1770. case 401: return "Unauthorized";
  1771. case 402: return "Payment Required";
  1772. case 403: return "Forbidden";
  1773. case 404: return "Not Found";
  1774. case 405: return "Method Not Allowed";
  1775. case 406: return "Not Acceptable";
  1776. case 407: return "Proxy Authentication Required";
  1777. case 408: return "Request Timeout";
  1778. case 409: return "Conflict";
  1779. case 410: return "Gone";
  1780. case 411: return "Length Required";
  1781. case 412: return "Precondition Failed";
  1782. case 413: return "Payload Too Large";
  1783. case 414: return "URI Too Long";
  1784. case 415: return "Unsupported Media Type";
  1785. case 416: return "Range Not Satisfiable";
  1786. case 417: return "Expectation Failed";
  1787. case 418: return "I'm a teapot";
  1788. case 421: return "Misdirected Request";
  1789. case 422: return "Unprocessable Entity";
  1790. case 423: return "Locked";
  1791. case 424: return "Failed Dependency";
  1792. case 425: return "Too Early";
  1793. case 426: return "Upgrade Required";
  1794. case 428: return "Precondition Required";
  1795. case 429: return "Too Many Requests";
  1796. case 431: return "Request Header Fields Too Large";
  1797. case 451: return "Unavailable For Legal Reasons";
  1798. case 501: return "Not Implemented";
  1799. case 502: return "Bad Gateway";
  1800. case 503: return "Service Unavailable";
  1801. case 504: return "Gateway Timeout";
  1802. case 505: return "HTTP Version Not Supported";
  1803. case 506: return "Variant Also Negotiates";
  1804. case 507: return "Insufficient Storage";
  1805. case 508: return "Loop Detected";
  1806. case 510: return "Not Extended";
  1807. case 511: return "Network Authentication Required";
  1808. default:
  1809. case 500: return "Internal Server Error";
  1810. }
  1811. }
  1812. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1813. inline bool can_compress(const std::string &content_type) {
  1814. return !content_type.find("text/") || content_type == "image/svg+xml" ||
  1815. content_type == "application/javascript" ||
  1816. content_type == "application/json" ||
  1817. content_type == "application/xml" ||
  1818. content_type == "application/xhtml+xml";
  1819. }
  1820. inline bool compress(std::string &content) {
  1821. z_stream strm;
  1822. strm.zalloc = Z_NULL;
  1823. strm.zfree = Z_NULL;
  1824. strm.opaque = Z_NULL;
  1825. auto ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  1826. Z_DEFAULT_STRATEGY);
  1827. if (ret != Z_OK) { return false; }
  1828. strm.avail_in = static_cast<decltype(strm.avail_in)>(content.size());
  1829. strm.next_in =
  1830. const_cast<Bytef *>(reinterpret_cast<const Bytef *>(content.data()));
  1831. std::string compressed;
  1832. std::array<char, 16384> buff{};
  1833. do {
  1834. strm.avail_out = buff.size();
  1835. strm.next_out = reinterpret_cast<Bytef *>(buff.data());
  1836. ret = deflate(&strm, Z_FINISH);
  1837. assert(ret != Z_STREAM_ERROR);
  1838. compressed.append(buff.data(), buff.size() - strm.avail_out);
  1839. } while (strm.avail_out == 0);
  1840. assert(ret == Z_STREAM_END);
  1841. assert(strm.avail_in == 0);
  1842. content.swap(compressed);
  1843. deflateEnd(&strm);
  1844. return true;
  1845. }
  1846. class decompressor {
  1847. public:
  1848. decompressor() {
  1849. std::memset(&strm, 0, sizeof(strm));
  1850. strm.zalloc = Z_NULL;
  1851. strm.zfree = Z_NULL;
  1852. strm.opaque = Z_NULL;
  1853. // 15 is the value of wbits, which should be at the maximum possible value
  1854. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  1855. // that the stream type should be automatically detected either gzip or
  1856. // deflate.
  1857. is_valid_ = inflateInit2(&strm, 32 + 15) == Z_OK;
  1858. }
  1859. ~decompressor() { inflateEnd(&strm); }
  1860. bool is_valid() const { return is_valid_; }
  1861. template <typename T>
  1862. bool decompress(const char *data, size_t data_length, T callback) {
  1863. int ret = Z_OK;
  1864. strm.avail_in = static_cast<decltype(strm.avail_in)>(data_length);
  1865. strm.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  1866. std::array<char, 16384> buff{};
  1867. do {
  1868. strm.avail_out = buff.size();
  1869. strm.next_out = reinterpret_cast<Bytef *>(buff.data());
  1870. ret = inflate(&strm, Z_NO_FLUSH);
  1871. assert(ret != Z_STREAM_ERROR);
  1872. switch (ret) {
  1873. case Z_NEED_DICT:
  1874. case Z_DATA_ERROR:
  1875. case Z_MEM_ERROR: inflateEnd(&strm); return false;
  1876. }
  1877. if (!callback(buff.data(), buff.size() - strm.avail_out)) {
  1878. return false;
  1879. }
  1880. } while (strm.avail_out == 0);
  1881. return ret == Z_OK || ret == Z_STREAM_END;
  1882. }
  1883. private:
  1884. bool is_valid_;
  1885. z_stream strm;
  1886. };
  1887. #endif
  1888. inline bool has_header(const Headers &headers, const char *key) {
  1889. return headers.find(key) != headers.end();
  1890. }
  1891. inline const char *get_header_value(const Headers &headers, const char *key,
  1892. size_t id = 0, const char *def = nullptr) {
  1893. auto rng = headers.equal_range(key);
  1894. auto it = rng.first;
  1895. std::advance(it, static_cast<ssize_t>(id));
  1896. if (it != rng.second) { return it->second.c_str(); }
  1897. return def;
  1898. }
  1899. inline uint64_t get_header_value_uint64(const Headers &headers, const char *key,
  1900. uint64_t def = 0) {
  1901. auto it = headers.find(key);
  1902. if (it != headers.end()) {
  1903. return std::strtoull(it->second.data(), nullptr, 10);
  1904. }
  1905. return def;
  1906. }
  1907. inline void parse_header(const char *beg, const char *end, Headers &headers) {
  1908. auto p = beg;
  1909. while (p < end && *p != ':') {
  1910. p++;
  1911. }
  1912. if (p < end) {
  1913. auto key_end = p;
  1914. p++; // skip ':'
  1915. while (p < end && (*p == ' ' || *p == '\t')) {
  1916. p++;
  1917. }
  1918. if (p < end) {
  1919. auto val_begin = p;
  1920. while (p < end) {
  1921. p++;
  1922. }
  1923. headers.emplace(std::string(beg, key_end), std::string(val_begin, end));
  1924. }
  1925. }
  1926. }
  1927. inline bool read_headers(Stream &strm, Headers &headers) {
  1928. const auto bufsiz = 2048;
  1929. char buf[bufsiz];
  1930. stream_line_reader line_reader(strm, buf, bufsiz);
  1931. for (;;) {
  1932. if (!line_reader.getline()) { return false; }
  1933. // Check if the line ends with CRLF.
  1934. if (line_reader.end_with_crlf()) {
  1935. // Blank line indicates end of headers.
  1936. if (line_reader.size() == 2) { break; }
  1937. } else {
  1938. continue; // Skip invalid line.
  1939. }
  1940. // Skip trailing spaces and tabs.
  1941. auto end = line_reader.ptr() + line_reader.size() - 2;
  1942. while (line_reader.ptr() < end && (end[-1] == ' ' || end[-1] == '\t')) {
  1943. end--;
  1944. }
  1945. parse_header(line_reader.ptr(), end, headers);
  1946. }
  1947. return true;
  1948. }
  1949. inline bool read_content_with_length(Stream &strm, uint64_t len,
  1950. Progress progress, ContentReceiver out) {
  1951. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  1952. uint64_t r = 0;
  1953. while (r < len) {
  1954. auto read_len = static_cast<size_t>(len - r);
  1955. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  1956. if (n <= 0) { return false; }
  1957. if (!out(buf, static_cast<size_t>(n))) { return false; }
  1958. r += static_cast<uint64_t>(n);
  1959. if (progress) {
  1960. if (!progress(r, len)) { return false; }
  1961. }
  1962. }
  1963. return true;
  1964. }
  1965. inline void skip_content_with_length(Stream &strm, uint64_t len) {
  1966. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  1967. uint64_t r = 0;
  1968. while (r < len) {
  1969. auto read_len = static_cast<size_t>(len - r);
  1970. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  1971. if (n <= 0) { return; }
  1972. r += static_cast<uint64_t>(n);
  1973. }
  1974. }
  1975. inline bool read_content_without_length(Stream &strm, ContentReceiver out) {
  1976. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  1977. for (;;) {
  1978. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  1979. if (n < 0) {
  1980. return false;
  1981. } else if (n == 0) {
  1982. return true;
  1983. }
  1984. if (!out(buf, static_cast<size_t>(n))) { return false; }
  1985. }
  1986. return true;
  1987. }
  1988. inline bool read_content_chunked(Stream &strm, ContentReceiver out) {
  1989. const auto bufsiz = 16;
  1990. char buf[bufsiz];
  1991. stream_line_reader line_reader(strm, buf, bufsiz);
  1992. if (!line_reader.getline()) { return false; }
  1993. unsigned long chunk_len;
  1994. while (true) {
  1995. char *end_ptr;
  1996. chunk_len = std::strtoul(line_reader.ptr(), &end_ptr, 16);
  1997. if (end_ptr == line_reader.ptr()) { return false; }
  1998. if (chunk_len == ULONG_MAX) { return false; }
  1999. if (chunk_len == 0) { break; }
  2000. if (!read_content_with_length(strm, chunk_len, nullptr, out)) {
  2001. return false;
  2002. }
  2003. if (!line_reader.getline()) { return false; }
  2004. if (strcmp(line_reader.ptr(), "\r\n")) { break; }
  2005. if (!line_reader.getline()) { return false; }
  2006. }
  2007. if (chunk_len == 0) {
  2008. // Reader terminator after chunks
  2009. if (!line_reader.getline() || strcmp(line_reader.ptr(), "\r\n"))
  2010. return false;
  2011. }
  2012. return true;
  2013. }
  2014. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  2015. return !strcasecmp(get_header_value(headers, "Transfer-Encoding", 0, ""),
  2016. "chunked");
  2017. }
  2018. template <typename T>
  2019. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  2020. Progress progress, ContentReceiver receiver,
  2021. bool decompress) {
  2022. ContentReceiver out = [&](const char *buf, size_t n) {
  2023. return receiver(buf, n);
  2024. };
  2025. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2026. decompressor decompressor;
  2027. #endif
  2028. if (decompress) {
  2029. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2030. std::string content_encoding = x.get_header_value("Content-Encoding");
  2031. if (content_encoding.find("gzip") != std::string::npos ||
  2032. content_encoding.find("deflate") != std::string::npos) {
  2033. if (!decompressor.is_valid()) {
  2034. status = 500;
  2035. return false;
  2036. }
  2037. out = [&](const char *buf, size_t n) {
  2038. return decompressor.decompress(buf, n, [&](const char *buf, size_t n) {
  2039. return receiver(buf, n);
  2040. });
  2041. };
  2042. }
  2043. #else
  2044. if (x.get_header_value("Content-Encoding") == "gzip") {
  2045. status = 415;
  2046. return false;
  2047. }
  2048. #endif
  2049. }
  2050. auto ret = true;
  2051. auto exceed_payload_max_length = false;
  2052. if (is_chunked_transfer_encoding(x.headers)) {
  2053. ret = read_content_chunked(strm, out);
  2054. } else if (!has_header(x.headers, "Content-Length")) {
  2055. ret = read_content_without_length(strm, out);
  2056. } else {
  2057. auto len = get_header_value_uint64(x.headers, "Content-Length", 0);
  2058. if (len > payload_max_length) {
  2059. exceed_payload_max_length = true;
  2060. skip_content_with_length(strm, len);
  2061. ret = false;
  2062. } else if (len > 0) {
  2063. ret = read_content_with_length(strm, len, progress, out);
  2064. }
  2065. }
  2066. if (!ret) { status = exceed_payload_max_length ? 413 : 400; }
  2067. return ret;
  2068. }
  2069. template <typename T>
  2070. inline ssize_t write_headers(Stream &strm, const T &info,
  2071. const Headers &headers) {
  2072. ssize_t write_len = 0;
  2073. for (const auto &x : info.headers) {
  2074. if (x.first == "EXCEPTION_WHAT") { continue; }
  2075. auto len =
  2076. strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str());
  2077. if (len < 0) { return len; }
  2078. write_len += len;
  2079. }
  2080. for (const auto &x : headers) {
  2081. auto len =
  2082. strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str());
  2083. if (len < 0) { return len; }
  2084. write_len += len;
  2085. }
  2086. auto len = strm.write("\r\n");
  2087. if (len < 0) { return len; }
  2088. write_len += len;
  2089. return write_len;
  2090. }
  2091. inline bool write_data(Stream &strm, const char *d, size_t l) {
  2092. size_t offset = 0;
  2093. while (offset < l) {
  2094. auto length = strm.write(d + offset, l - offset);
  2095. if (length < 0) { return false; }
  2096. offset += static_cast<size_t>(length);
  2097. }
  2098. return true;
  2099. }
  2100. inline ssize_t write_content(Stream &strm, ContentProvider content_provider,
  2101. size_t offset, size_t length) {
  2102. size_t begin_offset = offset;
  2103. size_t end_offset = offset + length;
  2104. auto ok = true;
  2105. DataSink data_sink;
  2106. data_sink.write = [&](const char *d, size_t l) {
  2107. if (ok) {
  2108. offset += l;
  2109. if (!write_data(strm, d, l)) { ok = false; }
  2110. }
  2111. };
  2112. data_sink.is_writable = [&](void) { return ok && strm.is_writable(); };
  2113. while (ok && offset < end_offset) {
  2114. if (!content_provider(offset, end_offset - offset, data_sink)) {
  2115. return -1;
  2116. }
  2117. if (!ok) { return -1; }
  2118. }
  2119. return static_cast<ssize_t>(offset - begin_offset);
  2120. }
  2121. template <typename T>
  2122. inline ssize_t write_content_chunked(Stream &strm,
  2123. ContentProvider content_provider,
  2124. T is_shutting_down) {
  2125. size_t offset = 0;
  2126. auto data_available = true;
  2127. ssize_t total_written_length = 0;
  2128. auto ok = true;
  2129. DataSink data_sink;
  2130. data_sink.write = [&](const char *d, size_t l) {
  2131. if (ok) {
  2132. data_available = l > 0;
  2133. offset += l;
  2134. // Emit chunked response header and footer for each chunk
  2135. auto chunk = from_i_to_hex(l) + "\r\n" + std::string(d, l) + "\r\n";
  2136. if (write_data(strm, chunk.data(), chunk.size())) {
  2137. total_written_length += chunk.size();
  2138. } else {
  2139. ok = false;
  2140. }
  2141. }
  2142. };
  2143. data_sink.done = [&](void) {
  2144. data_available = false;
  2145. if (ok) {
  2146. static const std::string done_marker("0\r\n\r\n");
  2147. if (write_data(strm, done_marker.data(), done_marker.size())) {
  2148. total_written_length += done_marker.size();
  2149. } else {
  2150. ok = false;
  2151. }
  2152. }
  2153. };
  2154. data_sink.is_writable = [&](void) { return ok && strm.is_writable(); };
  2155. while (data_available && !is_shutting_down()) {
  2156. if (!content_provider(offset, 0, data_sink)) { return -1; }
  2157. if (!ok) { return -1; }
  2158. }
  2159. return total_written_length;
  2160. }
  2161. template <typename T>
  2162. inline bool redirect(T &cli, const Request &req, Response &res,
  2163. const std::string &path) {
  2164. Request new_req = req;
  2165. new_req.path = path;
  2166. new_req.redirect_count -= 1;
  2167. if (res.status == 303 && (req.method != "GET" && req.method != "HEAD")) {
  2168. new_req.method = "GET";
  2169. new_req.body.clear();
  2170. new_req.headers.clear();
  2171. }
  2172. Response new_res;
  2173. auto ret = cli.send(new_req, new_res);
  2174. if (ret) { res = new_res; }
  2175. return ret;
  2176. }
  2177. inline std::string encode_url(const std::string &s) {
  2178. std::string result;
  2179. for (size_t i = 0; s[i]; i++) {
  2180. switch (s[i]) {
  2181. case ' ': result += "%20"; break;
  2182. case '+': result += "%2B"; break;
  2183. case '\r': result += "%0D"; break;
  2184. case '\n': result += "%0A"; break;
  2185. case '\'': result += "%27"; break;
  2186. case ',': result += "%2C"; break;
  2187. // case ':': result += "%3A"; break; // ok? probably...
  2188. case ';': result += "%3B"; break;
  2189. default:
  2190. auto c = static_cast<uint8_t>(s[i]);
  2191. if (c >= 0x80) {
  2192. result += '%';
  2193. char hex[4];
  2194. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  2195. assert(len == 2);
  2196. result.append(hex, static_cast<size_t>(len));
  2197. } else {
  2198. result += s[i];
  2199. }
  2200. break;
  2201. }
  2202. }
  2203. return result;
  2204. }
  2205. inline std::string decode_url(const std::string &s,
  2206. bool convert_plus_to_space) {
  2207. std::string result;
  2208. for (size_t i = 0; i < s.size(); i++) {
  2209. if (s[i] == '%' && i + 1 < s.size()) {
  2210. if (s[i + 1] == 'u') {
  2211. int val = 0;
  2212. if (from_hex_to_i(s, i + 2, 4, val)) {
  2213. // 4 digits Unicode codes
  2214. char buff[4];
  2215. size_t len = to_utf8(val, buff);
  2216. if (len > 0) { result.append(buff, len); }
  2217. i += 5; // 'u0000'
  2218. } else {
  2219. result += s[i];
  2220. }
  2221. } else {
  2222. int val = 0;
  2223. if (from_hex_to_i(s, i + 1, 2, val)) {
  2224. // 2 digits hex codes
  2225. result += static_cast<char>(val);
  2226. i += 2; // '00'
  2227. } else {
  2228. result += s[i];
  2229. }
  2230. }
  2231. } else if (convert_plus_to_space && s[i] == '+') {
  2232. result += ' ';
  2233. } else {
  2234. result += s[i];
  2235. }
  2236. }
  2237. return result;
  2238. }
  2239. inline std::string params_to_query_str(const Params &params) {
  2240. std::string query;
  2241. for (auto it = params.begin(); it != params.end(); ++it) {
  2242. if (it != params.begin()) { query += "&"; }
  2243. query += it->first;
  2244. query += "=";
  2245. query += detail::encode_url(it->second);
  2246. }
  2247. return query;
  2248. }
  2249. inline void parse_query_text(const std::string &s, Params &params) {
  2250. split(&s[0], &s[s.size()], '&', [&](const char *b, const char *e) {
  2251. std::string key;
  2252. std::string val;
  2253. split(b, e, '=', [&](const char *b2, const char *e2) {
  2254. if (key.empty()) {
  2255. key.assign(b2, e2);
  2256. } else {
  2257. val.assign(b2, e2);
  2258. }
  2259. });
  2260. params.emplace(decode_url(key, true), decode_url(val, true));
  2261. });
  2262. }
  2263. inline bool parse_multipart_boundary(const std::string &content_type,
  2264. std::string &boundary) {
  2265. auto pos = content_type.find("boundary=");
  2266. if (pos == std::string::npos) { return false; }
  2267. boundary = content_type.substr(pos + 9);
  2268. return true;
  2269. }
  2270. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  2271. static auto re_first_range = std::regex(R"(bytes=(\d*-\d*(?:,\s*\d*-\d*)*))");
  2272. std::smatch m;
  2273. if (std::regex_match(s, m, re_first_range)) {
  2274. auto pos = static_cast<size_t>(m.position(1));
  2275. auto len = static_cast<size_t>(m.length(1));
  2276. bool all_valid_ranges = true;
  2277. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  2278. if (!all_valid_ranges) return;
  2279. static auto re_another_range = std::regex(R"(\s*(\d*)-(\d*))");
  2280. std::cmatch cm;
  2281. if (std::regex_match(b, e, cm, re_another_range)) {
  2282. ssize_t first = -1;
  2283. if (!cm.str(1).empty()) {
  2284. first = static_cast<ssize_t>(std::stoll(cm.str(1)));
  2285. }
  2286. ssize_t last = -1;
  2287. if (!cm.str(2).empty()) {
  2288. last = static_cast<ssize_t>(std::stoll(cm.str(2)));
  2289. }
  2290. if (first != -1 && last != -1 && first > last) {
  2291. all_valid_ranges = false;
  2292. return;
  2293. }
  2294. ranges.emplace_back(std::make_pair(first, last));
  2295. }
  2296. });
  2297. return all_valid_ranges;
  2298. }
  2299. return false;
  2300. }
  2301. class MultipartFormDataParser {
  2302. public:
  2303. MultipartFormDataParser() = default;
  2304. void set_boundary(std::string boundary) { boundary_ = std::move(boundary); }
  2305. bool is_valid() const { return is_valid_; }
  2306. template <typename T, typename U>
  2307. bool parse(const char *buf, size_t n, T content_callback, U header_callback) {
  2308. static const std::regex re_content_type(R"(^Content-Type:\s*(.*?)\s*$)",
  2309. std::regex_constants::icase);
  2310. static const std::regex re_content_disposition(
  2311. "^Content-Disposition:\\s*form-data;\\s*name=\"(.*?)\"(?:;\\s*filename="
  2312. "\"(.*?)\")?\\s*$",
  2313. std::regex_constants::icase);
  2314. static const std::string dash_ = "--";
  2315. static const std::string crlf_ = "\r\n";
  2316. buf_.append(buf, n); // TODO: performance improvement
  2317. while (!buf_.empty()) {
  2318. switch (state_) {
  2319. case 0: { // Initial boundary
  2320. auto pattern = dash_ + boundary_ + crlf_;
  2321. if (pattern.size() > buf_.size()) { return true; }
  2322. auto pos = buf_.find(pattern);
  2323. if (pos != 0) {
  2324. is_done_ = true;
  2325. return false;
  2326. }
  2327. buf_.erase(0, pattern.size());
  2328. off_ += pattern.size();
  2329. state_ = 1;
  2330. break;
  2331. }
  2332. case 1: { // New entry
  2333. clear_file_info();
  2334. state_ = 2;
  2335. break;
  2336. }
  2337. case 2: { // Headers
  2338. auto pos = buf_.find(crlf_);
  2339. while (pos != std::string::npos) {
  2340. // Empty line
  2341. if (pos == 0) {
  2342. if (!header_callback(file_)) {
  2343. is_valid_ = false;
  2344. is_done_ = false;
  2345. return false;
  2346. }
  2347. buf_.erase(0, crlf_.size());
  2348. off_ += crlf_.size();
  2349. state_ = 3;
  2350. break;
  2351. }
  2352. auto header = buf_.substr(0, pos);
  2353. {
  2354. std::smatch m;
  2355. if (std::regex_match(header, m, re_content_type)) {
  2356. file_.content_type = m[1];
  2357. } else if (std::regex_match(header, m, re_content_disposition)) {
  2358. file_.name = m[1];
  2359. file_.filename = m[2];
  2360. }
  2361. }
  2362. buf_.erase(0, pos + crlf_.size());
  2363. off_ += pos + crlf_.size();
  2364. pos = buf_.find(crlf_);
  2365. }
  2366. break;
  2367. }
  2368. case 3: { // Body
  2369. {
  2370. auto pattern = crlf_ + dash_;
  2371. if (pattern.size() > buf_.size()) { return true; }
  2372. auto pos = buf_.find(pattern);
  2373. if (pos == std::string::npos) { pos = buf_.size(); }
  2374. if (!content_callback(buf_.data(), pos)) {
  2375. is_valid_ = false;
  2376. is_done_ = false;
  2377. return false;
  2378. }
  2379. off_ += pos;
  2380. buf_.erase(0, pos);
  2381. }
  2382. {
  2383. auto pattern = crlf_ + dash_ + boundary_;
  2384. if (pattern.size() > buf_.size()) { return true; }
  2385. auto pos = buf_.find(pattern);
  2386. if (pos != std::string::npos) {
  2387. if (!content_callback(buf_.data(), pos)) {
  2388. is_valid_ = false;
  2389. is_done_ = false;
  2390. return false;
  2391. }
  2392. off_ += pos + pattern.size();
  2393. buf_.erase(0, pos + pattern.size());
  2394. state_ = 4;
  2395. } else {
  2396. if (!content_callback(buf_.data(), pattern.size())) {
  2397. is_valid_ = false;
  2398. is_done_ = false;
  2399. return false;
  2400. }
  2401. off_ += pattern.size();
  2402. buf_.erase(0, pattern.size());
  2403. }
  2404. }
  2405. break;
  2406. }
  2407. case 4: { // Boundary
  2408. if (crlf_.size() > buf_.size()) { return true; }
  2409. if (buf_.find(crlf_) == 0) {
  2410. buf_.erase(0, crlf_.size());
  2411. off_ += crlf_.size();
  2412. state_ = 1;
  2413. } else {
  2414. auto pattern = dash_ + crlf_;
  2415. if (pattern.size() > buf_.size()) { return true; }
  2416. if (buf_.find(pattern) == 0) {
  2417. buf_.erase(0, pattern.size());
  2418. off_ += pattern.size();
  2419. is_valid_ = true;
  2420. state_ = 5;
  2421. } else {
  2422. is_done_ = true;
  2423. return true;
  2424. }
  2425. }
  2426. break;
  2427. }
  2428. case 5: { // Done
  2429. is_valid_ = false;
  2430. return false;
  2431. }
  2432. }
  2433. }
  2434. return true;
  2435. }
  2436. private:
  2437. void clear_file_info() {
  2438. file_.name.clear();
  2439. file_.filename.clear();
  2440. file_.content_type.clear();
  2441. }
  2442. std::string boundary_;
  2443. std::string buf_;
  2444. size_t state_ = 0;
  2445. bool is_valid_ = false;
  2446. bool is_done_ = false;
  2447. size_t off_ = 0;
  2448. MultipartFormData file_;
  2449. };
  2450. inline std::string to_lower(const char *beg, const char *end) {
  2451. std::string out;
  2452. auto it = beg;
  2453. while (it != end) {
  2454. out += static_cast<char>(::tolower(*it));
  2455. it++;
  2456. }
  2457. return out;
  2458. }
  2459. inline std::string make_multipart_data_boundary() {
  2460. static const char data[] =
  2461. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  2462. std::random_device seed_gen;
  2463. std::mt19937 engine(seed_gen());
  2464. std::string result = "--cpp-httplib-multipart-data-";
  2465. for (auto i = 0; i < 16; i++) {
  2466. result += data[engine() % (sizeof(data) - 1)];
  2467. }
  2468. return result;
  2469. }
  2470. inline std::pair<size_t, size_t>
  2471. get_range_offset_and_length(const Request &req, size_t content_length,
  2472. size_t index) {
  2473. auto r = req.ranges[index];
  2474. if (r.first == -1 && r.second == -1) {
  2475. return std::make_pair(0, content_length);
  2476. }
  2477. auto slen = static_cast<ssize_t>(content_length);
  2478. if (r.first == -1) {
  2479. r.first = slen - r.second;
  2480. r.second = slen - 1;
  2481. }
  2482. if (r.second == -1) { r.second = slen - 1; }
  2483. return std::make_pair(r.first, r.second - r.first + 1);
  2484. }
  2485. inline std::string make_content_range_header_field(size_t offset, size_t length,
  2486. size_t content_length) {
  2487. std::string field = "bytes ";
  2488. field += std::to_string(offset);
  2489. field += "-";
  2490. field += std::to_string(offset + length - 1);
  2491. field += "/";
  2492. field += std::to_string(content_length);
  2493. return field;
  2494. }
  2495. template <typename SToken, typename CToken, typename Content>
  2496. bool process_multipart_ranges_data(const Request &req, Response &res,
  2497. const std::string &boundary,
  2498. const std::string &content_type,
  2499. SToken stoken, CToken ctoken,
  2500. Content content) {
  2501. for (size_t i = 0; i < req.ranges.size(); i++) {
  2502. ctoken("--");
  2503. stoken(boundary);
  2504. ctoken("\r\n");
  2505. if (!content_type.empty()) {
  2506. ctoken("Content-Type: ");
  2507. stoken(content_type);
  2508. ctoken("\r\n");
  2509. }
  2510. auto offsets = get_range_offset_and_length(req, res.body.size(), i);
  2511. auto offset = offsets.first;
  2512. auto length = offsets.second;
  2513. ctoken("Content-Range: ");
  2514. stoken(make_content_range_header_field(offset, length, res.body.size()));
  2515. ctoken("\r\n");
  2516. ctoken("\r\n");
  2517. if (!content(offset, length)) { return false; }
  2518. ctoken("\r\n");
  2519. }
  2520. ctoken("--");
  2521. stoken(boundary);
  2522. ctoken("--\r\n");
  2523. return true;
  2524. }
  2525. inline std::string make_multipart_ranges_data(const Request &req, Response &res,
  2526. const std::string &boundary,
  2527. const std::string &content_type) {
  2528. std::string data;
  2529. process_multipart_ranges_data(
  2530. req, res, boundary, content_type,
  2531. [&](const std::string &token) { data += token; },
  2532. [&](const char *token) { data += token; },
  2533. [&](size_t offset, size_t length) {
  2534. data += res.body.substr(offset, length);
  2535. return true;
  2536. });
  2537. return data;
  2538. }
  2539. inline size_t
  2540. get_multipart_ranges_data_length(const Request &req, Response &res,
  2541. const std::string &boundary,
  2542. const std::string &content_type) {
  2543. size_t data_length = 0;
  2544. process_multipart_ranges_data(
  2545. req, res, boundary, content_type,
  2546. [&](const std::string &token) { data_length += token.size(); },
  2547. [&](const char *token) { data_length += strlen(token); },
  2548. [&](size_t /*offset*/, size_t length) {
  2549. data_length += length;
  2550. return true;
  2551. });
  2552. return data_length;
  2553. }
  2554. inline bool write_multipart_ranges_data(Stream &strm, const Request &req,
  2555. Response &res,
  2556. const std::string &boundary,
  2557. const std::string &content_type) {
  2558. return process_multipart_ranges_data(
  2559. req, res, boundary, content_type,
  2560. [&](const std::string &token) { strm.write(token); },
  2561. [&](const char *token) { strm.write(token); },
  2562. [&](size_t offset, size_t length) {
  2563. return write_content(strm, res.content_provider_, offset, length) >= 0;
  2564. });
  2565. }
  2566. inline std::pair<size_t, size_t>
  2567. get_range_offset_and_length(const Request &req, const Response &res,
  2568. size_t index) {
  2569. auto r = req.ranges[index];
  2570. if (r.second == -1) {
  2571. r.second = static_cast<ssize_t>(res.content_length_) - 1;
  2572. }
  2573. return std::make_pair(r.first, r.second - r.first + 1);
  2574. }
  2575. inline bool expect_content(const Request &req) {
  2576. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  2577. req.method == "PRI" ||
  2578. (req.method == "DELETE" && req.has_header("Content-Length"))) {
  2579. return true;
  2580. }
  2581. // TODO: check if Content-Length is set
  2582. return false;
  2583. }
  2584. inline bool has_crlf(const char *s) {
  2585. auto p = s;
  2586. while (*p) {
  2587. if (*p == '\r' || *p == '\n') { return true; }
  2588. p++;
  2589. }
  2590. return false;
  2591. }
  2592. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2593. template <typename CTX, typename Init, typename Update, typename Final>
  2594. inline std::string message_digest(const std::string &s, Init init,
  2595. Update update, Final final,
  2596. size_t digest_length) {
  2597. using namespace std;
  2598. std::vector<unsigned char> md(digest_length, 0);
  2599. CTX ctx;
  2600. init(&ctx);
  2601. update(&ctx, s.data(), s.size());
  2602. final(md.data(), &ctx);
  2603. stringstream ss;
  2604. for (auto c : md) {
  2605. ss << setfill('0') << setw(2) << hex << (unsigned int)c;
  2606. }
  2607. return ss.str();
  2608. }
  2609. inline std::string MD5(const std::string &s) {
  2610. return message_digest<MD5_CTX>(s, MD5_Init, MD5_Update, MD5_Final,
  2611. MD5_DIGEST_LENGTH);
  2612. }
  2613. inline std::string SHA_256(const std::string &s) {
  2614. return message_digest<SHA256_CTX>(s, SHA256_Init, SHA256_Update, SHA256_Final,
  2615. SHA256_DIGEST_LENGTH);
  2616. }
  2617. inline std::string SHA_512(const std::string &s) {
  2618. return message_digest<SHA512_CTX>(s, SHA512_Init, SHA512_Update, SHA512_Final,
  2619. SHA512_DIGEST_LENGTH);
  2620. }
  2621. #endif
  2622. #ifdef _WIN32
  2623. class WSInit {
  2624. public:
  2625. WSInit() {
  2626. WSADATA wsaData;
  2627. WSAStartup(0x0002, &wsaData);
  2628. }
  2629. ~WSInit() { WSACleanup(); }
  2630. };
  2631. static WSInit wsinit_;
  2632. #endif
  2633. } // namespace detail
  2634. // Header utilities
  2635. inline std::pair<std::string, std::string> make_range_header(Ranges ranges) {
  2636. std::string field = "bytes=";
  2637. auto i = 0;
  2638. for (auto r : ranges) {
  2639. if (i != 0) { field += ", "; }
  2640. if (r.first != -1) { field += std::to_string(r.first); }
  2641. field += '-';
  2642. if (r.second != -1) { field += std::to_string(r.second); }
  2643. i++;
  2644. }
  2645. return std::make_pair("Range", field);
  2646. }
  2647. inline std::pair<std::string, std::string>
  2648. make_basic_authentication_header(const std::string &username,
  2649. const std::string &password,
  2650. bool is_proxy = false) {
  2651. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  2652. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  2653. return std::make_pair(key, field);
  2654. }
  2655. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2656. inline std::pair<std::string, std::string> make_digest_authentication_header(
  2657. const Request &req, const std::map<std::string, std::string> &auth,
  2658. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  2659. const std::string &password, bool is_proxy = false) {
  2660. using namespace std;
  2661. string nc;
  2662. {
  2663. stringstream ss;
  2664. ss << setfill('0') << setw(8) << hex << cnonce_count;
  2665. nc = ss.str();
  2666. }
  2667. auto qop = auth.at("qop");
  2668. if (qop.find("auth-int") != std::string::npos) {
  2669. qop = "auth-int";
  2670. } else {
  2671. qop = "auth";
  2672. }
  2673. std::string algo = "MD5";
  2674. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  2675. string response;
  2676. {
  2677. auto H = algo == "SHA-256"
  2678. ? detail::SHA_256
  2679. : algo == "SHA-512" ? detail::SHA_512 : detail::MD5;
  2680. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  2681. auto A2 = req.method + ":" + req.path;
  2682. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  2683. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  2684. ":" + qop + ":" + H(A2));
  2685. }
  2686. auto field = "Digest username=\"" + username + "\", realm=\"" +
  2687. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  2688. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  2689. ", qop=" + qop + ", nc=\"" + nc + "\", cnonce=\"" + cnonce +
  2690. "\", response=\"" + response + "\"";
  2691. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  2692. return std::make_pair(key, field);
  2693. }
  2694. #endif
  2695. inline bool parse_www_authenticate(const Response &res,
  2696. std::map<std::string, std::string> &auth,
  2697. bool is_proxy) {
  2698. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  2699. if (res.has_header(auth_key)) {
  2700. static auto re = std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  2701. auto s = res.get_header_value(auth_key);
  2702. auto pos = s.find(' ');
  2703. if (pos != std::string::npos) {
  2704. auto type = s.substr(0, pos);
  2705. if (type == "Basic") {
  2706. return false;
  2707. } else if (type == "Digest") {
  2708. s = s.substr(pos + 1);
  2709. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  2710. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  2711. auto m = *i;
  2712. auto key = s.substr(static_cast<size_t>(m.position(1)),
  2713. static_cast<size_t>(m.length(1)));
  2714. auto val = m.length(2) > 0
  2715. ? s.substr(static_cast<size_t>(m.position(2)),
  2716. static_cast<size_t>(m.length(2)))
  2717. : s.substr(static_cast<size_t>(m.position(3)),
  2718. static_cast<size_t>(m.length(3)));
  2719. auth[key] = val;
  2720. }
  2721. return true;
  2722. }
  2723. }
  2724. }
  2725. return false;
  2726. }
  2727. // https://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c/440240#answer-440240
  2728. inline std::string random_string(size_t length) {
  2729. auto randchar = []() -> char {
  2730. const char charset[] = "0123456789"
  2731. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  2732. "abcdefghijklmnopqrstuvwxyz";
  2733. const size_t max_index = (sizeof(charset) - 1);
  2734. return charset[static_cast<size_t>(rand()) % max_index];
  2735. };
  2736. std::string str(length, 0);
  2737. std::generate_n(str.begin(), length, randchar);
  2738. return str;
  2739. }
  2740. // Request implementation
  2741. inline bool Request::has_header(const char *key) const {
  2742. return detail::has_header(headers, key);
  2743. }
  2744. inline std::string Request::get_header_value(const char *key, size_t id) const {
  2745. return detail::get_header_value(headers, key, id, "");
  2746. }
  2747. inline size_t Request::get_header_value_count(const char *key) const {
  2748. auto r = headers.equal_range(key);
  2749. return static_cast<size_t>(std::distance(r.first, r.second));
  2750. }
  2751. inline void Request::set_header(const char *key, const char *val) {
  2752. if (!detail::has_crlf(key) && !detail::has_crlf(val)) {
  2753. headers.emplace(key, val);
  2754. }
  2755. }
  2756. inline void Request::set_header(const char *key, const std::string &val) {
  2757. if (!detail::has_crlf(key) && !detail::has_crlf(val.c_str())) {
  2758. headers.emplace(key, val);
  2759. }
  2760. }
  2761. inline bool Request::has_param(const char *key) const {
  2762. return params.find(key) != params.end();
  2763. }
  2764. inline std::string Request::get_param_value(const char *key, size_t id) const {
  2765. auto rng = params.equal_range(key);
  2766. auto it = rng.first;
  2767. std::advance(it, static_cast<ssize_t>(id));
  2768. if (it != rng.second) { return it->second; }
  2769. return std::string();
  2770. }
  2771. inline size_t Request::get_param_value_count(const char *key) const {
  2772. auto r = params.equal_range(key);
  2773. return static_cast<size_t>(std::distance(r.first, r.second));
  2774. }
  2775. inline bool Request::is_multipart_form_data() const {
  2776. const auto &content_type = get_header_value("Content-Type");
  2777. return !content_type.find("multipart/form-data");
  2778. }
  2779. inline bool Request::has_file(const char *key) const {
  2780. return files.find(key) != files.end();
  2781. }
  2782. inline MultipartFormData Request::get_file_value(const char *key) const {
  2783. auto it = files.find(key);
  2784. if (it != files.end()) { return it->second; }
  2785. return MultipartFormData();
  2786. }
  2787. // Response implementation
  2788. inline bool Response::has_header(const char *key) const {
  2789. return headers.find(key) != headers.end();
  2790. }
  2791. inline std::string Response::get_header_value(const char *key,
  2792. size_t id) const {
  2793. return detail::get_header_value(headers, key, id, "");
  2794. }
  2795. inline size_t Response::get_header_value_count(const char *key) const {
  2796. auto r = headers.equal_range(key);
  2797. return static_cast<size_t>(std::distance(r.first, r.second));
  2798. }
  2799. inline void Response::set_header(const char *key, const char *val) {
  2800. if (!detail::has_crlf(key) && !detail::has_crlf(val)) {
  2801. headers.emplace(key, val);
  2802. }
  2803. }
  2804. inline void Response::set_header(const char *key, const std::string &val) {
  2805. if (!detail::has_crlf(key) && !detail::has_crlf(val.c_str())) {
  2806. headers.emplace(key, val);
  2807. }
  2808. }
  2809. inline void Response::set_redirect(const char *url, int stat) {
  2810. if (!detail::has_crlf(url)) {
  2811. set_header("Location", url);
  2812. if (300 <= stat && stat < 400) {
  2813. this->status = stat;
  2814. } else {
  2815. this->status = 302;
  2816. }
  2817. }
  2818. }
  2819. inline void Response::set_content(const char *s, size_t n,
  2820. const char *content_type) {
  2821. body.assign(s, n);
  2822. set_header("Content-Type", content_type);
  2823. }
  2824. inline void Response::set_content(std::string s, const char *content_type) {
  2825. body = std::move(s);
  2826. set_header("Content-Type", content_type);
  2827. }
  2828. inline void
  2829. Response::set_content_provider(size_t in_length, ContentProvider provider,
  2830. std::function<void()> resource_releaser) {
  2831. assert(in_length > 0);
  2832. content_length_ = in_length;
  2833. content_provider_ = [provider](size_t offset, size_t length, DataSink &sink) {
  2834. return provider(offset, length, sink);
  2835. };
  2836. content_provider_resource_releaser_ = resource_releaser;
  2837. }
  2838. inline void Response::set_chunked_content_provider(
  2839. ChunkedContentProvider provider, std::function<void()> resource_releaser) {
  2840. content_length_ = 0;
  2841. content_provider_ = [provider](size_t offset, size_t, DataSink &sink) {
  2842. return provider(offset, sink);
  2843. };
  2844. content_provider_resource_releaser_ = resource_releaser;
  2845. }
  2846. // Rstream implementation
  2847. inline ssize_t Stream::write(const char *ptr) {
  2848. return write(ptr, strlen(ptr));
  2849. }
  2850. inline ssize_t Stream::write(const std::string &s) {
  2851. return write(s.data(), s.size());
  2852. }
  2853. template <typename... Args>
  2854. inline ssize_t Stream::write_format(const char *fmt, const Args &... args) {
  2855. std::array<char, 2048> buf;
  2856. #if defined(_MSC_VER) && _MSC_VER < 1900
  2857. auto sn = _snprintf_s(buf, bufsiz, buf.size() - 1, fmt, args...);
  2858. #else
  2859. auto sn = snprintf(buf.data(), buf.size() - 1, fmt, args...);
  2860. #endif
  2861. if (sn <= 0) { return sn; }
  2862. auto n = static_cast<size_t>(sn);
  2863. if (n >= buf.size() - 1) {
  2864. std::vector<char> glowable_buf(buf.size());
  2865. while (n >= glowable_buf.size() - 1) {
  2866. glowable_buf.resize(glowable_buf.size() * 2);
  2867. #if defined(_MSC_VER) && _MSC_VER < 1900
  2868. n = static_cast<size_t>(_snprintf_s(&glowable_buf[0], glowable_buf.size(),
  2869. glowable_buf.size() - 1, fmt,
  2870. args...));
  2871. #else
  2872. n = static_cast<size_t>(
  2873. snprintf(&glowable_buf[0], glowable_buf.size() - 1, fmt, args...));
  2874. #endif
  2875. }
  2876. return write(&glowable_buf[0], n);
  2877. } else {
  2878. return write(buf.data(), n);
  2879. }
  2880. }
  2881. namespace detail {
  2882. // Socket stream implementation
  2883. inline SocketStream::SocketStream(socket_t sock, time_t read_timeout_sec,
  2884. time_t read_timeout_usec,
  2885. time_t write_timeout_sec,
  2886. time_t write_timeout_usec)
  2887. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  2888. read_timeout_usec_(read_timeout_usec),
  2889. write_timeout_sec_(write_timeout_sec),
  2890. write_timeout_usec_(write_timeout_usec) {}
  2891. inline SocketStream::~SocketStream() {}
  2892. inline bool SocketStream::is_readable() const {
  2893. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  2894. }
  2895. inline bool SocketStream::is_writable() const {
  2896. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  2897. }
  2898. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  2899. if (!is_readable()) { return -1; }
  2900. #ifdef _WIN32
  2901. if (size > static_cast<size_t>((std::numeric_limits<int>::max)())) {
  2902. return -1;
  2903. }
  2904. return recv(sock_, ptr, static_cast<int>(size), 0);
  2905. #else
  2906. return handle_EINTR([&]() { return recv(sock_, ptr, size, 0); });
  2907. #endif
  2908. }
  2909. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  2910. if (!is_writable()) { return -1; }
  2911. #ifdef _WIN32
  2912. if (size > static_cast<size_t>((std::numeric_limits<int>::max)())) {
  2913. return -1;
  2914. }
  2915. return send(sock_, ptr, static_cast<int>(size), 0);
  2916. #else
  2917. return handle_EINTR([&]() { return send(sock_, ptr, size, 0); });
  2918. #endif
  2919. }
  2920. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  2921. int &port) const {
  2922. return detail::get_remote_ip_and_port(sock_, ip, port);
  2923. }
  2924. // Buffer stream implementation
  2925. inline bool BufferStream::is_readable() const { return true; }
  2926. inline bool BufferStream::is_writable() const { return true; }
  2927. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  2928. #if defined(_MSC_VER) && _MSC_VER < 1900
  2929. auto len_read = buffer._Copy_s(ptr, size, size, position);
  2930. #else
  2931. auto len_read = buffer.copy(ptr, size, position);
  2932. #endif
  2933. position += static_cast<size_t>(len_read);
  2934. return static_cast<ssize_t>(len_read);
  2935. }
  2936. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  2937. buffer.append(ptr, size);
  2938. return static_cast<ssize_t>(size);
  2939. }
  2940. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  2941. int & /*port*/) const {}
  2942. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  2943. } // namespace detail
  2944. // HTTP server implementation
  2945. inline Server::Server() : is_running_(false), svr_sock_(INVALID_SOCKET) {
  2946. #ifndef _WIN32
  2947. signal(SIGPIPE, SIG_IGN);
  2948. #endif
  2949. new_task_queue = [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); };
  2950. }
  2951. inline Server::~Server() {}
  2952. inline Server &Server::Get(const char *pattern, Handler handler) {
  2953. get_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  2954. return *this;
  2955. }
  2956. inline Server &Server::Post(const char *pattern, Handler handler) {
  2957. post_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  2958. return *this;
  2959. }
  2960. inline Server &Server::Post(const char *pattern,
  2961. HandlerWithContentReader handler) {
  2962. post_handlers_for_content_reader_.push_back(
  2963. std::make_pair(std::regex(pattern), handler));
  2964. return *this;
  2965. }
  2966. inline Server &Server::Put(const char *pattern, Handler handler) {
  2967. put_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  2968. return *this;
  2969. }
  2970. inline Server &Server::Put(const char *pattern,
  2971. HandlerWithContentReader handler) {
  2972. put_handlers_for_content_reader_.push_back(
  2973. std::make_pair(std::regex(pattern), handler));
  2974. return *this;
  2975. }
  2976. inline Server &Server::Patch(const char *pattern, Handler handler) {
  2977. patch_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  2978. return *this;
  2979. }
  2980. inline Server &Server::Patch(const char *pattern,
  2981. HandlerWithContentReader handler) {
  2982. patch_handlers_for_content_reader_.push_back(
  2983. std::make_pair(std::regex(pattern), handler));
  2984. return *this;
  2985. }
  2986. inline Server &Server::Delete(const char *pattern, Handler handler) {
  2987. delete_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  2988. return *this;
  2989. }
  2990. inline Server &Server::Delete(const char *pattern,
  2991. HandlerWithContentReader handler) {
  2992. delete_handlers_for_content_reader_.push_back(
  2993. std::make_pair(std::regex(pattern), handler));
  2994. return *this;
  2995. }
  2996. inline Server &Server::Options(const char *pattern, Handler handler) {
  2997. options_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  2998. return *this;
  2999. }
  3000. inline bool Server::set_base_dir(const char *dir, const char *mount_point) {
  3001. return set_mount_point(mount_point, dir);
  3002. }
  3003. inline bool Server::set_mount_point(const char *mount_point, const char *dir) {
  3004. if (detail::is_dir(dir)) {
  3005. std::string mnt = mount_point ? mount_point : "/";
  3006. if (!mnt.empty() && mnt[0] == '/') {
  3007. base_dirs_.emplace_back(mnt, dir);
  3008. return true;
  3009. }
  3010. }
  3011. return false;
  3012. }
  3013. inline bool Server::remove_mount_point(const char *mount_point) {
  3014. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  3015. if (it->first == mount_point) {
  3016. base_dirs_.erase(it);
  3017. return true;
  3018. }
  3019. }
  3020. return false;
  3021. }
  3022. inline void Server::set_file_extension_and_mimetype_mapping(const char *ext,
  3023. const char *mime) {
  3024. file_extension_and_mimetype_map_[ext] = mime;
  3025. }
  3026. inline void Server::set_file_request_handler(Handler handler) {
  3027. file_request_handler_ = std::move(handler);
  3028. }
  3029. inline void Server::set_error_handler(Handler handler) {
  3030. error_handler_ = std::move(handler);
  3031. }
  3032. inline void Server::set_logger(Logger logger) { logger_ = std::move(logger); }
  3033. inline void
  3034. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  3035. expect_100_continue_handler_ = std::move(handler);
  3036. }
  3037. inline void Server::set_keep_alive_max_count(size_t count) {
  3038. keep_alive_max_count_ = count;
  3039. }
  3040. inline void Server::set_read_timeout(time_t sec, time_t usec) {
  3041. read_timeout_sec_ = sec;
  3042. read_timeout_usec_ = usec;
  3043. }
  3044. inline void Server::set_write_timeout(time_t sec, time_t usec) {
  3045. write_timeout_sec_ = sec;
  3046. write_timeout_usec_ = usec;
  3047. }
  3048. inline void Server::set_idle_interval(time_t sec, time_t usec) {
  3049. idle_interval_sec_ = sec;
  3050. idle_interval_usec_ = usec;
  3051. }
  3052. inline void Server::set_payload_max_length(size_t length) {
  3053. payload_max_length_ = length;
  3054. }
  3055. inline bool Server::bind_to_port(const char *host, int port, int socket_flags) {
  3056. if (bind_internal(host, port, socket_flags) < 0) return false;
  3057. return true;
  3058. }
  3059. inline int Server::bind_to_any_port(const char *host, int socket_flags) {
  3060. return bind_internal(host, 0, socket_flags);
  3061. }
  3062. inline bool Server::listen_after_bind() { return listen_internal(); }
  3063. inline bool Server::listen(const char *host, int port, int socket_flags) {
  3064. return bind_to_port(host, port, socket_flags) && listen_internal();
  3065. }
  3066. inline bool Server::is_running() const { return is_running_; }
  3067. inline void Server::stop() {
  3068. if (is_running_) {
  3069. assert(svr_sock_ != INVALID_SOCKET);
  3070. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  3071. detail::shutdown_socket(sock);
  3072. detail::close_socket(sock);
  3073. }
  3074. }
  3075. inline bool Server::parse_request_line(const char *s, Request &req) {
  3076. const static std::regex re(
  3077. "(GET|HEAD|POST|PUT|DELETE|CONNECT|OPTIONS|TRACE|PATCH|PRI) "
  3078. "(([^?]+)(?:\\?(.*?))?) (HTTP/1\\.[01])\r\n");
  3079. std::cmatch m;
  3080. if (std::regex_match(s, m, re)) {
  3081. req.version = std::string(m[5]);
  3082. req.method = std::string(m[1]);
  3083. req.target = std::string(m[2]);
  3084. req.path = detail::decode_url(m[3], false);
  3085. // Parse query text
  3086. auto len = std::distance(m[4].first, m[4].second);
  3087. if (len > 0) { detail::parse_query_text(m[4], req.params); }
  3088. return true;
  3089. }
  3090. return false;
  3091. }
  3092. inline bool Server::write_response(Stream &strm, bool last_connection,
  3093. const Request &req, Response &res) {
  3094. assert(res.status != -1);
  3095. if (400 <= res.status && error_handler_) { error_handler_(req, res); }
  3096. detail::BufferStream bstrm;
  3097. // Response line
  3098. if (!bstrm.write_format("HTTP/1.1 %d %s\r\n", res.status,
  3099. detail::status_message(res.status))) {
  3100. return false;
  3101. }
  3102. // Headers
  3103. if (last_connection || req.get_header_value("Connection") == "close") {
  3104. res.set_header("Connection", "close");
  3105. }
  3106. if (!last_connection && req.get_header_value("Connection") == "Keep-Alive") {
  3107. res.set_header("Connection", "Keep-Alive");
  3108. }
  3109. if (!res.has_header("Content-Type") &&
  3110. (!res.body.empty() || res.content_length_ > 0)) {
  3111. res.set_header("Content-Type", "text/plain");
  3112. }
  3113. if (!res.has_header("Accept-Ranges") && req.method == "HEAD") {
  3114. res.set_header("Accept-Ranges", "bytes");
  3115. }
  3116. std::string content_type;
  3117. std::string boundary;
  3118. if (req.ranges.size() > 1) {
  3119. boundary = detail::make_multipart_data_boundary();
  3120. auto it = res.headers.find("Content-Type");
  3121. if (it != res.headers.end()) {
  3122. content_type = it->second;
  3123. res.headers.erase(it);
  3124. }
  3125. res.headers.emplace("Content-Type",
  3126. "multipart/byteranges; boundary=" + boundary);
  3127. }
  3128. if (res.body.empty()) {
  3129. if (res.content_length_ > 0) {
  3130. size_t length = 0;
  3131. if (req.ranges.empty()) {
  3132. length = res.content_length_;
  3133. } else if (req.ranges.size() == 1) {
  3134. auto offsets =
  3135. detail::get_range_offset_and_length(req, res.content_length_, 0);
  3136. auto offset = offsets.first;
  3137. length = offsets.second;
  3138. auto content_range = detail::make_content_range_header_field(
  3139. offset, length, res.content_length_);
  3140. res.set_header("Content-Range", content_range);
  3141. } else {
  3142. length = detail::get_multipart_ranges_data_length(req, res, boundary,
  3143. content_type);
  3144. }
  3145. res.set_header("Content-Length", std::to_string(length));
  3146. } else {
  3147. if (res.content_provider_) {
  3148. res.set_header("Transfer-Encoding", "chunked");
  3149. } else {
  3150. res.set_header("Content-Length", "0");
  3151. }
  3152. }
  3153. } else {
  3154. if (req.ranges.empty()) {
  3155. ;
  3156. } else if (req.ranges.size() == 1) {
  3157. auto offsets =
  3158. detail::get_range_offset_and_length(req, res.body.size(), 0);
  3159. auto offset = offsets.first;
  3160. auto length = offsets.second;
  3161. auto content_range = detail::make_content_range_header_field(
  3162. offset, length, res.body.size());
  3163. res.set_header("Content-Range", content_range);
  3164. res.body = res.body.substr(offset, length);
  3165. } else {
  3166. res.body =
  3167. detail::make_multipart_ranges_data(req, res, boundary, content_type);
  3168. }
  3169. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3170. // TODO: 'Accept-Encoding' has gzip, not gzip;q=0
  3171. const auto &encodings = req.get_header_value("Accept-Encoding");
  3172. if (encodings.find("gzip") != std::string::npos &&
  3173. detail::can_compress(res.get_header_value("Content-Type"))) {
  3174. if (detail::compress(res.body)) {
  3175. res.set_header("Content-Encoding", "gzip");
  3176. }
  3177. }
  3178. #endif
  3179. auto length = std::to_string(res.body.size());
  3180. res.set_header("Content-Length", length);
  3181. }
  3182. if (!detail::write_headers(bstrm, res, Headers())) { return false; }
  3183. // Flush buffer
  3184. auto &data = bstrm.get_buffer();
  3185. strm.write(data.data(), data.size());
  3186. // Body
  3187. if (req.method != "HEAD") {
  3188. if (!res.body.empty()) {
  3189. if (!strm.write(res.body)) { return false; }
  3190. } else if (res.content_provider_) {
  3191. if (!write_content_with_provider(strm, req, res, boundary,
  3192. content_type)) {
  3193. return false;
  3194. }
  3195. }
  3196. }
  3197. // Log
  3198. if (logger_) { logger_(req, res); }
  3199. return true;
  3200. }
  3201. inline bool
  3202. Server::write_content_with_provider(Stream &strm, const Request &req,
  3203. Response &res, const std::string &boundary,
  3204. const std::string &content_type) {
  3205. if (res.content_length_) {
  3206. if (req.ranges.empty()) {
  3207. if (detail::write_content(strm, res.content_provider_, 0,
  3208. res.content_length_) < 0) {
  3209. return false;
  3210. }
  3211. } else if (req.ranges.size() == 1) {
  3212. auto offsets =
  3213. detail::get_range_offset_and_length(req, res.content_length_, 0);
  3214. auto offset = offsets.first;
  3215. auto length = offsets.second;
  3216. if (detail::write_content(strm, res.content_provider_, offset, length) <
  3217. 0) {
  3218. return false;
  3219. }
  3220. } else {
  3221. if (!detail::write_multipart_ranges_data(strm, req, res, boundary,
  3222. content_type)) {
  3223. return false;
  3224. }
  3225. }
  3226. } else {
  3227. auto is_shutting_down = [this]() {
  3228. return this->svr_sock_ == INVALID_SOCKET;
  3229. };
  3230. if (detail::write_content_chunked(strm, res.content_provider_,
  3231. is_shutting_down) < 0) {
  3232. return false;
  3233. }
  3234. }
  3235. return true;
  3236. }
  3237. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  3238. MultipartFormDataMap::iterator cur;
  3239. if (read_content_core(
  3240. strm, req, res,
  3241. // Regular
  3242. [&](const char *buf, size_t n) {
  3243. if (req.body.size() + n > req.body.max_size()) { return false; }
  3244. req.body.append(buf, n);
  3245. return true;
  3246. },
  3247. // Multipart
  3248. [&](const MultipartFormData &file) {
  3249. cur = req.files.emplace(file.name, file);
  3250. return true;
  3251. },
  3252. [&](const char *buf, size_t n) {
  3253. auto &content = cur->second.content;
  3254. if (content.size() + n > content.max_size()) { return false; }
  3255. content.append(buf, n);
  3256. return true;
  3257. })) {
  3258. const auto &content_type = req.get_header_value("Content-Type");
  3259. if (!content_type.find("application/x-www-form-urlencoded")) {
  3260. detail::parse_query_text(req.body, req.params);
  3261. }
  3262. return true;
  3263. }
  3264. return false;
  3265. }
  3266. inline bool Server::read_content_with_content_receiver(
  3267. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  3268. MultipartContentHeader multipart_header,
  3269. ContentReceiver multipart_receiver) {
  3270. return read_content_core(strm, req, res, receiver, multipart_header,
  3271. multipart_receiver);
  3272. }
  3273. inline bool Server::read_content_core(Stream &strm, Request &req, Response &res,
  3274. ContentReceiver receiver,
  3275. MultipartContentHeader mulitpart_header,
  3276. ContentReceiver multipart_receiver) {
  3277. detail::MultipartFormDataParser multipart_form_data_parser;
  3278. ContentReceiver out;
  3279. if (req.is_multipart_form_data()) {
  3280. const auto &content_type = req.get_header_value("Content-Type");
  3281. std::string boundary;
  3282. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  3283. res.status = 400;
  3284. return false;
  3285. }
  3286. multipart_form_data_parser.set_boundary(std::move(boundary));
  3287. out = [&](const char *buf, size_t n) {
  3288. return multipart_form_data_parser.parse(buf, n, multipart_receiver,
  3289. mulitpart_header);
  3290. };
  3291. } else {
  3292. out = receiver;
  3293. }
  3294. if (!detail::read_content(strm, req, payload_max_length_, res.status,
  3295. Progress(), out, true)) {
  3296. return false;
  3297. }
  3298. if (req.is_multipart_form_data()) {
  3299. if (!multipart_form_data_parser.is_valid()) {
  3300. res.status = 400;
  3301. return false;
  3302. }
  3303. }
  3304. return true;
  3305. }
  3306. inline bool Server::handle_file_request(Request &req, Response &res,
  3307. bool head) {
  3308. for (const auto &kv : base_dirs_) {
  3309. const auto &mount_point = kv.first;
  3310. const auto &base_dir = kv.second;
  3311. // Prefix match
  3312. if (!req.path.find(mount_point)) {
  3313. std::string sub_path = "/" + req.path.substr(mount_point.size());
  3314. if (detail::is_valid_path(sub_path)) {
  3315. auto path = base_dir + sub_path;
  3316. if (path.back() == '/') { path += "index.html"; }
  3317. if (detail::is_file(path)) {
  3318. detail::read_file(path, res.body);
  3319. auto type =
  3320. detail::find_content_type(path, file_extension_and_mimetype_map_);
  3321. if (type) { res.set_header("Content-Type", type); }
  3322. res.status = 200;
  3323. if (!head && file_request_handler_) {
  3324. file_request_handler_(req, res);
  3325. }
  3326. return true;
  3327. }
  3328. }
  3329. }
  3330. }
  3331. return false;
  3332. }
  3333. inline socket_t
  3334. Server::create_server_socket(const char *host, int port, int socket_flags,
  3335. SocketOptions socket_options) const {
  3336. return detail::create_socket(
  3337. host, port, socket_flags, socket_options,
  3338. [](socket_t sock, struct addrinfo &ai) -> bool {
  3339. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  3340. return false;
  3341. }
  3342. if (::listen(sock, 5)) { // Listen through 5 channels
  3343. return false;
  3344. }
  3345. return true;
  3346. });
  3347. }
  3348. inline int Server::bind_internal(const char *host, int port, int socket_flags) {
  3349. if (!is_valid()) { return -1; }
  3350. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  3351. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  3352. if (port == 0) {
  3353. struct sockaddr_storage addr;
  3354. socklen_t addr_len = sizeof(addr);
  3355. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  3356. &addr_len) == -1) {
  3357. return -1;
  3358. }
  3359. if (addr.ss_family == AF_INET) {
  3360. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  3361. } else if (addr.ss_family == AF_INET6) {
  3362. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  3363. } else {
  3364. return -1;
  3365. }
  3366. } else {
  3367. return port;
  3368. }
  3369. }
  3370. inline bool Server::listen_internal() {
  3371. auto ret = true;
  3372. is_running_ = true;
  3373. {
  3374. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  3375. while (svr_sock_ != INVALID_SOCKET) {
  3376. #ifndef _WIN32
  3377. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  3378. #endif
  3379. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  3380. idle_interval_usec_);
  3381. if (val == 0) { // Timeout
  3382. task_queue->on_idle();
  3383. continue;
  3384. }
  3385. #ifndef _WIN32
  3386. }
  3387. #endif
  3388. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  3389. if (sock == INVALID_SOCKET) {
  3390. if (errno == EMFILE) {
  3391. // The per-process limit of open file descriptors has been reached.
  3392. // Try to accept new connections after a short sleep.
  3393. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3394. continue;
  3395. }
  3396. if (svr_sock_ != INVALID_SOCKET) {
  3397. detail::close_socket(svr_sock_);
  3398. ret = false;
  3399. } else {
  3400. ; // The server socket was closed by user.
  3401. }
  3402. break;
  3403. }
  3404. #if __cplusplus > 201703L
  3405. task_queue->enqueue([=, this]() { process_and_close_socket(sock); });
  3406. #else
  3407. task_queue->enqueue([=]() { process_and_close_socket(sock); });
  3408. #endif
  3409. }
  3410. task_queue->shutdown();
  3411. }
  3412. is_running_ = false;
  3413. return ret;
  3414. }
  3415. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  3416. // File handler
  3417. bool is_head_request = req.method == "HEAD";
  3418. if ((req.method == "GET" || is_head_request) &&
  3419. handle_file_request(req, res, is_head_request)) {
  3420. return true;
  3421. }
  3422. if (detail::expect_content(req)) {
  3423. // Content reader handler
  3424. {
  3425. ContentReader reader(
  3426. [&](ContentReceiver receiver) {
  3427. return read_content_with_content_receiver(strm, req, res, receiver,
  3428. nullptr, nullptr);
  3429. },
  3430. [&](MultipartContentHeader header, ContentReceiver receiver) {
  3431. return read_content_with_content_receiver(strm, req, res, nullptr,
  3432. header, receiver);
  3433. });
  3434. if (req.method == "POST") {
  3435. if (dispatch_request_for_content_reader(
  3436. req, res, reader, post_handlers_for_content_reader_)) {
  3437. return true;
  3438. }
  3439. } else if (req.method == "PUT") {
  3440. if (dispatch_request_for_content_reader(
  3441. req, res, reader, put_handlers_for_content_reader_)) {
  3442. return true;
  3443. }
  3444. } else if (req.method == "PATCH") {
  3445. if (dispatch_request_for_content_reader(
  3446. req, res, reader, patch_handlers_for_content_reader_)) {
  3447. return true;
  3448. }
  3449. } else if (req.method == "DELETE") {
  3450. if (dispatch_request_for_content_reader(
  3451. req, res, reader, delete_handlers_for_content_reader_)) {
  3452. return true;
  3453. }
  3454. }
  3455. }
  3456. // Read content into `req.body`
  3457. if (!read_content(strm, req, res)) { return false; }
  3458. }
  3459. // Regular handler
  3460. if (req.method == "GET" || req.method == "HEAD") {
  3461. return dispatch_request(req, res, get_handlers_);
  3462. } else if (req.method == "POST") {
  3463. return dispatch_request(req, res, post_handlers_);
  3464. } else if (req.method == "PUT") {
  3465. return dispatch_request(req, res, put_handlers_);
  3466. } else if (req.method == "DELETE") {
  3467. return dispatch_request(req, res, delete_handlers_);
  3468. } else if (req.method == "OPTIONS") {
  3469. return dispatch_request(req, res, options_handlers_);
  3470. } else if (req.method == "PATCH") {
  3471. return dispatch_request(req, res, patch_handlers_);
  3472. }
  3473. res.status = 400;
  3474. return false;
  3475. }
  3476. inline bool Server::dispatch_request(Request &req, Response &res,
  3477. Handlers &handlers) {
  3478. try {
  3479. for (const auto &x : handlers) {
  3480. const auto &pattern = x.first;
  3481. const auto &handler = x.second;
  3482. if (std::regex_match(req.path, req.matches, pattern)) {
  3483. handler(req, res);
  3484. return true;
  3485. }
  3486. }
  3487. } catch (const std::exception &ex) {
  3488. res.status = 500;
  3489. res.set_header("EXCEPTION_WHAT", ex.what());
  3490. } catch (...) {
  3491. res.status = 500;
  3492. res.set_header("EXCEPTION_WHAT", "UNKNOWN");
  3493. }
  3494. return false;
  3495. }
  3496. inline bool Server::dispatch_request_for_content_reader(
  3497. Request &req, Response &res, ContentReader content_reader,
  3498. HandlersForContentReader &handlers) {
  3499. for (const auto &x : handlers) {
  3500. const auto &pattern = x.first;
  3501. const auto &handler = x.second;
  3502. if (std::regex_match(req.path, req.matches, pattern)) {
  3503. handler(req, res, content_reader);
  3504. return true;
  3505. }
  3506. }
  3507. return false;
  3508. }
  3509. inline bool
  3510. Server::process_request(Stream &strm, bool last_connection,
  3511. bool &connection_close,
  3512. const std::function<void(Request &)> &setup_request) {
  3513. std::array<char, 2048> buf{};
  3514. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  3515. // Connection has been closed on client
  3516. if (!line_reader.getline()) { return false; }
  3517. Request req;
  3518. Response res;
  3519. res.version = "HTTP/1.1";
  3520. // Check if the request URI doesn't exceed the limit
  3521. if (line_reader.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  3522. Headers dummy;
  3523. detail::read_headers(strm, dummy);
  3524. res.status = 414;
  3525. return write_response(strm, last_connection, req, res);
  3526. }
  3527. // Request line and headers
  3528. if (!parse_request_line(line_reader.ptr(), req) ||
  3529. !detail::read_headers(strm, req.headers)) {
  3530. res.status = 400;
  3531. return write_response(strm, last_connection, req, res);
  3532. }
  3533. if (req.get_header_value("Connection") == "close") {
  3534. connection_close = true;
  3535. }
  3536. if (req.version == "HTTP/1.0" &&
  3537. req.get_header_value("Connection") != "Keep-Alive") {
  3538. connection_close = true;
  3539. }
  3540. strm.get_remote_ip_and_port(req.remote_addr, req.remote_port);
  3541. req.set_header("REMOTE_ADDR", req.remote_addr);
  3542. req.set_header("REMOTE_PORT", std::to_string(req.remote_port));
  3543. if (req.has_header("Range")) {
  3544. const auto &range_header_value = req.get_header_value("Range");
  3545. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  3546. // TODO: error
  3547. }
  3548. }
  3549. if (setup_request) { setup_request(req); }
  3550. if (req.get_header_value("Expect") == "100-continue") {
  3551. auto status = 100;
  3552. if (expect_100_continue_handler_) {
  3553. status = expect_100_continue_handler_(req, res);
  3554. }
  3555. switch (status) {
  3556. case 100:
  3557. case 417:
  3558. strm.write_format("HTTP/1.1 %d %s\r\n\r\n", status,
  3559. detail::status_message(status));
  3560. break;
  3561. default: return write_response(strm, last_connection, req, res);
  3562. }
  3563. }
  3564. // Rounting
  3565. if (routing(req, res, strm)) {
  3566. if (res.status == -1) { res.status = req.ranges.empty() ? 200 : 206; }
  3567. } else {
  3568. if (res.status == -1) { res.status = 404; }
  3569. }
  3570. return write_response(strm, last_connection, req, res);
  3571. }
  3572. inline bool Server::is_valid() const { return true; }
  3573. inline bool Server::process_and_close_socket(socket_t sock) {
  3574. auto ret = detail::process_socket(
  3575. false, sock, keep_alive_max_count_, read_timeout_sec_, read_timeout_usec_,
  3576. write_timeout_sec_, write_timeout_usec_,
  3577. [this](Stream &strm, bool last_connection, bool &connection_close) {
  3578. return process_request(strm, last_connection, connection_close,
  3579. nullptr);
  3580. });
  3581. detail::close_socket(sock);
  3582. return ret;
  3583. }
  3584. // HTTP client implementation
  3585. inline Client::Client(const std::string &host)
  3586. : Client(host, 80, std::string(), std::string()) {}
  3587. inline Client::Client(const std::string &host, int port)
  3588. : Client(host, port, std::string(), std::string()) {}
  3589. inline Client::Client(const std::string &host, int port,
  3590. const std::string &client_cert_path,
  3591. const std::string &client_key_path)
  3592. : /*cli_sock_(INVALID_SOCKET),*/ host_(host), port_(port),
  3593. host_and_port_(host_ + ":" + std::to_string(port_)),
  3594. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  3595. inline Client::~Client() {
  3596. assert(socket_.sock == INVALID_SOCKET);
  3597. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3598. assert(socket_.ssl == nullptr);
  3599. #endif
  3600. }
  3601. inline bool Client::is_valid() const { return true; }
  3602. inline socket_t Client::create_client_socket() const {
  3603. if (!proxy_host_.empty()) {
  3604. return detail::create_client_socket(proxy_host_.c_str(), proxy_port_,
  3605. nullptr, connection_timeout_sec_,
  3606. connection_timeout_usec_, interface_);
  3607. }
  3608. return detail::create_client_socket(host_.c_str(), port_, nullptr,
  3609. connection_timeout_sec_,
  3610. connection_timeout_usec_, interface_);
  3611. }
  3612. inline bool Client::create_and_connect_socket(Socket &socket) {
  3613. auto sock = create_client_socket();
  3614. if (sock == INVALID_SOCKET) { return false; }
  3615. socket.sock = sock;
  3616. return true;
  3617. }
  3618. inline void Client::close_socket(Socket &socket, bool /*process_socket_ret*/) {
  3619. detail::close_socket(socket.sock);
  3620. socket_.sock = INVALID_SOCKET;
  3621. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3622. socket_.ssl = nullptr;
  3623. #endif
  3624. }
  3625. inline bool Client::read_response_line(Stream &strm, Response &res) {
  3626. std::array<char, 2048> buf;
  3627. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  3628. if (!line_reader.getline()) { return false; }
  3629. const static std::regex re("(HTTP/1\\.[01]) (\\d+?) .*\r\n");
  3630. std::cmatch m;
  3631. if (std::regex_match(line_reader.ptr(), m, re)) {
  3632. res.version = std::string(m[1]);
  3633. res.status = std::stoi(std::string(m[2]));
  3634. }
  3635. return true;
  3636. }
  3637. inline bool Client::send(const Request &req, Response &res) {
  3638. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  3639. auto need_new_socket = !is_socket_open();
  3640. if (need_new_socket) {
  3641. std::lock_guard<std::mutex> guard(socket_mutex_);
  3642. if (!create_and_connect_socket(socket_)) { return false; }
  3643. }
  3644. auto ret = process_socket(
  3645. socket_, 1,
  3646. [&](Stream &strm, bool /*last_connection*/, bool &connection_close) {
  3647. return handle_request(strm, req, res, connection_close);
  3648. });
  3649. if (need_new_socket) {
  3650. std::lock_guard<std::mutex> guard(socket_mutex_);
  3651. if (socket_.is_open()) { close_socket(socket_, ret); }
  3652. }
  3653. return ret;
  3654. }
  3655. inline bool Client::send(const std::vector<Request> &requests,
  3656. std::vector<Response> &responses) {
  3657. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  3658. size_t i = 0;
  3659. while (i < requests.size()) {
  3660. {
  3661. std::lock_guard<std::mutex> guard(socket_mutex_);
  3662. if (!create_and_connect_socket(socket_)) { return false; }
  3663. }
  3664. auto request_count = (std::min)(requests.size() - i, keep_alive_max_count_);
  3665. auto ret = process_socket(
  3666. socket_, request_count,
  3667. [&](Stream &strm, bool /*last_connection*/, bool &connection_close) {
  3668. auto &req = requests[i++];
  3669. auto res = Response();
  3670. auto ret = handle_request(strm, req, res, connection_close);
  3671. if (ret) { responses.emplace_back(std::move(res)); }
  3672. return ret;
  3673. });
  3674. {
  3675. std::lock_guard<std::mutex> guard(socket_mutex_);
  3676. if (socket_.is_open()) { close_socket(socket_, ret); }
  3677. }
  3678. if (!ret) { return false; }
  3679. }
  3680. return true;
  3681. }
  3682. inline bool Client::handle_request(Stream &strm, const Request &req,
  3683. Response &res, bool &connection_close) {
  3684. if (req.path.empty()) { return false; }
  3685. bool ret;
  3686. if (!is_ssl() && !proxy_host_.empty()) {
  3687. auto req2 = req;
  3688. req2.path = "http://" + host_and_port_ + req.path;
  3689. ret = process_request(strm, req2, res, connection_close);
  3690. } else {
  3691. ret = process_request(strm, req, res, connection_close);
  3692. }
  3693. if (!ret) { return false; }
  3694. if (300 < res.status && res.status < 400 && follow_location_) {
  3695. ret = redirect(req, res);
  3696. }
  3697. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3698. if ((res.status == 401 || res.status == 407) &&
  3699. req.authorization_count_ < 5) {
  3700. auto is_proxy = res.status == 407;
  3701. const auto &username =
  3702. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  3703. const auto &password =
  3704. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  3705. if (!username.empty() && !password.empty()) {
  3706. std::map<std::string, std::string> auth;
  3707. if (parse_www_authenticate(res, auth, is_proxy)) {
  3708. Request new_req = req;
  3709. new_req.authorization_count_ += 1;
  3710. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  3711. new_req.headers.erase(key);
  3712. new_req.headers.insert(make_digest_authentication_header(
  3713. req, auth, new_req.authorization_count_, random_string(10),
  3714. username, password, is_proxy));
  3715. Response new_res;
  3716. ret = send(new_req, new_res);
  3717. if (ret) { res = new_res; }
  3718. }
  3719. }
  3720. }
  3721. #endif
  3722. return ret;
  3723. }
  3724. inline bool Client::redirect(const Request &req, Response &res) {
  3725. if (req.redirect_count == 0) { return false; }
  3726. auto location = res.get_header_value("location");
  3727. if (location.empty()) { return false; }
  3728. const static std::regex re(
  3729. R"(^(?:(https?):)?(?://([^:/?#]*)(?::(\d+))?)?([^?#]*(?:\?[^#]*)?)(?:#.*)?)");
  3730. std::smatch m;
  3731. if (!std::regex_match(location, m, re)) { return false; }
  3732. auto scheme = is_ssl() ? "https" : "http";
  3733. auto next_scheme = m[1].str();
  3734. auto next_host = m[2].str();
  3735. auto port_str = m[3].str();
  3736. auto next_path = m[4].str();
  3737. auto next_port = port_;
  3738. if (!port_str.empty()) {
  3739. next_port = std::stoi(port_str);
  3740. } else if (!next_scheme.empty()) {
  3741. next_port = next_scheme == "https" ? 443 : 80;
  3742. }
  3743. if (next_scheme.empty()) { next_scheme = scheme; }
  3744. if (next_host.empty()) { next_host = host_; }
  3745. if (next_path.empty()) { next_path = "/"; }
  3746. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  3747. return detail::redirect(*this, req, res, next_path);
  3748. } else {
  3749. if (next_scheme == "https") {
  3750. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3751. SSLClient cli(next_host.c_str(), next_port);
  3752. cli.copy_settings(*this);
  3753. return detail::redirect(cli, req, res, next_path);
  3754. #else
  3755. return false;
  3756. #endif
  3757. } else {
  3758. Client cli(next_host.c_str(), next_port);
  3759. cli.copy_settings(*this);
  3760. return detail::redirect(cli, req, res, next_path);
  3761. }
  3762. }
  3763. }
  3764. inline bool Client::write_request(Stream &strm, const Request &req) {
  3765. detail::BufferStream bstrm;
  3766. // Request line
  3767. const auto &path = detail::encode_url(req.path);
  3768. bstrm.write_format("%s %s HTTP/1.1\r\n", req.method.c_str(), path.c_str());
  3769. // Additonal headers
  3770. Headers headers;
  3771. if (!req.has_header("Host")) {
  3772. if (is_ssl()) {
  3773. if (port_ == 443) {
  3774. headers.emplace("Host", host_);
  3775. } else {
  3776. headers.emplace("Host", host_and_port_);
  3777. }
  3778. } else {
  3779. if (port_ == 80) {
  3780. headers.emplace("Host", host_);
  3781. } else {
  3782. headers.emplace("Host", host_and_port_);
  3783. }
  3784. }
  3785. }
  3786. if (!req.has_header("Accept")) { headers.emplace("Accept", "*/*"); }
  3787. if (!req.has_header("User-Agent")) {
  3788. headers.emplace("User-Agent", "cpp-httplib/0.6");
  3789. }
  3790. if (req.body.empty()) {
  3791. if (req.content_provider) {
  3792. auto length = std::to_string(req.content_length);
  3793. headers.emplace("Content-Length", length);
  3794. } else {
  3795. headers.emplace("Content-Length", "0");
  3796. }
  3797. } else {
  3798. if (!req.has_header("Content-Type")) {
  3799. headers.emplace("Content-Type", "text/plain");
  3800. }
  3801. if (!req.has_header("Content-Length")) {
  3802. auto length = std::to_string(req.body.size());
  3803. headers.emplace("Content-Length", length);
  3804. }
  3805. }
  3806. if (!basic_auth_username_.empty() && !basic_auth_password_.empty()) {
  3807. headers.insert(make_basic_authentication_header(
  3808. basic_auth_username_, basic_auth_password_, false));
  3809. }
  3810. if (!proxy_basic_auth_username_.empty() &&
  3811. !proxy_basic_auth_password_.empty()) {
  3812. headers.insert(make_basic_authentication_header(
  3813. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  3814. }
  3815. detail::write_headers(bstrm, req, headers);
  3816. // Flush buffer
  3817. auto &data = bstrm.get_buffer();
  3818. if (!detail::write_data(strm, data.data(), data.size())) { return false; }
  3819. // Body
  3820. if (req.body.empty()) {
  3821. if (req.content_provider) {
  3822. size_t offset = 0;
  3823. size_t end_offset = req.content_length;
  3824. bool ok = true;
  3825. DataSink data_sink;
  3826. data_sink.write = [&](const char *d, size_t l) {
  3827. if (ok) {
  3828. if (detail::write_data(strm, d, l)) {
  3829. offset += l;
  3830. } else {
  3831. ok = false;
  3832. }
  3833. }
  3834. };
  3835. data_sink.is_writable = [&](void) { return ok && strm.is_writable(); };
  3836. while (offset < end_offset) {
  3837. if (!req.content_provider(offset, end_offset - offset, data_sink)) {
  3838. return false;
  3839. }
  3840. if (!ok) { return false; }
  3841. }
  3842. }
  3843. } else {
  3844. return detail::write_data(strm, req.body.data(), req.body.size());
  3845. }
  3846. return true;
  3847. }
  3848. inline std::shared_ptr<Response> Client::send_with_content_provider(
  3849. const char *method, const char *path, const Headers &headers,
  3850. const std::string &body, size_t content_length,
  3851. ContentProvider content_provider, const char *content_type) {
  3852. Request req;
  3853. req.method = method;
  3854. req.headers = headers;
  3855. req.path = path;
  3856. if (content_type) { req.headers.emplace("Content-Type", content_type); }
  3857. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3858. if (compress_) {
  3859. if (content_provider) {
  3860. size_t offset = 0;
  3861. DataSink data_sink;
  3862. data_sink.write = [&](const char *data, size_t data_len) {
  3863. req.body.append(data, data_len);
  3864. offset += data_len;
  3865. };
  3866. data_sink.is_writable = [&](void) { return true; };
  3867. while (offset < content_length) {
  3868. if (!content_provider(offset, content_length - offset, data_sink)) {
  3869. return nullptr;
  3870. }
  3871. }
  3872. } else {
  3873. req.body = body;
  3874. }
  3875. if (!detail::compress(req.body)) { return nullptr; }
  3876. req.headers.emplace("Content-Encoding", "gzip");
  3877. } else
  3878. #endif
  3879. {
  3880. if (content_provider) {
  3881. req.content_length = content_length;
  3882. req.content_provider = content_provider;
  3883. } else {
  3884. req.body = body;
  3885. }
  3886. }
  3887. auto res = std::make_shared<Response>();
  3888. return send(req, *res) ? res : nullptr;
  3889. }
  3890. inline bool Client::process_request(Stream &strm, const Request &req,
  3891. Response &res, bool &connection_close) {
  3892. // Send request
  3893. if (!write_request(strm, req)) { return false; }
  3894. // Receive response and headers
  3895. if (!read_response_line(strm, res) ||
  3896. !detail::read_headers(strm, res.headers)) {
  3897. return false;
  3898. }
  3899. if (res.get_header_value("Connection") == "close" ||
  3900. res.version == "HTTP/1.0") {
  3901. connection_close = true;
  3902. }
  3903. if (req.response_handler) {
  3904. if (!req.response_handler(res)) { return false; }
  3905. }
  3906. // Body
  3907. if (req.method != "HEAD" && req.method != "CONNECT") {
  3908. auto out =
  3909. req.content_receiver
  3910. ? static_cast<ContentReceiver>([&](const char *buf, size_t n) {
  3911. return req.content_receiver(buf, n);
  3912. })
  3913. : static_cast<ContentReceiver>([&](const char *buf, size_t n) {
  3914. if (res.body.size() + n > res.body.max_size()) { return false; }
  3915. res.body.append(buf, n);
  3916. return true;
  3917. });
  3918. int dummy_status;
  3919. if (!detail::read_content(strm, res, (std::numeric_limits<size_t>::max)(),
  3920. dummy_status, req.progress, out, decompress_)) {
  3921. return false;
  3922. }
  3923. }
  3924. // Log
  3925. if (logger_) { logger_(req, res); }
  3926. return true;
  3927. }
  3928. inline bool
  3929. Client::process_socket(Socket &socket, size_t request_count,
  3930. std::function<bool(Stream &strm, bool last_connection,
  3931. bool &connection_close)>
  3932. callback) {
  3933. return detail::process_socket(
  3934. true, socket.sock, request_count, read_timeout_sec_, read_timeout_usec_,
  3935. write_timeout_sec_, write_timeout_usec_, callback);
  3936. }
  3937. inline bool Client::is_ssl() const { return false; }
  3938. inline std::shared_ptr<Response> Client::Get(const char *path) {
  3939. return Get(path, Headers(), Progress());
  3940. }
  3941. inline std::shared_ptr<Response> Client::Get(const char *path,
  3942. Progress progress) {
  3943. return Get(path, Headers(), std::move(progress));
  3944. }
  3945. inline std::shared_ptr<Response> Client::Get(const char *path,
  3946. const Headers &headers) {
  3947. return Get(path, headers, Progress());
  3948. }
  3949. inline std::shared_ptr<Response>
  3950. Client::Get(const char *path, const Headers &headers, Progress progress) {
  3951. Request req;
  3952. req.method = "GET";
  3953. req.path = path;
  3954. req.headers = headers;
  3955. req.progress = std::move(progress);
  3956. auto res = std::make_shared<Response>();
  3957. return send(req, *res) ? res : nullptr;
  3958. }
  3959. inline std::shared_ptr<Response> Client::Get(const char *path,
  3960. ContentReceiver content_receiver) {
  3961. return Get(path, Headers(), nullptr, std::move(content_receiver), Progress());
  3962. }
  3963. inline std::shared_ptr<Response> Client::Get(const char *path,
  3964. ContentReceiver content_receiver,
  3965. Progress progress) {
  3966. return Get(path, Headers(), nullptr, std::move(content_receiver),
  3967. std::move(progress));
  3968. }
  3969. inline std::shared_ptr<Response> Client::Get(const char *path,
  3970. const Headers &headers,
  3971. ContentReceiver content_receiver) {
  3972. return Get(path, headers, nullptr, std::move(content_receiver), Progress());
  3973. }
  3974. inline std::shared_ptr<Response> Client::Get(const char *path,
  3975. const Headers &headers,
  3976. ContentReceiver content_receiver,
  3977. Progress progress) {
  3978. return Get(path, headers, nullptr, std::move(content_receiver),
  3979. std::move(progress));
  3980. }
  3981. inline std::shared_ptr<Response> Client::Get(const char *path,
  3982. const Headers &headers,
  3983. ResponseHandler response_handler,
  3984. ContentReceiver content_receiver) {
  3985. return Get(path, headers, std::move(response_handler), content_receiver,
  3986. Progress());
  3987. }
  3988. inline std::shared_ptr<Response> Client::Get(const char *path,
  3989. const Headers &headers,
  3990. ResponseHandler response_handler,
  3991. ContentReceiver content_receiver,
  3992. Progress progress) {
  3993. Request req;
  3994. req.method = "GET";
  3995. req.path = path;
  3996. req.headers = headers;
  3997. req.response_handler = std::move(response_handler);
  3998. req.content_receiver = std::move(content_receiver);
  3999. req.progress = std::move(progress);
  4000. auto res = std::make_shared<Response>();
  4001. return send(req, *res) ? res : nullptr;
  4002. }
  4003. inline std::shared_ptr<Response> Client::Head(const char *path) {
  4004. return Head(path, Headers());
  4005. }
  4006. inline std::shared_ptr<Response> Client::Head(const char *path,
  4007. const Headers &headers) {
  4008. Request req;
  4009. req.method = "HEAD";
  4010. req.headers = headers;
  4011. req.path = path;
  4012. auto res = std::make_shared<Response>();
  4013. return send(req, *res) ? res : nullptr;
  4014. }
  4015. inline std::shared_ptr<Response> Client::Post(const char *path) {
  4016. return Post(path, std::string(), nullptr);
  4017. }
  4018. inline std::shared_ptr<Response> Client::Post(const char *path,
  4019. const std::string &body,
  4020. const char *content_type) {
  4021. return Post(path, Headers(), body, content_type);
  4022. }
  4023. inline std::shared_ptr<Response> Client::Post(const char *path,
  4024. const Headers &headers,
  4025. const std::string &body,
  4026. const char *content_type) {
  4027. return send_with_content_provider("POST", path, headers, body, 0, nullptr,
  4028. content_type);
  4029. }
  4030. inline std::shared_ptr<Response> Client::Post(const char *path,
  4031. const Params &params) {
  4032. return Post(path, Headers(), params);
  4033. }
  4034. inline std::shared_ptr<Response> Client::Post(const char *path,
  4035. size_t content_length,
  4036. ContentProvider content_provider,
  4037. const char *content_type) {
  4038. return Post(path, Headers(), content_length, content_provider, content_type);
  4039. }
  4040. inline std::shared_ptr<Response>
  4041. Client::Post(const char *path, const Headers &headers, size_t content_length,
  4042. ContentProvider content_provider, const char *content_type) {
  4043. return send_with_content_provider("POST", path, headers, std::string(),
  4044. content_length, content_provider,
  4045. content_type);
  4046. }
  4047. inline std::shared_ptr<Response>
  4048. Client::Post(const char *path, const Headers &headers, const Params &params) {
  4049. auto query = detail::params_to_query_str(params);
  4050. return Post(path, headers, query, "application/x-www-form-urlencoded");
  4051. }
  4052. inline std::shared_ptr<Response>
  4053. Client::Post(const char *path, const MultipartFormDataItems &items) {
  4054. return Post(path, Headers(), items);
  4055. }
  4056. inline std::shared_ptr<Response>
  4057. Client::Post(const char *path, const Headers &headers,
  4058. const MultipartFormDataItems &items) {
  4059. auto boundary = detail::make_multipart_data_boundary();
  4060. std::string body;
  4061. for (const auto &item : items) {
  4062. body += "--" + boundary + "\r\n";
  4063. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4064. if (!item.filename.empty()) {
  4065. body += "; filename=\"" + item.filename + "\"";
  4066. }
  4067. body += "\r\n";
  4068. if (!item.content_type.empty()) {
  4069. body += "Content-Type: " + item.content_type + "\r\n";
  4070. }
  4071. body += "\r\n";
  4072. body += item.content + "\r\n";
  4073. }
  4074. body += "--" + boundary + "--\r\n";
  4075. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4076. return Post(path, headers, body, content_type.c_str());
  4077. }
  4078. inline std::shared_ptr<Response> Client::Put(const char *path) {
  4079. return Put(path, std::string(), nullptr);
  4080. }
  4081. inline std::shared_ptr<Response> Client::Put(const char *path,
  4082. const std::string &body,
  4083. const char *content_type) {
  4084. return Put(path, Headers(), body, content_type);
  4085. }
  4086. inline std::shared_ptr<Response> Client::Put(const char *path,
  4087. const Headers &headers,
  4088. const std::string &body,
  4089. const char *content_type) {
  4090. return send_with_content_provider("PUT", path, headers, body, 0, nullptr,
  4091. content_type);
  4092. }
  4093. inline std::shared_ptr<Response> Client::Put(const char *path,
  4094. size_t content_length,
  4095. ContentProvider content_provider,
  4096. const char *content_type) {
  4097. return Put(path, Headers(), content_length, content_provider, content_type);
  4098. }
  4099. inline std::shared_ptr<Response>
  4100. Client::Put(const char *path, const Headers &headers, size_t content_length,
  4101. ContentProvider content_provider, const char *content_type) {
  4102. return send_with_content_provider("PUT", path, headers, std::string(),
  4103. content_length, content_provider,
  4104. content_type);
  4105. }
  4106. inline std::shared_ptr<Response> Client::Put(const char *path,
  4107. const Params &params) {
  4108. return Put(path, Headers(), params);
  4109. }
  4110. inline std::shared_ptr<Response>
  4111. Client::Put(const char *path, const Headers &headers, const Params &params) {
  4112. auto query = detail::params_to_query_str(params);
  4113. return Put(path, headers, query, "application/x-www-form-urlencoded");
  4114. }
  4115. inline std::shared_ptr<Response> Client::Patch(const char *path,
  4116. const std::string &body,
  4117. const char *content_type) {
  4118. return Patch(path, Headers(), body, content_type);
  4119. }
  4120. inline std::shared_ptr<Response> Client::Patch(const char *path,
  4121. const Headers &headers,
  4122. const std::string &body,
  4123. const char *content_type) {
  4124. return send_with_content_provider("PATCH", path, headers, body, 0, nullptr,
  4125. content_type);
  4126. }
  4127. inline std::shared_ptr<Response> Client::Patch(const char *path,
  4128. size_t content_length,
  4129. ContentProvider content_provider,
  4130. const char *content_type) {
  4131. return Patch(path, Headers(), content_length, content_provider, content_type);
  4132. }
  4133. inline std::shared_ptr<Response>
  4134. Client::Patch(const char *path, const Headers &headers, size_t content_length,
  4135. ContentProvider content_provider, const char *content_type) {
  4136. return send_with_content_provider("PATCH", path, headers, std::string(),
  4137. content_length, content_provider,
  4138. content_type);
  4139. }
  4140. inline std::shared_ptr<Response> Client::Delete(const char *path) {
  4141. return Delete(path, Headers(), std::string(), nullptr);
  4142. }
  4143. inline std::shared_ptr<Response> Client::Delete(const char *path,
  4144. const std::string &body,
  4145. const char *content_type) {
  4146. return Delete(path, Headers(), body, content_type);
  4147. }
  4148. inline std::shared_ptr<Response> Client::Delete(const char *path,
  4149. const Headers &headers) {
  4150. return Delete(path, headers, std::string(), nullptr);
  4151. }
  4152. inline std::shared_ptr<Response> Client::Delete(const char *path,
  4153. const Headers &headers,
  4154. const std::string &body,
  4155. const char *content_type) {
  4156. Request req;
  4157. req.method = "DELETE";
  4158. req.headers = headers;
  4159. req.path = path;
  4160. if (content_type) { req.headers.emplace("Content-Type", content_type); }
  4161. req.body = body;
  4162. auto res = std::make_shared<Response>();
  4163. return send(req, *res) ? res : nullptr;
  4164. }
  4165. inline std::shared_ptr<Response> Client::Options(const char *path) {
  4166. return Options(path, Headers());
  4167. }
  4168. inline std::shared_ptr<Response> Client::Options(const char *path,
  4169. const Headers &headers) {
  4170. Request req;
  4171. req.method = "OPTIONS";
  4172. req.path = path;
  4173. req.headers = headers;
  4174. auto res = std::make_shared<Response>();
  4175. return send(req, *res) ? res : nullptr;
  4176. }
  4177. inline size_t Client::is_socket_open() const {
  4178. std::lock_guard<std::mutex> guard(socket_mutex_);
  4179. return socket_.is_open();
  4180. }
  4181. inline void Client::stop() {
  4182. std::lock_guard<std::mutex> guard(socket_mutex_);
  4183. if (socket_.is_open()) {
  4184. detail::shutdown_socket(socket_.sock);
  4185. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4186. close_socket(socket_, true);
  4187. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4188. }
  4189. }
  4190. inline void Client::set_timeout_sec(time_t timeout_sec) {
  4191. set_connection_timeout(timeout_sec, 0);
  4192. }
  4193. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  4194. connection_timeout_sec_ = sec;
  4195. connection_timeout_usec_ = usec;
  4196. }
  4197. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  4198. read_timeout_sec_ = sec;
  4199. read_timeout_usec_ = usec;
  4200. }
  4201. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  4202. write_timeout_sec_ = sec;
  4203. write_timeout_usec_ = usec;
  4204. }
  4205. inline void Client::set_keep_alive_max_count(size_t count) {
  4206. keep_alive_max_count_ = count;
  4207. }
  4208. inline void Client::set_basic_auth(const char *username, const char *password) {
  4209. basic_auth_username_ = username;
  4210. basic_auth_password_ = password;
  4211. }
  4212. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4213. inline void Client::set_digest_auth(const char *username,
  4214. const char *password) {
  4215. digest_auth_username_ = username;
  4216. digest_auth_password_ = password;
  4217. }
  4218. #endif
  4219. inline void Client::set_follow_location(bool on) { follow_location_ = on; }
  4220. inline void Client::set_compress(bool on) { compress_ = on; }
  4221. inline void Client::set_decompress(bool on) { decompress_ = on; }
  4222. inline void Client::set_interface(const char *intf) { interface_ = intf; }
  4223. inline void Client::set_proxy(const char *host, int port) {
  4224. proxy_host_ = host;
  4225. proxy_port_ = port;
  4226. }
  4227. inline void Client::set_proxy_basic_auth(const char *username,
  4228. const char *password) {
  4229. proxy_basic_auth_username_ = username;
  4230. proxy_basic_auth_password_ = password;
  4231. }
  4232. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4233. inline void Client::set_proxy_digest_auth(const char *username,
  4234. const char *password) {
  4235. proxy_digest_auth_username_ = username;
  4236. proxy_digest_auth_password_ = password;
  4237. }
  4238. #endif
  4239. inline void Client::set_logger(Logger logger) { logger_ = std::move(logger); }
  4240. /*
  4241. * SSL Implementation
  4242. */
  4243. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4244. namespace detail {
  4245. template <typename U, typename V>
  4246. inline SSL *ssl_new(socket_t sock, SSL_CTX *ctx, std::mutex &ctx_mutex,
  4247. U SSL_connect_or_accept, V setup) {
  4248. SSL *ssl = nullptr;
  4249. {
  4250. std::lock_guard<std::mutex> guard(ctx_mutex);
  4251. ssl = SSL_new(ctx);
  4252. }
  4253. if (ssl) {
  4254. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  4255. SSL_set_bio(ssl, bio, bio);
  4256. if (!setup(ssl) || SSL_connect_or_accept(ssl) != 1) {
  4257. SSL_shutdown(ssl);
  4258. {
  4259. std::lock_guard<std::mutex> guard(ctx_mutex);
  4260. SSL_free(ssl);
  4261. }
  4262. return nullptr;
  4263. }
  4264. }
  4265. return ssl;
  4266. }
  4267. inline void ssl_delete(std::mutex &ctx_mutex, SSL *ssl,
  4268. bool process_socket_ret) {
  4269. if (process_socket_ret) {
  4270. SSL_shutdown(ssl); // shutdown only if not already closed by remote
  4271. }
  4272. std::lock_guard<std::mutex> guard(ctx_mutex);
  4273. SSL_free(ssl);
  4274. }
  4275. template <typename T>
  4276. inline bool
  4277. process_socket_ssl(SSL *ssl, bool is_client_request, socket_t sock,
  4278. size_t keep_alive_max_count, time_t read_timeout_sec,
  4279. time_t read_timeout_usec, time_t write_timeout_sec,
  4280. time_t write_timeout_usec, T callback) {
  4281. return process_socket_core(
  4282. is_client_request, sock, keep_alive_max_count,
  4283. [&](bool last_connection, bool connection_close) {
  4284. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
  4285. write_timeout_sec, write_timeout_usec);
  4286. return callback(strm, last_connection, connection_close);
  4287. });
  4288. }
  4289. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  4290. static std::shared_ptr<std::vector<std::mutex>> openSSL_locks_;
  4291. class SSLThreadLocks {
  4292. public:
  4293. SSLThreadLocks() {
  4294. openSSL_locks_ =
  4295. std::make_shared<std::vector<std::mutex>>(CRYPTO_num_locks());
  4296. CRYPTO_set_locking_callback(locking_callback);
  4297. }
  4298. ~SSLThreadLocks() { CRYPTO_set_locking_callback(nullptr); }
  4299. private:
  4300. static void locking_callback(int mode, int type, const char * /*file*/,
  4301. int /*line*/) {
  4302. auto &lk = (*openSSL_locks_)[static_cast<size_t>(type)];
  4303. if (mode & CRYPTO_LOCK) {
  4304. lk.lock();
  4305. } else {
  4306. lk.unlock();
  4307. }
  4308. }
  4309. };
  4310. #endif
  4311. class SSLInit {
  4312. public:
  4313. SSLInit() {
  4314. #if OPENSSL_VERSION_NUMBER < 0x1010001fL
  4315. SSL_load_error_strings();
  4316. SSL_library_init();
  4317. #else
  4318. OPENSSL_init_ssl(
  4319. OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
  4320. #endif
  4321. }
  4322. ~SSLInit() {
  4323. #if OPENSSL_VERSION_NUMBER < 0x1010001fL
  4324. ERR_free_strings();
  4325. #endif
  4326. }
  4327. private:
  4328. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  4329. SSLThreadLocks thread_init_;
  4330. #endif
  4331. };
  4332. // SSL socket stream implementation
  4333. inline SSLSocketStream::SSLSocketStream(socket_t sock, SSL *ssl,
  4334. time_t read_timeout_sec,
  4335. time_t read_timeout_usec,
  4336. time_t write_timeout_sec,
  4337. time_t write_timeout_usec)
  4338. : sock_(sock), ssl_(ssl), read_timeout_sec_(read_timeout_sec),
  4339. read_timeout_usec_(read_timeout_usec),
  4340. write_timeout_sec_(write_timeout_sec),
  4341. write_timeout_usec_(write_timeout_usec) {}
  4342. inline SSLSocketStream::~SSLSocketStream() {}
  4343. inline bool SSLSocketStream::is_readable() const {
  4344. return detail::select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  4345. }
  4346. inline bool SSLSocketStream::is_writable() const {
  4347. return detail::select_write(sock_, write_timeout_sec_, write_timeout_usec_) >
  4348. 0;
  4349. }
  4350. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  4351. if (SSL_pending(ssl_) > 0 || is_readable()) {
  4352. return SSL_read(ssl_, ptr, static_cast<int>(size));
  4353. }
  4354. return -1;
  4355. }
  4356. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  4357. if (is_writable()) { return SSL_write(ssl_, ptr, static_cast<int>(size)); }
  4358. return -1;
  4359. }
  4360. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  4361. int &port) const {
  4362. detail::get_remote_ip_and_port(sock_, ip, port);
  4363. }
  4364. static SSLInit sslinit_;
  4365. } // namespace detail
  4366. // SSL HTTP server implementation
  4367. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  4368. const char *client_ca_cert_file_path,
  4369. const char *client_ca_cert_dir_path) {
  4370. ctx_ = SSL_CTX_new(SSLv23_server_method());
  4371. if (ctx_) {
  4372. SSL_CTX_set_options(ctx_,
  4373. SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
  4374. SSL_OP_NO_COMPRESSION |
  4375. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  4376. // auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  4377. // SSL_CTX_set_tmp_ecdh(ctx_, ecdh);
  4378. // EC_KEY_free(ecdh);
  4379. if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 ||
  4380. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) !=
  4381. 1) {
  4382. SSL_CTX_free(ctx_);
  4383. ctx_ = nullptr;
  4384. } else if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  4385. // if (client_ca_cert_file_path) {
  4386. // auto list = SSL_load_client_CA_file(client_ca_cert_file_path);
  4387. // SSL_CTX_set_client_CA_list(ctx_, list);
  4388. // }
  4389. SSL_CTX_load_verify_locations(ctx_, client_ca_cert_file_path,
  4390. client_ca_cert_dir_path);
  4391. SSL_CTX_set_verify(
  4392. ctx_,
  4393. SSL_VERIFY_PEER |
  4394. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  4395. nullptr);
  4396. }
  4397. }
  4398. }
  4399. inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key,
  4400. X509_STORE *client_ca_cert_store) {
  4401. ctx_ = SSL_CTX_new(SSLv23_server_method());
  4402. if (ctx_) {
  4403. SSL_CTX_set_options(ctx_,
  4404. SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
  4405. SSL_OP_NO_COMPRESSION |
  4406. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  4407. if (SSL_CTX_use_certificate(ctx_, cert) != 1 ||
  4408. SSL_CTX_use_PrivateKey(ctx_, private_key) != 1) {
  4409. SSL_CTX_free(ctx_);
  4410. ctx_ = nullptr;
  4411. } else if (client_ca_cert_store) {
  4412. SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
  4413. SSL_CTX_set_verify(
  4414. ctx_,
  4415. SSL_VERIFY_PEER |
  4416. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  4417. nullptr);
  4418. }
  4419. }
  4420. }
  4421. inline SSLServer::~SSLServer() {
  4422. if (ctx_) { SSL_CTX_free(ctx_); }
  4423. }
  4424. inline bool SSLServer::is_valid() const { return ctx_; }
  4425. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  4426. auto ssl = detail::ssl_new(sock, ctx_, ctx_mutex_, SSL_accept,
  4427. [](SSL * /*ssl*/) { return true; });
  4428. if (ssl) {
  4429. auto ret = detail::process_socket_ssl(
  4430. ssl, false, sock, keep_alive_max_count_, read_timeout_sec_,
  4431. read_timeout_usec_, write_timeout_sec_, write_timeout_usec_,
  4432. [this, ssl](Stream &strm, bool last_connection,
  4433. bool &connection_close) {
  4434. return process_request(strm, last_connection, connection_close,
  4435. [&](Request &req) { req.ssl = ssl; });
  4436. });
  4437. detail::ssl_delete(ctx_mutex_, ssl, ret);
  4438. return ret;
  4439. }
  4440. detail::close_socket(sock);
  4441. return false;
  4442. }
  4443. // SSL HTTP client implementation
  4444. inline SSLClient::SSLClient(const std::string &host)
  4445. : SSLClient(host, 443, std::string(), std::string()) {}
  4446. inline SSLClient::SSLClient(const std::string &host, int port)
  4447. : SSLClient(host, port, std::string(), std::string()) {}
  4448. inline SSLClient::SSLClient(const std::string &host, int port,
  4449. const std::string &client_cert_path,
  4450. const std::string &client_key_path)
  4451. : Client(host, port, client_cert_path, client_key_path) {
  4452. ctx_ = SSL_CTX_new(SSLv23_client_method());
  4453. detail::split(&host_[0], &host_[host_.size()], '.',
  4454. [&](const char *b, const char *e) {
  4455. host_components_.emplace_back(std::string(b, e));
  4456. });
  4457. if (!client_cert_path.empty() && !client_key_path.empty()) {
  4458. if (SSL_CTX_use_certificate_file(ctx_, client_cert_path.c_str(),
  4459. SSL_FILETYPE_PEM) != 1 ||
  4460. SSL_CTX_use_PrivateKey_file(ctx_, client_key_path.c_str(),
  4461. SSL_FILETYPE_PEM) != 1) {
  4462. SSL_CTX_free(ctx_);
  4463. ctx_ = nullptr;
  4464. }
  4465. }
  4466. }
  4467. inline SSLClient::SSLClient(const std::string &host, int port,
  4468. X509 *client_cert, EVP_PKEY *client_key)
  4469. : Client(host, port) {
  4470. ctx_ = SSL_CTX_new(SSLv23_client_method());
  4471. detail::split(&host_[0], &host_[host_.size()], '.',
  4472. [&](const char *b, const char *e) {
  4473. host_components_.emplace_back(std::string(b, e));
  4474. });
  4475. if (client_cert != nullptr && client_key != nullptr) {
  4476. if (SSL_CTX_use_certificate(ctx_, client_cert) != 1 ||
  4477. SSL_CTX_use_PrivateKey(ctx_, client_key) != 1) {
  4478. SSL_CTX_free(ctx_);
  4479. ctx_ = nullptr;
  4480. }
  4481. }
  4482. }
  4483. inline SSLClient::~SSLClient() {
  4484. if (ctx_) { SSL_CTX_free(ctx_); }
  4485. }
  4486. inline bool SSLClient::is_valid() const { return ctx_; }
  4487. inline void SSLClient::set_ca_cert_path(const char *ca_cert_file_path,
  4488. const char *ca_cert_dir_path) {
  4489. if (ca_cert_file_path) { ca_cert_file_path_ = ca_cert_file_path; }
  4490. if (ca_cert_dir_path) { ca_cert_dir_path_ = ca_cert_dir_path; }
  4491. }
  4492. inline void SSLClient::set_ca_cert_store(X509_STORE *ca_cert_store) {
  4493. if (ca_cert_store) { ca_cert_store_ = ca_cert_store; }
  4494. }
  4495. inline void SSLClient::enable_server_certificate_verification(bool enabled) {
  4496. server_certificate_verification_ = enabled;
  4497. }
  4498. inline long SSLClient::get_openssl_verify_result() const {
  4499. return verify_result_;
  4500. }
  4501. inline SSL_CTX *SSLClient::ssl_context() const { return ctx_; }
  4502. inline bool SSLClient::create_and_connect_socket(Socket &socket) {
  4503. if (is_valid() && Client::create_and_connect_socket(socket) &&
  4504. initialize_ssl(socket)) {
  4505. if (!proxy_host_.empty()) {
  4506. bool error;
  4507. if (!connect_with_proxy(socket, error)) { return error; }
  4508. }
  4509. return true;
  4510. }
  4511. return false;
  4512. }
  4513. inline bool SSLClient::connect_with_proxy(Socket &socket, bool &error) {
  4514. error = true;
  4515. Response res;
  4516. if (!detail::process_socket_core(
  4517. true, socket.sock, 1,
  4518. [&](bool /*last_connection*/, bool &connection_close) {
  4519. detail::SocketStream strm(socket.sock, read_timeout_sec_,
  4520. read_timeout_usec_, write_timeout_sec_,
  4521. write_timeout_usec_);
  4522. Request req2;
  4523. req2.method = "CONNECT";
  4524. req2.path = host_and_port_;
  4525. return process_request(strm, req2, res, connection_close);
  4526. })) {
  4527. close_socket(socket, true);
  4528. error = false;
  4529. return false;
  4530. }
  4531. if (res.status == 407) {
  4532. if (!proxy_digest_auth_username_.empty() &&
  4533. !proxy_digest_auth_password_.empty()) {
  4534. std::map<std::string, std::string> auth;
  4535. if (parse_www_authenticate(res, auth, true)) {
  4536. Response res3;
  4537. if (!detail::process_socket_core(
  4538. true, socket.sock, 1,
  4539. [&](bool /*last_connection*/, bool &connection_close) {
  4540. detail::SocketStream strm(
  4541. socket.sock, read_timeout_sec_, read_timeout_usec_,
  4542. write_timeout_sec_, write_timeout_usec_);
  4543. Request req3;
  4544. req3.method = "CONNECT";
  4545. req3.path = host_and_port_;
  4546. req3.headers.insert(make_digest_authentication_header(
  4547. req3, auth, 1, random_string(10),
  4548. proxy_digest_auth_username_, proxy_digest_auth_password_,
  4549. true));
  4550. return process_request(strm, req3, res3, connection_close);
  4551. })) {
  4552. close_socket(socket, true);
  4553. error = false;
  4554. return false;
  4555. }
  4556. }
  4557. } else {
  4558. return false;
  4559. }
  4560. }
  4561. return true;
  4562. }
  4563. inline bool SSLClient::initialize_ssl(Socket &socket) {
  4564. auto ssl = detail::ssl_new(
  4565. socket.sock, ctx_, ctx_mutex_,
  4566. [&](SSL *ssl) {
  4567. if (ca_cert_file_path_.empty() && ca_cert_store_ == nullptr) {
  4568. SSL_CTX_set_verify(ctx_, SSL_VERIFY_NONE, nullptr);
  4569. } else if (!ca_cert_file_path_.empty()) {
  4570. if (!SSL_CTX_load_verify_locations(ctx_, ca_cert_file_path_.c_str(),
  4571. nullptr)) {
  4572. return false;
  4573. }
  4574. SSL_CTX_set_verify(ctx_, SSL_VERIFY_PEER, nullptr);
  4575. } else if (ca_cert_store_ != nullptr) {
  4576. if (SSL_CTX_get_cert_store(ctx_) != ca_cert_store_) {
  4577. SSL_CTX_set_cert_store(ctx_, ca_cert_store_);
  4578. }
  4579. SSL_CTX_set_verify(ctx_, SSL_VERIFY_PEER, nullptr);
  4580. }
  4581. if (SSL_connect(ssl) != 1) { return false; }
  4582. if (server_certificate_verification_) {
  4583. verify_result_ = SSL_get_verify_result(ssl);
  4584. if (verify_result_ != X509_V_OK) { return false; }
  4585. auto server_cert = SSL_get_peer_certificate(ssl);
  4586. if (server_cert == nullptr) { return false; }
  4587. if (!verify_host(server_cert)) {
  4588. X509_free(server_cert);
  4589. return false;
  4590. }
  4591. X509_free(server_cert);
  4592. }
  4593. return true;
  4594. },
  4595. [&](SSL *ssl) {
  4596. SSL_set_tlsext_host_name(ssl, host_.c_str());
  4597. return true;
  4598. });
  4599. if (ssl) {
  4600. socket.ssl = ssl;
  4601. return true;
  4602. }
  4603. close_socket(socket, false);
  4604. return false;
  4605. }
  4606. inline void SSLClient::close_socket(Socket &socket, bool process_socket_ret) {
  4607. detail::close_socket(socket.sock);
  4608. socket_.sock = INVALID_SOCKET;
  4609. if (socket.ssl) {
  4610. detail::ssl_delete(ctx_mutex_, socket.ssl, process_socket_ret);
  4611. socket_.ssl = nullptr;
  4612. }
  4613. }
  4614. inline bool
  4615. SSLClient::process_socket(Socket &socket, size_t request_count,
  4616. std::function<bool(Stream &strm, bool last_connection,
  4617. bool &connection_close)>
  4618. callback) {
  4619. assert(socket.ssl);
  4620. return detail::process_socket_ssl(
  4621. socket.ssl, true, socket.sock, request_count, read_timeout_sec_,
  4622. read_timeout_usec_, write_timeout_sec_, write_timeout_usec_,
  4623. [&](Stream &strm, bool last_connection, bool &connection_close) {
  4624. return callback(strm, last_connection, connection_close);
  4625. });
  4626. }
  4627. inline bool SSLClient::is_ssl() const { return true; }
  4628. inline bool SSLClient::verify_host(X509 *server_cert) const {
  4629. /* Quote from RFC2818 section 3.1 "Server Identity"
  4630. If a subjectAltName extension of type dNSName is present, that MUST
  4631. be used as the identity. Otherwise, the (most specific) Common Name
  4632. field in the Subject field of the certificate MUST be used. Although
  4633. the use of the Common Name is existing practice, it is deprecated and
  4634. Certification Authorities are encouraged to use the dNSName instead.
  4635. Matching is performed using the matching rules specified by
  4636. [RFC2459]. If more than one identity of a given type is present in
  4637. the certificate (e.g., more than one dNSName name, a match in any one
  4638. of the set is considered acceptable.) Names may contain the wildcard
  4639. character * which is considered to match any single domain name
  4640. component or component fragment. E.g., *.a.com matches foo.a.com but
  4641. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  4642. In some cases, the URI is specified as an IP address rather than a
  4643. hostname. In this case, the iPAddress subjectAltName must be present
  4644. in the certificate and must exactly match the IP in the URI.
  4645. */
  4646. return verify_host_with_subject_alt_name(server_cert) ||
  4647. verify_host_with_common_name(server_cert);
  4648. }
  4649. inline bool
  4650. SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
  4651. auto ret = false;
  4652. auto type = GEN_DNS;
  4653. struct in6_addr addr6;
  4654. struct in_addr addr;
  4655. size_t addr_len = 0;
  4656. #ifndef __MINGW32__
  4657. if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
  4658. type = GEN_IPADD;
  4659. addr_len = sizeof(struct in6_addr);
  4660. } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
  4661. type = GEN_IPADD;
  4662. addr_len = sizeof(struct in_addr);
  4663. }
  4664. #endif
  4665. auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
  4666. X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
  4667. if (alt_names) {
  4668. auto dsn_matched = false;
  4669. auto ip_mached = false;
  4670. auto count = sk_GENERAL_NAME_num(alt_names);
  4671. for (auto i = 0; i < count && !dsn_matched; i++) {
  4672. auto val = sk_GENERAL_NAME_value(alt_names, i);
  4673. if (val->type == type) {
  4674. auto name = (const char *)ASN1_STRING_get0_data(val->d.ia5);
  4675. auto name_len = (size_t)ASN1_STRING_length(val->d.ia5);
  4676. if (strlen(name) == name_len) {
  4677. switch (type) {
  4678. case GEN_DNS: dsn_matched = check_host_name(name, name_len); break;
  4679. case GEN_IPADD:
  4680. if (!memcmp(&addr6, name, addr_len) ||
  4681. !memcmp(&addr, name, addr_len)) {
  4682. ip_mached = true;
  4683. }
  4684. break;
  4685. }
  4686. }
  4687. }
  4688. }
  4689. if (dsn_matched || ip_mached) { ret = true; }
  4690. }
  4691. GENERAL_NAMES_free((STACK_OF(GENERAL_NAME) *)alt_names);
  4692. return ret;
  4693. }
  4694. inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
  4695. const auto subject_name = X509_get_subject_name(server_cert);
  4696. if (subject_name != nullptr) {
  4697. char name[BUFSIZ];
  4698. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  4699. name, sizeof(name));
  4700. if (name_len != -1) {
  4701. return check_host_name(name, static_cast<size_t>(name_len));
  4702. }
  4703. }
  4704. return false;
  4705. }
  4706. inline bool SSLClient::check_host_name(const char *pattern,
  4707. size_t pattern_len) const {
  4708. if (host_.size() == pattern_len && host_ == pattern) { return true; }
  4709. // Wildcard match
  4710. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  4711. std::vector<std::string> pattern_components;
  4712. detail::split(&pattern[0], &pattern[pattern_len], '.',
  4713. [&](const char *b, const char *e) {
  4714. pattern_components.emplace_back(std::string(b, e));
  4715. });
  4716. if (host_components_.size() != pattern_components.size()) { return false; }
  4717. auto itr = pattern_components.begin();
  4718. for (const auto &h : host_components_) {
  4719. auto &p = *itr;
  4720. if (p != h && p != "*") {
  4721. auto partial_match = (p.size() > 0 && p[p.size() - 1] == '*' &&
  4722. !p.compare(0, p.size() - 1, h));
  4723. if (!partial_match) { return false; }
  4724. }
  4725. ++itr;
  4726. }
  4727. return true;
  4728. }
  4729. #endif
  4730. // ----------------------------------------------------------------------------
  4731. } // namespace httplib
  4732. #endif // CPPHTTPLIB_HTTPLIB_H