httplib.h 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2025 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #ifndef CPPHTTPLIB_HTTPLIB_H
  8. #define CPPHTTPLIB_HTTPLIB_H
  9. #define CPPHTTPLIB_VERSION "0.20.1"
  10. /*
  11. * Configuration
  12. */
  13. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  14. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  15. #endif
  16. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND
  17. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000
  18. #endif
  19. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  20. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100
  21. #endif
  22. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
  23. #define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
  24. #endif
  25. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
  26. #define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
  27. #endif
  28. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND
  29. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5
  30. #endif
  31. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND
  32. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0
  33. #endif
  34. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND
  35. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5
  36. #endif
  37. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND
  38. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0
  39. #endif
  40. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND
  41. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300
  42. #endif
  43. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND
  44. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0
  45. #endif
  46. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND
  47. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5
  48. #endif
  49. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND
  50. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0
  51. #endif
  52. #ifndef CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND
  53. #define CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND 0
  54. #endif
  55. #ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
  56. #define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
  57. #endif
  58. #ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
  59. #ifdef _WIN32
  60. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 10000
  61. #else
  62. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
  63. #endif
  64. #endif
  65. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  66. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  67. #endif
  68. #ifndef CPPHTTPLIB_HEADER_MAX_LENGTH
  69. #define CPPHTTPLIB_HEADER_MAX_LENGTH 8192
  70. #endif
  71. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  72. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  73. #endif
  74. #ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT
  75. #define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024
  76. #endif
  77. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  78. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH ((std::numeric_limits<size_t>::max)())
  79. #endif
  80. #ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH
  81. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192
  82. #endif
  83. #ifndef CPPHTTPLIB_RANGE_MAX_COUNT
  84. #define CPPHTTPLIB_RANGE_MAX_COUNT 1024
  85. #endif
  86. #ifndef CPPHTTPLIB_TCP_NODELAY
  87. #define CPPHTTPLIB_TCP_NODELAY false
  88. #endif
  89. #ifndef CPPHTTPLIB_IPV6_V6ONLY
  90. #define CPPHTTPLIB_IPV6_V6ONLY false
  91. #endif
  92. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  93. #define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u)
  94. #endif
  95. #ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
  96. #define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
  97. #endif
  98. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  99. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  100. ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
  101. ? std::thread::hardware_concurrency() - 1 \
  102. : 0))
  103. #endif
  104. #ifndef CPPHTTPLIB_RECV_FLAGS
  105. #define CPPHTTPLIB_RECV_FLAGS 0
  106. #endif
  107. #ifndef CPPHTTPLIB_SEND_FLAGS
  108. #define CPPHTTPLIB_SEND_FLAGS 0
  109. #endif
  110. #ifndef CPPHTTPLIB_LISTEN_BACKLOG
  111. #define CPPHTTPLIB_LISTEN_BACKLOG 5
  112. #endif
  113. #ifndef CPPHTTPLIB_MAX_LINE_LENGTH
  114. #define CPPHTTPLIB_MAX_LINE_LENGTH 32768
  115. #endif
  116. /*
  117. * Headers
  118. */
  119. #ifdef _WIN32
  120. #ifndef _CRT_SECURE_NO_WARNINGS
  121. #define _CRT_SECURE_NO_WARNINGS
  122. #endif //_CRT_SECURE_NO_WARNINGS
  123. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  124. #define _CRT_NONSTDC_NO_DEPRECATE
  125. #endif //_CRT_NONSTDC_NO_DEPRECATE
  126. #if defined(_MSC_VER)
  127. #if _MSC_VER < 1900
  128. #error Sorry, Visual Studio versions prior to 2015 are not supported
  129. #endif
  130. #pragma comment(lib, "ws2_32.lib")
  131. #ifdef _WIN64
  132. using ssize_t = __int64;
  133. #else
  134. using ssize_t = long;
  135. #endif
  136. #endif // _MSC_VER
  137. #ifndef S_ISREG
  138. #define S_ISREG(m) (((m) & S_IFREG) == S_IFREG)
  139. #endif // S_ISREG
  140. #ifndef S_ISDIR
  141. #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR)
  142. #endif // S_ISDIR
  143. #ifndef NOMINMAX
  144. #define NOMINMAX
  145. #endif // NOMINMAX
  146. #include <io.h>
  147. #include <winsock2.h>
  148. #include <ws2tcpip.h>
  149. // afunix.h uses types declared in winsock2.h, so has to be included after it.
  150. #include <afunix.h>
  151. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  152. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  153. #endif
  154. using nfds_t = unsigned long;
  155. using socket_t = SOCKET;
  156. using socklen_t = int;
  157. #else // not _WIN32
  158. #include <arpa/inet.h>
  159. #if !defined(_AIX) && !defined(__MVS__)
  160. #include <ifaddrs.h>
  161. #endif
  162. #ifdef __MVS__
  163. #include <strings.h>
  164. #ifndef NI_MAXHOST
  165. #define NI_MAXHOST 1025
  166. #endif
  167. #endif
  168. #include <net/if.h>
  169. #include <netdb.h>
  170. #include <netinet/in.h>
  171. #ifdef __linux__
  172. #include <resolv.h>
  173. #endif
  174. #include <csignal>
  175. #include <netinet/tcp.h>
  176. #include <poll.h>
  177. #include <pthread.h>
  178. #include <sys/mman.h>
  179. #include <sys/socket.h>
  180. #include <sys/un.h>
  181. #include <unistd.h>
  182. using socket_t = int;
  183. #ifndef INVALID_SOCKET
  184. #define INVALID_SOCKET (-1)
  185. #endif
  186. #endif //_WIN32
  187. #include <algorithm>
  188. #include <array>
  189. #include <atomic>
  190. #include <cassert>
  191. #include <cctype>
  192. #include <climits>
  193. #include <condition_variable>
  194. #include <cstring>
  195. #include <errno.h>
  196. #include <exception>
  197. #include <fcntl.h>
  198. #include <functional>
  199. #include <iomanip>
  200. #include <iostream>
  201. #include <list>
  202. #include <map>
  203. #include <memory>
  204. #include <mutex>
  205. #include <random>
  206. #include <regex>
  207. #include <set>
  208. #include <sstream>
  209. #include <string>
  210. #include <sys/stat.h>
  211. #include <thread>
  212. #include <unordered_map>
  213. #include <unordered_set>
  214. #include <utility>
  215. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  216. #ifdef _WIN32
  217. #include <wincrypt.h>
  218. // these are defined in wincrypt.h and it breaks compilation if BoringSSL is
  219. // used
  220. #undef X509_NAME
  221. #undef X509_CERT_PAIR
  222. #undef X509_EXTENSIONS
  223. #undef PKCS7_SIGNER_INFO
  224. #ifdef _MSC_VER
  225. #pragma comment(lib, "crypt32.lib")
  226. #endif
  227. #elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && defined(__APPLE__)
  228. #include <TargetConditionals.h>
  229. #if TARGET_OS_OSX
  230. #include <CoreFoundation/CoreFoundation.h>
  231. #include <Security/Security.h>
  232. #endif // TARGET_OS_OSX
  233. #endif // _WIN32
  234. #include <openssl/err.h>
  235. #include <openssl/evp.h>
  236. #include <openssl/ssl.h>
  237. #include <openssl/x509v3.h>
  238. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  239. #include <openssl/applink.c>
  240. #endif
  241. #include <iostream>
  242. #include <sstream>
  243. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  244. #if OPENSSL_VERSION_NUMBER < 0x1010107f
  245. #error Please use OpenSSL or a current version of BoringSSL
  246. #endif
  247. #define SSL_get1_peer_certificate SSL_get_peer_certificate
  248. #elif OPENSSL_VERSION_NUMBER < 0x30000000L
  249. #error Sorry, OpenSSL versions prior to 3.0.0 are not supported
  250. #endif
  251. #endif
  252. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  253. #include <zlib.h>
  254. #endif
  255. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  256. #include <brotli/decode.h>
  257. #include <brotli/encode.h>
  258. #endif
  259. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  260. #include <zstd.h>
  261. #endif
  262. /*
  263. * Declaration
  264. */
  265. namespace httplib {
  266. namespace detail {
  267. /*
  268. * Backport std::make_unique from C++14.
  269. *
  270. * NOTE: This code came up with the following stackoverflow post:
  271. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  272. *
  273. */
  274. template <class T, class... Args>
  275. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  276. make_unique(Args &&...args) {
  277. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  278. }
  279. template <class T>
  280. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  281. make_unique(std::size_t n) {
  282. typedef typename std::remove_extent<T>::type RT;
  283. return std::unique_ptr<T>(new RT[n]);
  284. }
  285. namespace case_ignore {
  286. inline unsigned char to_lower(int c) {
  287. const static unsigned char table[256] = {
  288. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  289. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  290. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  291. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  292. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  293. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  294. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  295. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  296. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  297. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  298. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  299. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  300. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  301. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  302. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  303. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  304. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  305. 255,
  306. };
  307. return table[(unsigned char)(char)c];
  308. }
  309. inline bool equal(const std::string &a, const std::string &b) {
  310. return a.size() == b.size() &&
  311. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  312. return to_lower(ca) == to_lower(cb);
  313. });
  314. }
  315. struct equal_to {
  316. bool operator()(const std::string &a, const std::string &b) const {
  317. return equal(a, b);
  318. }
  319. };
  320. struct hash {
  321. size_t operator()(const std::string &key) const {
  322. return hash_core(key.data(), key.size(), 0);
  323. }
  324. size_t hash_core(const char *s, size_t l, size_t h) const {
  325. return (l == 0) ? h
  326. : hash_core(s + 1, l - 1,
  327. // Unsets the 6 high bits of h, therefore no
  328. // overflow happens
  329. (((std::numeric_limits<size_t>::max)() >> 6) &
  330. h * 33) ^
  331. static_cast<unsigned char>(to_lower(*s)));
  332. }
  333. };
  334. } // namespace case_ignore
  335. // This is based on
  336. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  337. struct scope_exit {
  338. explicit scope_exit(std::function<void(void)> &&f)
  339. : exit_function(std::move(f)), execute_on_destruction{true} {}
  340. scope_exit(scope_exit &&rhs) noexcept
  341. : exit_function(std::move(rhs.exit_function)),
  342. execute_on_destruction{rhs.execute_on_destruction} {
  343. rhs.release();
  344. }
  345. ~scope_exit() {
  346. if (execute_on_destruction) { this->exit_function(); }
  347. }
  348. void release() { this->execute_on_destruction = false; }
  349. private:
  350. scope_exit(const scope_exit &) = delete;
  351. void operator=(const scope_exit &) = delete;
  352. scope_exit &operator=(scope_exit &&) = delete;
  353. std::function<void(void)> exit_function;
  354. bool execute_on_destruction;
  355. };
  356. } // namespace detail
  357. enum SSLVerifierResponse {
  358. // no decision has been made, use the built-in certificate verifier
  359. NoDecisionMade,
  360. // connection certificate is verified and accepted
  361. CertificateAccepted,
  362. // connection certificate was processed but is rejected
  363. CertificateRejected
  364. };
  365. enum StatusCode {
  366. // Information responses
  367. Continue_100 = 100,
  368. SwitchingProtocol_101 = 101,
  369. Processing_102 = 102,
  370. EarlyHints_103 = 103,
  371. // Successful responses
  372. OK_200 = 200,
  373. Created_201 = 201,
  374. Accepted_202 = 202,
  375. NonAuthoritativeInformation_203 = 203,
  376. NoContent_204 = 204,
  377. ResetContent_205 = 205,
  378. PartialContent_206 = 206,
  379. MultiStatus_207 = 207,
  380. AlreadyReported_208 = 208,
  381. IMUsed_226 = 226,
  382. // Redirection messages
  383. MultipleChoices_300 = 300,
  384. MovedPermanently_301 = 301,
  385. Found_302 = 302,
  386. SeeOther_303 = 303,
  387. NotModified_304 = 304,
  388. UseProxy_305 = 305,
  389. unused_306 = 306,
  390. TemporaryRedirect_307 = 307,
  391. PermanentRedirect_308 = 308,
  392. // Client error responses
  393. BadRequest_400 = 400,
  394. Unauthorized_401 = 401,
  395. PaymentRequired_402 = 402,
  396. Forbidden_403 = 403,
  397. NotFound_404 = 404,
  398. MethodNotAllowed_405 = 405,
  399. NotAcceptable_406 = 406,
  400. ProxyAuthenticationRequired_407 = 407,
  401. RequestTimeout_408 = 408,
  402. Conflict_409 = 409,
  403. Gone_410 = 410,
  404. LengthRequired_411 = 411,
  405. PreconditionFailed_412 = 412,
  406. PayloadTooLarge_413 = 413,
  407. UriTooLong_414 = 414,
  408. UnsupportedMediaType_415 = 415,
  409. RangeNotSatisfiable_416 = 416,
  410. ExpectationFailed_417 = 417,
  411. ImATeapot_418 = 418,
  412. MisdirectedRequest_421 = 421,
  413. UnprocessableContent_422 = 422,
  414. Locked_423 = 423,
  415. FailedDependency_424 = 424,
  416. TooEarly_425 = 425,
  417. UpgradeRequired_426 = 426,
  418. PreconditionRequired_428 = 428,
  419. TooManyRequests_429 = 429,
  420. RequestHeaderFieldsTooLarge_431 = 431,
  421. UnavailableForLegalReasons_451 = 451,
  422. // Server error responses
  423. InternalServerError_500 = 500,
  424. NotImplemented_501 = 501,
  425. BadGateway_502 = 502,
  426. ServiceUnavailable_503 = 503,
  427. GatewayTimeout_504 = 504,
  428. HttpVersionNotSupported_505 = 505,
  429. VariantAlsoNegotiates_506 = 506,
  430. InsufficientStorage_507 = 507,
  431. LoopDetected_508 = 508,
  432. NotExtended_510 = 510,
  433. NetworkAuthenticationRequired_511 = 511,
  434. };
  435. using Headers =
  436. std::unordered_multimap<std::string, std::string, detail::case_ignore::hash,
  437. detail::case_ignore::equal_to>;
  438. using Params = std::multimap<std::string, std::string>;
  439. using Match = std::smatch;
  440. using Progress = std::function<bool(uint64_t current, uint64_t total)>;
  441. struct Response;
  442. using ResponseHandler = std::function<bool(const Response &response)>;
  443. struct MultipartFormData {
  444. std::string name;
  445. std::string content;
  446. std::string filename;
  447. std::string content_type;
  448. };
  449. using MultipartFormDataItems = std::vector<MultipartFormData>;
  450. using MultipartFormDataMap = std::multimap<std::string, MultipartFormData>;
  451. class DataSink {
  452. public:
  453. DataSink() : os(&sb_), sb_(*this) {}
  454. DataSink(const DataSink &) = delete;
  455. DataSink &operator=(const DataSink &) = delete;
  456. DataSink(DataSink &&) = delete;
  457. DataSink &operator=(DataSink &&) = delete;
  458. std::function<bool(const char *data, size_t data_len)> write;
  459. std::function<bool()> is_writable;
  460. std::function<void()> done;
  461. std::function<void(const Headers &trailer)> done_with_trailer;
  462. std::ostream os;
  463. private:
  464. class data_sink_streambuf final : public std::streambuf {
  465. public:
  466. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  467. protected:
  468. std::streamsize xsputn(const char *s, std::streamsize n) override {
  469. sink_.write(s, static_cast<size_t>(n));
  470. return n;
  471. }
  472. private:
  473. DataSink &sink_;
  474. };
  475. data_sink_streambuf sb_;
  476. };
  477. using ContentProvider =
  478. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  479. using ContentProviderWithoutLength =
  480. std::function<bool(size_t offset, DataSink &sink)>;
  481. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  482. struct MultipartFormDataProvider {
  483. std::string name;
  484. ContentProviderWithoutLength provider;
  485. std::string filename;
  486. std::string content_type;
  487. };
  488. using MultipartFormDataProviderItems = std::vector<MultipartFormDataProvider>;
  489. using ContentReceiverWithProgress =
  490. std::function<bool(const char *data, size_t data_length, uint64_t offset,
  491. uint64_t total_length)>;
  492. using ContentReceiver =
  493. std::function<bool(const char *data, size_t data_length)>;
  494. using MultipartContentHeader =
  495. std::function<bool(const MultipartFormData &file)>;
  496. class ContentReader {
  497. public:
  498. using Reader = std::function<bool(ContentReceiver receiver)>;
  499. using MultipartReader = std::function<bool(MultipartContentHeader header,
  500. ContentReceiver receiver)>;
  501. ContentReader(Reader reader, MultipartReader multipart_reader)
  502. : reader_(std::move(reader)),
  503. multipart_reader_(std::move(multipart_reader)) {}
  504. bool operator()(MultipartContentHeader header,
  505. ContentReceiver receiver) const {
  506. return multipart_reader_(std::move(header), std::move(receiver));
  507. }
  508. bool operator()(ContentReceiver receiver) const {
  509. return reader_(std::move(receiver));
  510. }
  511. Reader reader_;
  512. MultipartReader multipart_reader_;
  513. };
  514. using Range = std::pair<ssize_t, ssize_t>;
  515. using Ranges = std::vector<Range>;
  516. struct Request {
  517. std::string method;
  518. std::string path;
  519. Params params;
  520. Headers headers;
  521. std::string body;
  522. std::string remote_addr;
  523. int remote_port = -1;
  524. std::string local_addr;
  525. int local_port = -1;
  526. // for server
  527. std::string version;
  528. std::string target;
  529. MultipartFormDataMap files;
  530. Ranges ranges;
  531. Match matches;
  532. std::unordered_map<std::string, std::string> path_params;
  533. std::function<bool()> is_connection_closed = []() { return true; };
  534. // for client
  535. ResponseHandler response_handler;
  536. ContentReceiverWithProgress content_receiver;
  537. Progress progress;
  538. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  539. const SSL *ssl = nullptr;
  540. #endif
  541. bool has_header(const std::string &key) const;
  542. std::string get_header_value(const std::string &key, const char *def = "",
  543. size_t id = 0) const;
  544. uint64_t get_header_value_u64(const std::string &key, uint64_t def = 0,
  545. size_t id = 0) const;
  546. size_t get_header_value_count(const std::string &key) const;
  547. void set_header(const std::string &key, const std::string &val);
  548. bool has_param(const std::string &key) const;
  549. std::string get_param_value(const std::string &key, size_t id = 0) const;
  550. size_t get_param_value_count(const std::string &key) const;
  551. bool is_multipart_form_data() const;
  552. bool has_file(const std::string &key) const;
  553. MultipartFormData get_file_value(const std::string &key) const;
  554. std::vector<MultipartFormData> get_file_values(const std::string &key) const;
  555. // private members...
  556. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  557. size_t content_length_ = 0;
  558. ContentProvider content_provider_;
  559. bool is_chunked_content_provider_ = false;
  560. size_t authorization_count_ = 0;
  561. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  562. (std::chrono::steady_clock::time_point::min)();
  563. };
  564. struct Response {
  565. std::string version;
  566. int status = -1;
  567. std::string reason;
  568. Headers headers;
  569. std::string body;
  570. std::string location; // Redirect location
  571. bool has_header(const std::string &key) const;
  572. std::string get_header_value(const std::string &key, const char *def = "",
  573. size_t id = 0) const;
  574. uint64_t get_header_value_u64(const std::string &key, uint64_t def = 0,
  575. size_t id = 0) const;
  576. size_t get_header_value_count(const std::string &key) const;
  577. void set_header(const std::string &key, const std::string &val);
  578. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  579. void set_content(const char *s, size_t n, const std::string &content_type);
  580. void set_content(const std::string &s, const std::string &content_type);
  581. void set_content(std::string &&s, const std::string &content_type);
  582. void set_content_provider(
  583. size_t length, const std::string &content_type, ContentProvider provider,
  584. ContentProviderResourceReleaser resource_releaser = nullptr);
  585. void set_content_provider(
  586. const std::string &content_type, ContentProviderWithoutLength provider,
  587. ContentProviderResourceReleaser resource_releaser = nullptr);
  588. void set_chunked_content_provider(
  589. const std::string &content_type, ContentProviderWithoutLength provider,
  590. ContentProviderResourceReleaser resource_releaser = nullptr);
  591. void set_file_content(const std::string &path,
  592. const std::string &content_type);
  593. void set_file_content(const std::string &path);
  594. Response() = default;
  595. Response(const Response &) = default;
  596. Response &operator=(const Response &) = default;
  597. Response(Response &&) = default;
  598. Response &operator=(Response &&) = default;
  599. ~Response() {
  600. if (content_provider_resource_releaser_) {
  601. content_provider_resource_releaser_(content_provider_success_);
  602. }
  603. }
  604. // private members...
  605. size_t content_length_ = 0;
  606. ContentProvider content_provider_;
  607. ContentProviderResourceReleaser content_provider_resource_releaser_;
  608. bool is_chunked_content_provider_ = false;
  609. bool content_provider_success_ = false;
  610. std::string file_content_path_;
  611. std::string file_content_content_type_;
  612. };
  613. class Stream {
  614. public:
  615. virtual ~Stream() = default;
  616. virtual bool is_readable() const = 0;
  617. virtual bool wait_readable() const = 0;
  618. virtual bool wait_writable() const = 0;
  619. virtual ssize_t read(char *ptr, size_t size) = 0;
  620. virtual ssize_t write(const char *ptr, size_t size) = 0;
  621. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  622. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  623. virtual socket_t socket() const = 0;
  624. virtual time_t duration() const = 0;
  625. ssize_t write(const char *ptr);
  626. ssize_t write(const std::string &s);
  627. };
  628. class TaskQueue {
  629. public:
  630. TaskQueue() = default;
  631. virtual ~TaskQueue() = default;
  632. virtual bool enqueue(std::function<void()> fn) = 0;
  633. virtual void shutdown() = 0;
  634. virtual void on_idle() {}
  635. };
  636. class ThreadPool final : public TaskQueue {
  637. public:
  638. explicit ThreadPool(size_t n, size_t mqr = 0)
  639. : shutdown_(false), max_queued_requests_(mqr) {
  640. while (n) {
  641. threads_.emplace_back(worker(*this));
  642. n--;
  643. }
  644. }
  645. ThreadPool(const ThreadPool &) = delete;
  646. ~ThreadPool() override = default;
  647. bool enqueue(std::function<void()> fn) override {
  648. {
  649. std::unique_lock<std::mutex> lock(mutex_);
  650. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  651. return false;
  652. }
  653. jobs_.push_back(std::move(fn));
  654. }
  655. cond_.notify_one();
  656. return true;
  657. }
  658. void shutdown() override {
  659. // Stop all worker threads...
  660. {
  661. std::unique_lock<std::mutex> lock(mutex_);
  662. shutdown_ = true;
  663. }
  664. cond_.notify_all();
  665. // Join...
  666. for (auto &t : threads_) {
  667. t.join();
  668. }
  669. }
  670. private:
  671. struct worker {
  672. explicit worker(ThreadPool &pool) : pool_(pool) {}
  673. void operator()() {
  674. for (;;) {
  675. std::function<void()> fn;
  676. {
  677. std::unique_lock<std::mutex> lock(pool_.mutex_);
  678. pool_.cond_.wait(
  679. lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; });
  680. if (pool_.shutdown_ && pool_.jobs_.empty()) { break; }
  681. fn = pool_.jobs_.front();
  682. pool_.jobs_.pop_front();
  683. }
  684. assert(true == static_cast<bool>(fn));
  685. fn();
  686. }
  687. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  688. !defined(LIBRESSL_VERSION_NUMBER)
  689. OPENSSL_thread_stop();
  690. #endif
  691. }
  692. ThreadPool &pool_;
  693. };
  694. friend struct worker;
  695. std::vector<std::thread> threads_;
  696. std::list<std::function<void()>> jobs_;
  697. bool shutdown_;
  698. size_t max_queued_requests_ = 0;
  699. std::condition_variable cond_;
  700. std::mutex mutex_;
  701. };
  702. using Logger = std::function<void(const Request &, const Response &)>;
  703. using SocketOptions = std::function<void(socket_t sock)>;
  704. namespace detail {
  705. bool set_socket_opt_impl(socket_t sock, int level, int optname,
  706. const void *optval, socklen_t optlen);
  707. bool set_socket_opt(socket_t sock, int level, int optname, int opt);
  708. bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec,
  709. time_t usec);
  710. } // namespace detail
  711. void default_socket_options(socket_t sock);
  712. const char *status_message(int status);
  713. std::string get_bearer_token_auth(const Request &req);
  714. namespace detail {
  715. class MatcherBase {
  716. public:
  717. virtual ~MatcherBase() = default;
  718. // Match request path and populate its matches and
  719. virtual bool match(Request &request) const = 0;
  720. };
  721. /**
  722. * Captures parameters in request path and stores them in Request::path_params
  723. *
  724. * Capture name is a substring of a pattern from : to /.
  725. * The rest of the pattern is matched against the request path directly
  726. * Parameters are captured starting from the next character after
  727. * the end of the last matched static pattern fragment until the next /.
  728. *
  729. * Example pattern:
  730. * "/path/fragments/:capture/more/fragments/:second_capture"
  731. * Static fragments:
  732. * "/path/fragments/", "more/fragments/"
  733. *
  734. * Given the following request path:
  735. * "/path/fragments/:1/more/fragments/:2"
  736. * the resulting capture will be
  737. * {{"capture", "1"}, {"second_capture", "2"}}
  738. */
  739. class PathParamsMatcher final : public MatcherBase {
  740. public:
  741. PathParamsMatcher(const std::string &pattern);
  742. bool match(Request &request) const override;
  743. private:
  744. // Treat segment separators as the end of path parameter capture
  745. // Does not need to handle query parameters as they are parsed before path
  746. // matching
  747. static constexpr char separator = '/';
  748. // Contains static path fragments to match against, excluding the '/' after
  749. // path params
  750. // Fragments are separated by path params
  751. std::vector<std::string> static_fragments_;
  752. // Stores the names of the path parameters to be used as keys in the
  753. // Request::path_params map
  754. std::vector<std::string> param_names_;
  755. };
  756. /**
  757. * Performs std::regex_match on request path
  758. * and stores the result in Request::matches
  759. *
  760. * Note that regex match is performed directly on the whole request.
  761. * This means that wildcard patterns may match multiple path segments with /:
  762. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  763. */
  764. class RegexMatcher final : public MatcherBase {
  765. public:
  766. RegexMatcher(const std::string &pattern) : regex_(pattern) {}
  767. bool match(Request &request) const override;
  768. private:
  769. std::regex regex_;
  770. };
  771. ssize_t write_headers(Stream &strm, const Headers &headers);
  772. } // namespace detail
  773. class Server {
  774. public:
  775. using Handler = std::function<void(const Request &, Response &)>;
  776. using ExceptionHandler =
  777. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  778. enum class HandlerResponse {
  779. Handled,
  780. Unhandled,
  781. };
  782. using HandlerWithResponse =
  783. std::function<HandlerResponse(const Request &, Response &)>;
  784. using HandlerWithContentReader = std::function<void(
  785. const Request &, Response &, const ContentReader &content_reader)>;
  786. using Expect100ContinueHandler =
  787. std::function<int(const Request &, Response &)>;
  788. Server();
  789. virtual ~Server();
  790. virtual bool is_valid() const;
  791. Server &Get(const std::string &pattern, Handler handler);
  792. Server &Post(const std::string &pattern, Handler handler);
  793. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  794. Server &Put(const std::string &pattern, Handler handler);
  795. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  796. Server &Patch(const std::string &pattern, Handler handler);
  797. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  798. Server &Delete(const std::string &pattern, Handler handler);
  799. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  800. Server &Options(const std::string &pattern, Handler handler);
  801. bool set_base_dir(const std::string &dir,
  802. const std::string &mount_point = std::string());
  803. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  804. Headers headers = Headers());
  805. bool remove_mount_point(const std::string &mount_point);
  806. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  807. const std::string &mime);
  808. Server &set_default_file_mimetype(const std::string &mime);
  809. Server &set_file_request_handler(Handler handler);
  810. template <class ErrorHandlerFunc>
  811. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  812. return set_error_handler_core(
  813. std::forward<ErrorHandlerFunc>(handler),
  814. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  815. }
  816. Server &set_exception_handler(ExceptionHandler handler);
  817. Server &set_pre_routing_handler(HandlerWithResponse handler);
  818. Server &set_post_routing_handler(Handler handler);
  819. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  820. Server &set_logger(Logger logger);
  821. Server &set_address_family(int family);
  822. Server &set_tcp_nodelay(bool on);
  823. Server &set_ipv6_v6only(bool on);
  824. Server &set_socket_options(SocketOptions socket_options);
  825. Server &set_default_headers(Headers headers);
  826. Server &
  827. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  828. Server &set_keep_alive_max_count(size_t count);
  829. Server &set_keep_alive_timeout(time_t sec);
  830. Server &set_read_timeout(time_t sec, time_t usec = 0);
  831. template <class Rep, class Period>
  832. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  833. Server &set_write_timeout(time_t sec, time_t usec = 0);
  834. template <class Rep, class Period>
  835. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  836. Server &set_idle_interval(time_t sec, time_t usec = 0);
  837. template <class Rep, class Period>
  838. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  839. Server &set_payload_max_length(size_t length);
  840. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  841. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  842. bool listen_after_bind();
  843. bool listen(const std::string &host, int port, int socket_flags = 0);
  844. bool is_running() const;
  845. void wait_until_ready() const;
  846. void stop();
  847. void decommission();
  848. std::function<TaskQueue *(void)> new_task_queue;
  849. protected:
  850. bool process_request(Stream &strm, const std::string &remote_addr,
  851. int remote_port, const std::string &local_addr,
  852. int local_port, bool close_connection,
  853. bool &connection_closed,
  854. const std::function<void(Request &)> &setup_request);
  855. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  856. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  857. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  858. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  859. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  860. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  861. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  862. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  863. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  864. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  865. private:
  866. using Handlers =
  867. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  868. using HandlersForContentReader =
  869. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  870. HandlerWithContentReader>>;
  871. static std::unique_ptr<detail::MatcherBase>
  872. make_matcher(const std::string &pattern);
  873. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  874. Server &set_error_handler_core(Handler handler, std::false_type);
  875. socket_t create_server_socket(const std::string &host, int port,
  876. int socket_flags,
  877. SocketOptions socket_options) const;
  878. int bind_internal(const std::string &host, int port, int socket_flags);
  879. bool listen_internal();
  880. bool routing(Request &req, Response &res, Stream &strm);
  881. bool handle_file_request(const Request &req, Response &res,
  882. bool head = false);
  883. bool dispatch_request(Request &req, Response &res,
  884. const Handlers &handlers) const;
  885. bool dispatch_request_for_content_reader(
  886. Request &req, Response &res, ContentReader content_reader,
  887. const HandlersForContentReader &handlers) const;
  888. bool parse_request_line(const char *s, Request &req) const;
  889. void apply_ranges(const Request &req, Response &res,
  890. std::string &content_type, std::string &boundary) const;
  891. bool write_response(Stream &strm, bool close_connection, Request &req,
  892. Response &res);
  893. bool write_response_with_content(Stream &strm, bool close_connection,
  894. const Request &req, Response &res);
  895. bool write_response_core(Stream &strm, bool close_connection,
  896. const Request &req, Response &res,
  897. bool need_apply_ranges);
  898. bool write_content_with_provider(Stream &strm, const Request &req,
  899. Response &res, const std::string &boundary,
  900. const std::string &content_type);
  901. bool read_content(Stream &strm, Request &req, Response &res);
  902. bool
  903. read_content_with_content_receiver(Stream &strm, Request &req, Response &res,
  904. ContentReceiver receiver,
  905. MultipartContentHeader multipart_header,
  906. ContentReceiver multipart_receiver);
  907. bool read_content_core(Stream &strm, Request &req, Response &res,
  908. ContentReceiver receiver,
  909. MultipartContentHeader multipart_header,
  910. ContentReceiver multipart_receiver) const;
  911. virtual bool process_and_close_socket(socket_t sock);
  912. std::atomic<bool> is_running_{false};
  913. std::atomic<bool> is_decommissioned{false};
  914. struct MountPointEntry {
  915. std::string mount_point;
  916. std::string base_dir;
  917. Headers headers;
  918. };
  919. std::vector<MountPointEntry> base_dirs_;
  920. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  921. std::string default_file_mimetype_ = "application/octet-stream";
  922. Handler file_request_handler_;
  923. Handlers get_handlers_;
  924. Handlers post_handlers_;
  925. HandlersForContentReader post_handlers_for_content_reader_;
  926. Handlers put_handlers_;
  927. HandlersForContentReader put_handlers_for_content_reader_;
  928. Handlers patch_handlers_;
  929. HandlersForContentReader patch_handlers_for_content_reader_;
  930. Handlers delete_handlers_;
  931. HandlersForContentReader delete_handlers_for_content_reader_;
  932. Handlers options_handlers_;
  933. HandlerWithResponse error_handler_;
  934. ExceptionHandler exception_handler_;
  935. HandlerWithResponse pre_routing_handler_;
  936. Handler post_routing_handler_;
  937. Expect100ContinueHandler expect_100_continue_handler_;
  938. Logger logger_;
  939. int address_family_ = AF_UNSPEC;
  940. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  941. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  942. SocketOptions socket_options_ = default_socket_options;
  943. Headers default_headers_;
  944. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  945. detail::write_headers;
  946. };
  947. enum class Error {
  948. Success = 0,
  949. Unknown,
  950. Connection,
  951. BindIPAddress,
  952. Read,
  953. Write,
  954. ExceedRedirectCount,
  955. Canceled,
  956. SSLConnection,
  957. SSLLoadingCerts,
  958. SSLServerVerification,
  959. SSLServerHostnameVerification,
  960. UnsupportedMultipartBoundaryChars,
  961. Compression,
  962. ConnectionTimeout,
  963. ProxyConnection,
  964. // For internal use only
  965. SSLPeerCouldBeClosed_,
  966. };
  967. std::string to_string(Error error);
  968. std::ostream &operator<<(std::ostream &os, const Error &obj);
  969. class Result {
  970. public:
  971. Result() = default;
  972. Result(std::unique_ptr<Response> &&res, Error err,
  973. Headers &&request_headers = Headers{})
  974. : res_(std::move(res)), err_(err),
  975. request_headers_(std::move(request_headers)) {}
  976. // Response
  977. operator bool() const { return res_ != nullptr; }
  978. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  979. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  980. const Response &value() const { return *res_; }
  981. Response &value() { return *res_; }
  982. const Response &operator*() const { return *res_; }
  983. Response &operator*() { return *res_; }
  984. const Response *operator->() const { return res_.get(); }
  985. Response *operator->() { return res_.get(); }
  986. // Error
  987. Error error() const { return err_; }
  988. // Request Headers
  989. bool has_request_header(const std::string &key) const;
  990. std::string get_request_header_value(const std::string &key,
  991. const char *def = "",
  992. size_t id = 0) const;
  993. uint64_t get_request_header_value_u64(const std::string &key,
  994. uint64_t def = 0, size_t id = 0) const;
  995. size_t get_request_header_value_count(const std::string &key) const;
  996. private:
  997. std::unique_ptr<Response> res_;
  998. Error err_ = Error::Unknown;
  999. Headers request_headers_;
  1000. };
  1001. class ClientImpl {
  1002. public:
  1003. explicit ClientImpl(const std::string &host);
  1004. explicit ClientImpl(const std::string &host, int port);
  1005. explicit ClientImpl(const std::string &host, int port,
  1006. const std::string &client_cert_path,
  1007. const std::string &client_key_path);
  1008. virtual ~ClientImpl();
  1009. virtual bool is_valid() const;
  1010. Result Get(const std::string &path);
  1011. Result Get(const std::string &path, const Headers &headers);
  1012. Result Get(const std::string &path, Progress progress);
  1013. Result Get(const std::string &path, const Headers &headers,
  1014. Progress progress);
  1015. Result Get(const std::string &path, ContentReceiver content_receiver);
  1016. Result Get(const std::string &path, const Headers &headers,
  1017. ContentReceiver content_receiver);
  1018. Result Get(const std::string &path, ContentReceiver content_receiver,
  1019. Progress progress);
  1020. Result Get(const std::string &path, const Headers &headers,
  1021. ContentReceiver content_receiver, Progress progress);
  1022. Result Get(const std::string &path, ResponseHandler response_handler,
  1023. ContentReceiver content_receiver);
  1024. Result Get(const std::string &path, const Headers &headers,
  1025. ResponseHandler response_handler,
  1026. ContentReceiver content_receiver);
  1027. Result Get(const std::string &path, ResponseHandler response_handler,
  1028. ContentReceiver content_receiver, Progress progress);
  1029. Result Get(const std::string &path, const Headers &headers,
  1030. ResponseHandler response_handler, ContentReceiver content_receiver,
  1031. Progress progress);
  1032. Result Get(const std::string &path, const Params &params,
  1033. const Headers &headers, Progress progress = nullptr);
  1034. Result Get(const std::string &path, const Params &params,
  1035. const Headers &headers, ContentReceiver content_receiver,
  1036. Progress progress = nullptr);
  1037. Result Get(const std::string &path, const Params &params,
  1038. const Headers &headers, ResponseHandler response_handler,
  1039. ContentReceiver content_receiver, Progress progress = nullptr);
  1040. Result Head(const std::string &path);
  1041. Result Head(const std::string &path, const Headers &headers);
  1042. Result Post(const std::string &path);
  1043. Result Post(const std::string &path, const Headers &headers);
  1044. Result Post(const std::string &path, const char *body, size_t content_length,
  1045. const std::string &content_type);
  1046. Result Post(const std::string &path, const Headers &headers, const char *body,
  1047. size_t content_length, const std::string &content_type);
  1048. Result Post(const std::string &path, const Headers &headers, const char *body,
  1049. size_t content_length, const std::string &content_type,
  1050. Progress progress);
  1051. Result Post(const std::string &path, const std::string &body,
  1052. const std::string &content_type);
  1053. Result Post(const std::string &path, const std::string &body,
  1054. const std::string &content_type, Progress progress);
  1055. Result Post(const std::string &path, const Headers &headers,
  1056. const std::string &body, const std::string &content_type);
  1057. Result Post(const std::string &path, const Headers &headers,
  1058. const std::string &body, const std::string &content_type,
  1059. Progress progress);
  1060. Result Post(const std::string &path, size_t content_length,
  1061. ContentProvider content_provider,
  1062. const std::string &content_type);
  1063. Result Post(const std::string &path,
  1064. ContentProviderWithoutLength content_provider,
  1065. const std::string &content_type);
  1066. Result Post(const std::string &path, const Headers &headers,
  1067. size_t content_length, ContentProvider content_provider,
  1068. const std::string &content_type);
  1069. Result Post(const std::string &path, const Headers &headers,
  1070. ContentProviderWithoutLength content_provider,
  1071. const std::string &content_type);
  1072. Result Post(const std::string &path, const Params &params);
  1073. Result Post(const std::string &path, const Headers &headers,
  1074. const Params &params);
  1075. Result Post(const std::string &path, const Headers &headers,
  1076. const Params &params, Progress progress);
  1077. Result Post(const std::string &path, const MultipartFormDataItems &items);
  1078. Result Post(const std::string &path, const Headers &headers,
  1079. const MultipartFormDataItems &items);
  1080. Result Post(const std::string &path, const Headers &headers,
  1081. const MultipartFormDataItems &items, const std::string &boundary);
  1082. Result Post(const std::string &path, const Headers &headers,
  1083. const MultipartFormDataItems &items,
  1084. const MultipartFormDataProviderItems &provider_items);
  1085. Result Put(const std::string &path);
  1086. Result Put(const std::string &path, const char *body, size_t content_length,
  1087. const std::string &content_type);
  1088. Result Put(const std::string &path, const Headers &headers, const char *body,
  1089. size_t content_length, const std::string &content_type);
  1090. Result Put(const std::string &path, const Headers &headers, const char *body,
  1091. size_t content_length, const std::string &content_type,
  1092. Progress progress);
  1093. Result Put(const std::string &path, const std::string &body,
  1094. const std::string &content_type);
  1095. Result Put(const std::string &path, const std::string &body,
  1096. const std::string &content_type, Progress progress);
  1097. Result Put(const std::string &path, const Headers &headers,
  1098. const std::string &body, const std::string &content_type);
  1099. Result Put(const std::string &path, const Headers &headers,
  1100. const std::string &body, const std::string &content_type,
  1101. Progress progress);
  1102. Result Put(const std::string &path, size_t content_length,
  1103. ContentProvider content_provider, const std::string &content_type);
  1104. Result Put(const std::string &path,
  1105. ContentProviderWithoutLength content_provider,
  1106. const std::string &content_type);
  1107. Result Put(const std::string &path, const Headers &headers,
  1108. size_t content_length, ContentProvider content_provider,
  1109. const std::string &content_type);
  1110. Result Put(const std::string &path, const Headers &headers,
  1111. ContentProviderWithoutLength content_provider,
  1112. const std::string &content_type);
  1113. Result Put(const std::string &path, const Params &params);
  1114. Result Put(const std::string &path, const Headers &headers,
  1115. const Params &params);
  1116. Result Put(const std::string &path, const Headers &headers,
  1117. const Params &params, Progress progress);
  1118. Result Put(const std::string &path, const MultipartFormDataItems &items);
  1119. Result Put(const std::string &path, const Headers &headers,
  1120. const MultipartFormDataItems &items);
  1121. Result Put(const std::string &path, const Headers &headers,
  1122. const MultipartFormDataItems &items, const std::string &boundary);
  1123. Result Put(const std::string &path, const Headers &headers,
  1124. const MultipartFormDataItems &items,
  1125. const MultipartFormDataProviderItems &provider_items);
  1126. Result Patch(const std::string &path);
  1127. Result Patch(const std::string &path, const char *body, size_t content_length,
  1128. const std::string &content_type);
  1129. Result Patch(const std::string &path, const char *body, size_t content_length,
  1130. const std::string &content_type, Progress progress);
  1131. Result Patch(const std::string &path, const Headers &headers,
  1132. const char *body, size_t content_length,
  1133. const std::string &content_type);
  1134. Result Patch(const std::string &path, const Headers &headers,
  1135. const char *body, size_t content_length,
  1136. const std::string &content_type, Progress progress);
  1137. Result Patch(const std::string &path, const std::string &body,
  1138. const std::string &content_type);
  1139. Result Patch(const std::string &path, const std::string &body,
  1140. const std::string &content_type, Progress progress);
  1141. Result Patch(const std::string &path, const Headers &headers,
  1142. const std::string &body, const std::string &content_type);
  1143. Result Patch(const std::string &path, const Headers &headers,
  1144. const std::string &body, const std::string &content_type,
  1145. Progress progress);
  1146. Result Patch(const std::string &path, size_t content_length,
  1147. ContentProvider content_provider,
  1148. const std::string &content_type);
  1149. Result Patch(const std::string &path,
  1150. ContentProviderWithoutLength content_provider,
  1151. const std::string &content_type);
  1152. Result Patch(const std::string &path, const Headers &headers,
  1153. size_t content_length, ContentProvider content_provider,
  1154. const std::string &content_type);
  1155. Result Patch(const std::string &path, const Headers &headers,
  1156. ContentProviderWithoutLength content_provider,
  1157. const std::string &content_type);
  1158. Result Delete(const std::string &path);
  1159. Result Delete(const std::string &path, const Headers &headers);
  1160. Result Delete(const std::string &path, const char *body,
  1161. size_t content_length, const std::string &content_type);
  1162. Result Delete(const std::string &path, const char *body,
  1163. size_t content_length, const std::string &content_type,
  1164. Progress progress);
  1165. Result Delete(const std::string &path, const Headers &headers,
  1166. const char *body, size_t content_length,
  1167. const std::string &content_type);
  1168. Result Delete(const std::string &path, const Headers &headers,
  1169. const char *body, size_t content_length,
  1170. const std::string &content_type, Progress progress);
  1171. Result Delete(const std::string &path, const std::string &body,
  1172. const std::string &content_type);
  1173. Result Delete(const std::string &path, const std::string &body,
  1174. const std::string &content_type, Progress progress);
  1175. Result Delete(const std::string &path, const Headers &headers,
  1176. const std::string &body, const std::string &content_type);
  1177. Result Delete(const std::string &path, const Headers &headers,
  1178. const std::string &body, const std::string &content_type,
  1179. Progress progress);
  1180. Result Options(const std::string &path);
  1181. Result Options(const std::string &path, const Headers &headers);
  1182. bool send(Request &req, Response &res, Error &error);
  1183. Result send(const Request &req);
  1184. void stop();
  1185. std::string host() const;
  1186. int port() const;
  1187. size_t is_socket_open() const;
  1188. socket_t socket() const;
  1189. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1190. void set_default_headers(Headers headers);
  1191. void
  1192. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1193. void set_address_family(int family);
  1194. void set_tcp_nodelay(bool on);
  1195. void set_ipv6_v6only(bool on);
  1196. void set_socket_options(SocketOptions socket_options);
  1197. void set_connection_timeout(time_t sec, time_t usec = 0);
  1198. template <class Rep, class Period>
  1199. void
  1200. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1201. void set_read_timeout(time_t sec, time_t usec = 0);
  1202. template <class Rep, class Period>
  1203. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1204. void set_write_timeout(time_t sec, time_t usec = 0);
  1205. template <class Rep, class Period>
  1206. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1207. void set_max_timeout(time_t msec);
  1208. template <class Rep, class Period>
  1209. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1210. void set_basic_auth(const std::string &username, const std::string &password);
  1211. void set_bearer_token_auth(const std::string &token);
  1212. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1213. void set_digest_auth(const std::string &username,
  1214. const std::string &password);
  1215. #endif
  1216. void set_keep_alive(bool on);
  1217. void set_follow_location(bool on);
  1218. void set_url_encode(bool on);
  1219. void set_compress(bool on);
  1220. void set_decompress(bool on);
  1221. void set_interface(const std::string &intf);
  1222. void set_proxy(const std::string &host, int port);
  1223. void set_proxy_basic_auth(const std::string &username,
  1224. const std::string &password);
  1225. void set_proxy_bearer_token_auth(const std::string &token);
  1226. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1227. void set_proxy_digest_auth(const std::string &username,
  1228. const std::string &password);
  1229. #endif
  1230. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1231. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1232. const std::string &ca_cert_dir_path = std::string());
  1233. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1234. X509_STORE *create_ca_cert_store(const char *ca_cert, std::size_t size) const;
  1235. #endif
  1236. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1237. void enable_server_certificate_verification(bool enabled);
  1238. void enable_server_hostname_verification(bool enabled);
  1239. void set_server_certificate_verifier(
  1240. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1241. #endif
  1242. void set_logger(Logger logger);
  1243. protected:
  1244. struct Socket {
  1245. socket_t sock = INVALID_SOCKET;
  1246. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1247. SSL *ssl = nullptr;
  1248. #endif
  1249. bool is_open() const { return sock != INVALID_SOCKET; }
  1250. };
  1251. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  1252. // All of:
  1253. // shutdown_ssl
  1254. // shutdown_socket
  1255. // close_socket
  1256. // should ONLY be called when socket_mutex_ is locked.
  1257. // Also, shutdown_ssl and close_socket should also NOT be called concurrently
  1258. // with a DIFFERENT thread sending requests using that socket.
  1259. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  1260. void shutdown_socket(Socket &socket) const;
  1261. void close_socket(Socket &socket);
  1262. bool process_request(Stream &strm, Request &req, Response &res,
  1263. bool close_connection, Error &error);
  1264. bool write_content_with_provider(Stream &strm, const Request &req,
  1265. Error &error) const;
  1266. void copy_settings(const ClientImpl &rhs);
  1267. // Socket endpoint information
  1268. const std::string host_;
  1269. const int port_;
  1270. const std::string host_and_port_;
  1271. // Current open socket
  1272. Socket socket_;
  1273. mutable std::mutex socket_mutex_;
  1274. std::recursive_mutex request_mutex_;
  1275. // These are all protected under socket_mutex
  1276. size_t socket_requests_in_flight_ = 0;
  1277. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  1278. bool socket_should_be_closed_when_request_is_done_ = false;
  1279. // Hostname-IP map
  1280. std::map<std::string, std::string> addr_map_;
  1281. // Default headers
  1282. Headers default_headers_;
  1283. // Header writer
  1284. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1285. detail::write_headers;
  1286. // Settings
  1287. std::string client_cert_path_;
  1288. std::string client_key_path_;
  1289. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  1290. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  1291. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  1292. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  1293. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  1294. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  1295. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  1296. std::string basic_auth_username_;
  1297. std::string basic_auth_password_;
  1298. std::string bearer_token_auth_token_;
  1299. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1300. std::string digest_auth_username_;
  1301. std::string digest_auth_password_;
  1302. #endif
  1303. bool keep_alive_ = false;
  1304. bool follow_location_ = false;
  1305. bool url_encode_ = true;
  1306. int address_family_ = AF_UNSPEC;
  1307. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1308. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1309. SocketOptions socket_options_ = nullptr;
  1310. bool compress_ = false;
  1311. bool decompress_ = true;
  1312. std::string interface_;
  1313. std::string proxy_host_;
  1314. int proxy_port_ = -1;
  1315. std::string proxy_basic_auth_username_;
  1316. std::string proxy_basic_auth_password_;
  1317. std::string proxy_bearer_token_auth_token_;
  1318. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1319. std::string proxy_digest_auth_username_;
  1320. std::string proxy_digest_auth_password_;
  1321. #endif
  1322. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1323. std::string ca_cert_file_path_;
  1324. std::string ca_cert_dir_path_;
  1325. X509_STORE *ca_cert_store_ = nullptr;
  1326. #endif
  1327. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1328. bool server_certificate_verification_ = true;
  1329. bool server_hostname_verification_ = true;
  1330. std::function<SSLVerifierResponse(SSL *ssl)> server_certificate_verifier_;
  1331. #endif
  1332. Logger logger_;
  1333. private:
  1334. bool send_(Request &req, Response &res, Error &error);
  1335. Result send_(Request &&req);
  1336. socket_t create_client_socket(Error &error) const;
  1337. bool read_response_line(Stream &strm, const Request &req,
  1338. Response &res) const;
  1339. bool write_request(Stream &strm, Request &req, bool close_connection,
  1340. Error &error);
  1341. bool redirect(Request &req, Response &res, Error &error);
  1342. bool handle_request(Stream &strm, Request &req, Response &res,
  1343. bool close_connection, Error &error);
  1344. std::unique_ptr<Response> send_with_content_provider(
  1345. Request &req, const char *body, size_t content_length,
  1346. ContentProvider content_provider,
  1347. ContentProviderWithoutLength content_provider_without_length,
  1348. const std::string &content_type, Error &error);
  1349. Result send_with_content_provider(
  1350. const std::string &method, const std::string &path,
  1351. const Headers &headers, const char *body, size_t content_length,
  1352. ContentProvider content_provider,
  1353. ContentProviderWithoutLength content_provider_without_length,
  1354. const std::string &content_type, Progress progress);
  1355. ContentProviderWithoutLength get_multipart_content_provider(
  1356. const std::string &boundary, const MultipartFormDataItems &items,
  1357. const MultipartFormDataProviderItems &provider_items) const;
  1358. std::string adjust_host_string(const std::string &host) const;
  1359. virtual bool
  1360. process_socket(const Socket &socket,
  1361. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1362. std::function<bool(Stream &strm)> callback);
  1363. virtual bool is_ssl() const;
  1364. };
  1365. class Client {
  1366. public:
  1367. // Universal interface
  1368. explicit Client(const std::string &scheme_host_port);
  1369. explicit Client(const std::string &scheme_host_port,
  1370. const std::string &client_cert_path,
  1371. const std::string &client_key_path);
  1372. // HTTP only interface
  1373. explicit Client(const std::string &host, int port);
  1374. explicit Client(const std::string &host, int port,
  1375. const std::string &client_cert_path,
  1376. const std::string &client_key_path);
  1377. Client(Client &&) = default;
  1378. Client &operator=(Client &&) = default;
  1379. ~Client();
  1380. bool is_valid() const;
  1381. Result Get(const std::string &path);
  1382. Result Get(const std::string &path, const Headers &headers);
  1383. Result Get(const std::string &path, Progress progress);
  1384. Result Get(const std::string &path, const Headers &headers,
  1385. Progress progress);
  1386. Result Get(const std::string &path, ContentReceiver content_receiver);
  1387. Result Get(const std::string &path, const Headers &headers,
  1388. ContentReceiver content_receiver);
  1389. Result Get(const std::string &path, ContentReceiver content_receiver,
  1390. Progress progress);
  1391. Result Get(const std::string &path, const Headers &headers,
  1392. ContentReceiver content_receiver, Progress progress);
  1393. Result Get(const std::string &path, ResponseHandler response_handler,
  1394. ContentReceiver content_receiver);
  1395. Result Get(const std::string &path, const Headers &headers,
  1396. ResponseHandler response_handler,
  1397. ContentReceiver content_receiver);
  1398. Result Get(const std::string &path, const Headers &headers,
  1399. ResponseHandler response_handler, ContentReceiver content_receiver,
  1400. Progress progress);
  1401. Result Get(const std::string &path, ResponseHandler response_handler,
  1402. ContentReceiver content_receiver, Progress progress);
  1403. Result Get(const std::string &path, const Params &params,
  1404. const Headers &headers, Progress progress = nullptr);
  1405. Result Get(const std::string &path, const Params &params,
  1406. const Headers &headers, ContentReceiver content_receiver,
  1407. Progress progress = nullptr);
  1408. Result Get(const std::string &path, const Params &params,
  1409. const Headers &headers, ResponseHandler response_handler,
  1410. ContentReceiver content_receiver, Progress progress = nullptr);
  1411. Result Head(const std::string &path);
  1412. Result Head(const std::string &path, const Headers &headers);
  1413. Result Post(const std::string &path);
  1414. Result Post(const std::string &path, const Headers &headers);
  1415. Result Post(const std::string &path, const char *body, size_t content_length,
  1416. const std::string &content_type);
  1417. Result Post(const std::string &path, const Headers &headers, const char *body,
  1418. size_t content_length, const std::string &content_type);
  1419. Result Post(const std::string &path, const Headers &headers, const char *body,
  1420. size_t content_length, const std::string &content_type,
  1421. Progress progress);
  1422. Result Post(const std::string &path, const std::string &body,
  1423. const std::string &content_type);
  1424. Result Post(const std::string &path, const std::string &body,
  1425. const std::string &content_type, Progress progress);
  1426. Result Post(const std::string &path, const Headers &headers,
  1427. const std::string &body, const std::string &content_type);
  1428. Result Post(const std::string &path, const Headers &headers,
  1429. const std::string &body, const std::string &content_type,
  1430. Progress progress);
  1431. Result Post(const std::string &path, size_t content_length,
  1432. ContentProvider content_provider,
  1433. const std::string &content_type);
  1434. Result Post(const std::string &path,
  1435. ContentProviderWithoutLength content_provider,
  1436. const std::string &content_type);
  1437. Result Post(const std::string &path, const Headers &headers,
  1438. size_t content_length, ContentProvider content_provider,
  1439. const std::string &content_type);
  1440. Result Post(const std::string &path, const Headers &headers,
  1441. ContentProviderWithoutLength content_provider,
  1442. const std::string &content_type);
  1443. Result Post(const std::string &path, const Params &params);
  1444. Result Post(const std::string &path, const Headers &headers,
  1445. const Params &params);
  1446. Result Post(const std::string &path, const Headers &headers,
  1447. const Params &params, Progress progress);
  1448. Result Post(const std::string &path, const MultipartFormDataItems &items);
  1449. Result Post(const std::string &path, const Headers &headers,
  1450. const MultipartFormDataItems &items);
  1451. Result Post(const std::string &path, const Headers &headers,
  1452. const MultipartFormDataItems &items, const std::string &boundary);
  1453. Result Post(const std::string &path, const Headers &headers,
  1454. const MultipartFormDataItems &items,
  1455. const MultipartFormDataProviderItems &provider_items);
  1456. Result Put(const std::string &path);
  1457. Result Put(const std::string &path, const char *body, size_t content_length,
  1458. const std::string &content_type);
  1459. Result Put(const std::string &path, const Headers &headers, const char *body,
  1460. size_t content_length, const std::string &content_type);
  1461. Result Put(const std::string &path, const Headers &headers, const char *body,
  1462. size_t content_length, const std::string &content_type,
  1463. Progress progress);
  1464. Result Put(const std::string &path, const std::string &body,
  1465. const std::string &content_type);
  1466. Result Put(const std::string &path, const std::string &body,
  1467. const std::string &content_type, Progress progress);
  1468. Result Put(const std::string &path, const Headers &headers,
  1469. const std::string &body, const std::string &content_type);
  1470. Result Put(const std::string &path, const Headers &headers,
  1471. const std::string &body, const std::string &content_type,
  1472. Progress progress);
  1473. Result Put(const std::string &path, size_t content_length,
  1474. ContentProvider content_provider, const std::string &content_type);
  1475. Result Put(const std::string &path,
  1476. ContentProviderWithoutLength content_provider,
  1477. const std::string &content_type);
  1478. Result Put(const std::string &path, const Headers &headers,
  1479. size_t content_length, ContentProvider content_provider,
  1480. const std::string &content_type);
  1481. Result Put(const std::string &path, const Headers &headers,
  1482. ContentProviderWithoutLength content_provider,
  1483. const std::string &content_type);
  1484. Result Put(const std::string &path, const Params &params);
  1485. Result Put(const std::string &path, const Headers &headers,
  1486. const Params &params);
  1487. Result Put(const std::string &path, const Headers &headers,
  1488. const Params &params, Progress progress);
  1489. Result Put(const std::string &path, const MultipartFormDataItems &items);
  1490. Result Put(const std::string &path, const Headers &headers,
  1491. const MultipartFormDataItems &items);
  1492. Result Put(const std::string &path, const Headers &headers,
  1493. const MultipartFormDataItems &items, const std::string &boundary);
  1494. Result Put(const std::string &path, const Headers &headers,
  1495. const MultipartFormDataItems &items,
  1496. const MultipartFormDataProviderItems &provider_items);
  1497. Result Patch(const std::string &path);
  1498. Result Patch(const std::string &path, const char *body, size_t content_length,
  1499. const std::string &content_type);
  1500. Result Patch(const std::string &path, const char *body, size_t content_length,
  1501. const std::string &content_type, Progress progress);
  1502. Result Patch(const std::string &path, const Headers &headers,
  1503. const char *body, size_t content_length,
  1504. const std::string &content_type);
  1505. Result Patch(const std::string &path, const Headers &headers,
  1506. const char *body, size_t content_length,
  1507. const std::string &content_type, Progress progress);
  1508. Result Patch(const std::string &path, const std::string &body,
  1509. const std::string &content_type);
  1510. Result Patch(const std::string &path, const std::string &body,
  1511. const std::string &content_type, Progress progress);
  1512. Result Patch(const std::string &path, const Headers &headers,
  1513. const std::string &body, const std::string &content_type);
  1514. Result Patch(const std::string &path, const Headers &headers,
  1515. const std::string &body, const std::string &content_type,
  1516. Progress progress);
  1517. Result Patch(const std::string &path, size_t content_length,
  1518. ContentProvider content_provider,
  1519. const std::string &content_type);
  1520. Result Patch(const std::string &path,
  1521. ContentProviderWithoutLength content_provider,
  1522. const std::string &content_type);
  1523. Result Patch(const std::string &path, const Headers &headers,
  1524. size_t content_length, ContentProvider content_provider,
  1525. const std::string &content_type);
  1526. Result Patch(const std::string &path, const Headers &headers,
  1527. ContentProviderWithoutLength content_provider,
  1528. const std::string &content_type);
  1529. Result Delete(const std::string &path);
  1530. Result Delete(const std::string &path, const Headers &headers);
  1531. Result Delete(const std::string &path, const char *body,
  1532. size_t content_length, const std::string &content_type);
  1533. Result Delete(const std::string &path, const char *body,
  1534. size_t content_length, const std::string &content_type,
  1535. Progress progress);
  1536. Result Delete(const std::string &path, const Headers &headers,
  1537. const char *body, size_t content_length,
  1538. const std::string &content_type);
  1539. Result Delete(const std::string &path, const Headers &headers,
  1540. const char *body, size_t content_length,
  1541. const std::string &content_type, Progress progress);
  1542. Result Delete(const std::string &path, const std::string &body,
  1543. const std::string &content_type);
  1544. Result Delete(const std::string &path, const std::string &body,
  1545. const std::string &content_type, Progress progress);
  1546. Result Delete(const std::string &path, const Headers &headers,
  1547. const std::string &body, const std::string &content_type);
  1548. Result Delete(const std::string &path, const Headers &headers,
  1549. const std::string &body, const std::string &content_type,
  1550. Progress progress);
  1551. Result Options(const std::string &path);
  1552. Result Options(const std::string &path, const Headers &headers);
  1553. bool send(Request &req, Response &res, Error &error);
  1554. Result send(const Request &req);
  1555. void stop();
  1556. std::string host() const;
  1557. int port() const;
  1558. size_t is_socket_open() const;
  1559. socket_t socket() const;
  1560. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1561. void set_default_headers(Headers headers);
  1562. void
  1563. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1564. void set_address_family(int family);
  1565. void set_tcp_nodelay(bool on);
  1566. void set_socket_options(SocketOptions socket_options);
  1567. void set_connection_timeout(time_t sec, time_t usec = 0);
  1568. template <class Rep, class Period>
  1569. void
  1570. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1571. void set_read_timeout(time_t sec, time_t usec = 0);
  1572. template <class Rep, class Period>
  1573. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1574. void set_write_timeout(time_t sec, time_t usec = 0);
  1575. template <class Rep, class Period>
  1576. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1577. void set_max_timeout(time_t msec);
  1578. template <class Rep, class Period>
  1579. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1580. void set_basic_auth(const std::string &username, const std::string &password);
  1581. void set_bearer_token_auth(const std::string &token);
  1582. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1583. void set_digest_auth(const std::string &username,
  1584. const std::string &password);
  1585. #endif
  1586. void set_keep_alive(bool on);
  1587. void set_follow_location(bool on);
  1588. void set_url_encode(bool on);
  1589. void set_compress(bool on);
  1590. void set_decompress(bool on);
  1591. void set_interface(const std::string &intf);
  1592. void set_proxy(const std::string &host, int port);
  1593. void set_proxy_basic_auth(const std::string &username,
  1594. const std::string &password);
  1595. void set_proxy_bearer_token_auth(const std::string &token);
  1596. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1597. void set_proxy_digest_auth(const std::string &username,
  1598. const std::string &password);
  1599. #endif
  1600. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1601. void enable_server_certificate_verification(bool enabled);
  1602. void enable_server_hostname_verification(bool enabled);
  1603. void set_server_certificate_verifier(
  1604. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1605. #endif
  1606. void set_logger(Logger logger);
  1607. // SSL
  1608. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1609. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1610. const std::string &ca_cert_dir_path = std::string());
  1611. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1612. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1613. long get_openssl_verify_result() const;
  1614. SSL_CTX *ssl_context() const;
  1615. #endif
  1616. private:
  1617. std::unique_ptr<ClientImpl> cli_;
  1618. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1619. bool is_ssl_ = false;
  1620. #endif
  1621. };
  1622. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1623. class SSLServer : public Server {
  1624. public:
  1625. SSLServer(const char *cert_path, const char *private_key_path,
  1626. const char *client_ca_cert_file_path = nullptr,
  1627. const char *client_ca_cert_dir_path = nullptr,
  1628. const char *private_key_password = nullptr);
  1629. SSLServer(X509 *cert, EVP_PKEY *private_key,
  1630. X509_STORE *client_ca_cert_store = nullptr);
  1631. SSLServer(
  1632. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback);
  1633. ~SSLServer() override;
  1634. bool is_valid() const override;
  1635. SSL_CTX *ssl_context() const;
  1636. void update_certs(X509 *cert, EVP_PKEY *private_key,
  1637. X509_STORE *client_ca_cert_store = nullptr);
  1638. private:
  1639. bool process_and_close_socket(socket_t sock) override;
  1640. SSL_CTX *ctx_;
  1641. std::mutex ctx_mutex_;
  1642. };
  1643. class SSLClient final : public ClientImpl {
  1644. public:
  1645. explicit SSLClient(const std::string &host);
  1646. explicit SSLClient(const std::string &host, int port);
  1647. explicit SSLClient(const std::string &host, int port,
  1648. const std::string &client_cert_path,
  1649. const std::string &client_key_path,
  1650. const std::string &private_key_password = std::string());
  1651. explicit SSLClient(const std::string &host, int port, X509 *client_cert,
  1652. EVP_PKEY *client_key,
  1653. const std::string &private_key_password = std::string());
  1654. ~SSLClient() override;
  1655. bool is_valid() const override;
  1656. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1657. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1658. long get_openssl_verify_result() const;
  1659. SSL_CTX *ssl_context() const;
  1660. private:
  1661. bool create_and_connect_socket(Socket &socket, Error &error) override;
  1662. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  1663. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  1664. bool
  1665. process_socket(const Socket &socket,
  1666. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1667. std::function<bool(Stream &strm)> callback) override;
  1668. bool is_ssl() const override;
  1669. bool connect_with_proxy(
  1670. Socket &sock,
  1671. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1672. Response &res, bool &success, Error &error);
  1673. bool initialize_ssl(Socket &socket, Error &error);
  1674. bool load_certs();
  1675. bool verify_host(X509 *server_cert) const;
  1676. bool verify_host_with_subject_alt_name(X509 *server_cert) const;
  1677. bool verify_host_with_common_name(X509 *server_cert) const;
  1678. bool check_host_name(const char *pattern, size_t pattern_len) const;
  1679. SSL_CTX *ctx_;
  1680. std::mutex ctx_mutex_;
  1681. std::once_flag initialize_cert_;
  1682. std::vector<std::string> host_components_;
  1683. long verify_result_ = 0;
  1684. friend class ClientImpl;
  1685. };
  1686. #endif
  1687. /*
  1688. * Implementation of template methods.
  1689. */
  1690. namespace detail {
  1691. template <typename T, typename U>
  1692. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  1693. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  1694. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  1695. duration - std::chrono::seconds(sec))
  1696. .count();
  1697. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  1698. }
  1699. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  1700. return N - 1;
  1701. }
  1702. inline bool is_numeric(const std::string &str) {
  1703. return !str.empty() && std::all_of(str.begin(), str.end(), ::isdigit);
  1704. }
  1705. inline uint64_t get_header_value_u64(const Headers &headers,
  1706. const std::string &key, uint64_t def,
  1707. size_t id, bool &is_invalid_value) {
  1708. is_invalid_value = false;
  1709. auto rng = headers.equal_range(key);
  1710. auto it = rng.first;
  1711. std::advance(it, static_cast<ssize_t>(id));
  1712. if (it != rng.second) {
  1713. if (is_numeric(it->second)) {
  1714. return std::strtoull(it->second.data(), nullptr, 10);
  1715. } else {
  1716. is_invalid_value = true;
  1717. }
  1718. }
  1719. return def;
  1720. }
  1721. inline uint64_t get_header_value_u64(const Headers &headers,
  1722. const std::string &key, uint64_t def,
  1723. size_t id) {
  1724. bool dummy = false;
  1725. return get_header_value_u64(headers, key, def, id, dummy);
  1726. }
  1727. } // namespace detail
  1728. inline uint64_t Request::get_header_value_u64(const std::string &key,
  1729. uint64_t def, size_t id) const {
  1730. return detail::get_header_value_u64(headers, key, def, id);
  1731. }
  1732. inline uint64_t Response::get_header_value_u64(const std::string &key,
  1733. uint64_t def, size_t id) const {
  1734. return detail::get_header_value_u64(headers, key, def, id);
  1735. }
  1736. namespace detail {
  1737. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  1738. const void *optval, socklen_t optlen) {
  1739. return setsockopt(sock, level, optname,
  1740. #ifdef _WIN32
  1741. reinterpret_cast<const char *>(optval),
  1742. #else
  1743. optval,
  1744. #endif
  1745. optlen) == 0;
  1746. }
  1747. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  1748. return set_socket_opt_impl(sock, level, optname, &optval, sizeof(optval));
  1749. }
  1750. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  1751. time_t sec, time_t usec) {
  1752. #ifdef _WIN32
  1753. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  1754. #else
  1755. timeval timeout;
  1756. timeout.tv_sec = static_cast<long>(sec);
  1757. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  1758. #endif
  1759. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  1760. }
  1761. } // namespace detail
  1762. inline void default_socket_options(socket_t sock) {
  1763. detail::set_socket_opt(sock, SOL_SOCKET,
  1764. #ifdef SO_REUSEPORT
  1765. SO_REUSEPORT,
  1766. #else
  1767. SO_REUSEADDR,
  1768. #endif
  1769. 1);
  1770. }
  1771. inline const char *status_message(int status) {
  1772. switch (status) {
  1773. case StatusCode::Continue_100: return "Continue";
  1774. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  1775. case StatusCode::Processing_102: return "Processing";
  1776. case StatusCode::EarlyHints_103: return "Early Hints";
  1777. case StatusCode::OK_200: return "OK";
  1778. case StatusCode::Created_201: return "Created";
  1779. case StatusCode::Accepted_202: return "Accepted";
  1780. case StatusCode::NonAuthoritativeInformation_203:
  1781. return "Non-Authoritative Information";
  1782. case StatusCode::NoContent_204: return "No Content";
  1783. case StatusCode::ResetContent_205: return "Reset Content";
  1784. case StatusCode::PartialContent_206: return "Partial Content";
  1785. case StatusCode::MultiStatus_207: return "Multi-Status";
  1786. case StatusCode::AlreadyReported_208: return "Already Reported";
  1787. case StatusCode::IMUsed_226: return "IM Used";
  1788. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  1789. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  1790. case StatusCode::Found_302: return "Found";
  1791. case StatusCode::SeeOther_303: return "See Other";
  1792. case StatusCode::NotModified_304: return "Not Modified";
  1793. case StatusCode::UseProxy_305: return "Use Proxy";
  1794. case StatusCode::unused_306: return "unused";
  1795. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  1796. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  1797. case StatusCode::BadRequest_400: return "Bad Request";
  1798. case StatusCode::Unauthorized_401: return "Unauthorized";
  1799. case StatusCode::PaymentRequired_402: return "Payment Required";
  1800. case StatusCode::Forbidden_403: return "Forbidden";
  1801. case StatusCode::NotFound_404: return "Not Found";
  1802. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  1803. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  1804. case StatusCode::ProxyAuthenticationRequired_407:
  1805. return "Proxy Authentication Required";
  1806. case StatusCode::RequestTimeout_408: return "Request Timeout";
  1807. case StatusCode::Conflict_409: return "Conflict";
  1808. case StatusCode::Gone_410: return "Gone";
  1809. case StatusCode::LengthRequired_411: return "Length Required";
  1810. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  1811. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  1812. case StatusCode::UriTooLong_414: return "URI Too Long";
  1813. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  1814. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  1815. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  1816. case StatusCode::ImATeapot_418: return "I'm a teapot";
  1817. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  1818. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  1819. case StatusCode::Locked_423: return "Locked";
  1820. case StatusCode::FailedDependency_424: return "Failed Dependency";
  1821. case StatusCode::TooEarly_425: return "Too Early";
  1822. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  1823. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  1824. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  1825. case StatusCode::RequestHeaderFieldsTooLarge_431:
  1826. return "Request Header Fields Too Large";
  1827. case StatusCode::UnavailableForLegalReasons_451:
  1828. return "Unavailable For Legal Reasons";
  1829. case StatusCode::NotImplemented_501: return "Not Implemented";
  1830. case StatusCode::BadGateway_502: return "Bad Gateway";
  1831. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  1832. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  1833. case StatusCode::HttpVersionNotSupported_505:
  1834. return "HTTP Version Not Supported";
  1835. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  1836. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  1837. case StatusCode::LoopDetected_508: return "Loop Detected";
  1838. case StatusCode::NotExtended_510: return "Not Extended";
  1839. case StatusCode::NetworkAuthenticationRequired_511:
  1840. return "Network Authentication Required";
  1841. default:
  1842. case StatusCode::InternalServerError_500: return "Internal Server Error";
  1843. }
  1844. }
  1845. inline std::string get_bearer_token_auth(const Request &req) {
  1846. if (req.has_header("Authorization")) {
  1847. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  1848. return req.get_header_value("Authorization")
  1849. .substr(bearer_header_prefix_len);
  1850. }
  1851. return "";
  1852. }
  1853. template <class Rep, class Period>
  1854. inline Server &
  1855. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1856. detail::duration_to_sec_and_usec(
  1857. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  1858. return *this;
  1859. }
  1860. template <class Rep, class Period>
  1861. inline Server &
  1862. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1863. detail::duration_to_sec_and_usec(
  1864. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  1865. return *this;
  1866. }
  1867. template <class Rep, class Period>
  1868. inline Server &
  1869. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  1870. detail::duration_to_sec_and_usec(
  1871. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  1872. return *this;
  1873. }
  1874. inline std::string to_string(const Error error) {
  1875. switch (error) {
  1876. case Error::Success: return "Success (no error)";
  1877. case Error::Connection: return "Could not establish connection";
  1878. case Error::BindIPAddress: return "Failed to bind IP address";
  1879. case Error::Read: return "Failed to read connection";
  1880. case Error::Write: return "Failed to write connection";
  1881. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  1882. case Error::Canceled: return "Connection handling canceled";
  1883. case Error::SSLConnection: return "SSL connection failed";
  1884. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  1885. case Error::SSLServerVerification: return "SSL server verification failed";
  1886. case Error::SSLServerHostnameVerification:
  1887. return "SSL server hostname verification failed";
  1888. case Error::UnsupportedMultipartBoundaryChars:
  1889. return "Unsupported HTTP multipart boundary characters";
  1890. case Error::Compression: return "Compression failed";
  1891. case Error::ConnectionTimeout: return "Connection timed out";
  1892. case Error::ProxyConnection: return "Proxy connection failed";
  1893. case Error::Unknown: return "Unknown";
  1894. default: break;
  1895. }
  1896. return "Invalid";
  1897. }
  1898. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  1899. os << to_string(obj);
  1900. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  1901. return os;
  1902. }
  1903. inline uint64_t Result::get_request_header_value_u64(const std::string &key,
  1904. uint64_t def,
  1905. size_t id) const {
  1906. return detail::get_header_value_u64(request_headers_, key, def, id);
  1907. }
  1908. template <class Rep, class Period>
  1909. inline void ClientImpl::set_connection_timeout(
  1910. const std::chrono::duration<Rep, Period> &duration) {
  1911. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  1912. set_connection_timeout(sec, usec);
  1913. });
  1914. }
  1915. template <class Rep, class Period>
  1916. inline void ClientImpl::set_read_timeout(
  1917. const std::chrono::duration<Rep, Period> &duration) {
  1918. detail::duration_to_sec_and_usec(
  1919. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  1920. }
  1921. template <class Rep, class Period>
  1922. inline void ClientImpl::set_write_timeout(
  1923. const std::chrono::duration<Rep, Period> &duration) {
  1924. detail::duration_to_sec_and_usec(
  1925. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  1926. }
  1927. template <class Rep, class Period>
  1928. inline void ClientImpl::set_max_timeout(
  1929. const std::chrono::duration<Rep, Period> &duration) {
  1930. auto msec =
  1931. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  1932. set_max_timeout(msec);
  1933. }
  1934. template <class Rep, class Period>
  1935. inline void Client::set_connection_timeout(
  1936. const std::chrono::duration<Rep, Period> &duration) {
  1937. cli_->set_connection_timeout(duration);
  1938. }
  1939. template <class Rep, class Period>
  1940. inline void
  1941. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1942. cli_->set_read_timeout(duration);
  1943. }
  1944. template <class Rep, class Period>
  1945. inline void
  1946. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1947. cli_->set_write_timeout(duration);
  1948. }
  1949. template <class Rep, class Period>
  1950. inline void
  1951. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1952. cli_->set_max_timeout(duration);
  1953. }
  1954. /*
  1955. * Forward declarations and types that will be part of the .h file if split into
  1956. * .h + .cc.
  1957. */
  1958. std::string hosted_at(const std::string &hostname);
  1959. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  1960. std::string append_query_params(const std::string &path, const Params &params);
  1961. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  1962. std::pair<std::string, std::string>
  1963. make_basic_authentication_header(const std::string &username,
  1964. const std::string &password,
  1965. bool is_proxy = false);
  1966. namespace detail {
  1967. #if defined(_WIN32)
  1968. inline std::wstring u8string_to_wstring(const char *s) {
  1969. std::wstring ws;
  1970. auto len = static_cast<int>(strlen(s));
  1971. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  1972. if (wlen > 0) {
  1973. ws.resize(wlen);
  1974. wlen = ::MultiByteToWideChar(
  1975. CP_UTF8, 0, s, len,
  1976. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  1977. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  1978. }
  1979. return ws;
  1980. }
  1981. #endif
  1982. struct FileStat {
  1983. FileStat(const std::string &path);
  1984. bool is_file() const;
  1985. bool is_dir() const;
  1986. private:
  1987. #if defined(_WIN32)
  1988. struct _stat st_;
  1989. #else
  1990. struct stat st_;
  1991. #endif
  1992. int ret_ = -1;
  1993. };
  1994. std::string encode_query_param(const std::string &value);
  1995. std::string decode_url(const std::string &s, bool convert_plus_to_space);
  1996. std::string trim_copy(const std::string &s);
  1997. void divide(
  1998. const char *data, std::size_t size, char d,
  1999. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2000. fn);
  2001. void divide(
  2002. const std::string &str, char d,
  2003. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2004. fn);
  2005. void split(const char *b, const char *e, char d,
  2006. std::function<void(const char *, const char *)> fn);
  2007. void split(const char *b, const char *e, char d, size_t m,
  2008. std::function<void(const char *, const char *)> fn);
  2009. bool process_client_socket(
  2010. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2011. time_t write_timeout_sec, time_t write_timeout_usec,
  2012. time_t max_timeout_msec,
  2013. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2014. std::function<bool(Stream &)> callback);
  2015. socket_t create_client_socket(const std::string &host, const std::string &ip,
  2016. int port, int address_family, bool tcp_nodelay,
  2017. bool ipv6_v6only, SocketOptions socket_options,
  2018. time_t connection_timeout_sec,
  2019. time_t connection_timeout_usec,
  2020. time_t read_timeout_sec, time_t read_timeout_usec,
  2021. time_t write_timeout_sec,
  2022. time_t write_timeout_usec,
  2023. const std::string &intf, Error &error);
  2024. const char *get_header_value(const Headers &headers, const std::string &key,
  2025. const char *def, size_t id);
  2026. std::string params_to_query_str(const Params &params);
  2027. void parse_query_text(const char *data, std::size_t size, Params &params);
  2028. void parse_query_text(const std::string &s, Params &params);
  2029. bool parse_multipart_boundary(const std::string &content_type,
  2030. std::string &boundary);
  2031. bool parse_range_header(const std::string &s, Ranges &ranges);
  2032. int close_socket(socket_t sock);
  2033. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  2034. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  2035. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  2036. EncodingType encoding_type(const Request &req, const Response &res);
  2037. class BufferStream final : public Stream {
  2038. public:
  2039. BufferStream() = default;
  2040. ~BufferStream() override = default;
  2041. bool is_readable() const override;
  2042. bool wait_readable() const override;
  2043. bool wait_writable() const override;
  2044. ssize_t read(char *ptr, size_t size) override;
  2045. ssize_t write(const char *ptr, size_t size) override;
  2046. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2047. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2048. socket_t socket() const override;
  2049. time_t duration() const override;
  2050. const std::string &get_buffer() const;
  2051. private:
  2052. std::string buffer;
  2053. size_t position = 0;
  2054. };
  2055. class compressor {
  2056. public:
  2057. virtual ~compressor() = default;
  2058. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2059. virtual bool compress(const char *data, size_t data_length, bool last,
  2060. Callback callback) = 0;
  2061. };
  2062. class decompressor {
  2063. public:
  2064. virtual ~decompressor() = default;
  2065. virtual bool is_valid() const = 0;
  2066. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2067. virtual bool decompress(const char *data, size_t data_length,
  2068. Callback callback) = 0;
  2069. };
  2070. class nocompressor final : public compressor {
  2071. public:
  2072. ~nocompressor() override = default;
  2073. bool compress(const char *data, size_t data_length, bool /*last*/,
  2074. Callback callback) override;
  2075. };
  2076. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2077. class gzip_compressor final : public compressor {
  2078. public:
  2079. gzip_compressor();
  2080. ~gzip_compressor() override;
  2081. bool compress(const char *data, size_t data_length, bool last,
  2082. Callback callback) override;
  2083. private:
  2084. bool is_valid_ = false;
  2085. z_stream strm_;
  2086. };
  2087. class gzip_decompressor final : public decompressor {
  2088. public:
  2089. gzip_decompressor();
  2090. ~gzip_decompressor() override;
  2091. bool is_valid() const override;
  2092. bool decompress(const char *data, size_t data_length,
  2093. Callback callback) override;
  2094. private:
  2095. bool is_valid_ = false;
  2096. z_stream strm_;
  2097. };
  2098. #endif
  2099. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2100. class brotli_compressor final : public compressor {
  2101. public:
  2102. brotli_compressor();
  2103. ~brotli_compressor();
  2104. bool compress(const char *data, size_t data_length, bool last,
  2105. Callback callback) override;
  2106. private:
  2107. BrotliEncoderState *state_ = nullptr;
  2108. };
  2109. class brotli_decompressor final : public decompressor {
  2110. public:
  2111. brotli_decompressor();
  2112. ~brotli_decompressor();
  2113. bool is_valid() const override;
  2114. bool decompress(const char *data, size_t data_length,
  2115. Callback callback) override;
  2116. private:
  2117. BrotliDecoderResult decoder_r;
  2118. BrotliDecoderState *decoder_s = nullptr;
  2119. };
  2120. #endif
  2121. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  2122. class zstd_compressor : public compressor {
  2123. public:
  2124. zstd_compressor();
  2125. ~zstd_compressor();
  2126. bool compress(const char *data, size_t data_length, bool last,
  2127. Callback callback) override;
  2128. private:
  2129. ZSTD_CCtx *ctx_ = nullptr;
  2130. };
  2131. class zstd_decompressor : public decompressor {
  2132. public:
  2133. zstd_decompressor();
  2134. ~zstd_decompressor();
  2135. bool is_valid() const override;
  2136. bool decompress(const char *data, size_t data_length,
  2137. Callback callback) override;
  2138. private:
  2139. ZSTD_DCtx *ctx_ = nullptr;
  2140. };
  2141. #endif
  2142. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  2143. // to store data. The call can set memory on stack for performance.
  2144. class stream_line_reader {
  2145. public:
  2146. stream_line_reader(Stream &strm, char *fixed_buffer,
  2147. size_t fixed_buffer_size);
  2148. const char *ptr() const;
  2149. size_t size() const;
  2150. bool end_with_crlf() const;
  2151. bool getline();
  2152. private:
  2153. void append(char c);
  2154. Stream &strm_;
  2155. char *fixed_buffer_;
  2156. const size_t fixed_buffer_size_;
  2157. size_t fixed_buffer_used_size_ = 0;
  2158. std::string growable_buffer_;
  2159. };
  2160. class mmap {
  2161. public:
  2162. mmap(const char *path);
  2163. ~mmap();
  2164. bool open(const char *path);
  2165. void close();
  2166. bool is_open() const;
  2167. size_t size() const;
  2168. const char *data() const;
  2169. private:
  2170. #if defined(_WIN32)
  2171. HANDLE hFile_ = NULL;
  2172. HANDLE hMapping_ = NULL;
  2173. #else
  2174. int fd_ = -1;
  2175. #endif
  2176. size_t size_ = 0;
  2177. void *addr_ = nullptr;
  2178. bool is_open_empty_file = false;
  2179. };
  2180. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  2181. namespace fields {
  2182. inline bool is_token_char(char c) {
  2183. return std::isalnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  2184. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  2185. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  2186. }
  2187. inline bool is_token(const std::string &s) {
  2188. if (s.empty()) { return false; }
  2189. for (auto c : s) {
  2190. if (!is_token_char(c)) { return false; }
  2191. }
  2192. return true;
  2193. }
  2194. inline bool is_field_name(const std::string &s) { return is_token(s); }
  2195. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  2196. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  2197. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  2198. inline bool is_field_content(const std::string &s) {
  2199. if (s.empty()) { return true; }
  2200. if (s.size() == 1) {
  2201. return is_field_vchar(s[0]);
  2202. } else if (s.size() == 2) {
  2203. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  2204. } else {
  2205. size_t i = 0;
  2206. if (!is_field_vchar(s[i])) { return false; }
  2207. i++;
  2208. while (i < s.size() - 1) {
  2209. auto c = s[i++];
  2210. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  2211. } else {
  2212. return false;
  2213. }
  2214. }
  2215. return is_field_vchar(s[i]);
  2216. }
  2217. }
  2218. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  2219. } // namespace fields
  2220. } // namespace detail
  2221. } // namespace httplib
  2222. #endif // CPPHTTPLIB_HTTPLIB_H