httplib.h 33 KB

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