httplib.h 50 KB

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