httplib.h 41 KB

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