httplib.h 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133
  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. case 406: return "Not Acceptable";
  571. default:
  572. case 500: return "Internal Server Error";
  573. }
  574. }
  575. inline const char* get_header_value(const Headers& headers, const char* key, const char* def)
  576. {
  577. auto it = headers.find(key);
  578. if (it != headers.end()) {
  579. return it->second.c_str();
  580. }
  581. return def;
  582. }
  583. inline int get_header_value_int(const Headers& headers, const char* key, int def)
  584. {
  585. auto it = headers.find(key);
  586. if (it != headers.end()) {
  587. return std::stoi(it->second);
  588. }
  589. return def;
  590. }
  591. inline bool read_headers(Stream& strm, Headers& headers)
  592. {
  593. static std::regex re(R"((.+?):\s*(.+?)\s*\r\n)");
  594. const auto bufsiz = 2048;
  595. char buf[bufsiz];
  596. stream_line_reader reader(strm, buf, bufsiz);
  597. for (;;) {
  598. if (!reader.getline()) {
  599. return false;
  600. }
  601. if (!strcmp(reader.ptr(), "\r\n")) {
  602. break;
  603. }
  604. std::cmatch m;
  605. if (std::regex_match(reader.ptr(), m, re)) {
  606. auto key = std::string(m[1]);
  607. auto val = std::string(m[2]);
  608. headers.emplace(key, val);
  609. }
  610. }
  611. return true;
  612. }
  613. template <typename T>
  614. bool read_content_with_length(Stream& strm, T& x, size_t len, Progress progress)
  615. {
  616. x.body.assign(len, 0);
  617. size_t r = 0;
  618. while (r < len){
  619. auto n = strm.read(&x.body[r], len - r);
  620. if (n <= 0) {
  621. return false;
  622. }
  623. r += n;
  624. if (progress) {
  625. progress(r, len);
  626. }
  627. }
  628. return true;
  629. }
  630. template <typename T>
  631. bool read_content_without_length(Stream& strm, T& x)
  632. {
  633. for (;;) {
  634. char byte;
  635. auto n = strm.read(&byte, 1);
  636. if (n < 0) {
  637. return false;
  638. } else if (n == 0) {
  639. return true;
  640. }
  641. x.body += byte;
  642. }
  643. return true;
  644. }
  645. template <typename T>
  646. bool read_content_chunked(Stream& strm, T& x)
  647. {
  648. const auto bufsiz = 16;
  649. char buf[bufsiz];
  650. stream_line_reader reader(strm, buf, bufsiz);
  651. if (!reader.getline()) {
  652. return false;
  653. }
  654. auto chunk_len = std::stoi(reader.ptr(), 0, 16);
  655. while (chunk_len > 0){
  656. std::string chunk(chunk_len, 0);
  657. auto n = strm.read(&chunk[0], chunk_len);
  658. if (n <= 0) {
  659. return false;
  660. }
  661. if (!reader.getline()) {
  662. return false;
  663. }
  664. if (strcmp(reader.ptr(), "\r\n")) {
  665. break;
  666. }
  667. x.body += chunk;
  668. if (!reader.getline()) {
  669. return false;
  670. }
  671. chunk_len = std::stoi(reader.ptr(), 0, 16);
  672. }
  673. return true;
  674. }
  675. template <typename T>
  676. bool read_content(Stream& strm, T& x, Progress progress = Progress())
  677. {
  678. auto len = get_header_value_int(x.headers, "Content-Length", 0);
  679. if (len) {
  680. return read_content_with_length(strm, x, len, progress);
  681. } else {
  682. const auto& encoding = get_header_value(x.headers, "Transfer-Encoding", "");
  683. if (!strcmp(encoding, "chunked")) {
  684. return read_content_chunked(strm, x);
  685. } else {
  686. return read_content_without_length(strm, x);
  687. }
  688. }
  689. return true;
  690. }
  691. template <typename T>
  692. inline void write_headers(Stream& strm, const T& info)
  693. {
  694. for (const auto& x: info.headers) {
  695. strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str());
  696. }
  697. strm.write("\r\n");
  698. }
  699. inline std::string encode_url(const std::string& s)
  700. {
  701. std::string result;
  702. for (auto i = 0; s[i]; i++) {
  703. switch (s[i]) {
  704. case ' ': result += "+"; break;
  705. case '\'': result += "%27"; break;
  706. case ',': result += "%2C"; break;
  707. case ':': result += "%3A"; break;
  708. case ';': result += "%3B"; break;
  709. default:
  710. if (s[i] < 0) {
  711. result += '%';
  712. char hex[4];
  713. size_t len = snprintf(hex, sizeof(hex) - 1, "%02X", (unsigned char)s[i]);
  714. assert(len == 2);
  715. result.append(hex, len);
  716. } else {
  717. result += s[i];
  718. }
  719. break;
  720. }
  721. }
  722. return result;
  723. }
  724. inline bool is_hex(char c, int& v)
  725. {
  726. if (0x20 <= c && isdigit(c)) {
  727. v = c - '0';
  728. return true;
  729. } else if ('A' <= c && c <= 'F') {
  730. v = c - 'A' + 10;
  731. return true;
  732. } else if ('a' <= c && c <= 'f') {
  733. v = c - 'a' + 10;
  734. return true;
  735. }
  736. return false;
  737. }
  738. inline bool from_hex_to_i(const std::string& s, int i, int cnt, int& val)
  739. {
  740. val = 0;
  741. for (; cnt; i++, cnt--) {
  742. if (!s[i]) {
  743. return false;
  744. }
  745. int v = 0;
  746. if (is_hex(s[i], v)) {
  747. val = val * 16 + v;
  748. } else {
  749. return false;
  750. }
  751. }
  752. return true;
  753. }
  754. inline size_t to_utf8(int code, char* buff)
  755. {
  756. if (code < 0x0080) {
  757. buff[0] = (code & 0x7F);
  758. return 1;
  759. } else if (code < 0x0800) {
  760. buff[0] = (0xC0 | ((code >> 6) & 0x1F));
  761. buff[1] = (0x80 | (code & 0x3F));
  762. return 2;
  763. } else if (code < 0xD800) {
  764. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  765. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  766. buff[2] = (0x80 | (code & 0x3F));
  767. return 3;
  768. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  769. return 0;
  770. } else if (code < 0x10000) {
  771. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  772. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  773. buff[2] = (0x80 | (code & 0x3F));
  774. return 3;
  775. } else if (code < 0x110000) {
  776. buff[0] = (0xF0 | ((code >> 18) & 0x7));
  777. buff[1] = (0x80 | ((code >> 12) & 0x3F));
  778. buff[2] = (0x80 | ((code >> 6) & 0x3F));
  779. buff[3] = (0x80 | (code & 0x3F));
  780. return 4;
  781. }
  782. // NOTREACHED
  783. return 0;
  784. }
  785. inline std::string decode_url(const std::string& s)
  786. {
  787. std::string result;
  788. for (int i = 0; s[i]; i++) {
  789. if (s[i] == '%') {
  790. if (s[i + 1] && s[i + 1] == 'u') {
  791. int val = 0;
  792. if (from_hex_to_i(s, i + 2, 4, val)) {
  793. // 4 digits Unicode codes
  794. char buff[4];
  795. size_t len = to_utf8(val, buff);
  796. if (len > 0) {
  797. result.append(buff, len);
  798. }
  799. i += 5; // 'u0000'
  800. } else {
  801. result += s[i];
  802. }
  803. } else {
  804. int val = 0;
  805. if (from_hex_to_i(s, i + 1, 2, val)) {
  806. // 2 digits hex codes
  807. result += val;
  808. i += 2; // '00'
  809. } else {
  810. result += s[i];
  811. }
  812. }
  813. } else if (s[i] == '+') {
  814. result += ' ';
  815. } else {
  816. result += s[i];
  817. }
  818. }
  819. return result;
  820. }
  821. inline void parse_query_text(const std::string& s, Params& params)
  822. {
  823. split(&s[0], &s[s.size()], '&', [&](const char* b, const char* e) {
  824. std::string key;
  825. std::string val;
  826. split(b, e, '=', [&](const char* b, const char* e) {
  827. if (key.empty()) {
  828. key.assign(b, e);
  829. } else {
  830. val.assign(b, e);
  831. }
  832. });
  833. params.emplace(key, decode_url(val));
  834. });
  835. }
  836. inline bool parse_multipart_boundary(const std::string& content_type, std::string& boundary)
  837. {
  838. auto pos = content_type.find("boundary=");
  839. if (pos == std::string::npos) {
  840. return false;
  841. }
  842. boundary = content_type.substr(pos + 9);
  843. return true;
  844. }
  845. inline bool parse_multipart_formdata(
  846. const std::string& boundary, const std::string& body, MultipartFiles& files)
  847. {
  848. static std::string dash = "--";
  849. static std::string crlf = "\r\n";
  850. static std::regex re_content_type(
  851. "Content-Type: (.*?)", std::regex_constants::icase);
  852. static std::regex re_content_disposition(
  853. "Content-Disposition: form-data; name=\"(.*?)\"(?:; filename=\"(.*?)\")?",
  854. std::regex_constants::icase);
  855. auto dash_boundary = dash + boundary;
  856. auto pos = body.find(dash_boundary);
  857. if (pos != 0) {
  858. return false;
  859. }
  860. pos += dash_boundary.size();
  861. auto next_pos = body.find(crlf, pos);
  862. if (next_pos == std::string::npos) {
  863. return false;
  864. }
  865. pos = next_pos + crlf.size();
  866. while (pos < body.size()) {
  867. next_pos = body.find(crlf, pos);
  868. if (next_pos == std::string::npos) {
  869. return false;
  870. }
  871. std::string name;
  872. MultipartFile file;
  873. auto header = body.substr(pos, (next_pos - pos));
  874. while (pos != next_pos) {
  875. std::smatch m;
  876. if (std::regex_match(header, m, re_content_type)) {
  877. file.content_type = m[1];
  878. } else if (std::regex_match(header, m, re_content_disposition)) {
  879. name = m[1];
  880. file.filename = m[2];
  881. }
  882. pos = next_pos + crlf.size();
  883. next_pos = body.find(crlf, pos);
  884. if (next_pos == std::string::npos) {
  885. return false;
  886. }
  887. header = body.substr(pos, (next_pos - pos));
  888. }
  889. pos = next_pos + crlf.size();
  890. next_pos = body.find(crlf + dash_boundary, pos);
  891. if (next_pos == std::string::npos) {
  892. return false;
  893. }
  894. file.offset = pos;
  895. file.length = next_pos - pos;
  896. pos = next_pos + crlf.size() + dash_boundary.size();
  897. next_pos = body.find(crlf, pos);
  898. if (next_pos == std::string::npos) {
  899. return false;
  900. }
  901. files.emplace(name, file);
  902. pos = next_pos + crlf.size();
  903. }
  904. return true;
  905. }
  906. inline std::string to_lower(const char* beg, const char* end)
  907. {
  908. std::string out;
  909. auto it = beg;
  910. while (it != end) {
  911. out += ::tolower(*it);
  912. it++;
  913. }
  914. return out;
  915. }
  916. inline void make_range_header_core(std::string&) {}
  917. template<typename uint64_t>
  918. inline void make_range_header_core(std::string& field, uint64_t value)
  919. {
  920. if (!field.empty()) {
  921. field += ", ";
  922. }
  923. field += std::to_string(value) + "-";
  924. }
  925. template<typename uint64_t, typename... Args>
  926. inline void make_range_header_core(std::string& field, uint64_t value1, uint64_t value2, Args... args)
  927. {
  928. if (!field.empty()) {
  929. field += ", ";
  930. }
  931. field += std::to_string(value1) + "-" + std::to_string(value2);
  932. make_range_header_core(field, args...);
  933. }
  934. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  935. inline bool can_compress(const std::string& content_type) {
  936. return !content_type.find("text/") ||
  937. content_type == "image/svg+xml" ||
  938. content_type == "application/javascript" ||
  939. content_type == "application/json" ||
  940. content_type == "application/xml" ||
  941. content_type == "application/xhtml+xml";
  942. }
  943. inline void compress(const Request& req, Response& res)
  944. {
  945. // TODO: Server version is HTTP/1.1 and 'Accpet-Encoding' has gzip, not gzip;q=0
  946. const auto& encodings = req.get_header_value("Accept-Encoding");
  947. if (encodings.find("gzip") == std::string::npos) {
  948. return;
  949. }
  950. if (!can_compress(res.get_header_value("Content-Type"))) {
  951. return;
  952. }
  953. z_stream strm;
  954. strm.zalloc = Z_NULL;
  955. strm.zfree = Z_NULL;
  956. strm.opaque = Z_NULL;
  957. auto ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY);
  958. if (ret != Z_OK) {
  959. return;
  960. }
  961. strm.avail_in = res.body.size();
  962. strm.next_in = (Bytef *)res.body.data();
  963. std::string compressed;
  964. const auto bufsiz = 16384;
  965. char buff[bufsiz];
  966. do {
  967. strm.avail_out = bufsiz;
  968. strm.next_out = (Bytef *)buff;
  969. deflate(&strm, Z_FINISH);
  970. compressed.append(buff, bufsiz - strm.avail_out);
  971. } while (strm.avail_out == 0);
  972. res.set_header("Content-Encoding", "gzip");
  973. res.body.swap(compressed);
  974. deflateEnd(&strm);
  975. }
  976. inline void decompress_request_body(Request& req)
  977. {
  978. if (req.get_header_value("Content-Encoding") != "gzip")
  979. return;
  980. z_stream strm;
  981. strm.zalloc = Z_NULL;
  982. strm.zfree = Z_NULL;
  983. strm.opaque = Z_NULL;
  984. // 15 is the value of wbits, which should be at the maximum possible value to ensure
  985. // that any gzip stream can be decoded. The offset of 16 specifies that the stream
  986. // to decompress will be formatted with a gzip wrapper.
  987. auto ret = inflateInit2(&strm, 16 + 15);
  988. if (ret != Z_OK) {
  989. return;
  990. }
  991. strm.avail_in = req.body.size();
  992. strm.next_in = (Bytef *)req.body.data();
  993. std::string decompressed;
  994. const auto bufsiz = 16384;
  995. char buff[bufsiz];
  996. do {
  997. strm.avail_out = bufsiz;
  998. strm.next_out = (Bytef *)buff;
  999. inflate(&strm, Z_NO_FLUSH);
  1000. decompressed.append(buff, bufsiz - strm.avail_out);
  1001. } while (strm.avail_out == 0);
  1002. req.body.swap(decompressed);
  1003. inflateEnd(&strm);
  1004. }
  1005. #endif
  1006. #ifdef _WIN32
  1007. class WSInit {
  1008. public:
  1009. WSInit() {
  1010. WSADATA wsaData;
  1011. WSAStartup(0x0002, &wsaData);
  1012. }
  1013. ~WSInit() {
  1014. WSACleanup();
  1015. }
  1016. };
  1017. static WSInit wsinit_;
  1018. #endif
  1019. } // namespace detail
  1020. // Header utilities
  1021. template<typename uint64_t, typename... Args>
  1022. inline std::pair<std::string, std::string> make_range_header(uint64_t value, Args... args)
  1023. {
  1024. std::string field;
  1025. detail::make_range_header_core(field, value, args...);
  1026. field.insert(0, "bytes=");
  1027. return std::make_pair("Range", field);
  1028. }
  1029. // Request implementation
  1030. inline bool Request::has_header(const char* key) const
  1031. {
  1032. return headers.find(key) != headers.end();
  1033. }
  1034. inline std::string Request::get_header_value(const char* key) const
  1035. {
  1036. return detail::get_header_value(headers, key, "");
  1037. }
  1038. inline void Request::set_header(const char* key, const char* val)
  1039. {
  1040. headers.emplace(key, val);
  1041. }
  1042. inline bool Request::has_param(const char* key) const
  1043. {
  1044. return params.find(key) != params.end();
  1045. }
  1046. inline std::string Request::get_param_value(const char* key) const
  1047. {
  1048. auto it = params.find(key);
  1049. if (it != params.end()) {
  1050. return it->second;
  1051. }
  1052. return std::string();
  1053. }
  1054. inline bool Request::has_file(const char* key) const
  1055. {
  1056. return files.find(key) != files.end();
  1057. }
  1058. inline MultipartFile Request::get_file_value(const char* key) const
  1059. {
  1060. auto it = files.find(key);
  1061. if (it != files.end()) {
  1062. return it->second;
  1063. }
  1064. return MultipartFile();
  1065. }
  1066. // Response implementation
  1067. inline bool Response::has_header(const char* key) const
  1068. {
  1069. return headers.find(key) != headers.end();
  1070. }
  1071. inline std::string Response::get_header_value(const char* key) const
  1072. {
  1073. return detail::get_header_value(headers, key, "");
  1074. }
  1075. inline void Response::set_header(const char* key, const char* val)
  1076. {
  1077. headers.emplace(key, val);
  1078. }
  1079. inline void Response::set_redirect(const char* url)
  1080. {
  1081. set_header("Location", url);
  1082. status = 302;
  1083. }
  1084. inline void Response::set_content(const char* s, size_t n, const char* content_type)
  1085. {
  1086. body.assign(s, n);
  1087. set_header("Content-Type", content_type);
  1088. }
  1089. inline void Response::set_content(const std::string& s, const char* content_type)
  1090. {
  1091. body = s;
  1092. set_header("Content-Type", content_type);
  1093. }
  1094. // Rstream implementation
  1095. template <typename ...Args>
  1096. inline void Stream::write_format(const char* fmt, const Args& ...args)
  1097. {
  1098. const auto bufsiz = 2048;
  1099. char buf[bufsiz];
  1100. #if defined(_MSC_VER) && _MSC_VER < 1900
  1101. auto n = _snprintf_s(buf, bufsiz, bufsiz - 1, fmt, args...);
  1102. #else
  1103. auto n = snprintf(buf, bufsiz - 1, fmt, args...);
  1104. #endif
  1105. if (n > 0) {
  1106. if (n >= bufsiz - 1) {
  1107. std::vector<char> glowable_buf(bufsiz);
  1108. while (n >= static_cast<int>(glowable_buf.size() - 1)) {
  1109. glowable_buf.resize(glowable_buf.size() * 2);
  1110. #if defined(_MSC_VER) && _MSC_VER < 1900
  1111. n = _snprintf_s(&glowable_buf[0], glowable_buf.size(), glowable_buf.size() - 1, fmt, args...);
  1112. #else
  1113. n = snprintf(&glowable_buf[0], glowable_buf.size() - 1, fmt, args...);
  1114. #endif
  1115. }
  1116. write(&glowable_buf[0], n);
  1117. } else {
  1118. write(buf, n);
  1119. }
  1120. }
  1121. }
  1122. // Socket stream implementation
  1123. inline SocketStream::SocketStream(socket_t sock): sock_(sock)
  1124. {
  1125. }
  1126. inline SocketStream::~SocketStream()
  1127. {
  1128. }
  1129. inline int SocketStream::read(char* ptr, size_t size)
  1130. {
  1131. return recv(sock_, ptr, size, 0);
  1132. }
  1133. inline int SocketStream::write(const char* ptr, size_t size)
  1134. {
  1135. return send(sock_, ptr, size, 0);
  1136. }
  1137. inline int SocketStream::write(const char* ptr)
  1138. {
  1139. return write(ptr, strlen(ptr));
  1140. }
  1141. inline std::string SocketStream::get_remote_addr() {
  1142. return detail::get_remote_addr(sock_);
  1143. }
  1144. // HTTP server implementation
  1145. inline Server::Server(HttpVersion http_version)
  1146. : http_version_(http_version)
  1147. , svr_sock_(-1)
  1148. {
  1149. #ifndef _WIN32
  1150. signal(SIGPIPE, SIG_IGN);
  1151. #endif
  1152. }
  1153. inline Server::~Server()
  1154. {
  1155. }
  1156. inline Server& Server::get(const char* pattern, Handler handler)
  1157. {
  1158. get_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  1159. return *this;
  1160. }
  1161. inline Server& Server::post(const char* pattern, Handler handler)
  1162. {
  1163. post_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  1164. return *this;
  1165. }
  1166. inline bool Server::set_base_dir(const char* path)
  1167. {
  1168. if (detail::is_dir(path)) {
  1169. base_dir_ = path;
  1170. return true;
  1171. }
  1172. return false;
  1173. }
  1174. inline void Server::set_error_handler(Handler handler)
  1175. {
  1176. error_handler_ = handler;
  1177. }
  1178. inline void Server::set_logger(Logger logger)
  1179. {
  1180. logger_ = logger;
  1181. }
  1182. inline bool Server::listen(const char* host, int port, int socket_flags)
  1183. {
  1184. if (!is_valid()) {
  1185. return false;
  1186. }
  1187. svr_sock_ = create_server_socket(host, port, socket_flags);
  1188. if (svr_sock_ == -1) {
  1189. return false;
  1190. }
  1191. auto ret = true;
  1192. for (;;) {
  1193. auto val = detail::select_read(svr_sock_, 0, 100000);
  1194. if (val == 0) { // Timeout
  1195. if (svr_sock_ == -1) {
  1196. // The server socket was closed by 'stop' method.
  1197. break;
  1198. }
  1199. continue;
  1200. }
  1201. socket_t sock = accept(svr_sock_, NULL, NULL);
  1202. if (sock == -1) {
  1203. if (svr_sock_ != -1) {
  1204. detail::close_socket(svr_sock_);
  1205. ret = false;
  1206. } else {
  1207. ; // The server socket was closed by user.
  1208. }
  1209. break;
  1210. }
  1211. // TODO: Use thread pool...
  1212. std::thread([=]() {
  1213. read_and_close_socket(sock);
  1214. }).detach();
  1215. }
  1216. return ret;
  1217. }
  1218. inline bool Server::is_running() const
  1219. {
  1220. return svr_sock_ != -1;
  1221. }
  1222. inline void Server::stop()
  1223. {
  1224. detail::shutdown_socket(svr_sock_);
  1225. detail::close_socket(svr_sock_);
  1226. svr_sock_ = -1;
  1227. }
  1228. inline bool Server::parse_request_line(const char* s, Request& req)
  1229. {
  1230. static std::regex re("(GET|HEAD|POST) ([^?]+)(?:\\?(.+?))? (HTTP/1\\.[01])\r\n");
  1231. std::cmatch m;
  1232. if (std::regex_match(s, m, re)) {
  1233. req.version = std::string(m[4]);
  1234. req.method = std::string(m[1]);
  1235. req.path = detail::decode_url(m[2]);
  1236. // Parse query text
  1237. auto len = std::distance(m[3].first, m[3].second);
  1238. if (len > 0) {
  1239. detail::parse_query_text(m[3], req.params);
  1240. }
  1241. return true;
  1242. }
  1243. return false;
  1244. }
  1245. inline void Server::write_response(Stream& strm, bool last_connection, const Request& req, Response& res)
  1246. {
  1247. assert(res.status != -1);
  1248. if (400 <= res.status && error_handler_) {
  1249. error_handler_(req, res);
  1250. }
  1251. // Response line
  1252. strm.write_format("%s %d %s\r\n",
  1253. detail::http_version_strings[static_cast<size_t>(http_version_)],
  1254. res.status,
  1255. detail::status_message(res.status));
  1256. // Headers
  1257. if (!res.has_header("Connection") && (last_connection || req.version == "HTTP/1.0")) {
  1258. res.set_header("Connection", "close");
  1259. }
  1260. if (!res.body.empty()) {
  1261. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1262. detail::compress(req, res);
  1263. #endif
  1264. if (!res.has_header("Content-Type")) {
  1265. res.set_header("Content-Type", "text/plain");
  1266. }
  1267. auto length = std::to_string(res.body.size());
  1268. res.set_header("Content-Length", length.c_str());
  1269. }
  1270. detail::write_headers(strm, res);
  1271. // Body
  1272. if (!res.body.empty() && req.method != "HEAD") {
  1273. strm.write(res.body.c_str(), res.body.size());
  1274. }
  1275. // Log
  1276. if (logger_) {
  1277. logger_(req, res);
  1278. }
  1279. }
  1280. inline bool Server::handle_file_request(Request& req, Response& res)
  1281. {
  1282. if (!base_dir_.empty() && detail::is_valid_path(req.path)) {
  1283. std::string path = base_dir_ + req.path;
  1284. if (!path.empty() && path.back() == '/') {
  1285. path += "index.html";
  1286. }
  1287. if (detail::is_file(path)) {
  1288. detail::read_file(path, res.body);
  1289. auto type = detail::find_content_type(path);
  1290. if (type) {
  1291. res.set_header("Content-Type", type);
  1292. }
  1293. res.status = 200;
  1294. return true;
  1295. }
  1296. }
  1297. return false;
  1298. }
  1299. inline socket_t Server::create_server_socket(const char* host, int port, int socket_flags) const
  1300. {
  1301. return detail::create_socket(host, port,
  1302. [](socket_t sock, struct addrinfo& ai) -> bool {
  1303. if (::bind(sock, ai.ai_addr, ai.ai_addrlen)) {
  1304. return false;
  1305. }
  1306. if (::listen(sock, 5)) { // Listen through 5 channels
  1307. return false;
  1308. }
  1309. return true;
  1310. }, socket_flags);
  1311. }
  1312. inline bool Server::routing(Request& req, Response& res)
  1313. {
  1314. if (req.method == "GET" && handle_file_request(req, res)) {
  1315. return true;
  1316. }
  1317. if (req.method == "GET" || req.method == "HEAD") {
  1318. return dispatch_request(req, res, get_handlers_);
  1319. } else if (req.method == "POST") {
  1320. return dispatch_request(req, res, post_handlers_);
  1321. }
  1322. return false;
  1323. }
  1324. inline bool Server::dispatch_request(Request& req, Response& res, Handlers& handlers)
  1325. {
  1326. for (const auto& x: handlers) {
  1327. const auto& pattern = x.first;
  1328. const auto& handler = x.second;
  1329. if (std::regex_match(req.path, req.matches, pattern)) {
  1330. handler(req, res);
  1331. return true;
  1332. }
  1333. }
  1334. return false;
  1335. }
  1336. inline bool Server::process_request(Stream& strm, bool last_connection)
  1337. {
  1338. const auto bufsiz = 2048;
  1339. char buf[bufsiz];
  1340. detail::stream_line_reader reader(strm, buf, bufsiz);
  1341. // Connection has been closed on client
  1342. if (!reader.getline()) {
  1343. return false;
  1344. }
  1345. Request req;
  1346. Response res;
  1347. res.version = detail::http_version_strings[static_cast<size_t>(http_version_)];
  1348. // Request line and headers
  1349. if (!parse_request_line(reader.ptr(), req) || !detail::read_headers(strm, req.headers)) {
  1350. res.status = 400;
  1351. write_response(strm, last_connection, req, res);
  1352. return true;
  1353. }
  1354. auto ret = true;
  1355. if (req.get_header_value("Connection") == "close") {
  1356. ret = false;
  1357. }
  1358. req.set_header("REMOTE_ADDR", strm.get_remote_addr().c_str());
  1359. // Body
  1360. if (req.method == "POST") {
  1361. if (!detail::read_content(strm, req)) {
  1362. res.status = 400;
  1363. write_response(strm, last_connection, req, res);
  1364. return ret;
  1365. }
  1366. const auto& content_type = req.get_header_value("Content-Type");
  1367. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1368. detail::decompress_request_body(req);
  1369. #else
  1370. if (req.get_header_value("Content-Encoding") == "gzip") {
  1371. res.status = 406;
  1372. write_response(strm, last_connection, req, res);
  1373. return ret;
  1374. }
  1375. #endif
  1376. if (!content_type.find("application/x-www-form-urlencoded")) {
  1377. detail::parse_query_text(req.body, req.params);
  1378. } else if(!content_type.find("multipart/form-data")) {
  1379. std::string boundary;
  1380. if (!detail::parse_multipart_boundary(content_type, boundary) ||
  1381. !detail::parse_multipart_formdata(boundary, req.body, req.files)) {
  1382. res.status = 400;
  1383. write_response(strm, last_connection, req, res);
  1384. return ret;
  1385. }
  1386. }
  1387. }
  1388. if (routing(req, res)) {
  1389. if (res.status == -1) {
  1390. res.status = 200;
  1391. }
  1392. } else {
  1393. res.status = 404;
  1394. }
  1395. write_response(strm, last_connection, req, res);
  1396. return ret;
  1397. }
  1398. inline bool Server::is_valid() const
  1399. {
  1400. return true;
  1401. }
  1402. inline bool Server::read_and_close_socket(socket_t sock)
  1403. {
  1404. auto keep_alive = http_version_ == HttpVersion::v1_1;
  1405. return detail::read_and_close_socket(
  1406. sock,
  1407. keep_alive,
  1408. [this](Stream& strm, bool last_connection) {
  1409. return process_request(strm, last_connection);
  1410. });
  1411. }
  1412. // HTTP client implementation
  1413. inline Client::Client(
  1414. const char* host, int port, size_t timeout_sec, HttpVersion http_version)
  1415. : host_(host)
  1416. , port_(port)
  1417. , timeout_sec_(timeout_sec)
  1418. , http_version_(http_version)
  1419. , host_and_port_(host_ + ":" + std::to_string(port_))
  1420. {
  1421. }
  1422. inline Client::~Client()
  1423. {
  1424. }
  1425. inline bool Client::is_valid() const
  1426. {
  1427. return true;
  1428. }
  1429. inline socket_t Client::create_client_socket() const
  1430. {
  1431. return detail::create_socket(host_.c_str(), port_,
  1432. [=](socket_t sock, struct addrinfo& ai) -> bool {
  1433. detail::set_nonblocking(sock, true);
  1434. auto ret = connect(sock, ai.ai_addr, ai.ai_addrlen);
  1435. if (ret < 0) {
  1436. if (detail::is_connection_error() ||
  1437. !detail::wait_until_socket_is_ready(sock, timeout_sec_, 0)) {
  1438. detail::close_socket(sock);
  1439. return false;
  1440. }
  1441. }
  1442. detail::set_nonblocking(sock, false);
  1443. return true;
  1444. });
  1445. }
  1446. inline bool Client::read_response_line(Stream& strm, Response& res)
  1447. {
  1448. const auto bufsiz = 2048;
  1449. char buf[bufsiz];
  1450. detail::stream_line_reader reader(strm, buf, bufsiz);
  1451. if (!reader.getline()) {
  1452. return false;
  1453. }
  1454. const static std::regex re("HTTP/1\\.[01] (\\d+?) .+\r\n");
  1455. std::cmatch m;
  1456. if (std::regex_match(reader.ptr(), m, re)) {
  1457. res.status = std::stoi(std::string(m[1]));
  1458. }
  1459. return true;
  1460. }
  1461. inline bool Client::send(Request& req, Response& res)
  1462. {
  1463. if (req.path.empty()) {
  1464. return false;
  1465. }
  1466. auto sock = create_client_socket();
  1467. if (sock == -1) {
  1468. return false;
  1469. }
  1470. return read_and_close_socket(sock, req, res);
  1471. }
  1472. inline void Client::write_request(Stream& strm, Request& req)
  1473. {
  1474. auto path = detail::encode_url(req.path);
  1475. // Request line
  1476. strm.write_format("%s %s %s\r\n",
  1477. req.method.c_str(),
  1478. path.c_str(),
  1479. detail::http_version_strings[static_cast<size_t>(http_version_)]);
  1480. // Headers
  1481. req.set_header("Host", host_and_port_.c_str());
  1482. if (!req.has_header("Accept")) {
  1483. req.set_header("Accept", "*/*");
  1484. }
  1485. if (!req.has_header("User-Agent")) {
  1486. req.set_header("User-Agent", "cpp-httplib/0.2");
  1487. }
  1488. // TODO: if (!req.has_header("Connection") &&
  1489. // (last_connection || http_version_ == detail::HttpVersion::v1_0)) {
  1490. if (!req.has_header("Connection")) {
  1491. req.set_header("Connection", "close");
  1492. }
  1493. if (!req.body.empty()) {
  1494. if (!req.has_header("Content-Type")) {
  1495. req.set_header("Content-Type", "text/plain");
  1496. }
  1497. auto length = std::to_string(req.body.size());
  1498. req.set_header("Content-Length", length.c_str());
  1499. }
  1500. detail::write_headers(strm, req);
  1501. // Body
  1502. if (!req.body.empty()) {
  1503. if (req.get_header_value("Content-Type") == "application/x-www-form-urlencoded") {
  1504. auto str = detail::encode_url(req.body);
  1505. strm.write(str.c_str(), str.size());
  1506. } else {
  1507. strm.write(req.body.c_str(), req.body.size());
  1508. }
  1509. }
  1510. }
  1511. inline bool Client::process_request(Stream& strm, Request& req, Response& res)
  1512. {
  1513. // Send request
  1514. write_request(strm, req);
  1515. // Receive response and headers
  1516. if (!read_response_line(strm, res) || !detail::read_headers(strm, res.headers)) {
  1517. return false;
  1518. }
  1519. // TODO: Check if 'Connection' header is 'close' or HTTP version is 1.0, then close socket...
  1520. // Body
  1521. if (req.method != "HEAD") {
  1522. if (!detail::read_content(strm, res, req.progress)) {
  1523. return false;
  1524. }
  1525. }
  1526. return true;
  1527. }
  1528. inline bool Client::read_and_close_socket(socket_t sock, Request& req, Response& res)
  1529. {
  1530. return detail::read_and_close_socket(sock, false, [&](Stream& strm, bool /*last_connection*/) {
  1531. return process_request(strm, req, res);
  1532. });
  1533. }
  1534. inline std::shared_ptr<Response> Client::get(const char* path, Progress progress)
  1535. {
  1536. return get(path, Headers(), progress);
  1537. }
  1538. inline std::shared_ptr<Response> Client::get(const char* path, const Headers& headers, Progress progress)
  1539. {
  1540. Request req;
  1541. req.method = "GET";
  1542. req.path = path;
  1543. req.headers = headers;
  1544. req.progress = progress;
  1545. auto res = std::make_shared<Response>();
  1546. return send(req, *res) ? res : nullptr;
  1547. }
  1548. inline std::shared_ptr<Response> Client::head(const char* path)
  1549. {
  1550. return head(path, Headers());
  1551. }
  1552. inline std::shared_ptr<Response> Client::head(const char* path, const Headers& headers)
  1553. {
  1554. Request req;
  1555. req.method = "HEAD";
  1556. req.headers = headers;
  1557. req.path = path;
  1558. auto res = std::make_shared<Response>();
  1559. return send(req, *res) ? res : nullptr;
  1560. }
  1561. inline std::shared_ptr<Response> Client::post(
  1562. const char* path, const std::string& body, const char* content_type)
  1563. {
  1564. return post(path, Headers(), body, content_type);
  1565. }
  1566. inline std::shared_ptr<Response> Client::post(
  1567. const char* path, const Headers& headers, const std::string& body, const char* content_type)
  1568. {
  1569. Request req;
  1570. req.method = "POST";
  1571. req.headers = headers;
  1572. req.path = path;
  1573. req.headers.emplace("Content-Type", content_type);
  1574. req.body = body;
  1575. auto res = std::make_shared<Response>();
  1576. return send(req, *res) ? res : nullptr;
  1577. }
  1578. inline std::shared_ptr<Response> Client::post(const char* path, const Params& params)
  1579. {
  1580. return post(path, Headers(), params);
  1581. }
  1582. inline std::shared_ptr<Response> Client::post(const char* path, const Headers& headers, const Params& params)
  1583. {
  1584. std::string query;
  1585. for (auto it = params.begin(); it != params.end(); ++it) {
  1586. if (it != params.begin()) {
  1587. query += "&";
  1588. }
  1589. query += it->first;
  1590. query += "=";
  1591. query += it->second;
  1592. }
  1593. return post(path, headers, query, "application/x-www-form-urlencoded");
  1594. }
  1595. /*
  1596. * SSL Implementation
  1597. */
  1598. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1599. namespace detail {
  1600. template <typename U, typename V, typename T>
  1601. inline bool read_and_close_socket_ssl(
  1602. socket_t sock, bool keep_alive,
  1603. SSL_CTX* ctx, U SSL_connect_or_accept, V setup,
  1604. T callback)
  1605. {
  1606. auto ssl = SSL_new(ctx);
  1607. if (!ssl) {
  1608. return false;
  1609. }
  1610. auto bio = BIO_new_socket(sock, BIO_NOCLOSE);
  1611. SSL_set_bio(ssl, bio, bio);
  1612. setup(ssl);
  1613. SSL_connect_or_accept(ssl);
  1614. bool ret = false;
  1615. if (keep_alive) {
  1616. auto count = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  1617. while (count > 0 &&
  1618. detail::select_read(sock,
  1619. CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND,
  1620. CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND) > 0) {
  1621. auto last_connection = count == 1;
  1622. SSLSocketStream strm(sock, ssl);
  1623. ret = callback(strm, last_connection);
  1624. if (!ret) {
  1625. break;
  1626. }
  1627. count--;
  1628. }
  1629. } else {
  1630. SSLSocketStream strm(sock, ssl);
  1631. ret = callback(strm, true);
  1632. }
  1633. SSL_shutdown(ssl);
  1634. SSL_free(ssl);
  1635. close_socket(sock);
  1636. return ret;
  1637. }
  1638. class SSLInit {
  1639. public:
  1640. SSLInit() {
  1641. SSL_load_error_strings();
  1642. SSL_library_init();
  1643. }
  1644. };
  1645. static SSLInit sslinit_;
  1646. } // namespace detail
  1647. // SSL socket stream implementation
  1648. inline SSLSocketStream::SSLSocketStream(socket_t sock, SSL* ssl)
  1649. : sock_(sock), ssl_(ssl)
  1650. {
  1651. }
  1652. inline SSLSocketStream::~SSLSocketStream()
  1653. {
  1654. }
  1655. inline int SSLSocketStream::read(char* ptr, size_t size)
  1656. {
  1657. return SSL_read(ssl_, ptr, size);
  1658. }
  1659. inline int SSLSocketStream::write(const char* ptr, size_t size)
  1660. {
  1661. return SSL_write(ssl_, ptr, size);
  1662. }
  1663. inline int SSLSocketStream::write(const char* ptr)
  1664. {
  1665. return write(ptr, strlen(ptr));
  1666. }
  1667. inline std::string SSLSocketStream::get_remote_addr() {
  1668. return detail::get_remote_addr(sock_);
  1669. }
  1670. // SSL HTTP server implementation
  1671. inline SSLServer::SSLServer(const char* cert_path, const char* private_key_path, HttpVersion http_version)
  1672. : Server(http_version)
  1673. {
  1674. ctx_ = SSL_CTX_new(SSLv23_server_method());
  1675. if (ctx_) {
  1676. SSL_CTX_set_options(ctx_,
  1677. SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
  1678. SSL_OP_NO_COMPRESSION |
  1679. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  1680. // auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  1681. // SSL_CTX_set_tmp_ecdh(ctx_, ecdh);
  1682. // EC_KEY_free(ecdh);
  1683. if (SSL_CTX_use_certificate_file(ctx_, cert_path, SSL_FILETYPE_PEM) != 1 ||
  1684. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) != 1) {
  1685. SSL_CTX_free(ctx_);
  1686. ctx_ = nullptr;
  1687. }
  1688. }
  1689. }
  1690. inline SSLServer::~SSLServer()
  1691. {
  1692. if (ctx_) {
  1693. SSL_CTX_free(ctx_);
  1694. }
  1695. }
  1696. inline bool SSLServer::is_valid() const
  1697. {
  1698. return ctx_;
  1699. }
  1700. inline bool SSLServer::read_and_close_socket(socket_t sock)
  1701. {
  1702. auto keep_alive = http_version_ == HttpVersion::v1_1;
  1703. return detail::read_and_close_socket_ssl(
  1704. sock,
  1705. keep_alive,
  1706. ctx_,
  1707. SSL_accept,
  1708. [](SSL* /*ssl*/) {},
  1709. [this](Stream& strm, bool last_connection) {
  1710. return process_request(strm, last_connection);
  1711. });
  1712. }
  1713. // SSL HTTP client implementation
  1714. inline SSLClient::SSLClient(
  1715. const char* host, int port, size_t timeout_sec, HttpVersion http_version)
  1716. : Client(host, port, timeout_sec, http_version)
  1717. {
  1718. ctx_ = SSL_CTX_new(SSLv23_client_method());
  1719. }
  1720. inline SSLClient::~SSLClient()
  1721. {
  1722. if (ctx_) {
  1723. SSL_CTX_free(ctx_);
  1724. }
  1725. }
  1726. inline bool SSLClient::is_valid() const
  1727. {
  1728. return ctx_;
  1729. }
  1730. inline bool SSLClient::read_and_close_socket(socket_t sock, Request& req, Response& res)
  1731. {
  1732. return is_valid() && detail::read_and_close_socket_ssl(
  1733. sock, false,
  1734. ctx_, SSL_connect,
  1735. [&](SSL* ssl) {
  1736. SSL_set_tlsext_host_name(ssl, host_.c_str());
  1737. },
  1738. [&](Stream& strm, bool /*last_connection*/) {
  1739. return process_request(strm, req, res);
  1740. });
  1741. }
  1742. #endif
  1743. } // namespace httplib
  1744. #endif
  1745. // vim: et ts=4 sw=4 cin cino={1s ff=unix