httplib.h 32 KB

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