httplib.h 45 KB

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