httplib.h 49 KB

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