httplib.h 164 KB

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