httplib.h 50 KB

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