httplib.h 47 KB

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