httplib.h 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229
  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 get_file_extention(const std::string& path)
  329. {
  330. std::smatch m;
  331. auto pat = std::regex("\\.([a-zA-Z0-9]+)$");
  332. auto ret = std::regex_search(path, m, pat);
  333. std::string content_type;
  334. if (ret) {
  335. return m[1].str();
  336. }
  337. return std::string();
  338. }
  339. inline const char* get_content_type_from_file_extention(const std::string& ext)
  340. {
  341. if (ext == "html") {
  342. return "text/html";
  343. }
  344. return "text/plain";
  345. }
  346. inline const char* status_message(int status)
  347. {
  348. switch (status) {
  349. case 200: return "OK";
  350. case 400: return "Bad Request";
  351. case 404: return "Not Found";
  352. default:
  353. case 500: return "Internal Server Error";
  354. }
  355. }
  356. inline const char* get_header_value(const MultiMap& map, const char* key, const char* def)
  357. {
  358. auto it = map.find(key);
  359. if (it != map.end()) {
  360. return it->second.c_str();
  361. }
  362. return def;
  363. }
  364. inline int get_header_value_int(const MultiMap& map, const char* key, int def)
  365. {
  366. auto it = map.find(key);
  367. if (it != map.end()) {
  368. return std::stoi(it->second);
  369. }
  370. return def;
  371. }
  372. inline bool read_headers(Stream& strm, MultiMap& headers)
  373. {
  374. static std::regex re("(.+?): (.+?)\r\n");
  375. const auto BUFSIZ_HEADER = 2048;
  376. char buf[BUFSIZ_HEADER];
  377. for (;;) {
  378. if (!socket_gets(strm, buf, BUFSIZ_HEADER)) {
  379. return false;
  380. }
  381. if (!strcmp(buf, "\r\n")) {
  382. break;
  383. }
  384. std::cmatch m;
  385. if (std::regex_match(buf, m, re)) {
  386. auto key = std::string(m[1]);
  387. auto val = std::string(m[2]);
  388. headers.insert(std::make_pair(key, val));
  389. }
  390. }
  391. return true;
  392. }
  393. template <typename T>
  394. bool read_content(Stream& strm, T& x)
  395. {
  396. auto len = get_header_value_int(x.headers, "Content-Length", 0);
  397. if (len) {
  398. x.body.assign(len, 0);
  399. if (!strm.read(&x.body[0], x.body.size())) {
  400. return false;
  401. }
  402. }
  403. return true;
  404. }
  405. template <typename T>
  406. inline void write_headers(Stream& strm, const T& res)
  407. {
  408. strm.write("Connection: close\r\n");
  409. for (const auto& x: res.headers) {
  410. if (x.first != "Content-Type" && x.first != "Content-Length") {
  411. socket_printf(strm, "%s: %s\r\n", x.first.c_str(), x.second.c_str());
  412. }
  413. }
  414. auto t = get_header_value(res.headers, "Content-Type", "text/plain");
  415. socket_printf(strm, "Content-Type: %s\r\n", t);
  416. socket_printf(strm, "Content-Length: %ld\r\n", res.body.size());
  417. strm.write("\r\n");
  418. }
  419. inline void write_response(Stream& strm, const Request& req, const Response& res)
  420. {
  421. socket_printf(strm, "HTTP/1.0 %d %s\r\n", res.status, status_message(res.status));
  422. write_headers(strm, res);
  423. if (!res.body.empty() && req.method != "HEAD") {
  424. strm.write(res.body.c_str(), res.body.size());
  425. }
  426. }
  427. inline std::string encode_url(const std::string& s)
  428. {
  429. std::string result;
  430. for (auto i = 0; s[i]; i++) {
  431. switch (s[i]) {
  432. case ' ': result += "+"; break;
  433. case '\'': result += "%27"; break;
  434. case ',': result += "%2C"; break;
  435. case ':': result += "%3A"; break;
  436. case ';': result += "%3B"; break;
  437. default:
  438. if (s[i] < 0) {
  439. result += '%';
  440. char hex[4];
  441. size_t len = snprintf(hex, sizeof(hex), "%02X", (unsigned char)s[i]);
  442. assert(len == 2);
  443. result.append(hex, len);
  444. } else {
  445. result += s[i];
  446. }
  447. break;
  448. }
  449. }
  450. return result;
  451. }
  452. inline bool is_hex(char c, int& v)
  453. {
  454. if (0x20 <= c && isdigit(c)) {
  455. v = c - '0';
  456. return true;
  457. } else if ('A' <= c && c <= 'F') {
  458. v = c - 'A' + 10;
  459. return true;
  460. } else if ('a' <= c && c <= 'f') {
  461. v = c - 'a' + 10;
  462. return true;
  463. }
  464. return false;
  465. }
  466. inline int from_hex_to_i(const std::string& s, int i, int cnt, int& val)
  467. {
  468. val = 0;
  469. for (; s[i] && cnt; i++, cnt--) {
  470. int v = 0;
  471. if (is_hex(s[i], v)) {
  472. val = val * 16 + v;
  473. } else {
  474. break;
  475. }
  476. }
  477. return --i;
  478. }
  479. inline size_t to_utf8(int code, char* buff)
  480. {
  481. if (code < 0x0080) {
  482. buff[0] = (code & 0x7F);
  483. return 1;
  484. } else if (code < 0x0800) {
  485. buff[0] = (0xC0 | ((code >> 6) & 0x1F));
  486. buff[1] = (0x80 | (code & 0x3F));
  487. return 2;
  488. } else if (code < 0xD800) {
  489. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  490. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  491. buff[2] = (0x80 | (code & 0x3F));
  492. return 3;
  493. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  494. return 0;
  495. } else if (code < 0x10000) {
  496. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  497. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  498. buff[2] = (0x80 | (code & 0x3F));
  499. return 3;
  500. } else if (code < 0x110000) {
  501. buff[0] = (0xF0 | ((code >> 18) & 0x7));
  502. buff[1] = (0x80 | ((code >> 12) & 0x3F));
  503. buff[2] = (0x80 | ((code >> 6) & 0x3F));
  504. buff[3] = (0x80 | (code & 0x3F));
  505. return 4;
  506. }
  507. // NOTREACHED
  508. return 0;
  509. }
  510. inline std::string decode_url(const std::string& s)
  511. {
  512. std::string result;
  513. for (int i = 0; s[i]; i++) {
  514. if (s[i] == '%') {
  515. i++;
  516. assert(s[i]);
  517. if (s[i] == '%') {
  518. result += s[i];
  519. } else if (s[i] == 'u') {
  520. // Unicode
  521. i++;
  522. assert(s[i]);
  523. int val = 0;
  524. i = from_hex_to_i(s, i, 4, val);
  525. char buff[4];
  526. size_t len = to_utf8(val, buff);
  527. if (len > 0) {
  528. result.append(buff, len);
  529. }
  530. } else {
  531. // HEX
  532. int val = 0;
  533. i = from_hex_to_i(s, i, 2, val);
  534. result += val;
  535. }
  536. } else if (s[i] == '+') {
  537. result += ' ';
  538. } else {
  539. result += s[i];
  540. }
  541. }
  542. return result;
  543. }
  544. inline void write_request(Stream& strm, const Request& req)
  545. {
  546. auto path = encode_url(req.path);
  547. socket_printf(strm, "%s %s HTTP/1.0\r\n", req.method.c_str(), path.c_str());
  548. write_headers(strm, req);
  549. if (!req.body.empty()) {
  550. if (req.has_header("application/x-www-form-urlencoded")) {
  551. auto str = encode_url(req.body);
  552. strm.write(str.c_str(), str.size());
  553. } else {
  554. strm.write(req.body.c_str(), req.body.size());
  555. }
  556. }
  557. }
  558. inline void parse_query_text(const std::string& s, Map& params)
  559. {
  560. split(&s[0], &s[s.size()], '&', [&](const char* b, const char* e) {
  561. std::string key;
  562. std::string val;
  563. split(b, e, '=', [&](const char* b, const char* e) {
  564. if (key.empty()) {
  565. key.assign(b, e);
  566. } else {
  567. val.assign(b, e);
  568. }
  569. });
  570. params[key] = detail::decode_url(val);
  571. });
  572. }
  573. #ifdef _MSC_VER
  574. class WSInit {
  575. public:
  576. WSInit() {
  577. WSADATA wsaData;
  578. WSAStartup(0x0002, &wsaData);
  579. }
  580. ~WSInit() {
  581. WSACleanup();
  582. }
  583. };
  584. static WSInit wsinit_;
  585. #endif
  586. } // namespace detail
  587. // Request implementation
  588. inline bool Request::has_header(const char* key) const
  589. {
  590. return headers.find(key) != headers.end();
  591. }
  592. inline std::string Request::get_header_value(const char* key) const
  593. {
  594. return detail::get_header_value(headers, key, "");
  595. }
  596. inline void Request::set_header(const char* key, const char* val)
  597. {
  598. headers.insert(std::make_pair(key, val));
  599. }
  600. inline bool Request::has_param(const char* key) const
  601. {
  602. return params.find(key) != params.end();
  603. }
  604. // Response implementation
  605. inline bool Response::has_header(const char* key) const
  606. {
  607. return headers.find(key) != headers.end();
  608. }
  609. inline std::string Response::get_header_value(const char* key) const
  610. {
  611. return detail::get_header_value(headers, key, "");
  612. }
  613. inline void Response::set_header(const char* key, const char* val)
  614. {
  615. headers.insert(std::make_pair(key, val));
  616. }
  617. inline void Response::set_redirect(const char* url)
  618. {
  619. set_header("Location", url);
  620. status = 302;
  621. }
  622. inline void Response::set_content(const char* s, size_t n, const char* content_type)
  623. {
  624. body.assign(s, n);
  625. set_header("Content-Type", content_type);
  626. }
  627. inline void Response::set_content(const std::string& s, const char* content_type)
  628. {
  629. body = s;
  630. set_header("Content-Type", content_type);
  631. }
  632. // Socket stream implementation
  633. inline SocketStream::SocketStream(socket_t sock): sock_(sock)
  634. {
  635. }
  636. inline SocketStream::~SocketStream()
  637. {
  638. }
  639. inline int SocketStream::read(char* ptr, size_t size)
  640. {
  641. return recv(sock_, ptr, size, 0);
  642. }
  643. inline int SocketStream::write(const char* ptr, size_t size)
  644. {
  645. return send(sock_, ptr, size, 0);
  646. }
  647. inline int SocketStream::write(const char* ptr)
  648. {
  649. return write(ptr, strlen(ptr));
  650. }
  651. // HTTP server implementation
  652. inline Server::Server()
  653. : svr_sock_(-1)
  654. {
  655. }
  656. inline Server::~Server()
  657. {
  658. }
  659. inline void Server::get(const char* pattern, Handler handler)
  660. {
  661. get_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  662. }
  663. inline void Server::post(const char* pattern, Handler handler)
  664. {
  665. post_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  666. }
  667. inline bool Server::set_base_dir(const char* path)
  668. {
  669. if (detail::is_dir(path)) {
  670. base_dir_ = path;
  671. return true;
  672. }
  673. return false;
  674. }
  675. inline void Server::set_error_handler(Handler handler)
  676. {
  677. error_handler_ = handler;
  678. }
  679. inline void Server::set_logger(Logger logger)
  680. {
  681. logger_ = logger;
  682. }
  683. inline bool Server::listen(const char* host, int port)
  684. {
  685. svr_sock_ = detail::create_server_socket(host, port);
  686. if (svr_sock_ == -1) {
  687. return false;
  688. }
  689. auto ret = true;
  690. for (;;) {
  691. socket_t sock = accept(svr_sock_, NULL, NULL);
  692. if (sock == -1) {
  693. if (svr_sock_ != -1) {
  694. detail::close_socket(svr_sock_);
  695. ret = false;
  696. } else {
  697. ; // The server socket was closed by user.
  698. }
  699. break;
  700. }
  701. // TODO: should be async
  702. read_and_close_socket(sock);
  703. }
  704. return ret;
  705. }
  706. inline void Server::stop()
  707. {
  708. detail::shutdown_socket(svr_sock_);
  709. detail::close_socket(svr_sock_);
  710. svr_sock_ = -1;
  711. }
  712. inline bool Server::read_request_line(Stream& strm, Request& req)
  713. {
  714. const auto BUFSIZ_REQUESTLINE = 2048;
  715. char buf[BUFSIZ_REQUESTLINE];
  716. if (!detail::socket_gets(strm, buf, BUFSIZ_REQUESTLINE)) {
  717. return false;
  718. }
  719. static std::regex re("(GET|HEAD|POST) ([^?]+)(?:\\?(.+?))? HTTP/1\\.[01]\r\n");
  720. std::cmatch m;
  721. if (std::regex_match(buf, m, re)) {
  722. req.method = std::string(m[1]);
  723. req.path = detail::decode_url(m[2]);
  724. // Parse query text
  725. auto len = std::distance(m[3].first, m[3].second);
  726. if (len > 0) {
  727. detail::parse_query_text(m[3], req.params);
  728. }
  729. return true;
  730. }
  731. return false;
  732. }
  733. inline bool Server::handle_file_request(Request& req, Response& res)
  734. {
  735. if (!base_dir_.empty()) {
  736. std::string path = base_dir_ + req.path;
  737. if (!path.empty() && path.back() == '/') {
  738. path += "index.html";
  739. }
  740. if (detail::is_file(path)) {
  741. detail::read_file(path, res.body);
  742. res.set_header("Content-Type",
  743. detail::get_content_type_from_file_extention(
  744. detail::get_file_extention(path)));
  745. res.status = 200;
  746. return true;
  747. }
  748. }
  749. return false;
  750. }
  751. inline bool Server::routing(Request& req, Response& res)
  752. {
  753. if (req.method == "GET" && handle_file_request(req, res)) {
  754. return true;
  755. }
  756. if (req.method == "GET" || req.method == "HEAD") {
  757. return dispatch_request(req, res, get_handlers_);
  758. } else if (req.method == "POST") {
  759. return dispatch_request(req, res, post_handlers_);
  760. }
  761. return false;
  762. }
  763. inline bool Server::dispatch_request(Request& req, Response& res, Handlers& handlers)
  764. {
  765. for (const auto& x: handlers) {
  766. const auto& pattern = x.first;
  767. const auto& handler = x.second;
  768. if (std::regex_match(req.path, req.matches, pattern)) {
  769. handler(req, res);
  770. return true;
  771. }
  772. }
  773. return false;
  774. }
  775. inline void Server::process_request(Stream& strm)
  776. {
  777. Request req;
  778. Response res;
  779. if (!read_request_line(strm, req) ||
  780. !detail::read_headers(strm, req.headers)) {
  781. // TODO:
  782. return;
  783. }
  784. if (req.method == "POST") {
  785. if (!detail::read_content(strm, req)) {
  786. // TODO:
  787. return;
  788. }
  789. static std::string type = "application/x-www-form-urlencoded";
  790. if (!req.get_header_value("Content-Type").compare(0, type.size(), type)) {
  791. detail::parse_query_text(req.body, req.params);
  792. }
  793. }
  794. if (routing(req, res)) {
  795. if (res.status == -1) {
  796. res.status = 200;
  797. }
  798. } else {
  799. res.status = 404;
  800. }
  801. assert(res.status != -1);
  802. if (400 <= res.status && error_handler_) {
  803. error_handler_(req, res);
  804. }
  805. detail::write_response(strm, req, res);
  806. if (logger_) {
  807. logger_(req, res);
  808. }
  809. }
  810. inline bool Server::read_and_close_socket(socket_t sock)
  811. {
  812. return detail::read_and_close_socket(sock, [this](Stream& strm) {
  813. process_request(strm);
  814. return true;
  815. });
  816. }
  817. // HTTP client implementation
  818. inline Client::Client(const char* host, int port)
  819. : host_(host)
  820. , port_(port)
  821. {
  822. }
  823. inline Client::~Client()
  824. {
  825. }
  826. inline bool Client::read_response_line(Stream& strm, Response& res)
  827. {
  828. const auto BUFSIZ_RESPONSELINE = 2048;
  829. char buf[BUFSIZ_RESPONSELINE];
  830. if (!detail::socket_gets(strm, buf, BUFSIZ_RESPONSELINE)) {
  831. return false;
  832. }
  833. const static std::regex re("HTTP/1\\.[01] (\\d+?) .+\r\n");
  834. std::cmatch m;
  835. if (std::regex_match(buf, m, re)) {
  836. res.status = std::stoi(std::string(m[1]));
  837. }
  838. return true;
  839. }
  840. inline bool Client::send(const Request& req, Response& res)
  841. {
  842. auto sock = detail::create_client_socket(host_.c_str(), port_);
  843. if (sock == -1) {
  844. return false;
  845. }
  846. return read_and_close_socket(sock, req, res);
  847. }
  848. inline bool Client::process_request(Stream& strm, const Request& req, Response& res)
  849. {
  850. // Send request
  851. detail::write_request(strm, req);
  852. // Receive response
  853. if (!read_response_line(strm, res) ||
  854. !detail::read_headers(strm, res.headers)) {
  855. return false;
  856. }
  857. if (req.method != "HEAD") {
  858. if (!detail::read_content(strm, res)) {
  859. return false;
  860. }
  861. }
  862. return true;
  863. }
  864. inline bool Client::read_and_close_socket(socket_t sock, const Request& req, Response& res)
  865. {
  866. return detail::read_and_close_socket(sock, [&](Stream& strm) {
  867. return process_request(strm, req, res);
  868. });
  869. }
  870. inline std::shared_ptr<Response> Client::get(const char* path)
  871. {
  872. Request req;
  873. req.method = "GET";
  874. req.path = path;
  875. auto res = std::make_shared<Response>();
  876. return send(req, *res) ? res : nullptr;
  877. }
  878. inline std::shared_ptr<Response> Client::head(const char* path)
  879. {
  880. Request req;
  881. req.method = "HEAD";
  882. req.path = path;
  883. auto res = std::make_shared<Response>();
  884. return send(req, *res) ? res : nullptr;
  885. }
  886. inline std::shared_ptr<Response> Client::post(
  887. const char* path, const std::string& body, const char* content_type)
  888. {
  889. Request req;
  890. req.method = "POST";
  891. req.path = path;
  892. req.set_header("Content-Type", content_type);
  893. req.body = body;
  894. auto res = std::make_shared<Response>();
  895. return send(req, *res) ? res : nullptr;
  896. }
  897. inline std::shared_ptr<Response> Client::post(
  898. const char* path, const Map& params)
  899. {
  900. std::string query;
  901. for (auto it = params.begin(); it != params.end(); ++it) {
  902. if (it != params.begin()) {
  903. query += "&";
  904. }
  905. query += it->first;
  906. query += "=";
  907. query += it->second;
  908. }
  909. return post(path, query, "application/x-www-form-urlencoded");
  910. }
  911. /*
  912. * SSL Implementation
  913. */
  914. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  915. namespace detail {
  916. template <typename U, typename T>
  917. inline bool read_and_close_socket_ssl(socket_t sock, SSL_CTX* ctx, U SSL_connect_or_accept, T callback)
  918. {
  919. auto ssl = SSL_new(ctx);
  920. auto bio = BIO_new_socket(sock, BIO_NOCLOSE);
  921. SSL_set_bio(ssl, bio, bio);
  922. SSL_connect_or_accept(ssl);
  923. SSLSocketStream strm(ssl);
  924. auto ret = callback(strm);
  925. SSL_shutdown(ssl);
  926. SSL_free(ssl);
  927. close_socket(sock);
  928. return ret;
  929. }
  930. class SSLInit {
  931. public:
  932. SSLInit() {
  933. SSL_load_error_strings();
  934. SSL_library_init();
  935. }
  936. };
  937. static SSLInit sslinit_;
  938. } // namespace detail
  939. // SSL socket stream implementation
  940. inline SSLSocketStream::SSLSocketStream(SSL* ssl): ssl_(ssl)
  941. {
  942. }
  943. inline SSLSocketStream::~SSLSocketStream()
  944. {
  945. }
  946. inline int SSLSocketStream::read(char* ptr, size_t size)
  947. {
  948. return SSL_read(ssl_, ptr, size);
  949. }
  950. inline int SSLSocketStream::write(const char* ptr, size_t size)
  951. {
  952. return SSL_write(ssl_, ptr, size);
  953. }
  954. inline int SSLSocketStream::write(const char* ptr)
  955. {
  956. return write(ptr, strlen(ptr));
  957. }
  958. // SSL HTTP server implementation
  959. inline SSLServer::SSLServer(const char* cert_path, const char* private_key_path)
  960. {
  961. ctx_ = SSL_CTX_new(SSLv23_server_method());
  962. if (ctx_) {
  963. SSL_CTX_set_options(ctx_,
  964. SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
  965. SSL_OP_NO_COMPRESSION |
  966. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  967. // auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  968. // SSL_CTX_set_tmp_ecdh(ctx_, ecdh);
  969. // EC_KEY_free(ecdh);
  970. if (SSL_CTX_use_certificate_file(ctx_, cert_path, SSL_FILETYPE_PEM) != 1 ||
  971. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) != 1) {
  972. SSL_CTX_free(ctx_);
  973. ctx_ = nullptr;
  974. }
  975. }
  976. }
  977. inline SSLServer::~SSLServer()
  978. {
  979. if (ctx_) {
  980. SSL_CTX_free(ctx_);
  981. }
  982. }
  983. inline bool SSLServer::read_and_close_socket(socket_t sock)
  984. {
  985. return detail::read_and_close_socket_ssl(sock, ctx_, SSL_accept, [this](Stream& strm) {
  986. process_request(strm);
  987. return true;
  988. });
  989. }
  990. // SSL HTTP client implementation
  991. inline SSLClient::SSLClient(const char* host, int port)
  992. : Client(host, port)
  993. {
  994. ctx_ = SSL_CTX_new(SSLv23_client_method());
  995. }
  996. inline SSLClient::~SSLClient()
  997. {
  998. if (ctx_) {
  999. SSL_CTX_free(ctx_);
  1000. }
  1001. }
  1002. inline bool SSLClient::read_and_close_socket(socket_t sock, const Request& req, Response& res)
  1003. {
  1004. return detail::read_and_close_socket_ssl(sock, ctx_, SSL_connect, [&](Stream& strm) {
  1005. return process_request(strm, req, res);
  1006. });
  1007. }
  1008. #endif
  1009. } // namespace httplib
  1010. #endif
  1011. // vim: et ts=4 sw=4 cin cino={1s ff=unix