httplib.h 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2019 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #ifndef CPPHTTPLIB_HTTPLIB_H
  8. #define CPPHTTPLIB_HTTPLIB_H
  9. #ifdef _WIN32
  10. #ifndef _CRT_SECURE_NO_WARNINGS
  11. #define _CRT_SECURE_NO_WARNINGS
  12. #endif //_CRT_SECURE_NO_WARNINGS
  13. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  14. #define _CRT_NONSTDC_NO_DEPRECATE
  15. #endif //_CRT_NONSTDC_NO_DEPRECATE
  16. #if defined(_MSC_VER) && _MSC_VER < 1900
  17. #define snprintf _snprintf_s
  18. #endif // _MSC_VER
  19. #ifndef S_ISREG
  20. #define S_ISREG(m) (((m)&S_IFREG) == S_IFREG)
  21. #endif // S_ISREG
  22. #ifndef S_ISDIR
  23. #define S_ISDIR(m) (((m)&S_IFDIR) == S_IFDIR)
  24. #endif // S_ISDIR
  25. #ifndef NOMINMAX
  26. #define NOMINMAX
  27. #endif // NOMINMAX
  28. #include <io.h>
  29. #include <winsock2.h>
  30. #include <ws2tcpip.h>
  31. #pragma comment(lib, "ws2_32.lib")
  32. #ifndef strcasecmp
  33. #define strcasecmp _stricmp
  34. #endif // strcasecmp
  35. typedef SOCKET socket_t;
  36. #else
  37. #include <arpa/inet.h>
  38. #include <cstring>
  39. #include <netdb.h>
  40. #include <netinet/in.h>
  41. #include <pthread.h>
  42. #include <signal.h>
  43. #include <sys/select.h>
  44. #include <sys/socket.h>
  45. #include <unistd.h>
  46. typedef int socket_t;
  47. #define INVALID_SOCKET (-1)
  48. #endif //_WIN32
  49. #include <assert.h>
  50. #include <fcntl.h>
  51. #include <fstream>
  52. #include <functional>
  53. #include <map>
  54. #include <memory>
  55. #include <mutex>
  56. #include <regex>
  57. #include <string>
  58. #include <sys/stat.h>
  59. #include <thread>
  60. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  61. #include <openssl/err.h>
  62. #include <openssl/ssl.h>
  63. #endif
  64. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  65. #include <zlib.h>
  66. #endif
  67. /*
  68. * Configuration
  69. */
  70. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  71. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND 0
  72. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  73. namespace httplib {
  74. namespace detail {
  75. struct ci {
  76. bool operator()(const std::string &s1, const std::string &s2) const {
  77. return std::lexicographical_compare(
  78. s1.begin(), s1.end(), s2.begin(), s2.end(),
  79. [](char c1, char c2) { return ::tolower(c1) < ::tolower(c2); });
  80. }
  81. };
  82. } // namespace detail
  83. enum class HttpVersion { v1_0 = 0, v1_1 };
  84. typedef std::multimap<std::string, std::string, detail::ci> Headers;
  85. template <typename uint64_t, typename... Args>
  86. std::pair<std::string, std::string> make_range_header(uint64_t value,
  87. Args... args);
  88. typedef std::multimap<std::string, std::string> Params;
  89. typedef std::smatch Match;
  90. typedef std::function<bool(uint64_t current, uint64_t total)> Progress;
  91. struct MultipartFile {
  92. std::string filename;
  93. std::string content_type;
  94. size_t offset = 0;
  95. size_t length = 0;
  96. };
  97. typedef std::multimap<std::string, MultipartFile> MultipartFiles;
  98. struct Request {
  99. std::string version;
  100. std::string method;
  101. std::string target;
  102. std::string path;
  103. Headers headers;
  104. std::string body;
  105. Params params;
  106. MultipartFiles files;
  107. Match matches;
  108. Progress progress;
  109. bool has_header(const char *key) const;
  110. std::string get_header_value(const char *key, size_t id = 0) const;
  111. size_t get_header_value_count(const char *key) const;
  112. void set_header(const char *key, const char *val);
  113. bool has_param(const char *key) const;
  114. std::string get_param_value(const char *key, size_t id = 0) const;
  115. size_t get_param_value_count(const char *key) const;
  116. bool has_file(const char *key) const;
  117. MultipartFile get_file_value(const char *key) const;
  118. };
  119. struct Response {
  120. std::string version;
  121. int status;
  122. Headers headers;
  123. std::string body;
  124. std::function<std::string(uint64_t offset)> streamcb;
  125. bool has_header(const char *key) const;
  126. std::string get_header_value(const char *key, size_t id = 0) const;
  127. size_t get_header_value_count(const char *key) const;
  128. void set_header(const char *key, const char *val);
  129. void set_redirect(const char *uri);
  130. void set_content(const char *s, size_t n, const char *content_type);
  131. void set_content(const std::string &s, const char *content_type);
  132. Response() : status(-1) {}
  133. };
  134. class Stream {
  135. public:
  136. virtual ~Stream() {}
  137. virtual int read(char *ptr, size_t size) = 0;
  138. virtual int write(const char *ptr, size_t size1) = 0;
  139. virtual int write(const char *ptr) = 0;
  140. virtual std::string get_remote_addr() const = 0;
  141. template <typename... Args>
  142. void write_format(const char *fmt, const Args &... args);
  143. };
  144. class SocketStream : public Stream {
  145. public:
  146. SocketStream(socket_t sock);
  147. virtual ~SocketStream();
  148. virtual int read(char *ptr, size_t size);
  149. virtual int write(const char *ptr, size_t size);
  150. virtual int write(const char *ptr);
  151. virtual std::string get_remote_addr() const;
  152. private:
  153. socket_t sock_;
  154. };
  155. class BufferStream : public Stream {
  156. public:
  157. BufferStream() {}
  158. virtual ~BufferStream() {}
  159. virtual int read(char *ptr, size_t size);
  160. virtual int write(const char *ptr, size_t size);
  161. virtual int write(const char *ptr);
  162. virtual std::string get_remote_addr() const;
  163. const std::string &get_buffer() const;
  164. private:
  165. std::string buffer;
  166. };
  167. class Server {
  168. public:
  169. typedef std::function<void(const Request &, Response &)> Handler;
  170. typedef std::function<void(const Request &, const Response &)> Logger;
  171. Server();
  172. virtual ~Server();
  173. virtual bool is_valid() const;
  174. Server &Get(const char *pattern, Handler handler);
  175. Server &Post(const char *pattern, Handler handler);
  176. Server &Put(const char *pattern, Handler handler);
  177. Server &Patch(const char *pattern, Handler handler);
  178. Server &Delete(const char *pattern, Handler handler);
  179. Server &Options(const char *pattern, Handler handler);
  180. bool set_base_dir(const char *path);
  181. void set_error_handler(Handler handler);
  182. void set_logger(Logger logger);
  183. void set_keep_alive_max_count(size_t count);
  184. int bind_to_any_port(const char *host, int socket_flags = 0);
  185. bool listen_after_bind();
  186. bool listen(const char *host, int port, int socket_flags = 0);
  187. bool is_running() const;
  188. void stop();
  189. protected:
  190. bool process_request(Stream &strm, bool last_connection,
  191. bool &connection_close);
  192. size_t keep_alive_max_count_;
  193. private:
  194. typedef std::vector<std::pair<std::regex, Handler>> Handlers;
  195. socket_t create_server_socket(const char *host, int port,
  196. int socket_flags) const;
  197. int bind_internal(const char *host, int port, int socket_flags);
  198. bool listen_internal();
  199. bool routing(Request &req, Response &res);
  200. bool handle_file_request(Request &req, Response &res);
  201. bool dispatch_request(Request &req, Response &res, Handlers &handlers);
  202. bool parse_request_line(const char *s, Request &req);
  203. void write_response(Stream &strm, bool last_connection, const Request &req,
  204. Response &res);
  205. virtual bool read_and_close_socket(socket_t sock);
  206. bool is_running_;
  207. socket_t svr_sock_;
  208. std::string base_dir_;
  209. Handlers get_handlers_;
  210. Handlers post_handlers_;
  211. Handlers put_handlers_;
  212. Handlers patch_handlers_;
  213. Handlers delete_handlers_;
  214. Handlers options_handlers_;
  215. Handler error_handler_;
  216. Logger logger_;
  217. // TODO: Use thread pool...
  218. std::mutex running_threads_mutex_;
  219. int running_threads_;
  220. };
  221. class Client {
  222. public:
  223. Client(const char *host, int port = 80, time_t timeout_sec = 300);
  224. virtual ~Client();
  225. virtual bool is_valid() const;
  226. std::shared_ptr<Response> Get(const char *path, Progress progress = nullptr);
  227. std::shared_ptr<Response> Get(const char *path, const Headers &headers,
  228. Progress progress = nullptr);
  229. std::shared_ptr<Response> Head(const char *path);
  230. std::shared_ptr<Response> Head(const char *path, const Headers &headers);
  231. std::shared_ptr<Response> Post(const char *path, const std::string &body,
  232. const char *content_type);
  233. std::shared_ptr<Response> Post(const char *path, const Headers &headers,
  234. const std::string &body,
  235. const char *content_type);
  236. std::shared_ptr<Response> Post(const char *path, const Params &params);
  237. std::shared_ptr<Response> Post(const char *path, const Headers &headers,
  238. const Params &params);
  239. std::shared_ptr<Response> Put(const char *path, const std::string &body,
  240. const char *content_type);
  241. std::shared_ptr<Response> Put(const char *path, const Headers &headers,
  242. const std::string &body,
  243. const char *content_type);
  244. std::shared_ptr<Response> Patch(const char *path, const std::string &body,
  245. const char *content_type);
  246. std::shared_ptr<Response> Patch(const char *path, const Headers &headers,
  247. const std::string &body,
  248. const char *content_type);
  249. std::shared_ptr<Response> Delete(const char *path);
  250. std::shared_ptr<Response> Delete(const char *path, const Headers &headers);
  251. std::shared_ptr<Response> Options(const char *path);
  252. std::shared_ptr<Response> Options(const char *path, const Headers &headers);
  253. bool send(Request &req, Response &res);
  254. protected:
  255. bool process_request(Stream &strm, Request &req, Response &res,
  256. bool &connection_close);
  257. const std::string host_;
  258. const int port_;
  259. time_t timeout_sec_;
  260. const std::string host_and_port_;
  261. private:
  262. socket_t create_client_socket() const;
  263. bool read_response_line(Stream &strm, Response &res);
  264. void write_request(Stream &strm, Request &req);
  265. virtual bool read_and_close_socket(socket_t sock, Request &req,
  266. Response &res);
  267. virtual bool is_ssl() const;
  268. };
  269. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  270. class SSLSocketStream : public Stream {
  271. public:
  272. SSLSocketStream(socket_t sock, SSL *ssl);
  273. virtual ~SSLSocketStream();
  274. virtual int read(char *ptr, size_t size);
  275. virtual int write(const char *ptr, size_t size);
  276. virtual int write(const char *ptr);
  277. virtual std::string get_remote_addr() const;
  278. private:
  279. socket_t sock_;
  280. SSL *ssl_;
  281. };
  282. class SSLServer : public Server {
  283. public:
  284. SSLServer(const char *cert_path, const char *private_key_path);
  285. virtual ~SSLServer();
  286. virtual bool is_valid() const;
  287. private:
  288. virtual bool read_and_close_socket(socket_t sock);
  289. SSL_CTX *ctx_;
  290. std::mutex ctx_mutex_;
  291. };
  292. class SSLClient : public Client {
  293. public:
  294. SSLClient(const char *host, int port = 443, time_t timeout_sec = 300);
  295. virtual ~SSLClient();
  296. virtual bool is_valid() const;
  297. private:
  298. virtual bool read_and_close_socket(socket_t sock, Request &req,
  299. Response &res);
  300. virtual bool is_ssl() const;
  301. SSL_CTX *ctx_;
  302. std::mutex ctx_mutex_;
  303. };
  304. #endif
  305. /*
  306. * Implementation
  307. */
  308. namespace detail {
  309. template <class Fn> void split(const char *b, const char *e, char d, Fn fn) {
  310. int i = 0;
  311. int beg = 0;
  312. while (e ? (b + i != e) : (b[i] != '\0')) {
  313. if (b[i] == d) {
  314. fn(&b[beg], &b[i]);
  315. beg = i + 1;
  316. }
  317. i++;
  318. }
  319. if (i) { fn(&b[beg], &b[i]); }
  320. }
  321. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  322. // to store data. The call can set memory on stack for performance.
  323. class stream_line_reader {
  324. public:
  325. stream_line_reader(Stream &strm, char *fixed_buffer, size_t fixed_buffer_size)
  326. : strm_(strm), fixed_buffer_(fixed_buffer),
  327. fixed_buffer_size_(fixed_buffer_size) {}
  328. const char *ptr() const {
  329. if (glowable_buffer_.empty()) {
  330. return fixed_buffer_;
  331. } else {
  332. return glowable_buffer_.data();
  333. }
  334. }
  335. size_t size() const {
  336. if (glowable_buffer_.empty()) {
  337. return fixed_buffer_used_size_;
  338. } else {
  339. return glowable_buffer_.size();
  340. }
  341. }
  342. bool getline() {
  343. fixed_buffer_used_size_ = 0;
  344. glowable_buffer_.clear();
  345. for (size_t i = 0;; i++) {
  346. char byte;
  347. auto n = strm_.read(&byte, 1);
  348. if (n < 0) {
  349. return false;
  350. } else if (n == 0) {
  351. if (i == 0) {
  352. return false;
  353. } else {
  354. break;
  355. }
  356. }
  357. append(byte);
  358. if (byte == '\n') { break; }
  359. }
  360. return true;
  361. }
  362. private:
  363. void append(char c) {
  364. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  365. fixed_buffer_[fixed_buffer_used_size_++] = c;
  366. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  367. } else {
  368. if (glowable_buffer_.empty()) {
  369. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  370. glowable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  371. }
  372. glowable_buffer_ += c;
  373. }
  374. }
  375. Stream &strm_;
  376. char *fixed_buffer_;
  377. const size_t fixed_buffer_size_;
  378. size_t fixed_buffer_used_size_;
  379. std::string glowable_buffer_;
  380. };
  381. inline int close_socket(socket_t sock) {
  382. #ifdef _WIN32
  383. return closesocket(sock);
  384. #else
  385. return close(sock);
  386. #endif
  387. }
  388. inline int select_read(socket_t sock, time_t sec, time_t usec) {
  389. fd_set fds;
  390. FD_ZERO(&fds);
  391. FD_SET(sock, &fds);
  392. timeval tv;
  393. tv.tv_sec = static_cast<long>(sec);
  394. tv.tv_usec = static_cast<long>(usec);
  395. return select(static_cast<int>(sock + 1), &fds, NULL, NULL, &tv);
  396. }
  397. inline bool wait_until_socket_is_ready(socket_t sock, time_t sec, time_t usec) {
  398. fd_set fdsr;
  399. FD_ZERO(&fdsr);
  400. FD_SET(sock, &fdsr);
  401. auto fdsw = fdsr;
  402. auto fdse = fdsr;
  403. timeval tv;
  404. tv.tv_sec = static_cast<long>(sec);
  405. tv.tv_usec = static_cast<long>(usec);
  406. if (select(static_cast<int>(sock + 1), &fdsr, &fdsw, &fdse, &tv) < 0) {
  407. return false;
  408. } else if (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw)) {
  409. int error = 0;
  410. socklen_t len = sizeof(error);
  411. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (char *)&error, &len) < 0 ||
  412. error) {
  413. return false;
  414. }
  415. } else {
  416. return false;
  417. }
  418. return true;
  419. }
  420. template <typename T>
  421. inline bool read_and_close_socket(socket_t sock, size_t keep_alive_max_count,
  422. T callback) {
  423. bool ret = false;
  424. if (keep_alive_max_count > 0) {
  425. auto count = keep_alive_max_count;
  426. while (count > 0 &&
  427. detail::select_read(sock, CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND,
  428. CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND) > 0) {
  429. SocketStream strm(sock);
  430. auto last_connection = count == 1;
  431. auto connection_close = false;
  432. ret = callback(strm, last_connection, connection_close);
  433. if (!ret || connection_close) { break; }
  434. count--;
  435. }
  436. } else {
  437. SocketStream strm(sock);
  438. auto dummy_connection_close = false;
  439. ret = callback(strm, true, dummy_connection_close);
  440. }
  441. close_socket(sock);
  442. return ret;
  443. }
  444. inline int shutdown_socket(socket_t sock) {
  445. #ifdef _WIN32
  446. return shutdown(sock, SD_BOTH);
  447. #else
  448. return shutdown(sock, SHUT_RDWR);
  449. #endif
  450. }
  451. template <typename Fn>
  452. socket_t create_socket(const char *host, int port, Fn fn,
  453. int socket_flags = 0) {
  454. #ifdef _WIN32
  455. #define SO_SYNCHRONOUS_NONALERT 0x20
  456. #define SO_OPENTYPE 0x7008
  457. int opt = SO_SYNCHRONOUS_NONALERT;
  458. setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char *)&opt,
  459. sizeof(opt));
  460. #endif
  461. // Get address info
  462. struct addrinfo hints;
  463. struct addrinfo *result;
  464. memset(&hints, 0, sizeof(struct addrinfo));
  465. hints.ai_family = AF_UNSPEC;
  466. hints.ai_socktype = SOCK_STREAM;
  467. hints.ai_flags = socket_flags;
  468. hints.ai_protocol = 0;
  469. auto service = std::to_string(port);
  470. if (getaddrinfo(host, service.c_str(), &hints, &result)) {
  471. return INVALID_SOCKET;
  472. }
  473. for (auto rp = result; rp; rp = rp->ai_next) {
  474. // Create a socket
  475. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  476. if (sock == INVALID_SOCKET) { continue; }
  477. // Make 'reuse address' option available
  478. int yes = 1;
  479. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&yes, sizeof(yes));
  480. // bind or connect
  481. if (fn(sock, *rp)) {
  482. freeaddrinfo(result);
  483. return sock;
  484. }
  485. close_socket(sock);
  486. }
  487. freeaddrinfo(result);
  488. return INVALID_SOCKET;
  489. }
  490. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  491. #ifdef _WIN32
  492. auto flags = nonblocking ? 1UL : 0UL;
  493. ioctlsocket(sock, FIONBIO, &flags);
  494. #else
  495. auto flags = fcntl(sock, F_GETFL, 0);
  496. fcntl(sock, F_SETFL,
  497. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  498. #endif
  499. }
  500. inline bool is_connection_error() {
  501. #ifdef _WIN32
  502. return WSAGetLastError() != WSAEWOULDBLOCK;
  503. #else
  504. return errno != EINPROGRESS;
  505. #endif
  506. }
  507. inline std::string get_remote_addr(socket_t sock) {
  508. struct sockaddr_storage addr;
  509. socklen_t len = sizeof(addr);
  510. if (!getpeername(sock, (struct sockaddr *)&addr, &len)) {
  511. char ipstr[NI_MAXHOST];
  512. if (!getnameinfo((struct sockaddr *)&addr, len, ipstr, sizeof(ipstr),
  513. nullptr, 0, NI_NUMERICHOST)) {
  514. return ipstr;
  515. }
  516. }
  517. return std::string();
  518. }
  519. inline bool is_file(const std::string &path) {
  520. struct stat st;
  521. return stat(path.c_str(), &st) >= 0 && S_ISREG(st.st_mode);
  522. }
  523. inline bool is_dir(const std::string &path) {
  524. struct stat st;
  525. return stat(path.c_str(), &st) >= 0 && S_ISDIR(st.st_mode);
  526. }
  527. inline bool is_valid_path(const std::string &path) {
  528. size_t level = 0;
  529. size_t i = 0;
  530. // Skip slash
  531. while (i < path.size() && path[i] == '/') {
  532. i++;
  533. }
  534. while (i < path.size()) {
  535. // Read component
  536. auto beg = i;
  537. while (i < path.size() && path[i] != '/') {
  538. i++;
  539. }
  540. auto len = i - beg;
  541. assert(len > 0);
  542. if (!path.compare(beg, len, ".")) {
  543. ;
  544. } else if (!path.compare(beg, len, "..")) {
  545. if (level == 0) { return false; }
  546. level--;
  547. } else {
  548. level++;
  549. }
  550. // Skip slash
  551. while (i < path.size() && path[i] == '/') {
  552. i++;
  553. }
  554. }
  555. return true;
  556. }
  557. inline void read_file(const std::string &path, std::string &out) {
  558. std::ifstream fs(path, std::ios_base::binary);
  559. fs.seekg(0, std::ios_base::end);
  560. auto size = fs.tellg();
  561. fs.seekg(0);
  562. out.resize(static_cast<size_t>(size));
  563. fs.read(&out[0], size);
  564. }
  565. inline std::string file_extension(const std::string &path) {
  566. std::smatch m;
  567. auto pat = std::regex("\\.([a-zA-Z0-9]+)$");
  568. if (std::regex_search(path, m, pat)) { return m[1].str(); }
  569. return std::string();
  570. }
  571. inline const char *find_content_type(const std::string &path) {
  572. auto ext = file_extension(path);
  573. if (ext == "txt") {
  574. return "text/plain";
  575. } else if (ext == "html") {
  576. return "text/html";
  577. } else if (ext == "css") {
  578. return "text/css";
  579. } else if (ext == "jpeg" || ext == "jpg") {
  580. return "image/jpg";
  581. } else if (ext == "png") {
  582. return "image/png";
  583. } else if (ext == "gif") {
  584. return "image/gif";
  585. } else if (ext == "svg") {
  586. return "image/svg+xml";
  587. } else if (ext == "ico") {
  588. return "image/x-icon";
  589. } else if (ext == "json") {
  590. return "application/json";
  591. } else if (ext == "pdf") {
  592. return "application/pdf";
  593. } else if (ext == "js") {
  594. return "application/javascript";
  595. } else if (ext == "xml") {
  596. return "application/xml";
  597. } else if (ext == "xhtml") {
  598. return "application/xhtml+xml";
  599. }
  600. return nullptr;
  601. }
  602. inline const char *status_message(int status) {
  603. switch (status) {
  604. case 200: return "OK";
  605. case 301: return "Moved Permanently";
  606. case 302: return "Found";
  607. case 303: return "See Other";
  608. case 304: return "Not Modified";
  609. case 400: return "Bad Request";
  610. case 403: return "Forbidden";
  611. case 404: return "Not Found";
  612. case 414: return "Request-URI Too Long";
  613. case 415: return "Unsupported Media Type";
  614. default:
  615. case 500: return "Internal Server Error";
  616. }
  617. }
  618. inline bool has_header(const Headers &headers, const char *key) {
  619. return headers.find(key) != headers.end();
  620. }
  621. inline const char *get_header_value(const Headers &headers, const char *key,
  622. size_t id = 0, const char *def = nullptr) {
  623. auto it = headers.find(key);
  624. std::advance(it, id);
  625. if (it != headers.end()) { return it->second.c_str(); }
  626. return def;
  627. }
  628. inline uint64_t get_header_value_uint64(const Headers &headers, const char *key,
  629. int def = 0) {
  630. auto it = headers.find(key);
  631. if (it != headers.end()) {
  632. return std::strtoull(it->second.data(), nullptr, 10);
  633. }
  634. return def;
  635. }
  636. inline bool read_headers(Stream &strm, Headers &headers) {
  637. static std::regex re(R"((.+?):\s*(.+?)\s*\r\n)");
  638. const auto bufsiz = 2048;
  639. char buf[bufsiz];
  640. stream_line_reader reader(strm, buf, bufsiz);
  641. for (;;) {
  642. if (!reader.getline()) { return false; }
  643. if (!strcmp(reader.ptr(), "\r\n")) { break; }
  644. std::cmatch m;
  645. if (std::regex_match(reader.ptr(), m, re)) {
  646. auto key = std::string(m[1]);
  647. auto val = std::string(m[2]);
  648. headers.emplace(key, val);
  649. }
  650. }
  651. return true;
  652. }
  653. inline bool read_content_with_length(Stream &strm, std::string &out, size_t len,
  654. Progress progress) {
  655. out.assign(len, 0);
  656. size_t r = 0;
  657. while (r < len) {
  658. auto n = strm.read(&out[r], len - r);
  659. if (n <= 0) { return false; }
  660. r += n;
  661. if (progress) {
  662. if (!progress(r, len)) { return false; }
  663. }
  664. }
  665. return true;
  666. }
  667. inline bool read_content_without_length(Stream &strm, std::string &out) {
  668. for (;;) {
  669. char byte;
  670. auto n = strm.read(&byte, 1);
  671. if (n < 0) {
  672. return false;
  673. } else if (n == 0) {
  674. return true;
  675. }
  676. out += byte;
  677. }
  678. return true;
  679. }
  680. inline bool read_content_chunked(Stream &strm, std::string &out) {
  681. const auto bufsiz = 16;
  682. char buf[bufsiz];
  683. stream_line_reader reader(strm, buf, bufsiz);
  684. if (!reader.getline()) { return false; }
  685. auto chunk_len = std::stoi(reader.ptr(), 0, 16);
  686. while (chunk_len > 0) {
  687. std::string chunk;
  688. if (!read_content_with_length(strm, chunk, chunk_len, nullptr)) {
  689. return false;
  690. }
  691. if (!reader.getline()) { return false; }
  692. if (strcmp(reader.ptr(), "\r\n")) { break; }
  693. out += chunk;
  694. if (!reader.getline()) { return false; }
  695. chunk_len = std::stoi(reader.ptr(), 0, 16);
  696. }
  697. if (chunk_len == 0) {
  698. // Reader terminator after chunks
  699. if (!reader.getline() || strcmp(reader.ptr(), "\r\n")) return false;
  700. }
  701. return true;
  702. }
  703. template <typename T>
  704. bool read_content(Stream &strm, T &x, Progress progress = Progress()) {
  705. if (has_header(x.headers, "Content-Length")) {
  706. auto len = get_header_value_uint64(x.headers, "Content-Length", 0);
  707. if (len == 0) {
  708. const auto &encoding =
  709. get_header_value(x.headers, "Transfer-Encoding", 0, "");
  710. if (!strcasecmp(encoding, "chunked")) {
  711. return read_content_chunked(strm, x.body);
  712. }
  713. }
  714. return read_content_with_length(strm, x.body, len, progress);
  715. } else {
  716. const auto &encoding =
  717. get_header_value(x.headers, "Transfer-Encoding", 0, "");
  718. if (!strcasecmp(encoding, "chunked")) {
  719. return read_content_chunked(strm, x.body);
  720. }
  721. return read_content_without_length(strm, x.body);
  722. }
  723. return true;
  724. }
  725. template <typename T> inline void write_headers(Stream &strm, const T &info) {
  726. for (const auto &x : info.headers) {
  727. strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str());
  728. }
  729. strm.write("\r\n");
  730. }
  731. inline std::string encode_url(const std::string &s) {
  732. std::string result;
  733. for (auto i = 0; s[i]; i++) {
  734. switch (s[i]) {
  735. case ' ': result += "%20"; break;
  736. case '+': result += "%2B"; break;
  737. case '\r': result += "%0D"; break;
  738. case '\n': result += "%0A"; break;
  739. case '\'': result += "%27"; break;
  740. case ',': result += "%2C"; break;
  741. case ':': result += "%3A"; break;
  742. case ';': result += "%3B"; break;
  743. default:
  744. auto c = static_cast<uint8_t>(s[i]);
  745. if (c >= 0x80) {
  746. result += '%';
  747. char hex[4];
  748. size_t len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  749. assert(len == 2);
  750. result.append(hex, len);
  751. } else {
  752. result += s[i];
  753. }
  754. break;
  755. }
  756. }
  757. return result;
  758. }
  759. inline bool is_hex(char c, int &v) {
  760. if (0x20 <= c && isdigit(c)) {
  761. v = c - '0';
  762. return true;
  763. } else if ('A' <= c && c <= 'F') {
  764. v = c - 'A' + 10;
  765. return true;
  766. } else if ('a' <= c && c <= 'f') {
  767. v = c - 'a' + 10;
  768. return true;
  769. }
  770. return false;
  771. }
  772. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  773. int &val) {
  774. if (i >= s.size()) { return false; }
  775. val = 0;
  776. for (; cnt; i++, cnt--) {
  777. if (!s[i]) { return false; }
  778. int v = 0;
  779. if (is_hex(s[i], v)) {
  780. val = val * 16 + v;
  781. } else {
  782. return false;
  783. }
  784. }
  785. return true;
  786. }
  787. inline std::string from_i_to_hex(uint64_t n) {
  788. const char *charset = "0123456789abcdef";
  789. std::string ret;
  790. do {
  791. ret = charset[n & 15] + ret;
  792. n >>= 4;
  793. } while (n > 0);
  794. return ret;
  795. }
  796. inline size_t to_utf8(int code, char *buff) {
  797. if (code < 0x0080) {
  798. buff[0] = (code & 0x7F);
  799. return 1;
  800. } else if (code < 0x0800) {
  801. buff[0] = (0xC0 | ((code >> 6) & 0x1F));
  802. buff[1] = (0x80 | (code & 0x3F));
  803. return 2;
  804. } else if (code < 0xD800) {
  805. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  806. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  807. buff[2] = (0x80 | (code & 0x3F));
  808. return 3;
  809. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  810. return 0;
  811. } else if (code < 0x10000) {
  812. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  813. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  814. buff[2] = (0x80 | (code & 0x3F));
  815. return 3;
  816. } else if (code < 0x110000) {
  817. buff[0] = (0xF0 | ((code >> 18) & 0x7));
  818. buff[1] = (0x80 | ((code >> 12) & 0x3F));
  819. buff[2] = (0x80 | ((code >> 6) & 0x3F));
  820. buff[3] = (0x80 | (code & 0x3F));
  821. return 4;
  822. }
  823. // NOTREACHED
  824. return 0;
  825. }
  826. inline std::string decode_url(const std::string &s) {
  827. std::string result;
  828. for (size_t i = 0; i < s.size(); i++) {
  829. if (s[i] == '%' && i + 1 < s.size()) {
  830. if (s[i + 1] == 'u') {
  831. int val = 0;
  832. if (from_hex_to_i(s, i + 2, 4, val)) {
  833. // 4 digits Unicode codes
  834. char buff[4];
  835. size_t len = to_utf8(val, buff);
  836. if (len > 0) { result.append(buff, len); }
  837. i += 5; // 'u0000'
  838. } else {
  839. result += s[i];
  840. }
  841. } else {
  842. int val = 0;
  843. if (from_hex_to_i(s, i + 1, 2, val)) {
  844. // 2 digits hex codes
  845. result += val;
  846. i += 2; // '00'
  847. } else {
  848. result += s[i];
  849. }
  850. }
  851. } else if (s[i] == '+') {
  852. result += ' ';
  853. } else {
  854. result += s[i];
  855. }
  856. }
  857. return result;
  858. }
  859. inline void parse_query_text(const std::string &s, Params &params) {
  860. split(&s[0], &s[s.size()], '&', [&](const char *b, const char *e) {
  861. std::string key;
  862. std::string val;
  863. split(b, e, '=', [&](const char *b, const char *e) {
  864. if (key.empty()) {
  865. key.assign(b, e);
  866. } else {
  867. val.assign(b, e);
  868. }
  869. });
  870. params.emplace(key, decode_url(val));
  871. });
  872. }
  873. inline bool parse_multipart_boundary(const std::string &content_type,
  874. std::string &boundary) {
  875. auto pos = content_type.find("boundary=");
  876. if (pos == std::string::npos) { return false; }
  877. boundary = content_type.substr(pos + 9);
  878. return true;
  879. }
  880. inline bool parse_multipart_formdata(const std::string &boundary,
  881. const std::string &body,
  882. MultipartFiles &files) {
  883. static std::string dash = "--";
  884. static std::string crlf = "\r\n";
  885. static std::regex re_content_type("Content-Type: (.*?)",
  886. std::regex_constants::icase);
  887. static std::regex re_content_disposition(
  888. "Content-Disposition: form-data; name=\"(.*?)\"(?:; filename=\"(.*?)\")?",
  889. std::regex_constants::icase);
  890. auto dash_boundary = dash + boundary;
  891. auto pos = body.find(dash_boundary);
  892. if (pos != 0) { return false; }
  893. pos += dash_boundary.size();
  894. auto next_pos = body.find(crlf, pos);
  895. if (next_pos == std::string::npos) { return false; }
  896. pos = next_pos + crlf.size();
  897. while (pos < body.size()) {
  898. next_pos = body.find(crlf, pos);
  899. if (next_pos == std::string::npos) { return false; }
  900. std::string name;
  901. MultipartFile file;
  902. auto header = body.substr(pos, (next_pos - pos));
  903. while (pos != next_pos) {
  904. std::smatch m;
  905. if (std::regex_match(header, m, re_content_type)) {
  906. file.content_type = m[1];
  907. } else if (std::regex_match(header, m, re_content_disposition)) {
  908. name = m[1];
  909. file.filename = m[2];
  910. }
  911. pos = next_pos + crlf.size();
  912. next_pos = body.find(crlf, pos);
  913. if (next_pos == std::string::npos) { return false; }
  914. header = body.substr(pos, (next_pos - pos));
  915. }
  916. pos = next_pos + crlf.size();
  917. next_pos = body.find(crlf + dash_boundary, pos);
  918. if (next_pos == std::string::npos) { return false; }
  919. file.offset = pos;
  920. file.length = next_pos - pos;
  921. pos = next_pos + crlf.size() + dash_boundary.size();
  922. next_pos = body.find(crlf, pos);
  923. if (next_pos == std::string::npos) { return false; }
  924. files.emplace(name, file);
  925. pos = next_pos + crlf.size();
  926. }
  927. return true;
  928. }
  929. inline std::string to_lower(const char *beg, const char *end) {
  930. std::string out;
  931. auto it = beg;
  932. while (it != end) {
  933. out += ::tolower(*it);
  934. it++;
  935. }
  936. return out;
  937. }
  938. inline void make_range_header_core(std::string &) {}
  939. template <typename uint64_t>
  940. inline void make_range_header_core(std::string &field, uint64_t value) {
  941. if (!field.empty()) { field += ", "; }
  942. field += std::to_string(value) + "-";
  943. }
  944. template <typename uint64_t, typename... Args>
  945. inline void make_range_header_core(std::string &field, uint64_t value1,
  946. uint64_t value2, Args... args) {
  947. if (!field.empty()) { field += ", "; }
  948. field += std::to_string(value1) + "-" + std::to_string(value2);
  949. make_range_header_core(field, args...);
  950. }
  951. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  952. inline bool can_compress(const std::string &content_type) {
  953. return !content_type.find("text/") || content_type == "image/svg+xml" ||
  954. content_type == "application/javascript" ||
  955. content_type == "application/json" ||
  956. content_type == "application/xml" ||
  957. content_type == "application/xhtml+xml";
  958. }
  959. inline void compress(std::string &content) {
  960. z_stream strm;
  961. strm.zalloc = Z_NULL;
  962. strm.zfree = Z_NULL;
  963. strm.opaque = Z_NULL;
  964. auto ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  965. Z_DEFAULT_STRATEGY);
  966. if (ret != Z_OK) { return; }
  967. strm.avail_in = content.size();
  968. strm.next_in = (Bytef *)content.data();
  969. std::string compressed;
  970. const auto bufsiz = 16384;
  971. char buff[bufsiz];
  972. do {
  973. strm.avail_out = bufsiz;
  974. strm.next_out = (Bytef *)buff;
  975. deflate(&strm, Z_FINISH);
  976. compressed.append(buff, bufsiz - strm.avail_out);
  977. } while (strm.avail_out == 0);
  978. content.swap(compressed);
  979. deflateEnd(&strm);
  980. }
  981. inline void decompress(std::string &content) {
  982. z_stream strm;
  983. strm.zalloc = Z_NULL;
  984. strm.zfree = Z_NULL;
  985. strm.opaque = Z_NULL;
  986. // 15 is the value of wbits, which should be at the maximum possible value to
  987. // ensure that any gzip stream can be decoded. The offset of 16 specifies that
  988. // the stream to decompress will be formatted with a gzip wrapper.
  989. auto ret = inflateInit2(&strm, 16 + 15);
  990. if (ret != Z_OK) { return; }
  991. strm.avail_in = content.size();
  992. strm.next_in = (Bytef *)content.data();
  993. std::string decompressed;
  994. const auto bufsiz = 16384;
  995. char buff[bufsiz];
  996. do {
  997. strm.avail_out = bufsiz;
  998. strm.next_out = (Bytef *)buff;
  999. inflate(&strm, Z_NO_FLUSH);
  1000. decompressed.append(buff, bufsiz - strm.avail_out);
  1001. } while (strm.avail_out == 0);
  1002. content.swap(decompressed);
  1003. inflateEnd(&strm);
  1004. }
  1005. #endif
  1006. #ifdef _WIN32
  1007. class WSInit {
  1008. public:
  1009. WSInit() {
  1010. WSADATA wsaData;
  1011. WSAStartup(0x0002, &wsaData);
  1012. }
  1013. ~WSInit() { WSACleanup(); }
  1014. };
  1015. static WSInit wsinit_;
  1016. #endif
  1017. } // namespace detail
  1018. // Header utilities
  1019. template <typename uint64_t, typename... Args>
  1020. inline std::pair<std::string, std::string> make_range_header(uint64_t value,
  1021. Args... args) {
  1022. std::string field;
  1023. detail::make_range_header_core(field, value, args...);
  1024. field.insert(0, "bytes=");
  1025. return std::make_pair("Range", field);
  1026. }
  1027. // Request implementation
  1028. inline bool Request::has_header(const char *key) const {
  1029. return detail::has_header(headers, key);
  1030. }
  1031. inline std::string Request::get_header_value(const char *key, size_t id) const {
  1032. return detail::get_header_value(headers, key, id, "");
  1033. }
  1034. inline size_t Request::get_header_value_count(const char *key) const {
  1035. auto r = headers.equal_range(key);
  1036. return std::distance(r.first, r.second);
  1037. }
  1038. inline void Request::set_header(const char *key, const char *val) {
  1039. headers.emplace(key, val);
  1040. }
  1041. inline bool Request::has_param(const char *key) const {
  1042. return params.find(key) != params.end();
  1043. }
  1044. inline std::string Request::get_param_value(const char *key, size_t id) const {
  1045. auto it = params.find(key);
  1046. std::advance(it, id);
  1047. if (it != params.end()) { return it->second; }
  1048. return std::string();
  1049. }
  1050. inline size_t Request::get_param_value_count(const char *key) const {
  1051. auto r = params.equal_range(key);
  1052. return std::distance(r.first, r.second);
  1053. }
  1054. inline bool Request::has_file(const char *key) const {
  1055. return files.find(key) != files.end();
  1056. }
  1057. inline MultipartFile Request::get_file_value(const char *key) const {
  1058. auto it = files.find(key);
  1059. if (it != files.end()) { return it->second; }
  1060. return MultipartFile();
  1061. }
  1062. // Response implementation
  1063. inline bool Response::has_header(const char *key) const {
  1064. return headers.find(key) != headers.end();
  1065. }
  1066. inline std::string Response::get_header_value(const char *key,
  1067. size_t id) const {
  1068. return detail::get_header_value(headers, key, id, "");
  1069. }
  1070. inline size_t Response::get_header_value_count(const char *key) const {
  1071. auto r = headers.equal_range(key);
  1072. return std::distance(r.first, r.second);
  1073. }
  1074. inline void Response::set_header(const char *key, const char *val) {
  1075. headers.emplace(key, val);
  1076. }
  1077. inline void Response::set_redirect(const char *url) {
  1078. set_header("Location", url);
  1079. status = 302;
  1080. }
  1081. inline void Response::set_content(const char *s, size_t n,
  1082. const char *content_type) {
  1083. body.assign(s, n);
  1084. set_header("Content-Type", content_type);
  1085. }
  1086. inline void Response::set_content(const std::string &s,
  1087. const char *content_type) {
  1088. body = s;
  1089. set_header("Content-Type", content_type);
  1090. }
  1091. // Rstream implementation
  1092. template <typename... Args>
  1093. inline void Stream::write_format(const char *fmt, const Args &... args) {
  1094. const auto bufsiz = 2048;
  1095. char buf[bufsiz];
  1096. #if defined(_MSC_VER) && _MSC_VER < 1900
  1097. auto n = _snprintf_s(buf, bufsiz, bufsiz - 1, fmt, args...);
  1098. #else
  1099. auto n = snprintf(buf, bufsiz - 1, fmt, args...);
  1100. #endif
  1101. if (n > 0) {
  1102. if (n >= bufsiz - 1) {
  1103. std::vector<char> glowable_buf(bufsiz);
  1104. while (n >= static_cast<int>(glowable_buf.size() - 1)) {
  1105. glowable_buf.resize(glowable_buf.size() * 2);
  1106. #if defined(_MSC_VER) && _MSC_VER < 1900
  1107. n = _snprintf_s(&glowable_buf[0], glowable_buf.size(),
  1108. glowable_buf.size() - 1, fmt, args...);
  1109. #else
  1110. n = snprintf(&glowable_buf[0], glowable_buf.size() - 1, fmt, args...);
  1111. #endif
  1112. }
  1113. write(&glowable_buf[0], n);
  1114. } else {
  1115. write(buf, n);
  1116. }
  1117. }
  1118. }
  1119. // Socket stream implementation
  1120. inline SocketStream::SocketStream(socket_t sock) : sock_(sock) {}
  1121. inline SocketStream::~SocketStream() {}
  1122. inline int SocketStream::read(char *ptr, size_t size) {
  1123. return recv(sock_, ptr, static_cast<int>(size), 0);
  1124. }
  1125. inline int SocketStream::write(const char *ptr, size_t size) {
  1126. return send(sock_, ptr, static_cast<int>(size), 0);
  1127. }
  1128. inline int SocketStream::write(const char *ptr) {
  1129. return write(ptr, strlen(ptr));
  1130. }
  1131. inline std::string SocketStream::get_remote_addr() const {
  1132. return detail::get_remote_addr(sock_);
  1133. }
  1134. // Buffer stream implementation
  1135. inline int BufferStream::read(char *ptr, size_t size) {
  1136. #if defined(_MSC_VER) && _MSC_VER < 1900
  1137. return static_cast<int>(buffer._Copy_s(ptr, size, size));
  1138. #else
  1139. return static_cast<int>(buffer.copy(ptr, size));
  1140. #endif
  1141. }
  1142. inline int BufferStream::write(const char *ptr, size_t size) {
  1143. buffer.append(ptr, size);
  1144. return static_cast<int>(size);
  1145. }
  1146. inline int BufferStream::write(const char *ptr) {
  1147. size_t size = strlen(ptr);
  1148. buffer.append(ptr, size);
  1149. return static_cast<int>(size);
  1150. }
  1151. inline std::string BufferStream::get_remote_addr() const { return ""; }
  1152. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  1153. // HTTP server implementation
  1154. inline Server::Server()
  1155. : keep_alive_max_count_(5), is_running_(false), svr_sock_(INVALID_SOCKET),
  1156. running_threads_(0) {
  1157. #ifndef _WIN32
  1158. signal(SIGPIPE, SIG_IGN);
  1159. #endif
  1160. }
  1161. inline Server::~Server() {}
  1162. inline Server &Server::Get(const char *pattern, Handler handler) {
  1163. get_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  1164. return *this;
  1165. }
  1166. inline Server &Server::Post(const char *pattern, Handler handler) {
  1167. post_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  1168. return *this;
  1169. }
  1170. inline Server &Server::Put(const char *pattern, Handler handler) {
  1171. put_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  1172. return *this;
  1173. }
  1174. inline Server &Server::Patch(const char *pattern, Handler handler) {
  1175. patch_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  1176. return *this;
  1177. }
  1178. inline Server &Server::Delete(const char *pattern, Handler handler) {
  1179. delete_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  1180. return *this;
  1181. }
  1182. inline Server &Server::Options(const char *pattern, Handler handler) {
  1183. options_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  1184. return *this;
  1185. }
  1186. inline bool Server::set_base_dir(const char *path) {
  1187. if (detail::is_dir(path)) {
  1188. base_dir_ = path;
  1189. return true;
  1190. }
  1191. return false;
  1192. }
  1193. inline void Server::set_error_handler(Handler handler) {
  1194. error_handler_ = handler;
  1195. }
  1196. inline void Server::set_logger(Logger logger) { logger_ = logger; }
  1197. inline void Server::set_keep_alive_max_count(size_t count) {
  1198. keep_alive_max_count_ = count;
  1199. }
  1200. inline int Server::bind_to_any_port(const char *host, int socket_flags) {
  1201. return bind_internal(host, 0, socket_flags);
  1202. }
  1203. inline bool Server::listen_after_bind() { return listen_internal(); }
  1204. inline bool Server::listen(const char *host, int port, int socket_flags) {
  1205. if (bind_internal(host, port, socket_flags) < 0) return false;
  1206. return listen_internal();
  1207. }
  1208. inline bool Server::is_running() const { return is_running_; }
  1209. inline void Server::stop() {
  1210. if (is_running_) {
  1211. assert(svr_sock_ != INVALID_SOCKET);
  1212. auto sock = svr_sock_;
  1213. svr_sock_ = INVALID_SOCKET;
  1214. detail::shutdown_socket(sock);
  1215. detail::close_socket(sock);
  1216. }
  1217. }
  1218. inline bool Server::parse_request_line(const char *s, Request &req) {
  1219. static std::regex re("(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) "
  1220. "(([^?]+)(?:\\?(.+?))?) (HTTP/1\\.[01])\r\n");
  1221. std::cmatch m;
  1222. if (std::regex_match(s, m, re)) {
  1223. req.version = std::string(m[5]);
  1224. req.method = std::string(m[1]);
  1225. req.target = std::string(m[2]);
  1226. req.path = detail::decode_url(m[3]);
  1227. // Parse query text
  1228. auto len = std::distance(m[4].first, m[4].second);
  1229. if (len > 0) { detail::parse_query_text(m[4], req.params); }
  1230. return true;
  1231. }
  1232. return false;
  1233. }
  1234. inline void Server::write_response(Stream &strm, bool last_connection,
  1235. const Request &req, Response &res) {
  1236. assert(res.status != -1);
  1237. if (400 <= res.status && error_handler_) { error_handler_(req, res); }
  1238. // Response line
  1239. strm.write_format("HTTP/1.1 %d %s\r\n", res.status,
  1240. detail::status_message(res.status));
  1241. // Headers
  1242. if (last_connection || req.get_header_value("Connection") == "close") {
  1243. res.set_header("Connection", "close");
  1244. }
  1245. if (!last_connection && req.get_header_value("Connection") == "Keep-Alive") {
  1246. res.set_header("Connection", "Keep-Alive");
  1247. }
  1248. if (res.body.empty()) {
  1249. if (!res.has_header("Content-Length")) {
  1250. if (res.streamcb) {
  1251. // Streamed response
  1252. res.set_header("Transfer-Encoding", "chunked");
  1253. } else {
  1254. res.set_header("Content-Length", "0");
  1255. }
  1256. }
  1257. } else {
  1258. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1259. // TODO: 'Accpet-Encoding' has gzip, not gzip;q=0
  1260. const auto &encodings = req.get_header_value("Accept-Encoding");
  1261. if (encodings.find("gzip") != std::string::npos &&
  1262. detail::can_compress(res.get_header_value("Content-Type"))) {
  1263. detail::compress(res.body);
  1264. res.set_header("Content-Encoding", "gzip");
  1265. }
  1266. #endif
  1267. if (!res.has_header("Content-Type")) {
  1268. res.set_header("Content-Type", "text/plain");
  1269. }
  1270. auto length = std::to_string(res.body.size());
  1271. res.set_header("Content-Length", length.c_str());
  1272. }
  1273. detail::write_headers(strm, res);
  1274. // Body
  1275. if (req.method != "HEAD") {
  1276. if (!res.body.empty()) {
  1277. strm.write(res.body.c_str(), res.body.size());
  1278. } else if (res.streamcb) {
  1279. bool chunked_response = !res.has_header("Content-Length");
  1280. uint64_t offset = 0;
  1281. bool data_available = true;
  1282. while (data_available) {
  1283. std::string chunk = res.streamcb(offset);
  1284. offset += chunk.size();
  1285. data_available = !chunk.empty();
  1286. // Emit chunked response header and footer for each chunk
  1287. if (chunked_response)
  1288. chunk = detail::from_i_to_hex(chunk.size()) + "\r\n" + chunk + "\r\n";
  1289. if (strm.write(chunk.c_str(), chunk.size()) < 0) break; // Stop on error
  1290. }
  1291. }
  1292. }
  1293. // Log
  1294. if (logger_) { logger_(req, res); }
  1295. }
  1296. inline bool Server::handle_file_request(Request &req, Response &res) {
  1297. if (!base_dir_.empty() && detail::is_valid_path(req.path)) {
  1298. std::string path = base_dir_ + req.path;
  1299. if (!path.empty() && path.back() == '/') { path += "index.html"; }
  1300. if (detail::is_file(path)) {
  1301. detail::read_file(path, res.body);
  1302. auto type = detail::find_content_type(path);
  1303. if (type) { res.set_header("Content-Type", type); }
  1304. res.status = 200;
  1305. return true;
  1306. }
  1307. }
  1308. return false;
  1309. }
  1310. inline socket_t Server::create_server_socket(const char *host, int port,
  1311. int socket_flags) const {
  1312. return detail::create_socket(
  1313. host, port,
  1314. [](socket_t sock, struct addrinfo &ai) -> bool {
  1315. if (::bind(sock, ai.ai_addr, static_cast<int>(ai.ai_addrlen))) {
  1316. return false;
  1317. }
  1318. if (::listen(sock, 5)) { // Listen through 5 channels
  1319. return false;
  1320. }
  1321. return true;
  1322. },
  1323. socket_flags);
  1324. }
  1325. inline int Server::bind_internal(const char *host, int port, int socket_flags) {
  1326. if (!is_valid()) { return -1; }
  1327. svr_sock_ = create_server_socket(host, port, socket_flags);
  1328. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  1329. if (port == 0) {
  1330. struct sockaddr_storage address;
  1331. socklen_t len = sizeof(address);
  1332. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&address),
  1333. &len) == -1) {
  1334. return -1;
  1335. }
  1336. if (address.ss_family == AF_INET) {
  1337. return ntohs(reinterpret_cast<struct sockaddr_in *>(&address)->sin_port);
  1338. } else if (address.ss_family == AF_INET6) {
  1339. return ntohs(
  1340. reinterpret_cast<struct sockaddr_in6 *>(&address)->sin6_port);
  1341. } else {
  1342. return -1;
  1343. }
  1344. } else {
  1345. return port;
  1346. }
  1347. }
  1348. inline bool Server::listen_internal() {
  1349. auto ret = true;
  1350. is_running_ = true;
  1351. for (;;) {
  1352. auto val = detail::select_read(svr_sock_, 0, 100000);
  1353. if (val == 0) { // Timeout
  1354. if (svr_sock_ == INVALID_SOCKET) {
  1355. // The server socket was closed by 'stop' method.
  1356. break;
  1357. }
  1358. continue;
  1359. }
  1360. socket_t sock = accept(svr_sock_, NULL, NULL);
  1361. if (sock == INVALID_SOCKET) {
  1362. if (svr_sock_ != INVALID_SOCKET) {
  1363. detail::close_socket(svr_sock_);
  1364. ret = false;
  1365. } else {
  1366. ; // The server socket was closed by user.
  1367. }
  1368. break;
  1369. }
  1370. // TODO: Use thread pool...
  1371. std::thread([=]() {
  1372. {
  1373. std::lock_guard<std::mutex> guard(running_threads_mutex_);
  1374. running_threads_++;
  1375. }
  1376. read_and_close_socket(sock);
  1377. {
  1378. std::lock_guard<std::mutex> guard(running_threads_mutex_);
  1379. running_threads_--;
  1380. }
  1381. })
  1382. .detach();
  1383. }
  1384. // TODO: Use thread pool...
  1385. for (;;) {
  1386. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1387. std::lock_guard<std::mutex> guard(running_threads_mutex_);
  1388. if (!running_threads_) { break; }
  1389. }
  1390. is_running_ = false;
  1391. return ret;
  1392. }
  1393. inline bool Server::routing(Request &req, Response &res) {
  1394. if (req.method == "GET" && handle_file_request(req, res)) { return true; }
  1395. if (req.method == "GET" || req.method == "HEAD") {
  1396. return dispatch_request(req, res, get_handlers_);
  1397. } else if (req.method == "POST") {
  1398. return dispatch_request(req, res, post_handlers_);
  1399. } else if (req.method == "PUT") {
  1400. return dispatch_request(req, res, put_handlers_);
  1401. } else if (req.method == "PATCH") {
  1402. return dispatch_request(req, res, patch_handlers_);
  1403. } else if (req.method == "DELETE") {
  1404. return dispatch_request(req, res, delete_handlers_);
  1405. } else if (req.method == "OPTIONS") {
  1406. return dispatch_request(req, res, options_handlers_);
  1407. }
  1408. return false;
  1409. }
  1410. inline bool Server::dispatch_request(Request &req, Response &res,
  1411. Handlers &handlers) {
  1412. for (const auto &x : handlers) {
  1413. const auto &pattern = x.first;
  1414. const auto &handler = x.second;
  1415. if (std::regex_match(req.path, req.matches, pattern)) {
  1416. handler(req, res);
  1417. return true;
  1418. }
  1419. }
  1420. return false;
  1421. }
  1422. inline bool Server::process_request(Stream &strm, bool last_connection,
  1423. bool &connection_close) {
  1424. const auto bufsiz = 2048;
  1425. char buf[bufsiz];
  1426. detail::stream_line_reader reader(strm, buf, bufsiz);
  1427. // Connection has been closed on client
  1428. if (!reader.getline()) { return false; }
  1429. Request req;
  1430. Response res;
  1431. res.version = "HTTP/1.1";
  1432. // Check if the request URI doesn't exceed the limit
  1433. if (reader.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  1434. res.status = 414;
  1435. write_response(strm, last_connection, req, res);
  1436. return true;
  1437. }
  1438. // Request line and headers
  1439. if (!parse_request_line(reader.ptr(), req) ||
  1440. !detail::read_headers(strm, req.headers)) {
  1441. res.status = 400;
  1442. write_response(strm, last_connection, req, res);
  1443. return true;
  1444. }
  1445. if (req.get_header_value("Connection") == "close") {
  1446. connection_close = true;
  1447. }
  1448. req.set_header("REMOTE_ADDR", strm.get_remote_addr().c_str());
  1449. // Body
  1450. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH") {
  1451. if (!detail::read_content(strm, req)) {
  1452. res.status = 400;
  1453. write_response(strm, last_connection, req, res);
  1454. return true;
  1455. }
  1456. const auto &content_type = req.get_header_value("Content-Type");
  1457. if (req.get_header_value("Content-Encoding") == "gzip") {
  1458. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1459. detail::decompress(req.body);
  1460. #else
  1461. res.status = 415;
  1462. write_response(strm, last_connection, req, res);
  1463. return true;
  1464. #endif
  1465. }
  1466. if (!content_type.find("application/x-www-form-urlencoded")) {
  1467. detail::parse_query_text(req.body, req.params);
  1468. } else if (!content_type.find("multipart/form-data")) {
  1469. std::string boundary;
  1470. if (!detail::parse_multipart_boundary(content_type, boundary) ||
  1471. !detail::parse_multipart_formdata(boundary, req.body, req.files)) {
  1472. res.status = 400;
  1473. write_response(strm, last_connection, req, res);
  1474. return true;
  1475. }
  1476. }
  1477. }
  1478. if (routing(req, res)) {
  1479. if (res.status == -1) { res.status = 200; }
  1480. } else {
  1481. res.status = 404;
  1482. }
  1483. write_response(strm, last_connection, req, res);
  1484. return true;
  1485. }
  1486. inline bool Server::is_valid() const { return true; }
  1487. inline bool Server::read_and_close_socket(socket_t sock) {
  1488. return detail::read_and_close_socket(
  1489. sock, keep_alive_max_count_,
  1490. [this](Stream &strm, bool last_connection, bool &connection_close) {
  1491. return process_request(strm, last_connection, connection_close);
  1492. });
  1493. }
  1494. // HTTP client implementation
  1495. inline Client::Client(const char *host, int port, time_t timeout_sec)
  1496. : host_(host), port_(port), timeout_sec_(timeout_sec),
  1497. host_and_port_(host_ + ":" + std::to_string(port_)) {}
  1498. inline Client::~Client() {}
  1499. inline bool Client::is_valid() const { return true; }
  1500. inline socket_t Client::create_client_socket() const {
  1501. return detail::create_socket(
  1502. host_.c_str(), port_, [=](socket_t sock, struct addrinfo &ai) -> bool {
  1503. detail::set_nonblocking(sock, true);
  1504. auto ret = connect(sock, ai.ai_addr, static_cast<int>(ai.ai_addrlen));
  1505. if (ret < 0) {
  1506. if (detail::is_connection_error() ||
  1507. !detail::wait_until_socket_is_ready(sock, timeout_sec_, 0)) {
  1508. detail::close_socket(sock);
  1509. return false;
  1510. }
  1511. }
  1512. detail::set_nonblocking(sock, false);
  1513. return true;
  1514. });
  1515. }
  1516. inline bool Client::read_response_line(Stream &strm, Response &res) {
  1517. const auto bufsiz = 2048;
  1518. char buf[bufsiz];
  1519. detail::stream_line_reader reader(strm, buf, bufsiz);
  1520. if (!reader.getline()) { return false; }
  1521. const static std::regex re("(HTTP/1\\.[01]) (\\d+?) .*\r\n");
  1522. std::cmatch m;
  1523. if (std::regex_match(reader.ptr(), m, re)) {
  1524. res.version = std::string(m[1]);
  1525. res.status = std::stoi(std::string(m[2]));
  1526. }
  1527. return true;
  1528. }
  1529. inline bool Client::send(Request &req, Response &res) {
  1530. if (req.path.empty()) { return false; }
  1531. auto sock = create_client_socket();
  1532. if (sock == INVALID_SOCKET) { return false; }
  1533. return read_and_close_socket(sock, req, res);
  1534. }
  1535. inline void Client::write_request(Stream &strm, Request &req) {
  1536. BufferStream bstrm;
  1537. // Request line
  1538. auto path = detail::encode_url(req.path);
  1539. bstrm.write_format("%s %s HTTP/1.1\r\n", req.method.c_str(), path.c_str());
  1540. // Headers
  1541. if (!req.has_header("Host")) {
  1542. if (is_ssl()) {
  1543. if (port_ == 443) {
  1544. req.set_header("Host", host_.c_str());
  1545. } else {
  1546. req.set_header("Host", host_and_port_.c_str());
  1547. }
  1548. } else {
  1549. if (port_ == 80) {
  1550. req.set_header("Host", host_.c_str());
  1551. } else {
  1552. req.set_header("Host", host_and_port_.c_str());
  1553. }
  1554. }
  1555. }
  1556. if (!req.has_header("Accept")) { req.set_header("Accept", "*/*"); }
  1557. if (!req.has_header("User-Agent")) {
  1558. req.set_header("User-Agent", "cpp-httplib/0.2");
  1559. }
  1560. // TODO: Support KeepAlive connection
  1561. // if (!req.has_header("Connection")) {
  1562. req.set_header("Connection", "close");
  1563. // }
  1564. if (req.body.empty()) {
  1565. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH") {
  1566. req.set_header("Content-Length", "0");
  1567. }
  1568. } else {
  1569. if (!req.has_header("Content-Type")) {
  1570. req.set_header("Content-Type", "text/plain");
  1571. }
  1572. if (!req.has_header("Content-Length")) {
  1573. auto length = std::to_string(req.body.size());
  1574. req.set_header("Content-Length", length.c_str());
  1575. }
  1576. }
  1577. detail::write_headers(bstrm, req);
  1578. // Body
  1579. if (!req.body.empty()) { bstrm.write(req.body.c_str(), req.body.size()); }
  1580. // Flush buffer
  1581. auto &data = bstrm.get_buffer();
  1582. strm.write(data.data(), data.size());
  1583. }
  1584. inline bool Client::process_request(Stream &strm, Request &req, Response &res,
  1585. bool &connection_close) {
  1586. // Send request
  1587. write_request(strm, req);
  1588. // Receive response and headers
  1589. if (!read_response_line(strm, res) ||
  1590. !detail::read_headers(strm, res.headers)) {
  1591. return false;
  1592. }
  1593. if (res.get_header_value("Connection") == "close" ||
  1594. res.version == "HTTP/1.0") {
  1595. connection_close = true;
  1596. }
  1597. // Body
  1598. if (req.method != "HEAD") {
  1599. if (!detail::read_content(strm, res, req.progress)) { return false; }
  1600. if (res.get_header_value("Content-Encoding") == "gzip") {
  1601. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1602. detail::decompress(res.body);
  1603. #else
  1604. return false;
  1605. #endif
  1606. }
  1607. }
  1608. return true;
  1609. }
  1610. inline bool Client::read_and_close_socket(socket_t sock, Request &req,
  1611. Response &res) {
  1612. return detail::read_and_close_socket(
  1613. sock, 0,
  1614. [&](Stream &strm, bool /*last_connection*/, bool &connection_close) {
  1615. return process_request(strm, req, res, connection_close);
  1616. });
  1617. }
  1618. inline bool Client::is_ssl() const { return false; }
  1619. inline std::shared_ptr<Response> Client::Get(const char *path,
  1620. Progress progress) {
  1621. return Get(path, Headers(), progress);
  1622. }
  1623. inline std::shared_ptr<Response>
  1624. Client::Get(const char *path, const Headers &headers, Progress progress) {
  1625. Request req;
  1626. req.method = "GET";
  1627. req.path = path;
  1628. req.headers = headers;
  1629. req.progress = progress;
  1630. auto res = std::make_shared<Response>();
  1631. return send(req, *res) ? res : nullptr;
  1632. }
  1633. inline std::shared_ptr<Response> Client::Head(const char *path) {
  1634. return Head(path, Headers());
  1635. }
  1636. inline std::shared_ptr<Response> Client::Head(const char *path,
  1637. const Headers &headers) {
  1638. Request req;
  1639. req.method = "HEAD";
  1640. req.headers = headers;
  1641. req.path = path;
  1642. auto res = std::make_shared<Response>();
  1643. return send(req, *res) ? res : nullptr;
  1644. }
  1645. inline std::shared_ptr<Response> Client::Post(const char *path,
  1646. const std::string &body,
  1647. const char *content_type) {
  1648. return Post(path, Headers(), body, content_type);
  1649. }
  1650. inline std::shared_ptr<Response> Client::Post(const char *path,
  1651. const Headers &headers,
  1652. const std::string &body,
  1653. const char *content_type) {
  1654. Request req;
  1655. req.method = "POST";
  1656. req.headers = headers;
  1657. req.path = path;
  1658. req.headers.emplace("Content-Type", content_type);
  1659. req.body = body;
  1660. auto res = std::make_shared<Response>();
  1661. return send(req, *res) ? res : nullptr;
  1662. }
  1663. inline std::shared_ptr<Response> Client::Post(const char *path,
  1664. const Params &params) {
  1665. return Post(path, Headers(), params);
  1666. }
  1667. inline std::shared_ptr<Response>
  1668. Client::Post(const char *path, const Headers &headers, const Params &params) {
  1669. std::string query;
  1670. for (auto it = params.begin(); it != params.end(); ++it) {
  1671. if (it != params.begin()) { query += "&"; }
  1672. query += it->first;
  1673. query += "=";
  1674. query += it->second;
  1675. }
  1676. return Post(path, headers, query, "application/x-www-form-urlencoded");
  1677. }
  1678. inline std::shared_ptr<Response> Client::Put(const char *path,
  1679. const std::string &body,
  1680. const char *content_type) {
  1681. return Put(path, Headers(), body, content_type);
  1682. }
  1683. inline std::shared_ptr<Response> Client::Put(const char *path,
  1684. const Headers &headers,
  1685. const std::string &body,
  1686. const char *content_type) {
  1687. Request req;
  1688. req.method = "PUT";
  1689. req.headers = headers;
  1690. req.path = path;
  1691. req.headers.emplace("Content-Type", content_type);
  1692. req.body = body;
  1693. auto res = std::make_shared<Response>();
  1694. return send(req, *res) ? res : nullptr;
  1695. }
  1696. inline std::shared_ptr<Response> Client::Patch(const char *path,
  1697. const std::string &body,
  1698. const char *content_type) {
  1699. return Patch(path, Headers(), body, content_type);
  1700. }
  1701. inline std::shared_ptr<Response> Client::Patch(const char *path,
  1702. const Headers &headers,
  1703. const std::string &body,
  1704. const char *content_type) {
  1705. Request req;
  1706. req.method = "PATCH";
  1707. req.headers = headers;
  1708. req.path = path;
  1709. req.headers.emplace("Content-Type", content_type);
  1710. req.body = body;
  1711. auto res = std::make_shared<Response>();
  1712. return send(req, *res) ? res : nullptr;
  1713. }
  1714. inline std::shared_ptr<Response> Client::Delete(const char *path) {
  1715. return Delete(path, Headers());
  1716. }
  1717. inline std::shared_ptr<Response> Client::Delete(const char *path,
  1718. const Headers &headers) {
  1719. Request req;
  1720. req.method = "DELETE";
  1721. req.path = path;
  1722. req.headers = headers;
  1723. auto res = std::make_shared<Response>();
  1724. return send(req, *res) ? res : nullptr;
  1725. }
  1726. inline std::shared_ptr<Response> Client::Options(const char *path) {
  1727. return Options(path, Headers());
  1728. }
  1729. inline std::shared_ptr<Response> Client::Options(const char *path,
  1730. const Headers &headers) {
  1731. Request req;
  1732. req.method = "OPTIONS";
  1733. req.path = path;
  1734. req.headers = headers;
  1735. auto res = std::make_shared<Response>();
  1736. return send(req, *res) ? res : nullptr;
  1737. }
  1738. /*
  1739. * SSL Implementation
  1740. */
  1741. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1742. namespace detail {
  1743. template <typename U, typename V, typename T>
  1744. inline bool
  1745. read_and_close_socket_ssl(socket_t sock, size_t keep_alive_max_count,
  1746. // TODO: OpenSSL 1.0.2 occasionally crashes...
  1747. // The upcoming 1.1.0 is going to be thread safe.
  1748. SSL_CTX *ctx, std::mutex &ctx_mutex,
  1749. U SSL_connect_or_accept, V setup, T callback) {
  1750. SSL *ssl = nullptr;
  1751. {
  1752. std::lock_guard<std::mutex> guard(ctx_mutex);
  1753. ssl = SSL_new(ctx);
  1754. if (!ssl) { return false; }
  1755. }
  1756. auto bio = BIO_new_socket(sock, BIO_NOCLOSE);
  1757. SSL_set_bio(ssl, bio, bio);
  1758. setup(ssl);
  1759. SSL_connect_or_accept(ssl);
  1760. bool ret = false;
  1761. if (keep_alive_max_count > 0) {
  1762. auto count = keep_alive_max_count;
  1763. while (count > 0 &&
  1764. detail::select_read(sock, CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND,
  1765. CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND) > 0) {
  1766. SSLSocketStream strm(sock, ssl);
  1767. auto last_connection = count == 1;
  1768. auto connection_close = false;
  1769. ret = callback(strm, last_connection, connection_close);
  1770. if (!ret || connection_close) { break; }
  1771. count--;
  1772. }
  1773. } else {
  1774. SSLSocketStream strm(sock, ssl);
  1775. auto dummy_connection_close = false;
  1776. ret = callback(strm, true, dummy_connection_close);
  1777. }
  1778. SSL_shutdown(ssl);
  1779. {
  1780. std::lock_guard<std::mutex> guard(ctx_mutex);
  1781. SSL_free(ssl);
  1782. }
  1783. close_socket(sock);
  1784. return ret;
  1785. }
  1786. class SSLInit {
  1787. public:
  1788. SSLInit() {
  1789. SSL_load_error_strings();
  1790. SSL_library_init();
  1791. }
  1792. ~SSLInit() { ERR_free_strings(); }
  1793. };
  1794. static SSLInit sslinit_;
  1795. } // namespace detail
  1796. // SSL socket stream implementation
  1797. inline SSLSocketStream::SSLSocketStream(socket_t sock, SSL *ssl)
  1798. : sock_(sock), ssl_(ssl) {}
  1799. inline SSLSocketStream::~SSLSocketStream() {}
  1800. inline int SSLSocketStream::read(char *ptr, size_t size) {
  1801. return SSL_read(ssl_, ptr, size);
  1802. }
  1803. inline int SSLSocketStream::write(const char *ptr, size_t size) {
  1804. return SSL_write(ssl_, ptr, size);
  1805. }
  1806. inline int SSLSocketStream::write(const char *ptr) {
  1807. return write(ptr, strlen(ptr));
  1808. }
  1809. inline std::string SSLSocketStream::get_remote_addr() const {
  1810. return detail::get_remote_addr(sock_);
  1811. }
  1812. // SSL HTTP server implementation
  1813. inline SSLServer::SSLServer(const char *cert_path,
  1814. const char *private_key_path) {
  1815. ctx_ = SSL_CTX_new(SSLv23_server_method());
  1816. if (ctx_) {
  1817. SSL_CTX_set_options(ctx_,
  1818. SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
  1819. SSL_OP_NO_COMPRESSION |
  1820. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  1821. // auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  1822. // SSL_CTX_set_tmp_ecdh(ctx_, ecdh);
  1823. // EC_KEY_free(ecdh);
  1824. if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 ||
  1825. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) !=
  1826. 1) {
  1827. SSL_CTX_free(ctx_);
  1828. ctx_ = nullptr;
  1829. }
  1830. }
  1831. }
  1832. inline SSLServer::~SSLServer() {
  1833. if (ctx_) { SSL_CTX_free(ctx_); }
  1834. }
  1835. inline bool SSLServer::is_valid() const { return ctx_; }
  1836. inline bool SSLServer::read_and_close_socket(socket_t sock) {
  1837. return detail::read_and_close_socket_ssl(
  1838. sock, keep_alive_max_count_, ctx_, ctx_mutex_, SSL_accept,
  1839. [](SSL * /*ssl*/) {},
  1840. [this](Stream &strm, bool last_connection, bool &connection_close) {
  1841. return process_request(strm, last_connection, connection_close);
  1842. });
  1843. }
  1844. // SSL HTTP client implementation
  1845. inline SSLClient::SSLClient(const char *host, int port, time_t timeout_sec)
  1846. : Client(host, port, timeout_sec) {
  1847. ctx_ = SSL_CTX_new(SSLv23_client_method());
  1848. }
  1849. inline SSLClient::~SSLClient() {
  1850. if (ctx_) { SSL_CTX_free(ctx_); }
  1851. }
  1852. inline bool SSLClient::is_valid() const { return ctx_; }
  1853. inline bool SSLClient::read_and_close_socket(socket_t sock, Request &req,
  1854. Response &res) {
  1855. return is_valid() &&
  1856. detail::read_and_close_socket_ssl(
  1857. sock, 0, ctx_, ctx_mutex_, SSL_connect,
  1858. [&](SSL *ssl) { SSL_set_tlsext_host_name(ssl, host_.c_str()); },
  1859. [&](Stream &strm, bool /*last_connection*/,
  1860. bool &connection_close) {
  1861. return process_request(strm, req, res, connection_close);
  1862. });
  1863. }
  1864. inline bool SSLClient::is_ssl() const { return true; }
  1865. #endif
  1866. } // namespace httplib
  1867. #endif // CPPHTTPLIB_HTTPLIB_H
  1868. // vim: et ts=4 sw=4 cin cino={1s ff=unix