httplib.h 29 KB

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