httplib.h 38 KB

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