httplib.h 30 KB

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