httplib.h 31 KB

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