httplib.h 29 KB

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