httplib.h 49 KB

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