httplib.h 50 KB

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