{"id":"8LQ68LPqDL","url":"https://pastebin.ca/8LQ68LPqDL","raw_url":"https://raw.anybin.ca/8LQ68LPqDL","visibility":"public","access":"public","created_at":1793268430038,"expires_at":1793873230038,"fetch_limit":null,"fetches_used":0,"reads_remaining":null,"size_bytes":288389,"syntax_hint":null,"title":null,"filename":null,"change_note":null,"cipher":null,"cipher_meta":null,"parent_id":null,"root_id":"8LQ68LPqDL","version":1,"owner_id":null,"recipient_id":null,"body":"//\n//  httplib.h\n//\n//  Copyright (c) 2023 Yuji Hirose. All rights reserved.\n//  MIT License\n//\n\n#ifndef CPPHTTPLIB_HTTPLIB_H\n#define CPPHTTPLIB_HTTPLIB_H\n\n#define CPPHTTPLIB_VERSION \"0.12.2\"\n\n/*\n * Configuration\n */\n\n#ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND\n#define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5\n#endif\n\n#ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT\n#define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 5\n#endif\n\n#ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND\n#define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300\n#endif\n\n#ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND\n#define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0\n#endif\n\n#ifndef CPPHTTPLIB_READ_TIMEOUT_SECOND\n#define CPPHTTPLIB_READ_TIMEOUT_SECOND 5\n#endif\n\n#ifndef CPPHTTPLIB_READ_TIMEOUT_USECOND\n#define CPPHTTPLIB_READ_TIMEOUT_USECOND 0\n#endif\n\n#ifndef CPPHTTPLIB_WRITE_TIMEOUT_SECOND\n#define CPPHTTPLIB_WRITE_TIMEOUT_SECOND 5\n#endif\n\n#ifndef CPPHTTPLIB_WRITE_TIMEOUT_USECOND\n#define CPPHTTPLIB_WRITE_TIMEOUT_USECOND 0\n#endif\n\n#ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND\n#define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0\n#endif\n\n#ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND\n#ifdef _WIN32\n#define CPPHTTPLIB_IDLE_INTERVAL_USECOND 10000\n#else\n#define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0\n#endif\n#endif\n\n#ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH\n#define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192\n#endif\n\n#ifndef CPPHTTPLIB_HEADER_MAX_LENGTH\n#define CPPHTTPLIB_HEADER_MAX_LENGTH 8192\n#endif\n\n#ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT\n#define CPPHTTPLIB_REDIRECT_MAX_COUNT 20\n#endif\n\n#ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT\n#define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024\n#endif\n\n#ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH\n#define CPPHTTPLIB_PAYLOAD_MAX_LENGTH ((std::numeric_limits<size_t>::max)())\n#endif\n\n#ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH\n#define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192\n#endif\n\n#ifndef CPPHTTPLIB_TCP_NODELAY\n#define CPPHTTPLIB_TCP_NODELAY false\n#endif\n\n#ifndef CPPHTTPLIB_RECV_BUFSIZ\n#define CPPHTTPLIB_RECV_BUFSIZ size_t(4096u)\n#endif\n\n#ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ\n#define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)\n#endif\n\n#ifndef CPPHTTPLIB_THREAD_POOL_COUNT\n#define CPPHTTPLIB_THREAD_POOL_COUNT                                           \\\n  ((std::max)(8u, std::thread::hardware_concurrency() > 0                      \\\n                      ? std::thread::hardware_concurrency() - 1                \\\n                      : 0))\n#endif\n\n#ifndef CPPHTTPLIB_RECV_FLAGS\n#define CPPHTTPLIB_RECV_FLAGS 0\n#endif\n\n#ifndef CPPHTTPLIB_SEND_FLAGS\n#define CPPHTTPLIB_SEND_FLAGS 0\n#endif\n\n#ifndef CPPHTTPLIB_LISTEN_BACKLOG\n#define CPPHTTPLIB_LISTEN_BACKLOG 5\n#endif\n\n/*\n * Headers\n */\n\n#ifdef _WIN32\n#ifndef _CRT_SECURE_NO_WARNINGS\n#define _CRT_SECURE_NO_WARNINGS\n#endif //_CRT_SECURE_NO_WARNINGS\n\n#ifndef _CRT_NONSTDC_NO_DEPRECATE\n#define _CRT_NONSTDC_NO_DEPRECATE\n#endif //_CRT_NONSTDC_NO_DEPRECATE\n\n#if defined(_MSC_VER)\n#if _MSC_VER < 1900\n#error Sorry, Visual Studio versions prior to 2015 are not supported\n#endif\n\n#pragma comment(lib, \"ws2_32.lib\")\n\n#ifdef _WIN64\nusing ssize_t = __int64;\n#else\nusing ssize_t = long;\n#endif\n#endif // _MSC_VER\n\n#ifndef S_ISREG\n#define S_ISREG(m) (((m)&S_IFREG) == S_IFREG)\n#endif // S_ISREG\n\n#ifndef S_ISDIR\n#define S_ISDIR(m) (((m)&S_IFDIR) == S_IFDIR)\n#endif // S_ISDIR\n\n#ifndef NOMINMAX\n#define NOMINMAX\n#endif // NOMINMAX\n\n#include <io.h>\n#include <winsock2.h>\n#include <ws2tcpip.h>\n\n#ifndef WSA_FLAG_NO_HANDLE_INHERIT\n#define WSA_FLAG_NO_HANDLE_INHERIT 0x80\n#endif\n\n#ifndef strcasecmp\n#define strcasecmp _stricmp\n#endif // strcasecmp\n\nusing socket_t = SOCKET;\n#ifdef CPPHTTPLIB_USE_POLL\n#define poll(fds, nfds, timeout) WSAPoll(fds, nfds, timeout)\n#endif\n\n#else // not _WIN32\n\n#include <arpa/inet.h>\n#ifndef _AIX\n#include <ifaddrs.h>\n#endif\n#include <net/if.h>\n#include <netdb.h>\n#include <netinet/in.h>\n#ifdef __linux__\n#include <resolv.h>\n#endif\n#include <netinet/tcp.h>\n#ifdef CPPHTTPLIB_USE_POLL\n#include <poll.h>\n#endif\n#include <csignal>\n#include <pthread.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <unistd.h>\n\nusing socket_t = int;\n#ifndef INVALID_SOCKET\n#define INVALID_SOCKET (-1)\n#endif\n#endif //_WIN32\n\n#include <algorithm>\n#include <array>\n#include <atomic>\n#include <cassert>\n#include <cctype>\n#include <climits>\n#include <condition_variable>\n#include <cstring>\n#include <errno.h>\n#include <fcntl.h>\n#include <fstream>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <list>\n#include <map>\n#include <memory>\n#include <mutex>\n#include <random>\n#include <regex>\n#include <set>\n#include <sstream>\n#include <string>\n#include <sys/stat.h>\n#include <thread>\n\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n#ifdef _WIN32\n#include <wincrypt.h>\n\n// these are defined in wincrypt.h and it breaks compilation if BoringSSL is\n// used\n#undef X509_NAME\n#undef X509_CERT_PAIR\n#undef X509_EXTENSIONS\n#undef PKCS7_SIGNER_INFO\n\n#ifdef _MSC_VER\n#pragma comment(lib, \"crypt32.lib\")\n#pragma comment(lib, \"cryptui.lib\")\n#endif\n#elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && defined(__APPLE__)\n#include <TargetConditionals.h>\n#if TARGET_OS_OSX\n#include <CoreFoundation/CoreFoundation.h>\n#include <Security/Security.h>\n#endif // TARGET_OS_OSX\n#endif // _WIN32\n\n#include <openssl/err.h>\n#include <openssl/evp.h>\n#include <openssl/ssl.h>\n#include <openssl/x509v3.h>\n\n#if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)\n#include <openssl/applink.c>\n#endif\n\n#include <iostream>\n#include <sstream>\n\n#if OPENSSL_VERSION_NUMBER < 0x1010100fL\n#error Sorry, OpenSSL versions prior to 1.1.1 are not supported\n#elif OPENSSL_VERSION_NUMBER < 0x30000000L\n#define SSL_get1_peer_certificate SSL_get_peer_certificate\n#endif\n\n#endif\n\n#ifdef CPPHTTPLIB_ZLIB_SUPPORT\n#include <zlib.h>\n#endif\n\n#ifdef CPPHTTPLIB_BROTLI_SUPPORT\n#include <brotli/decode.h>\n#include <brotli/encode.h>\n#endif\n\n/*\n * Declaration\n */\nnamespace httplib {\n\nnamespace detail {\n\n/*\n * Backport std::make_unique from C++14.\n *\n * NOTE: This code came up with the following stackoverflow post:\n * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique\n *\n */\n\ntemplate <class T, class... Args>\ntypename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type\nmake_unique(Args &&...args) {\n  return std::unique_ptr<T>(new T(std::forward<Args>(args)...));\n}\n\ntemplate <class T>\ntypename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type\nmake_unique(std::size_t n) {\n  typedef typename std::remove_extent<T>::type RT;\n  return std::unique_ptr<T>(new RT[n]);\n}\n\nstruct ci {\n  bool operator()(const std::string &s1, const std::string &s2) const {\n    return std::lexicographical_compare(s1.begin(), s1.end(), s2.begin(),\n                                        s2.end(),\n                                        [](unsigned char c1, unsigned char c2) {\n                                          return ::tolower(c1) < ::tolower(c2);\n                                        });\n  }\n};\n\n// This is based on\n// \"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189\".\n\nstruct scope_exit {\n  explicit scope_exit(std::function<void(void)> &&f)\n      : exit_function(std::move(f)), execute_on_destruction{true} {}\n\n  scope_exit(scope_exit &&rhs)\n      : exit_function(std::move(rhs.exit_function)),\n        execute_on_destruction{rhs.execute_on_destruction} {\n    rhs.release();\n  }\n\n  ~scope_exit() {\n    if (execute_on_destruction) { this->exit_function(); }\n  }\n\n  void release() { this->execute_on_destruction = false; }\n\nprivate:\n  scope_exit(const scope_exit &) = delete;\n  void operator=(const scope_exit &) = delete;\n  scope_exit &operator=(scope_exit &&) = delete;\n\n  std::function<void(void)> exit_function;\n  bool execute_on_destruction;\n};\n\n} // namespace detail\n\nusing Headers = std::multimap<std::string, std::string, detail::ci>;\n\nusing Params = std::multimap<std::string, std::string>;\nusing Match = std::smatch;\n\nusing Progress = std::function<bool(uint64_t current, uint64_t total)>;\n\nstruct Response;\nusing ResponseHandler = std::function<bool(const Response &response)>;\n\nstruct MultipartFormData {\n  std::string name;\n  std::string content;\n  std::string filename;\n  std::string content_type;\n};\nusing MultipartFormDataItems = std::vector<MultipartFormData>;\nusing MultipartFormDataMap = std::multimap<std::string, MultipartFormData>;\n\nclass DataSink {\npublic:\n  DataSink() : os(&sb_), sb_(*this) {}\n\n  DataSink(const DataSink &) = delete;\n  DataSink &operator=(const DataSink &) = delete;\n  DataSink(DataSink &&) = delete;\n  DataSink &operator=(DataSink &&) = delete;\n\n  std::function<bool(const char *data, size_t data_len)> write;\n  std::function<void()> done;\n  std::function<void(const Headers &trailer)> done_with_trailer;\n  std::ostream os;\n\nprivate:\n  class data_sink_streambuf : public std::streambuf {\n  public:\n    explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}\n\n  protected:\n    std::streamsize xsputn(const char *s, std::streamsize n) {\n      sink_.write(s, static_cast<size_t>(n));\n      return n;\n    }\n\n  private:\n    DataSink &sink_;\n  };\n\n  data_sink_streambuf sb_;\n};\n\nusing ContentProvider =\n    std::function<bool(size_t offset, size_t length, DataSink &sink)>;\n\nusing ContentProviderWithoutLength =\n    std::function<bool(size_t offset, DataSink &sink)>;\n\nusing ContentProviderResourceReleaser = std::function<void(bool success)>;\n\nstruct MultipartFormDataProvider {\n  std::string name;\n  ContentProviderWithoutLength provider;\n  std::string filename;\n  std::string content_type;\n};\nusing MultipartFormDataProviderItems = std::vector<MultipartFormDataProvider>;\n\nusing ContentReceiverWithProgress =\n    std::function<bool(const char *data, size_t data_length, uint64_t offset,\n                       uint64_t total_length)>;\n\nusing ContentReceiver =\n    std::function<bool(const char *data, size_t data_length)>;\n\nusing MultipartContentHeader =\n    std::function<bool(const MultipartFormData &file)>;\n\nclass ContentReader {\npublic:\n  using Reader = std::function<bool(ContentReceiver receiver)>;\n  using MultipartReader = std::function<bool(MultipartContentHeader header,\n                                             ContentReceiver receiver)>;\n\n  ContentReader(Reader reader, MultipartReader multipart_reader)\n      : reader_(std::move(reader)),\n        multipart_reader_(std::move(multipart_reader)) {}\n\n  bool operator()(MultipartContentHeader header,\n                  ContentReceiver receiver) const {\n    return multipart_reader_(std::move(header), std::move(receiver));\n  }\n\n  bool operator()(ContentReceiver receiver) const {\n    return reader_(std::move(receiver));\n  }\n\n  Reader reader_;\n  MultipartReader multipart_reader_;\n};\n\nusing Range = std::pair<ssize_t, ssize_t>;\nusing Ranges = std::vector<Range>;\n\nstruct Request {\n  std::string method;\n  std::string path;\n  Headers headers;\n  std::string body;\n\n  std::string remote_addr;\n  int remote_port = -1;\n  std::string local_addr;\n  int local_port = -1;\n\n  // for server\n  std::string version;\n  std::string target;\n  Params params;\n  MultipartFormDataMap files;\n  Ranges ranges;\n  Match matches;\n\n  // for client\n  ResponseHandler response_handler;\n  ContentReceiverWithProgress content_receiver;\n  Progress progress;\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n  const SSL *ssl = nullptr;\n#endif\n\n  bool has_header(const std::string &key) const;\n  std::string get_header_value(const std::string &key, size_t id = 0) const;\n  template <typename T>\n  T get_header_value(const std::string &key, size_t id = 0) const;\n  size_t get_header_value_count(const std::string &key) const;\n  void set_header(const std::string &key, const std::string &val);\n\n  bool has_param(const std::string &key) const;\n  std::string get_param_value(const std::string &key, size_t id = 0) const;\n  size_t get_param_value_count(const std::string &key) const;\n\n  bool is_multipart_form_data() const;\n\n  bool has_file(const std::string &key) const;\n  MultipartFormData get_file_value(const std::string &key) const;\n  std::vector<MultipartFormData> get_file_values(const std::string &key) const;\n\n  // private members...\n  size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;\n  size_t content_length_ = 0;\n  ContentProvider content_provider_;\n  bool is_chunked_content_provider_ = false;\n  size_t authorization_count_ = 0;\n};\n\nstruct Response {\n  std::string version;\n  int status = -1;\n  std::string reason;\n  Headers headers;\n  std::string body;\n  std::string location; // Redirect location\n\n  bool has_header(const std::string &key) const;\n  std::string get_header_value(const std::string &key, size_t id = 0) const;\n  template <typename T>\n  T get_header_value(const std::string &key, size_t id = 0) const;\n  size_t get_header_value_count(const std::string &key) const;\n  void set_header(const std::string &key, const std::string &val);\n\n  void set_redirect(const std::string &url, int status = 302);\n  void set_content(const char *s, size_t n, const std::string &content_type);\n  void set_content(const std::string &s, const std::string &content_type);\n\n  void set_content_provider(\n      size_t length, const std::string &content_type, ContentProvider provider,\n      ContentProviderResourceReleaser resource_releaser = nullptr);\n\n  void set_content_provider(\n      const std::string &content_type, ContentProviderWithoutLength provider,\n      ContentProviderResourceReleaser resource_releaser = nullptr);\n\n  void set_chunked_content_provider(\n      const std::string &content_type, ContentProviderWithoutLength provider,\n      ContentProviderResourceReleaser resource_releaser = nullptr);\n\n  Response() = default;\n  Response(const Response &) = default;\n  Response &operator=(const Response &) = default;\n  Response(Response &&) = default;\n  Response &operator=(Response &&) = default;\n  ~Response() {\n    if (content_provider_resource_releaser_) {\n      content_provider_resource_releaser_(content_provider_success_);\n    }\n  }\n\n  // private members...\n  size_t content_length_ = 0;\n  ContentProvider content_provider_;\n  ContentProviderResourceReleaser content_provider_resource_releaser_;\n  bool is_chunked_content_provider_ = false;\n  bool content_provider_success_ = false;\n};\n\nclass Stream {\npublic:\n  virtual ~Stream() = default;\n\n  virtual bool is_readable() const = 0;\n  virtual bool is_writable() const = 0;\n\n  virtual ssize_t read(char *ptr, size_t size) = 0;\n  virtual ssize_t write(const char *ptr, size_t size) = 0;\n  virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;\n  virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;\n  virtual socket_t socket() const = 0;\n\n  template <typename... Args>\n  ssize_t write_format(const char *fmt, const Args &...args);\n  ssize_t write(const char *ptr);\n  ssize_t write(const std::string &s);\n};\n\nclass TaskQueue {\npublic:\n  TaskQueue() = default;\n  virtual ~TaskQueue() = default;\n\n  virtual void enqueue(std::function<void()> fn) = 0;\n  virtual void shutdown() = 0;\n\n  virtual void on_idle() {}\n};\n\nclass ThreadPool : public TaskQueue {\npublic:\n  explicit ThreadPool(size_t n) : shutdown_(false) {\n    while (n) {\n      threads_.emplace_back(worker(*this));\n      n--;\n    }\n  }\n\n  ThreadPool(const ThreadPool &) = delete;\n  ~ThreadPool() override = default;\n\n  void enqueue(std::function<void()> fn) override {\n    {\n      std::unique_lock<std::mutex> lock(mutex_);\n      jobs_.push_back(std::move(fn));\n    }\n\n    cond_.notify_one();\n  }\n\n  void shutdown() override {\n    // Stop all worker threads...\n    {\n      std::unique_lock<std::mutex> lock(mutex_);\n      shutdown_ = true;\n    }\n\n    cond_.notify_all();\n\n    // Join...\n    for (auto &t : threads_) {\n      t.join();\n    }\n  }\n\nprivate:\n  struct worker {\n    explicit worker(ThreadPool &pool) : pool_(pool) {}\n\n    void operator()() {\n      for (;;) {\n        std::function<void()> fn;\n        {\n          std::unique_lock<std::mutex> lock(pool_.mutex_);\n\n          pool_.cond_.wait(\n              lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; });\n\n          if (pool_.shutdown_ && pool_.jobs_.empty()) { break; }\n\n          fn = std::move(pool_.jobs_.front());\n          pool_.jobs_.pop_front();\n        }\n\n        assert(true == static_cast<bool>(fn));\n        fn();\n      }\n    }\n\n    ThreadPool &pool_;\n  };\n  friend struct worker;\n\n  std::vector<std::thread> threads_;\n  std::list<std::function<void()>> jobs_;\n\n  bool shutdown_;\n\n  std::condition_variable cond_;\n  std::mutex mutex_;\n};\n\nusing Logger = std::function<void(const Request &, const Response &)>;\n\nusing SocketOptions = std::function<void(socket_t sock)>;\n\nvoid default_socket_options(socket_t sock);\n\nclass Server {\npublic:\n  using Handler = std::function<void(const Request &, Response &)>;\n\n  using ExceptionHandler =\n      std::function<void(const Request &, Response &, std::exception_ptr ep)>;\n\n  enum class HandlerResponse {\n    Handled,\n    Unhandled,\n  };\n  using HandlerWithResponse =\n      std::function<HandlerResponse(const Request &, Response &)>;\n\n  using HandlerWithContentReader = std::function<void(\n      const Request &, Response &, const ContentReader &content_reader)>;\n\n  using Expect100ContinueHandler =\n      std::function<int(const Request &, Response &)>;\n\n  Server();\n\n  virtual ~Server();\n\n  virtual bool is_valid() const;\n\n  Server &Get(const std::string &pattern, Handler handler);\n  Server &Post(const std::string &pattern, Handler handler);\n  Server &Post(const std::string &pattern, HandlerWithContentReader handler);\n  Server &Put(const std::string &pattern, Handler handler);\n  Server &Put(const std::string &pattern, HandlerWithContentReader handler);\n  Server &Patch(const std::string &pattern, Handler handler);\n  Server &Patch(const std::string &pattern, HandlerWithContentReader handler);\n  Server &Delete(const std::string &pattern, Handler handler);\n  Server &Delete(const std::string &pattern, HandlerWithContentReader handler);\n  Server &Options(const std::string &pattern, Handler handler);\n\n  bool set_base_dir(const std::string &dir,\n                    const std::string &mount_point = std::string());\n  bool set_mount_point(const std::string &mount_point, const std::string &dir,\n                       Headers headers = Headers());\n  bool remove_mount_point(const std::string &mount_point);\n  Server &set_file_extension_and_mimetype_mapping(const std::string &ext,\n                                                  const std::string &mime);\n  Server &set_file_request_handler(Handler handler);\n\n  Server &set_error_handler(HandlerWithResponse handler);\n  Server &set_error_handler(Handler handler);\n  Server &set_exception_handler(ExceptionHandler handler);\n  Server &set_pre_routing_handler(HandlerWithResponse handler);\n  Server &set_post_routing_handler(Handler handler);\n\n  Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);\n  Server &set_logger(Logger logger);\n\n  Server &set_address_family(int family);\n  Server &set_tcp_nodelay(bool on);\n  Server &set_socket_options(SocketOptions socket_options);\n\n  Server &set_default_headers(Headers headers);\n\n  Server &set_keep_alive_max_count(size_t count);\n  Server &set_keep_alive_timeout(time_t sec);\n\n  Server &set_read_timeout(time_t sec, time_t usec = 0);\n  template <class Rep, class Period>\n  Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);\n\n  Server &set_write_timeout(time_t sec, time_t usec = 0);\n  template <class Rep, class Period>\n  Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);\n\n  Server &set_idle_interval(time_t sec, time_t usec = 0);\n  template <class Rep, class Period>\n  Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);\n\n  Server &set_payload_max_length(size_t length);\n\n  bool bind_to_port(const std::string &host, int port, int socket_flags = 0);\n  int bind_to_any_port(const std::string &host, int socket_flags = 0);\n  bool listen_after_bind();\n\n  bool listen(const std::string &host, int port, int socket_flags = 0);\n\n  bool is_running() const;\n  void wait_until_ready() const;\n  void stop();\n\n  std::function<TaskQueue *(void)> new_task_queue;\n\nprotected:\n  bool process_request(Stream &strm, bool close_connection,\n                       bool &connection_closed,\n                       const std::function<void(Request &)> &setup_request);\n\n  std::atomic<socket_t> svr_sock_{INVALID_SOCKET};\n  size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;\n  time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;\n  time_t read_timeout_sec_ = CPPHTTPLIB_READ_TIMEOUT_SECOND;\n  time_t read_timeout_usec_ = CPPHTTPLIB_READ_TIMEOUT_USECOND;\n  time_t write_timeout_sec_ = CPPHTTPLIB_WRITE_TIMEOUT_SECOND;\n  time_t write_timeout_usec_ = CPPHTTPLIB_WRITE_TIMEOUT_USECOND;\n  time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;\n  time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;\n  size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;\n\nprivate:\n  using Handlers = std::vector<std::pair<std::regex, Handler>>;\n  using HandlersForContentReader =\n      std::vector<std::pair<std::regex, HandlerWithContentReader>>;\n\n  socket_t create_server_socket(const std::string &host, int port,\n                                int socket_flags,\n                                SocketOptions socket_options) const;\n  int bind_internal(const std::string &host, int port, int socket_flags);\n  bool listen_internal();\n\n  bool routing(Request &req, Response &res, Stream &strm);\n  bool handle_file_request(const Request &req, Response &res,\n                           bool head = false);\n  bool dispatch_request(Request &req, Response &res, const Handlers &handlers);\n  bool\n  dispatch_request_for_content_reader(Request &req, Response &res,\n                                      ContentReader content_reader,\n                                      const HandlersForContentReader &handlers);\n\n  bool parse_request_line(const char *s, Request &req);\n  void apply_ranges(const Request &req, Response &res,\n                    std::string &content_type, std::string &boundary);\n  bool write_response(Stream &strm, bool close_connection, const Request &req,\n                      Response &res);\n  bool write_response_with_content(Stream &strm, bool close_connection,\n                                   const Request &req, Response &res);\n  bool write_response_core(Stream &strm, bool close_connection,\n                           const Request &req, Response &res,\n                           bool need_apply_ranges);\n  bool write_content_with_provider(Stream &strm, const Request &req,\n                                   Response &res, const std::string &boundary,\n                                   const std::string &content_type);\n  bool read_content(Stream &strm, Request &req, Response &res);\n  bool\n  read_content_with_content_receiver(Stream &strm, Request &req, Response &res,\n                                     ContentReceiver receiver,\n                                     MultipartContentHeader multipart_header,\n                                     ContentReceiver multipart_receiver);\n  bool read_content_core(Stream &strm, Request &req, Response &res,\n                         ContentReceiver receiver,\n                         MultipartContentHeader multipart_header,\n                         ContentReceiver multipart_receiver);\n\n  virtual bool process_and_close_socket(socket_t sock);\n\n  struct MountPointEntry {\n    std::string mount_point;\n    std::string base_dir;\n    Headers headers;\n  };\n  std::vector<MountPointEntry> base_dirs_;\n\n  std::atomic<bool> is_running_{false};\n  std::atomic<bool> done_{false};\n  std::map<std::string, std::string> file_extension_and_mimetype_map_;\n  Handler file_request_handler_;\n  Handlers get_handlers_;\n  Handlers post_handlers_;\n  HandlersForContentReader post_handlers_for_content_reader_;\n  Handlers put_handlers_;\n  HandlersForContentReader put_handlers_for_content_reader_;\n  Handlers patch_handlers_;\n  HandlersForContentReader patch_handlers_for_content_reader_;\n  Handlers delete_handlers_;\n  HandlersForContentReader delete_handlers_for_content_reader_;\n  Handlers options_handlers_;\n  HandlerWithResponse error_handler_;\n  ExceptionHandler exception_handler_;\n  HandlerWithResponse pre_routing_handler_;\n  Handler post_routing_handler_;\n  Logger logger_;\n  Expect100ContinueHandler expect_100_continue_handler_;\n\n  int address_family_ = AF_UNSPEC;\n  bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;\n  SocketOptions socket_options_ = default_socket_options;\n\n  Headers default_headers_;\n};\n\nenum class Error {\n  Success = 0,\n  Unknown,\n  Connection,\n  BindIPAddress,\n  Read,\n  Write,\n  ExceedRedirectCount,\n  Canceled,\n  SSLConnection,\n  SSLLoadingCerts,\n  SSLServerVerification,\n  UnsupportedMultipartBoundaryChars,\n  Compression,\n  ConnectionTimeout,\n\n  // For internal use only\n  SSLPeerCouldBeClosed_,\n};\n\nstd::string to_string(const Error error);\n\nstd::ostream &operator<<(std::ostream &os, const Error &obj);\n\nclass Result {\npublic:\n  Result(std::unique_ptr<Response> &&res, Error err,\n         Headers &&request_headers = Headers{})\n      : res_(std::move(res)), err_(err),\n        request_headers_(std::move(request_headers)) {}\n  // Response\n  operator bool() const { return res_ != nullptr; }\n  bool operator==(std::nullptr_t) const { return res_ == nullptr; }\n  bool operator!=(std::nullptr_t) const { return res_ != nullptr; }\n  const Response &value() const { return *res_; }\n  Response &value() { return *res_; }\n  const Response &operator*() const { return *res_; }\n  Response &operator*() { return *res_; }\n  const Response *operator->() const { return res_.get(); }\n  Response *operator->() { return res_.get(); }\n\n  // Error\n  Error error() const { return err_; }\n\n  // Request Headers\n  bool has_request_header(const std::string &key) const;\n  std::string get_request_header_value(const std::string &key,\n                                       size_t id = 0) const;\n  template <typename T>\n  T get_request_header_value(const std::string &key, size_t id = 0) const;\n  size_t get_request_header_value_count(const std::string &key) const;\n\nprivate:\n  std::unique_ptr<Response> res_;\n  Error err_;\n  Headers request_headers_;\n};\n\nclass ClientImpl {\npublic:\n  explicit ClientImpl(const std::string &host);\n\n  explicit ClientImpl(const std::string &host, int port);\n\n  explicit ClientImpl(const std::string &host, int port,\n                      const std::string &client_cert_path,\n                      const std::string &client_key_path);\n\n  virtual ~ClientImpl();\n\n  virtual bool is_valid() const;\n\n  Result Get(const std::string &path);\n  Result Get(const std::string &path, const Headers &headers);\n  Result Get(const std::string &path, Progress progress);\n  Result Get(const std::string &path, const Headers &headers,\n             Progress progress);\n  Result Get(const std::string &path, ContentReceiver content_receiver);\n  Result Get(const std::string &path, const Headers &headers,\n             ContentReceiver content_receiver);\n  Result Get(const std::string &path, ContentReceiver content_receiver,\n             Progress progress);\n  Result Get(const std::string &path, const Headers &headers,\n             ContentReceiver content_receiver, Progress progress);\n  Result Get(const std::string &path, ResponseHandler response_handler,\n             ContentReceiver content_receiver);\n  Result Get(const std::string &path, const Headers &headers,\n             ResponseHandler response_handler,\n             ContentReceiver content_receiver);\n  Result Get(const std::string &path, ResponseHandler response_handler,\n             ContentReceiver content_receiver, Progress progress);\n  Result Get(const std::string &path, const Headers &headers,\n             ResponseHandler response_handler, ContentReceiver content_receiver,\n             Progress progress);\n\n  Result Get(const std::string &path, const Params &params,\n             const Headers &headers, Progress progress = nullptr);\n  Result Get(const std::string &path, const Params &params,\n             const Headers &headers, ContentReceiver content_receiver,\n             Progress progress = nullptr);\n  Result Get(const std::string &path, const Params &params,\n             const Headers &headers, ResponseHandler response_handler,\n             ContentReceiver content_receiver, Progress progress = nullptr);\n\n  Result Head(const std::string &path);\n  Result Head(const std::string &path, const Headers &headers);\n\n  Result Post(const std::string &path);\n  Result Post(const std::string &path, const Headers &headers);\n  Result Post(const std::string &path, const char *body, size_t content_length,\n              const std::string &content_type);\n  Result Post(const std::string &path, const Headers &headers, const char *body,\n              size_t content_length, const std::string &content_type);\n  Result Post(const std::string &path, const std::string &body,\n              const std::string &content_type);\n  Result Post(const std::string &path, const Headers &headers,\n              const std::string &body, const std::string &content_type);\n  Result Post(const std::string &path, size_t content_length,\n              ContentProvider content_provider,\n              const std::string &content_type);\n  Result Post(const std::string &path,\n              ContentProviderWithoutLength content_provider,\n              const std::string &content_type);\n  Result Post(const std::string &path, const Headers &headers,\n              size_t content_length, ContentProvider content_provider,\n              const std::string &content_type);\n  Result Post(const std::string &path, const Headers &headers,\n              ContentProviderWithoutLength content_provider,\n              const std::string &content_type);\n  Result Post(const std::string &path, const Params &params);\n  Result Post(const std::string &path, const Headers &headers,\n              const Params &params);\n  Result Post(const std::string &path, const MultipartFormDataItems &items);\n  Result Post(const std::string &path, const Headers &headers,\n              const MultipartFormDataItems &items);\n  Result Post(const std::string &path, const Headers &headers,\n              const MultipartFormDataItems &items, const std::string &boundary);\n  Result Post(const std::string &path, const Headers &headers,\n              const MultipartFormDataItems &items,\n              const MultipartFormDataProviderItems &provider_items);\n\n  Result Put(const std::string &path);\n  Result Put(const std::string &path, const char *body, size_t content_length,\n             const std::string &content_type);\n  Result Put(const std::string &path, const Headers &headers, const char *body,\n             size_t content_length, const std::string &content_type);\n  Result Put(const std::string &path, const std::string &body,\n             const std::string &content_type);\n  Result Put(const std::string &path, const Headers &headers,\n             const std::string &body, const std::string &content_type);\n  Result Put(const std::string &path, size_t content_length,\n             ContentProvider content_provider, const std::string &content_type);\n  Result Put(const std::string &path,\n             ContentProviderWithoutLength content_provider,\n             const std::string &content_type);\n  Result Put(const std::string &path, const Headers &headers,\n             size_t content_length, ContentProvider content_provider,\n             const std::string &content_type);\n  Result Put(const std::string &path, const Headers &headers,\n             ContentProviderWithoutLength content_provider,\n             const std::string &content_type);\n  Result Put(const std::string &path, const Params &params);\n  Result Put(const std::string &path, const Headers &headers,\n             const Params &params);\n  Result Put(const std::string &path, const MultipartFormDataItems &items);\n  Result Put(const std::string &path, const Headers &headers,\n             const MultipartFormDataItems &items);\n  Result Put(const std::string &path, const Headers &headers,\n             const MultipartFormDataItems &items, const std::string &boundary);\n  Result Put(const std::string &path, const Headers &headers,\n             const MultipartFormDataItems &items,\n             const MultipartFormDataProviderItems &provider_items);\n\n  Result Patch(const std::string &path);\n  Result Patch(const std::string &path, const char *body, size_t content_length,\n               const std::string &content_type);\n  Result Patch(const std::string &path, const Headers &headers,\n               const char *body, size_t content_length,\n               const std::string &content_type);\n  Result Patch(const std::string &path, const std::string &body,\n               const std::string &content_type);\n  Result Patch(const std::string &path, const Headers &headers,\n               const std::string &body, const std::string &content_type);\n  Result Patch(const std::string &path, size_t content_length,\n               ContentProvider content_provider,\n               const std::string &content_type);\n  Result Patch(const std::string &path,\n               ContentProviderWithoutLength content_provider,\n               const std::string &content_type);\n  Result Patch(const std::string &path, const Headers &headers,\n               size_t content_length, ContentProvider content_provider,\n               const std::string &content_type);\n  Result Patch(const std::string &path, const Headers &headers,\n               ContentProviderWithoutLength content_provider,\n               const std::string &content_type);\n\n  Result Delete(const std::string &path);\n  Result Delete(const std::string &path, const Headers &headers);\n  Result Delete(const std::string &path, const char *body,\n                size_t content_length, const std::string &content_type);\n  Result Delete(const std::string &path, const Headers &headers,\n                const char *body, size_t content_length,\n                const std::string &content_type);\n  Result Delete(const std::string &path, const std::string &body,\n                const std::string &content_type);\n  Result Delete(const std::string &path, const Headers &headers,\n                const std::string &body, const std::string &content_type);\n\n  Result Options(const std::string &path);\n  Result Options(const std::string &path, const Headers &headers);\n\n  bool send(Request &req, Response &res, Error &error);\n  Result send(const Request &req);\n\n  size_t is_socket_open() const;\n\n  socket_t socket() const;\n\n  void stop();\n\n  void set_hostname_addr_map(std::map<std::string, std::string> addr_map);\n\n  void set_default_headers(Headers headers);\n\n  void set_address_family(int family);\n  void set_tcp_nodelay(bool on);\n  void set_socket_options(SocketOptions socket_options);\n\n  void set_connection_timeout(time_t sec, time_t usec = 0);\n  template <class Rep, class Period>\n  void\n  set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);\n\n  void set_read_timeout(time_t sec, time_t usec = 0);\n  template <class Rep, class Period>\n  void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);\n\n  void set_write_timeout(time_t sec, time_t usec = 0);\n  template <class Rep, class Period>\n  void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);\n\n  void set_basic_auth(const std::string &username, const std::string &password);\n  void set_bearer_token_auth(const std::string &token);\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n  void set_digest_auth(const std::string &username,\n                       const std::string &password);\n#endif\n\n  void set_keep_alive(bool on);\n  void set_follow_location(bool on);\n\n  void set_url_encode(bool on);\n\n  void set_compress(bool on);\n\n  void set_decompress(bool on);\n\n  void set_interface(const std::string &intf);\n\n  void set_proxy(const std::string &host, int port);\n  void set_proxy_basic_auth(const std::string &username,\n                            const std::string &password);\n  void set_proxy_bearer_token_auth(const std::string &token);\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n  void set_proxy_digest_auth(const std::string &username,\n                             const std::string &password);\n#endif\n\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n  void set_ca_cert_path(const std::string &ca_cert_file_path,\n                        const std::string &ca_cert_dir_path = std::string());\n  void set_ca_cert_store(X509_STORE *ca_cert_store);\n#endif\n\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n  void enable_server_certificate_verification(bool enabled);\n#endif\n\n  void set_logger(Logger logger);\n\nprotected:\n  struct Socket {\n    socket_t sock = INVALID_SOCKET;\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n    SSL *ssl = nullptr;\n#endif\n\n    bool is_open() const { return sock != INVALID_SOCKET; }\n  };\n\n  virtual bool create_and_connect_socket(Socket &socket, Error &error);\n\n  // All of:\n  //   shutdown_ssl\n  //   shutdown_socket\n  //   close_socket\n  // should ONLY be called when socket_mutex_ is locked.\n  // Also, shutdown_ssl and close_socket should also NOT be called concurrently\n  // with a DIFFERENT thread sending requests using that socket.\n  virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);\n  void shutdown_socket(Socket &socket);\n  void close_socket(Socket &socket);\n\n  bool process_request(Stream &strm, Request &req, Response &res,\n                       bool close_connection, Error &error);\n\n  bool write_content_with_provider(Stream &strm, const Request &req,\n                                   Error &error);\n\n  void copy_settings(const ClientImpl &rhs);\n\n  // Socket endpoint information\n  const std::string host_;\n  const int port_;\n  const std::string host_and_port_;\n\n  // Current open socket\n  Socket socket_;\n  mutable std::mutex socket_mutex_;\n  std::recursive_mutex request_mutex_;\n\n  // These are all protected under socket_mutex\n  size_t socket_requests_in_flight_ = 0;\n  std::thread::id socket_requests_are_from_thread_ = std::thread::id();\n  bool socket_should_be_closed_when_request_is_done_ = false;\n\n  // Hostname-IP map\n  std::map<std::string, std::string> addr_map_;\n\n  // Default headers\n  Headers default_headers_;\n\n  // Settings\n  std::string client_cert_path_;\n  std::string client_key_path_;\n\n  time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;\n  time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;\n  time_t read_timeout_sec_ = CPPHTTPLIB_READ_TIMEOUT_SECOND;\n  time_t read_timeout_usec_ = CPPHTTPLIB_READ_TIMEOUT_USECOND;\n  time_t write_timeout_sec_ = CPPHTTPLIB_WRITE_TIMEOUT_SECOND;\n  time_t write_timeout_usec_ = CPPHTTPLIB_WRITE_TIMEOUT_USECOND;\n\n  std::string basic_auth_username_;\n  std::string basic_auth_password_;\n  std::string bearer_token_auth_token_;\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n  std::string digest_auth_username_;\n  std::string digest_auth_password_;\n#endif\n\n  bool keep_alive_ = false;\n  bool follow_location_ = false;\n\n  bool url_encode_ = true;\n\n  int address_family_ = AF_UNSPEC;\n  bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;\n  SocketOptions socket_options_ = nullptr;\n\n  bool compress_ = false;\n  bool decompress_ = true;\n\n  std::string interface_;\n\n  std::string proxy_host_;\n  int proxy_port_ = -1;\n\n  std::string proxy_basic_auth_username_;\n  std::string proxy_basic_auth_password_;\n  std::string proxy_bearer_token_auth_token_;\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n  std::string proxy_digest_auth_username_;\n  std::string proxy_digest_auth_password_;\n#endif\n\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n  std::string ca_cert_file_path_;\n  std::string ca_cert_dir_path_;\n\n  X509_STORE *ca_cert_store_ = nullptr;\n#endif\n\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n  bool server_certificate_verification_ = true;\n#endif\n\n  Logger logger_;\n\nprivate:\n  bool send_(Request &req, Response &res, Error &error);\n  Result send_(Request &&req);\n\n  socket_t create_client_socket(Error &error) const;\n  bool read_response_line(Stream &strm, const Request &req, Response &res);\n  bool write_request(Stream &strm, Request &req, bool close_connection,\n                     Error &error);\n  bool redirect(Request &req, Response &res, Error &error);\n  bool handle_request(Stream &strm, Request &req, Response &res,\n                      bool close_connection, Error &error);\n  std::unique_ptr<Response> send_with_content_provider(\n      Request &req, const char *body, size_t content_length,\n      ContentProvider content_provider,\n      ContentProviderWithoutLength content_provider_without_length,\n      const std::string &content_type, Error &error);\n  Result send_with_content_provider(\n      const std::string &method, const std::string &path,\n      const Headers &headers, const char *body, size_t content_length,\n      ContentProvider content_provider,\n      ContentProviderWithoutLength content_provider_without_length,\n      const std::string &content_type);\n  ContentProviderWithoutLength get_multipart_content_provider(\n      const std::string &boundary, const MultipartFormDataItems &items,\n      const MultipartFormDataProviderItems &provider_items);\n\n  std::string adjust_host_string(const std::string &host) const;\n\n  virtual bool process_socket(const Socket &socket,\n                              std::function<bool(Stream &strm)> callback);\n  virtual bool is_ssl() const;\n};\n\nclass Client {\npublic:\n  // Universal interface\n  explicit Client(const std::string &scheme_host_port);\n\n  explicit Client(const std::string &scheme_host_port,\n                  const std::string &client_cert_path,\n                  const std::string &client_key_path);\n\n  // HTTP only interface\n  explicit Client(const std::string &host, int port);\n\n  explicit Client(const std::string &host, int port,\n                  const std::string &client_cert_path,\n                  const std::string &client_key_path);\n\n  Client(Client &&) = default;\n\n  ~Client();\n\n  bool is_valid() const;\n\n  Result Get(const std::string &path);\n  Result Get(const std::string &path, const Headers &headers);\n  Result Get(const std::string &path, Progress progress);\n  Result Get(const std::string &path, const Headers &headers,\n             Progress progress);\n  Result Get(const std::string &path, ContentReceiver content_receiver);\n  Result Get(const std::string &path, const Headers &headers,\n             ContentReceiver content_receiver);\n  Result Get(const std::string &path, ContentReceiver content_receiver,\n             Progress progress);\n  Result Get(const std::string &path, const Headers &headers,\n             ContentReceiver content_receiver, Progress progress);\n  Result Get(const std::string &path, ResponseHandler response_handler,\n             ContentReceiver content_receiver);\n  Result Get(const std::string &path, const Headers &headers,\n             ResponseHandler response_handler,\n             ContentReceiver content_receiver);\n  Result Get(const std::string &path, const Headers &headers,\n             ResponseHandler response_handler, ContentReceiver content_receiver,\n             Progress progress);\n  Result Get(const std::string &path, ResponseHandler response_handler,\n             ContentReceiver content_receiver, Progress progress);\n\n  Result Get(const std::string &path, const Params &params,\n             const Headers &headers, Progress progress = nullptr);\n  Result Get(const std::string &path, const Params &params,\n             const Headers &headers, ContentReceiver content_receiver,\n             Progress progress = nullptr);\n  Result Get(const std::string &path, const Params &params,\n             const Headers &headers, ResponseHandler response_handler,\n             ContentReceiver content_receiver, Progress progress = nullptr);\n\n  Result Head(const std::string &path);\n  Result Head(const std::string &path, const Headers &headers);\n\n  Result Post(const std::string &path);\n  Result Post(const std::string &path, const Headers &headers);\n  Result Post(const std::string &path, const char *body, size_t content_length,\n              const std::string &content_type);\n  Result Post(const std::string &path, const Headers &headers, const char *body,\n              size_t content_length, const std::string &content_type);\n  Result Post(const std::string &path, const std::string &body,\n              const std::string &content_type);\n  Result Post(const std::string &path, const Headers &headers,\n              const std::string &body, const std::string &content_type);\n  Result Post(const std::string &path, size_t content_length,\n              ContentProvider content_provider,\n              const std::string &content_type);\n  Result Post(const std::string &path,\n              ContentProviderWithoutLength content_provider,\n              const std::string &content_type);\n  Result Post(const std::string &path, const Headers &headers,\n              size_t content_length, ContentProvider content_provider,\n              const std::string &content_type);\n  Result Post(const std::string &path, const Headers &headers,\n              ContentProviderWithoutLength content_provider,\n              const std::string &content_type);\n  Result Post(const std::string &path, const Params &params);\n  Result Post(const std::string &path, const Headers &headers,\n              const Params &params);\n  Result Post(const std::string &path, const MultipartFormDataItems &items);\n  Result Post(const std::string &path, const Headers &headers,\n              const MultipartFormDataItems &items);\n  Result Post(const std::string &path, const Headers &headers,\n              const MultipartFormDataItems &items, const std::string &boundary);\n  Result Post(const std::string &path, const Headers &headers,\n              const MultipartFormDataItems &items,\n              const MultipartFormDataProviderItems &provider_items);\n\n  Result Put(const std::string &path);\n  Result Put(const std::string &path, const char *body, size_t content_length,\n             const std::string &content_type);\n  Result Put(const std::string &path, const Headers &headers, const char *body,\n             size_t content_length, const std::string &content_type);\n  Result Put(const std::string &path, const std::string &body,\n             const std::string &content_type);\n  Result Put(const std::string &path, const Headers &headers,\n             const std::string &body, const std::string &content_type);\n  Result Put(const std::string &path, size_t content_length,\n             ContentProvider content_provider, const std::string &content_type);\n  Result Put(const std::string &path,\n             ContentProviderWithoutLength content_provider,\n             const std::string &content_type);\n  Result Put(const std::string &path, const Headers &headers,\n             size_t content_length, ContentProvider content_provider,\n             const std::string &content_type);\n  Result Put(const std::string &path, const Headers &headers,\n             ContentProviderWithoutLength content_provider,\n             const std::string &content_type);\n  Result Put(const std::string &path, const Params &params);\n  Result Put(const std::string &path, const Headers &headers,\n             const Params &params);\n  Result Put(const std::string &path, const MultipartFormDataItems &items);\n  Result Put(const std::string &path, const Headers &headers,\n             const MultipartFormDataItems &items);\n  Result Put(const std::string &path, const Headers &headers,\n             const MultipartFormDataItems &items, const std::string &boundary);\n  Result Put(const std::string &path, const Headers &headers,\n             const MultipartFormDataItems &items,\n             const MultipartFormDataProviderItems &provider_items);\n\n  Result Patch(const std::string &path);\n  Result Patch(const std::string &path, const char *body, size_t content_length,\n               const std::string &content_type);\n  Result Patch(const std::string &path, const Headers &headers,\n               const char *body, size_t content_length,\n               const std::string &content_type);\n  Result Patch(const std::string &path, const std::string &body,\n               const std::string &content_type);\n  Result Patch(const std::string &path, const Headers &headers,\n               const std::string &body, const std::string &content_type);\n  Result Patch(const std::string &path, size_t content_length,\n               ContentProvider content_provider,\n               const std::string &content_type);\n  Result Patch(const std::string &path,\n               ContentProviderWithoutLength content_provider,\n               const std::string &content_type);\n  Result Patch(const std::string &path, const Headers &headers,\n               size_t content_length, ContentProvider content_provider,\n               const std::string &content_type);\n  Result Patch(const std::string &path, const Headers &headers,\n               ContentProviderWithoutLength content_provider,\n               const std::string &content_type);\n\n  Result Delete(const std::string &path);\n  Result Delete(const std::string &path, const Headers &headers);\n  Result Delete(const std::string &path, const char *body,\n                size_t content_length, const std::string &content_type);\n  Result Delete(const std::string &path, const Headers &headers,\n                const char *body, size_t content_length,\n                const std::string &content_type);\n  Result Delete(const std::string &path, const std::string &body,\n                const std::string &content_type);\n  Result Delete(const std::string &path, const Headers &headers,\n                const std::string &body, const std::string &content_type);\n\n  Result Options(const std::string &path);\n  Result Options(const std::string &path, const Headers &headers);\n\n  bool send(Request &req, Response &res, Error &error);\n  Result send(const Request &req);\n\n  size_t is_socket_open() const;\n\n  socket_t socket() const;\n\n  void stop();\n\n  void set_hostname_addr_map(std::map<std::string, std::string> addr_map);\n\n  void set_default_headers(Headers headers);\n\n  void set_address_family(int family);\n  void set_tcp_nodelay(bool on);\n  void set_socket_options(SocketOptions socket_options);\n\n  void set_connection_timeout(time_t sec, time_t usec = 0);\n  template <class Rep, class Period>\n  void\n  set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);\n\n  void set_read_timeout(time_t sec, time_t usec = 0);\n  template <class Rep, class Period>\n  void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);\n\n  void set_write_timeout(time_t sec, time_t usec = 0);\n  template <class Rep, class Period>\n  void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);\n\n  void set_basic_auth(const std::string &username, const std::string &password);\n  void set_bearer_token_auth(const std::string &token);\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n  void set_digest_auth(const std::string &username,\n                       const std::string &password);\n#endif\n\n  void set_keep_alive(bool on);\n  void set_follow_location(bool on);\n\n  void set_url_encode(bool on);\n\n  void set_compress(bool on);\n\n  void set_decompress(bool on);\n\n  void set_interface(const std::string &intf);\n\n  void set_proxy(const std::string &host, int port);\n  void set_proxy_basic_auth(const std::string &username,\n                            const std::string &password);\n  void set_proxy_bearer_token_auth(const std::string &token);\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n  void set_proxy_digest_auth(const std::string &username,\n                             const std::string &password);\n#endif\n\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n  void enable_server_certificate_verification(bool enabled);\n#endif\n\n  void set_logger(Logger logger);\n\n  // SSL\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n  void set_ca_cert_path(const std::string &ca_cert_file_path,\n                        const std::string &ca_cert_dir_path = std::string());\n\n  void set_ca_cert_store(X509_STORE *ca_cert_store);\n\n  long get_openssl_verify_result() const;\n\n  SSL_CTX *ssl_context() const;\n#endif\n\nprivate:\n  std::unique_ptr<ClientImpl> cli_;\n\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n  bool is_ssl_ = false;\n#endif\n};\n\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\nclass SSLServer : public Server {\npublic:\n  SSLServer(const char *cert_path, const char *private_key_path,\n            const char *client_ca_cert_file_path = nullptr,\n            const char *client_ca_cert_dir_path = nullptr,\n            const char *private_key_password = nullptr);\n\n  SSLServer(X509 *cert, EVP_PKEY *private_key,\n            X509_STORE *client_ca_cert_store = nullptr);\n\n  SSLServer(\n      const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback);\n\n  ~SSLServer() override;\n\n  bool is_valid() const override;\n\n  SSL_CTX *ssl_context() const;\n\nprivate:\n  bool process_and_close_socket(socket_t sock) override;\n\n  SSL_CTX *ctx_;\n  std::mutex ctx_mutex_;\n};\n\nclass SSLClient : public ClientImpl {\npublic:\n  explicit SSLClient(const std::string &host);\n\n  explicit SSLClient(const std::string &host, int port);\n\n  explicit SSLClient(const std::string &host, int port,\n                     const std::string &client_cert_path,\n                     const std::string &client_key_path);\n\n  explicit SSLClient(const std::string &host, int port, X509 *client_cert,\n                     EVP_PKEY *client_key);\n\n  ~SSLClient() override;\n\n  bool is_valid() const override;\n\n  void set_ca_cert_store(X509_STORE *ca_cert_store);\n\n  long get_openssl_verify_result() const;\n\n  SSL_CTX *ssl_context() const;\n\nprivate:\n  bool create_and_connect_socket(Socket &socket, Error &error) override;\n  void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;\n  void shutdown_ssl_impl(Socket &socket, bool shutdown_socket);\n\n  bool process_socket(const Socket &socket,\n                      std::function<bool(Stream &strm)> callback) override;\n  bool is_ssl() const override;\n\n  bool connect_with_proxy(Socket &sock, Response &res, bool &success,\n                          Error &error);\n  bool initialize_ssl(Socket &socket, Error &error);\n\n  bool load_certs();\n\n  bool verify_host(X509 *server_cert) const;\n  bool verify_host_with_subject_alt_name(X509 *server_cert) const;\n  bool verify_host_with_common_name(X509 *server_cert) const;\n  bool check_host_name(const char *pattern, size_t pattern_len) const;\n\n  SSL_CTX *ctx_;\n  std::mutex ctx_mutex_;\n  std::once_flag initialize_cert_;\n\n  std::vector<std::string> host_components_;\n\n  long verify_result_ = 0;\n\n  friend class ClientImpl;\n};\n#endif\n\n/*\n * Implementation of template methods.\n */\n\nnamespace detail {\n\ntemplate <typename T, typename U>\ninline void duration_to_sec_and_usec(const T &duration, U callback) {\n  auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();\n  auto usec = std::chrono::duration_cast<std::chrono::microseconds>(\n                  duration - std::chrono::seconds(sec))\n                  .count();\n  callback(static_cast<time_t>(sec), static_cast<time_t>(usec));\n}\n\ntemplate <typename T>\ninline T get_header_value(const Headers & /*headers*/,\n                          const std::string & /*key*/, size_t /*id*/ = 0,\n                          uint64_t /*def*/ = 0) {}\n\ntemplate <>\ninline uint64_t get_header_value<uint64_t>(const Headers &headers,\n                                           const std::string &key, size_t id,\n                                           uint64_t def) {\n  auto rng = headers.equal_range(key);\n  auto it = rng.first;\n  std::advance(it, static_cast<ssize_t>(id));\n  if (it != rng.second) {\n    return std::strtoull(it->second.data(), nullptr, 10);\n  }\n  return def;\n}\n\n} // namespace detail\n\ntemplate <typename T>\ninline T Request::get_header_value(const std::string &key, size_t id) const {\n  return detail::get_header_value<T>(headers, key, id, 0);\n}\n\ntemplate <typename T>\ninline T Response::get_header_value(const std::string &key, size_t id) const {\n  return detail::get_header_value<T>(headers, key, id, 0);\n}\n\ntemplate <typename... Args>\ninline ssize_t Stream::write_format(const char *fmt, const Args &...args) {\n  const auto bufsiz = 2048;\n  std::array<char, bufsiz> buf{};\n\n  auto sn = snprintf(buf.data(), buf.size() - 1, fmt, args...);\n  if (sn <= 0) { return sn; }\n\n  auto n = static_cast<size_t>(sn);\n\n  if (n >= buf.size() - 1) {\n    std::vector<char> glowable_buf(buf.size());\n\n    while (n >= glowable_buf.size() - 1) {\n      glowable_buf.resize(glowable_buf.size() * 2);\n      n = static_cast<size_t>(\n          snprintf(&glowable_buf[0], glowable_buf.size() - 1, fmt, args...));\n    }\n    return write(&glowable_buf[0], n);\n  } else {\n    return write(buf.data(), n);\n  }\n}\n\ninline void default_socket_options(socket_t sock) {\n  int yes = 1;\n#ifdef _WIN32\n  setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char *>(&yes),\n             sizeof(yes));\n  setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,\n             reinterpret_cast<char *>(&yes), sizeof(yes));\n#else\n#ifdef SO_REUSEPORT\n  setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, reinterpret_cast<void *>(&yes),\n             sizeof(yes));\n#else\n  setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<void *>(&yes),\n             sizeof(yes));\n#endif\n#endif\n}\n\ntemplate <class Rep, class Period>\ninline Server &\nServer::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {\n  detail::duration_to_sec_and_usec(\n      duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });\n  return *this;\n}\n\ntemplate <class Rep, class Period>\ninline Server &\nServer::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {\n  detail::duration_to_sec_and_usec(\n      duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });\n  return *this;\n}\n\ntemplate <class Rep, class Period>\ninline Server &\nServer::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {\n  detail::duration_to_sec_and_usec(\n      duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });\n  return *this;\n}\n\ninline std::string to_string(const Error error) {\n  switch (error) {\n  case Error::Success: return \"Success (no error)\";\n  case Error::Connection: return \"Could not establish connection\";\n  case Error::BindIPAddress: return \"Failed to bind IP address\";\n  case Error::Read: return \"Failed to read connection\";\n  case Error::Write: return \"Failed to write connection\";\n  case Error::ExceedRedirectCount: return \"Maximum redirect count exceeded\";\n  case Error::Canceled: return \"Connection handling canceled\";\n  case Error::SSLConnection: return \"SSL connection failed\";\n  case Error::SSLLoadingCerts: return \"SSL certificate loading failed\";\n  case Error::SSLServerVerification: return \"SSL server verification failed\";\n  case Error::UnsupportedMultipartBoundaryChars:\n    return \"Unsupported HTTP multipart boundary characters\";\n  case Error::Compression: return \"Compression failed\";\n  case Error::ConnectionTimeout: return \"Connection timed out\";\n  case Error::Unknown: return \"Unknown\";\n  default: break;\n  }\n\n  return \"Invalid\";\n}\n\ninline std::ostream &operator<<(std::ostream &os, const Error &obj) {\n  os << to_string(obj);\n  os << \" (\" << static_cast<std::underlying_type<Error>::type>(obj) << ')';\n  return os;\n}\n\ntemplate <typename T>\ninline T Result::get_request_header_value(const std::string &key,\n                                          size_t id) const {\n  return detail::get_header_value<T>(request_headers_, key, id, 0);\n}\n\ntemplate <class Rep, class Period>\ninline void ClientImpl::set_connection_timeout(\n    const std::chrono::duration<Rep, Period> &duration) {\n  detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {\n    set_connection_timeout(sec, usec);\n  });\n}\n\ntemplate <class Rep, class Period>\ninline void ClientImpl::set_read_timeout(\n    const std::chrono::duration<Rep, Period> &duration) {\n  detail::duration_to_sec_and_usec(\n      duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });\n}\n\ntemplate <class Rep, class Period>\ninline void ClientImpl::set_write_timeout(\n    const std::chrono::duration<Rep, Period> &duration) {\n  detail::duration_to_sec_and_usec(\n      duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });\n}\n\ntemplate <class Rep, class Period>\ninline void Client::set_connection_timeout(\n    const std::chrono::duration<Rep, Period> &duration) {\n  cli_->set_connection_timeout(duration);\n}\n\ntemplate <class Rep, class Period>\ninline void\nClient::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {\n  cli_->set_read_timeout(duration);\n}\n\ntemplate <class Rep, class Period>\ninline void\nClient::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {\n  cli_->set_write_timeout(duration);\n}\n\n/*\n * Forward declarations and types that will be part of the .h file if split into\n * .h + .cc.\n */\n\nstd::string hosted_at(const std::string &hostname);\n\nvoid hosted_at(const std::string &hostname, std::vector<std::string> &addrs);\n\nstd::string append_query_params(const std::string &path, const Params &params);\n\nstd::pair<std::string, std::string> make_range_header(Ranges ranges);\n\nstd::pair<std::string, std::string>\nmake_basic_authentication_header(const std::string &username,\n                                 const std::string &password,\n                                 bool is_proxy = false);\n\nnamespace detail {\n\nstd::string encode_query_param(const std::string &value);\n\nstd::string decode_url(const std::string &s, bool convert_plus_to_space);\n\nvoid read_file(const std::string &path, std::string &out);\n\nstd::string trim_copy(const std::string &s);\n\nvoid split(const char *b, const char *e, char d,\n           std::function<void(const char *, const char *)> fn);\n\nbool process_client_socket(socket_t sock, time_t read_timeout_sec,\n                           time_t read_timeout_usec, time_t write_timeout_sec,\n                           time_t write_timeout_usec,\n                           std::function<bool(Stream &)> callback);\n\nsocket_t create_client_socket(\n    const std::string &host, const std::string &ip, int port,\n    int address_family, bool tcp_nodelay, SocketOptions socket_options,\n    time_t connection_timeout_sec, time_t connection_timeout_usec,\n    time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,\n    time_t write_timeout_usec, const std::string &intf, Error &error);\n\nconst char *get_header_value(const Headers &headers, const std::string &key,\n                             size_t id = 0, const char *def = nullptr);\n\nstd::string params_to_query_str(const Params &params);\n\nvoid parse_query_text(const std::string &s, Params &params);\n\nbool parse_multipart_boundary(const std::string &content_type,\n                              std::string &boundary);\n\nbool parse_range_header(const std::string &s, Ranges &ranges);\n\nint close_socket(socket_t sock);\n\nssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);\n\nssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);\n\nenum class EncodingType { None = 0, Gzip, Brotli };\n\nEncodingType encoding_type(const Request &req, const Response &res);\n\nclass BufferStream : public Stream {\npublic:\n  BufferStream() = default;\n  ~BufferStream() override = default;\n\n  bool is_readable() const override;\n  bool is_writable() const override;\n  ssize_t read(char *ptr, size_t size) override;\n  ssize_t write(const char *ptr, size_t size) override;\n  void get_remote_ip_and_port(std::string &ip, int &port) const override;\n  void get_local_ip_and_port(std::string &ip, int &port) const override;\n  socket_t socket() const override;\n\n  const std::string &get_buffer() const;\n\nprivate:\n  std::string buffer;\n  size_t position = 0;\n};\n\nclass compressor {\npublic:\n  virtual ~compressor() = default;\n\n  typedef std::function<bool(const char *data, size_t data_len)> Callback;\n  virtual bool compress(const char *data, size_t data_length, bool last,\n                        Callback callback) = 0;\n};\n\nclass decompressor {\npublic:\n  virtual ~decompressor() = default;\n\n  virtual bool is_valid() const = 0;\n\n  typedef std::function<bool(const char *data, size_t data_len)> Callback;\n  virtual bool decompress(const char *data, size_t data_length,\n                          Callback callback) = 0;\n};\n\nclass nocompressor : public compressor {\npublic:\n  virtual ~nocompressor() = default;\n\n  bool compress(const char *data, size_t data_length, bool /*last*/,\n                Callback callback) override;\n};\n\n#ifdef CPPHTTPLIB_ZLIB_SUPPORT\nclass gzip_compressor : public compressor {\npublic:\n  gzip_compressor();\n  ~gzip_compressor();\n\n  bool compress(const char *data, size_t data_length, bool last,\n                Callback callback) override;\n\nprivate:\n  bool is_valid_ = false;\n  z_stream strm_;\n};\n\nclass gzip_decompressor : public decompressor {\npublic:\n  gzip_decompressor();\n  ~gzip_decompressor();\n\n  bool is_valid() const override;\n\n  bool decompress(const char *data, size_t data_length,\n                  Callback callback) override;\n\nprivate:\n  bool is_valid_ = false;\n  z_stream strm_;\n};\n#endif\n\n#ifdef CPPHTTPLIB_BROTLI_SUPPORT\nclass brotli_compressor : public compressor {\npublic:\n  brotli_compressor();\n  ~brotli_compressor();\n\n  bool compress(const char *data, size_t data_length, bool last,\n                Callback callback) override;\n\nprivate:\n  BrotliEncoderState *state_ = nullptr;\n};\n\nclass brotli_decompressor : public decompressor {\npublic:\n  brotli_decompressor();\n  ~brotli_decompressor();\n\n  bool is_valid() const override;\n\n  bool decompress(const char *data, size_t data_length,\n                  Callback callback) override;\n\nprivate:\n  BrotliDecoderResult decoder_r;\n  BrotliDecoderState *decoder_s = nullptr;\n};\n#endif\n\n// NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`\n// to store data. The call can set memory on stack for performance.\nclass stream_line_reader {\npublic:\n  stream_line_reader(Stream &strm, char *fixed_buffer,\n                     size_t fixed_buffer_size);\n  const char *ptr() const;\n  size_t size() const;\n  bool end_with_crlf() const;\n  bool getline();\n\nprivate:\n  void append(char c);\n\n  Stream &strm_;\n  char *fixed_buffer_;\n  const size_t fixed_buffer_size_;\n  size_t fixed_buffer_used_size_ = 0;\n  std::string glowable_buffer_;\n};\n\n} // namespace detail\n\n// ----------------------------------------------------------------------------\n\n/*\n * Implementation that will be part of the .cc file if split into .h + .cc.\n */\n\nnamespace detail {\n\ninline bool is_hex(char c, int &v) {\n  if (0x20 <= c && isdigit(c)) {\n    v = c - '0';\n    return true;\n  } else if ('A' <= c && c <= 'F') {\n    v = c - 'A' + 10;\n    return true;\n  } else if ('a' <= c && c <= 'f') {\n    v = c - 'a' + 10;\n    return true;\n  }\n  return false;\n}\n\ninline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,\n                          int &val) {\n  if (i >= s.size()) { return false; }\n\n  val = 0;\n  for (; cnt; i++, cnt--) {\n    if (!s[i]) { return false; }\n    int v = 0;\n    if (is_hex(s[i], v)) {\n      val = val * 16 + v;\n    } else {\n      return false;\n    }\n  }\n  return true;\n}\n\ninline std::string from_i_to_hex(size_t n) {\n  const char *charset = \"0123456789abcdef\";\n  std::string ret;\n  do {\n    ret = charset[n & 15] + ret;\n    n >>= 4;\n  } while (n > 0);\n  return ret;\n}\n\ninline size_t to_utf8(int code, char *buff) {\n  if (code < 0x0080) {\n    buff[0] = (code & 0x7F);\n    return 1;\n  } else if (code < 0x0800) {\n    buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));\n    buff[1] = static_cast<char>(0x80 | (code & 0x3F));\n    return 2;\n  } else if (code < 0xD800) {\n    buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));\n    buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));\n    buff[2] = static_cast<char>(0x80 | (code & 0x3F));\n    return 3;\n  } else if (code < 0xE000) { // D800 - DFFF is invalid...\n    return 0;\n  } else if (code < 0x10000) {\n    buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));\n    buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));\n    buff[2] = static_cast<char>(0x80 | (code & 0x3F));\n    return 3;\n  } else if (code < 0x110000) {\n    buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));\n    buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));\n    buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));\n    buff[3] = static_cast<char>(0x80 | (code & 0x3F));\n    return 4;\n  }\n\n  // NOTREACHED\n  return 0;\n}\n\n// NOTE: This code came up with the following stackoverflow post:\n// https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c\ninline std::string base64_encode(const std::string &in) {\n  static const auto lookup =\n      \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n  std::string out;\n  out.reserve(in.size());\n\n  int val = 0;\n  int valb = -6;\n\n  for (auto c : in) {\n    val = (val << 8) + static_cast<uint8_t>(c);\n    valb += 8;\n    while (valb >= 0) {\n      out.push_back(lookup[(val >> valb) & 0x3F]);\n      valb -= 6;\n    }\n  }\n\n  if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }\n\n  while (out.size() % 4) {\n    out.push_back('=');\n  }\n\n  return out;\n}\n\ninline bool is_file(const std::string &path) {\n#ifdef _WIN32\n  return _access_s(path.c_str(), 0) == 0;\n#else\n  struct stat st;\n  return stat(path.c_str(), &st) >= 0 && S_ISREG(st.st_mode);\n#endif\n}\n\ninline bool is_dir(const std::string &path) {\n  struct stat st;\n  return stat(path.c_str(), &st) >= 0 && S_ISDIR(st.st_mode);\n}\n\ninline bool is_valid_path(const std::string &path) {\n  size_t level = 0;\n  size_t i = 0;\n\n  // Skip slash\n  while (i < path.size() && path[i] == '/') {\n    i++;\n  }\n\n  while (i < path.size()) {\n    // Read component\n    auto beg = i;\n    while (i < path.size() && path[i] != '/') {\n      i++;\n    }\n\n    auto len = i - beg;\n    assert(len > 0);\n\n    if (!path.compare(beg, len, \".\")) {\n      ;\n    } else if (!path.compare(beg, len, \"..\")) {\n      if (level == 0) { return false; }\n      level--;\n    } else {\n      level++;\n    }\n\n    // Skip slash\n    while (i < path.size() && path[i] == '/') {\n      i++;\n    }\n  }\n\n  return true;\n}\n\ninline std::string encode_query_param(const std::string &value) {\n  std::ostringstream escaped;\n  escaped.fill('0');\n  escaped << std::hex;\n\n  for (auto c : value) {\n    if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||\n        c == '.' || c == '!' || c == '~' || c == '*' || c == '\\'' || c == '(' ||\n        c == ')') {\n      escaped << c;\n    } else {\n      escaped << std::uppercase;\n      escaped << '%' << std::setw(2)\n              << static_cast<int>(static_cast<unsigned char>(c));\n      escaped << std::nouppercase;\n    }\n  }\n\n  return escaped.str();\n}\n\ninline std::string encode_url(const std::string &s) {\n  std::string result;\n  result.reserve(s.size());\n\n  for (size_t i = 0; s[i]; i++) {\n    switch (s[i]) {\n    case ' ': result += \"%20\"; break;\n    case '+': result += \"%2B\"; break;\n    case '\\r': result += \"%0D\"; break;\n    case '\\n': result += \"%0A\"; break;\n    case '\\'': result += \"%27\"; break;\n    case ',': result += \"%2C\"; break;\n    // case ':': result += \"%3A\"; break; // ok? probably...\n    case ';': result += \"%3B\"; break;\n    default:\n      auto c = static_cast<uint8_t>(s[i]);\n      if (c >= 0x80) {\n        result += '%';\n        char hex[4];\n        auto len = snprintf(hex, sizeof(hex) - 1, \"%02X\", c);\n        assert(len == 2);\n        result.append(hex, static_cast<size_t>(len));\n      } else {\n        result += s[i];\n      }\n      break;\n    }\n  }\n\n  return result;\n}\n\ninline std::string decode_url(const std::string &s,\n                              bool convert_plus_to_space) {\n  std::string result;\n\n  for (size_t i = 0; i < s.size(); i++) {\n    if (s[i] == '%' && i + 1 < s.size()) {\n      if (s[i + 1] == 'u') {\n        int val = 0;\n        if (from_hex_to_i(s, i + 2, 4, val)) {\n          // 4 digits Unicode codes\n          char buff[4];\n          size_t len = to_utf8(val, buff);\n          if (len > 0) { result.append(buff, len); }\n          i += 5; // 'u0000'\n        } else {\n          result += s[i];\n        }\n      } else {\n        int val = 0;\n        if (from_hex_to_i(s, i + 1, 2, val)) {\n          // 2 digits hex codes\n          result += static_cast<char>(val);\n          i += 2; // '00'\n        } else {\n          result += s[i];\n        }\n      }\n    } else if (convert_plus_to_space && s[i] == '+') {\n      result += ' ';\n    } else {\n      result += s[i];\n    }\n  }\n\n  return result;\n}\n\ninline void read_file(const std::string &path, std::string &out) {\n  std::ifstream fs(path, std::ios_base::binary);\n  fs.seekg(0, std::ios_base::end);\n  auto size = fs.tellg();\n  fs.seekg(0);\n  out.resize(static_cast<size_t>(size));\n  fs.read(&out[0], static_cast<std::streamsize>(size));\n}\n\ninline std::string file_extension(const std::string &path) {\n  std::smatch m;\n  static auto re = std::regex(\"\\\\.([a-zA-Z0-9]+)$\");\n  if (std::regex_search(path, m, re)) { return m[1].str(); }\n  return std::string();\n}\n\ninline bool is_space_or_tab(char c) { return c == ' ' || c == '\\t'; }\n\ninline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,\n                                      size_t right) {\n  while (b + left < e && is_space_or_tab(b[left])) {\n    left++;\n  }\n  while (right > 0 && is_space_or_tab(b[right - 1])) {\n    right--;\n  }\n  return std::make_pair(left, right);\n}\n\ninline std::string trim_copy(const std::string &s) {\n  auto r = trim(s.data(), s.data() + s.size(), 0, s.size());\n  return s.substr(r.first, r.second - r.first);\n}\n\ninline void split(const char *b, const char *e, char d,\n                  std::function<void(const char *, const char *)> fn) {\n  size_t i = 0;\n  size_t beg = 0;\n\n  while (e ? (b + i < e) : (b[i] != '\\0')) {\n    if (b[i] == d) {\n      auto r = trim(b, e, beg, i);\n      if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }\n      beg = i + 1;\n    }\n    i++;\n  }\n\n  if (i) {\n    auto r = trim(b, e, beg, i);\n    if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }\n  }\n}\n\ninline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,\n                                              size_t fixed_buffer_size)\n    : strm_(strm), fixed_buffer_(fixed_buffer),\n      fixed_buffer_size_(fixed_buffer_size) {}\n\ninline const char *stream_line_reader::ptr() const {\n  if (glowable_buffer_.empty()) {\n    return fixed_buffer_;\n  } else {\n    return glowable_buffer_.data();\n  }\n}\n\ninline size_t stream_line_reader::size() const {\n  if (glowable_buffer_.empty()) {\n    return fixed_buffer_used_size_;\n  } else {\n    return glowable_buffer_.size();\n  }\n}\n\ninline bool stream_line_reader::end_with_crlf() const {\n  auto end = ptr() + size();\n  return size() >= 2 && end[-2] == '\\r' && end[-1] == '\\n';\n}\n\ninline bool stream_line_reader::getline() {\n  fixed_buffer_used_size_ = 0;\n  glowable_buffer_.clear();\n\n  for (size_t i = 0;; i++) {\n    char byte;\n    auto n = strm_.read(&byte, 1);\n\n    if (n < 0) {\n      return false;\n    } else if (n == 0) {\n      if (i == 0) {\n        return false;\n      } else {\n        break;\n      }\n    }\n\n    append(byte);\n\n    if (byte == '\\n') { break; }\n  }\n\n  return true;\n}\n\ninline void stream_line_reader::append(char c) {\n  if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {\n    fixed_buffer_[fixed_buffer_used_size_++] = c;\n    fixed_buffer_[fixed_buffer_used_size_] = '\\0';\n  } else {\n    if (glowable_buffer_.empty()) {\n      assert(fixed_buffer_[fixed_buffer_used_size_] == '\\0');\n      glowable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);\n    }\n    glowable_buffer_ += c;\n  }\n}\n\ninline int close_socket(socket_t sock) {\n#ifdef _WIN32\n  return closesocket(sock);\n#else\n  return close(sock);\n#endif\n}\n\ntemplate <typename T> inline ssize_t handle_EINTR(T fn) {\n  ssize_t res = false;\n  while (true) {\n    res = fn();\n    if (res < 0 && errno == EINTR) { continue; }\n    break;\n  }\n  return res;\n}\n\ninline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {\n  return handle_EINTR([&]() {\n    return recv(sock,\n#ifdef _WIN32\n                static_cast<char *>(ptr), static_cast<int>(size),\n#else\n                ptr, size,\n#endif\n                flags);\n  });\n}\n\ninline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,\n                           int flags) {\n  return handle_EINTR([&]() {\n    return send(sock,\n#ifdef _WIN32\n                static_cast<const char *>(ptr), static_cast<int>(size),\n#else\n                ptr, size,\n#endif\n                flags);\n  });\n}\n\ninline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {\n#ifdef CPPHTTPLIB_USE_POLL\n  struct pollfd pfd_read;\n  pfd_read.fd = sock;\n  pfd_read.events = POLLIN;\n\n  auto timeout = static_cast<int>(sec * 1000 + usec / 1000);\n\n  return handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); });\n#else\n#ifndef _WIN32\n  if (sock >= FD_SETSIZE) { return 1; }\n#endif\n\n  fd_set fds;\n  FD_ZERO(&fds);\n  FD_SET(sock, &fds);\n\n  timeval tv;\n  tv.tv_sec = static_cast<long>(sec);\n  tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);\n\n  return handle_EINTR([&]() {\n    return select(static_cast<int>(sock + 1), &fds, nullptr, nullptr, &tv);\n  });\n#endif\n}\n\ninline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {\n#ifdef CPPHTTPLIB_USE_POLL\n  struct pollfd pfd_read;\n  pfd_read.fd = sock;\n  pfd_read.events = POLLOUT;\n\n  auto timeout = static_cast<int>(sec * 1000 + usec / 1000);\n\n  return handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); });\n#else\n#ifndef _WIN32\n  if (sock >= FD_SETSIZE) { return 1; }\n#endif\n\n  fd_set fds;\n  FD_ZERO(&fds);\n  FD_SET(sock, &fds);\n\n  timeval tv;\n  tv.tv_sec = static_cast<long>(sec);\n  tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);\n\n  return handle_EINTR([&]() {\n    return select(static_cast<int>(sock + 1), nullptr, &fds, nullptr, &tv);\n  });\n#endif\n}\n\ninline Error wait_until_socket_is_ready(socket_t sock, time_t sec,\n                                        time_t usec) {\n#ifdef CPPHTTPLIB_USE_POLL\n  struct pollfd pfd_read;\n  pfd_read.fd = sock;\n  pfd_read.events = POLLIN | POLLOUT;\n\n  auto timeout = static_cast<int>(sec * 1000 + usec / 1000);\n\n  auto poll_res = handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); });\n\n  if (poll_res == 0) { return Error::ConnectionTimeout; }\n\n  if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {\n    int error = 0;\n    socklen_t len = sizeof(error);\n    auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,\n                          reinterpret_cast<char *>(&error), &len);\n    auto successful = res >= 0 && !error;\n    return successful ? Error::Success : Error::Connection;\n  }\n\n  return Error::Connection;\n#else\n#ifndef _WIN32\n  if (sock >= FD_SETSIZE) { return Error::Connection; }\n#endif\n\n  fd_set fdsr;\n  FD_ZERO(&fdsr);\n  FD_SET(sock, &fdsr);\n\n  auto fdsw = fdsr;\n  auto fdse = fdsr;\n\n  timeval tv;\n  tv.tv_sec = static_cast<long>(sec);\n  tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);\n\n  auto ret = handle_EINTR([&]() {\n    return select(static_cast<int>(sock + 1), &fdsr, &fdsw, &fdse, &tv);\n  });\n\n  if (ret == 0) { return Error::ConnectionTimeout; }\n\n  if (ret > 0 && (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) {\n    int error = 0;\n    socklen_t len = sizeof(error);\n    auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,\n                          reinterpret_cast<char *>(&error), &len);\n    auto successful = res >= 0 && !error;\n    return successful ? Error::Success : Error::Connection;\n  }\n  return Error::Connection;\n#endif\n}\n\ninline bool is_socket_alive(socket_t sock) {\n  const auto val = detail::select_read(sock, 0, 0);\n  if (val == 0) {\n    return true;\n  } else if (val < 0 && errno == EBADF) {\n    return false;\n  }\n  char buf[1];\n  return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;\n}\n\nclass SocketStream : public Stream {\npublic:\n  SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,\n               time_t write_timeout_sec, time_t write_timeout_usec);\n  ~SocketStream() override;\n\n  bool is_readable() const override;\n  bool is_writable() const override;\n  ssize_t read(char *ptr, size_t size) override;\n  ssize_t write(const char *ptr, size_t size) override;\n  void get_remote_ip_and_port(std::string &ip, int &port) const override;\n  void get_local_ip_and_port(std::string &ip, int &port) const override;\n  socket_t socket() const override;\n\nprivate:\n  socket_t sock_;\n  time_t read_timeout_sec_;\n  time_t read_timeout_usec_;\n  time_t write_timeout_sec_;\n  time_t write_timeout_usec_;\n\n  std::vector<char> read_buff_;\n  size_t read_buff_off_ = 0;\n  size_t read_buff_content_size_ = 0;\n\n  static const size_t read_buff_size_ = 1024 * 4;\n};\n\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\nclass SSLSocketStream : public Stream {\npublic:\n  SSLSocketStream(socket_t sock, SSL *ssl, time_t read_timeout_sec,\n                  time_t read_timeout_usec, time_t write_timeout_sec,\n                  time_t write_timeout_usec);\n  ~SSLSocketStream() override;\n\n  bool is_readable() const override;\n  bool is_writable() const override;\n  ssize_t read(char *ptr, size_t size) override;\n  ssize_t write(const char *ptr, size_t size) override;\n  void get_remote_ip_and_port(std::string &ip, int &port) const override;\n  void get_local_ip_and_port(std::string &ip, int &port) const override;\n  socket_t socket() const override;\n\nprivate:\n  socket_t sock_;\n  SSL *ssl_;\n  time_t read_timeout_sec_;\n  time_t read_timeout_usec_;\n  time_t write_timeout_sec_;\n  time_t write_timeout_usec_;\n};\n#endif\n\ninline bool keep_alive(socket_t sock, time_t keep_alive_timeout_sec) {\n  using namespace std::chrono;\n  auto start = steady_clock::now();\n  while (true) {\n    auto val = select_read(sock, 0, 10000);\n    if (val < 0) {\n      return false;\n    } else if (val == 0) {\n      auto current = steady_clock::now();\n      auto duration = duration_cast<milliseconds>(current - start);\n      auto timeout = keep_alive_timeout_sec * 1000;\n      if (duration.count() > timeout) { return false; }\n      std::this_thread::sleep_for(std::chrono::milliseconds(1));\n    } else {\n      return true;\n    }\n  }\n}\n\ntemplate <typename T>\ninline bool\nprocess_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,\n                           size_t keep_alive_max_count,\n                           time_t keep_alive_timeout_sec, T callback) {\n  assert(keep_alive_max_count > 0);\n  auto ret = false;\n  auto count = keep_alive_max_count;\n  while (svr_sock != INVALID_SOCKET && count > 0 &&\n         keep_alive(sock, keep_alive_timeout_sec)) {\n    auto close_connection = count == 1;\n    auto connection_closed = false;\n    ret = callback(close_connection, connection_closed);\n    if (!ret || connection_closed) { break; }\n    count--;\n  }\n  return ret;\n}\n\ntemplate <typename T>\ninline bool\nprocess_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,\n                      size_t keep_alive_max_count,\n                      time_t keep_alive_timeout_sec, time_t read_timeout_sec,\n                      time_t read_timeout_usec, time_t write_timeout_sec,\n                      time_t write_timeout_usec, T callback) {\n  return process_server_socket_core(\n      svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,\n      [&](bool close_connection, bool &connection_closed) {\n        SocketStream strm(sock, read_timeout_sec, read_timeout_usec,\n                          write_timeout_sec, write_timeout_usec);\n        return callback(strm, close_connection, connection_closed);\n      });\n}\n\ninline bool process_client_socket(socket_t sock, time_t read_timeout_sec,\n                                  time_t read_timeout_usec,\n                                  time_t write_timeout_sec,\n                                  time_t write_timeout_usec,\n                                  std::function<bool(Stream &)> callback) {\n  SocketStream strm(sock, read_timeout_sec, read_timeout_usec,\n                    write_timeout_sec, write_timeout_usec);\n  return callback(strm);\n}\n\ninline int shutdown_socket(socket_t sock) {\n#ifdef _WIN32\n  return shutdown(sock, SD_BOTH);\n#else\n  return shutdown(sock, SHUT_RDWR);\n#endif\n}\n\ntemplate <typename BindOrConnect>\nsocket_t create_socket(const std::string &host, const std::string &ip, int port,\n                       int address_family, int socket_flags, bool tcp_nodelay,\n                       SocketOptions socket_options,\n                       BindOrConnect bind_or_connect) {\n  // Get address info\n  const char *node = nullptr;\n  struct addrinfo hints;\n  struct addrinfo *result;\n\n  memset(&hints, 0, sizeof(struct addrinfo));\n  hints.ai_socktype = SOCK_STREAM;\n  hints.ai_protocol = 0;\n\n  if (!ip.empty()) {\n    node = ip.c_str();\n    // Ask getaddrinfo to convert IP in c-string to address\n    hints.ai_family = AF_UNSPEC;\n    hints.ai_flags = AI_NUMERICHOST;\n  } else {\n    if (!host.empty()) { node = host.c_str(); }\n    hints.ai_family = address_family;\n    hints.ai_flags = socket_flags;\n  }\n\n#ifndef _WIN32\n  if (hints.ai_family == AF_UNIX) {\n    const auto addrlen = host.length();\n    if (addrlen > sizeof(sockaddr_un::sun_path)) return INVALID_SOCKET;\n\n    auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);\n    if (sock != INVALID_SOCKET) {\n      sockaddr_un addr{};\n      addr.sun_family = AF_UNIX;\n      std::copy(host.begin(), host.end(), addr.sun_path);\n\n      hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);\n      hints.ai_addrlen = static_cast<socklen_t>(\n          sizeof(addr) - sizeof(addr.sun_path) + addrlen);\n\n      fcntl(sock, F_SETFD, FD_CLOEXEC);\n      if (socket_options) { socket_options(sock); }\n\n      if (!bind_or_connect(sock, hints)) {\n        close_socket(sock);\n        sock = INVALID_SOCKET;\n      }\n    }\n    return sock;\n  }\n#endif\n\n  auto service = std::to_string(port);\n\n  if (getaddrinfo(node, service.c_str(), &hints, &result)) {\n#if defined __linux__ && !defined __ANDROID__\n    res_init();\n#endif\n    return INVALID_SOCKET;\n  }\n\n  for (auto rp = result; rp; rp = rp->ai_next) {\n    // Create a socket\n#ifdef _WIN32\n    auto sock =\n        WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,\n                   WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);\n    /**\n     * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1\n     * and above the socket creation fails on older Windows Systems.\n     *\n     * Let's try to create a socket the old way in this case.\n     *\n     * Reference:\n     * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa\n     *\n     * WSA_FLAG_NO_HANDLE_INHERIT:\n     * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with\n     * SP1, and later\n     *\n     */\n    if (sock == INVALID_SOCKET) {\n      sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);\n    }\n#else\n    auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);\n#endif\n    if (sock == INVALID_SOCKET) { continue; }\n\n#ifndef _WIN32\n    if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {\n      close_socket(sock);\n      continue;\n    }\n#endif\n\n    if (tcp_nodelay) {\n      int yes = 1;\n      setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char *>(&yes),\n                 sizeof(yes));\n    }\n\n    if (socket_options) { socket_options(sock); }\n\n    if (rp->ai_family == AF_INET6) {\n      int no = 0;\n      setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<char *>(&no),\n                 sizeof(no));\n    }\n\n    // bind or connect\n    if (bind_or_connect(sock, *rp)) {\n      freeaddrinfo(result);\n      return sock;\n    }\n\n    close_socket(sock);\n  }\n\n  freeaddrinfo(result);\n  return INVALID_SOCKET;\n}\n\ninline void set_nonblocking(socket_t sock, bool nonblocking) {\n#ifdef _WIN32\n  auto flags = nonblocking ? 1UL : 0UL;\n  ioctlsocket(sock, FIONBIO, &flags);\n#else\n  auto flags = fcntl(sock, F_GETFL, 0);\n  fcntl(sock, F_SETFL,\n        nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));\n#endif\n}\n\ninline bool is_connection_error() {\n#ifdef _WIN32\n  return WSAGetLastError() != WSAEWOULDBLOCK;\n#else\n  return errno != EINPROGRESS;\n#endif\n}\n\ninline bool bind_ip_address(socket_t sock, const std::string &host) {\n  struct addrinfo hints;\n  struct addrinfo *result;\n\n  memset(&hints, 0, sizeof(struct addrinfo));\n  hints.ai_family = AF_UNSPEC;\n  hints.ai_socktype = SOCK_STREAM;\n  hints.ai_protocol = 0;\n\n  if (getaddrinfo(host.c_str(), \"0\", &hints, &result)) { return false; }\n\n  auto ret = false;\n  for (auto rp = result; rp; rp = rp->ai_next) {\n    const auto &ai = *rp;\n    if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {\n      ret = true;\n      break;\n    }\n  }\n\n  freeaddrinfo(result);\n  return ret;\n}\n\n#if !defined _WIN32 && !defined ANDROID && !defined _AIX\n#define USE_IF2IP\n#endif\n\n#ifdef USE_IF2IP\ninline std::string if2ip(int address_family, const std::string &ifn) {\n  struct ifaddrs *ifap;\n  getifaddrs(&ifap);\n  std::string addr_candidate;\n  for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {\n    if (ifa->ifa_addr && ifn == ifa->ifa_name &&\n        (AF_UNSPEC == address_family ||\n         ifa->ifa_addr->sa_family == address_family)) {\n      if (ifa->ifa_addr->sa_family == AF_INET) {\n        auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);\n        char buf[INET_ADDRSTRLEN];\n        if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {\n          freeifaddrs(ifap);\n          return std::string(buf, INET_ADDRSTRLEN);\n        }\n      } else if (ifa->ifa_addr->sa_family == AF_INET6) {\n        auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);\n        if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {\n          char buf[INET6_ADDRSTRLEN] = {};\n          if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {\n            // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL\n            auto s6_addr_head = sa->sin6_addr.s6_addr[0];\n            if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {\n              addr_candidate = std::string(buf, INET6_ADDRSTRLEN);\n            } else {\n              freeifaddrs(ifap);\n              return std::string(buf, INET6_ADDRSTRLEN);\n            }\n          }\n        }\n      }\n    }\n  }\n  freeifaddrs(ifap);\n  return addr_candidate;\n}\n#endif\n\ninline socket_t create_client_socket(\n    const std::string &host, const std::string &ip, int port,\n    int address_family, bool tcp_nodelay, SocketOptions socket_options,\n    time_t connection_timeout_sec, time_t connection_timeout_usec,\n    time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,\n    time_t write_timeout_usec, const std::string &intf, Error &error) {\n  auto sock = create_socket(\n      host, ip, port, address_family, 0, tcp_nodelay, std::move(socket_options),\n      [&](socket_t sock2, struct addrinfo &ai) -> bool {\n        if (!intf.empty()) {\n#ifdef USE_IF2IP\n          auto ip_from_if = if2ip(address_family, intf);\n          if (ip_from_if.empty()) { ip_from_if = intf; }\n          if (!bind_ip_address(sock2, ip_from_if.c_str())) {\n            error = Error::BindIPAddress;\n            return false;\n          }\n#endif\n        }\n\n        set_nonblocking(sock2, true);\n\n        auto ret =\n            ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));\n\n        if (ret < 0) {\n          if (is_connection_error()) {\n            error = Error::Connection;\n            return false;\n          }\n          error = wait_until_socket_is_ready(sock2, connection_timeout_sec,\n                                             connection_timeout_usec);\n          if (error != Error::Success) { return false; }\n        }\n\n        set_nonblocking(sock2, false);\n\n        {\n#ifdef _WIN32\n          auto timeout = static_cast<uint32_t>(read_timeout_sec * 1000 +\n                                               read_timeout_usec / 1000);\n          setsockopt(sock2, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,\n                     sizeof(timeout));\n#else\n          timeval tv;\n          tv.tv_sec = static_cast<long>(read_timeout_sec);\n          tv.tv_usec = static_cast<decltype(tv.tv_usec)>(read_timeout_usec);\n          setsockopt(sock2, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv));\n#endif\n        }\n        {\n\n#ifdef _WIN32\n          auto timeout = static_cast<uint32_t>(write_timeout_sec * 1000 +\n                                               write_timeout_usec / 1000);\n          setsockopt(sock2, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout,\n                     sizeof(timeout));\n#else\n          timeval tv;\n          tv.tv_sec = static_cast<long>(write_timeout_sec);\n          tv.tv_usec = static_cast<decltype(tv.tv_usec)>(write_timeout_usec);\n          setsockopt(sock2, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv));\n#endif\n        }\n\n        error = Error::Success;\n        return true;\n      });\n\n  if (sock != INVALID_SOCKET) {\n    error = Error::Success;\n  } else {\n    if (error == Error::Success) { error = Error::Connection; }\n  }\n\n  return sock;\n}\n\ninline bool get_ip_and_port(const struct sockaddr_storage &addr,\n                            socklen_t addr_len, std::string &ip, int &port) {\n  if (addr.ss_family == AF_INET) {\n    port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);\n  } else if (addr.ss_family == AF_INET6) {\n    port =\n        ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);\n  } else {\n    return false;\n  }\n\n  std::array<char, NI_MAXHOST> ipstr{};\n  if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,\n                  ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,\n                  0, NI_NUMERICHOST)) {\n    return false;\n  }\n\n  ip = ipstr.data();\n  return true;\n}\n\ninline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {\n  struct sockaddr_storage addr;\n  socklen_t addr_len = sizeof(addr);\n  if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),\n                   &addr_len)) {\n    get_ip_and_port(addr, addr_len, ip, port);\n  }\n}\n\ninline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {\n  struct sockaddr_storage addr;\n  socklen_t addr_len = sizeof(addr);\n\n  if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),\n                   &addr_len)) {\n#ifndef _WIN32\n    if (addr.ss_family == AF_UNIX) {\n#if defined(__linux__)\n      struct ucred ucred;\n      socklen_t len = sizeof(ucred);\n      if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {\n        port = ucred.pid;\n      }\n#elif defined(SOL_LOCAL) && defined(SO_PEERPID) // __APPLE__\n      pid_t pid;\n      socklen_t len = sizeof(pid);\n      if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {\n        port = pid;\n      }\n#endif\n      return;\n    }\n#endif\n    get_ip_and_port(addr, addr_len, ip, port);\n  }\n}\n\ninline constexpr unsigned int str2tag_core(const char *s, size_t l,\n                                           unsigned int h) {\n  return (l == 0)\n             ? h\n             : str2tag_core(\n                   s + 1, l - 1,\n                   // Unsets the 6 high bits of h, therefore no overflow happens\n                   (((std::numeric_limits<unsigned int>::max)() >> 6) &\n                    h * 33) ^\n                       static_cast<unsigned char>(*s));\n}\n\ninline unsigned int str2tag(const std::string &s) {\n  return str2tag_core(s.data(), s.size(), 0);\n}\n\nnamespace udl {\n\ninline constexpr unsigned int operator\"\" _t(const char *s, size_t l) {\n  return str2tag_core(s, l, 0);\n}\n\n} // namespace udl\n\ninline const char *\nfind_content_type(const std::string &path,\n                  const std::map<std::string, std::string> &user_data) {\n  auto ext = file_extension(path);\n\n  auto it = user_data.find(ext);\n  if (it != user_data.end()) { return it->second.c_str(); }\n\n  using udl::operator\"\"_t;\n\n  switch (str2tag(ext)) {\n  default: return nullptr;\n  case \"css\"_t: return \"text/css\";\n  case \"csv\"_t: return \"text/csv\";\n  case \"htm\"_t:\n  case \"html\"_t: return \"text/html\";\n  case \"js\"_t:\n  case \"mjs\"_t: return \"text/javascript\";\n  case \"txt\"_t: return \"text/plain\";\n  case \"vtt\"_t: return \"text/vtt\";\n\n  case \"apng\"_t: return \"image/apng\";\n  case \"avif\"_t: return \"image/avif\";\n  case \"bmp\"_t: return \"image/bmp\";\n  case \"gif\"_t: return \"image/gif\";\n  case \"png\"_t: return \"image/png\";\n  case \"svg\"_t: return \"image/svg+xml\";\n  case \"webp\"_t: return \"image/webp\";\n  case \"ico\"_t: return \"image/x-icon\";\n  case \"tif\"_t: return \"image/tiff\";\n  case \"tiff\"_t: return \"image/tiff\";\n  case \"jpg\"_t:\n  case \"jpeg\"_t: return \"image/jpeg\";\n\n  case \"mp4\"_t: return \"video/mp4\";\n  case \"mpeg\"_t: return \"video/mpeg\";\n  case \"webm\"_t: return \"video/webm\";\n\n  case \"mp3\"_t: return \"audio/mp3\";\n  case \"mpga\"_t: return \"audio/mpeg\";\n  case \"weba\"_t: return \"audio/webm\";\n  case \"wav\"_t: return \"audio/wave\";\n\n  case \"otf\"_t: return \"font/otf\";\n  case \"ttf\"_t: return \"font/ttf\";\n  case \"woff\"_t: return \"font/woff\";\n  case \"woff2\"_t: return \"font/woff2\";\n\n  case \"7z\"_t: return \"application/x-7z-compressed\";\n  case \"atom\"_t: return \"application/atom+xml\";\n  case \"pdf\"_t: return \"application/pdf\";\n  case \"json\"_t: return \"application/json\";\n  case \"rss\"_t: return \"application/rss+xml\";\n  case \"tar\"_t: return \"application/x-tar\";\n  case \"xht\"_t:\n  case \"xhtml\"_t: return \"application/xhtml+xml\";\n  case \"xslt\"_t: return \"application/xslt+xml\";\n  case \"xml\"_t: return \"application/xml\";\n  case \"gz\"_t: return \"application/gzip\";\n  case \"zip\"_t: return \"application/zip\";\n  case \"wasm\"_t: return \"application/wasm\";\n  }\n}\n\ninline const char *status_message(int status) {\n  switch (status) {\n  case 100: return \"Continue\";\n  case 101: return \"Switching Protocol\";\n  case 102: return \"Processing\";\n  case 103: return \"Early Hints\";\n  case 200: return \"OK\";\n  case 201: return \"Created\";\n  case 202: return \"Accepted\";\n  case 203: return \"Non-Authoritative Information\";\n  case 204: return \"No Content\";\n  case 205: return \"Reset Content\";\n  case 206: return \"Partial Content\";\n  case 207: return \"Multi-Status\";\n  case 208: return \"Already Reported\";\n  case 226: return \"IM Used\";\n  case 300: return \"Multiple Choice\";\n  case 301: return \"Moved Permanently\";\n  case 302: return \"Found\";\n  case 303: return \"See Other\";\n  case 304: return \"Not Modified\";\n  case 305: return \"Use Proxy\";\n  case 306: return \"unused\";\n  case 307: return \"Temporary Redirect\";\n  case 308: return \"Permanent Redirect\";\n  case 400: return \"Bad Request\";\n  case 401: return \"Unauthorized\";\n  case 402: return \"Payment Required\";\n  case 403: return \"Forbidden\";\n  case 404: return \"Not Found\";\n  case 405: return \"Method Not Allowed\";\n  case 406: return \"Not Acceptable\";\n  case 407: return \"Proxy Authentication Required\";\n  case 408: return \"Request Timeout\";\n  case 409: return \"Conflict\";\n  case 410: return \"Gone\";\n  case 411: return \"Length Required\";\n  case 412: return \"Precondition Failed\";\n  case 413: return \"Payload Too Large\";\n  case 414: return \"URI Too Long\";\n  case 415: return \"Unsupported Media Type\";\n  case 416: return \"Range Not Satisfiable\";\n  case 417: return \"Expectation Failed\";\n  case 418: return \"I'm a teapot\";\n  case 421: return \"Misdirected Request\";\n  case 422: return \"Unprocessable Entity\";\n  case 423: return \"Locked\";\n  case 424: return \"Failed Dependency\";\n  case 425: return \"Too Early\";\n  case 426: return \"Upgrade Required\";\n  case 428: return \"Precondition Required\";\n  case 429: return \"Too Many Requests\";\n  case 431: return \"Request Header Fields Too Large\";\n  case 451: return \"Unavailable For Legal Reasons\";\n  case 501: return \"Not Implemented\";\n  case 502: return \"Bad Gateway\";\n  case 503: return \"Service Unavailable\";\n  case 504: return \"Gateway Timeout\";\n  case 505: return \"HTTP Version Not Supported\";\n  case 506: return \"Variant Also Negotiates\";\n  case 507: return \"Insufficient Storage\";\n  case 508: return \"Loop Detected\";\n  case 510: return \"Not Extended\";\n  case 511: return \"Network Authentication Required\";\n\n  default:\n  case 500: return \"Internal Server Error\";\n  }\n}\n\ninline bool can_compress_content_type(const std::string &content_type) {\n  using udl::operator\"\"_t;\n\n  auto tag = str2tag(content_type);\n\n  switch (tag) {\n  case \"image/svg+xml\"_t:\n  case \"application/javascript\"_t:\n  case \"application/json\"_t:\n  case \"application/xml\"_t:\n  case \"application/protobuf\"_t:\n  case \"application/xhtml+xml\"_t: return true;\n\n  default:\n    return !content_type.rfind(\"text/\", 0) && tag != \"text/event-stream\"_t;\n  }\n}\n\ninline EncodingType encoding_type(const Request &req, const Response &res) {\n  auto ret =\n      detail::can_compress_content_type(res.get_header_value(\"Content-Type\"));\n  if (!ret) { return EncodingType::None; }\n\n  const auto &s = req.get_header_value(\"Accept-Encoding\");\n  (void)(s);\n\n#ifdef CPPHTTPLIB_BROTLI_SUPPORT\n  // TODO: 'Accept-Encoding' has br, not br;q=0\n  ret = s.find(\"br\") != std::string::npos;\n  if (ret) { return EncodingType::Brotli; }\n#endif\n\n#ifdef CPPHTTPLIB_ZLIB_SUPPORT\n  // TODO: 'Accept-Encoding' has gzip, not gzip;q=0\n  ret = s.find(\"gzip\") != std::string::npos;\n  if (ret) { return EncodingType::Gzip; }\n#endif\n\n  return EncodingType::None;\n}\n\ninline bool nocompressor::compress(const char *data, size_t data_length,\n                                   bool /*last*/, Callback callback) {\n  if (!data_length) { return true; }\n  return callback(data, data_length);\n}\n\n#ifdef CPPHTTPLIB_ZLIB_SUPPORT\ninline gzip_compressor::gzip_compressor() {\n  std::memset(&strm_, 0, sizeof(strm_));\n  strm_.zalloc = Z_NULL;\n  strm_.zfree = Z_NULL;\n  strm_.opaque = Z_NULL;\n\n  is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,\n                           Z_DEFAULT_STRATEGY) == Z_OK;\n}\n\ninline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }\n\ninline bool gzip_compressor::compress(const char *data, size_t data_length,\n                                      bool last, Callback callback) {\n  assert(is_valid_);\n\n  do {\n    constexpr size_t max_avail_in =\n        (std::numeric_limits<decltype(strm_.avail_in)>::max)();\n\n    strm_.avail_in = static_cast<decltype(strm_.avail_in)>(\n        (std::min)(data_length, max_avail_in));\n    strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));\n\n    data_length -= strm_.avail_in;\n    data += strm_.avail_in;\n\n    auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;\n    int ret = Z_OK;\n\n    std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};\n    do {\n      strm_.avail_out = static_cast<uInt>(buff.size());\n      strm_.next_out = reinterpret_cast<Bytef *>(buff.data());\n\n      ret = deflate(&strm_, flush);\n      if (ret == Z_STREAM_ERROR) { return false; }\n\n      if (!callback(buff.data(), buff.size() - strm_.avail_out)) {\n        return false;\n      }\n    } while (strm_.avail_out == 0);\n\n    assert((flush == Z_FINISH && ret == Z_STREAM_END) ||\n           (flush == Z_NO_FLUSH && ret == Z_OK));\n    assert(strm_.avail_in == 0);\n  } while (data_length > 0);\n\n  return true;\n}\n\ninline gzip_decompressor::gzip_decompressor() {\n  std::memset(&strm_, 0, sizeof(strm_));\n  strm_.zalloc = Z_NULL;\n  strm_.zfree = Z_NULL;\n  strm_.opaque = Z_NULL;\n\n  // 15 is the value of wbits, which should be at the maximum possible value\n  // to ensure that any gzip stream can be decoded. The offset of 32 specifies\n  // that the stream type should be automatically detected either gzip or\n  // deflate.\n  is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;\n}\n\ninline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }\n\ninline bool gzip_decompressor::is_valid() const { return is_valid_; }\n\ninline bool gzip_decompressor::decompress(const char *data, size_t data_length,\n                                          Callback callback) {\n  assert(is_valid_);\n\n  int ret = Z_OK;\n\n  do {\n    constexpr size_t max_avail_in =\n        (std::numeric_limits<decltype(strm_.avail_in)>::max)();\n\n    strm_.avail_in = static_cast<decltype(strm_.avail_in)>(\n        (std::min)(data_length, max_avail_in));\n    strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));\n\n    data_length -= strm_.avail_in;\n    data += strm_.avail_in;\n\n    std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};\n    while (strm_.avail_in > 0) {\n      strm_.avail_out = static_cast<uInt>(buff.size());\n      strm_.next_out = reinterpret_cast<Bytef *>(buff.data());\n\n      auto prev_avail_in = strm_.avail_in;\n\n      ret = inflate(&strm_, Z_NO_FLUSH);\n\n      if (prev_avail_in - strm_.avail_in == 0) { return false; }\n\n      assert(ret != Z_STREAM_ERROR);\n      switch (ret) {\n      case Z_NEED_DICT:\n      case Z_DATA_ERROR:\n      case Z_MEM_ERROR: inflateEnd(&strm_); return false;\n      }\n\n      if (!callback(buff.data(), buff.size() - strm_.avail_out)) {\n        return false;\n      }\n    }\n\n    if (ret != Z_OK && ret != Z_STREAM_END) return false;\n\n  } while (data_length > 0);\n\n  return true;\n}\n#endif\n\n#ifdef CPPHTTPLIB_BROTLI_SUPPORT\ninline brotli_compressor::brotli_compressor() {\n  state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);\n}\n\ninline brotli_compressor::~brotli_compressor() {\n  BrotliEncoderDestroyInstance(state_);\n}\n\ninline bool brotli_compressor::compress(const char *data, size_t data_length,\n                                        bool last, Callback callback) {\n  std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};\n\n  auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;\n  auto available_in = data_length;\n  auto next_in = reinterpret_cast<const uint8_t *>(data);\n\n  for (;;) {\n    if (last) {\n      if (BrotliEncoderIsFinished(state_)) { break; }\n    } else {\n      if (!available_in) { break; }\n    }\n\n    auto available_out = buff.size();\n    auto next_out = buff.data();\n\n    if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,\n                                     &available_out, &next_out, nullptr)) {\n      return false;\n    }\n\n    auto output_bytes = buff.size() - available_out;\n    if (output_bytes) {\n      callback(reinterpret_cast<const char *>(buff.data()), output_bytes);\n    }\n  }\n\n  return true;\n}\n\ninline brotli_decompressor::brotli_decompressor() {\n  decoder_s = BrotliDecoderCreateInstance(0, 0, 0);\n  decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT\n                        : BROTLI_DECODER_RESULT_ERROR;\n}\n\ninline brotli_decompressor::~brotli_decompressor() {\n  if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }\n}\n\ninline bool brotli_decompressor::is_valid() const { return decoder_s; }\n\ninline bool brotli_decompressor::decompress(const char *data,\n                                            size_t data_length,\n                                            Callback callback) {\n  if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||\n      decoder_r == BROTLI_DECODER_RESULT_ERROR) {\n    return 0;\n  }\n\n  const uint8_t *next_in = (const uint8_t *)data;\n  size_t avail_in = data_length;\n  size_t total_out;\n\n  decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;\n\n  std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};\n  while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {\n    char *next_out = buff.data();\n    size_t avail_out = buff.size();\n\n    decoder_r = BrotliDecoderDecompressStream(\n        decoder_s, &avail_in, &next_in, &avail_out,\n        reinterpret_cast<uint8_t **>(&next_out), &total_out);\n\n    if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }\n\n    if (!callback(buff.data(), buff.size() - avail_out)) { return false; }\n  }\n\n  return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||\n         decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;\n}\n#endif\n\ninline bool has_header(const Headers &headers, const std::string &key) {\n  return headers.find(key) != headers.end();\n}\n\ninline const char *get_header_value(const Headers &headers,\n                                    const std::string &key, size_t id,\n                                    const char *def) {\n  auto rng = headers.equal_range(key);\n  auto it = rng.first;\n  std::advance(it, static_cast<ssize_t>(id));\n  if (it != rng.second) { return it->second.c_str(); }\n  return def;\n}\n\ninline bool compare_case_ignore(const std::string &a, const std::string &b) {\n  if (a.size() != b.size()) { return false; }\n  for (size_t i = 0; i < b.size(); i++) {\n    if (::tolower(a[i]) != ::tolower(b[i])) { return false; }\n  }\n  return true;\n}\n\ntemplate <typename T>\ninline bool parse_header(const char *beg, const char *end, T fn) {\n  // Skip trailing spaces and tabs.\n  while (beg < end && is_space_or_tab(end[-1])) {\n    end--;\n  }\n\n  auto p = beg;\n  while (p < end && *p != ':') {\n    p++;\n  }\n\n  if (p == end) { return false; }\n\n  auto key_end = p;\n\n  if (*p++ != ':') { return false; }\n\n  while (p < end && is_space_or_tab(*p)) {\n    p++;\n  }\n\n  if (p < end) {\n    auto key = std::string(beg, key_end);\n    auto val = compare_case_ignore(key, \"Location\")\n                   ? std::string(p, end)\n                   : decode_url(std::string(p, end), false);\n    fn(std::move(key), std::move(val));\n    return true;\n  }\n\n  return false;\n}\n\ninline bool read_headers(Stream &strm, Headers &headers) {\n  const auto bufsiz = 2048;\n  char buf[bufsiz];\n  stream_line_reader line_reader(strm, buf, bufsiz);\n\n  for (;;) {\n    if (!line_reader.getline()) { return false; }\n\n    // Check if the line ends with CRLF.\n    auto line_terminator_len = 2;\n    if (line_reader.end_with_crlf()) {\n      // Blank line indicates end of headers.\n      if (line_reader.size() == 2) { break; }\n#ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR\n    } else {\n      // Blank line indicates end of headers.\n      if (line_reader.size() == 1) { break; }\n      line_terminator_len = 1;\n    }\n#else\n    } else {\n      continue; // Skip invalid line.\n    }\n#endif\n\n    if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }\n\n    // Exclude line terminator\n    auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;\n\n    parse_header(line_reader.ptr(), end,\n                 [&](std::string &&key, std::string &&val) {\n                   headers.emplace(std::move(key), std::move(val));\n                 });\n  }\n\n  return true;\n}\n\ninline bool read_content_with_length(Stream &strm, uint64_t len,\n                                     Progress progress,\n                                     ContentReceiverWithProgress out) {\n  char buf[CPPHTTPLIB_RECV_BUFSIZ];\n\n  uint64_t r = 0;\n  while (r < len) {\n    auto read_len = static_cast<size_t>(len - r);\n    auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));\n    if (n <= 0) { return false; }\n\n    if (!out(buf, static_cast<size_t>(n), r, len)) { return false; }\n    r += static_cast<uint64_t>(n);\n\n    if (progress) {\n      if (!progress(r, len)) { return false; }\n    }\n  }\n\n  return true;\n}\n\ninline void skip_content_with_length(Stream &strm, uint64_t len) {\n  char buf[CPPHTTPLIB_RECV_BUFSIZ];\n  uint64_t r = 0;\n  while (r < len) {\n    auto read_len = static_cast<size_t>(len - r);\n    auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));\n    if (n <= 0) { return; }\n    r += static_cast<uint64_t>(n);\n  }\n}\n\ninline bool read_content_without_length(Stream &strm,\n                                        ContentReceiverWithProgress out) {\n  char buf[CPPHTTPLIB_RECV_BUFSIZ];\n  uint64_t r = 0;\n  for (;;) {\n    auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);\n    if (n < 0) {\n      return false;\n    } else if (n == 0) {\n      return true;\n    }\n\n    if (!out(buf, static_cast<size_t>(n), r, 0)) { return false; }\n    r += static_cast<uint64_t>(n);\n  }\n\n  return true;\n}\n\ntemplate <typename T>\ninline bool read_content_chunked(Stream &strm, T &x,\n                                 ContentReceiverWithProgress out) {\n  const auto bufsiz = 16;\n  char buf[bufsiz];\n\n  stream_line_reader line_reader(strm, buf, bufsiz);\n\n  if (!line_reader.getline()) { return false; }\n\n  unsigned long chunk_len;\n  while (true) {\n    char *end_ptr;\n\n    chunk_len = std::strtoul(line_reader.ptr(), &end_ptr, 16);\n\n    if (end_ptr == line_reader.ptr()) { return false; }\n    if (chunk_len == ULONG_MAX) { return false; }\n\n    if (chunk_len == 0) { break; }\n\n    if (!read_content_with_length(strm, chunk_len, nullptr, out)) {\n      return false;\n    }\n\n    if (!line_reader.getline()) { return false; }\n\n    if (strcmp(line_reader.ptr(), \"\\r\\n\")) { return false; }\n\n    if (!line_reader.getline()) { return false; }\n  }\n\n  assert(chunk_len == 0);\n\n  // Trailer\n  if (!line_reader.getline()) { return false; }\n\n  while (strcmp(line_reader.ptr(), \"\\r\\n\")) {\n    if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }\n\n    // Exclude line terminator\n    constexpr auto line_terminator_len = 2;\n    auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;\n\n    parse_header(line_reader.ptr(), end,\n                 [&](std::string &&key, std::string &&val) {\n                   x.headers.emplace(std::move(key), std::move(val));\n                 });\n\n    if (!line_reader.getline()) { return false; }\n  }\n\n  return true;\n}\n\ninline bool is_chunked_transfer_encoding(const Headers &headers) {\n  return !strcasecmp(get_header_value(headers, \"Transfer-Encoding\", 0, \"\"),\n                     \"chunked\");\n}\n\ntemplate <typename T, typename U>\nbool prepare_content_receiver(T &x, int &status,\n                              ContentReceiverWithProgress receiver,\n                              bool decompress, U callback) {\n  if (decompress) {\n    std::string encoding = x.get_header_value(\"Content-Encoding\");\n    std::unique_ptr<decompressor> decompressor;\n\n    if (encoding == \"gzip\" || encoding == \"deflate\") {\n#ifdef CPPHTTPLIB_ZLIB_SUPPORT\n      decompressor = detail::make_unique<gzip_decompressor>();\n#else\n      status = 415;\n      return false;\n#endif\n    } else if (encoding.find(\"br\") != std::string::npos) {\n#ifdef CPPHTTPLIB_BROTLI_SUPPORT\n      decompressor = detail::make_unique<brotli_decompressor>();\n#else\n      status = 415;\n      return false;\n#endif\n    }\n\n    if (decompressor) {\n      if (decompressor->is_valid()) {\n        ContentReceiverWithProgress out = [&](const char *buf, size_t n,\n                                              uint64_t off, uint64_t len) {\n          return decompressor->decompress(buf, n,\n                                          [&](const char *buf2, size_t n2) {\n                                            return receiver(buf2, n2, off, len);\n                                          });\n        };\n        return callback(std::move(out));\n      } else {\n        status = 500;\n        return false;\n      }\n    }\n  }\n\n  ContentReceiverWithProgress out = [&](const char *buf, size_t n, uint64_t off,\n                                        uint64_t len) {\n    return receiver(buf, n, off, len);\n  };\n  return callback(std::move(out));\n}\n\ntemplate <typename T>\nbool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,\n                  Progress progress, ContentReceiverWithProgress receiver,\n                  bool decompress) {\n  return prepare_content_receiver(\n      x, status, std::move(receiver), decompress,\n      [&](const ContentReceiverWithProgress &out) {\n        auto ret = true;\n        auto exceed_payload_max_length = false;\n\n        if (is_chunked_transfer_encoding(x.headers)) {\n          ret = read_content_chunked(strm, x, out);\n        } else if (!has_header(x.headers, \"Content-Length\")) {\n          ret = read_content_without_length(strm, out);\n        } else {\n          auto len = get_header_value<uint64_t>(x.headers, \"Content-Length\");\n          if (len > payload_max_length) {\n            exceed_payload_max_length = true;\n            skip_content_with_length(strm, len);\n            ret = false;\n          } else if (len > 0) {\n            ret = read_content_with_length(strm, len, std::move(progress), out);\n          }\n        }\n\n        if (!ret) { status = exceed_payload_max_length ? 413 : 400; }\n        return ret;\n      });\n} // namespace detail\n\ninline ssize_t write_headers(Stream &strm, const Headers &headers) {\n  ssize_t write_len = 0;\n  for (const auto &x : headers) {\n    auto len =\n        strm.write_format(\"%s: %s\\r\\n\", x.first.c_str(), x.second.c_str());\n    if (len < 0) { return len; }\n    write_len += len;\n  }\n  auto len = strm.write(\"\\r\\n\");\n  if (len < 0) { return len; }\n  write_len += len;\n  return write_len;\n}\n\ninline bool write_data(Stream &strm, const char *d, size_t l) {\n  size_t offset = 0;\n  while (offset < l) {\n    auto length = strm.write(d + offset, l - offset);\n    if (length < 0) { return false; }\n    offset += static_cast<size_t>(length);\n  }\n  return true;\n}\n\ntemplate <typename T>\ninline bool write_content(Stream &strm, const ContentProvider &content_provider,\n                          size_t offset, size_t length, T is_shutting_down,\n                          Error &error) {\n  size_t end_offset = offset + length;\n  auto ok = true;\n  DataSink data_sink;\n\n  data_sink.write = [&](const char *d, size_t l) -> bool {\n    if (ok) {\n      if (strm.is_writable() && write_data(strm, d, l)) {\n        offset += l;\n      } else {\n        ok = false;\n      }\n    }\n    return ok;\n  };\n\n  while (offset < end_offset && !is_shutting_down()) {\n    if (!strm.is_writable()) {\n      error = Error::Write;\n      return false;\n    } else if (!content_provider(offset, end_offset - offset, data_sink)) {\n      error = Error::Canceled;\n      return false;\n    } else if (!ok) {\n      error = Error::Write;\n      return false;\n    }\n  }\n\n  error = Error::Success;\n  return true;\n}\n\ntemplate <typename T>\ninline bool write_content(Stream &strm, const ContentProvider &content_provider,\n                          size_t offset, size_t length,\n                          const T &is_shutting_down) {\n  auto error = Error::Success;\n  return write_content(strm, content_provider, offset, length, is_shutting_down,\n                       error);\n}\n\ntemplate <typename T>\ninline bool\nwrite_content_without_length(Stream &strm,\n                             const ContentProvider &content_provider,\n                             const T &is_shutting_down) {\n  size_t offset = 0;\n  auto data_available = true;\n  auto ok = true;\n  DataSink data_sink;\n\n  data_sink.write = [&](const char *d, size_t l) -> bool {\n    if (ok) {\n      offset += l;\n      if (!strm.is_writable() || !write_data(strm, d, l)) { ok = false; }\n    }\n    return ok;\n  };\n\n  data_sink.done = [&](void) { data_available = false; };\n\n  while (data_available && !is_shutting_down()) {\n    if (!strm.is_writable()) {\n      return false;\n    } else if (!content_provider(offset, 0, data_sink)) {\n      return false;\n    } else if (!ok) {\n      return false;\n    }\n  }\n  return true;\n}\n\ntemplate <typename T, typename U>\ninline bool\nwrite_content_chunked(Stream &strm, const ContentProvider &content_provider,\n                      const T &is_shutting_down, U &compressor, Error &error) {\n  size_t offset = 0;\n  auto data_available = true;\n  auto ok = true;\n  DataSink data_sink;\n\n  data_sink.write = [&](const char *d, size_t l) -> bool {\n    if (ok) {\n      data_available = l > 0;\n      offset += l;\n\n      std::string payload;\n      if (compressor.compress(d, l, false,\n                              [&](const char *data, size_t data_len) {\n                                payload.append(data, data_len);\n                                return true;\n                              })) {\n        if (!payload.empty()) {\n          // Emit chunked response header and footer for each chunk\n          auto chunk =\n              from_i_to_hex(payload.size()) + \"\\r\\n\" + payload + \"\\r\\n\";\n          if (!strm.is_writable() ||\n              !write_data(strm, chunk.data(), chunk.size())) {\n            ok = false;\n          }\n        }\n      } else {\n        ok = false;\n      }\n    }\n    return ok;\n  };\n\n  auto done_with_trailer = [&](const Headers *trailer) {\n    if (!ok) { return; }\n\n    data_available = false;\n\n    std::string payload;\n    if (!compressor.compress(nullptr, 0, true,\n                             [&](const char *data, size_t data_len) {\n                               payload.append(data, data_len);\n                               return true;\n                             })) {\n      ok = false;\n      return;\n    }\n\n    if (!payload.empty()) {\n      // Emit chunked response header and footer for each chunk\n      auto chunk = from_i_to_hex(payload.size()) + \"\\r\\n\" + payload + \"\\r\\n\";\n      if (!strm.is_writable() ||\n          !write_data(strm, chunk.data(), chunk.size())) {\n        ok = false;\n        return;\n      }\n    }\n\n    static const std::string done_marker(\"0\\r\\n\");\n    if (!write_data(strm, done_marker.data(), done_marker.size())) {\n      ok = false;\n    }\n\n    // Trailer\n    if (trailer) {\n      for (const auto &kv : *trailer) {\n        std::string field_line = kv.first + \": \" + kv.second + \"\\r\\n\";\n        if (!write_data(strm, field_line.data(), field_line.size())) {\n          ok = false;\n        }\n      }\n    }\n\n    static const std::string crlf(\"\\r\\n\");\n    if (!write_data(strm, crlf.data(), crlf.size())) { ok = false; }\n  };\n\n  data_sink.done = [&](void) { done_with_trailer(nullptr); };\n\n  data_sink.done_with_trailer = [&](const Headers &trailer) {\n    done_with_trailer(&trailer);\n  };\n\n  while (data_available && !is_shutting_down()) {\n    if (!strm.is_writable()) {\n      error = Error::Write;\n      return false;\n    } else if (!content_provider(offset, 0, data_sink)) {\n      error = Error::Canceled;\n      return false;\n    } else if (!ok) {\n      error = Error::Write;\n      return false;\n    }\n  }\n\n  error = Error::Success;\n  return true;\n}\n\ntemplate <typename T, typename U>\ninline bool write_content_chunked(Stream &strm,\n                                  const ContentProvider &content_provider,\n                                  const T &is_shutting_down, U &compressor) {\n  auto error = Error::Success;\n  return write_content_chunked(strm, content_provider, is_shutting_down,\n                               compressor, error);\n}\n\ntemplate <typename T>\ninline bool redirect(T &cli, Request &req, Response &res,\n                     const std::string &path, const std::string &location,\n                     Error &error) {\n  Request new_req = req;\n  new_req.path = path;\n  new_req.redirect_count_ -= 1;\n\n  if (res.status == 303 && (req.method != \"GET\" && req.method != \"HEAD\")) {\n    new_req.method = \"GET\";\n    new_req.body.clear();\n    new_req.headers.clear();\n  }\n\n  Response new_res;\n\n  auto ret = cli.send(new_req, new_res, error);\n  if (ret) {\n    req = new_req;\n    res = new_res;\n    res.location = location;\n  }\n  return ret;\n}\n\ninline std::string params_to_query_str(const Params &params) {\n  std::string query;\n\n  for (auto it = params.begin(); it != params.end(); ++it) {\n    if (it != params.begin()) { query += \"&\"; }\n    query += it->first;\n    query += \"=\";\n    query += encode_query_param(it->second);\n  }\n  return query;\n}\n\ninline void parse_query_text(const std::string &s, Params &params) {\n  std::set<std::string> cache;\n  split(s.data(), s.data() + s.size(), '&', [&](const char *b, const char *e) {\n    std::string kv(b, e);\n    if (cache.find(kv) != cache.end()) { return; }\n    cache.insert(kv);\n\n    std::string key;\n    std::string val;\n    split(b, e, '=', [&](const char *b2, const char *e2) {\n      if (key.empty()) {\n        key.assign(b2, e2);\n      } else {\n        val.assign(b2, e2);\n      }\n    });\n\n    if (!key.empty()) {\n      params.emplace(decode_url(key, true), decode_url(val, true));\n    }\n  });\n}\n\ninline bool parse_multipart_boundary(const std::string &content_type,\n                                     std::string &boundary) {\n  auto boundary_keyword = \"boundary=\";\n  auto pos = content_type.find(boundary_keyword);\n  if (pos == std::string::npos) { return false; }\n  auto end = content_type.find(';', pos);\n  auto beg = pos + strlen(boundary_keyword);\n  boundary = content_type.substr(beg, end - beg);\n  if (boundary.length() >= 2 && boundary.front() == '\"' &&\n      boundary.back() == '\"') {\n    boundary = boundary.substr(1, boundary.size() - 2);\n  }\n  return !boundary.empty();\n}\n\n#ifdef CPPHTTPLIB_NO_EXCEPTIONS\ninline bool parse_range_header(const std::string &s, Ranges &ranges) {\n#else\ninline bool parse_range_header(const std::string &s, Ranges &ranges) try {\n#endif\n  static auto re_first_range = std::regex(R\"(bytes=(\\d*-\\d*(?:,\\s*\\d*-\\d*)*))\");\n  std::smatch m;\n  if (std::regex_match(s, m, re_first_range)) {\n    auto pos = static_cast<size_t>(m.position(1));\n    auto len = static_cast<size_t>(m.length(1));\n    bool all_valid_ranges = true;\n    split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {\n      if (!all_valid_ranges) return;\n      static auto re_another_range = std::regex(R\"(\\s*(\\d*)-(\\d*))\");\n      std::cmatch cm;\n      if (std::regex_match(b, e, cm, re_another_range)) {\n        ssize_t first = -1;\n        if (!cm.str(1).empty()) {\n          first = static_cast<ssize_t>(std::stoll(cm.str(1)));\n        }\n\n        ssize_t last = -1;\n        if (!cm.str(2).empty()) {\n          last = static_cast<ssize_t>(std::stoll(cm.str(2)));\n        }\n\n        if (first != -1 && last != -1 && first > last) {\n          all_valid_ranges = false;\n          return;\n        }\n        ranges.emplace_back(std::make_pair(first, last));\n      }\n    });\n    return all_valid_ranges;\n  }\n  return false;\n#ifdef CPPHTTPLIB_NO_EXCEPTIONS\n}\n#else\n} catch (...) { return false; }\n#endif\n\nclass MultipartFormDataParser {\npublic:\n  MultipartFormDataParser() = default;\n\n  void set_boundary(std::string &&boundary) {\n    boundary_ = boundary;\n    dash_boundary_crlf_ = dash_ + boundary_ + crlf_;\n    crlf_dash_boundary_ = crlf_ + dash_ + boundary_;\n  }\n\n  bool is_valid() const { return is_valid_; }\n\n  bool parse(const char *buf, size_t n, const ContentReceiver &content_callback,\n             const MultipartContentHeader &header_callback) {\n\n    // TODO: support 'filename*'\n    static const std::regex re_content_disposition(\n        R\"~(^Content-Disposition:\\s*form-data;\\s*name=\"(.*?)\"(?:;\\s*filename=\"(.*?)\")?(?:;\\s*filename\\*=\\S+)?\\s*$)~\",\n        std::regex_constants::icase);\n\n    buf_append(buf, n);\n\n    while (buf_size() > 0) {\n      switch (state_) {\n      case 0: { // Initial boundary\n        buf_erase(buf_find(dash_boundary_crlf_));\n        if (dash_boundary_crlf_.size() > buf_size()) { return true; }\n        if (!buf_start_with(dash_boundary_crlf_)) { return false; }\n        buf_erase(dash_boundary_crlf_.size());\n        state_ = 1;\n        break;\n      }\n      case 1: { // New entry\n        clear_file_info();\n        state_ = 2;\n        break;\n      }\n      case 2: { // Headers\n        auto pos = buf_find(crlf_);\n        if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }\n        while (pos < buf_size()) {\n          // Empty line\n          if (pos == 0) {\n            if (!header_callback(file_)) {\n              is_valid_ = false;\n              return false;\n            }\n            buf_erase(crlf_.size());\n            state_ = 3;\n            break;\n          }\n\n          static const std::string header_name = \"content-type:\";\n          const auto header = buf_head(pos);\n          if (start_with_case_ignore(header, header_name)) {\n            file_.content_type = trim_copy(header.substr(header_name.size()));\n          } else {\n            std::smatch m;\n            if (std::regex_match(header, m, re_content_disposition)) {\n              file_.name = m[1];\n              file_.filename = m[2];\n            } else {\n              is_valid_ = false;\n              return false;\n            }\n          }\n          buf_erase(pos + crlf_.size());\n          pos = buf_find(crlf_);\n        }\n        if (state_ != 3) { return true; }\n        break;\n      }\n      case 3: { // Body\n        if (crlf_dash_boundary_.size() > buf_size()) { return true; }\n        auto pos = buf_find(crlf_dash_boundary_);\n        if (pos < buf_size()) {\n          if (!content_callback(buf_data(), pos)) {\n            is_valid_ = false;\n            return false;\n          }\n          buf_erase(pos + crlf_dash_boundary_.size());\n          state_ = 4;\n        } else {\n          auto len = buf_size() - crlf_dash_boundary_.size();\n          if (len > 0) {\n            if (!content_callback(buf_data(), len)) {\n              is_valid_ = false;\n              return false;\n            }\n            buf_erase(len);\n          }\n          return true;\n        }\n        break;\n      }\n      case 4: { // Boundary\n        if (crlf_.size() > buf_size()) { return true; }\n        if (buf_start_with(crlf_)) {\n          buf_erase(crlf_.size());\n          state_ = 1;\n        } else {\n          if (dash_crlf_.size() > buf_size()) { return true; }\n          if (buf_start_with(dash_crlf_)) {\n            buf_erase(dash_crlf_.size());\n            is_valid_ = true;\n            buf_erase(buf_size()); // Remove epilogue\n          } else {\n            return true;\n          }\n        }\n        break;\n      }\n      }\n    }\n\n    return true;\n  }\n\nprivate:\n  void clear_file_info() {\n    file_.name.clear();\n    file_.filename.clear();\n    file_.content_type.clear();\n  }\n\n  bool start_with_case_ignore(const std::string &a,\n                              const std::string &b) const {\n    if (a.size() < b.size()) { return false; }\n    for (size_t i = 0; i < b.size(); i++) {\n      if (::tolower(a[i]) != ::tolower(b[i])) { return false; }\n    }\n    return true;\n  }\n\n  const std::string dash_ = \"--\";\n  const std::string crlf_ = \"\\r\\n\";\n  const std::string dash_crlf_ = \"--\\r\\n\";\n  std::string boundary_;\n  std::string dash_boundary_crlf_;\n  std::string crlf_dash_boundary_;\n\n  size_t state_ = 0;\n  bool is_valid_ = false;\n  MultipartFormData file_;\n\n  // Buffer\n  bool start_with(const std::string &a, size_t spos, size_t epos,\n                  const std::string &b) const {\n    if (epos - spos < b.size()) { return false; }\n    for (size_t i = 0; i < b.size(); i++) {\n      if (a[i + spos] != b[i]) { return false; }\n    }\n    return true;\n  }\n\n  size_t buf_size() const { return buf_epos_ - buf_spos_; }\n\n  const char *buf_data() const { return &buf_[buf_spos_]; }\n\n  std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }\n\n  bool buf_start_with(const std::string &s) const {\n    return start_with(buf_, buf_spos_, buf_epos_, s);\n  }\n\n  size_t buf_find(const std::string &s) const {\n    auto c = s.front();\n\n    size_t off = buf_spos_;\n    while (off < buf_epos_) {\n      auto pos = off;\n      while (true) {\n        if (pos == buf_epos_) { return buf_size(); }\n        if (buf_[pos] == c) { break; }\n        pos++;\n      }\n\n      auto remaining_size = buf_epos_ - pos;\n      if (s.size() > remaining_size) { return buf_size(); }\n\n      if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }\n\n      off = pos + 1;\n    }\n\n    return buf_size();\n  }\n\n  void buf_append(const char *data, size_t n) {\n    auto remaining_size = buf_size();\n    if (remaining_size > 0 && buf_spos_ > 0) {\n      for (size_t i = 0; i < remaining_size; i++) {\n        buf_[i] = buf_[buf_spos_ + i];\n      }\n    }\n    buf_spos_ = 0;\n    buf_epos_ = remaining_size;\n\n    if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }\n\n    for (size_t i = 0; i < n; i++) {\n      buf_[buf_epos_ + i] = data[i];\n    }\n    buf_epos_ += n;\n  }\n\n  void buf_erase(size_t size) { buf_spos_ += size; }\n\n  std::string buf_;\n  size_t buf_spos_ = 0;\n  size_t buf_epos_ = 0;\n};\n\ninline std::string to_lower(const char *beg, const char *end) {\n  std::string out;\n  auto it = beg;\n  while (it != end) {\n    out += static_cast<char>(::tolower(*it));\n    it++;\n  }\n  return out;\n}\n\ninline std::string make_multipart_data_boundary() {\n  static const char data[] =\n      \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n  // std::random_device might actually be deterministic on some\n  // platforms, but due to lack of support in the c++ standard library,\n  // doing better requires either some ugly hacks or breaking portability.\n  std::random_device seed_gen;\n\n  // Request 128 bits of entropy for initialization\n  std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};\n  std::mt19937 engine(seed_sequence);\n\n  std::string result = \"--cpp-httplib-multipart-data-\";\n\n  for (auto i = 0; i < 16; i++) {\n    result += data[engine() % (sizeof(data) - 1)];\n  }\n\n  return result;\n}\n\ninline bool is_multipart_boundary_chars_valid(const std::string &boundary) {\n  auto valid = true;\n  for (size_t i = 0; i < boundary.size(); i++) {\n    auto c = boundary[i];\n    if (!std::isalnum(c) && c != '-' && c != '_') {\n      valid = false;\n      break;\n    }\n  }\n  return valid;\n}\n\ntemplate <typename T>\ninline std::string\nserialize_multipart_formdata_item_begin(const T &item,\n                                        const std::string &boundary) {\n  std::string body = \"--\" + boundary + \"\\r\\n\";\n  body += \"Content-Disposition: form-data; name=\\\"\" + item.name + \"\\\"\";\n  if (!item.filename.empty()) {\n    body += \"; filename=\\\"\" + item.filename + \"\\\"\";\n  }\n  body += \"\\r\\n\";\n  if (!item.content_type.empty()) {\n    body += \"Content-Type: \" + item.content_type + \"\\r\\n\";\n  }\n  body += \"\\r\\n\";\n\n  return body;\n}\n\ninline std::string serialize_multipart_formdata_item_end() { return \"\\r\\n\"; }\n\ninline std::string\nserialize_multipart_formdata_finish(const std::string &boundary) {\n  return \"--\" + boundary + \"--\\r\\n\";\n}\n\ninline std::string\nserialize_multipart_formdata_get_content_type(const std::string &boundary) {\n  return \"multipart/form-data; boundary=\" + boundary;\n}\n\ninline std::string\nserialize_multipart_formdata(const MultipartFormDataItems &items,\n                             const std::string &boundary, bool finish = true) {\n  std::string body;\n\n  for (const auto &item : items) {\n    body += serialize_multipart_formdata_item_begin(item, boundary);\n    body += item.content + serialize_multipart_formdata_item_end();\n  }\n\n  if (finish) body += serialize_multipart_formdata_finish(boundary);\n\n  return body;\n}\n\ninline std::pair<size_t, size_t>\nget_range_offset_and_length(const Request &req, size_t content_length,\n                            size_t index) {\n  auto r = req.ranges[index];\n\n  if (r.first == -1 && r.second == -1) {\n    return std::make_pair(0, content_length);\n  }\n\n  auto slen = static_cast<ssize_t>(content_length);\n\n  if (r.first == -1) {\n    r.first = (std::max)(static_cast<ssize_t>(0), slen - r.second);\n    r.second = slen - 1;\n  }\n\n  if (r.second == -1) { r.second = slen - 1; }\n  return std::make_pair(r.first, static_cast<size_t>(r.second - r.first) + 1);\n}\n\ninline std::string make_content_range_header_field(size_t offset, size_t length,\n                                                   size_t content_length) {\n  std::string field = \"bytes \";\n  field += std::to_string(offset);\n  field += \"-\";\n  field += std::to_string(offset + length - 1);\n  field += \"/\";\n  field += std::to_string(content_length);\n  return field;\n}\n\ntemplate <typename SToken, typename CToken, typename Content>\nbool process_multipart_ranges_data(const Request &req, Response &res,\n                                   const std::string &boundary,\n                                   const std::string &content_type,\n                                   SToken stoken, CToken ctoken,\n                                   Content content) {\n  for (size_t i = 0; i < req.ranges.size(); i++) {\n    ctoken(\"--\");\n    stoken(boundary);\n    ctoken(\"\\r\\n\");\n    if (!content_type.empty()) {\n      ctoken(\"Content-Type: \");\n      stoken(content_type);\n      ctoken(\"\\r\\n\");\n    }\n\n    auto offsets = get_range_offset_and_length(req, res.body.size(), i);\n    auto offset = offsets.first;\n    auto length = offsets.second;\n\n    ctoken(\"Content-Range: \");\n    stoken(make_content_range_header_field(offset, length, res.body.size()));\n    ctoken(\"\\r\\n\");\n    ctoken(\"\\r\\n\");\n    if (!content(offset, length)) { return false; }\n    ctoken(\"\\r\\n\");\n  }\n\n  ctoken(\"--\");\n  stoken(boundary);\n  ctoken(\"--\\r\\n\");\n\n  return true;\n}\n\ninline bool make_multipart_ranges_data(const Request &req, Response &res,\n                                       const std::string &boundary,\n                                       const std::string &content_type,\n                                       std::string &data) {\n  return process_multipart_ranges_data(\n      req, res, boundary, content_type,\n      [&](const std::string &token) { data += token; },\n      [&](const std::string &token) { data += token; },\n      [&](size_t offset, size_t length) {\n        if (offset < res.body.size()) {\n          data += res.body.substr(offset, length);\n          return true;\n        }\n        return false;\n      });\n}\n\ninline size_t\nget_multipart_ranges_data_length(const Request &req, Response &res,\n                                 const std::string &boundary,\n                                 const std::string &content_type) {\n  size_t data_length = 0;\n\n  process_multipart_ranges_data(\n      req, res, boundary, content_type,\n      [&](const std::string &token) { data_length += token.size(); },\n      [&](const std::string &token) { data_length += token.size(); },\n      [&](size_t /*offset*/, size_t length) {\n        data_length += length;\n        return true;\n      });\n\n  return data_length;\n}\n\ntemplate <typename T>\ninline bool write_multipart_ranges_data(Stream &strm, const Request &req,\n                                        Response &res,\n                                        const std::string &boundary,\n                                        const std::string &content_type,\n                                        const T &is_shutting_down) {\n  return process_multipart_ranges_data(\n      req, res, boundary, content_type,\n      [&](const std::string &token) { strm.write(token); },\n      [&](const std::string &token) { strm.write(token); },\n      [&](size_t offset, size_t length) {\n        return write_content(strm, res.content_provider_, offset, length,\n                             is_shutting_down);\n      });\n}\n\ninline std::pair<size_t, size_t>\nget_range_offset_and_length(const Request &req, const Response &res,\n                            size_t index) {\n  auto r = req.ranges[index];\n\n  if (r.second == -1) {\n    r.second = static_cast<ssize_t>(res.content_length_) - 1;\n  }\n\n  return std::make_pair(r.first, r.second - r.first + 1);\n}\n\ninline bool expect_content(const Request &req) {\n  if (req.method == \"POST\" || req.method == \"PUT\" || req.method == \"PATCH\" ||\n      req.method == \"PRI\" || req.method == \"DELETE\") {\n    return true;\n  }\n  // TODO: check if Content-Length is set\n  return false;\n}\n\ninline bool has_crlf(const std::string &s) {\n  auto p = s.c_str();\n  while (*p) {\n    if (*p == '\\r' || *p == '\\n') { return true; }\n    p++;\n  }\n  return false;\n}\n\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\ninline std::string message_digest(const std::string &s, const EVP_MD *algo) {\n  auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(\n      EVP_MD_CTX_new(), EVP_MD_CTX_free);\n\n  unsigned int hash_length = 0;\n  unsigned char hash[EVP_MAX_MD_SIZE];\n\n  EVP_DigestInit_ex(context.get(), algo, nullptr);\n  EVP_DigestUpdate(context.get(), s.c_str(), s.size());\n  EVP_DigestFinal_ex(context.get(), hash, &hash_length);\n\n  std::stringstream ss;\n  for (auto i = 0u; i < hash_length; ++i) {\n    ss << std::hex << std::setw(2) << std::setfill('0')\n       << (unsigned int)hash[i];\n  }\n\n  return ss.str();\n}\n\ninline std::string MD5(const std::string &s) {\n  return message_digest(s, EVP_md5());\n}\n\ninline std::string SHA_256(const std::string &s) {\n  return message_digest(s, EVP_sha256());\n}\n\ninline std::string SHA_512(const std::string &s) {\n  return message_digest(s, EVP_sha512());\n}\n#endif\n\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n#ifdef _WIN32\n// NOTE: This code came up with the following stackoverflow post:\n// https://stackoverflow.com/questions/9507184/can-openssl-on-windows-use-the-system-certificate-store\ninline bool load_system_certs_on_windows(X509_STORE *store) {\n  auto hStore = CertOpenSystemStoreW((HCRYPTPROV_LEGACY)NULL, L\"ROOT\");\n  if (!hStore) { return false; }\n\n  auto result = false;\n  PCCERT_CONTEXT pContext = NULL;\n  while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=\n         nullptr) {\n    auto encoded_cert =\n        static_cast<const unsigned char *>(pContext->pbCertEncoded);\n\n    auto x509 = d2i_X509(NULL, &encoded_cert, pContext->cbCertEncoded);\n    if (x509) {\n      X509_STORE_add_cert(store, x509);\n      X509_free(x509);\n      result = true;\n    }\n  }\n\n  CertFreeCertificateContext(pContext);\n  CertCloseStore(hStore, 0);\n\n  return result;\n}\n#elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && defined(__APPLE__)\n#if TARGET_OS_OSX\ntemplate <typename T>\nusing CFObjectPtr =\n    std::unique_ptr<typename std::remove_pointer<T>::type, void (*)(CFTypeRef)>;\n\ninline void cf_object_ptr_deleter(CFTypeRef obj) {\n  if (obj) { CFRelease(obj); }\n}\n\ninline bool retrieve_certs_from_keychain(CFObjectPtr<CFArrayRef> &certs) {\n  CFStringRef keys[] = {kSecClass, kSecMatchLimit, kSecReturnRef};\n  CFTypeRef values[] = {kSecClassCertificate, kSecMatchLimitAll,\n                        kCFBooleanTrue};\n\n  CFObjectPtr<CFDictionaryRef> query(\n      CFDictionaryCreate(nullptr, reinterpret_cast<const void **>(keys), values,\n                         sizeof(keys) / sizeof(keys[0]),\n                         &kCFTypeDictionaryKeyCallBacks,\n                         &kCFTypeDictionaryValueCallBacks),\n      cf_object_ptr_deleter);\n\n  if (!query) { return false; }\n\n  CFTypeRef security_items = nullptr;\n  if (SecItemCopyMatching(query.get(), &security_items) != errSecSuccess ||\n      CFArrayGetTypeID() != CFGetTypeID(security_items)) {\n    return false;\n  }\n\n  certs.reset(reinterpret_cast<CFArrayRef>(security_items));\n  return true;\n}\n\ninline bool retrieve_root_certs_from_keychain(CFObjectPtr<CFArrayRef> &certs) {\n  CFArrayRef root_security_items = nullptr;\n  if (SecTrustCopyAnchorCertificates(&root_security_items) != errSecSuccess) {\n    return false;\n  }\n\n  certs.reset(root_security_items);\n  return true;\n}\n\ninline bool add_certs_to_x509_store(CFArrayRef certs, X509_STORE *store) {\n  auto result = false;\n  for (int i = 0; i < CFArrayGetCount(certs); ++i) {\n    const auto cert = reinterpret_cast<const __SecCertificate *>(\n        CFArrayGetValueAtIndex(certs, i));\n\n    if (SecCertificateGetTypeID() != CFGetTypeID(cert)) { continue; }\n\n    CFDataRef cert_data = nullptr;\n    if (SecItemExport(cert, kSecFormatX509Cert, 0, nullptr, &cert_data) !=\n        errSecSuccess) {\n      continue;\n    }\n\n    CFObjectPtr<CFDataRef> cert_data_ptr(cert_data, cf_object_ptr_deleter);\n\n    auto encoded_cert = static_cast<const unsigned char *>(\n        CFDataGetBytePtr(cert_data_ptr.get()));\n\n    auto x509 =\n        d2i_X509(NULL, &encoded_cert, CFDataGetLength(cert_data_ptr.get()));\n\n    if (x509) {\n      X509_STORE_add_cert(store, x509);\n      X509_free(x509);\n      result = true;\n    }\n  }\n\n  return result;\n}\n\ninline bool load_system_certs_on_macos(X509_STORE *store) {\n  auto result = false;\n  CFObjectPtr<CFArrayRef> certs(nullptr, cf_object_ptr_deleter);\n  if (retrieve_certs_from_keychain(certs) && certs) {\n    result = add_certs_to_x509_store(certs.get(), store);\n  }\n\n  if (retrieve_root_certs_from_keychain(certs) && certs) {\n    result = add_certs_to_x509_store(certs.get(), store) || result;\n  }\n\n  return result;\n}\n#endif // TARGET_OS_OSX\n#endif // _WIN32\n#endif // CPPHTTPLIB_OPENSSL_SUPPORT\n\n#ifdef _WIN32\nclass WSInit {\npublic:\n  WSInit() {\n    WSADATA wsaData;\n    if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;\n  }\n\n  ~WSInit() {\n    if (is_valid_) WSACleanup();\n  }\n\n  bool is_valid_ = false;\n};\n\nstatic WSInit wsinit_;\n#endif\n\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\ninline std::pair<std::string, std::string> make_digest_authentication_header(\n    const Request &req, const std::map<std::string, std::string> &auth,\n    size_t cnonce_count, const std::string &cnonce, const std::string &username,\n    const std::string &password, bool is_proxy = false) {\n  std::string nc;\n  {\n    std::stringstream ss;\n    ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;\n    nc = ss.str();\n  }\n\n  std::string qop;\n  if (auth.find(\"qop\") != auth.end()) {\n    qop = auth.at(\"qop\");\n    if (qop.find(\"auth-int\") != std::string::npos) {\n      qop = \"auth-int\";\n    } else if (qop.find(\"auth\") != std::string::npos) {\n      qop = \"auth\";\n    } else {\n      qop.clear();\n    }\n  }\n\n  std::string algo = \"MD5\";\n  if (auth.find(\"algorithm\") != auth.end()) { algo = auth.at(\"algorithm\"); }\n\n  std::string response;\n  {\n    auto H = algo == \"SHA-256\"   ? detail::SHA_256\n             : algo == \"SHA-512\" ? detail::SHA_512\n                                 : detail::MD5;\n\n    auto A1 = username + \":\" + auth.at(\"realm\") + \":\" + password;\n\n    auto A2 = req.method + \":\" + req.path;\n    if (qop == \"auth-int\") { A2 += \":\" + H(req.body); }\n\n    if (qop.empty()) {\n      response = H(H(A1) + \":\" + auth.at(\"nonce\") + \":\" + H(A2));\n    } else {\n      response = H(H(A1) + \":\" + auth.at(\"nonce\") + \":\" + nc + \":\" + cnonce +\n                   \":\" + qop + \":\" + H(A2));\n    }\n  }\n\n  auto opaque = (auth.find(\"opaque\") != auth.end()) ? auth.at(\"opaque\") : \"\";\n\n  auto field = \"Digest username=\\\"\" + username + \"\\\", realm=\\\"\" +\n               auth.at(\"realm\") + \"\\\", nonce=\\\"\" + auth.at(\"nonce\") +\n               \"\\\", uri=\\\"\" + req.path + \"\\\", algorithm=\" + algo +\n               (qop.empty() ? \", response=\\\"\"\n                            : \", qop=\" + qop + \", nc=\" + nc + \", cnonce=\\\"\" +\n                                  cnonce + \"\\\", response=\\\"\") +\n               response + \"\\\"\" +\n               (opaque.empty() ? \"\" : \", opaque=\\\"\" + opaque + \"\\\"\");\n\n  auto key = is_proxy ? \"Proxy-Authorization\" : \"Authorization\";\n  return std::make_pair(key, field);\n}\n#endif\n\ninline bool parse_www_authenticate(const Response &res,\n                                   std::map<std::string, std::string> &auth,\n                                   bool is_proxy) {\n  auto auth_key = is_proxy ? \"Proxy-Authenticate\" : \"WWW-Authenticate\";\n  if (res.has_header(auth_key)) {\n    static auto re = std::regex(R\"~((?:(?:,\\s*)?(.+?)=(?:\"(.*?)\"|([^,]*))))~\");\n    auto s = res.get_header_value(auth_key);\n    auto pos = s.find(' ');\n    if (pos != std::string::npos) {\n      auto type = s.substr(0, pos);\n      if (type == \"Basic\") {\n        return false;\n      } else if (type == \"Digest\") {\n        s = s.substr(pos + 1);\n        auto beg = std::sregex_iterator(s.begin(), s.end(), re);\n        for (auto i = beg; i != std::sregex_iterator(); ++i) {\n          auto m = *i;\n          auto key = s.substr(static_cast<size_t>(m.position(1)),\n                              static_cast<size_t>(m.length(1)));\n          auto val = m.length(2) > 0\n                         ? s.substr(static_cast<size_t>(m.position(2)),\n                                    static_cast<size_t>(m.length(2)))\n                         : s.substr(static_cast<size_t>(m.position(3)),\n                                    static_cast<size_t>(m.length(3)));\n          auth[key] = val;\n        }\n        return true;\n      }\n    }\n  }\n  return false;\n}\n\n// https://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c/440240#answer-440240\ninline std::string random_string(size_t length) {\n  auto randchar = []() -> char {\n    const char charset[] = \"0123456789\"\n                           \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n                           \"abcdefghijklmnopqrstuvwxyz\";\n    const size_t max_index = (sizeof(charset) - 1);\n    return charset[static_cast<size_t>(std::rand()) % max_index];\n  };\n  std::string str(length, 0);\n  std::generate_n(str.begin(), length, randchar);\n  return str;\n}\n\nclass ContentProviderAdapter {\npublic:\n  explicit ContentProviderAdapter(\n      ContentProviderWithoutLength &&content_provider)\n      : content_provider_(content_provider) {}\n\n  bool operator()(size_t offset, size_t, DataSink &sink) {\n    return content_provider_(offset, sink);\n  }\n\nprivate:\n  ContentProviderWithoutLength content_provider_;\n};\n\n} // namespace detail\n\ninline std::string hosted_at(const std::string &hostname) {\n  std::vector<std::string> addrs;\n  hosted_at(hostname, addrs);\n  if (addrs.empty()) { return std::string(); }\n  return addrs[0];\n}\n\ninline void hosted_at(const std::string &hostname,\n                      std::vector<std::string> &addrs) {\n  struct addrinfo hints;\n  struct addrinfo *result;\n\n  memset(&hints, 0, sizeof(struct addrinfo));\n  hints.ai_family = AF_UNSPEC;\n  hints.ai_socktype = SOCK_STREAM;\n  hints.ai_protocol = 0;\n\n  if (getaddrinfo(hostname.c_str(), nullptr, &hints, &result)) {\n#if defined __linux__ && !defined __ANDROID__\n    res_init();\n#endif\n    return;\n  }\n\n  for (auto rp = result; rp; rp = rp->ai_next) {\n    const auto &addr =\n        *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);\n    std::string ip;\n    int dummy = -1;\n    if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,\n                                dummy)) {\n      addrs.push_back(ip);\n    }\n  }\n\n  freeaddrinfo(result);\n}\n\ninline std::string append_query_params(const std::string &path,\n                                       const Params &params) {\n  std::string path_with_query = path;\n  const static std::regex re(\"[^?]+\\\\?.*\");\n  auto delm = std::regex_match(path, re) ? '&' : '?';\n  path_with_query += delm + detail::params_to_query_str(params);\n  return path_with_query;\n}\n\n// Header utilities\ninline std::pair<std::string, std::string> make_range_header(Ranges ranges) {\n  std::string field = \"bytes=\";\n  auto i = 0;\n  for (auto r : ranges) {\n    if (i != 0) { field += \", \"; }\n    if (r.first != -1) { field += std::to_string(r.first); }\n    field += '-';\n    if (r.second != -1) { field += std::to_string(r.second); }\n    i++;\n  }\n  return std::make_pair(\"Range\", std::move(field));\n}\n\ninline std::pair<std::string, std::string>\nmake_basic_authentication_header(const std::string &username,\n                                 const std::string &password, bool is_proxy) {\n  auto field = \"Basic \" + detail::base64_encode(username + \":\" + password);\n  auto key = is_proxy ? \"Proxy-Authorization\" : \"Authorization\";\n  return std::make_pair(key, std::move(field));\n}\n\ninline std::pair<std::string, std::string>\nmake_bearer_token_authentication_header(const std::string &token,\n                                        bool is_proxy = false) {\n  auto field = \"Bearer \" + token;\n  auto key = is_proxy ? \"Proxy-Authorization\" : \"Authorization\";\n  return std::make_pair(key, std::move(field));\n}\n\n// Request implementation\ninline bool Request::has_header(const std::string &key) const {\n  return detail::has_header(headers, key);\n}\n\ninline std::string Request::get_header_value(const std::string &key,\n                                             size_t id) const {\n  return detail::get_header_value(headers, key, id, \"\");\n}\n\ninline size_t Request::get_header_value_count(const std::string &key) const {\n  auto r = headers.equal_range(key);\n  return static_cast<size_t>(std::distance(r.first, r.second));\n}\n\ninline void Request::set_header(const std::string &key,\n                                const std::string &val) {\n  if (!detail::has_crlf(key) && !detail::has_crlf(val)) {\n    headers.emplace(key, val);\n  }\n}\n\ninline bool Request::has_param(const std::string &key) const {\n  return params.find(key) != params.end();\n}\n\ninline std::string Request::get_param_value(const std::string &key,\n                                            size_t id) const {\n  auto rng = params.equal_range(key);\n  auto it = rng.first;\n  std::advance(it, static_cast<ssize_t>(id));\n  if (it != rng.second) { return it->second; }\n  return std::string();\n}\n\ninline size_t Request::get_param_value_count(const std::string &key) const {\n  auto r = params.equal_range(key);\n  return static_cast<size_t>(std::distance(r.first, r.second));\n}\n\ninline bool Request::is_multipart_form_data() const {\n  const auto &content_type = get_header_value(\"Content-Type\");\n  return !content_type.rfind(\"multipart/form-data\", 0);\n}\n\ninline bool Request::has_file(const std::string &key) const {\n  return files.find(key) != files.end();\n}\n\ninline MultipartFormData Request::get_file_value(const std::string &key) const {\n  auto it = files.find(key);\n  if (it != files.end()) { return it->second; }\n  return MultipartFormData();\n}\n\ninline std::vector<MultipartFormData>\nRequest::get_file_values(const std::string &key) const {\n  std::vector<MultipartFormData> values;\n  auto rng = files.equal_range(key);\n  for (auto it = rng.first; it != rng.second; it++) {\n    values.push_back(it->second);\n  }\n  return values;\n}\n\n// Response implementation\ninline bool Response::has_header(const std::string &key) const {\n  return headers.find(key) != headers.end();\n}\n\ninline std::string Response::get_header_value(const std::string &key,\n                                              size_t id) const {\n  return detail::get_header_value(headers, key, id, \"\");\n}\n\ninline size_t Response::get_header_value_count(const std::string &key) const {\n  auto r = headers.equal_range(key);\n  return static_cast<size_t>(std::distance(r.first, r.second));\n}\n\ninline void Response::set_header(const std::string &key,\n                                 const std::string &val) {\n  if (!detail::has_crlf(key) && !detail::has_crlf(val)) {\n    headers.emplace(key, val);\n  }\n}\n\ninline void Response::set_redirect(const std::string &url, int stat) {\n  if (!detail::has_crlf(url)) {\n    set_header(\"Location\", url);\n    if (300 <= stat && stat < 400) {\n      this->status = stat;\n    } else {\n      this->status = 302;\n    }\n  }\n}\n\ninline void Response::set_content(const char *s, size_t n,\n                                  const std::string &content_type) {\n  body.assign(s, n);\n\n  auto rng = headers.equal_range(\"Content-Type\");\n  headers.erase(rng.first, rng.second);\n  set_header(\"Content-Type\", content_type);\n}\n\ninline void Response::set_content(const std::string &s,\n                                  const std::string &content_type) {\n  set_content(s.data(), s.size(), content_type);\n}\n\ninline void Response::set_content_provider(\n    size_t in_length, const std::string &content_type, ContentProvider provider,\n    ContentProviderResourceReleaser resource_releaser) {\n  set_header(\"Content-Type\", content_type);\n  content_length_ = in_length;\n  if (in_length > 0) { content_provider_ = std::move(provider); }\n  content_provider_resource_releaser_ = resource_releaser;\n  is_chunked_content_provider_ = false;\n}\n\ninline void Response::set_content_provider(\n    const std::string &content_type, ContentProviderWithoutLength provider,\n    ContentProviderResourceReleaser resource_releaser) {\n  set_header(\"Content-Type\", content_type);\n  content_length_ = 0;\n  content_provider_ = detail::ContentProviderAdapter(std::move(provider));\n  content_provider_resource_releaser_ = resource_releaser;\n  is_chunked_content_provider_ = false;\n}\n\ninline void Response::set_chunked_content_provider(\n    const std::string &content_type, ContentProviderWithoutLength provider,\n    ContentProviderResourceReleaser resource_releaser) {\n  set_header(\"Content-Type\", content_type);\n  content_length_ = 0;\n  content_provider_ = detail::ContentProviderAdapter(std::move(provider));\n  content_provider_resource_releaser_ = resource_releaser;\n  is_chunked_content_provider_ = true;\n}\n\n// Result implementation\ninline bool Result::has_request_header(const std::string &key) const {\n  return request_headers_.find(key) != request_headers_.end();\n}\n\ninline std::string Result::get_request_header_value(const std::string &key,\n                                                    size_t id) const {\n  return detail::get_header_value(request_headers_, key, id, \"\");\n}\n\ninline size_t\nResult::get_request_header_value_count(const std::string &key) const {\n  auto r = request_headers_.equal_range(key);\n  return static_cast<size_t>(std::distance(r.first, r.second));\n}\n\n// Stream implementation\ninline ssize_t Stream::write(const char *ptr) {\n  return write(ptr, strlen(ptr));\n}\n\ninline ssize_t Stream::write(const std::string &s) {\n  return write(s.data(), s.size());\n}\n\nnamespace detail {\n\n// Socket stream implementation\ninline SocketStream::SocketStream(socket_t sock, time_t read_timeout_sec,\n                                  time_t read_timeout_usec,\n                                  time_t write_timeout_sec,\n                                  time_t write_timeout_usec)\n    : sock_(sock), read_timeout_sec_(read_timeout_sec),\n      read_timeout_usec_(read_timeout_usec),\n      write_timeout_sec_(write_timeout_sec),\n      write_timeout_usec_(write_timeout_usec), read_buff_(read_buff_size_, 0) {}\n\ninline SocketStream::~SocketStream() {}\n\ninline bool SocketStream::is_readable() const {\n  return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;\n}\n\ninline bool SocketStream::is_writable() const {\n  return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&\n         is_socket_alive(sock_);\n}\n\ninline ssize_t SocketStream::read(char *ptr, size_t size) {\n#ifdef _WIN32\n  size =\n      (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));\n#else\n  size = (std::min)(size,\n                    static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));\n#endif\n\n  if (read_buff_off_ < read_buff_content_size_) {\n    auto remaining_size = read_buff_content_size_ - read_buff_off_;\n    if (size <= remaining_size) {\n      memcpy(ptr, read_buff_.data() + read_buff_off_, size);\n      read_buff_off_ += size;\n      return static_cast<ssize_t>(size);\n    } else {\n      memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);\n      read_buff_off_ += remaining_size;\n      return static_cast<ssize_t>(remaining_size);\n    }\n  }\n\n  if (!is_readable()) { return -1; }\n\n  read_buff_off_ = 0;\n  read_buff_content_size_ = 0;\n\n  if (size < read_buff_size_) {\n    auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,\n                         CPPHTTPLIB_RECV_FLAGS);\n    if (n <= 0) {\n      return n;\n    } else if (n <= static_cast<ssize_t>(size)) {\n      memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));\n      return n;\n    } else {\n      memcpy(ptr, read_buff_.data(), size);\n      read_buff_off_ = size;\n      read_buff_content_size_ = static_cast<size_t>(n);\n      return static_cast<ssize_t>(size);\n    }\n  } else {\n    return read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);\n  }\n}\n\ninline ssize_t SocketStream::write(const char *ptr, size_t size) {\n  if (!is_writable()) { return -1; }\n\n#if defined(_WIN32) && !defined(_WIN64)\n  size =\n      (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));\n#endif\n\n  return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);\n}\n\ninline void SocketStream::get_remote_ip_and_port(std::string &ip,\n                                                 int &port) const {\n  return detail::get_remote_ip_and_port(sock_, ip, port);\n}\n\ninline void SocketStream::get_local_ip_and_port(std::string &ip,\n                                                int &port) const {\n  return detail::get_local_ip_and_port(sock_, ip, port);\n}\n\ninline socket_t SocketStream::socket() const { return sock_; }\n\n// Buffer stream implementation\ninline bool BufferStream::is_readable() const { return true; }\n\ninline bool BufferStream::is_writable() const { return true; }\n\ninline ssize_t BufferStream::read(char *ptr, size_t size) {\n#if defined(_MSC_VER) && _MSC_VER < 1910\n  auto len_read = buffer._Copy_s(ptr, size, size, position);\n#else\n  auto len_read = buffer.copy(ptr, size, position);\n#endif\n  position += static_cast<size_t>(len_read);\n  return static_cast<ssize_t>(len_read);\n}\n\ninline ssize_t BufferStream::write(const char *ptr, size_t size) {\n  buffer.append(ptr, size);\n  return static_cast<ssize_t>(size);\n}\n\ninline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,\n                                                 int & /*port*/) const {}\n\ninline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,\n                                                int & /*port*/) const {}\n\ninline socket_t BufferStream::socket() const { return 0; }\n\ninline const std::string &BufferStream::get_buffer() const { return buffer; }\n\n} // namespace detail\n\n// HTTP server implementation\ninline Server::Server()\n    : new_task_queue(\n          [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }) {\n#ifndef _WIN32\n  signal(SIGPIPE, SIG_IGN);\n#endif\n}\n\ninline Server::~Server() {}\n\ninline Server &Server::Get(const std::string &pattern, Handler handler) {\n  get_handlers_.push_back(\n      std::make_pair(std::regex(pattern), std::move(handler)));\n  return *this;\n}\n\ninline Server &Server::Post(const std::string &pattern, Handler handler) {\n  post_handlers_.push_back(\n      std::make_pair(std::regex(pattern), std::move(handler)));\n  return *this;\n}\n\ninline Server &Server::Post(const std::string &pattern,\n                            HandlerWithContentReader handler) {\n  post_handlers_for_content_reader_.push_back(\n      std::make_pair(std::regex(pattern), std::move(handler)));\n  return *this;\n}\n\ninline Server &Server::Put(const std::string &pattern, Handler handler) {\n  put_handlers_.push_back(\n      std::make_pair(std::regex(pattern), std::move(handler)));\n  return *this;\n}\n\ninline Server &Server::Put(const std::string &pattern,\n                           HandlerWithContentReader handler) {\n  put_handlers_for_content_reader_.push_back(\n      std::make_pair(std::regex(pattern), std::move(handler)));\n  return *this;\n}\n\ninline Server &Server::Patch(const std::string &pattern, Handler handler) {\n  patch_handlers_.push_back(\n      std::make_pair(std::regex(pattern), std::move(handler)));\n  return *this;\n}\n\ninline Server &Server::Patch(const std::string &pattern,\n                             HandlerWithContentReader handler) {\n  patch_handlers_for_content_reader_.push_back(\n      std::make_pair(std::regex(pattern), std::move(handler)));\n  return *this;\n}\n\ninline Server &Server::Delete(const std::string &pattern, Handler handler) {\n  delete_handlers_.push_back(\n      std::make_pair(std::regex(pattern), std::move(handler)));\n  return *this;\n}\n\ninline Server &Server::Delete(const std::string &pattern,\n                              HandlerWithContentReader handler) {\n  delete_handlers_for_content_reader_.push_back(\n      std::make_pair(std::regex(pattern), std::move(handler)));\n  return *this;\n}\n\ninline Server &Server::Options(const std::string &pattern, Handler handler) {\n  options_handlers_.push_back(\n      std::make_pair(std::regex(pattern), std::move(handler)));\n  return *this;\n}\n\ninline bool Server::set_base_dir(const std::string &dir,\n                                 const std::string &mount_point) {\n  return set_mount_point(mount_point, dir);\n}\n\ninline bool Server::set_mount_point(const std::string &mount_point,\n                                    const std::string &dir, Headers headers) {\n  if (detail::is_dir(dir)) {\n    std::string mnt = !mount_point.empty() ? mount_point : \"/\";\n    if (!mnt.empty() && mnt[0] == '/') {\n      base_dirs_.push_back({mnt, dir, std::move(headers)});\n      return true;\n    }\n  }\n  return false;\n}\n\ninline bool Server::remove_mount_point(const std::string &mount_point) {\n  for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {\n    if (it->mount_point == mount_point) {\n      base_dirs_.erase(it);\n      return true;\n    }\n  }\n  return false;\n}\n\ninline Server &\nServer::set_file_extension_and_mimetype_mapping(const std::string &ext,\n                                                const std::string &mime) {\n  file_extension_and_mimetype_map_[ext] = mime;\n  return *this;\n}\n\ninline Server &Server::set_file_request_handler(Handler handler) {\n  file_request_handler_ = std::move(handler);\n  return *this;\n}\n\ninline Server &Server::set_error_handler(HandlerWithResponse handler) {\n  error_handler_ = std::move(handler);\n  return *this;\n}\n\ninline Server &Server::set_error_handler(Handler handler) {\n  error_handler_ = [handler](const Request &req, Response &res) {\n    handler(req, res);\n    return HandlerResponse::Handled;\n  };\n  return *this;\n}\n\ninline Server &Server::set_exception_handler(ExceptionHandler handler) {\n  exception_handler_ = std::move(handler);\n  return *this;\n}\n\ninline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {\n  pre_routing_handler_ = std::move(handler);\n  return *this;\n}\n\ninline Server &Server::set_post_routing_handler(Handler handler) {\n  post_routing_handler_ = std::move(handler);\n  return *this;\n}\n\ninline Server &Server::set_logger(Logger logger) {\n  logger_ = std::move(logger);\n  return *this;\n}\n\ninline Server &\nServer::set_expect_100_continue_handler(Expect100ContinueHandler handler) {\n  expect_100_continue_handler_ = std::move(handler);\n\n  return *this;\n}\n\ninline Server &Server::set_address_family(int family) {\n  address_family_ = family;\n  return *this;\n}\n\ninline Server &Server::set_tcp_nodelay(bool on) {\n  tcp_nodelay_ = on;\n  return *this;\n}\n\ninline Server &Server::set_socket_options(SocketOptions socket_options) {\n  socket_options_ = std::move(socket_options);\n  return *this;\n}\n\ninline Server &Server::set_default_headers(Headers headers) {\n  default_headers_ = std::move(headers);\n  return *this;\n}\n\ninline Server &Server::set_keep_alive_max_count(size_t count) {\n  keep_alive_max_count_ = count;\n  return *this;\n}\n\ninline Server &Server::set_keep_alive_timeout(time_t sec) {\n  keep_alive_timeout_sec_ = sec;\n  return *this;\n}\n\ninline Server &Server::set_read_timeout(time_t sec, time_t usec) {\n  read_timeout_sec_ = sec;\n  read_timeout_usec_ = usec;\n  return *this;\n}\n\ninline Server &Server::set_write_timeout(time_t sec, time_t usec) {\n  write_timeout_sec_ = sec;\n  write_timeout_usec_ = usec;\n  return *this;\n}\n\ninline Server &Server::set_idle_interval(time_t sec, time_t usec) {\n  idle_interval_sec_ = sec;\n  idle_interval_usec_ = usec;\n  return *this;\n}\n\ninline Server &Server::set_payload_max_length(size_t length) {\n  payload_max_length_ = length;\n  return *this;\n}\n\ninline bool Server::bind_to_port(const std::string &host, int port,\n                                 int socket_flags) {\n  if (bind_internal(host, port, socket_flags) < 0) return false;\n  return true;\n}\ninline int Server::bind_to_any_port(const std::string &host, int socket_flags) {\n  return bind_internal(host, 0, socket_flags);\n}\n\ninline bool Server::listen_after_bind() {\n  auto se = detail::scope_exit([&]() { done_ = true; });\n  return listen_internal();\n}\n\ninline bool Server::listen(const std::string &host, int port,\n                           int socket_flags) {\n  auto se = detail::scope_exit([&]() { done_ = true; });\n  return bind_to_port(host, port, socket_flags) && listen_internal();\n}\n\ninline bool Server::is_running() const { return is_running_; }\n\ninline void Server::wait_until_ready() const {\n  while (!is_running() && !done_) {\n    std::this_thread::sleep_for(std::chrono::milliseconds{1});\n  }\n}\n\ninline void Server::stop() {\n  if (is_running_) {\n    assert(svr_sock_ != INVALID_SOCKET);\n    std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));\n    detail::shutdown_socket(sock);\n    detail::close_socket(sock);\n  }\n}\n\ninline bool Server::parse_request_line(const char *s, Request &req) {\n  auto len = strlen(s);\n  if (len < 2 || s[len - 2] != '\\r' || s[len - 1] != '\\n') { return false; }\n  len -= 2;\n\n  {\n    size_t count = 0;\n\n    detail::split(s, s + len, ' ', [&](const char *b, const char *e) {\n      switch (count) {\n      case 0: req.method = std::string(b, e); break;\n      case 1: req.target = std::string(b, e); break;\n      case 2: req.version = std::string(b, e); break;\n      default: break;\n      }\n      count++;\n    });\n\n    if (count != 3) { return false; }\n  }\n\n  static const std::set<std::string> methods{\n      \"GET\",     \"HEAD\",    \"POST\",  \"PUT\",   \"DELETE\",\n      \"CONNECT\", \"OPTIONS\", \"TRACE\", \"PATCH\", \"PRI\"};\n\n  if (methods.find(req.method) == methods.end()) { return false; }\n\n  if (req.version != \"HTTP/1.1\" && req.version != \"HTTP/1.0\") { return false; }\n\n  {\n    // Skip URL fragment\n    for (size_t i = 0; i < req.target.size(); i++) {\n      if (req.target[i] == '#') {\n        req.target.erase(i);\n        break;\n      }\n    }\n\n    size_t count = 0;\n\n    detail::split(req.target.data(), req.target.data() + req.target.size(), '?',\n                  [&](const char *b, const char *e) {\n                    switch (count) {\n                    case 0:\n                      req.path = detail::decode_url(std::string(b, e), false);\n                      break;\n                    case 1: {\n                      if (e - b > 0) {\n                        detail::parse_query_text(std::string(b, e), req.params);\n                      }\n                      break;\n                    }\n                    default: break;\n                    }\n                    count++;\n                  });\n\n    if (count > 2) { return false; }\n  }\n\n  return true;\n}\n\ninline bool Server::write_response(Stream &strm, bool close_connection,\n                                   const Request &req, Response &res) {\n  return write_response_core(strm, close_connection, req, res, false);\n}\n\ninline bool Server::write_response_with_content(Stream &strm,\n                                                bool close_connection,\n                                                const Request &req,\n                                                Response &res) {\n  return write_response_core(strm, close_connection, req, res, true);\n}\n\ninline bool Server::write_response_core(Stream &strm, bool close_connection,\n                                        const Request &req, Response &res,\n                                        bool need_apply_ranges) {\n  assert(res.status != -1);\n\n  if (400 <= res.status && error_handler_ &&\n      error_handler_(req, res) == HandlerResponse::Handled) {\n    need_apply_ranges = true;\n  }\n\n  std::string content_type;\n  std::string boundary;\n  if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }\n\n  // Prepare additional headers\n  if (close_connection || req.get_header_value(\"Connection\") == \"close\") {\n    res.set_header(\"Connection\", \"close\");\n  } else {\n    std::stringstream ss;\n    ss << \"timeout=\" << keep_alive_timeout_sec_\n       << \", max=\" << keep_alive_max_count_;\n    res.set_header(\"Keep-Alive\", ss.str());\n  }\n\n  if (!res.has_header(\"Content-Type\") &&\n      (!res.body.empty() || res.content_length_ > 0 || res.content_provider_)) {\n    res.set_header(\"Content-Type\", \"text/plain\");\n  }\n\n  if (!res.has_header(\"Content-Length\") && res.body.empty() &&\n      !res.content_length_ && !res.content_provider_) {\n    res.set_header(\"Content-Length\", \"0\");\n  }\n\n  if (!res.has_header(\"Accept-Ranges\") && req.method == \"HEAD\") {\n    res.set_header(\"Accept-Ranges\", \"bytes\");\n  }\n\n  if (post_routing_handler_) { post_routing_handler_(req, res); }\n\n  // Response line and headers\n  {\n    detail::BufferStream bstrm;\n\n    if (!bstrm.write_format(\"HTTP/1.1 %d %s\\r\\n\", res.status,\n                            detail::status_message(res.status))) {\n      return false;\n    }\n\n    if (!detail::write_headers(bstrm, res.headers)) { return false; }\n\n    // Flush buffer\n    auto &data = bstrm.get_buffer();\n    detail::write_data(strm, data.data(), data.size());\n  }\n\n  // Body\n  auto ret = true;\n  if (req.method != \"HEAD\") {\n    if (!res.body.empty()) {\n      if (!detail::write_data(strm, res.body.data(), res.body.size())) {\n        ret = false;\n      }\n    } else if (res.content_provider_) {\n      if (write_content_with_provider(strm, req, res, boundary, content_type)) {\n        res.content_provider_success_ = true;\n      } else {\n        res.content_provider_success_ = false;\n        ret = false;\n      }\n    }\n  }\n\n  // Log\n  if (logger_) { logger_(req, res); }\n\n  return ret;\n}\n\ninline bool\nServer::write_content_with_provider(Stream &strm, const Request &req,\n                                    Response &res, const std::string &boundary,\n                                    const std::string &content_type) {\n  auto is_shutting_down = [this]() {\n    return this->svr_sock_ == INVALID_SOCKET;\n  };\n\n  if (res.content_length_ > 0) {\n    if (req.ranges.empty()) {\n      return detail::write_content(strm, res.content_provider_, 0,\n                                   res.content_length_, is_shutting_down);\n    } else if (req.ranges.size() == 1) {\n      auto offsets =\n          detail::get_range_offset_and_length(req, res.content_length_, 0);\n      auto offset = offsets.first;\n      auto length = offsets.second;\n      return detail::write_content(strm, res.content_provider_, offset, length,\n                                   is_shutting_down);\n    } else {\n      return detail::write_multipart_ranges_data(\n          strm, req, res, boundary, content_type, is_shutting_down);\n    }\n  } else {\n    if (res.is_chunked_content_provider_) {\n      auto type = detail::encoding_type(req, res);\n\n      std::unique_ptr<detail::compressor> compressor;\n      if (type == detail::EncodingType::Gzip) {\n#ifdef CPPHTTPLIB_ZLIB_SUPPORT\n        compressor = detail::make_unique<detail::gzip_compressor>();\n#endif\n      } else if (type == detail::EncodingType::Brotli) {\n#ifdef CPPHTTPLIB_BROTLI_SUPPORT\n        compressor = detail::make_unique<detail::brotli_compressor>();\n#endif\n      } else {\n        compressor = detail::make_unique<detail::nocompressor>();\n      }\n      assert(compressor != nullptr);\n\n      return detail::write_content_chunked(strm, res.content_provider_,\n                                           is_shutting_down, *compressor);\n    } else {\n      return detail::write_content_without_length(strm, res.content_provider_,\n                                                  is_shutting_down);\n    }\n  }\n}\n\ninline bool Server::read_content(Stream &strm, Request &req, Response &res) {\n  MultipartFormDataMap::iterator cur;\n  auto file_count = 0;\n  if (read_content_core(\n          strm, req, res,\n          // Regular\n          [&](const char *buf, size_t n) {\n            if (req.body.size() + n > req.body.max_size()) { return false; }\n            req.body.append(buf, n);\n            return true;\n          },\n          // Multipart\n          [&](const MultipartFormData &file) {\n            if (file_count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {\n              return false;\n            }\n            cur = req.files.emplace(file.name, file);\n            return true;\n          },\n          [&](const char *buf, size_t n) {\n            auto &content = cur->second.content;\n            if (content.size() + n > content.max_size()) { return false; }\n            content.append(buf, n);\n            return true;\n          })) {\n    const auto &content_type = req.get_header_value(\"Content-Type\");\n    if (!content_type.find(\"application/x-www-form-urlencoded\")) {\n      if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {\n        res.status = 413; // NOTE: should be 414?\n        return false;\n      }\n      detail::parse_query_text(req.body, req.params);\n    }\n    return true;\n  }\n  return false;\n}\n\ninline bool Server::read_content_with_content_receiver(\n    Stream &strm, Request &req, Response &res, ContentReceiver receiver,\n    MultipartContentHeader multipart_header,\n    ContentReceiver multipart_receiver) {\n  return read_content_core(strm, req, res, std::move(receiver),\n                           std::move(multipart_header),\n                           std::move(multipart_receiver));\n}\n\ninline bool Server::read_content_core(Stream &strm, Request &req, Response &res,\n                                      ContentReceiver receiver,\n                                      MultipartContentHeader multipart_header,\n                                      ContentReceiver multipart_receiver) {\n  detail::MultipartFormDataParser multipart_form_data_parser;\n  ContentReceiverWithProgress out;\n\n  if (req.is_multipart_form_data()) {\n    const auto &content_type = req.get_header_value(\"Content-Type\");\n    std::string boundary;\n    if (!detail::parse_multipart_boundary(content_type, boundary)) {\n      res.status = 400;\n      return false;\n    }\n\n    multipart_form_data_parser.set_boundary(std::move(boundary));\n    out = [&](const char *buf, size_t n, uint64_t /*off*/, uint64_t /*len*/) {\n      /* For debug\n      size_t pos = 0;\n      while (pos < n) {\n        auto read_size = (std::min)<size_t>(1, n - pos);\n        auto ret = multipart_form_data_parser.parse(\n            buf + pos, read_size, multipart_receiver, multipart_header);\n        if (!ret) { return false; }\n        pos += read_size;\n      }\n      return true;\n      */\n      return multipart_form_data_parser.parse(buf, n, multipart_receiver,\n                                              multipart_header);\n    };\n  } else {\n    out = [receiver](const char *buf, size_t n, uint64_t /*off*/,\n                     uint64_t /*len*/) { return receiver(buf, n); };\n  }\n\n  if (req.method == \"DELETE\" && !req.has_header(\"Content-Length\")) {\n    return true;\n  }\n\n  if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,\n                            out, true)) {\n    return false;\n  }\n\n  if (req.is_multipart_form_data()) {\n    if (!multipart_form_data_parser.is_valid()) {\n      res.status = 400;\n      return false;\n    }\n  }\n\n  return true;\n}\n\ninline bool Server::handle_file_request(const Request &req, Response &res,\n                                        bool head) {\n  for (const auto &entry : base_dirs_) {\n    // Prefix match\n    if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {\n      std::string sub_path = \"/\" + req.path.substr(entry.mount_point.size());\n      if (detail::is_valid_path(sub_path)) {\n        auto path = entry.base_dir + sub_path;\n        if (path.back() == '/') { path += \"index.html\"; }\n\n        if (detail::is_file(path)) {\n          detail::read_file(path, res.body);\n          auto type =\n              detail::find_content_type(path, file_extension_and_mimetype_map_);\n          if (type) { res.set_header(\"Content-Type\", type); }\n          for (const auto &kv : entry.headers) {\n            res.set_header(kv.first.c_str(), kv.second);\n          }\n          res.status = req.has_header(\"Range\") ? 206 : 200;\n          if (!head && file_request_handler_) {\n            file_request_handler_(req, res);\n          }\n          return true;\n        }\n      }\n    }\n  }\n  return false;\n}\n\ninline socket_t\nServer::create_server_socket(const std::string &host, int port,\n                             int socket_flags,\n                             SocketOptions socket_options) const {\n  return detail::create_socket(\n      host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,\n      std::move(socket_options),\n      [](socket_t sock, struct addrinfo &ai) -> bool {\n        if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {\n          return false;\n        }\n        if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) { return false; }\n        return true;\n      });\n}\n\ninline int Server::bind_internal(const std::string &host, int port,\n                                 int socket_flags) {\n  if (!is_valid()) { return -1; }\n\n  svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);\n  if (svr_sock_ == INVALID_SOCKET) { return -1; }\n\n  if (port == 0) {\n    struct sockaddr_storage addr;\n    socklen_t addr_len = sizeof(addr);\n    if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),\n                    &addr_len) == -1) {\n      return -1;\n    }\n    if (addr.ss_family == AF_INET) {\n      return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);\n    } else if (addr.ss_family == AF_INET6) {\n      return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);\n    } else {\n      return -1;\n    }\n  } else {\n    return port;\n  }\n}\n\ninline bool Server::listen_internal() {\n  auto ret = true;\n  is_running_ = true;\n  auto se = detail::scope_exit([&]() { is_running_ = false; });\n\n  {\n    std::unique_ptr<TaskQueue> task_queue(new_task_queue());\n\n    while (svr_sock_ != INVALID_SOCKET) {\n#ifndef _WIN32\n      if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {\n#endif\n        auto val = detail::select_read(svr_sock_, idle_interval_sec_,\n                                       idle_interval_usec_);\n        if (val == 0) { // Timeout\n          task_queue->on_idle();\n          continue;\n        }\n#ifndef _WIN32\n      }\n#endif\n      socket_t sock = accept(svr_sock_, nullptr, nullptr);\n\n      if (sock == INVALID_SOCKET) {\n        if (errno == EMFILE) {\n          // The per-process limit of open file descriptors has been reached.\n          // Try to accept new connections after a short sleep.\n          std::this_thread::sleep_for(std::chrono::milliseconds(1));\n          continue;\n        } else if (errno == EINTR || errno == EAGAIN) {\n          continue;\n        }\n        if (svr_sock_ != INVALID_SOCKET) {\n          detail::close_socket(svr_sock_);\n          ret = false;\n        } else {\n          ; // The server socket was closed by user.\n        }\n        break;\n      }\n\n      {\n#ifdef _WIN32\n        auto timeout = static_cast<uint32_t>(read_timeout_sec_ * 1000 +\n                                             read_timeout_usec_ / 1000);\n        setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,\n                   sizeof(timeout));\n#else\n        timeval tv;\n        tv.tv_sec = static_cast<long>(read_timeout_sec_);\n        tv.tv_usec = static_cast<decltype(tv.tv_usec)>(read_timeout_usec_);\n        setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv));\n#endif\n      }\n      {\n\n#ifdef _WIN32\n        auto timeout = static_cast<uint32_t>(write_timeout_sec_ * 1000 +\n                                             write_timeout_usec_ / 1000);\n        setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout,\n                   sizeof(timeout));\n#else\n        timeval tv;\n        tv.tv_sec = static_cast<long>(write_timeout_sec_);\n        tv.tv_usec = static_cast<decltype(tv.tv_usec)>(write_timeout_usec_);\n        setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv));\n#endif\n      }\n\n      task_queue->enqueue([this, sock]() { process_and_close_socket(sock); });\n    }\n\n    task_queue->shutdown();\n  }\n\n  return ret;\n}\n\ninline bool Server::routing(Request &req, Response &res, Stream &strm) {\n  if (pre_routing_handler_ &&\n      pre_routing_handler_(req, res) == HandlerResponse::Handled) {\n    return true;\n  }\n\n  // File handler\n  bool is_head_request = req.method == \"HEAD\";\n  if ((req.method == \"GET\" || is_head_request) &&\n      handle_file_request(req, res, is_head_request)) {\n    return true;\n  }\n\n  if (detail::expect_content(req)) {\n    // Content reader handler\n    {\n      ContentReader reader(\n          [&](ContentReceiver receiver) {\n            return read_content_with_content_receiver(\n                strm, req, res, std::move(receiver), nullptr, nullptr);\n          },\n          [&](MultipartContentHeader header, ContentReceiver receiver) {\n            return read_content_with_content_receiver(strm, req, res, nullptr,\n                                                      std::move(header),\n                                                      std::move(receiver));\n          });\n\n      if (req.method == \"POST\") {\n        if (dispatch_request_for_content_reader(\n                req, res, std::move(reader),\n                post_handlers_for_content_reader_)) {\n          return true;\n        }\n      } else if (req.method == \"PUT\") {\n        if (dispatch_request_for_content_reader(\n                req, res, std::move(reader),\n                put_handlers_for_content_reader_)) {\n          return true;\n        }\n      } else if (req.method == \"PATCH\") {\n        if (dispatch_request_for_content_reader(\n                req, res, std::move(reader),\n                patch_handlers_for_content_reader_)) {\n          return true;\n        }\n      } else if (req.method == \"DELETE\") {\n        if (dispatch_request_for_content_reader(\n                req, res, std::move(reader),\n                delete_handlers_for_content_reader_)) {\n          return true;\n        }\n      }\n    }\n\n    // Read content into `req.body`\n    if (!read_content(strm, req, res)) { return false; }\n  }\n\n  // Regular handler\n  if (req.method == \"GET\" || req.method == \"HEAD\") {\n    return dispatch_request(req, res, get_handlers_);\n  } else if (req.method == \"POST\") {\n    return dispatch_request(req, res, post_handlers_);\n  } else if (req.method == \"PUT\") {\n    return dispatch_request(req, res, put_handlers_);\n  } else if (req.method == \"DELETE\") {\n    return dispatch_request(req, res, delete_handlers_);\n  } else if (req.method == \"OPTIONS\") {\n    return dispatch_request(req, res, options_handlers_);\n  } else if (req.method == \"PATCH\") {\n    return dispatch_request(req, res, patch_handlers_);\n  }\n\n  res.status = 400;\n  return false;\n}\n\ninline bool Server::dispatch_request(Request &req, Response &res,\n                                     const Handlers &handlers) {\n  for (const auto &x : handlers) {\n    const auto &pattern = x.first;\n    const auto &handler = x.second;\n\n    if (std::regex_match(req.path, req.matches, pattern)) {\n      handler(req, res);\n      return true;\n    }\n  }\n  return false;\n}\n\ninline void Server::apply_ranges(const Request &req, Response &res,\n                                 std::string &content_type,\n                                 std::string &boundary) {\n  if (req.ranges.size() > 1) {\n    boundary = detail::make_multipart_data_boundary();\n\n    auto it = res.headers.find(\"Content-Type\");\n    if (it != res.headers.end()) {\n      content_type = it->second;\n      res.headers.erase(it);\n    }\n\n    res.headers.emplace(\"Content-Type\",\n                        \"multipart/byteranges; boundary=\" + boundary);\n  }\n\n  auto type = detail::encoding_type(req, res);\n\n  if (res.body.empty()) {\n    if (res.content_length_ > 0) {\n      size_t length = 0;\n      if (req.ranges.empty()) {\n        length = res.content_length_;\n      } else if (req.ranges.size() == 1) {\n        auto offsets =\n            detail::get_range_offset_and_length(req, res.content_length_, 0);\n        auto offset = offsets.first;\n        length = offsets.second;\n        auto content_range = detail::make_content_range_header_field(\n            offset, length, res.content_length_);\n        res.set_header(\"Content-Range\", content_range);\n      } else {\n        length = detail::get_multipart_ranges_data_length(req, res, boundary,\n                                                          content_type);\n      }\n      res.set_header(\"Content-Length\", std::to_string(length));\n    } else {\n      if (res.content_provider_) {\n        if (res.is_chunked_content_provider_) {\n          res.set_header(\"Transfer-Encoding\", \"chunked\");\n          if (type == detail::EncodingType::Gzip) {\n            res.set_header(\"Content-Encoding\", \"gzip\");\n          } else if (type == detail::EncodingType::Brotli) {\n            res.set_header(\"Content-Encoding\", \"br\");\n          }\n        }\n      }\n    }\n  } else {\n    if (req.ranges.empty()) {\n      ;\n    } else if (req.ranges.size() == 1) {\n      auto offsets =\n          detail::get_range_offset_and_length(req, res.body.size(), 0);\n      auto offset = offsets.first;\n      auto length = offsets.second;\n      auto content_range = detail::make_content_range_header_field(\n          offset, length, res.body.size());\n      res.set_header(\"Content-Range\", content_range);\n      if (offset < res.body.size()) {\n        res.body = res.body.substr(offset, length);\n      } else {\n        res.body.clear();\n        res.status = 416;\n      }\n    } else {\n      std::string data;\n      if (detail::make_multipart_ranges_data(req, res, boundary, content_type,\n                                             data)) {\n        res.body.swap(data);\n      } else {\n        res.body.clear();\n        res.status = 416;\n      }\n    }\n\n    if (type != detail::EncodingType::None) {\n      std::unique_ptr<detail::compressor> compressor;\n      std::string content_encoding;\n\n      if (type == detail::EncodingType::Gzip) {\n#ifdef CPPHTTPLIB_ZLIB_SUPPORT\n        compressor = detail::make_unique<detail::gzip_compressor>();\n        content_encoding = \"gzip\";\n#endif\n      } else if (type == detail::EncodingType::Brotli) {\n#ifdef CPPHTTPLIB_BROTLI_SUPPORT\n        compressor = detail::make_unique<detail::brotli_compressor>();\n        content_encoding = \"br\";\n#endif\n      }\n\n      if (compressor) {\n        std::string compressed;\n        if (compressor->compress(res.body.data(), res.body.size(), true,\n                                 [&](const char *data, size_t data_len) {\n                                   compressed.append(data, data_len);\n                                   return true;\n                                 })) {\n          res.body.swap(compressed);\n          res.set_header(\"Content-Encoding\", content_encoding);\n        }\n      }\n    }\n\n    auto length = std::to_string(res.body.size());\n    res.set_header(\"Content-Length\", length);\n  }\n}\n\ninline bool Server::dispatch_request_for_content_reader(\n    Request &req, Response &res, ContentReader content_reader,\n    const HandlersForContentReader &handlers) {\n  for (const auto &x : handlers) {\n    const auto &pattern = x.first;\n    const auto &handler = x.second;\n\n    if (std::regex_match(req.path, req.matches, pattern)) {\n      handler(req, res, content_reader);\n      return true;\n    }\n  }\n  return false;\n}\n\ninline bool\nServer::process_request(Stream &strm, bool close_connection,\n                        bool &connection_closed,\n                        const std::function<void(Request &)> &setup_request) {\n  std::array<char, 2048> buf{};\n\n  detail::stream_line_reader line_reader(strm, buf.data(), buf.size());\n\n  // Connection has been closed on client\n  if (!line_reader.getline()) { return false; }\n\n  Request req;\n  Response res;\n\n  res.version = \"HTTP/1.1\";\n\n  for (const auto &header : default_headers_) {\n    if (res.headers.find(header.first) == res.headers.end()) {\n      res.headers.insert(header);\n    }\n  }\n\n#ifdef _WIN32\n  // TODO: Increase FD_SETSIZE statically (libzmq), dynamically (MySQL).\n#else\n#ifndef CPPHTTPLIB_USE_POLL\n  // Socket file descriptor exceeded FD_SETSIZE...\n  if (strm.socket() >= FD_SETSIZE) {\n    Headers dummy;\n    detail::read_headers(strm, dummy);\n    res.status = 500;\n    return write_response(strm, close_connection, req, res);\n  }\n#endif\n#endif\n\n  // Check if the request URI doesn't exceed the limit\n  if (line_reader.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {\n    Headers dummy;\n    detail::read_headers(strm, dummy);\n    res.status = 414;\n    return write_response(strm, close_connection, req, res);\n  }\n\n  // Request line and headers\n  if (!parse_request_line(line_reader.ptr(), req) ||\n      !detail::read_headers(strm, req.headers)) {\n    res.status = 400;\n    return write_response(strm, close_connection, req, res);\n  }\n\n  if (req.get_header_value(\"Connection\") == \"close\") {\n    connection_closed = true;\n  }\n\n  if (req.version == \"HTTP/1.0\" &&\n      req.get_header_value(\"Connection\") != \"Keep-Alive\") {\n    connection_closed = true;\n  }\n\n  strm.get_remote_ip_and_port(req.remote_addr, req.remote_port);\n  req.set_header(\"REMOTE_ADDR\", req.remote_addr);\n  req.set_header(\"REMOTE_PORT\", std::to_string(req.remote_port));\n\n  strm.get_local_ip_and_port(req.local_addr, req.local_port);\n  req.set_header(\"LOCAL_ADDR\", req.local_addr);\n  req.set_header(\"LOCAL_PORT\", std::to_string(req.local_port));\n\n  if (req.has_header(\"Range\")) {\n    const auto &range_header_value = req.get_header_value(\"Range\");\n    if (!detail::parse_range_header(range_header_value, req.ranges)) {\n      res.status = 416;\n      return write_response(strm, close_connection, req, res);\n    }\n  }\n\n  if (setup_request) { setup_request(req); }\n\n  if (req.get_header_value(\"Expect\") == \"100-continue\") {\n    auto status = 100;\n    if (expect_100_continue_handler_) {\n      status = expect_100_continue_handler_(req, res);\n    }\n    switch (status) {\n    case 100:\n    case 417:\n      strm.write_format(\"HTTP/1.1 %d %s\\r\\n\\r\\n\", status,\n                        detail::status_message(status));\n      break;\n    default: return write_response(strm, close_connection, req, res);\n    }\n  }\n\n  // Rounting\n  bool routed = false;\n#ifdef CPPHTTPLIB_NO_EXCEPTIONS\n  routed = routing(req, res, strm);\n#else\n  try {\n    routed = routing(req, res, strm);\n  } catch (std::exception &e) {\n    if (exception_handler_) {\n      auto ep = std::current_exception();\n      exception_handler_(req, res, ep);\n      routed = true;\n    } else {\n      res.status = 500;\n      std::string val;\n      auto s = e.what();\n      for (size_t i = 0; s[i]; i++) {\n        switch (s[i]) {\n        case '\\r': val += \"\\\\r\"; break;\n        case '\\n': val += \"\\\\n\"; break;\n        default: val += s[i]; break;\n        }\n      }\n      res.set_header(\"EXCEPTION_WHAT\", val);\n    }\n  } catch (...) {\n    if (exception_handler_) {\n      auto ep = std::current_exception();\n      exception_handler_(req, res, ep);\n      routed = true;\n    } else {\n      res.status = 500;\n      res.set_header(\"EXCEPTION_WHAT\", \"UNKNOWN\");\n    }\n  }\n#endif\n\n  if (routed) {\n    if (res.status == -1) { res.status = req.ranges.empty() ? 200 : 206; }\n    return write_response_with_content(strm, close_connection, req, res);\n  } else {\n    if (res.status == -1) { res.status = 404; }\n    return write_response(strm, close_connection, req, res);\n  }\n}\n\ninline bool Server::is_valid() const { return true; }\n\ninline bool Server::process_and_close_socket(socket_t sock) {\n  auto ret = detail::process_server_socket(\n      svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,\n      read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,\n      write_timeout_usec_,\n      [this](Stream &strm, bool close_connection, bool &connection_closed) {\n        return process_request(strm, close_connection, connection_closed,\n                               nullptr);\n      });\n\n  detail::shutdown_socket(sock);\n  detail::close_socket(sock);\n  return ret;\n}\n\n// HTTP client implementation\ninline ClientImpl::ClientImpl(const std::string &host)\n    : ClientImpl(host, 80, std::string(), std::string()) {}\n\ninline ClientImpl::ClientImpl(const std::string &host, int port)\n    : ClientImpl(host, port, std::string(), std::string()) {}\n\ninline ClientImpl::ClientImpl(const std::string &host, int port,\n                              const std::string &client_cert_path,\n                              const std::string &client_key_path)\n    : host_(host), port_(port),\n      host_and_port_(adjust_host_string(host) + \":\" + std::to_string(port)),\n      client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}\n\ninline ClientImpl::~ClientImpl() {\n  std::lock_guard<std::mutex> guard(socket_mutex_);\n  shutdown_socket(socket_);\n  close_socket(socket_);\n}\n\ninline bool ClientImpl::is_valid() const { return true; }\n\ninline void ClientImpl::copy_settings(const ClientImpl &rhs) {\n  client_cert_path_ = rhs.client_cert_path_;\n  client_key_path_ = rhs.client_key_path_;\n  connection_timeout_sec_ = rhs.connection_timeout_sec_;\n  read_timeout_sec_ = rhs.read_timeout_sec_;\n  read_timeout_usec_ = rhs.read_timeout_usec_;\n  write_timeout_sec_ = rhs.write_timeout_sec_;\n  write_timeout_usec_ = rhs.write_timeout_usec_;\n  basic_auth_username_ = rhs.basic_auth_username_;\n  basic_auth_password_ = rhs.basic_auth_password_;\n  bearer_token_auth_token_ = rhs.bearer_token_auth_token_;\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n  digest_auth_username_ = rhs.digest_auth_username_;\n  digest_auth_password_ = rhs.digest_auth_password_;\n#endif\n  keep_alive_ = rhs.keep_alive_;\n  follow_location_ = rhs.follow_location_;\n  url_encode_ = rhs.url_encode_;\n  address_family_ = rhs.address_family_;\n  tcp_nodelay_ = rhs.tcp_nodelay_;\n  socket_options_ = rhs.socket_options_;\n  compress_ = rhs.compress_;\n  decompress_ = rhs.decompress_;\n  interface_ = rhs.interface_;\n  proxy_host_ = rhs.proxy_host_;\n  proxy_port_ = rhs.proxy_port_;\n  proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;\n  proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;\n  proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n  proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;\n  proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;\n#endif\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n  ca_cert_file_path_ = rhs.ca_cert_file_path_;\n  ca_cert_dir_path_ = rhs.ca_cert_dir_path_;\n  ca_cert_store_ = rhs.ca_cert_store_;\n#endif\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n  server_certificate_verification_ = rhs.server_certificate_verification_;\n#endif\n  logger_ = rhs.logger_;\n}\n\ninline socket_t ClientImpl::create_client_socket(Error &error) const {\n  if (!proxy_host_.empty() && proxy_port_ != -1) {\n    return detail::create_client_socket(\n        proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,\n        socket_options_, connection_timeout_sec_, connection_timeout_usec_,\n        read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,\n        write_timeout_usec_, interface_, error);\n  }\n\n  // Check is custom IP specified for host_\n  std::string ip;\n  auto it = addr_map_.find(host_);\n  if (it != addr_map_.end()) ip = it->second;\n\n  return detail::create_client_socket(\n      host_, ip, port_, address_family_, tcp_nodelay_, socket_options_,\n      connection_timeout_sec_, connection_timeout_usec_, read_timeout_sec_,\n      read_timeout_usec_, write_timeout_sec_, write_timeout_usec_, interface_,\n      error);\n}\n\ninline bool ClientImpl::create_and_connect_socket(Socket &socket,\n                                                  Error &error) {\n  auto sock = create_client_socket(error);\n  if (sock == INVALID_SOCKET) { return false; }\n  socket.sock = sock;\n  return true;\n}\n\ninline void ClientImpl::shutdown_ssl(Socket & /*socket*/,\n                                     bool /*shutdown_gracefully*/) {\n  // If there are any requests in flight from threads other than us, then it's\n  // a thread-unsafe race because individual ssl* objects are not thread-safe.\n  assert(socket_requests_in_flight_ == 0 ||\n         socket_requests_are_from_thread_ == std::this_thread::get_id());\n}\n\ninline void ClientImpl::shutdown_socket(Socket &socket) {\n  if (socket.sock == INVALID_SOCKET) { return; }\n  detail::shutdown_socket(socket.sock);\n}\n\ninline void ClientImpl::close_socket(Socket &socket) {\n  // If there are requests in flight in another thread, usually closing\n  // the socket will be fine and they will simply receive an error when\n  // using the closed socket, but it is still a bug since rarely the OS\n  // may reassign the socket id to be used for a new socket, and then\n  // suddenly they will be operating on a live socket that is different\n  // than the one they intended!\n  assert(socket_requests_in_flight_ == 0 ||\n         socket_requests_are_from_thread_ == std::this_thread::get_id());\n\n  // It is also a bug if this happens while SSL is still active\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n  assert(socket.ssl == nullptr);\n#endif\n  if (socket.sock == INVALID_SOCKET) { return; }\n  detail::close_socket(socket.sock);\n  socket.sock = INVALID_SOCKET;\n}\n\ninline bool ClientImpl::read_response_line(Stream &strm, const Request &req,\n                                           Response &res) {\n  std::array<char, 2048> buf{};\n\n  detail::stream_line_reader line_reader(strm, buf.data(), buf.size());\n\n  if (!line_reader.getline()) { return false; }\n\n#ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR\n  const static std::regex re(\"(HTTP/1\\\\.[01]) (\\\\d{3})(?: (.*?))?\\r\\n\");\n#else\n  const static std::regex re(\"(HTTP/1\\\\.[01]) (\\\\d{3})(?: (.*?))?\\r?\\n\");\n#endif\n\n  std::cmatch m;\n  if (!std::regex_match(line_reader.ptr(), m, re)) {\n    return req.method == \"CONNECT\";\n  }\n  res.version = std::string(m[1]);\n  res.status = std::stoi(std::string(m[2]));\n  res.reason = std::string(m[3]);\n\n  // Ignore '100 Continue'\n  while (res.status == 100) {\n    if (!line_reader.getline()) { return false; } // CRLF\n    if (!line_reader.getline()) { return false; } // next response line\n\n    if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }\n    res.version = std::string(m[1]);\n    res.status = std::stoi(std::string(m[2]));\n    res.reason = std::string(m[3]);\n  }\n\n  return true;\n}\n\ninline bool ClientImpl::send(Request &req, Response &res, Error &error) {\n  std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);\n  auto ret = send_(req, res, error);\n  if (error == Error::SSLPeerCouldBeClosed_) {\n    assert(!ret);\n    ret = send_(req, res, error);\n  }\n  return ret;\n}\n\ninline bool ClientImpl::send_(Request &req, Response &res, Error &error) {\n  {\n    std::lock_guard<std::mutex> guard(socket_mutex_);\n\n    // Set this to false immediately - if it ever gets set to true by the end of\n    // the request, we know another thread instructed us to close the socket.\n    socket_should_be_closed_when_request_is_done_ = false;\n\n    auto is_alive = false;\n    if (socket_.is_open()) {\n      is_alive = detail::is_socket_alive(socket_.sock);\n      if (!is_alive) {\n        // Attempt to avoid sigpipe by shutting down nongracefully if it seems\n        // like the other side has already closed the connection Also, there\n        // cannot be any requests in flight from other threads since we locked\n        // request_mutex_, so safe to close everything immediately\n        const bool shutdown_gracefully = false;\n        shutdown_ssl(socket_, shutdown_gracefully);\n        shutdown_socket(socket_);\n        close_socket(socket_);\n      }\n    }\n\n    if (!is_alive) {\n      if (!create_and_connect_socket(socket_, error)) { return false; }\n\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n      // TODO: refactoring\n      if (is_ssl()) {\n        auto &scli = static_cast<SSLClient &>(*this);\n        if (!proxy_host_.empty() && proxy_port_ != -1) {\n          auto success = false;\n          if (!scli.connect_with_proxy(socket_, res, success, error)) {\n            return success;\n          }\n        }\n\n        if (!scli.initialize_ssl(socket_, error)) { return false; }\n      }\n#endif\n    }\n\n    // Mark the current socket as being in use so that it cannot be closed by\n    // anyone else while this request is ongoing, even though we will be\n    // releasing the mutex.\n    if (socket_requests_in_flight_ > 1) {\n      assert(socket_requests_are_from_thread_ == std::this_thread::get_id());\n    }\n    socket_requests_in_flight_ += 1;\n    socket_requests_are_from_thread_ = std::this_thread::get_id();\n  }\n\n  for (const auto &header : default_headers_) {\n    if (req.headers.find(header.first) == req.headers.end()) {\n      req.headers.insert(header);\n    }\n  }\n\n  auto ret = false;\n  auto close_connection = !keep_alive_;\n\n  auto se = detail::scope_exit([&]() {\n    // Briefly lock mutex in order to mark that a request is no longer ongoing\n    std::lock_guard<std::mutex> guard(socket_mutex_);\n    socket_requests_in_flight_ -= 1;\n    if (socket_requests_in_flight_ <= 0) {\n      assert(socket_requests_in_flight_ == 0);\n      socket_requests_are_from_thread_ = std::thread::id();\n    }\n\n    if (socket_should_be_closed_when_request_is_done_ || close_connection ||\n        !ret) {\n      shutdown_ssl(socket_, true);\n      shutdown_socket(socket_);\n      close_socket(socket_);\n    }\n  });\n\n  ret = process_socket(socket_, [&](Stream &strm) {\n    return handle_request(strm, req, res, close_connection, error);\n  });\n\n  if (!ret) {\n    if (error == Error::Success) { error = Error::Unknown; }\n  }\n\n  return ret;\n}\n\ninline Result ClientImpl::send(const Request &req) {\n  auto req2 = req;\n  return send_(std::move(req2));\n}\n\ninline Result ClientImpl::send_(Request &&req) {\n  auto res = detail::make_unique<Response>();\n  auto error = Error::Success;\n  auto ret = send(req, *res, error);\n  return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};\n}\n\ninline bool ClientImpl::handle_request(Stream &strm, Request &req,\n                                       Response &res, bool close_connection,\n                                       Error &error) {\n  if (req.path.empty()) {\n    error = Error::Connection;\n    return false;\n  }\n\n  auto req_save = req;\n\n  bool ret;\n\n  if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) {\n    auto req2 = req;\n    req2.path = \"http://\" + host_and_port_ + req.path;\n    ret = process_request(strm, req2, res, close_connection, error);\n    req = req2;\n    req.path = req_save.path;\n  } else {\n    ret = process_request(strm, req, res, close_connection, error);\n  }\n\n  if (!ret) { return false; }\n\n  if (300 < res.status && res.status < 400 && follow_location_) {\n    req = req_save;\n    ret = redirect(req, res, error);\n  }\n\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n  if ((res.status == 401 || res.status == 407) &&\n      req.authorization_count_ < 5) {\n    auto is_proxy = res.status == 407;\n    const auto &username =\n        is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;\n    const auto &password =\n        is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;\n\n    if (!username.empty() && !password.empty()) {\n      std::map<std::string, std::string> auth;\n      if (detail::parse_www_authenticate(res, auth, is_proxy)) {\n        Request new_req = req;\n        new_req.authorization_count_ += 1;\n        new_req.headers.erase(is_proxy ? \"Proxy-Authorization\"\n                                       : \"Authorization\");\n        new_req.headers.insert(detail::make_digest_authentication_header(\n            req, auth, new_req.authorization_count_, detail::random_string(10),\n            username, password, is_proxy));\n\n        Response new_res;\n\n        ret = send(new_req, new_res, error);\n        if (ret) { res = new_res; }\n      }\n    }\n  }\n#endif\n\n  return ret;\n}\n\ninline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {\n  if (req.redirect_count_ == 0) {\n    error = Error::ExceedRedirectCount;\n    return false;\n  }\n\n  auto location = res.get_header_value(\"location\");\n  if (location.empty()) { return false; }\n\n  const static std::regex re(\n      R\"((?:(https?):)?(?://(?:\\[([\\d:]+)\\]|([^:/?#]+))(?::(\\d+))?)?([^?#]*)(\\?[^#]*)?(?:#.*)?)\");\n\n  std::smatch m;\n  if (!std::regex_match(location, m, re)) { return false; }\n\n  auto scheme = is_ssl() ? \"https\" : \"http\";\n\n  auto next_scheme = m[1].str();\n  auto next_host = m[2].str();\n  if (next_host.empty()) { next_host = m[3].str(); }\n  auto port_str = m[4].str();\n  auto next_path = m[5].str();\n  auto next_query = m[6].str();\n\n  auto next_port = port_;\n  if (!port_str.empty()) {\n    next_port = std::stoi(port_str);\n  } else if (!next_scheme.empty()) {\n    next_port = next_scheme == \"https\" ? 443 : 80;\n  }\n\n  if (next_scheme.empty()) { next_scheme = scheme; }\n  if (next_host.empty()) { next_host = host_; }\n  if (next_path.empty()) { next_path = \"/\"; }\n\n  auto path = detail::decode_url(next_path, true) + next_query;\n\n  if (next_scheme == scheme && next_host == host_ && next_port == port_) {\n    return detail::redirect(*this, req, res, path, location, error);\n  } else {\n    if (next_scheme == \"https\") {\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n      SSLClient cli(next_host.c_str(), next_port);\n      cli.copy_settings(*this);\n      if (ca_cert_store_) { cli.set_ca_cert_store(ca_cert_store_); }\n      return detail::redirect(cli, req, res, path, location, error);\n#else\n      return false;\n#endif\n    } else {\n      ClientImpl cli(next_host.c_str(), next_port);\n      cli.copy_settings(*this);\n      return detail::redirect(cli, req, res, path, location, error);\n    }\n  }\n}\n\ninline bool ClientImpl::write_content_with_provider(Stream &strm,\n                                                    const Request &req,\n                                                    Error &error) {\n  auto is_shutting_down = []() { return false; };\n\n  if (req.is_chunked_content_provider_) {\n    // TODO: Brotli support\n    std::unique_ptr<detail::compressor> compressor;\n#ifdef CPPHTTPLIB_ZLIB_SUPPORT\n    if (compress_) {\n      compressor = detail::make_unique<detail::gzip_compressor>();\n    } else\n#endif\n    {\n      compressor = detail::make_unique<detail::nocompressor>();\n    }\n\n    return detail::write_content_chunked(strm, req.content_provider_,\n                                         is_shutting_down, *compressor, error);\n  } else {\n    return detail::write_content(strm, req.content_provider_, 0,\n                                 req.content_length_, is_shutting_down, error);\n  }\n}\n\ninline bool ClientImpl::write_request(Stream &strm, Request &req,\n                                      bool close_connection, Error &error) {\n  // Prepare additional headers\n  if (close_connection) {\n    if (!req.has_header(\"Connection\")) {\n      req.headers.emplace(\"Connection\", \"close\");\n    }\n  }\n\n  if (!req.has_header(\"Host\")) {\n    if (is_ssl()) {\n      if (port_ == 443) {\n        req.headers.emplace(\"Host\", host_);\n      } else {\n        req.headers.emplace(\"Host\", host_and_port_);\n      }\n    } else {\n      if (port_ == 80) {\n        req.headers.emplace(\"Host\", host_);\n      } else {\n        req.headers.emplace(\"Host\", host_and_port_);\n      }\n    }\n  }\n\n  if (!req.has_header(\"Accept\")) { req.headers.emplace(\"Accept\", \"*/*\"); }\n\n#ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT\n  if (!req.has_header(\"User-Agent\")) {\n    auto agent = std::string(\"cpp-httplib/\") + CPPHTTPLIB_VERSION;\n    req.headers.emplace(\"User-Agent\", agent);\n  }\n#endif\n\n  if (req.body.empty()) {\n    if (req.content_provider_) {\n      if (!req.is_chunked_content_provider_) {\n        if (!req.has_header(\"Content-Length\")) {\n          auto length = std::to_string(req.content_length_);\n          req.headers.emplace(\"Content-Length\", length);\n        }\n      }\n    } else {\n      if (req.method == \"POST\" || req.method == \"PUT\" ||\n          req.method == \"PATCH\") {\n        req.headers.emplace(\"Content-Length\", \"0\");\n      }\n    }\n  } else {\n    if (!req.has_header(\"Content-Type\")) {\n      req.headers.emplace(\"Content-Type\", \"text/plain\");\n    }\n\n    if (!req.has_header(\"Content-Length\")) {\n      auto length = std::to_string(req.body.size());\n      req.headers.emplace(\"Content-Length\", length);\n    }\n  }\n\n  if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {\n    if (!req.has_header(\"Authorization\")) {\n      req.headers.insert(make_basic_authentication_header(\n          basic_auth_username_, basic_auth_password_, false));\n    }\n  }\n\n  if (!proxy_basic_auth_username_.empty() &&\n      !proxy_basic_auth_password_.empty()) {\n    if (!req.has_header(\"Proxy-Authorization\")) {\n      req.headers.insert(make_basic_authentication_header(\n          proxy_basic_auth_username_, proxy_basic_auth_password_, true));\n    }\n  }\n\n  if (!bearer_token_auth_token_.empty()) {\n    if (!req.has_header(\"Authorization\")) {\n      req.headers.insert(make_bearer_token_authentication_header(\n          bearer_token_auth_token_, false));\n    }\n  }\n\n  if (!proxy_bearer_token_auth_token_.empty()) {\n    if (!req.has_header(\"Proxy-Authorization\")) {\n      req.headers.insert(make_bearer_token_authentication_header(\n          proxy_bearer_token_auth_token_, true));\n    }\n  }\n\n  // Request line and headers\n  {\n    detail::BufferStream bstrm;\n\n    const auto &path = url_encode_ ? detail::encode_url(req.path) : req.path;\n    bstrm.write_format(\"%s %s HTTP/1.1\\r\\n\", req.method.c_str(), path.c_str());\n\n    detail::write_headers(bstrm, req.headers);\n\n    // Flush buffer\n    auto &data = bstrm.get_buffer();\n    if (!detail::write_data(strm, data.data(), data.size())) {\n      error = Error::Write;\n      return false;\n    }\n  }\n\n  // Body\n  if (req.body.empty()) {\n    return write_content_with_provider(strm, req, error);\n  }\n\n  if (!detail::write_data(strm, req.body.data(), req.body.size())) {\n    error = Error::Write;\n    return false;\n  }\n\n  return true;\n}\n\ninline std::unique_ptr<Response> ClientImpl::send_with_content_provider(\n    Request &req, const char *body, size_t content_length,\n    ContentProvider content_provider,\n    ContentProviderWithoutLength content_provider_without_length,\n    const std::string &content_type, Error &error) {\n  if (!content_type.empty()) {\n    req.headers.emplace(\"Content-Type\", content_type);\n  }\n\n#ifdef CPPHTTPLIB_ZLIB_SUPPORT\n  if (compress_) { req.headers.emplace(\"Content-Encoding\", \"gzip\"); }\n#endif\n\n#ifdef CPPHTTPLIB_ZLIB_SUPPORT\n  if (compress_ && !content_provider_without_length) {\n    // TODO: Brotli support\n    detail::gzip_compressor compressor;\n\n    if (content_provider) {\n      auto ok = true;\n      size_t offset = 0;\n      DataSink data_sink;\n\n      data_sink.write = [&](const char *data, size_t data_len) -> bool {\n        if (ok) {\n          auto last = offset + data_len == content_length;\n\n          auto ret = compressor.compress(\n              data, data_len, last,\n              [&](const char *compressed_data, size_t compressed_data_len) {\n                req.body.append(compressed_data, compressed_data_len);\n                return true;\n              });\n\n          if (ret) {\n            offset += data_len;\n          } else {\n            ok = false;\n          }\n        }\n        return ok;\n      };\n\n      while (ok && offset < content_length) {\n        if (!content_provider(offset, content_length - offset, data_sink)) {\n          error = Error::Canceled;\n          return nullptr;\n        }\n      }\n    } else {\n      if (!compressor.compress(body, content_length, true,\n                               [&](const char *data, size_t data_len) {\n                                 req.body.append(data, data_len);\n                                 return true;\n                               })) {\n        error = Error::Compression;\n        return nullptr;\n      }\n    }\n  } else\n#endif\n  {\n    if (content_provider) {\n      req.content_length_ = content_length;\n      req.content_provider_ = std::move(content_provider);\n      req.is_chunked_content_provider_ = false;\n    } else if (content_provider_without_length) {\n      req.content_length_ = 0;\n      req.content_provider_ = detail::ContentProviderAdapter(\n          std::move(content_provider_without_length));\n      req.is_chunked_content_provider_ = true;\n      req.headers.emplace(\"Transfer-Encoding\", \"chunked\");\n    } else {\n      req.body.assign(body, content_length);\n      ;\n    }\n  }\n\n  auto res = detail::make_unique<Response>();\n  return send(req, *res, error) ? std::move(res) : nullptr;\n}\n\ninline Result ClientImpl::send_with_content_provider(\n    const std::string &method, const std::string &path, const Headers &headers,\n    const char *body, size_t content_length, ContentProvider content_provider,\n    ContentProviderWithoutLength content_provider_without_length,\n    const std::string &content_type) {\n  Request req;\n  req.method = method;\n  req.headers = headers;\n  req.path = path;\n\n  auto error = Error::Success;\n\n  auto res = send_with_content_provider(\n      req, body, content_length, std::move(content_provider),\n      std::move(content_provider_without_length), content_type, error);\n\n  return Result{std::move(res), error, std::move(req.headers)};\n}\n\ninline std::string\nClientImpl::adjust_host_string(const std::string &host) const {\n  if (host.find(':') != std::string::npos) { return \"[\" + host + \"]\"; }\n  return host;\n}\n\ninline bool ClientImpl::process_request(Stream &strm, Request &req,\n                                        Response &res, bool close_connection,\n                                        Error &error) {\n  // Send request\n  if (!write_request(strm, req, close_connection, error)) { return false; }\n\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n  if (is_ssl()) {\n    auto is_proxy_enabled = !proxy_host_.empty() && proxy_port_ != -1;\n    if (!is_proxy_enabled) {\n      char buf[1];\n      if (SSL_peek(socket_.ssl, buf, 1) == 0 &&\n          SSL_get_error(socket_.ssl, 0) == SSL_ERROR_ZERO_RETURN) {\n        error = Error::SSLPeerCouldBeClosed_;\n        return false;\n      }\n    }\n  }\n#endif\n\n  // Receive response and headers\n  if (!read_response_line(strm, req, res) ||\n      !detail::read_headers(strm, res.headers)) {\n    error = Error::Read;\n    return false;\n  }\n\n  // Body\n  if ((res.status != 204) && req.method != \"HEAD\" && req.method != \"CONNECT\") {\n    auto redirect = 300 < res.status && res.status < 400 && follow_location_;\n\n    if (req.response_handler && !redirect) {\n      if (!req.response_handler(res)) {\n        error = Error::Canceled;\n        return false;\n      }\n    }\n\n    auto out =\n        req.content_receiver\n            ? static_cast<ContentReceiverWithProgress>(\n                  [&](const char *buf, size_t n, uint64_t off, uint64_t len) {\n                    if (redirect) { return true; }\n                    auto ret = req.content_receiver(buf, n, off, len);\n                    if (!ret) { error = Error::Canceled; }\n                    return ret;\n                  })\n            : static_cast<ContentReceiverWithProgress>(\n                  [&](const char *buf, size_t n, uint64_t /*off*/,\n                      uint64_t /*len*/) {\n                    if (res.body.size() + n > res.body.max_size()) {\n                      return false;\n                    }\n                    res.body.append(buf, n);\n                    return true;\n                  });\n\n    auto progress = [&](uint64_t current, uint64_t total) {\n      if (!req.progress || redirect) { return true; }\n      auto ret = req.progress(current, total);\n      if (!ret) { error = Error::Canceled; }\n      return ret;\n    };\n\n    int dummy_status;\n    if (!detail::read_content(strm, res, (std::numeric_limits<size_t>::max)(),\n                              dummy_status, std::move(progress), std::move(out),\n                              decompress_)) {\n      if (error != Error::Canceled) { error = Error::Read; }\n      return false;\n    }\n  }\n\n  if (res.get_header_value(\"Connection\") == \"close\" ||\n      (res.version == \"HTTP/1.0\" && res.reason != \"Connection established\")) {\n    // TODO this requires a not-entirely-obvious chain of calls to be correct\n    // for this to be safe. Maybe a code refactor (such as moving this out to\n    // the send function and getting rid of the recursiveness of the mutex)\n    // could make this more obvious.\n\n    // This is safe to call because process_request is only called by\n    // handle_request which is only called by send, which locks the request\n    // mutex during the process. It would be a bug to call it from a different\n    // thread since it's a thread-safety issue to do these things to the socket\n    // if another thread is using the socket.\n    std::lock_guard<std::mutex> guard(socket_mutex_);\n    shutdown_ssl(socket_, true);\n    shutdown_socket(socket_);\n    close_socket(socket_);\n  }\n\n  // Log\n  if (logger_) { logger_(req, res); }\n\n  return true;\n}\n\ninline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(\n    const std::string &boundary, const MultipartFormDataItems &items,\n    const MultipartFormDataProviderItems &provider_items) {\n  size_t cur_item = 0, cur_start = 0;\n  // cur_item and cur_start are copied to within the std::function and maintain\n  // state between successive calls\n  return [&, cur_item, cur_start](size_t offset,\n                                  DataSink &sink) mutable -> bool {\n    if (!offset && items.size()) {\n      sink.os << detail::serialize_multipart_formdata(items, boundary, false);\n      return true;\n    } else if (cur_item < provider_items.size()) {\n      if (!cur_start) {\n        const auto &begin = detail::serialize_multipart_formdata_item_begin(\n            provider_items[cur_item], boundary);\n        offset += begin.size();\n        cur_start = offset;\n        sink.os << begin;\n      }\n\n      DataSink cur_sink;\n      bool has_data = true;\n      cur_sink.write = sink.write;\n      cur_sink.done = [&]() { has_data = false; };\n\n      if (!provider_items[cur_item].provider(offset - cur_start, cur_sink))\n        return false;\n\n      if (!has_data) {\n        sink.os << detail::serialize_multipart_formdata_item_end();\n        cur_item++;\n        cur_start = 0;\n      }\n      return true;\n    } else {\n      sink.os << detail::serialize_multipart_formdata_finish(boundary);\n      sink.done();\n      return true;\n    }\n  };\n}\n\ninline bool\nClientImpl::process_socket(const Socket &socket,\n                           std::function<bool(Stream &strm)> callback) {\n  return detail::process_client_socket(\n      socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,\n      write_timeout_usec_, std::move(callback));\n}\n\ninline bool ClientImpl::is_ssl() const { return false; }\n\ninline Result ClientImpl::Get(const std::string &path) {\n  return Get(path, Headers(), Progress());\n}\n\ninline Result ClientImpl::Get(const std::string &path, Progress progress) {\n  return Get(path, Headers(), std::move(progress));\n}\n\ninline Result ClientImpl::Get(const std::string &path, const Headers &headers) {\n  return Get(path, headers, Progress());\n}\n\ninline Result ClientImpl::Get(const std::string &path, const Headers &headers,\n                              Progress progress) {\n  Request req;\n  req.method = \"GET\";\n  req.path = path;\n  req.headers = headers;\n  req.progress = std::move(progress);\n\n  return send_(std::move(req));\n}\n\ninline Result ClientImpl::Get(const std::string &path,\n                              ContentReceiver content_receiver) {\n  return Get(path, Headers(), nullptr, std::move(content_receiver), nullptr);\n}\n\ninline Result ClientImpl::Get(const std::string &path,\n                              ContentReceiver content_receiver,\n                              Progress progress) {\n  return Get(path, Headers(), nullptr, std::move(content_receiver),\n             std::move(progress));\n}\n\ninline Result ClientImpl::Get(const std::string &path, const Headers &headers,\n                              ContentReceiver content_receiver) {\n  return Get(path, headers, nullptr, std::move(content_receiver), nullptr);\n}\n\ninline Result ClientImpl::Get(const std::string &path, const Headers &headers,\n                              ContentReceiver content_receiver,\n                              Progress progress) {\n  return Get(path, headers, nullptr, std::move(content_receiver),\n             std::move(progress));\n}\n\ninline Result ClientImpl::Get(const std::string &path,\n                              ResponseHandler response_handler,\n                              ContentReceiver content_receiver) {\n  return Get(path, Headers(), std::move(response_handler),\n             std::move(content_receiver), nullptr);\n}\n\ninline Result ClientImpl::Get(const std::string &path, const Headers &headers,\n                              ResponseHandler response_handler,\n                              ContentReceiver content_receiver) {\n  return Get(path, headers, std::move(response_handler),\n             std::move(content_receiver), nullptr);\n}\n\ninline Result ClientImpl::Get(const std::string &path,\n                              ResponseHandler response_handler,\n                              ContentReceiver content_receiver,\n                              Progress progress) {\n  return Get(path, Headers(), std::move(response_handler),\n             std::move(content_receiver), std::move(progress));\n}\n\ninline Result ClientImpl::Get(const std::string &path, const Headers &headers,\n                              ResponseHandler response_handler,\n                              ContentReceiver content_receiver,\n                              Progress progress) {\n  Request req;\n  req.method = \"GET\";\n  req.path = path;\n  req.headers = headers;\n  req.response_handler = std::move(response_handler);\n  req.content_receiver =\n      [content_receiver](const char *data, size_t data_length,\n                         uint64_t /*offset*/, uint64_t /*total_length*/) {\n        return content_receiver(data, data_length);\n      };\n  req.progress = std::move(progress);\n\n  return send_(std::move(req));\n}\n\ninline Result ClientImpl::Get(const std::string &path, const Params &params,\n                              const Headers &headers, Progress progress) {\n  if (params.empty()) { return Get(path, headers); }\n\n  std::string path_with_query = append_query_params(path, params);\n  return Get(path_with_query.c_str(), headers, progress);\n}\n\ninline Result ClientImpl::Get(const std::string &path, const Params &params,\n                              const Headers &headers,\n                              ContentReceiver content_receiver,\n                              Progress progress) {\n  return Get(path, params, headers, nullptr, content_receiver, progress);\n}\n\ninline Result ClientImpl::Get(const std::string &path, const Params &params,\n                              const Headers &headers,\n                              ResponseHandler response_handler,\n                              ContentReceiver content_receiver,\n                              Progress progress) {\n  if (params.empty()) {\n    return Get(path, headers, response_handler, content_receiver, progress);\n  }\n\n  std::string path_with_query = append_query_params(path, params);\n  return Get(path_with_query.c_str(), headers, response_handler,\n             content_receiver, progress);\n}\n\ninline Result ClientImpl::Head(const std::string &path) {\n  return Head(path, Headers());\n}\n\ninline Result ClientImpl::Head(const std::string &path,\n                               const Headers &headers) {\n  Request req;\n  req.method = \"HEAD\";\n  req.headers = headers;\n  req.path = path;\n\n  return send_(std::move(req));\n}\n\ninline Result ClientImpl::Post(const std::string &path) {\n  return Post(path, std::string(), std::string());\n}\n\ninline Result ClientImpl::Post(const std::string &path,\n                               const Headers &headers) {\n  return Post(path, headers, nullptr, 0, std::string());\n}\n\ninline Result ClientImpl::Post(const std::string &path, const char *body,\n                               size_t content_length,\n                               const std::string &content_type) {\n  return Post(path, Headers(), body, content_length, content_type);\n}\n\ninline Result ClientImpl::Post(const std::string &path, const Headers &headers,\n                               const char *body, size_t content_length,\n                               const std::string &content_type) {\n  return send_with_content_provider(\"POST\", path, headers, body, content_length,\n                                    nullptr, nullptr, content_type);\n}\n\ninline Result ClientImpl::Post(const std::string &path, const std::string &body,\n                               const std::string &content_type) {\n  return Post(path, Headers(), body, content_type);\n}\n\ninline Result ClientImpl::Post(const std::string &path, const Headers &headers,\n                               const std::string &body,\n                               const std::string &content_type) {\n  return send_with_content_provider(\"POST\", path, headers, body.data(),\n                                    body.size(), nullptr, nullptr,\n                                    content_type);\n}\n\ninline Result ClientImpl::Post(const std::string &path, const Params &params) {\n  return Post(path, Headers(), params);\n}\n\ninline Result ClientImpl::Post(const std::string &path, size_t content_length,\n                               ContentProvider content_provider,\n                               const std::string &content_type) {\n  return Post(path, Headers(), content_length, std::move(content_provider),\n              content_type);\n}\n\ninline Result ClientImpl::Post(const std::string &path,\n                               ContentProviderWithoutLength content_provider,\n                               const std::string &content_type) {\n  return Post(path, Headers(), std::move(content_provider), content_type);\n}\n\ninline Result ClientImpl::Post(const std::string &path, const Headers &headers,\n                               size_t content_length,\n                               ContentProvider content_provider,\n                               const std::string &content_type) {\n  return send_with_content_provider(\"POST\", path, headers, nullptr,\n                                    content_length, std::move(content_provider),\n                                    nullptr, content_type);\n}\n\ninline Result ClientImpl::Post(const std::string &path, const Headers &headers,\n                               ContentProviderWithoutLength content_provider,\n                               const std::string &content_type) {\n  return send_with_content_provider(\"POST\", path, headers, nullptr, 0, nullptr,\n                                    std::move(content_provider), content_type);\n}\n\ninline Result ClientImpl::Post(const std::string &path, const Headers &headers,\n                               const Params &params) {\n  auto query = detail::params_to_query_str(params);\n  return Post(path, headers, query, \"application/x-www-form-urlencoded\");\n}\n\ninline Result ClientImpl::Post(const std::string &path,\n                               const MultipartFormDataItems &items) {\n  return Post(path, Headers(), items);\n}\n\ninline Result ClientImpl::Post(const std::string &path, const Headers &headers,\n                               const MultipartFormDataItems &items) {\n  const auto &boundary = detail::make_multipart_data_boundary();\n  const auto &content_type =\n      detail::serialize_multipart_formdata_get_content_type(boundary);\n  const auto &body = detail::serialize_multipart_formdata(items, boundary);\n  return Post(path, headers, body, content_type.c_str());\n}\n\ninline Result ClientImpl::Post(const std::string &path, const Headers &headers,\n                               const MultipartFormDataItems &items,\n                               const std::string &boundary) {\n  if (!detail::is_multipart_boundary_chars_valid(boundary)) {\n    return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};\n  }\n\n  const auto &content_type =\n      detail::serialize_multipart_formdata_get_content_type(boundary);\n  const auto &body = detail::serialize_multipart_formdata(items, boundary);\n  return Post(path, headers, body, content_type.c_str());\n}\n\ninline Result\nClientImpl::Post(const std::string &path, const Headers &headers,\n                 const MultipartFormDataItems &items,\n                 const MultipartFormDataProviderItems &provider_items) {\n  const auto &boundary = detail::make_multipart_data_boundary();\n  const auto &content_type =\n      detail::serialize_multipart_formdata_get_content_type(boundary);\n  return send_with_content_provider(\n      \"POST\", path, headers, nullptr, 0, nullptr,\n      get_multipart_content_provider(boundary, items, provider_items),\n      content_type);\n}\n\ninline Result ClientImpl::Put(const std::string &path) {\n  return Put(path, std::string(), std::string());\n}\n\ninline Result ClientImpl::Put(const std::string &path, const char *body,\n                              size_t content_length,\n                              const std::string &content_type) {\n  return Put(path, Headers(), body, content_length, content_type);\n}\n\ninline Result ClientImpl::Put(const std::string &path, const Headers &headers,\n                              const char *body, size_t content_length,\n                              const std::string &content_type) {\n  return send_with_content_provider(\"PUT\", path, headers, body, content_length,\n                                    nullptr, nullptr, content_type);\n}\n\ninline Result ClientImpl::Put(const std::string &path, const std::string &body,\n                              const std::string &content_type) {\n  return Put(path, Headers(), body, content_type);\n}\n\ninline Result ClientImpl::Put(const std::string &path, const Headers &headers,\n                              const std::string &body,\n                              const std::string &content_type) {\n  return send_with_content_provider(\"PUT\", path, headers, body.data(),\n                                    body.size(), nullptr, nullptr,\n                                    content_type);\n}\n\ninline Result ClientImpl::Put(const std::string &path, size_t content_length,\n                              ContentProvider content_provider,\n                              const std::string &content_type) {\n  return Put(path, Headers(), content_length, std::move(content_provider),\n             content_type);\n}\n\ninline Result ClientImpl::Put(const std::string &path,\n                              ContentProviderWithoutLength content_provider,\n                              const std::string &content_type) {\n  return Put(path, Headers(), std::move(content_provider), content_type);\n}\n\ninline Result ClientImpl::Put(const std::string &path, const Headers &headers,\n                              size_t content_length,\n                              ContentProvider content_provider,\n                              const std::string &content_type) {\n  return send_with_content_provider(\"PUT\", path, headers, nullptr,\n                                    content_length, std::move(content_provider),\n                                    nullptr, content_type);\n}\n\ninline Result ClientImpl::Put(const std::string &path, const Headers &headers,\n                              ContentProviderWithoutLength content_provider,\n                              const std::string &content_type) {\n  return send_with_content_provider(\"PUT\", path, headers, nullptr, 0, nullptr,\n                                    std::move(content_provider), content_type);\n}\n\ninline Result ClientImpl::Put(const std::string &path, const Params &params) {\n  return Put(path, Headers(), params);\n}\n\ninline Result ClientImpl::Put(const std::string &path, const Headers &headers,\n                              const Params &params) {\n  auto query = detail::params_to_query_str(params);\n  return Put(path, headers, query, \"application/x-www-form-urlencoded\");\n}\n\ninline Result ClientImpl::Put(const std::string &path,\n                              const MultipartFormDataItems &items) {\n  return Put(path, Headers(), items);\n}\n\ninline Result ClientImpl::Put(const std::string &path, const Headers &headers,\n                              const MultipartFormDataItems &items) {\n  const auto &boundary = detail::make_multipart_data_boundary();\n  const auto &content_type =\n      detail::serialize_multipart_formdata_get_content_type(boundary);\n  const auto &body = detail::serialize_multipart_formdata(items, boundary);\n  return Put(path, headers, body, content_type);\n}\n\ninline Result ClientImpl::Put(const std::string &path, const Headers &headers,\n                              const MultipartFormDataItems &items,\n                              const std::string &boundary) {\n  if (!detail::is_multipart_boundary_chars_valid(boundary)) {\n    return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};\n  }\n\n  const auto &content_type =\n      detail::serialize_multipart_formdata_get_content_type(boundary);\n  const auto &body = detail::serialize_multipart_formdata(items, boundary);\n  return Put(path, headers, body, content_type);\n}\n\ninline Result\nClientImpl::Put(const std::string &path, const Headers &headers,\n                const MultipartFormDataItems &items,\n                const MultipartFormDataProviderItems &provider_items) {\n  const auto &boundary = detail::make_multipart_data_boundary();\n  const auto &content_type =\n      detail::serialize_multipart_formdata_get_content_type(boundary);\n  return send_with_content_provider(\n      \"PUT\", path, headers, nullptr, 0, nullptr,\n      get_multipart_content_provider(boundary, items, provider_items),\n      content_type);\n}\ninline Result ClientImpl::Patch(const std::string &path) {\n  return Patch(path, std::string(), std::string());\n}\n\ninline Result ClientImpl::Patch(const std::string &path, const char *body,\n                                size_t content_length,\n                                const std::string &content_type) {\n  return Patch(path, Headers(), body, content_length, content_type);\n}\n\ninline Result ClientImpl::Patch(const std::string &path, const Headers &headers,\n                                const char *body, size_t content_length,\n                                const std::string &content_type) {\n  return send_with_content_provider(\"PATCH\", path, headers, body,\n                                    content_length, nullptr, nullptr,\n                                    content_type);\n}\n\ninline Result ClientImpl::Patch(const std::string &path,\n                                const std::string &body,\n                                const std::string &content_type) {\n  return Patch(path, Headers(), body, content_type);\n}\n\ninline Result ClientImpl::Patch(const std::string &path, const Headers &headers,\n                                const std::string &body,\n                                const std::string &content_type) {\n  return send_with_content_provider(\"PATCH\", path, headers, body.data(),\n                                    body.size(), nullptr, nullptr,\n                                    content_type);\n}\n\ninline Result ClientImpl::Patch(const std::string &path, size_t content_length,\n                                ContentProvider content_provider,\n                                const std::string &content_type) {\n  return Patch(path, Headers(), content_length, std::move(content_provider),\n               content_type);\n}\n\ninline Result ClientImpl::Patch(const std::string &path,\n                                ContentProviderWithoutLength content_provider,\n                                const std::string &content_type) {\n  return Patch(path, Headers(), std::move(content_provider), content_type);\n}\n\ninline Result ClientImpl::Patch(const std::string &path, const Headers &headers,\n                                size_t content_length,\n                                ContentProvider content_provider,\n                                const std::string &content_type) {\n  return send_with_content_provider(\"PATCH\", path, headers, nullptr,\n                                    content_length, std::move(content_provider),\n                                    nullptr, content_type);\n}\n\ninline Result ClientImpl::Patch(const std::string &path, const Headers &headers,\n                                ContentProviderWithoutLength content_provider,\n                                const std::string &content_type) {\n  return send_with_content_provider(\"PATCH\", path, headers, nullptr, 0, nullptr,\n                                    std::move(content_provider), content_type);\n}\n\ninline Result ClientImpl::Delete(const std::string &path) {\n  return Delete(path, Headers(), std::string(), std::string());\n}\n\ninline Result ClientImpl::Delete(const std::string &path,\n                                 const Headers &headers) {\n  return Delete(path, headers, std::string(), std::string());\n}\n\ninline Result ClientImpl::Delete(const std::string &path, const char *body,\n                                 size_t content_length,\n                                 const std::string &content_type) {\n  return Delete(path, Headers(), body, content_length, content_type);\n}\n\ninline Result ClientImpl::Delete(const std::string &path,\n                                 const Headers &headers, const char *body,\n                                 size_t content_length,\n                                 const std::string &content_type) {\n  Request req;\n  req.method = \"DELETE\";\n  req.headers = headers;\n  req.path = path;\n\n  if (!content_type.empty()) {\n    req.headers.emplace(\"Content-Type\", content_type);\n  }\n  req.body.assign(body, content_length);\n\n  return send_(std::move(req));\n}\n\ninline Result ClientImpl::Delete(const std::string &path,\n                                 const std::string &body,\n                                 const std::string &content_type) {\n  return Delete(path, Headers(), body.data(), body.size(), content_type);\n}\n\ninline Result ClientImpl::Delete(const std::string &path,\n                                 const Headers &headers,\n                                 const std::string &body,\n                                 const std::string &content_type) {\n  return Delete(path, headers, body.data(), body.size(), content_type);\n}\n\ninline Result ClientImpl::Options(const std::string &path) {\n  return Options(path, Headers());\n}\n\ninline Result ClientImpl::Options(const std::string &path,\n                                  const Headers &headers) {\n  Request req;\n  req.method = \"OPTIONS\";\n  req.headers = headers;\n  req.path = path;\n\n  return send_(std::move(req));\n}\n\ninline size_t ClientImpl::is_socket_open() const {\n  std::lock_guard<std::mutex> guard(socket_mutex_);\n  return socket_.is_open();\n}\n\ninline socket_t ClientImpl::socket() const { return socket_.sock; }\n\ninline void ClientImpl::stop() {\n  std::lock_guard<std::mutex> guard(socket_mutex_);\n\n  // If there is anything ongoing right now, the ONLY thread-safe thing we can\n  // do is to shutdown_socket, so that threads using this socket suddenly\n  // discover they can't read/write any more and error out. Everything else\n  // (closing the socket, shutting ssl down) is unsafe because these actions are\n  // not thread-safe.\n  if (socket_requests_in_flight_ > 0) {\n    shutdown_socket(socket_);\n\n    // Aside from that, we set a flag for the socket to be closed when we're\n    // done.\n    socket_should_be_closed_when_request_is_done_ = true;\n    return;\n  }\n\n  // Otherwise, still holding the mutex, we can shut everything down ourselves\n  shutdown_ssl(socket_, true);\n  shutdown_socket(socket_);\n  close_socket(socket_);\n}\n\ninline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {\n  connection_timeout_sec_ = sec;\n  connection_timeout_usec_ = usec;\n}\n\ninline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {\n  read_timeout_sec_ = sec;\n  read_timeout_usec_ = usec;\n}\n\ninline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {\n  write_timeout_sec_ = sec;\n  write_timeout_usec_ = usec;\n}\n\ninline void ClientImpl::set_basic_auth(const std::string &username,\n                                       const std::string &password) {\n  basic_auth_username_ = username;\n  basic_auth_password_ = password;\n}\n\ninline void ClientImpl::set_bearer_token_auth(const std::string &token) {\n  bearer_token_auth_token_ = token;\n}\n\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\ninline void ClientImpl::set_digest_auth(const std::string &username,\n                                        const std::string &password) {\n  digest_auth_username_ = username;\n  digest_auth_password_ = password;\n}\n#endif\n\ninline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }\n\ninline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }\n\ninline void ClientImpl::set_url_encode(bool on) { url_encode_ = on; }\n\ninline void\nClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {\n  addr_map_ = std::move(addr_map);\n}\n\ninline void ClientImpl::set_default_headers(Headers headers) {\n  default_headers_ = std::move(headers);\n}\n\ninline void ClientImpl::set_address_family(int family) {\n  address_family_ = family;\n}\n\ninline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }\n\ninline void ClientImpl::set_socket_options(SocketOptions socket_options) {\n  socket_options_ = std::move(socket_options);\n}\n\ninline void ClientImpl::set_compress(bool on) { compress_ = on; }\n\ninline void ClientImpl::set_decompress(bool on) { decompress_ = on; }\n\ninline void ClientImpl::set_interface(const std::string &intf) {\n  interface_ = intf;\n}\n\ninline void ClientImpl::set_proxy(const std::string &host, int port) {\n  proxy_host_ = host;\n  proxy_port_ = port;\n}\n\ninline void ClientImpl::set_proxy_basic_auth(const std::string &username,\n                                             const std::string &password) {\n  proxy_basic_auth_username_ = username;\n  proxy_basic_auth_password_ = password;\n}\n\ninline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {\n  proxy_bearer_token_auth_token_ = token;\n}\n\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\ninline void ClientImpl::set_proxy_digest_auth(const std::string &username,\n                                              const std::string &password) {\n  proxy_digest_auth_username_ = username;\n  proxy_digest_auth_password_ = password;\n}\n#endif\n\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\ninline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,\n                                         const std::string &ca_cert_dir_path) {\n  ca_cert_file_path_ = ca_cert_file_path;\n  ca_cert_dir_path_ = ca_cert_dir_path;\n}\n\ninline void ClientImpl::set_ca_cert_store(X509_STORE *ca_cert_store) {\n  if (ca_cert_store && ca_cert_store != ca_cert_store_) {\n    ca_cert_store_ = ca_cert_store;\n  }\n}\n#endif\n\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\ninline void ClientImpl::enable_server_certificate_verification(bool enabled) {\n  server_certificate_verification_ = enabled;\n}\n#endif\n\ninline void ClientImpl::set_logger(Logger logger) {\n  logger_ = std::move(logger);\n}\n\n/*\n * SSL Implementation\n */\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\nnamespace detail {\n\ntemplate <typename U, typename V>\ninline SSL *ssl_new(socket_t sock, SSL_CTX *ctx, std::mutex &ctx_mutex,\n                    U SSL_connect_or_accept, V setup) {\n  SSL *ssl = nullptr;\n  {\n    std::lock_guard<std::mutex> guard(ctx_mutex);\n    ssl = SSL_new(ctx);\n  }\n\n  if (ssl) {\n    set_nonblocking(sock, true);\n    auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);\n    BIO_set_nbio(bio, 1);\n    SSL_set_bio(ssl, bio, bio);\n\n    if (!setup(ssl) || SSL_connect_or_accept(ssl) != 1) {\n      SSL_shutdown(ssl);\n      {\n        std::lock_guard<std::mutex> guard(ctx_mutex);\n        SSL_free(ssl);\n      }\n      set_nonblocking(sock, false);\n      return nullptr;\n    }\n    BIO_set_nbio(bio, 0);\n    set_nonblocking(sock, false);\n  }\n\n  return ssl;\n}\n\ninline void ssl_delete(std::mutex &ctx_mutex, SSL *ssl,\n                       bool shutdown_gracefully) {\n  // sometimes we may want to skip this to try to avoid SIGPIPE if we know\n  // the remote has closed the network connection\n  // Note that it is not always possible to avoid SIGPIPE, this is merely a\n  // best-efforts.\n  if (shutdown_gracefully) { SSL_shutdown(ssl); }\n\n  std::lock_guard<std::mutex> guard(ctx_mutex);\n  SSL_free(ssl);\n}\n\ntemplate <typename U>\nbool ssl_connect_or_accept_nonblocking(socket_t sock, SSL *ssl,\n                                       U ssl_connect_or_accept,\n                                       time_t timeout_sec,\n                                       time_t timeout_usec) {\n  int res = 0;\n  while ((res = ssl_connect_or_accept(ssl)) != 1) {\n    auto err = SSL_get_error(ssl, res);\n    switch (err) {\n    case SSL_ERROR_WANT_READ:\n      if (select_read(sock, timeout_sec, timeout_usec) > 0) { continue; }\n      break;\n    case SSL_ERROR_WANT_WRITE:\n      if (select_write(sock, timeout_sec, timeout_usec) > 0) { continue; }\n      break;\n    default: break;\n    }\n    return false;\n  }\n  return true;\n}\n\ntemplate <typename T>\ninline bool process_server_socket_ssl(\n    const std::atomic<socket_t> &svr_sock, SSL *ssl, socket_t sock,\n    size_t keep_alive_max_count, time_t keep_alive_timeout_sec,\n    time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,\n    time_t write_timeout_usec, T callback) {\n  return process_server_socket_core(\n      svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,\n      [&](bool close_connection, bool &connection_closed) {\n        SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,\n                             write_timeout_sec, write_timeout_usec);\n        return callback(strm, close_connection, connection_closed);\n      });\n}\n\ntemplate <typename T>\ninline bool\nprocess_client_socket_ssl(SSL *ssl, socket_t sock, time_t read_timeout_sec,\n                          time_t read_timeout_usec, time_t write_timeout_sec,\n                          time_t write_timeout_usec, T callback) {\n  SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,\n                       write_timeout_sec, write_timeout_usec);\n  return callback(strm);\n}\n\nclass SSLInit {\npublic:\n  SSLInit() {\n    OPENSSL_init_ssl(\n        OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);\n  }\n};\n\n// SSL socket stream implementation\ninline SSLSocketStream::SSLSocketStream(socket_t sock, SSL *ssl,\n                                        time_t read_timeout_sec,\n                                        time_t read_timeout_usec,\n                                        time_t write_timeout_sec,\n                                        time_t write_timeout_usec)\n    : sock_(sock), ssl_(ssl), read_timeout_sec_(read_timeout_sec),\n      read_timeout_usec_(read_timeout_usec),\n      write_timeout_sec_(write_timeout_sec),\n      write_timeout_usec_(write_timeout_usec) {\n  SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);\n}\n\ninline SSLSocketStream::~SSLSocketStream() {}\n\ninline bool SSLSocketStream::is_readable() const {\n  return detail::select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;\n}\n\ninline bool SSLSocketStream::is_writable() const {\n  return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&\n         is_socket_alive(sock_);\n}\n\ninline ssize_t SSLSocketStream::read(char *ptr, size_t size) {\n  if (SSL_pending(ssl_) > 0) {\n    return SSL_read(ssl_, ptr, static_cast<int>(size));\n  } else if (is_readable()) {\n    auto ret = SSL_read(ssl_, ptr, static_cast<int>(size));\n    if (ret < 0) {\n      auto err = SSL_get_error(ssl_, ret);\n      int n = 1000;\n#ifdef _WIN32\n      while (--n >= 0 && (err == SSL_ERROR_WANT_READ ||\n                          (err == SSL_ERROR_SYSCALL &&\n                           WSAGetLastError() == WSAETIMEDOUT))) {\n#else\n      while (--n >= 0 && err == SSL_ERROR_WANT_READ) {\n#endif\n        if (SSL_pending(ssl_) > 0) {\n          return SSL_read(ssl_, ptr, static_cast<int>(size));\n        } else if (is_readable()) {\n          std::this_thread::sleep_for(std::chrono::milliseconds(1));\n          ret = SSL_read(ssl_, ptr, static_cast<int>(size));\n          if (ret >= 0) { return ret; }\n          err = SSL_get_error(ssl_, ret);\n        } else {\n          return -1;\n        }\n      }\n    }\n    return ret;\n  }\n  return -1;\n}\n\ninline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {\n  if (is_writable()) {\n    auto handle_size = static_cast<int>(\n        std::min<size_t>(size, (std::numeric_limits<int>::max)()));\n\n    auto ret = SSL_write(ssl_, ptr, static_cast<int>(handle_size));\n    if (ret < 0) {\n      auto err = SSL_get_error(ssl_, ret);\n      int n = 1000;\n#ifdef _WIN32\n      while (--n >= 0 && (err == SSL_ERROR_WANT_WRITE ||\n                          (err == SSL_ERROR_SYSCALL &&\n                           WSAGetLastError() == WSAETIMEDOUT))) {\n#else\n      while (--n >= 0 && err == SSL_ERROR_WANT_WRITE) {\n#endif\n        if (is_writable()) {\n          std::this_thread::sleep_for(std::chrono::milliseconds(1));\n          ret = SSL_write(ssl_, ptr, static_cast<int>(handle_size));\n          if (ret >= 0) { return ret; }\n          err = SSL_get_error(ssl_, ret);\n        } else {\n          return -1;\n        }\n      }\n    }\n    return ret;\n  }\n  return -1;\n}\n\ninline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,\n                                                    int &port) const {\n  detail::get_remote_ip_and_port(sock_, ip, port);\n}\n\ninline void SSLSocketStream::get_local_ip_and_port(std::string &ip,\n                                                   int &port) const {\n  detail::get_local_ip_and_port(sock_, ip, port);\n}\n\ninline socket_t SSLSocketStream::socket() const { return sock_; }\n\nstatic SSLInit sslinit_;\n\n} // namespace detail\n\n// SSL HTTP server implementation\ninline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,\n                            const char *client_ca_cert_file_path,\n                            const char *client_ca_cert_dir_path,\n                            const char *private_key_password) {\n  ctx_ = SSL_CTX_new(TLS_server_method());\n\n  if (ctx_) {\n    SSL_CTX_set_options(ctx_,\n                        SSL_OP_NO_COMPRESSION |\n                            SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);\n\n    SSL_CTX_set_min_proto_version(ctx_, TLS1_1_VERSION);\n\n    // add default password callback before opening encrypted private key\n    if (private_key_password != nullptr && (private_key_password[0] != '\\0')) {\n      SSL_CTX_set_default_passwd_cb_userdata(ctx_,\n                                             (char *)private_key_password);\n    }\n\n    if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 ||\n        SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) !=\n            1) {\n      SSL_CTX_free(ctx_);\n      ctx_ = nullptr;\n    } else if (client_ca_cert_file_path || client_ca_cert_dir_path) {\n      SSL_CTX_load_verify_locations(ctx_, client_ca_cert_file_path,\n                                    client_ca_cert_dir_path);\n\n      SSL_CTX_set_verify(\n          ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);\n    }\n  }\n}\n\ninline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key,\n                            X509_STORE *client_ca_cert_store) {\n  ctx_ = SSL_CTX_new(TLS_server_method());\n\n  if (ctx_) {\n    SSL_CTX_set_options(ctx_,\n                        SSL_OP_NO_COMPRESSION |\n                            SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);\n\n    SSL_CTX_set_min_proto_version(ctx_, TLS1_1_VERSION);\n\n    if (SSL_CTX_use_certificate(ctx_, cert) != 1 ||\n        SSL_CTX_use_PrivateKey(ctx_, private_key) != 1) {\n      SSL_CTX_free(ctx_);\n      ctx_ = nullptr;\n    } else if (client_ca_cert_store) {\n      SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);\n\n      SSL_CTX_set_verify(\n          ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);\n    }\n  }\n}\n\ninline SSLServer::SSLServer(\n    const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback) {\n  ctx_ = SSL_CTX_new(TLS_method());\n  if (ctx_) {\n    if (!setup_ssl_ctx_callback(*ctx_)) {\n      SSL_CTX_free(ctx_);\n      ctx_ = nullptr;\n    }\n  }\n}\n\ninline SSLServer::~SSLServer() {\n  if (ctx_) { SSL_CTX_free(ctx_); }\n}\n\ninline bool SSLServer::is_valid() const { return ctx_; }\n\ninline SSL_CTX *SSLServer::ssl_context() const { return ctx_; }\n\ninline bool SSLServer::process_and_close_socket(socket_t sock) {\n  auto ssl = detail::ssl_new(\n      sock, ctx_, ctx_mutex_,\n      [&](SSL *ssl2) {\n        return detail::ssl_connect_or_accept_nonblocking(\n            sock, ssl2, SSL_accept, read_timeout_sec_, read_timeout_usec_);\n      },\n      [](SSL * /*ssl2*/) { return true; });\n\n  auto ret = false;\n  if (ssl) {\n    ret = detail::process_server_socket_ssl(\n        svr_sock_, ssl, sock, keep_alive_max_count_, keep_alive_timeout_sec_,\n        read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,\n        write_timeout_usec_,\n        [this, ssl](Stream &strm, bool close_connection,\n                    bool &connection_closed) {\n          return process_request(strm, close_connection, connection_closed,\n                                 [&](Request &req) { req.ssl = ssl; });\n        });\n\n    // Shutdown gracefully if the result seemed successful, non-gracefully if\n    // the connection appeared to be closed.\n    const bool shutdown_gracefully = ret;\n    detail::ssl_delete(ctx_mutex_, ssl, shutdown_gracefully);\n  }\n\n  detail::shutdown_socket(sock);\n  detail::close_socket(sock);\n  return ret;\n}\n\n// SSL HTTP client implementation\ninline SSLClient::SSLClient(const std::string &host)\n    : SSLClient(host, 443, std::string(), std::string()) {}\n\ninline SSLClient::SSLClient(const std::string &host, int port)\n    : SSLClient(host, port, std::string(), std::string()) {}\n\ninline SSLClient::SSLClient(const std::string &host, int port,\n                            const std::string &client_cert_path,\n                            const std::string &client_key_path)\n    : ClientImpl(host, port, client_cert_path, client_key_path) {\n  ctx_ = SSL_CTX_new(TLS_client_method());\n\n  detail::split(&host_[0], &host_[host_.size()], '.',\n                [&](const char *b, const char *e) {\n                  host_components_.emplace_back(std::string(b, e));\n                });\n\n  if (!client_cert_path.empty() && !client_key_path.empty()) {\n    if (SSL_CTX_use_certificate_file(ctx_, client_cert_path.c_str(),\n                                     SSL_FILETYPE_PEM) != 1 ||\n        SSL_CTX_use_PrivateKey_file(ctx_, client_key_path.c_str(),\n                                    SSL_FILETYPE_PEM) != 1) {\n      SSL_CTX_free(ctx_);\n      ctx_ = nullptr;\n    }\n  }\n}\n\ninline SSLClient::SSLClient(const std::string &host, int port,\n                            X509 *client_cert, EVP_PKEY *client_key)\n    : ClientImpl(host, port) {\n  ctx_ = SSL_CTX_new(TLS_client_method());\n\n  detail::split(&host_[0], &host_[host_.size()], '.',\n                [&](const char *b, const char *e) {\n                  host_components_.emplace_back(std::string(b, e));\n                });\n\n  if (client_cert != nullptr && client_key != nullptr) {\n    if (SSL_CTX_use_certificate(ctx_, client_cert) != 1 ||\n        SSL_CTX_use_PrivateKey(ctx_, client_key) != 1) {\n      SSL_CTX_free(ctx_);\n      ctx_ = nullptr;\n    }\n  }\n}\n\ninline SSLClient::~SSLClient() {\n  if (ctx_) { SSL_CTX_free(ctx_); }\n  // Make sure to shut down SSL since shutdown_ssl will resolve to the\n  // base function rather than the derived function once we get to the\n  // base class destructor, and won't free the SSL (causing a leak).\n  shutdown_ssl_impl(socket_, true);\n}\n\ninline bool SSLClient::is_valid() const { return ctx_; }\n\ninline void SSLClient::set_ca_cert_store(X509_STORE *ca_cert_store) {\n  if (ca_cert_store) {\n    if (ctx_) {\n      if (SSL_CTX_get_cert_store(ctx_) != ca_cert_store) {\n        // Free memory allocated for old cert and use new store `ca_cert_store`\n        SSL_CTX_set_cert_store(ctx_, ca_cert_store);\n      }\n    } else {\n      X509_STORE_free(ca_cert_store);\n    }\n  }\n}\n\ninline long SSLClient::get_openssl_verify_result() const {\n  return verify_result_;\n}\n\ninline SSL_CTX *SSLClient::ssl_context() const { return ctx_; }\n\ninline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {\n  return is_valid() && ClientImpl::create_and_connect_socket(socket, error);\n}\n\n// Assumes that socket_mutex_ is locked and that there are no requests in flight\ninline bool SSLClient::connect_with_proxy(Socket &socket, Response &res,\n                                          bool &success, Error &error) {\n  success = true;\n  Response res2;\n  if (!detail::process_client_socket(\n          socket.sock, read_timeout_sec_, read_timeout_usec_,\n          write_timeout_sec_, write_timeout_usec_, [&](Stream &strm) {\n            Request req2;\n            req2.method = \"CONNECT\";\n            req2.path = host_and_port_;\n            return process_request(strm, req2, res2, false, error);\n          })) {\n    // Thread-safe to close everything because we are assuming there are no\n    // requests in flight\n    shutdown_ssl(socket, true);\n    shutdown_socket(socket);\n    close_socket(socket);\n    success = false;\n    return false;\n  }\n\n  if (res2.status == 407) {\n    if (!proxy_digest_auth_username_.empty() &&\n        !proxy_digest_auth_password_.empty()) {\n      std::map<std::string, std::string> auth;\n      if (detail::parse_www_authenticate(res2, auth, true)) {\n        Response res3;\n        if (!detail::process_client_socket(\n                socket.sock, read_timeout_sec_, read_timeout_usec_,\n                write_timeout_sec_, write_timeout_usec_, [&](Stream &strm) {\n                  Request req3;\n                  req3.method = \"CONNECT\";\n                  req3.path = host_and_port_;\n                  req3.headers.insert(detail::make_digest_authentication_header(\n                      req3, auth, 1, detail::random_string(10),\n                      proxy_digest_auth_username_, proxy_digest_auth_password_,\n                      true));\n                  return process_request(strm, req3, res3, false, error);\n                })) {\n          // Thread-safe to close everything because we are assuming there are\n          // no requests in flight\n          shutdown_ssl(socket, true);\n          shutdown_socket(socket);\n          close_socket(socket);\n          success = false;\n          return false;\n        }\n      }\n    } else {\n      res = res2;\n      return false;\n    }\n  }\n\n  return true;\n}\n\ninline bool SSLClient::load_certs() {\n  bool ret = true;\n\n  std::call_once(initialize_cert_, [&]() {\n    std::lock_guard<std::mutex> guard(ctx_mutex_);\n    if (!ca_cert_file_path_.empty()) {\n      if (!SSL_CTX_load_verify_locations(ctx_, ca_cert_file_path_.c_str(),\n                                         nullptr)) {\n        ret = false;\n      }\n    } else if (!ca_cert_dir_path_.empty()) {\n      if (!SSL_CTX_load_verify_locations(ctx_, nullptr,\n                                         ca_cert_dir_path_.c_str())) {\n        ret = false;\n      }\n    } else {\n      auto loaded = false;\n#ifdef _WIN32\n      loaded =\n          detail::load_system_certs_on_windows(SSL_CTX_get_cert_store(ctx_));\n#elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && defined(__APPLE__)\n#if TARGET_OS_OSX\n      loaded = detail::load_system_certs_on_macos(SSL_CTX_get_cert_store(ctx_));\n#endif // TARGET_OS_OSX\n#endif // _WIN32\n      if (!loaded) { SSL_CTX_set_default_verify_paths(ctx_); }\n    }\n  });\n\n  return ret;\n}\n\ninline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {\n  auto ssl = detail::ssl_new(\n      socket.sock, ctx_, ctx_mutex_,\n      [&](SSL *ssl2) {\n        if (server_certificate_verification_) {\n          if (!load_certs()) {\n            error = Error::SSLLoadingCerts;\n            return false;\n          }\n          SSL_set_verify(ssl2, SSL_VERIFY_NONE, nullptr);\n        }\n\n        if (!detail::ssl_connect_or_accept_nonblocking(\n                socket.sock, ssl2, SSL_connect, connection_timeout_sec_,\n                connection_timeout_usec_)) {\n          error = Error::SSLConnection;\n          return false;\n        }\n\n        if (server_certificate_verification_) {\n          verify_result_ = SSL_get_verify_result(ssl2);\n\n          if (verify_result_ != X509_V_OK) {\n            error = Error::SSLServerVerification;\n            return false;\n          }\n\n          auto server_cert = SSL_get1_peer_certificate(ssl2);\n\n          if (server_cert == nullptr) {\n            error = Error::SSLServerVerification;\n            return false;\n          }\n\n          if (!verify_host(server_cert)) {\n            X509_free(server_cert);\n            error = Error::SSLServerVerification;\n            return false;\n          }\n          X509_free(server_cert);\n        }\n\n        return true;\n      },\n      [&](SSL *ssl2) {\n        SSL_set_tlsext_host_name(ssl2, host_.c_str());\n        return true;\n      });\n\n  if (ssl) {\n    socket.ssl = ssl;\n    return true;\n  }\n\n  shutdown_socket(socket);\n  close_socket(socket);\n  return false;\n}\n\ninline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {\n  shutdown_ssl_impl(socket, shutdown_gracefully);\n}\n\ninline void SSLClient::shutdown_ssl_impl(Socket &socket,\n                                         bool shutdown_gracefully) {\n  if (socket.sock == INVALID_SOCKET) {\n    assert(socket.ssl == nullptr);\n    return;\n  }\n  if (socket.ssl) {\n    detail::ssl_delete(ctx_mutex_, socket.ssl, shutdown_gracefully);\n    socket.ssl = nullptr;\n  }\n  assert(socket.ssl == nullptr);\n}\n\ninline bool\nSSLClient::process_socket(const Socket &socket,\n                          std::function<bool(Stream &strm)> callback) {\n  assert(socket.ssl);\n  return detail::process_client_socket_ssl(\n      socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,\n      write_timeout_sec_, write_timeout_usec_, std::move(callback));\n}\n\ninline bool SSLClient::is_ssl() const { return true; }\n\ninline bool SSLClient::verify_host(X509 *server_cert) const {\n  /* Quote from RFC2818 section 3.1 \"Server Identity\"\n\n     If a subjectAltName extension of type dNSName is present, that MUST\n     be used as the identity. Otherwise, the (most specific) Common Name\n     field in the Subject field of the certificate MUST be used. Although\n     the use of the Common Name is existing practice, it is deprecated and\n     Certification Authorities are encouraged to use the dNSName instead.\n\n     Matching is performed using the matching rules specified by\n     [RFC2459].  If more than one identity of a given type is present in\n     the certificate (e.g., more than one dNSName name, a match in any one\n     of the set is considered acceptable.) Names may contain the wildcard\n     character * which is considered to match any single domain name\n     component or component fragment. E.g., *.a.com matches foo.a.com but\n     not bar.foo.a.com. f*.com matches foo.com but not bar.com.\n\n     In some cases, the URI is specified as an IP address rather than a\n     hostname. In this case, the iPAddress subjectAltName must be present\n     in the certificate and must exactly match the IP in the URI.\n\n  */\n  return verify_host_with_subject_alt_name(server_cert) ||\n         verify_host_with_common_name(server_cert);\n}\n\ninline bool\nSSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {\n  auto ret = false;\n\n  auto type = GEN_DNS;\n\n  struct in6_addr addr6;\n  struct in_addr addr;\n  size_t addr_len = 0;\n\n#ifndef __MINGW32__\n  if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {\n    type = GEN_IPADD;\n    addr_len = sizeof(struct in6_addr);\n  } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {\n    type = GEN_IPADD;\n    addr_len = sizeof(struct in_addr);\n  }\n#endif\n\n  auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(\n      X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));\n\n  if (alt_names) {\n    auto dsn_matched = false;\n    auto ip_matched = false;\n\n    auto count = sk_GENERAL_NAME_num(alt_names);\n\n    for (decltype(count) i = 0; i < count && !dsn_matched; i++) {\n      auto val = sk_GENERAL_NAME_value(alt_names, i);\n      if (val->type == type) {\n        auto name = (const char *)ASN1_STRING_get0_data(val->d.ia5);\n        auto name_len = (size_t)ASN1_STRING_length(val->d.ia5);\n\n        switch (type) {\n        case GEN_DNS: dsn_matched = check_host_name(name, name_len); break;\n\n        case GEN_IPADD:\n          if (!memcmp(&addr6, name, addr_len) ||\n              !memcmp(&addr, name, addr_len)) {\n            ip_matched = true;\n          }\n          break;\n        }\n      }\n    }\n\n    if (dsn_matched || ip_matched) { ret = true; }\n  }\n\n  GENERAL_NAMES_free((STACK_OF(GENERAL_NAME) *)alt_names);\n  return ret;\n}\n\ninline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {\n  const auto subject_name = X509_get_subject_name(server_cert);\n\n  if (subject_name != nullptr) {\n    char name[BUFSIZ];\n    auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,\n                                              name, sizeof(name));\n\n    if (name_len != -1) {\n      return check_host_name(name, static_cast<size_t>(name_len));\n    }\n  }\n\n  return false;\n}\n\ninline bool SSLClient::check_host_name(const char *pattern,\n                                       size_t pattern_len) const {\n  if (host_.size() == pattern_len && host_ == pattern) { return true; }\n\n  // Wildcard match\n  // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484\n  std::vector<std::string> pattern_components;\n  detail::split(&pattern[0], &pattern[pattern_len], '.',\n                [&](const char *b, const char *e) {\n                  pattern_components.emplace_back(std::string(b, e));\n                });\n\n  if (host_components_.size() != pattern_components.size()) { return false; }\n\n  auto itr = pattern_components.begin();\n  for (const auto &h : host_components_) {\n    auto &p = *itr;\n    if (p != h && p != \"*\") {\n      auto partial_match = (p.size() > 0 && p[p.size() - 1] == '*' &&\n                            !p.compare(0, p.size() - 1, h));\n      if (!partial_match) { return false; }\n    }\n    ++itr;\n  }\n\n  return true;\n}\n#endif\n\n// Universal client implementation\ninline Client::Client(const std::string &scheme_host_port)\n    : Client(scheme_host_port, std::string(), std::string()) {}\n\ninline Client::Client(const std::string &scheme_host_port,\n                      const std::string &client_cert_path,\n                      const std::string &client_key_path) {\n  const static std::regex re(\n      R\"((?:([a-z]+):\\/\\/)?(?:\\[([\\d:]+)\\]|([^:/?#]+))(?::(\\d+))?)\");\n\n  std::smatch m;\n  if (std::regex_match(scheme_host_port, m, re)) {\n    auto scheme = m[1].str();\n\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n    if (!scheme.empty() && (scheme != \"http\" && scheme != \"https\")) {\n#else\n    if (!scheme.empty() && scheme != \"http\") {\n#endif\n#ifndef CPPHTTPLIB_NO_EXCEPTIONS\n      std::string msg = \"'\" + scheme + \"' scheme is not supported.\";\n      throw std::invalid_argument(msg);\n#endif\n      return;\n    }\n\n    auto is_ssl = scheme == \"https\";\n\n    auto host = m[2].str();\n    if (host.empty()) { host = m[3].str(); }\n\n    auto port_str = m[4].str();\n    auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80);\n\n    if (is_ssl) {\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\n      cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,\n                                            client_key_path);\n      is_ssl_ = is_ssl;\n#endif\n    } else {\n      cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,\n                                             client_key_path);\n    }\n  } else {\n    cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,\n                                           client_cert_path, client_key_path);\n  }\n}\n\ninline Client::Client(const std::string &host, int port)\n    : cli_(detail::make_unique<ClientImpl>(host, port)) {}\n\ninline Client::Client(const std::string &host, int port,\n                      const std::string &client_cert_path,\n                      const std::string &client_key_path)\n    : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,\n                                           client_key_path)) {}\n\ninline Client::~Client() {}\n\ninline bool Client::is_valid() const {\n  return cli_ != nullptr && cli_->is_valid();\n}\n\ninline Result Client::Get(const std::string &path) { return cli_->Get(path); }\ninline Result Client::Get(const std::string &path, const Headers &headers) {\n  return cli_->Get(path, headers);\n}\ninline Result Client::Get(const std::string &path, Progress progress) {\n  return cli_->Get(path, std::move(progress));\n}\ninline Result Client::Get(const std::string &path, const Headers &headers,\n                          Progress progress) {\n  return cli_->Get(path, headers, std::move(progress));\n}\ninline Result Client::Get(const std::string &path,\n                          ContentReceiver content_receiver) {\n  return cli_->Get(path, std::move(content_receiver));\n}\ninline Result Client::Get(const std::string &path, const Headers &headers,\n                          ContentReceiver content_receiver) {\n  return cli_->Get(path, headers, std::move(content_receiver));\n}\ninline Result Client::Get(const std::string &path,\n                          ContentReceiver content_receiver, Progress progress) {\n  return cli_->Get(path, std::move(content_receiver), std::move(progress));\n}\ninline Result Client::Get(const std::string &path, const Headers &headers,\n                          ContentReceiver content_receiver, Progress progress) {\n  return cli_->Get(path, headers, std::move(content_receiver),\n                   std::move(progress));\n}\ninline Result Client::Get(const std::string &path,\n                          ResponseHandler response_handler,\n                          ContentReceiver content_receiver) {\n  return cli_->Get(path, std::move(response_handler),\n                   std::move(content_receiver));\n}\ninline Result Client::Get(const std::string &path, const Headers &headers,\n                          ResponseHandler response_handler,\n                          ContentReceiver content_receiver) {\n  return cli_->Get(path, headers, std::move(response_handler),\n                   std::move(content_receiver));\n}\ninline Result Client::Get(const std::string &path,\n                          ResponseHandler response_handler,\n                          ContentReceiver content_receiver, Progress progress) {\n  return cli_->Get(path, std::move(response_handler),\n                   std::move(content_receiver), std::move(progress));\n}\ninline Result Client::Get(const std::string &path, const Headers &headers,\n                          ResponseHandler response_handler,\n                          ContentReceiver content_receiver, Progress progress) {\n  return cli_->Get(path, headers, std::move(response_handler),\n                   std::move(content_receiver), std::move(progress));\n}\ninline Result Client::Get(const std::string &path, const Params &params,\n                          const Headers &headers, Progress progress) {\n  return cli_->Get(path, params, headers, progress);\n}\ninline Result Client::Get(const std::string &path, const Params &params,\n                          const Headers &headers,\n                          ContentReceiver content_receiver, Progress progress) {\n  return cli_->Get(path, params, headers, content_receiver, progress);\n}\ninline Result Client::Get(const std::string &path, const Params &params,\n                          const Headers &headers,\n                          ResponseHandler response_handler,\n                          ContentReceiver content_receiver, Progress progress) {\n  return cli_->Get(path, params, headers, response_handler, content_receiver,\n                   progress);\n}\n\ninline Result Client::Head(const std::string &path) { return cli_->Head(path); }\ninline Result Client::Head(const std::string &path, const Headers &headers) {\n  return cli_->Head(path, headers);\n}\n\ninline Result Client::Post(const std::string &path) { return cli_->Post(path); }\ninline Result Client::Post(const std::string &path, const Headers &headers) {\n  return cli_->Post(path, headers);\n}\ninline Result Client::Post(const std::string &path, const char *body,\n                           size_t content_length,\n                           const std::string &content_type) {\n  return cli_->Post(path, body, content_length, content_type);\n}\ninline Result Client::Post(const std::string &path, const Headers &headers,\n                           const char *body, size_t content_length,\n                           const std::string &content_type) {\n  return cli_->Post(path, headers, body, content_length, content_type);\n}\ninline Result Client::Post(const std::string &path, const std::string &body,\n                           const std::string &content_type) {\n  return cli_->Post(path, body, content_type);\n}\ninline Result Client::Post(const std::string &path, const Headers &headers,\n                           const std::string &body,\n                           const std::string &content_type) {\n  return cli_->Post(path, headers, body, content_type);\n}\ninline Result Client::Post(const std::string &path, size_t content_length,\n                           ContentProvider content_provider,\n                           const std::string &content_type) {\n  return cli_->Post(path, content_length, std::move(content_provider),\n                    content_type);\n}\ninline Result Client::Post(const std::string &path,\n                           ContentProviderWithoutLength content_provider,\n                           const std::string &content_type) {\n  return cli_->Post(path, std::move(content_provider), content_type);\n}\ninline Result Client::Post(const std::string &path, const Headers &headers,\n                           size_t content_length,\n                           ContentProvider content_provider,\n                           const std::string &content_type) {\n  return cli_->Post(path, headers, content_length, std::move(content_provider),\n                    content_type);\n}\ninline Result Client::Post(const std::string &path, const Headers &headers,\n                           ContentProviderWithoutLength content_provider,\n                           const std::string &content_type) {\n  return cli_->Post(path, headers, std::move(content_provider), content_type);\n}\ninline Result Client::Post(const std::string &path, const Params &params) {\n  return cli_->Post(path, params);\n}\ninline Result Client::Post(const std::string &path, const Headers &headers,\n                           const Params &params) {\n  return cli_->Post(path, headers, params);\n}\ninline Result Client::Post(const std::string &path,\n                           const MultipartFormDataItems &items) {\n  return cli_->Post(path, items);\n}\ninline Result Client::Post(const std::string &path, const Headers &headers,\n                           const MultipartFormDataItems &items) {\n  return cli_->Post(path, headers, items);\n}\ninline Result Client::Post(const std::string &path, const Headers &headers,\n                           const MultipartFormDataItems &items,\n                           const std::string &boundary) {\n  return cli_->Post(path, headers, items, boundary);\n}\ninline Result\nClient::Post(const std::string &path, const Headers &headers,\n             const MultipartFormDataItems &items,\n             const MultipartFormDataProviderItems &provider_items) {\n  return cli_->Post(path, headers, items, provider_items);\n}\ninline Result Client::Put(const std::string &path) { return cli_->Put(path); }\ninline Result Client::Put(const std::string &path, const char *body,\n                          size_t content_length,\n                          const std::string &content_type) {\n  return cli_->Put(path, body, content_length, content_type);\n}\ninline Result Client::Put(const std::string &path, const Headers &headers,\n                          const char *body, size_t content_length,\n                          const std::string &content_type) {\n  return cli_->Put(path, headers, body, content_length, content_type);\n}\ninline Result Client::Put(const std::string &path, const std::string &body,\n                          const std::string &content_type) {\n  return cli_->Put(path, body, content_type);\n}\ninline Result Client::Put(const std::string &path, const Headers &headers,\n                          const std::string &body,\n                          const std::string &content_type) {\n  return cli_->Put(path, headers, body, content_type);\n}\ninline Result Client::Put(const std::string &path, size_t content_length,\n                          ContentProvider content_provider,\n                          const std::string &content_type) {\n  return cli_->Put(path, content_length, std::move(content_provider),\n                   content_type);\n}\ninline Result Client::Put(const std::string &path,\n                          ContentProviderWithoutLength content_provider,\n                          const std::string &content_type) {\n  return cli_->Put(path, std::move(content_provider), content_type);\n}\ninline Result Client::Put(const std::string &path, const Headers &headers,\n                          size_t content_length,\n                          ContentProvider content_provider,\n                          const std::string &content_type) {\n  return cli_->Put(path, headers, content_length, std::move(content_provider),\n                   content_type);\n}\ninline Result Client::Put(const std::string &path, const Headers &headers,\n                          ContentProviderWithoutLength content_provider,\n                          const std::string &content_type) {\n  return cli_->Put(path, headers, std::move(content_provider), content_type);\n}\ninline Result Client::Put(const std::string &path, const Params &params) {\n  return cli_->Put(path, params);\n}\ninline Result Client::Put(const std::string &path, const Headers &headers,\n                          const Params &params) {\n  return cli_->Put(path, headers, params);\n}\ninline Result Client::Put(const std::string &path,\n                          const MultipartFormDataItems &items) {\n  return cli_->Put(path, items);\n}\ninline Result Client::Put(const std::string &path, const Headers &headers,\n                          const MultipartFormDataItems &items) {\n  return cli_->Put(path, headers, items);\n}\ninline Result Client::Put(const std::string &path, const Headers &headers,\n                          const MultipartFormDataItems &items,\n                          const std::string &boundary) {\n  return cli_->Put(path, headers, items, boundary);\n}\ninline Result\nClient::Put(const std::string &path, const Headers &headers,\n            const MultipartFormDataItems &items,\n            const MultipartFormDataProviderItems &provider_items) {\n  return cli_->Put(path, headers, items, provider_items);\n}\ninline Result Client::Patch(const std::string &path) {\n  return cli_->Patch(path);\n}\ninline Result Client::Patch(const std::string &path, const char *body,\n                            size_t content_length,\n                            const std::string &content_type) {\n  return cli_->Patch(path, body, content_length, content_type);\n}\ninline Result Client::Patch(const std::string &path, const Headers &headers,\n                            const char *body, size_t content_length,\n                            const std::string &content_type) {\n  return cli_->Patch(path, headers, body, content_length, content_type);\n}\ninline Result Client::Patch(const std::string &path, const std::string &body,\n                            const std::string &content_type) {\n  return cli_->Patch(path, body, content_type);\n}\ninline Result Client::Patch(const std::string &path, const Headers &headers,\n                            const std::string &body,\n                            const std::string &content_type) {\n  return cli_->Patch(path, headers, body, content_type);\n}\ninline Result Client::Patch(const std::string &path, size_t content_length,\n                            ContentProvider content_provider,\n                            const std::string &content_type) {\n  return cli_->Patch(path, content_length, std::move(content_provider),\n                     content_type);\n}\ninline Result Client::Patch(const std::string &path,\n                            ContentProviderWithoutLength content_provider,\n                            const std::string &content_type) {\n  return cli_->Patch(path, std::move(content_provider), content_type);\n}\ninline Result Client::Patch(const std::string &path, const Headers &headers,\n                            size_t content_length,\n                            ContentProvider content_provider,\n                            const std::string &content_type) {\n  return cli_->Patch(path, headers, content_length, std::move(content_provider),\n                     content_type);\n}\ninline Result Client::Patch(const std::string &path, const Headers &headers,\n                            ContentProviderWithoutLength content_provider,\n                            const std::string &content_type) {\n  return cli_->Patch(path, headers, std::move(content_provider), content_type);\n}\ninline Result Client::Delete(const std::string &path) {\n  return cli_->Delete(path);\n}\ninline Result Client::Delete(const std::string &path, const Headers &headers) {\n  return cli_->Delete(path, headers);\n}\ninline Result Client::Delete(const std::string &path, const char *body,\n                             size_t content_length,\n                             const std::string &content_type) {\n  return cli_->Delete(path, body, content_length, content_type);\n}\ninline Result Client::Delete(const std::string &path, const Headers &headers,\n                             const char *body, size_t content_length,\n                             const std::string &content_type) {\n  return cli_->Delete(path, headers, body, content_length, content_type);\n}\ninline Result Client::Delete(const std::string &path, const std::string &body,\n                             const std::string &content_type) {\n  return cli_->Delete(path, body, content_type);\n}\ninline Result Client::Delete(const std::string &path, const Headers &headers,\n                             const std::string &body,\n                             const std::string &content_type) {\n  return cli_->Delete(path, headers, body, content_type);\n}\ninline Result Client::Options(const std::string &path) {\n  return cli_->Options(path);\n}\ninline Result Client::Options(const std::string &path, const Headers &headers) {\n  return cli_->Options(path, headers);\n}\n\ninline bool Client::send(Request &req, Response &res, Error &error) {\n  return cli_->send(req, res, error);\n}\n\ninline Result Client::send(const Request &req) { return cli_->send(req); }\n\ninline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }\n\ninline socket_t Client::socket() const { return cli_->socket(); }\n\ninline void Client::stop() { cli_->stop(); }\n\ninline void\nClient::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {\n  cli_->set_hostname_addr_map(std::move(addr_map));\n}\n\ninline void Client::set_default_headers(Headers headers) {\n  cli_->set_default_headers(std::move(headers));\n}\n\ninline void Client::set_address_family(int family) {\n  cli_->set_address_family(family);\n}\n\ninline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }\n\ninline void Client::set_socket_options(SocketOptions socket_options) {\n  cli_->set_socket_options(std::move(socket_options));\n}\n\ninline void Client::set_connection_timeout(time_t sec, time_t usec) {\n  cli_->set_connection_timeout(sec, usec);\n}\n\ninline void Client::set_read_timeout(time_t sec, time_t usec) {\n  cli_->set_read_timeout(sec, usec);\n}\n\ninline void Client::set_write_timeout(time_t sec, time_t usec) {\n  cli_->set_write_timeout(sec, usec);\n}\n\ninline void Client::set_basic_auth(const std::string &username,\n                                   const std::string &password) {\n  cli_->set_basic_auth(username, password);\n}\ninline void Client::set_bearer_token_auth(const std::string &token) {\n  cli_->set_bearer_token_auth(token);\n}\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\ninline void Client::set_digest_auth(const std::string &username,\n                                    const std::string &password) {\n  cli_->set_digest_auth(username, password);\n}\n#endif\n\ninline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }\ninline void Client::set_follow_location(bool on) {\n  cli_->set_follow_location(on);\n}\n\ninline void Client::set_url_encode(bool on) { cli_->set_url_encode(on); }\n\ninline void Client::set_compress(bool on) { cli_->set_compress(on); }\n\ninline void Client::set_decompress(bool on) { cli_->set_decompress(on); }\n\ninline void Client::set_interface(const std::string &intf) {\n  cli_->set_interface(intf);\n}\n\ninline void Client::set_proxy(const std::string &host, int port) {\n  cli_->set_proxy(host, port);\n}\ninline void Client::set_proxy_basic_auth(const std::string &username,\n                                         const std::string &password) {\n  cli_->set_proxy_basic_auth(username, password);\n}\ninline void Client::set_proxy_bearer_token_auth(const std::string &token) {\n  cli_->set_proxy_bearer_token_auth(token);\n}\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\ninline void Client::set_proxy_digest_auth(const std::string &username,\n                                          const std::string &password) {\n  cli_->set_proxy_digest_auth(username, password);\n}\n#endif\n\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\ninline void Client::enable_server_certificate_verification(bool enabled) {\n  cli_->enable_server_certificate_verification(enabled);\n}\n#endif\n\ninline void Client::set_logger(Logger logger) { cli_->set_logger(logger); }\n\n#ifdef CPPHTTPLIB_OPENSSL_SUPPORT\ninline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,\n                                     const std::string &ca_cert_dir_path) {\n  cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);\n}\n\ninline void Client::set_ca_cert_store(X509_STORE *ca_cert_store) {\n  if (is_ssl_) {\n    static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);\n  } else {\n    cli_->set_ca_cert_store(ca_cert_store);\n  }\n}\n\ninline long Client::get_openssl_verify_result() const {\n  if (is_ssl_) {\n    return static_cast<SSLClient &>(*cli_).get_openssl_verify_result();\n  }\n  return -1; // NOTE: -1 doesn't match any of X509_V_ERR_???\n}\n\ninline SSL_CTX *Client::ssl_context() const {\n  if (is_ssl_) { return static_cast<SSLClient &>(*cli_).ssl_context(); }\n  return nullptr;\n}\n#endif\n\n// ----------------------------------------------------------------------------\n\n} // namespace httplib\n\n#if defined(_WIN32) && defined(CPPHTTPLIB_USE_POLL)\n#undef poll\n#endif\n\n#endif // CPPHTTPLIB_HTTPLIB_H\n"}