httplib.h 54 KB

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