httplib.h 53 KB

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