httplib.h 28 KB

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