httplib.h 41 KB

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