httplib.h 30 KB

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