httplib.h 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445
  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 int from_hex_to_i(const std::string& s, int i, int cnt, int& val)
  611. {
  612. val = 0;
  613. for (; s[i] && cnt; i++, cnt--) {
  614. int v = 0;
  615. if (is_hex(s[i], v)) {
  616. val = val * 16 + v;
  617. } else {
  618. break;
  619. }
  620. }
  621. return --i;
  622. }
  623. inline size_t to_utf8(int code, char* buff)
  624. {
  625. if (code < 0x0080) {
  626. buff[0] = (code & 0x7F);
  627. return 1;
  628. } else if (code < 0x0800) {
  629. buff[0] = (0xC0 | ((code >> 6) & 0x1F));
  630. buff[1] = (0x80 | (code & 0x3F));
  631. return 2;
  632. } else if (code < 0xD800) {
  633. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  634. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  635. buff[2] = (0x80 | (code & 0x3F));
  636. return 3;
  637. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  638. return 0;
  639. } else if (code < 0x10000) {
  640. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  641. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  642. buff[2] = (0x80 | (code & 0x3F));
  643. return 3;
  644. } else if (code < 0x110000) {
  645. buff[0] = (0xF0 | ((code >> 18) & 0x7));
  646. buff[1] = (0x80 | ((code >> 12) & 0x3F));
  647. buff[2] = (0x80 | ((code >> 6) & 0x3F));
  648. buff[3] = (0x80 | (code & 0x3F));
  649. return 4;
  650. }
  651. // NOTREACHED
  652. return 0;
  653. }
  654. inline std::string decode_url(const std::string& s)
  655. {
  656. std::string result;
  657. for (int i = 0; s[i]; i++) {
  658. if (s[i] == '%') {
  659. i++;
  660. assert(s[i]);
  661. if (s[i] == '%') {
  662. result += s[i];
  663. } else if (s[i] == 'u') {
  664. // Unicode
  665. i++;
  666. assert(s[i]);
  667. int val = 0;
  668. i = from_hex_to_i(s, i, 4, val);
  669. char buff[4];
  670. size_t len = to_utf8(val, buff);
  671. if (len > 0) {
  672. result.append(buff, len);
  673. }
  674. } else {
  675. // HEX
  676. int val = 0;
  677. i = from_hex_to_i(s, i, 2, val);
  678. result += val;
  679. }
  680. } else if (s[i] == '+') {
  681. result += ' ';
  682. } else {
  683. result += s[i];
  684. }
  685. }
  686. return result;
  687. }
  688. inline void write_request(Stream& strm, const Request& req, const char* ver)
  689. {
  690. auto path = encode_url(req.path);
  691. socket_printf(strm, "%s %s %s\r\n", req.method.c_str(), path.c_str(), ver);
  692. write_headers(strm, req);
  693. if (!req.body.empty()) {
  694. if (req.has_header("application/x-www-form-urlencoded")) {
  695. auto str = encode_url(req.body);
  696. strm.write(str.c_str(), str.size());
  697. } else {
  698. strm.write(req.body.c_str(), req.body.size());
  699. }
  700. }
  701. }
  702. inline void parse_query_text(const std::string& s, Map& params)
  703. {
  704. split(&s[0], &s[s.size()], '&', [&](const char* b, const char* e) {
  705. std::string key;
  706. std::string val;
  707. split(b, e, '=', [&](const char* b, const char* e) {
  708. if (key.empty()) {
  709. key.assign(b, e);
  710. } else {
  711. val.assign(b, e);
  712. }
  713. });
  714. params[key] = detail::decode_url(val);
  715. });
  716. }
  717. #ifdef _MSC_VER
  718. class WSInit {
  719. public:
  720. WSInit() {
  721. WSADATA wsaData;
  722. WSAStartup(0x0002, &wsaData);
  723. }
  724. ~WSInit() {
  725. WSACleanup();
  726. }
  727. };
  728. static WSInit wsinit_;
  729. #endif
  730. } // namespace detail
  731. // Request implementation
  732. inline bool Request::has_header(const char* key) const
  733. {
  734. return headers.find(key) != headers.end();
  735. }
  736. inline std::string Request::get_header_value(const char* key) const
  737. {
  738. return detail::get_header_value(headers, key, "");
  739. }
  740. inline void Request::set_header(const char* key, const char* val)
  741. {
  742. headers.insert(std::make_pair(key, val));
  743. }
  744. inline bool Request::has_param(const char* key) const
  745. {
  746. return params.find(key) != params.end();
  747. }
  748. // Response implementation
  749. inline bool Response::has_header(const char* key) const
  750. {
  751. return headers.find(key) != headers.end();
  752. }
  753. inline std::string Response::get_header_value(const char* key) const
  754. {
  755. return detail::get_header_value(headers, key, "");
  756. }
  757. inline void Response::set_header(const char* key, const char* val)
  758. {
  759. headers.insert(std::make_pair(key, val));
  760. }
  761. inline void Response::set_redirect(const char* url)
  762. {
  763. set_header("Location", url);
  764. status = 302;
  765. }
  766. inline void Response::set_content(const char* s, size_t n, const char* content_type)
  767. {
  768. body.assign(s, n);
  769. set_header("Content-Type", content_type);
  770. }
  771. inline void Response::set_content(const std::string& s, const char* content_type)
  772. {
  773. body = s;
  774. set_header("Content-Type", content_type);
  775. }
  776. // Socket stream implementation
  777. inline SocketStream::SocketStream(socket_t sock): sock_(sock)
  778. {
  779. }
  780. inline SocketStream::~SocketStream()
  781. {
  782. }
  783. inline int SocketStream::read(char* ptr, size_t size)
  784. {
  785. return recv(sock_, ptr, size, 0);
  786. }
  787. inline int SocketStream::write(const char* ptr, size_t size)
  788. {
  789. return send(sock_, ptr, size, 0);
  790. }
  791. inline int SocketStream::write(const char* ptr)
  792. {
  793. return write(ptr, strlen(ptr));
  794. }
  795. // HTTP server implementation
  796. inline Server::Server()
  797. : svr_sock_(-1)
  798. {
  799. #ifndef _MSC_VER
  800. signal(SIGPIPE, SIG_IGN);
  801. #endif
  802. }
  803. inline Server::~Server()
  804. {
  805. }
  806. inline Server& Server::get(const char* pattern, Handler handler)
  807. {
  808. get_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  809. return *this;
  810. }
  811. inline Server& Server::post(const char* pattern, Handler handler)
  812. {
  813. post_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  814. return *this;
  815. }
  816. inline bool Server::set_base_dir(const char* path)
  817. {
  818. if (detail::is_dir(path)) {
  819. base_dir_ = path;
  820. return true;
  821. }
  822. return false;
  823. }
  824. inline void Server::set_error_handler(Handler handler)
  825. {
  826. error_handler_ = handler;
  827. }
  828. inline void Server::set_logger(Logger logger)
  829. {
  830. logger_ = logger;
  831. }
  832. inline bool Server::listen(const char* host, int port, int socket_flags)
  833. {
  834. svr_sock_ = detail::create_server_socket(host, port, socket_flags);
  835. if (svr_sock_ == -1) {
  836. return false;
  837. }
  838. auto ret = true;
  839. for (;;) {
  840. socket_t sock = accept(svr_sock_, NULL, NULL);
  841. if (sock == -1) {
  842. if (svr_sock_ != -1) {
  843. detail::close_socket(svr_sock_);
  844. ret = false;
  845. } else {
  846. ; // The server socket was closed by user.
  847. }
  848. break;
  849. }
  850. // TODO: should be async
  851. read_and_close_socket(sock);
  852. }
  853. return ret;
  854. }
  855. inline void Server::stop()
  856. {
  857. detail::shutdown_socket(svr_sock_);
  858. detail::close_socket(svr_sock_);
  859. svr_sock_ = -1;
  860. }
  861. inline bool Server::read_request_line(Stream& strm, Request& req)
  862. {
  863. const auto BUFSIZ_REQUESTLINE = 2048;
  864. char buf[BUFSIZ_REQUESTLINE];
  865. if (!detail::socket_gets(strm, buf, BUFSIZ_REQUESTLINE)) {
  866. return false;
  867. }
  868. static std::regex re("(GET|HEAD|POST) ([^?]+)(?:\\?(.+?))? HTTP/1\\.[01]\r\n");
  869. std::cmatch m;
  870. if (std::regex_match(buf, m, re)) {
  871. req.method = std::string(m[1]);
  872. req.path = detail::decode_url(m[2]);
  873. // Parse query text
  874. auto len = std::distance(m[3].first, m[3].second);
  875. if (len > 0) {
  876. detail::parse_query_text(m[3], req.params);
  877. }
  878. return true;
  879. }
  880. return false;
  881. }
  882. inline void Server::write_response(Stream& strm, const Request& req, Response& res)
  883. {
  884. assert(res.status != -1);
  885. if (400 <= res.status && error_handler_) {
  886. error_handler_(req, res);
  887. }
  888. detail::write_response(strm, req, res);
  889. if (logger_) {
  890. logger_(req, res);
  891. }
  892. }
  893. inline bool Server::handle_file_request(Request& req, Response& res)
  894. {
  895. if (!base_dir_.empty() && detail::is_valid_path(req.path)) {
  896. std::string path = base_dir_ + req.path;
  897. if (!path.empty() && path.back() == '/') {
  898. path += "index.html";
  899. }
  900. if (detail::is_file(path)) {
  901. detail::read_file(path, res.body);
  902. auto type = detail::content_type(path);
  903. if (type) {
  904. res.set_header("Content-Type", type);
  905. }
  906. res.status = 200;
  907. return true;
  908. }
  909. }
  910. return false;
  911. }
  912. inline bool Server::routing(Request& req, Response& res)
  913. {
  914. if (req.method == "GET" && handle_file_request(req, res)) {
  915. return true;
  916. }
  917. if (req.method == "GET" || req.method == "HEAD") {
  918. return dispatch_request(req, res, get_handlers_);
  919. } else if (req.method == "POST") {
  920. return dispatch_request(req, res, post_handlers_);
  921. }
  922. return false;
  923. }
  924. inline bool Server::dispatch_request(Request& req, Response& res, Handlers& handlers)
  925. {
  926. for (const auto& x: handlers) {
  927. const auto& pattern = x.first;
  928. const auto& handler = x.second;
  929. if (std::regex_match(req.path, req.matches, pattern)) {
  930. handler(req, res);
  931. return true;
  932. }
  933. }
  934. return false;
  935. }
  936. inline void Server::process_request(Stream& strm)
  937. {
  938. Request req;
  939. Response res;
  940. if (!read_request_line(strm, req) || !detail::read_headers(strm, req.headers)) {
  941. res.status = 400;
  942. write_response(strm, req, res);
  943. return;
  944. }
  945. if (req.method == "POST") {
  946. if (!detail::read_content(strm, req)) {
  947. res.status = 400;
  948. write_response(strm, req, res);
  949. return;
  950. }
  951. static std::string type = "application/x-www-form-urlencoded";
  952. if (!req.get_header_value("Content-Type").compare(0, type.size(), type)) {
  953. detail::parse_query_text(req.body, req.params);
  954. }
  955. }
  956. if (routing(req, res)) {
  957. if (res.status == -1) {
  958. res.status = 200;
  959. }
  960. } else {
  961. res.status = 404;
  962. }
  963. write_response(strm, req, res);
  964. }
  965. inline bool Server::read_and_close_socket(socket_t sock)
  966. {
  967. return detail::read_and_close_socket(sock, [this](Stream& strm) {
  968. process_request(strm);
  969. return true;
  970. });
  971. }
  972. // HTTP client implementation
  973. inline Client::Client(const char* host, int port, HttpVersion http_version)
  974. : host_(host)
  975. , port_(port)
  976. , http_version_(http_version)
  977. , host_and_port_(host_ + ":" + std::to_string(port_))
  978. {
  979. }
  980. inline Client::~Client()
  981. {
  982. }
  983. inline bool Client::read_response_line(Stream& strm, Response& res)
  984. {
  985. const auto BUFSIZ_RESPONSELINE = 2048;
  986. char buf[BUFSIZ_RESPONSELINE];
  987. if (!detail::socket_gets(strm, buf, BUFSIZ_RESPONSELINE)) {
  988. return false;
  989. }
  990. const static std::regex re("HTTP/1\\.[01] (\\d+?) .+\r\n");
  991. std::cmatch m;
  992. if (std::regex_match(buf, m, re)) {
  993. res.status = std::stoi(std::string(m[1]));
  994. }
  995. return true;
  996. }
  997. inline bool Client::send(const Request& req, Response& res)
  998. {
  999. auto sock = detail::create_client_socket(host_.c_str(), port_);
  1000. if (sock == -1) {
  1001. return false;
  1002. }
  1003. return read_and_close_socket(sock, req, res);
  1004. }
  1005. inline bool Client::process_request(Stream& strm, const Request& req, Response& res)
  1006. {
  1007. // Send request
  1008. auto ver = detail::http_version_strings[static_cast<size_t>(http_version_)];
  1009. detail::write_request(strm, req, ver);
  1010. // Receive response
  1011. if (!read_response_line(strm, res) ||
  1012. !detail::read_headers(strm, res.headers)) {
  1013. return false;
  1014. }
  1015. if (req.method != "HEAD") {
  1016. if (!detail::read_content(strm, res, req.progress)) {
  1017. return false;
  1018. }
  1019. }
  1020. return true;
  1021. }
  1022. inline bool Client::read_and_close_socket(socket_t sock, const Request& req, Response& res)
  1023. {
  1024. return detail::read_and_close_socket(sock, [&](Stream& strm) {
  1025. return process_request(strm, req, res);
  1026. });
  1027. }
  1028. inline void Client::add_default_headers(Request& req)
  1029. {
  1030. req.set_header("Host", host_and_port_.c_str());
  1031. req.set_header("Accept", "*/*");
  1032. req.set_header("User-Agent", "cpp-httplib/0.1");
  1033. }
  1034. inline std::shared_ptr<Response> Client::get(const char* path, Progress callback)
  1035. {
  1036. Request req;
  1037. req.method = "GET";
  1038. req.path = path;
  1039. req.progress = callback;
  1040. add_default_headers(req);
  1041. auto res = std::make_shared<Response>();
  1042. return send(req, *res) ? res : nullptr;
  1043. }
  1044. inline std::shared_ptr<Response> Client::head(const char* path)
  1045. {
  1046. Request req;
  1047. req.method = "HEAD";
  1048. req.path = path;
  1049. add_default_headers(req);
  1050. auto res = std::make_shared<Response>();
  1051. return send(req, *res) ? res : nullptr;
  1052. }
  1053. inline std::shared_ptr<Response> Client::post(
  1054. const char* path, const std::string& body, const char* content_type)
  1055. {
  1056. Request req;
  1057. req.method = "POST";
  1058. req.path = path;
  1059. add_default_headers(req);
  1060. req.set_header("Content-Type", content_type);
  1061. req.body = body;
  1062. auto res = std::make_shared<Response>();
  1063. return send(req, *res) ? res : nullptr;
  1064. }
  1065. inline std::shared_ptr<Response> Client::post(
  1066. const char* path, const Map& params)
  1067. {
  1068. std::string query;
  1069. for (auto it = params.begin(); it != params.end(); ++it) {
  1070. if (it != params.begin()) {
  1071. query += "&";
  1072. }
  1073. query += it->first;
  1074. query += "=";
  1075. query += it->second;
  1076. }
  1077. return post(path, query, "application/x-www-form-urlencoded");
  1078. }
  1079. /*
  1080. * SSL Implementation
  1081. */
  1082. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1083. namespace detail {
  1084. template <typename U, typename V, typename T>
  1085. inline bool read_and_close_socket_ssl(socket_t sock, SSL_CTX* ctx, U SSL_connect_or_accept, V setup, T callback)
  1086. {
  1087. auto ssl = SSL_new(ctx);
  1088. auto bio = BIO_new_socket(sock, BIO_NOCLOSE);
  1089. SSL_set_bio(ssl, bio, bio);
  1090. setup(ssl);
  1091. SSL_connect_or_accept(ssl);
  1092. SSLSocketStream strm(ssl);
  1093. auto ret = callback(strm);
  1094. SSL_shutdown(ssl);
  1095. SSL_free(ssl);
  1096. close_socket(sock);
  1097. return ret;
  1098. }
  1099. class SSLInit {
  1100. public:
  1101. SSLInit() {
  1102. SSL_load_error_strings();
  1103. SSL_library_init();
  1104. }
  1105. };
  1106. static SSLInit sslinit_;
  1107. } // namespace detail
  1108. // SSL socket stream implementation
  1109. inline SSLSocketStream::SSLSocketStream(SSL* ssl): ssl_(ssl)
  1110. {
  1111. }
  1112. inline SSLSocketStream::~SSLSocketStream()
  1113. {
  1114. }
  1115. inline int SSLSocketStream::read(char* ptr, size_t size)
  1116. {
  1117. return SSL_read(ssl_, ptr, size);
  1118. }
  1119. inline int SSLSocketStream::write(const char* ptr, size_t size)
  1120. {
  1121. return SSL_write(ssl_, ptr, size);
  1122. }
  1123. inline int SSLSocketStream::write(const char* ptr)
  1124. {
  1125. return write(ptr, strlen(ptr));
  1126. }
  1127. // SSL HTTP server implementation
  1128. inline SSLServer::SSLServer(const char* cert_path, const char* private_key_path)
  1129. {
  1130. ctx_ = SSL_CTX_new(SSLv23_server_method());
  1131. if (ctx_) {
  1132. SSL_CTX_set_options(ctx_,
  1133. SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
  1134. SSL_OP_NO_COMPRESSION |
  1135. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  1136. // auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  1137. // SSL_CTX_set_tmp_ecdh(ctx_, ecdh);
  1138. // EC_KEY_free(ecdh);
  1139. if (SSL_CTX_use_certificate_file(ctx_, cert_path, SSL_FILETYPE_PEM) != 1 ||
  1140. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) != 1) {
  1141. SSL_CTX_free(ctx_);
  1142. ctx_ = nullptr;
  1143. }
  1144. }
  1145. }
  1146. inline SSLServer::~SSLServer()
  1147. {
  1148. if (ctx_) {
  1149. SSL_CTX_free(ctx_);
  1150. }
  1151. }
  1152. inline bool SSLServer::read_and_close_socket(socket_t sock)
  1153. {
  1154. return detail::read_and_close_socket_ssl(
  1155. sock, ctx_,
  1156. SSL_accept,
  1157. [](SSL* /*ssl*/) {},
  1158. [this](Stream& strm) {
  1159. process_request(strm);
  1160. return true;
  1161. });
  1162. }
  1163. // SSL HTTP client implementation
  1164. inline SSLClient::SSLClient(const char* host, int port, HttpVersion http_version)
  1165. : Client(host, port, http_version)
  1166. {
  1167. ctx_ = SSL_CTX_new(SSLv23_client_method());
  1168. }
  1169. inline SSLClient::~SSLClient()
  1170. {
  1171. if (ctx_) {
  1172. SSL_CTX_free(ctx_);
  1173. }
  1174. }
  1175. inline bool SSLClient::read_and_close_socket(socket_t sock, const Request& req, Response& res)
  1176. {
  1177. return detail::read_and_close_socket_ssl(
  1178. sock, ctx_,
  1179. SSL_connect,
  1180. [&](SSL* ssl) {
  1181. SSL_set_tlsext_host_name(ssl, host_.c_str());
  1182. },
  1183. [&](Stream& strm) {
  1184. return process_request(strm, req, res);
  1185. });
  1186. }
  1187. #endif
  1188. } // namespace httplib
  1189. #endif
  1190. // vim: et ts=4 sw=4 cin cino={1s ff=unix