httplib.h 30 KB

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