httplib.h 53 KB

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