httplib.h 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2017 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #ifndef _CPPHTTPLIB_HTTPLIB_H_
  8. #define _CPPHTTPLIB_HTTPLIB_H_
  9. #ifdef _WIN32
  10. #ifndef _CRT_SECURE_NO_WARNINGS
  11. #define _CRT_SECURE_NO_WARNINGS
  12. #endif
  13. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  14. #define _CRT_NONSTDC_NO_DEPRECATE
  15. #endif
  16. #if defined(_MSC_VER) && _MSC_VER < 1900
  17. #define snprintf _snprintf_s
  18. #endif
  19. #ifndef S_ISREG
  20. #define S_ISREG(m) (((m)&S_IFREG)==S_IFREG)
  21. #endif
  22. #ifndef S_ISDIR
  23. #define S_ISDIR(m) (((m)&S_IFDIR)==S_IFDIR)
  24. #endif
  25. #include <fcntl.h>
  26. #include <io.h>
  27. #include <winsock2.h>
  28. #include <ws2tcpip.h>
  29. #undef min
  30. #undef max
  31. typedef SOCKET socket_t;
  32. #else
  33. #include <pthread.h>
  34. #include <unistd.h>
  35. #include <netdb.h>
  36. #include <cstring>
  37. #include <netinet/in.h>
  38. #include <arpa/inet.h>
  39. #include <signal.h>
  40. #include <sys/socket.h>
  41. typedef int socket_t;
  42. #endif
  43. #include <fstream>
  44. #include <functional>
  45. #include <map>
  46. #include <memory>
  47. #include <regex>
  48. #include <string>
  49. #include <thread>
  50. #include <sys/stat.h>
  51. #include <assert.h>
  52. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  53. #include <openssl/ssl.h>
  54. #endif
  55. /*
  56. * Configuration
  57. */
  58. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 5
  59. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  60. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND 0
  61. namespace httplib
  62. {
  63. namespace detail {
  64. struct ci {
  65. bool operator() (const std::string & s1, const std::string & s2) const {
  66. return std::lexicographical_compare(
  67. s1.begin(), s1.end(),
  68. s2.begin(), s2.end(),
  69. [](char c1, char c2) {
  70. return ::tolower(c1) < ::tolower(c2);
  71. });
  72. }
  73. };
  74. } // namespace detail
  75. enum class HttpVersion { v1_0 = 0, v1_1 };
  76. typedef std::multimap<std::string, std::string, detail::ci> Headers;
  77. template<typename uint64_t, typename... Args>
  78. std::pair<std::string, std::string> make_range_header(uint64_t value, Args... args);
  79. typedef std::multimap<std::string, std::string> Params;
  80. typedef std::smatch Match;
  81. typedef std::function<void (uint64_t current, uint64_t total)> Progress;
  82. struct MultipartFile {
  83. std::string filename;
  84. std::string content_type;
  85. size_t offset = 0;
  86. size_t length = 0;
  87. };
  88. typedef std::multimap<std::string, MultipartFile> MultipartFiles;
  89. struct Request {
  90. std::string version;
  91. std::string method;
  92. std::string path;
  93. Headers headers;
  94. std::string body;
  95. Params params;
  96. MultipartFiles files;
  97. Match matches;
  98. Progress progress;
  99. bool has_header(const char* key) const;
  100. std::string get_header_value(const char* key) const;
  101. void set_header(const char* key, const char* val);
  102. bool has_param(const char* key) const;
  103. std::string get_param_value(const char* key) const;
  104. bool has_file(const char* key) const;
  105. MultipartFile get_file_value(const char* key) const;
  106. };
  107. struct Response {
  108. std::string version;
  109. int status;
  110. Headers headers;
  111. std::string body;
  112. bool has_header(const char* key) const;
  113. std::string get_header_value(const char* key) const;
  114. void set_header(const char* key, const char* val);
  115. void set_redirect(const char* url);
  116. void set_content(const char* s, size_t n, const char* content_type);
  117. void set_content(const std::string& s, const char* content_type);
  118. Response() : status(-1) {}
  119. };
  120. class Stream {
  121. public:
  122. virtual ~Stream() {}
  123. virtual int read(char* ptr, size_t size) = 0;
  124. virtual int write(const char* ptr, size_t size1) = 0;
  125. virtual int write(const char* ptr) = 0;
  126. template <typename ...Args>
  127. void write_format(const char* fmt, const Args& ...args);
  128. };
  129. class SocketStream : public Stream {
  130. public:
  131. SocketStream(socket_t sock);
  132. virtual ~SocketStream();
  133. virtual int read(char* ptr, size_t size);
  134. virtual int write(const char* ptr, size_t size);
  135. virtual int write(const char* ptr);
  136. private:
  137. socket_t sock_;
  138. };
  139. class Server {
  140. public:
  141. typedef std::function<void (const Request&, Response&)> Handler;
  142. typedef std::function<void (const Request&, const Response&)> Logger;
  143. Server(HttpVersion http_version = HttpVersion::v1_0);
  144. virtual ~Server();
  145. virtual bool is_valid() const;
  146. Server& get(const char* pattern, Handler handler);
  147. Server& post(const char* pattern, Handler handler);
  148. bool set_base_dir(const char* path);
  149. void set_error_handler(Handler handler);
  150. void set_logger(Logger logger);
  151. bool listen(const char* host, int port, int socket_flags = 0);
  152. bool is_running() const;
  153. void stop();
  154. protected:
  155. bool process_request(Stream& strm, bool last_connection);
  156. const HttpVersion http_version_;
  157. private:
  158. typedef std::vector<std::pair<std::regex, Handler>> Handlers;
  159. bool routing(Request& req, Response& res);
  160. bool handle_file_request(Request& req, Response& res);
  161. bool dispatch_request(Request& req, Response& res, Handlers& handlers);
  162. bool parse_request_line(const char* s, Request& req);
  163. void write_response(Stream& strm, bool last_connection, const Request& req, Response& res);
  164. virtual bool read_and_close_socket(socket_t sock);
  165. socket_t svr_sock_;
  166. std::string base_dir_;
  167. Handlers get_handlers_;
  168. Handlers post_handlers_;
  169. Handler error_handler_;
  170. Logger logger_;
  171. };
  172. class Client {
  173. public:
  174. Client(const char* host, int port, HttpVersion http_version = HttpVersion::v1_0);
  175. virtual ~Client();
  176. virtual bool is_valid() const;
  177. std::shared_ptr<Response> get(const char* path, Progress progress = nullptr);
  178. std::shared_ptr<Response> get(const char* path, const Headers& headers, Progress progress = nullptr);
  179. std::shared_ptr<Response> head(const char* path);
  180. std::shared_ptr<Response> head(const char* path, const Headers& headers);
  181. std::shared_ptr<Response> post(const char* path, const std::string& body, const char* content_type);
  182. std::shared_ptr<Response> post(const char* path, const Headers& headers, const std::string& body, const char* content_type);
  183. std::shared_ptr<Response> post(const char* path, const Params& params);
  184. std::shared_ptr<Response> post(const char* path, const Headers& headers, const Params& params);
  185. bool send(Request& req, Response& res);
  186. protected:
  187. bool process_request(Stream& strm, Request& req, Response& res);
  188. const std::string host_;
  189. const int port_;
  190. const HttpVersion http_version_;
  191. const std::string host_and_port_;
  192. private:
  193. bool read_response_line(Stream& strm, Response& res);
  194. void write_request(Stream& strm, Request& req);
  195. virtual bool read_and_close_socket(socket_t sock, Request& req, Response& res);
  196. };
  197. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  198. class SSLSocketStream : public Stream {
  199. public:
  200. SSLSocketStream(SSL* ssl);
  201. virtual ~SSLSocketStream();
  202. virtual int read(char* ptr, size_t size);
  203. virtual int write(const char* ptr, size_t size);
  204. virtual int write(const char* ptr);
  205. private:
  206. SSL* ssl_;
  207. };
  208. class SSLServer : public Server {
  209. public:
  210. SSLServer(
  211. const char* cert_path, const char* private_key_path,
  212. HttpVersion http_version = HttpVersion::v1_0);
  213. virtual ~SSLServer();
  214. virtual bool is_valid() const;
  215. private:
  216. virtual bool read_and_close_socket(socket_t sock);
  217. SSL_CTX* ctx_;
  218. };
  219. class SSLClient : public Client {
  220. public:
  221. SSLClient(const char* host, int port, HttpVersion http_version = HttpVersion::v1_0);
  222. virtual ~SSLClient();
  223. virtual bool is_valid() const;
  224. private:
  225. virtual bool read_and_close_socket(socket_t sock, Request& req, Response& res);
  226. SSL_CTX* ctx_;
  227. };
  228. #endif
  229. /*
  230. * Implementation
  231. */
  232. namespace detail {
  233. static std::vector<const char*> http_version_strings = { "HTTP/1.0", "HTTP/1.1" };
  234. template <class Fn>
  235. void split(const char* b, const char* e, char d, Fn fn)
  236. {
  237. int i = 0;
  238. int beg = 0;
  239. while (e ? (b + i != e) : (b[i] != '\0')) {
  240. if (b[i] == d) {
  241. fn(&b[beg], &b[i]);
  242. beg = i + 1;
  243. }
  244. i++;
  245. }
  246. if (i) {
  247. fn(&b[beg], &b[i]);
  248. }
  249. }
  250. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  251. // to store data. The call can set memory on stack for performance.
  252. class stream_line_reader {
  253. public:
  254. stream_line_reader(Stream& strm, char* fixed_buffer, size_t fixed_buffer_size)
  255. : strm_(strm)
  256. , fixed_buffer_(fixed_buffer)
  257. , fixed_buffer_size_(fixed_buffer_size) {
  258. }
  259. const char* ptr() const {
  260. if (glowable_buffer_.empty()) {
  261. return fixed_buffer_;
  262. } else {
  263. return glowable_buffer_.data();
  264. }
  265. }
  266. bool getline() {
  267. fixed_buffer_used_size_ = 0;
  268. glowable_buffer_.clear();
  269. for (size_t i = 0; ; i++) {
  270. char byte;
  271. auto n = strm_.read(&byte, 1);
  272. if (n < 0) {
  273. return false;
  274. } else if (n == 0) {
  275. if (i == 0) {
  276. return false;
  277. } else {
  278. break;
  279. }
  280. }
  281. append(byte);
  282. if (byte == '\n') {
  283. break;
  284. }
  285. }
  286. return true;
  287. }
  288. private:
  289. void append(char c) {
  290. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  291. fixed_buffer_[fixed_buffer_used_size_++] = c;
  292. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  293. } else {
  294. if (glowable_buffer_.empty()) {
  295. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  296. glowable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  297. }
  298. glowable_buffer_ += c;
  299. }
  300. }
  301. Stream& strm_;
  302. char* fixed_buffer_;
  303. const size_t fixed_buffer_size_;
  304. size_t fixed_buffer_used_size_;
  305. std::string glowable_buffer_;
  306. };
  307. inline int close_socket(socket_t sock)
  308. {
  309. #ifdef _WIN32
  310. return closesocket(sock);
  311. #else
  312. return close(sock);
  313. #endif
  314. }
  315. inline int select(socket_t sock, size_t sec, size_t usec)
  316. {
  317. fd_set fds;
  318. FD_ZERO(&fds);
  319. FD_SET(sock, &fds);
  320. timeval tv;
  321. tv.tv_sec = sec;
  322. tv.tv_usec = usec;
  323. return ::select(sock + 1, &fds, NULL, NULL, &tv);
  324. }
  325. template <typename T>
  326. inline bool read_and_close_socket(socket_t sock, bool keep_alive, T callback)
  327. {
  328. bool ret = false;
  329. if (keep_alive) {
  330. auto count = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  331. while (count > 0 &&
  332. detail::select(sock,
  333. CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND,
  334. CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND) > 0) {
  335. auto last_connection = count == 1;
  336. SocketStream strm(sock);
  337. ret = callback(strm, last_connection);
  338. if (!ret) {
  339. break;
  340. }
  341. count--;
  342. }
  343. } else {
  344. SocketStream strm(sock);
  345. ret = callback(strm, true);
  346. }
  347. close_socket(sock);
  348. return ret;
  349. }
  350. inline int shutdown_socket(socket_t sock)
  351. {
  352. #ifdef _WIN32
  353. return shutdown(sock, SD_BOTH);
  354. #else
  355. return shutdown(sock, SHUT_RDWR);
  356. #endif
  357. }
  358. template <typename Fn>
  359. socket_t create_socket(const char* host, int port, Fn fn, int socket_flags = 0)
  360. {
  361. #ifdef _WIN32
  362. #define SO_SYNCHRONOUS_NONALERT 0x20
  363. #define SO_OPENTYPE 0x7008
  364. int opt = SO_SYNCHRONOUS_NONALERT;
  365. setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char*)&opt, sizeof(opt));
  366. #endif
  367. // Get address info
  368. struct addrinfo hints;
  369. struct addrinfo *result;
  370. memset(&hints, 0, sizeof(struct addrinfo));
  371. hints.ai_family = AF_UNSPEC;
  372. hints.ai_socktype = SOCK_STREAM;
  373. hints.ai_flags = socket_flags;
  374. hints.ai_protocol = 0;
  375. auto service = std::to_string(port);
  376. if (getaddrinfo(host, service.c_str(), &hints, &result)) {
  377. return -1;
  378. }
  379. for (auto rp = result; rp; rp = rp->ai_next) {
  380. // Create a socket
  381. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  382. if (sock == -1) {
  383. continue;
  384. }
  385. // Make 'reuse address' option available
  386. int yes = 1;
  387. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(yes));
  388. // bind or connect
  389. if (fn(sock, *rp)) {
  390. freeaddrinfo(result);
  391. return sock;
  392. }
  393. close_socket(sock);
  394. }
  395. freeaddrinfo(result);
  396. return -1;
  397. }
  398. inline socket_t create_server_socket(const char* host, int port, int socket_flags)
  399. {
  400. return create_socket(host, port, [](socket_t sock, struct addrinfo& ai) -> socket_t {
  401. if (::bind(sock, ai.ai_addr, ai.ai_addrlen)) {
  402. return false;
  403. }
  404. if (listen(sock, 5)) { // Listen through 5 channels
  405. return false;
  406. }
  407. return true;
  408. }, socket_flags);
  409. }
  410. inline socket_t create_client_socket(const char* host, int port)
  411. {
  412. return create_socket(host, port, [](socket_t sock, struct addrinfo& ai) -> socket_t {
  413. if (connect(sock, ai.ai_addr, ai.ai_addrlen)) {
  414. return false;
  415. }
  416. return true;
  417. });
  418. }
  419. inline bool is_file(const std::string& path)
  420. {
  421. struct stat st;
  422. return stat(path.c_str(), &st) >= 0 && S_ISREG(st.st_mode);
  423. }
  424. inline bool is_dir(const std::string& path)
  425. {
  426. struct stat st;
  427. return stat(path.c_str(), &st) >= 0 && S_ISDIR(st.st_mode);
  428. }
  429. inline bool is_valid_path(const std::string& path) {
  430. size_t level = 0;
  431. size_t i = 0;
  432. // Skip slash
  433. while (i < path.size() && path[i] == '/') {
  434. i++;
  435. }
  436. while (i < path.size()) {
  437. // Read component
  438. auto beg = i;
  439. while (i < path.size() && path[i] != '/') {
  440. i++;
  441. }
  442. auto len = i - beg;
  443. assert(len > 0);
  444. if (!path.compare(beg, len, ".")) {
  445. ;
  446. } else if (!path.compare(beg, len, "..")) {
  447. if (level == 0) {
  448. return false;
  449. }
  450. level--;
  451. } else {
  452. level++;
  453. }
  454. // Skip slash
  455. while (i < path.size() && path[i] == '/') {
  456. i++;
  457. }
  458. }
  459. return true;
  460. }
  461. inline void read_file(const std::string& path, std::string& out)
  462. {
  463. std::ifstream fs(path, std::ios_base::binary);
  464. fs.seekg(0, std::ios_base::end);
  465. auto size = fs.tellg();
  466. fs.seekg(0);
  467. out.resize(static_cast<size_t>(size));
  468. fs.read(&out[0], size);
  469. }
  470. inline std::string file_extension(const std::string& path)
  471. {
  472. std::smatch m;
  473. auto pat = std::regex("\\.([a-zA-Z0-9]+)$");
  474. if (std::regex_search(path, m, pat)) {
  475. return m[1].str();
  476. }
  477. return std::string();
  478. }
  479. inline const char* content_type(const std::string& path)
  480. {
  481. auto ext = file_extension(path);
  482. if (ext == "txt") {
  483. return "text/plain";
  484. } else if (ext == "html") {
  485. return "text/html";
  486. } else if (ext == "js") {
  487. return "text/javascript";
  488. } else if (ext == "css") {
  489. return "text/css";
  490. } else if (ext == "xml") {
  491. return "text/xml";
  492. } else if (ext == "jpeg" || ext == "jpg") {
  493. return "image/jpg";
  494. } else if (ext == "png") {
  495. return "image/png";
  496. } else if (ext == "gif") {
  497. return "image/gif";
  498. } else if (ext == "svg") {
  499. return "image/svg+xml";
  500. } else if (ext == "ico") {
  501. return "image/x-icon";
  502. } else if (ext == "json") {
  503. return "application/json";
  504. } else if (ext == "pdf") {
  505. return "application/pdf";
  506. } else if (ext == "xhtml") {
  507. return "application/xhtml+xml";
  508. }
  509. return nullptr;
  510. }
  511. inline const char* status_message(int status)
  512. {
  513. switch (status) {
  514. case 200: return "OK";
  515. case 400: return "Bad Request";
  516. case 404: return "Not Found";
  517. default:
  518. case 500: return "Internal Server Error";
  519. }
  520. }
  521. inline const char* get_header_value(const Headers& headers, const char* key, const char* def)
  522. {
  523. auto it = headers.find(key);
  524. if (it != headers.end()) {
  525. return it->second.c_str();
  526. }
  527. return def;
  528. }
  529. inline int get_header_value_int(const Headers& headers, const char* key, int def)
  530. {
  531. auto it = headers.find(key);
  532. if (it != headers.end()) {
  533. return std::stoi(it->second);
  534. }
  535. return def;
  536. }
  537. inline bool read_headers(Stream& strm, Headers& headers)
  538. {
  539. static std::regex re(R"((.+?):\s*(.+?)\s*\r\n)");
  540. const auto bufsiz = 2048;
  541. char buf[bufsiz];
  542. stream_line_reader reader(strm, buf, bufsiz);
  543. for (;;) {
  544. if (!reader.getline()) {
  545. return false;
  546. }
  547. if (!strcmp(reader.ptr(), "\r\n")) {
  548. break;
  549. }
  550. std::cmatch m;
  551. if (std::regex_match(reader.ptr(), m, re)) {
  552. auto key = std::string(m[1]);
  553. auto val = std::string(m[2]);
  554. headers.emplace(key, val);
  555. }
  556. }
  557. return true;
  558. }
  559. template <typename T>
  560. bool read_content_with_length(Stream& strm, T& x, size_t len, Progress progress)
  561. {
  562. x.body.assign(len, 0);
  563. size_t r = 0;
  564. while (r < len){
  565. auto n = strm.read(&x.body[r], len - r);
  566. if (n <= 0) {
  567. return false;
  568. }
  569. r += n;
  570. if (progress) {
  571. progress(r, len);
  572. }
  573. }
  574. return true;
  575. }
  576. template <typename T>
  577. bool read_content_without_length(Stream& strm, T& x)
  578. {
  579. for (;;) {
  580. char byte;
  581. auto n = strm.read(&byte, 1);
  582. if (n < 0) {
  583. return false;
  584. } else if (n == 0) {
  585. return true;
  586. }
  587. x.body += byte;
  588. }
  589. return true;
  590. }
  591. template <typename T>
  592. bool read_content_chunked(Stream& strm, T& x)
  593. {
  594. const auto bufsiz = 16;
  595. char buf[bufsiz];
  596. stream_line_reader reader(strm, buf, bufsiz);
  597. if (!reader.getline()) {
  598. return false;
  599. }
  600. auto chunk_len = std::stoi(reader.ptr(), 0, 16);
  601. while (chunk_len > 0){
  602. std::string chunk(chunk_len, 0);
  603. auto n = strm.read(&chunk[0], chunk_len);
  604. if (n <= 0) {
  605. return false;
  606. }
  607. if (!reader.getline()) {
  608. return false;
  609. }
  610. if (strcmp(reader.ptr(), "\r\n")) {
  611. break;
  612. }
  613. x.body += chunk;
  614. if (!reader.getline()) {
  615. return false;
  616. }
  617. chunk_len = std::stoi(reader.ptr(), 0, 16);
  618. }
  619. return true;
  620. }
  621. template <typename T>
  622. bool read_content(Stream& strm, T& x, Progress progress = Progress())
  623. {
  624. auto len = get_header_value_int(x.headers, "Content-Length", 0);
  625. if (len) {
  626. return read_content_with_length(strm, x, len, progress);
  627. } else {
  628. auto encoding = get_header_value(x.headers, "Transfer-Encoding", "");
  629. if (!strcmp(encoding, "chunked")) {
  630. return read_content_chunked(strm, x);
  631. } else {
  632. return read_content_without_length(strm, x);
  633. }
  634. }
  635. return true;
  636. }
  637. template <typename T>
  638. inline void write_headers(Stream& strm, const T& info)
  639. {
  640. for (const auto& x: info.headers) {
  641. strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str());
  642. }
  643. strm.write("\r\n");
  644. }
  645. inline std::string encode_url(const std::string& s)
  646. {
  647. std::string result;
  648. for (auto i = 0; s[i]; i++) {
  649. switch (s[i]) {
  650. case ' ': result += "+"; break;
  651. case '\'': result += "%27"; break;
  652. case ',': result += "%2C"; break;
  653. case ':': result += "%3A"; break;
  654. case ';': result += "%3B"; break;
  655. default:
  656. if (s[i] < 0) {
  657. result += '%';
  658. char hex[4];
  659. size_t len = snprintf(hex, sizeof(hex) - 1, "%02X", (unsigned char)s[i]);
  660. assert(len == 2);
  661. result.append(hex, len);
  662. } else {
  663. result += s[i];
  664. }
  665. break;
  666. }
  667. }
  668. return result;
  669. }
  670. inline bool is_hex(char c, int& v)
  671. {
  672. if (0x20 <= c && isdigit(c)) {
  673. v = c - '0';
  674. return true;
  675. } else if ('A' <= c && c <= 'F') {
  676. v = c - 'A' + 10;
  677. return true;
  678. } else if ('a' <= c && c <= 'f') {
  679. v = c - 'a' + 10;
  680. return true;
  681. }
  682. return false;
  683. }
  684. inline bool from_hex_to_i(const std::string& s, int i, int cnt, int& val)
  685. {
  686. val = 0;
  687. for (; cnt; i++, cnt--) {
  688. if (!s[i]) {
  689. return false;
  690. }
  691. int v = 0;
  692. if (is_hex(s[i], v)) {
  693. val = val * 16 + v;
  694. } else {
  695. return false;
  696. }
  697. }
  698. return true;
  699. }
  700. inline size_t to_utf8(int code, char* buff)
  701. {
  702. if (code < 0x0080) {
  703. buff[0] = (code & 0x7F);
  704. return 1;
  705. } else if (code < 0x0800) {
  706. buff[0] = (0xC0 | ((code >> 6) & 0x1F));
  707. buff[1] = (0x80 | (code & 0x3F));
  708. return 2;
  709. } else if (code < 0xD800) {
  710. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  711. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  712. buff[2] = (0x80 | (code & 0x3F));
  713. return 3;
  714. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  715. return 0;
  716. } else if (code < 0x10000) {
  717. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  718. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  719. buff[2] = (0x80 | (code & 0x3F));
  720. return 3;
  721. } else if (code < 0x110000) {
  722. buff[0] = (0xF0 | ((code >> 18) & 0x7));
  723. buff[1] = (0x80 | ((code >> 12) & 0x3F));
  724. buff[2] = (0x80 | ((code >> 6) & 0x3F));
  725. buff[3] = (0x80 | (code & 0x3F));
  726. return 4;
  727. }
  728. // NOTREACHED
  729. return 0;
  730. }
  731. inline std::string decode_url(const std::string& s)
  732. {
  733. std::string result;
  734. for (int i = 0; s[i]; i++) {
  735. if (s[i] == '%') {
  736. if (s[i + 1] && s[i + 1] == 'u') {
  737. int val = 0;
  738. if (from_hex_to_i(s, i + 2, 4, val)) {
  739. // 4 digits Unicode codes
  740. char buff[4];
  741. size_t len = to_utf8(val, buff);
  742. if (len > 0) {
  743. result.append(buff, len);
  744. }
  745. i += 5; // 'u0000'
  746. } else {
  747. result += s[i];
  748. }
  749. } else {
  750. int val = 0;
  751. if (from_hex_to_i(s, i + 1, 2, val)) {
  752. // 2 digits hex codes
  753. result += val;
  754. i += 2; // '00'
  755. } else {
  756. result += s[i];
  757. }
  758. }
  759. } else if (s[i] == '+') {
  760. result += ' ';
  761. } else {
  762. result += s[i];
  763. }
  764. }
  765. return result;
  766. }
  767. inline void parse_query_text(const std::string& s, Params& params)
  768. {
  769. split(&s[0], &s[s.size()], '&', [&](const char* b, const char* e) {
  770. std::string key;
  771. std::string val;
  772. split(b, e, '=', [&](const char* b, const char* e) {
  773. if (key.empty()) {
  774. key.assign(b, e);
  775. } else {
  776. val.assign(b, e);
  777. }
  778. });
  779. params.emplace(key, decode_url(val));
  780. });
  781. }
  782. inline bool parse_multipart_boundary(const std::string& content_type, std::string& boundary)
  783. {
  784. auto pos = content_type.find("boundary=");
  785. if (pos == std::string::npos) {
  786. return false;
  787. }
  788. boundary = content_type.substr(pos + 9);
  789. return true;
  790. }
  791. inline bool parse_multipart_formdata(
  792. const std::string& boundary, const std::string& body, MultipartFiles& files)
  793. {
  794. static std::string dash = "--";
  795. static std::string crlf = "\r\n";
  796. static std::regex re_content_type(
  797. "Content-Type: (.*?)");
  798. static std::regex re_content_disposition(
  799. "Content-Disposition: form-data; name=\"(.*?)\"(?:; filename=\"(.*?)\")?");
  800. auto dash_boundary = dash + boundary;
  801. auto pos = body.find(dash_boundary);
  802. if (pos != 0) {
  803. return false;
  804. }
  805. pos += dash_boundary.size();
  806. auto next_pos = body.find(crlf, pos);
  807. if (next_pos == std::string::npos) {
  808. return false;
  809. }
  810. pos = next_pos + crlf.size();
  811. while (pos < body.size()) {
  812. next_pos = body.find(crlf, pos);
  813. if (next_pos == std::string::npos) {
  814. return false;
  815. }
  816. std::string name;
  817. MultipartFile file;
  818. auto header = body.substr(pos, (next_pos - pos));
  819. while (pos != next_pos) {
  820. std::smatch m;
  821. if (std::regex_match(header, m, re_content_type)) {
  822. file.content_type = m[1];
  823. } else if (std::regex_match(header, m, re_content_disposition)) {
  824. name = m[1];
  825. file.filename = m[2];
  826. }
  827. pos = next_pos + crlf.size();
  828. next_pos = body.find(crlf, pos);
  829. if (next_pos == std::string::npos) {
  830. return false;
  831. }
  832. header = body.substr(pos, (next_pos - pos));
  833. }
  834. pos = next_pos + crlf.size();
  835. next_pos = body.find(crlf + dash_boundary, pos);
  836. if (next_pos == std::string::npos) {
  837. return false;
  838. }
  839. file.offset = pos;
  840. file.length = next_pos - pos;
  841. pos = next_pos + crlf.size() + dash_boundary.size();
  842. next_pos = body.find(crlf, pos);
  843. if (next_pos == std::string::npos) {
  844. return false;
  845. }
  846. files.emplace(name, file);
  847. pos = next_pos + crlf.size();
  848. }
  849. return true;
  850. }
  851. inline std::string to_lower(const char* beg, const char* end)
  852. {
  853. std::string out;
  854. auto it = beg;
  855. while (it != end) {
  856. out += ::tolower(*it);
  857. it++;
  858. }
  859. return out;
  860. }
  861. inline void make_range_header_core(std::string&) {}
  862. template<typename uint64_t>
  863. inline void make_range_header_core(std::string& field, uint64_t value)
  864. {
  865. if (!field.empty()) {
  866. field += ", ";
  867. }
  868. field += std::to_string(value) + "-";
  869. }
  870. template<typename uint64_t, typename... Args>
  871. inline void make_range_header_core(std::string& field, uint64_t value1, uint64_t value2, Args... args)
  872. {
  873. if (!field.empty()) {
  874. field += ", ";
  875. }
  876. field += std::to_string(value1) + "-" + std::to_string(value2);
  877. make_range_header_core(field, args...);
  878. }
  879. #ifdef _WIN32
  880. class WSInit {
  881. public:
  882. WSInit() {
  883. WSADATA wsaData;
  884. WSAStartup(0x0002, &wsaData);
  885. }
  886. ~WSInit() {
  887. WSACleanup();
  888. }
  889. };
  890. static WSInit wsinit_;
  891. #endif
  892. } // namespace detail
  893. // Header utilities
  894. template<typename uint64_t, typename... Args>
  895. inline std::pair<std::string, std::string> make_range_header(uint64_t value, Args... args)
  896. {
  897. std::string field;
  898. detail::make_range_header_core(field, value, args...);
  899. field.insert(0, "bytes=");
  900. return std::make_pair("Range", field);
  901. }
  902. // Request implementation
  903. inline bool Request::has_header(const char* key) const
  904. {
  905. return headers.find(key) != headers.end();
  906. }
  907. inline std::string Request::get_header_value(const char* key) const
  908. {
  909. return detail::get_header_value(headers, key, "");
  910. }
  911. inline void Request::set_header(const char* key, const char* val)
  912. {
  913. headers.emplace(key, val);
  914. }
  915. inline bool Request::has_param(const char* key) const
  916. {
  917. return params.find(key) != params.end();
  918. }
  919. inline std::string Request::get_param_value(const char* key) const
  920. {
  921. auto it = params.find(key);
  922. if (it != params.end()) {
  923. return it->second;
  924. }
  925. return std::string();
  926. }
  927. inline bool Request::has_file(const char* key) const
  928. {
  929. return files.find(key) != files.end();
  930. }
  931. inline MultipartFile Request::get_file_value(const char* key) const
  932. {
  933. auto it = files.find(key);
  934. if (it != files.end()) {
  935. return it->second;
  936. }
  937. return MultipartFile();
  938. }
  939. // Response implementation
  940. inline bool Response::has_header(const char* key) const
  941. {
  942. return headers.find(key) != headers.end();
  943. }
  944. inline std::string Response::get_header_value(const char* key) const
  945. {
  946. return detail::get_header_value(headers, key, "");
  947. }
  948. inline void Response::set_header(const char* key, const char* val)
  949. {
  950. headers.emplace(key, val);
  951. }
  952. inline void Response::set_redirect(const char* url)
  953. {
  954. set_header("Location", url);
  955. status = 302;
  956. }
  957. inline void Response::set_content(const char* s, size_t n, const char* content_type)
  958. {
  959. body.assign(s, n);
  960. set_header("Content-Type", content_type);
  961. }
  962. inline void Response::set_content(const std::string& s, const char* content_type)
  963. {
  964. body = s;
  965. set_header("Content-Type", content_type);
  966. }
  967. // Rstream implementation
  968. template <typename ...Args>
  969. inline void Stream::write_format(const char* fmt, const Args& ...args)
  970. {
  971. const auto bufsiz = 2048;
  972. char buf[bufsiz];
  973. #if defined(_MSC_VER) && _MSC_VER < 1900
  974. auto n = _snprintf_s(buf, bufsiz, bufsiz - 1, fmt, args...);
  975. #else
  976. auto n = snprintf(buf, bufsiz - 1, fmt, args...);
  977. #endif
  978. if (n > 0) {
  979. if (n >= bufsiz - 1) {
  980. std::vector<char> glowable_buf(bufsiz);
  981. while (n >= static_cast<int>(glowable_buf.size() - 1)) {
  982. glowable_buf.resize(glowable_buf.size() * 2);
  983. #if defined(_MSC_VER) && _MSC_VER < 1900
  984. n = _snprintf_s(&glowable_buf[0], glowable_buf.size(), glowable_buf.size() - 1, fmt, args...);
  985. #else
  986. n = snprintf(&glowable_buf[0], glowable_buf.size() - 1, fmt, args...);
  987. #endif
  988. }
  989. write(&glowable_buf[0], n);
  990. } else {
  991. write(buf, n);
  992. }
  993. }
  994. }
  995. // Socket stream implementation
  996. inline SocketStream::SocketStream(socket_t sock): sock_(sock)
  997. {
  998. }
  999. inline SocketStream::~SocketStream()
  1000. {
  1001. }
  1002. inline int SocketStream::read(char* ptr, size_t size)
  1003. {
  1004. return recv(sock_, ptr, size, 0);
  1005. }
  1006. inline int SocketStream::write(const char* ptr, size_t size)
  1007. {
  1008. return send(sock_, ptr, size, 0);
  1009. }
  1010. inline int SocketStream::write(const char* ptr)
  1011. {
  1012. return write(ptr, strlen(ptr));
  1013. }
  1014. // HTTP server implementation
  1015. inline Server::Server(HttpVersion http_version)
  1016. : http_version_(http_version)
  1017. , svr_sock_(-1)
  1018. {
  1019. #ifndef _WIN32
  1020. signal(SIGPIPE, SIG_IGN);
  1021. #endif
  1022. }
  1023. inline Server::~Server()
  1024. {
  1025. }
  1026. inline Server& Server::get(const char* pattern, Handler handler)
  1027. {
  1028. get_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  1029. return *this;
  1030. }
  1031. inline Server& Server::post(const char* pattern, Handler handler)
  1032. {
  1033. post_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  1034. return *this;
  1035. }
  1036. inline bool Server::set_base_dir(const char* path)
  1037. {
  1038. if (detail::is_dir(path)) {
  1039. base_dir_ = path;
  1040. return true;
  1041. }
  1042. return false;
  1043. }
  1044. inline void Server::set_error_handler(Handler handler)
  1045. {
  1046. error_handler_ = handler;
  1047. }
  1048. inline void Server::set_logger(Logger logger)
  1049. {
  1050. logger_ = logger;
  1051. }
  1052. inline bool Server::listen(const char* host, int port, int socket_flags)
  1053. {
  1054. if (!is_valid()) {
  1055. return false;
  1056. }
  1057. svr_sock_ = detail::create_server_socket(host, port, socket_flags);
  1058. if (svr_sock_ == -1) {
  1059. return false;
  1060. }
  1061. auto ret = true;
  1062. for (;;) {
  1063. auto val = detail::select(svr_sock_, 0, 100000);
  1064. if (val == 0) { // Timeout
  1065. if (svr_sock_ == -1) {
  1066. // The server socket was closed by 'stop' method.
  1067. break;
  1068. }
  1069. continue;
  1070. }
  1071. socket_t sock = accept(svr_sock_, NULL, NULL);
  1072. if (sock == -1) {
  1073. if (svr_sock_ != -1) {
  1074. detail::close_socket(svr_sock_);
  1075. ret = false;
  1076. } else {
  1077. ; // The server socket was closed by user.
  1078. }
  1079. break;
  1080. }
  1081. // TODO: Use thread pool...
  1082. std::thread([=]() {
  1083. read_and_close_socket(sock);
  1084. }).detach();
  1085. }
  1086. return ret;
  1087. }
  1088. inline bool Server::is_running() const
  1089. {
  1090. return svr_sock_ != -1;
  1091. }
  1092. inline void Server::stop()
  1093. {
  1094. detail::shutdown_socket(svr_sock_);
  1095. detail::close_socket(svr_sock_);
  1096. svr_sock_ = -1;
  1097. }
  1098. inline bool Server::parse_request_line(const char* s, Request& req)
  1099. {
  1100. static std::regex re("(GET|HEAD|POST) ([^?]+)(?:\\?(.+?))? (HTTP/1\\.[01])\r\n");
  1101. std::cmatch m;
  1102. if (std::regex_match(s, m, re)) {
  1103. req.version = std::string(m[4]);
  1104. req.method = std::string(m[1]);
  1105. req.path = detail::decode_url(m[2]);
  1106. // Parse query text
  1107. auto len = std::distance(m[3].first, m[3].second);
  1108. if (len > 0) {
  1109. detail::parse_query_text(m[3], req.params);
  1110. }
  1111. return true;
  1112. }
  1113. return false;
  1114. }
  1115. inline void Server::write_response(Stream& strm, bool last_connection, const Request& req, Response& res)
  1116. {
  1117. assert(res.status != -1);
  1118. if (400 <= res.status && error_handler_) {
  1119. error_handler_(req, res);
  1120. }
  1121. // Response line
  1122. strm.write_format("%s %d %s\r\n",
  1123. detail::http_version_strings[static_cast<size_t>(http_version_)],
  1124. res.status,
  1125. detail::status_message(res.status));
  1126. // Headers
  1127. if (!res.has_header("Connection") && (last_connection || req.version == "HTTP/1.0")) {
  1128. res.set_header("Connection", "close");
  1129. }
  1130. if (!res.body.empty()) {
  1131. if (!res.has_header("Content-Type")) {
  1132. res.set_header("Content-Type", "text/plain");
  1133. }
  1134. auto length = std::to_string(res.body.size());
  1135. res.set_header("Content-Length", length.c_str());
  1136. }
  1137. detail::write_headers(strm, res);
  1138. // Body
  1139. if (!res.body.empty() && req.method != "HEAD") {
  1140. strm.write(res.body.c_str(), res.body.size());
  1141. }
  1142. // Log
  1143. if (logger_) {
  1144. logger_(req, res);
  1145. }
  1146. }
  1147. inline bool Server::handle_file_request(Request& req, Response& res)
  1148. {
  1149. if (!base_dir_.empty() && detail::is_valid_path(req.path)) {
  1150. std::string path = base_dir_ + req.path;
  1151. if (!path.empty() && path.back() == '/') {
  1152. path += "index.html";
  1153. }
  1154. if (detail::is_file(path)) {
  1155. detail::read_file(path, res.body);
  1156. auto type = detail::content_type(path);
  1157. if (type) {
  1158. res.set_header("Content-Type", type);
  1159. }
  1160. res.status = 200;
  1161. return true;
  1162. }
  1163. }
  1164. return false;
  1165. }
  1166. inline bool Server::routing(Request& req, Response& res)
  1167. {
  1168. if (req.method == "GET" && handle_file_request(req, res)) {
  1169. return true;
  1170. }
  1171. if (req.method == "GET" || req.method == "HEAD") {
  1172. return dispatch_request(req, res, get_handlers_);
  1173. } else if (req.method == "POST") {
  1174. return dispatch_request(req, res, post_handlers_);
  1175. }
  1176. return false;
  1177. }
  1178. inline bool Server::dispatch_request(Request& req, Response& res, Handlers& handlers)
  1179. {
  1180. for (const auto& x: handlers) {
  1181. const auto& pattern = x.first;
  1182. const auto& handler = x.second;
  1183. if (std::regex_match(req.path, req.matches, pattern)) {
  1184. handler(req, res);
  1185. return true;
  1186. }
  1187. }
  1188. return false;
  1189. }
  1190. inline bool Server::process_request(Stream& strm, bool last_connection)
  1191. {
  1192. const auto bufsiz = 2048;
  1193. char buf[bufsiz];
  1194. detail::stream_line_reader reader(strm, buf, bufsiz);
  1195. // Connection has been closed on client
  1196. if (!reader.getline()) {
  1197. return false;
  1198. }
  1199. Request req;
  1200. Response res;
  1201. res.version = detail::http_version_strings[static_cast<size_t>(http_version_)];
  1202. // Request line and headers
  1203. if (!parse_request_line(reader.ptr(), req) || !detail::read_headers(strm, req.headers)) {
  1204. res.status = 400;
  1205. write_response(strm, last_connection, req, res);
  1206. return true;
  1207. }
  1208. auto ret = true;
  1209. if (req.get_header_value("Connection") == "close") {
  1210. ret = false;
  1211. }
  1212. // Body
  1213. if (req.method == "POST") {
  1214. if (!detail::read_content(strm, req)) {
  1215. res.status = 400;
  1216. write_response(strm, last_connection, req, res);
  1217. return ret;
  1218. }
  1219. const auto& content_type = req.get_header_value("Content-Type");
  1220. if (!content_type.find("application/x-www-form-urlencoded")) {
  1221. detail::parse_query_text(req.body, req.params);
  1222. } else if(!content_type.find("multipart/form-data")) {
  1223. std::string boundary;
  1224. if (!detail::parse_multipart_boundary(content_type, boundary) ||
  1225. !detail::parse_multipart_formdata(boundary, req.body, req.files)) {
  1226. res.status = 400;
  1227. write_response(strm, last_connection, req, res);
  1228. return ret;
  1229. }
  1230. }
  1231. }
  1232. if (routing(req, res)) {
  1233. if (res.status == -1) {
  1234. res.status = 200;
  1235. }
  1236. } else {
  1237. res.status = 404;
  1238. }
  1239. write_response(strm, last_connection, req, res);
  1240. return ret;
  1241. }
  1242. inline bool Server::is_valid() const
  1243. {
  1244. return true;
  1245. }
  1246. inline bool Server::read_and_close_socket(socket_t sock)
  1247. {
  1248. auto keep_alive = http_version_ == HttpVersion::v1_1;
  1249. return detail::read_and_close_socket(
  1250. sock,
  1251. keep_alive,
  1252. [this](Stream& strm, bool last_connection) {
  1253. return process_request(strm, last_connection);
  1254. });
  1255. }
  1256. // HTTP client implementation
  1257. inline Client::Client(const char* host, int port, HttpVersion http_version)
  1258. : host_(host)
  1259. , port_(port)
  1260. , http_version_(http_version)
  1261. , host_and_port_(host_ + ":" + std::to_string(port_))
  1262. {
  1263. }
  1264. inline Client::~Client()
  1265. {
  1266. }
  1267. inline bool Client::is_valid() const
  1268. {
  1269. return true;
  1270. }
  1271. inline bool Client::read_response_line(Stream& strm, Response& res)
  1272. {
  1273. const auto bufsiz = 2048;
  1274. char buf[bufsiz];
  1275. detail::stream_line_reader reader(strm, buf, bufsiz);
  1276. if (!reader.getline()) {
  1277. return false;
  1278. }
  1279. const static std::regex re("HTTP/1\\.[01] (\\d+?) .+\r\n");
  1280. std::cmatch m;
  1281. if (std::regex_match(reader.ptr(), m, re)) {
  1282. res.status = std::stoi(std::string(m[1]));
  1283. }
  1284. return true;
  1285. }
  1286. inline bool Client::send(Request& req, Response& res)
  1287. {
  1288. if (req.path.empty()) {
  1289. return false;
  1290. }
  1291. auto sock = detail::create_client_socket(host_.c_str(), port_);
  1292. if (sock == -1) {
  1293. return false;
  1294. }
  1295. return read_and_close_socket(sock, req, res);
  1296. }
  1297. inline void Client::write_request(Stream& strm, Request& req)
  1298. {
  1299. auto path = detail::encode_url(req.path);
  1300. // Request line
  1301. strm.write_format("%s %s %s\r\n",
  1302. req.method.c_str(),
  1303. path.c_str(),
  1304. detail::http_version_strings[static_cast<size_t>(http_version_)]);
  1305. // Headers
  1306. req.set_header("Host", host_and_port_.c_str());
  1307. if (!req.has_header("Accept")) {
  1308. req.set_header("Accept", "*/*");
  1309. }
  1310. if (!req.has_header("User-Agent")) {
  1311. req.set_header("User-Agent", "cpp-httplib/0.2");
  1312. }
  1313. // TODO: if (!req.has_header("Connection") &&
  1314. // (last_connection || http_version_ == detail::HttpVersion::v1_0)) {
  1315. if (!req.has_header("Connection")) {
  1316. req.set_header("Connection", "close");
  1317. }
  1318. if (!req.body.empty()) {
  1319. if (!req.has_header("Content-Type")) {
  1320. req.set_header("Content-Type", "text/plain");
  1321. }
  1322. auto length = std::to_string(req.body.size());
  1323. req.set_header("Content-Length", length.c_str());
  1324. }
  1325. detail::write_headers(strm, req);
  1326. // Body
  1327. if (!req.body.empty()) {
  1328. if (req.get_header_value("Content-Type") == "application/x-www-form-urlencoded") {
  1329. auto str = detail::encode_url(req.body);
  1330. strm.write(str.c_str(), str.size());
  1331. } else {
  1332. strm.write(req.body.c_str(), req.body.size());
  1333. }
  1334. }
  1335. }
  1336. inline bool Client::process_request(Stream& strm, Request& req, Response& res)
  1337. {
  1338. // Send request
  1339. write_request(strm, req);
  1340. // Receive response and headers
  1341. if (!read_response_line(strm, res) || !detail::read_headers(strm, res.headers)) {
  1342. return false;
  1343. }
  1344. // TODO: Check if 'Connection' header is 'close' or HTTP version is 1.0, then close socket...
  1345. // Body
  1346. if (req.method != "HEAD") {
  1347. if (!detail::read_content(strm, res, req.progress)) {
  1348. return false;
  1349. }
  1350. }
  1351. return true;
  1352. }
  1353. inline bool Client::read_and_close_socket(socket_t sock, Request& req, Response& res)
  1354. {
  1355. return detail::read_and_close_socket(sock, false, [&](Stream& strm, bool /*last_connection*/) {
  1356. return process_request(strm, req, res);
  1357. });
  1358. }
  1359. inline std::shared_ptr<Response> Client::get(const char* path, Progress progress)
  1360. {
  1361. return get(path, Headers(), progress);
  1362. }
  1363. inline std::shared_ptr<Response> Client::get(const char* path, const Headers& headers, Progress progress)
  1364. {
  1365. Request req;
  1366. req.method = "GET";
  1367. req.path = path;
  1368. req.headers = headers;
  1369. req.progress = progress;
  1370. auto res = std::make_shared<Response>();
  1371. return send(req, *res) ? res : nullptr;
  1372. }
  1373. inline std::shared_ptr<Response> Client::head(const char* path)
  1374. {
  1375. return head(path, Headers());
  1376. }
  1377. inline std::shared_ptr<Response> Client::head(const char* path, const Headers& headers)
  1378. {
  1379. Request req;
  1380. req.method = "HEAD";
  1381. req.headers = headers;
  1382. req.path = path;
  1383. auto res = std::make_shared<Response>();
  1384. return send(req, *res) ? res : nullptr;
  1385. }
  1386. inline std::shared_ptr<Response> Client::post(
  1387. const char* path, const std::string& body, const char* content_type)
  1388. {
  1389. return post(path, Headers(), body, content_type);
  1390. }
  1391. inline std::shared_ptr<Response> Client::post(
  1392. const char* path, const Headers& headers, const std::string& body, const char* content_type)
  1393. {
  1394. Request req;
  1395. req.method = "POST";
  1396. req.headers = headers;
  1397. req.path = path;
  1398. req.headers.emplace("Content-Type", content_type);
  1399. req.body = body;
  1400. auto res = std::make_shared<Response>();
  1401. return send(req, *res) ? res : nullptr;
  1402. }
  1403. inline std::shared_ptr<Response> Client::post(const char* path, const Params& params)
  1404. {
  1405. return post(path, Headers(), params);
  1406. }
  1407. inline std::shared_ptr<Response> Client::post(const char* path, const Headers& headers, const Params& params)
  1408. {
  1409. std::string query;
  1410. for (auto it = params.begin(); it != params.end(); ++it) {
  1411. if (it != params.begin()) {
  1412. query += "&";
  1413. }
  1414. query += it->first;
  1415. query += "=";
  1416. query += it->second;
  1417. }
  1418. return post(path, headers, query, "application/x-www-form-urlencoded");
  1419. }
  1420. /*
  1421. * SSL Implementation
  1422. */
  1423. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1424. namespace detail {
  1425. template <typename U, typename V, typename T>
  1426. inline bool read_and_close_socket_ssl(
  1427. socket_t sock, bool keep_alive,
  1428. SSL_CTX* ctx, U SSL_connect_or_accept, V setup,
  1429. T callback)
  1430. {
  1431. auto ssl = SSL_new(ctx);
  1432. if (!ssl) {
  1433. return false;
  1434. }
  1435. auto bio = BIO_new_socket(sock, BIO_NOCLOSE);
  1436. SSL_set_bio(ssl, bio, bio);
  1437. setup(ssl);
  1438. SSL_connect_or_accept(ssl);
  1439. bool ret = false;
  1440. if (keep_alive) {
  1441. auto count = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  1442. while (count > 0 &&
  1443. detail::select(sock,
  1444. CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND,
  1445. CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND) > 0) {
  1446. auto last_connection = count == 1;
  1447. SSLSocketStream strm(ssl);
  1448. ret = callback(strm, last_connection);
  1449. if (!ret) {
  1450. break;
  1451. }
  1452. count--;
  1453. }
  1454. } else {
  1455. SSLSocketStream strm(ssl);
  1456. ret = callback(strm, true);
  1457. }
  1458. SSL_shutdown(ssl);
  1459. SSL_free(ssl);
  1460. close_socket(sock);
  1461. return ret;
  1462. }
  1463. class SSLInit {
  1464. public:
  1465. SSLInit() {
  1466. SSL_load_error_strings();
  1467. SSL_library_init();
  1468. }
  1469. };
  1470. static SSLInit sslinit_;
  1471. } // namespace detail
  1472. // SSL socket stream implementation
  1473. inline SSLSocketStream::SSLSocketStream(SSL* ssl): ssl_(ssl)
  1474. {
  1475. }
  1476. inline SSLSocketStream::~SSLSocketStream()
  1477. {
  1478. }
  1479. inline int SSLSocketStream::read(char* ptr, size_t size)
  1480. {
  1481. return SSL_read(ssl_, ptr, size);
  1482. }
  1483. inline int SSLSocketStream::write(const char* ptr, size_t size)
  1484. {
  1485. return SSL_write(ssl_, ptr, size);
  1486. }
  1487. inline int SSLSocketStream::write(const char* ptr)
  1488. {
  1489. return write(ptr, strlen(ptr));
  1490. }
  1491. // SSL HTTP server implementation
  1492. inline SSLServer::SSLServer(const char* cert_path, const char* private_key_path, HttpVersion http_version)
  1493. : Server(http_version)
  1494. {
  1495. ctx_ = SSL_CTX_new(SSLv23_server_method());
  1496. if (ctx_) {
  1497. SSL_CTX_set_options(ctx_,
  1498. SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
  1499. SSL_OP_NO_COMPRESSION |
  1500. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  1501. // auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  1502. // SSL_CTX_set_tmp_ecdh(ctx_, ecdh);
  1503. // EC_KEY_free(ecdh);
  1504. if (SSL_CTX_use_certificate_file(ctx_, cert_path, SSL_FILETYPE_PEM) != 1 ||
  1505. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) != 1) {
  1506. SSL_CTX_free(ctx_);
  1507. ctx_ = nullptr;
  1508. }
  1509. }
  1510. }
  1511. inline SSLServer::~SSLServer()
  1512. {
  1513. if (ctx_) {
  1514. SSL_CTX_free(ctx_);
  1515. }
  1516. }
  1517. inline bool SSLServer::is_valid() const
  1518. {
  1519. return ctx_;
  1520. }
  1521. inline bool SSLServer::read_and_close_socket(socket_t sock)
  1522. {
  1523. auto keep_alive = http_version_ == HttpVersion::v1_1;
  1524. return detail::read_and_close_socket_ssl(
  1525. sock,
  1526. keep_alive,
  1527. ctx_,
  1528. SSL_accept,
  1529. [](SSL* /*ssl*/) {},
  1530. [this](Stream& strm, bool last_connection) {
  1531. return process_request(strm, last_connection);
  1532. });
  1533. }
  1534. // SSL HTTP client implementation
  1535. inline SSLClient::SSLClient(const char* host, int port, HttpVersion http_version)
  1536. : Client(host, port, http_version)
  1537. {
  1538. ctx_ = SSL_CTX_new(SSLv23_client_method());
  1539. }
  1540. inline SSLClient::~SSLClient()
  1541. {
  1542. if (ctx_) {
  1543. SSL_CTX_free(ctx_);
  1544. }
  1545. }
  1546. inline bool SSLClient::is_valid() const
  1547. {
  1548. return ctx_;
  1549. }
  1550. inline bool SSLClient::read_and_close_socket(socket_t sock, Request& req, Response& res)
  1551. {
  1552. return is_valid() && detail::read_and_close_socket_ssl(
  1553. sock, false,
  1554. ctx_, SSL_connect,
  1555. [&](SSL* ssl) {
  1556. SSL_set_tlsext_host_name(ssl, host_.c_str());
  1557. },
  1558. [&](Stream& strm, bool /*last_connection*/) {
  1559. return process_request(strm, req, res);
  1560. });
  1561. }
  1562. #endif
  1563. } // namespace httplib
  1564. #endif
  1565. // vim: et ts=4 sw=4 cin cino={1s ff=unix