httplib.h 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2017 Yuji Hirose. All rights reserved.
  5. // The Boost Software License 1.0
  6. //
  7. #ifndef _CPPHTTPLIB_HTTPLIB_H_
  8. #define _CPPHTTPLIB_HTTPLIB_H_
  9. #ifdef _MSC_VER
  10. #define _CRT_SECURE_NO_WARNINGS
  11. #define _CRT_NONSTDC_NO_DEPRECATE
  12. #ifndef SO_SYNCHRONOUS_NONALERT
  13. #define SO_SYNCHRONOUS_NONALERT 0x20
  14. #endif
  15. #ifndef SO_OPENTYPE
  16. #define SO_OPENTYPE 0x7008
  17. #endif
  18. #if (_MSC_VER < 1900)
  19. #define snprintf _snprintf_s
  20. #endif
  21. #define S_ISREG(m) (((m)&S_IFREG)==S_IFREG)
  22. #define S_ISDIR(m) (((m)&S_IFDIR)==S_IFDIR)
  23. #include <fcntl.h>
  24. #include <io.h>
  25. #include <winsock2.h>
  26. #include <ws2tcpip.h>
  27. #undef min
  28. #undef max
  29. typedef SOCKET socket_t;
  30. #else
  31. #include <pthread.h>
  32. #include <unistd.h>
  33. #include <netdb.h>
  34. #include <cstring>
  35. #include <netinet/in.h>
  36. #include <arpa/inet.h>
  37. #include <signal.h>
  38. #include <sys/socket.h>
  39. typedef int socket_t;
  40. #endif
  41. #include <fstream>
  42. #include <functional>
  43. #include <map>
  44. #include <memory>
  45. #include <regex>
  46. #include <string>
  47. #include <sys/stat.h>
  48. #include <assert.h>
  49. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  50. #include <openssl/ssl.h>
  51. #endif
  52. namespace httplib
  53. {
  54. typedef std::map<std::string, std::string> Map;
  55. typedef std::multimap<std::string, std::string> MultiMap;
  56. typedef std::smatch Match;
  57. struct Request {
  58. std::string method;
  59. std::string path;
  60. MultiMap headers;
  61. std::string body;
  62. Map params;
  63. Match matches;
  64. bool has_header(const char* key) const;
  65. std::string get_header_value(const char* key) const;
  66. void set_header(const char* key, const char* val);
  67. bool has_param(const char* key) const;
  68. };
  69. struct Response {
  70. int status;
  71. MultiMap headers;
  72. std::string body;
  73. bool has_header(const char* key) const;
  74. std::string get_header_value(const char* key) const;
  75. void set_header(const char* key, const char* val);
  76. void set_redirect(const char* url);
  77. void set_content(const char* s, size_t n, const char* content_type);
  78. void set_content(const std::string& s, const char* content_type);
  79. Response() : status(-1) {}
  80. };
  81. class Stream {
  82. public:
  83. virtual ~Stream() {}
  84. virtual int read(char* ptr, size_t size) = 0;
  85. virtual int write(const char* ptr, size_t size1) = 0;
  86. virtual int write(const char* ptr) = 0;
  87. };
  88. class SocketStream : public Stream {
  89. public:
  90. SocketStream(socket_t sock);
  91. virtual ~SocketStream();
  92. virtual int read(char* ptr, size_t size);
  93. virtual int write(const char* ptr, size_t size);
  94. virtual int write(const char* ptr);
  95. private:
  96. socket_t sock_;
  97. };
  98. class Server {
  99. public:
  100. typedef std::function<void (const Request&, Response&)> Handler;
  101. typedef std::function<void (const Request&, const Response&)> Logger;
  102. Server();
  103. virtual ~Server();
  104. void get(const char* pattern, Handler handler);
  105. void post(const char* pattern, Handler handler);
  106. bool set_base_dir(const char* path);
  107. void set_error_handler(Handler handler);
  108. void set_logger(Logger logger);
  109. bool listen(const char* host, int port, int socket_flags = 0);
  110. void stop();
  111. protected:
  112. void process_request(Stream& strm);
  113. private:
  114. typedef std::vector<std::pair<std::regex, Handler>> Handlers;
  115. bool routing(Request& req, Response& res);
  116. bool handle_file_request(Request& req, Response& res);
  117. bool dispatch_request(Request& req, Response& res, Handlers& handlers);
  118. bool read_request_line(Stream& strm, Request& req);
  119. virtual bool read_and_close_socket(socket_t sock);
  120. socket_t svr_sock_;
  121. std::string base_dir_;
  122. Handlers get_handlers_;
  123. Handlers post_handlers_;
  124. Handler error_handler_;
  125. Logger logger_;
  126. };
  127. class Client {
  128. public:
  129. Client(const char* host, int port);
  130. virtual ~Client();
  131. std::shared_ptr<Response> get(const char* path);
  132. std::shared_ptr<Response> head(const char* path);
  133. std::shared_ptr<Response> post(const char* path, const std::string& body, const char* content_type);
  134. std::shared_ptr<Response> post(const char* path, const Map& params);
  135. bool send(const Request& req, Response& res);
  136. protected:
  137. bool process_request(Stream& strm, const Request& req, Response& res);
  138. const std::string host_;
  139. const int port_;
  140. private:
  141. bool read_response_line(Stream& strm, Response& res);
  142. void add_default_headers(Request& req);
  143. virtual bool read_and_close_socket(socket_t sock, const Request& req, Response& res);
  144. };
  145. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  146. class SSLSocketStream : public Stream {
  147. public:
  148. SSLSocketStream(SSL* ssl);
  149. virtual ~SSLSocketStream();
  150. virtual int read(char* ptr, size_t size);
  151. virtual int write(const char* ptr, size_t size);
  152. virtual int write(const char* ptr);
  153. private:
  154. SSL* ssl_;
  155. };
  156. class SSLServer : public Server {
  157. public:
  158. SSLServer(const char* cert_path, const char* private_key_path);
  159. virtual ~SSLServer();
  160. private:
  161. virtual bool read_and_close_socket(socket_t sock);
  162. SSL_CTX* ctx_;
  163. };
  164. class SSLClient : public Client {
  165. public:
  166. SSLClient(const char* host, int port);
  167. virtual ~SSLClient();
  168. private:
  169. virtual bool read_and_close_socket(socket_t sock, const Request& req, Response& res);
  170. SSL_CTX* ctx_;
  171. };
  172. #endif
  173. /*
  174. * Implementation
  175. */
  176. namespace detail {
  177. template <class Fn>
  178. void split(const char* b, const char* e, char d, Fn fn)
  179. {
  180. int i = 0;
  181. int beg = 0;
  182. while (e ? (b + i != e) : (b[i] != '\0')) {
  183. if (b[i] == d) {
  184. fn(&b[beg], &b[i]);
  185. beg = i + 1;
  186. }
  187. i++;
  188. }
  189. if (i) {
  190. fn(&b[beg], &b[i]);
  191. }
  192. }
  193. inline bool socket_gets(Stream& strm, char* buf, int bufsiz)
  194. {
  195. // TODO: buffering for better performance
  196. size_t i = 0;
  197. for (;;) {
  198. char byte;
  199. auto n = strm.read(&byte, 1);
  200. if (n < 1) {
  201. if (i == 0) {
  202. return false;
  203. } else {
  204. break;
  205. }
  206. }
  207. buf[i++] = byte;
  208. if (byte == '\n') {
  209. break;
  210. }
  211. }
  212. buf[i] = '\0';
  213. return true;
  214. }
  215. template <typename ...Args>
  216. inline void socket_printf(Stream& strm, const char* fmt, const Args& ...args)
  217. {
  218. char buf[BUFSIZ];
  219. auto n = snprintf(buf, BUFSIZ, fmt, args...);
  220. if (n > 0) {
  221. if (n >= BUFSIZ) {
  222. // TODO: buffer size is not large enough...
  223. } else {
  224. strm.write(buf, n);
  225. }
  226. }
  227. }
  228. inline int close_socket(socket_t sock)
  229. {
  230. #ifdef _MSC_VER
  231. return closesocket(sock);
  232. #else
  233. return close(sock);
  234. #endif
  235. }
  236. template <typename T>
  237. inline bool read_and_close_socket(socket_t sock, T callback)
  238. {
  239. SocketStream strm(sock);
  240. auto ret = callback(strm);
  241. close_socket(sock);
  242. return ret;
  243. }
  244. inline int shutdown_socket(socket_t sock)
  245. {
  246. #ifdef _MSC_VER
  247. return shutdown(sock, SD_BOTH);
  248. #else
  249. return shutdown(sock, SHUT_RDWR);
  250. #endif
  251. }
  252. template <typename Fn>
  253. socket_t create_socket(const char* host, int port, Fn fn, int socket_flags = 0)
  254. {
  255. #ifdef _MSC_VER
  256. int opt = SO_SYNCHRONOUS_NONALERT;
  257. setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char*)&opt, sizeof(opt));
  258. #endif
  259. // Get address info
  260. struct addrinfo hints;
  261. struct addrinfo *result;
  262. memset(&hints, 0, sizeof(struct addrinfo));
  263. hints.ai_family = AF_UNSPEC;
  264. hints.ai_socktype = SOCK_STREAM;
  265. hints.ai_flags = socket_flags;
  266. hints.ai_protocol = 0;
  267. auto service = std::to_string(port);
  268. if (getaddrinfo(host, service.c_str(), &hints, &result)) {
  269. return -1;
  270. }
  271. for (auto rp = result; rp; rp = rp->ai_next) {
  272. // Create a socket
  273. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  274. if (sock == -1) {
  275. continue;
  276. }
  277. // Make 'reuse address' option available
  278. int yes = 1;
  279. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(yes));
  280. // bind or connect
  281. if (fn(sock, *rp)) {
  282. freeaddrinfo(result);
  283. return sock;
  284. }
  285. close_socket(sock);
  286. }
  287. freeaddrinfo(result);
  288. return -1;
  289. }
  290. inline socket_t create_server_socket(const char* host, int port, int socket_flags)
  291. {
  292. return create_socket(host, port, [](socket_t sock, struct addrinfo& ai) -> socket_t {
  293. if (::bind(sock, ai.ai_addr, ai.ai_addrlen)) {
  294. return false;
  295. }
  296. if (listen(sock, 5)) { // Listen through 5 channels
  297. return false;
  298. }
  299. return true;
  300. }, socket_flags);
  301. }
  302. inline socket_t create_client_socket(const char* host, int port)
  303. {
  304. return create_socket(host, port, [](socket_t sock, struct addrinfo& ai) -> socket_t {
  305. if (connect(sock, ai.ai_addr, ai.ai_addrlen)) {
  306. return false;
  307. }
  308. return true;
  309. });
  310. }
  311. inline bool is_file(const std::string& s)
  312. {
  313. struct stat st;
  314. return stat(s.c_str(), &st) >= 0 && S_ISREG(st.st_mode);
  315. }
  316. inline bool is_dir(const std::string& s)
  317. {
  318. struct stat st;
  319. return stat(s.c_str(), &st) >= 0 && S_ISDIR(st.st_mode);
  320. }
  321. inline void read_file(const std::string& path, std::string& out)
  322. {
  323. std::ifstream fs(path, std::ios_base::binary);
  324. fs.seekg(0, std::ios_base::end);
  325. auto size = fs.tellg();
  326. fs.seekg(0);
  327. out.resize(static_cast<size_t>(size));
  328. fs.read(&out[0], size);
  329. }
  330. inline std::string file_extension(const std::string& path)
  331. {
  332. std::smatch m;
  333. auto pat = std::regex("\\.([a-zA-Z0-9]+)$");
  334. if (std::regex_search(path, m, pat)) {
  335. return m[1].str();
  336. }
  337. return std::string();
  338. }
  339. inline const char* content_type(const std::string& path)
  340. {
  341. auto ext = detail::file_extension(path);
  342. if (ext == "txt") {
  343. return "text/plain";
  344. } else if (ext == "html") {
  345. return "text/html";
  346. } else if (ext == "js") {
  347. return "text/javascript";
  348. } else if (ext == "css") {
  349. return "text/css";
  350. } else if (ext == "xml") {
  351. return "text/xml";
  352. } else if (ext == "jpeg" || ext == "jpg") {
  353. return "image/jpg";
  354. } else if (ext == "png") {
  355. return "image/png";
  356. } else if (ext == "gif") {
  357. return "image/gif";
  358. } else if (ext == "svg") {
  359. return "image/svg+xml";
  360. } else if (ext == "ico") {
  361. return "image/x-icon";
  362. } else if (ext == "json") {
  363. return "application/json";
  364. } else if (ext == "pdf") {
  365. return "application/pdf";
  366. } else if (ext == "xhtml") {
  367. return "application/xhtml+xml";
  368. }
  369. return nullptr;
  370. }
  371. inline const char* status_message(int status)
  372. {
  373. switch (status) {
  374. case 200: return "OK";
  375. case 400: return "Bad Request";
  376. case 404: return "Not Found";
  377. default:
  378. case 500: return "Internal Server Error";
  379. }
  380. }
  381. inline const char* get_header_value(const MultiMap& map, const char* key, const char* def)
  382. {
  383. auto it = map.find(key);
  384. if (it != map.end()) {
  385. return it->second.c_str();
  386. }
  387. return def;
  388. }
  389. inline int get_header_value_int(const MultiMap& map, const char* key, int def)
  390. {
  391. auto it = map.find(key);
  392. if (it != map.end()) {
  393. return std::stoi(it->second);
  394. }
  395. return def;
  396. }
  397. inline bool read_headers(Stream& strm, MultiMap& headers)
  398. {
  399. static std::regex re("(.+?): (.+?)\r\n");
  400. const auto BUFSIZ_HEADER = 2048;
  401. char buf[BUFSIZ_HEADER];
  402. for (;;) {
  403. if (!socket_gets(strm, buf, BUFSIZ_HEADER)) {
  404. return false;
  405. }
  406. if (!strcmp(buf, "\r\n")) {
  407. break;
  408. }
  409. std::cmatch m;
  410. if (std::regex_match(buf, m, re)) {
  411. auto key = std::string(m[1]);
  412. auto val = std::string(m[2]);
  413. headers.insert(std::make_pair(key, val));
  414. }
  415. }
  416. return true;
  417. }
  418. template <typename T>
  419. bool read_content(Stream& strm, T& x, bool allow_no_content_length)
  420. {
  421. auto len = get_header_value_int(x.headers, "Content-Length", 0);
  422. if (len) {
  423. x.body.assign(len, 0);
  424. auto r = 0;
  425. while (r < len){
  426. auto r_incr = strm.read(&x.body[r], len - r);
  427. if (r_incr <= 0) {
  428. return false;
  429. }
  430. r += r_incr;
  431. }
  432. } else if (allow_no_content_length) {
  433. for (;;) {
  434. char byte;
  435. auto n = strm.read(&byte, 1);
  436. if (n < 1) {
  437. if (x.body.size() == 0) {
  438. return true; // no body
  439. } else {
  440. break;
  441. }
  442. }
  443. x.body += byte;
  444. }
  445. }
  446. return true;
  447. }
  448. template <typename T>
  449. inline void write_headers(Stream& strm, const T& res)
  450. {
  451. strm.write("Connection: close\r\n");
  452. for (const auto& x: res.headers) {
  453. if (x.first != "Content-Type" && x.first != "Content-Length") {
  454. socket_printf(strm, "%s: %s\r\n", x.first.c_str(), x.second.c_str());
  455. }
  456. }
  457. auto t = get_header_value(res.headers, "Content-Type", "text/plain");
  458. socket_printf(strm, "Content-Type: %s\r\n", t);
  459. socket_printf(strm, "Content-Length: %ld\r\n", res.body.size());
  460. strm.write("\r\n");
  461. }
  462. inline void write_response(Stream& strm, const Request& req, const Response& res)
  463. {
  464. socket_printf(strm, "HTTP/1.0 %d %s\r\n", res.status, status_message(res.status));
  465. write_headers(strm, res);
  466. if (!res.body.empty() && req.method != "HEAD") {
  467. strm.write(res.body.c_str(), res.body.size());
  468. }
  469. }
  470. inline std::string encode_url(const std::string& s)
  471. {
  472. std::string result;
  473. for (auto i = 0; s[i]; i++) {
  474. switch (s[i]) {
  475. case ' ': result += "+"; break;
  476. case '\'': result += "%27"; break;
  477. case ',': result += "%2C"; break;
  478. case ':': result += "%3A"; break;
  479. case ';': result += "%3B"; break;
  480. default:
  481. if (s[i] < 0) {
  482. result += '%';
  483. char hex[4];
  484. size_t len = snprintf(hex, sizeof(hex), "%02X", (unsigned char)s[i]);
  485. assert(len == 2);
  486. result.append(hex, len);
  487. } else {
  488. result += s[i];
  489. }
  490. break;
  491. }
  492. }
  493. return result;
  494. }
  495. inline bool is_hex(char c, int& v)
  496. {
  497. if (0x20 <= c && isdigit(c)) {
  498. v = c - '0';
  499. return true;
  500. } else if ('A' <= c && c <= 'F') {
  501. v = c - 'A' + 10;
  502. return true;
  503. } else if ('a' <= c && c <= 'f') {
  504. v = c - 'a' + 10;
  505. return true;
  506. }
  507. return false;
  508. }
  509. inline int from_hex_to_i(const std::string& s, int i, int cnt, int& val)
  510. {
  511. val = 0;
  512. for (; s[i] && cnt; i++, cnt--) {
  513. int v = 0;
  514. if (is_hex(s[i], v)) {
  515. val = val * 16 + v;
  516. } else {
  517. break;
  518. }
  519. }
  520. return --i;
  521. }
  522. inline size_t to_utf8(int code, char* buff)
  523. {
  524. if (code < 0x0080) {
  525. buff[0] = (code & 0x7F);
  526. return 1;
  527. } else if (code < 0x0800) {
  528. buff[0] = (0xC0 | ((code >> 6) & 0x1F));
  529. buff[1] = (0x80 | (code & 0x3F));
  530. return 2;
  531. } else if (code < 0xD800) {
  532. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  533. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  534. buff[2] = (0x80 | (code & 0x3F));
  535. return 3;
  536. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  537. return 0;
  538. } else if (code < 0x10000) {
  539. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  540. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  541. buff[2] = (0x80 | (code & 0x3F));
  542. return 3;
  543. } else if (code < 0x110000) {
  544. buff[0] = (0xF0 | ((code >> 18) & 0x7));
  545. buff[1] = (0x80 | ((code >> 12) & 0x3F));
  546. buff[2] = (0x80 | ((code >> 6) & 0x3F));
  547. buff[3] = (0x80 | (code & 0x3F));
  548. return 4;
  549. }
  550. // NOTREACHED
  551. return 0;
  552. }
  553. inline std::string decode_url(const std::string& s)
  554. {
  555. std::string result;
  556. for (int i = 0; s[i]; i++) {
  557. if (s[i] == '%') {
  558. i++;
  559. assert(s[i]);
  560. if (s[i] == '%') {
  561. result += s[i];
  562. } else if (s[i] == 'u') {
  563. // Unicode
  564. i++;
  565. assert(s[i]);
  566. int val = 0;
  567. i = from_hex_to_i(s, i, 4, val);
  568. char buff[4];
  569. size_t len = to_utf8(val, buff);
  570. if (len > 0) {
  571. result.append(buff, len);
  572. }
  573. } else {
  574. // HEX
  575. int val = 0;
  576. i = from_hex_to_i(s, i, 2, val);
  577. result += val;
  578. }
  579. } else if (s[i] == '+') {
  580. result += ' ';
  581. } else {
  582. result += s[i];
  583. }
  584. }
  585. return result;
  586. }
  587. inline void write_request(Stream& strm, const Request& req)
  588. {
  589. auto path = encode_url(req.path);
  590. socket_printf(strm, "%s %s HTTP/1.0\r\n", req.method.c_str(), path.c_str());
  591. write_headers(strm, req);
  592. if (!req.body.empty()) {
  593. if (req.has_header("application/x-www-form-urlencoded")) {
  594. auto str = encode_url(req.body);
  595. strm.write(str.c_str(), str.size());
  596. } else {
  597. strm.write(req.body.c_str(), req.body.size());
  598. }
  599. }
  600. }
  601. inline void parse_query_text(const std::string& s, Map& params)
  602. {
  603. split(&s[0], &s[s.size()], '&', [&](const char* b, const char* e) {
  604. std::string key;
  605. std::string val;
  606. split(b, e, '=', [&](const char* b, const char* e) {
  607. if (key.empty()) {
  608. key.assign(b, e);
  609. } else {
  610. val.assign(b, e);
  611. }
  612. });
  613. params[key] = detail::decode_url(val);
  614. });
  615. }
  616. #ifdef _MSC_VER
  617. class WSInit {
  618. public:
  619. WSInit() {
  620. WSADATA wsaData;
  621. WSAStartup(0x0002, &wsaData);
  622. }
  623. ~WSInit() {
  624. WSACleanup();
  625. }
  626. };
  627. static WSInit wsinit_;
  628. #endif
  629. } // namespace detail
  630. // Request implementation
  631. inline bool Request::has_header(const char* key) const
  632. {
  633. return headers.find(key) != headers.end();
  634. }
  635. inline std::string Request::get_header_value(const char* key) const
  636. {
  637. return detail::get_header_value(headers, key, "");
  638. }
  639. inline void Request::set_header(const char* key, const char* val)
  640. {
  641. headers.insert(std::make_pair(key, val));
  642. }
  643. inline bool Request::has_param(const char* key) const
  644. {
  645. return params.find(key) != params.end();
  646. }
  647. // Response implementation
  648. inline bool Response::has_header(const char* key) const
  649. {
  650. return headers.find(key) != headers.end();
  651. }
  652. inline std::string Response::get_header_value(const char* key) const
  653. {
  654. return detail::get_header_value(headers, key, "");
  655. }
  656. inline void Response::set_header(const char* key, const char* val)
  657. {
  658. headers.insert(std::make_pair(key, val));
  659. }
  660. inline void Response::set_redirect(const char* url)
  661. {
  662. set_header("Location", url);
  663. status = 302;
  664. }
  665. inline void Response::set_content(const char* s, size_t n, const char* content_type)
  666. {
  667. body.assign(s, n);
  668. set_header("Content-Type", content_type);
  669. }
  670. inline void Response::set_content(const std::string& s, const char* content_type)
  671. {
  672. body = s;
  673. set_header("Content-Type", content_type);
  674. }
  675. // Socket stream implementation
  676. inline SocketStream::SocketStream(socket_t sock): sock_(sock)
  677. {
  678. }
  679. inline SocketStream::~SocketStream()
  680. {
  681. }
  682. inline int SocketStream::read(char* ptr, size_t size)
  683. {
  684. return recv(sock_, ptr, size, 0);
  685. }
  686. inline int SocketStream::write(const char* ptr, size_t size)
  687. {
  688. return send(sock_, ptr, size, 0);
  689. }
  690. inline int SocketStream::write(const char* ptr)
  691. {
  692. return write(ptr, strlen(ptr));
  693. }
  694. // HTTP server implementation
  695. inline Server::Server()
  696. : svr_sock_(-1)
  697. {
  698. #ifndef _MSC_VER
  699. signal(SIGPIPE, SIG_IGN);
  700. #endif
  701. }
  702. inline Server::~Server()
  703. {
  704. }
  705. inline void Server::get(const char* pattern, Handler handler)
  706. {
  707. get_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  708. }
  709. inline void Server::post(const char* pattern, Handler handler)
  710. {
  711. post_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  712. }
  713. inline bool Server::set_base_dir(const char* path)
  714. {
  715. if (detail::is_dir(path)) {
  716. base_dir_ = path;
  717. return true;
  718. }
  719. return false;
  720. }
  721. inline void Server::set_error_handler(Handler handler)
  722. {
  723. error_handler_ = handler;
  724. }
  725. inline void Server::set_logger(Logger logger)
  726. {
  727. logger_ = logger;
  728. }
  729. inline bool Server::listen(const char* host, int port, int socket_flags)
  730. {
  731. svr_sock_ = detail::create_server_socket(host, port, socket_flags);
  732. if (svr_sock_ == -1) {
  733. return false;
  734. }
  735. auto ret = true;
  736. for (;;) {
  737. socket_t sock = accept(svr_sock_, NULL, NULL);
  738. if (sock == -1) {
  739. if (svr_sock_ != -1) {
  740. detail::close_socket(svr_sock_);
  741. ret = false;
  742. } else {
  743. ; // The server socket was closed by user.
  744. }
  745. break;
  746. }
  747. // TODO: should be async
  748. read_and_close_socket(sock);
  749. }
  750. return ret;
  751. }
  752. inline void Server::stop()
  753. {
  754. detail::shutdown_socket(svr_sock_);
  755. detail::close_socket(svr_sock_);
  756. svr_sock_ = -1;
  757. }
  758. inline bool Server::read_request_line(Stream& strm, Request& req)
  759. {
  760. const auto BUFSIZ_REQUESTLINE = 2048;
  761. char buf[BUFSIZ_REQUESTLINE];
  762. if (!detail::socket_gets(strm, buf, BUFSIZ_REQUESTLINE)) {
  763. return false;
  764. }
  765. static std::regex re("(GET|HEAD|POST) ([^?]+)(?:\\?(.+?))? HTTP/1\\.[01]\r\n");
  766. std::cmatch m;
  767. if (std::regex_match(buf, m, re)) {
  768. req.method = std::string(m[1]);
  769. req.path = detail::decode_url(m[2]);
  770. // Parse query text
  771. auto len = std::distance(m[3].first, m[3].second);
  772. if (len > 0) {
  773. detail::parse_query_text(m[3], req.params);
  774. }
  775. return true;
  776. }
  777. return false;
  778. }
  779. inline bool Server::handle_file_request(Request& req, Response& res)
  780. {
  781. if (!base_dir_.empty()) {
  782. std::string path = base_dir_ + req.path;
  783. if (!path.empty() && path.back() == '/') {
  784. path += "index.html";
  785. }
  786. if (detail::is_file(path)) {
  787. detail::read_file(path, res.body);
  788. auto type = detail::content_type(path);
  789. if (type) {
  790. res.set_header("Content-Type", type);
  791. }
  792. res.status = 200;
  793. return true;
  794. }
  795. }
  796. return false;
  797. }
  798. inline bool Server::routing(Request& req, Response& res)
  799. {
  800. if (req.method == "GET" && handle_file_request(req, res)) {
  801. return true;
  802. }
  803. if (req.method == "GET" || req.method == "HEAD") {
  804. return dispatch_request(req, res, get_handlers_);
  805. } else if (req.method == "POST") {
  806. return dispatch_request(req, res, post_handlers_);
  807. }
  808. return false;
  809. }
  810. inline bool Server::dispatch_request(Request& req, Response& res, Handlers& handlers)
  811. {
  812. for (const auto& x: handlers) {
  813. const auto& pattern = x.first;
  814. const auto& handler = x.second;
  815. if (std::regex_match(req.path, req.matches, pattern)) {
  816. handler(req, res);
  817. return true;
  818. }
  819. }
  820. return false;
  821. }
  822. inline void Server::process_request(Stream& strm)
  823. {
  824. Request req;
  825. Response res;
  826. if (!read_request_line(strm, req) ||
  827. !detail::read_headers(strm, req.headers)) {
  828. // TODO:
  829. return;
  830. }
  831. if (req.method == "POST") {
  832. if (!detail::read_content(strm, req, false)) {
  833. // TODO:
  834. return;
  835. }
  836. static std::string type = "application/x-www-form-urlencoded";
  837. if (!req.get_header_value("Content-Type").compare(0, type.size(), type)) {
  838. detail::parse_query_text(req.body, req.params);
  839. }
  840. }
  841. if (routing(req, res)) {
  842. if (res.status == -1) {
  843. res.status = 200;
  844. }
  845. } else {
  846. res.status = 404;
  847. }
  848. assert(res.status != -1);
  849. if (400 <= res.status && error_handler_) {
  850. error_handler_(req, res);
  851. }
  852. detail::write_response(strm, req, res);
  853. if (logger_) {
  854. logger_(req, res);
  855. }
  856. }
  857. inline bool Server::read_and_close_socket(socket_t sock)
  858. {
  859. return detail::read_and_close_socket(sock, [this](Stream& strm) {
  860. process_request(strm);
  861. return true;
  862. });
  863. }
  864. // HTTP client implementation
  865. inline Client::Client(const char* host, int port)
  866. : host_(host)
  867. , port_(port)
  868. {
  869. }
  870. inline Client::~Client()
  871. {
  872. }
  873. inline bool Client::read_response_line(Stream& strm, Response& res)
  874. {
  875. const auto BUFSIZ_RESPONSELINE = 2048;
  876. char buf[BUFSIZ_RESPONSELINE];
  877. if (!detail::socket_gets(strm, buf, BUFSIZ_RESPONSELINE)) {
  878. return false;
  879. }
  880. const static std::regex re("HTTP/1\\.[01] (\\d+?) .+\r\n");
  881. std::cmatch m;
  882. if (std::regex_match(buf, m, re)) {
  883. res.status = std::stoi(std::string(m[1]));
  884. }
  885. return true;
  886. }
  887. inline bool Client::send(const Request& req, Response& res)
  888. {
  889. auto sock = detail::create_client_socket(host_.c_str(), port_);
  890. if (sock == -1) {
  891. return false;
  892. }
  893. return read_and_close_socket(sock, req, res);
  894. }
  895. inline bool Client::process_request(Stream& strm, const Request& req, Response& res)
  896. {
  897. // Send request
  898. detail::write_request(strm, req);
  899. // Receive response
  900. if (!read_response_line(strm, res) ||
  901. !detail::read_headers(strm, res.headers)) {
  902. return false;
  903. }
  904. if (req.method != "HEAD") {
  905. if (!detail::read_content(strm, res, true)) {
  906. return false;
  907. }
  908. }
  909. return true;
  910. }
  911. inline bool Client::read_and_close_socket(socket_t sock, const Request& req, Response& res)
  912. {
  913. return detail::read_and_close_socket(sock, [&](Stream& strm) {
  914. return process_request(strm, req, res);
  915. });
  916. }
  917. inline void Client::add_default_headers(Request& req)
  918. {
  919. req.set_header("Host", host_.c_str());
  920. req.set_header("Accept", "*/*");
  921. req.set_header("User-Agent", "cpp-httplib/0.1");
  922. }
  923. inline std::shared_ptr<Response> Client::get(const char* path)
  924. {
  925. Request req;
  926. req.method = "GET";
  927. req.path = path;
  928. add_default_headers(req);
  929. auto res = std::make_shared<Response>();
  930. return send(req, *res) ? res : nullptr;
  931. }
  932. inline std::shared_ptr<Response> Client::head(const char* path)
  933. {
  934. Request req;
  935. req.method = "HEAD";
  936. req.path = path;
  937. add_default_headers(req);
  938. auto res = std::make_shared<Response>();
  939. return send(req, *res) ? res : nullptr;
  940. }
  941. inline std::shared_ptr<Response> Client::post(
  942. const char* path, const std::string& body, const char* content_type)
  943. {
  944. Request req;
  945. req.method = "POST";
  946. req.path = path;
  947. add_default_headers(req);
  948. req.set_header("Content-Type", content_type);
  949. req.body = body;
  950. auto res = std::make_shared<Response>();
  951. return send(req, *res) ? res : nullptr;
  952. }
  953. inline std::shared_ptr<Response> Client::post(
  954. const char* path, const Map& params)
  955. {
  956. std::string query;
  957. for (auto it = params.begin(); it != params.end(); ++it) {
  958. if (it != params.begin()) {
  959. query += "&";
  960. }
  961. query += it->first;
  962. query += "=";
  963. query += it->second;
  964. }
  965. return post(path, query, "application/x-www-form-urlencoded");
  966. }
  967. /*
  968. * SSL Implementation
  969. */
  970. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  971. namespace detail {
  972. template <typename U, typename V, typename T>
  973. inline bool read_and_close_socket_ssl(socket_t sock, SSL_CTX* ctx, U SSL_connect_or_accept, V setup, T callback)
  974. {
  975. auto ssl = SSL_new(ctx);
  976. auto bio = BIO_new_socket(sock, BIO_NOCLOSE);
  977. SSL_set_bio(ssl, bio, bio);
  978. setup(ssl);
  979. SSL_connect_or_accept(ssl);
  980. SSLSocketStream strm(ssl);
  981. auto ret = callback(strm);
  982. SSL_shutdown(ssl);
  983. SSL_free(ssl);
  984. close_socket(sock);
  985. return ret;
  986. }
  987. class SSLInit {
  988. public:
  989. SSLInit() {
  990. SSL_load_error_strings();
  991. SSL_library_init();
  992. }
  993. };
  994. static SSLInit sslinit_;
  995. } // namespace detail
  996. // SSL socket stream implementation
  997. inline SSLSocketStream::SSLSocketStream(SSL* ssl): ssl_(ssl)
  998. {
  999. }
  1000. inline SSLSocketStream::~SSLSocketStream()
  1001. {
  1002. }
  1003. inline int SSLSocketStream::read(char* ptr, size_t size)
  1004. {
  1005. return SSL_read(ssl_, ptr, size);
  1006. }
  1007. inline int SSLSocketStream::write(const char* ptr, size_t size)
  1008. {
  1009. return SSL_write(ssl_, ptr, size);
  1010. }
  1011. inline int SSLSocketStream::write(const char* ptr)
  1012. {
  1013. return write(ptr, strlen(ptr));
  1014. }
  1015. // SSL HTTP server implementation
  1016. inline SSLServer::SSLServer(const char* cert_path, const char* private_key_path)
  1017. {
  1018. ctx_ = SSL_CTX_new(SSLv23_server_method());
  1019. if (ctx_) {
  1020. SSL_CTX_set_options(ctx_,
  1021. SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
  1022. SSL_OP_NO_COMPRESSION |
  1023. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  1024. // auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  1025. // SSL_CTX_set_tmp_ecdh(ctx_, ecdh);
  1026. // EC_KEY_free(ecdh);
  1027. if (SSL_CTX_use_certificate_file(ctx_, cert_path, SSL_FILETYPE_PEM) != 1 ||
  1028. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) != 1) {
  1029. SSL_CTX_free(ctx_);
  1030. ctx_ = nullptr;
  1031. }
  1032. }
  1033. }
  1034. inline SSLServer::~SSLServer()
  1035. {
  1036. if (ctx_) {
  1037. SSL_CTX_free(ctx_);
  1038. }
  1039. }
  1040. inline bool SSLServer::read_and_close_socket(socket_t sock)
  1041. {
  1042. return detail::read_and_close_socket_ssl(
  1043. sock, ctx_,
  1044. SSL_accept,
  1045. [](SSL* ssl) {},
  1046. [this](Stream& strm) {
  1047. process_request(strm);
  1048. return true;
  1049. });
  1050. }
  1051. // SSL HTTP client implementation
  1052. inline SSLClient::SSLClient(const char* host, int port)
  1053. : Client(host, port)
  1054. {
  1055. ctx_ = SSL_CTX_new(SSLv23_client_method());
  1056. }
  1057. inline SSLClient::~SSLClient()
  1058. {
  1059. if (ctx_) {
  1060. SSL_CTX_free(ctx_);
  1061. }
  1062. }
  1063. inline bool SSLClient::read_and_close_socket(socket_t sock, const Request& req, Response& res)
  1064. {
  1065. return detail::read_and_close_socket_ssl(
  1066. sock, ctx_,
  1067. SSL_connect,
  1068. [&](SSL* ssl) {
  1069. SSL_set_tlsext_host_name(ssl, host_.c_str());
  1070. },
  1071. [&](Stream& strm) {
  1072. return process_request(strm, req, res);
  1073. });
  1074. }
  1075. #endif
  1076. } // namespace httplib
  1077. #endif
  1078. // vim: et ts=4 sw=4 cin cino={1s ff=unix