httplib.h 129 KB

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