httplib.h 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311
  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. Server& get(const char* pattern, Handler handler);
  111. Server& 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 Server& Server::get(const char* pattern, Handler handler)
  714. {
  715. get_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  716. return *this;
  717. }
  718. inline Server& Server::post(const char* pattern, Handler handler)
  719. {
  720. post_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  721. return *this;
  722. }
  723. inline bool Server::set_base_dir(const char* path)
  724. {
  725. if (detail::is_dir(path)) {
  726. base_dir_ = path;
  727. return true;
  728. }
  729. return false;
  730. }
  731. inline void Server::set_error_handler(Handler handler)
  732. {
  733. error_handler_ = handler;
  734. }
  735. inline void Server::set_logger(Logger logger)
  736. {
  737. logger_ = logger;
  738. }
  739. inline bool Server::listen(const char* host, int port, int socket_flags)
  740. {
  741. svr_sock_ = detail::create_server_socket(host, port, socket_flags);
  742. if (svr_sock_ == -1) {
  743. return false;
  744. }
  745. auto ret = true;
  746. for (;;) {
  747. socket_t sock = accept(svr_sock_, NULL, NULL);
  748. if (sock == -1) {
  749. if (svr_sock_ != -1) {
  750. detail::close_socket(svr_sock_);
  751. ret = false;
  752. } else {
  753. ; // The server socket was closed by user.
  754. }
  755. break;
  756. }
  757. // TODO: should be async
  758. read_and_close_socket(sock);
  759. }
  760. return ret;
  761. }
  762. inline void Server::stop()
  763. {
  764. detail::shutdown_socket(svr_sock_);
  765. detail::close_socket(svr_sock_);
  766. svr_sock_ = -1;
  767. }
  768. inline bool Server::read_request_line(Stream& strm, Request& req)
  769. {
  770. const auto BUFSIZ_REQUESTLINE = 2048;
  771. char buf[BUFSIZ_REQUESTLINE];
  772. if (!detail::socket_gets(strm, buf, BUFSIZ_REQUESTLINE)) {
  773. return false;
  774. }
  775. static std::regex re("(GET|HEAD|POST) ([^?]+)(?:\\?(.+?))? HTTP/1\\.[01]\r\n");
  776. std::cmatch m;
  777. if (std::regex_match(buf, m, re)) {
  778. req.method = std::string(m[1]);
  779. req.path = detail::decode_url(m[2]);
  780. // Parse query text
  781. auto len = std::distance(m[3].first, m[3].second);
  782. if (len > 0) {
  783. detail::parse_query_text(m[3], req.params);
  784. }
  785. return true;
  786. }
  787. return false;
  788. }
  789. inline bool Server::handle_file_request(Request& req, Response& res)
  790. {
  791. if (!base_dir_.empty()) {
  792. std::string path = base_dir_ + req.path;
  793. if (!path.empty() && path.back() == '/') {
  794. path += "index.html";
  795. }
  796. if (detail::is_file(path)) {
  797. detail::read_file(path, res.body);
  798. auto type = detail::content_type(path);
  799. if (type) {
  800. res.set_header("Content-Type", type);
  801. }
  802. res.status = 200;
  803. return true;
  804. }
  805. }
  806. return false;
  807. }
  808. inline bool Server::routing(Request& req, Response& res)
  809. {
  810. if (req.method == "GET" && handle_file_request(req, res)) {
  811. return true;
  812. }
  813. if (req.method == "GET" || req.method == "HEAD") {
  814. return dispatch_request(req, res, get_handlers_);
  815. } else if (req.method == "POST") {
  816. return dispatch_request(req, res, post_handlers_);
  817. }
  818. return false;
  819. }
  820. inline bool Server::dispatch_request(Request& req, Response& res, Handlers& handlers)
  821. {
  822. for (const auto& x: handlers) {
  823. const auto& pattern = x.first;
  824. const auto& handler = x.second;
  825. if (std::regex_match(req.path, req.matches, pattern)) {
  826. handler(req, res);
  827. return true;
  828. }
  829. }
  830. return false;
  831. }
  832. inline void Server::process_request(Stream& strm)
  833. {
  834. Request req;
  835. Response res;
  836. if (!read_request_line(strm, req) ||
  837. !detail::read_headers(strm, req.headers)) {
  838. // TODO:
  839. return;
  840. }
  841. if (req.method == "POST") {
  842. if (!detail::read_content(strm, req, false)) {
  843. // TODO:
  844. return;
  845. }
  846. static std::string type = "application/x-www-form-urlencoded";
  847. if (!req.get_header_value("Content-Type").compare(0, type.size(), type)) {
  848. detail::parse_query_text(req.body, req.params);
  849. }
  850. }
  851. if (routing(req, res)) {
  852. if (res.status == -1) {
  853. res.status = 200;
  854. }
  855. } else {
  856. res.status = 404;
  857. }
  858. assert(res.status != -1);
  859. if (400 <= res.status && error_handler_) {
  860. error_handler_(req, res);
  861. }
  862. detail::write_response(strm, req, res);
  863. if (logger_) {
  864. logger_(req, res);
  865. }
  866. }
  867. inline bool Server::read_and_close_socket(socket_t sock)
  868. {
  869. return detail::read_and_close_socket(sock, [this](Stream& strm) {
  870. process_request(strm);
  871. return true;
  872. });
  873. }
  874. // HTTP client implementation
  875. inline Client::Client(const char* host, int port)
  876. : host_(host)
  877. , port_(port)
  878. , host_and_port_(host_ + ":" + std::to_string(port_))
  879. {
  880. }
  881. inline Client::~Client()
  882. {
  883. }
  884. inline bool Client::read_response_line(Stream& strm, Response& res)
  885. {
  886. const auto BUFSIZ_RESPONSELINE = 2048;
  887. char buf[BUFSIZ_RESPONSELINE];
  888. if (!detail::socket_gets(strm, buf, BUFSIZ_RESPONSELINE)) {
  889. return false;
  890. }
  891. const static std::regex re("HTTP/1\\.[01] (\\d+?) .+\r\n");
  892. std::cmatch m;
  893. if (std::regex_match(buf, m, re)) {
  894. res.status = std::stoi(std::string(m[1]));
  895. }
  896. return true;
  897. }
  898. inline bool Client::send(const Request& req, Response& res)
  899. {
  900. auto sock = detail::create_client_socket(host_.c_str(), port_);
  901. if (sock == -1) {
  902. return false;
  903. }
  904. return read_and_close_socket(sock, req, res);
  905. }
  906. inline bool Client::process_request(Stream& strm, const Request& req, Response& res)
  907. {
  908. // Send request
  909. detail::write_request(strm, req);
  910. // Receive response
  911. if (!read_response_line(strm, res) ||
  912. !detail::read_headers(strm, res.headers)) {
  913. return false;
  914. }
  915. if (req.method != "HEAD") {
  916. if (!detail::read_content(strm, res, true, req.progress)) {
  917. return false;
  918. }
  919. }
  920. return true;
  921. }
  922. inline bool Client::read_and_close_socket(socket_t sock, const Request& req, Response& res)
  923. {
  924. return detail::read_and_close_socket(sock, [&](Stream& strm) {
  925. return process_request(strm, req, res);
  926. });
  927. }
  928. inline void Client::add_default_headers(Request& req)
  929. {
  930. req.set_header("Host", host_and_port_.c_str());
  931. req.set_header("Accept", "*/*");
  932. req.set_header("User-Agent", "cpp-httplib/0.1");
  933. }
  934. inline std::shared_ptr<Response> Client::get(const char* path, Progress callback)
  935. {
  936. Request req;
  937. req.method = "GET";
  938. req.path = path;
  939. req.progress = callback;
  940. add_default_headers(req);
  941. auto res = std::make_shared<Response>();
  942. return send(req, *res) ? res : nullptr;
  943. }
  944. inline std::shared_ptr<Response> Client::head(const char* path)
  945. {
  946. Request req;
  947. req.method = "HEAD";
  948. req.path = path;
  949. add_default_headers(req);
  950. auto res = std::make_shared<Response>();
  951. return send(req, *res) ? res : nullptr;
  952. }
  953. inline std::shared_ptr<Response> Client::post(
  954. const char* path, const std::string& body, const char* content_type)
  955. {
  956. Request req;
  957. req.method = "POST";
  958. req.path = path;
  959. add_default_headers(req);
  960. req.set_header("Content-Type", content_type);
  961. req.body = body;
  962. auto res = std::make_shared<Response>();
  963. return send(req, *res) ? res : nullptr;
  964. }
  965. inline std::shared_ptr<Response> Client::post(
  966. const char* path, const Map& params)
  967. {
  968. std::string query;
  969. for (auto it = params.begin(); it != params.end(); ++it) {
  970. if (it != params.begin()) {
  971. query += "&";
  972. }
  973. query += it->first;
  974. query += "=";
  975. query += it->second;
  976. }
  977. return post(path, query, "application/x-www-form-urlencoded");
  978. }
  979. /*
  980. * SSL Implementation
  981. */
  982. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  983. namespace detail {
  984. template <typename U, typename V, typename T>
  985. inline bool read_and_close_socket_ssl(socket_t sock, SSL_CTX* ctx, U SSL_connect_or_accept, V setup, T callback)
  986. {
  987. auto ssl = SSL_new(ctx);
  988. auto bio = BIO_new_socket(sock, BIO_NOCLOSE);
  989. SSL_set_bio(ssl, bio, bio);
  990. setup(ssl);
  991. SSL_connect_or_accept(ssl);
  992. SSLSocketStream strm(ssl);
  993. auto ret = callback(strm);
  994. SSL_shutdown(ssl);
  995. SSL_free(ssl);
  996. close_socket(sock);
  997. return ret;
  998. }
  999. class SSLInit {
  1000. public:
  1001. SSLInit() {
  1002. SSL_load_error_strings();
  1003. SSL_library_init();
  1004. }
  1005. };
  1006. static SSLInit sslinit_;
  1007. } // namespace detail
  1008. // SSL socket stream implementation
  1009. inline SSLSocketStream::SSLSocketStream(SSL* ssl): ssl_(ssl)
  1010. {
  1011. }
  1012. inline SSLSocketStream::~SSLSocketStream()
  1013. {
  1014. }
  1015. inline int SSLSocketStream::read(char* ptr, size_t size)
  1016. {
  1017. return SSL_read(ssl_, ptr, size);
  1018. }
  1019. inline int SSLSocketStream::write(const char* ptr, size_t size)
  1020. {
  1021. return SSL_write(ssl_, ptr, size);
  1022. }
  1023. inline int SSLSocketStream::write(const char* ptr)
  1024. {
  1025. return write(ptr, strlen(ptr));
  1026. }
  1027. // SSL HTTP server implementation
  1028. inline SSLServer::SSLServer(const char* cert_path, const char* private_key_path)
  1029. {
  1030. ctx_ = SSL_CTX_new(SSLv23_server_method());
  1031. if (ctx_) {
  1032. SSL_CTX_set_options(ctx_,
  1033. SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
  1034. SSL_OP_NO_COMPRESSION |
  1035. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  1036. // auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  1037. // SSL_CTX_set_tmp_ecdh(ctx_, ecdh);
  1038. // EC_KEY_free(ecdh);
  1039. if (SSL_CTX_use_certificate_file(ctx_, cert_path, SSL_FILETYPE_PEM) != 1 ||
  1040. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) != 1) {
  1041. SSL_CTX_free(ctx_);
  1042. ctx_ = nullptr;
  1043. }
  1044. }
  1045. }
  1046. inline SSLServer::~SSLServer()
  1047. {
  1048. if (ctx_) {
  1049. SSL_CTX_free(ctx_);
  1050. }
  1051. }
  1052. inline bool SSLServer::read_and_close_socket(socket_t sock)
  1053. {
  1054. return detail::read_and_close_socket_ssl(
  1055. sock, ctx_,
  1056. SSL_accept,
  1057. [](SSL* ssl) {},
  1058. [this](Stream& strm) {
  1059. process_request(strm);
  1060. return true;
  1061. });
  1062. }
  1063. // SSL HTTP client implementation
  1064. inline SSLClient::SSLClient(const char* host, int port)
  1065. : Client(host, port)
  1066. {
  1067. ctx_ = SSL_CTX_new(SSLv23_client_method());
  1068. }
  1069. inline SSLClient::~SSLClient()
  1070. {
  1071. if (ctx_) {
  1072. SSL_CTX_free(ctx_);
  1073. }
  1074. }
  1075. inline bool SSLClient::read_and_close_socket(socket_t sock, const Request& req, Response& res)
  1076. {
  1077. return detail::read_and_close_socket_ssl(
  1078. sock, ctx_,
  1079. SSL_connect,
  1080. [&](SSL* ssl) {
  1081. SSL_set_tlsext_host_name(ssl, host_.c_str());
  1082. },
  1083. [&](Stream& strm) {
  1084. return process_request(strm, req, res);
  1085. });
  1086. }
  1087. #endif
  1088. } // namespace httplib
  1089. #endif
  1090. // vim: et ts=4 sw=4 cin cino={1s ff=unix