19#ifdef USE_HTTP_REQUEST_HOST_H
23#ifndef CPPHTTPLIB_HTTPLIB_H
24#define CPPHTTPLIB_HTTPLIB_H
26#define CPPHTTPLIB_VERSION "0.18.2"
32#ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
33#define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
36#ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND
37#define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000
40#ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
41#define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100
44#ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
45#define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
48#ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
49#define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
52#ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND
53#define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5
56#ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND
57#define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0
60#ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND
61#define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5
64#ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND
65#define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0
68#ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND
69#define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300
72#ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND
73#define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0
76#ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND
77#define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5
80#ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND
81#define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0
84#ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
85#define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
88#ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
90#define CPPHTTPLIB_IDLE_INTERVAL_USECOND 10000
92#define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
96#ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
97#define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
100#ifndef CPPHTTPLIB_HEADER_MAX_LENGTH
101#define CPPHTTPLIB_HEADER_MAX_LENGTH 8192
104#ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
105#define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
108#ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT
109#define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024
112#ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
113#define CPPHTTPLIB_PAYLOAD_MAX_LENGTH ((std::numeric_limits<size_t>::max)())
116#ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH
117#define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192
120#ifndef CPPHTTPLIB_RANGE_MAX_COUNT
121#define CPPHTTPLIB_RANGE_MAX_COUNT 1024
124#ifndef CPPHTTPLIB_TCP_NODELAY
125#define CPPHTTPLIB_TCP_NODELAY false
128#ifndef CPPHTTPLIB_IPV6_V6ONLY
129#define CPPHTTPLIB_IPV6_V6ONLY false
132#ifndef CPPHTTPLIB_RECV_BUFSIZ
133#define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u)
136#ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
137#define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
140#ifndef CPPHTTPLIB_THREAD_POOL_COUNT
141#define CPPHTTPLIB_THREAD_POOL_COUNT \
142 ((std::max) (8u, std::thread::hardware_concurrency() > 0 ? std::thread::hardware_concurrency() - 1 : 0))
145#ifndef CPPHTTPLIB_RECV_FLAGS
146#define CPPHTTPLIB_RECV_FLAGS 0
149#ifndef CPPHTTPLIB_SEND_FLAGS
150#define CPPHTTPLIB_SEND_FLAGS 0
153#ifndef CPPHTTPLIB_LISTEN_BACKLOG
154#define CPPHTTPLIB_LISTEN_BACKLOG 5
162#ifndef _CRT_SECURE_NO_WARNINGS
163#define _CRT_SECURE_NO_WARNINGS
166#ifndef _CRT_NONSTDC_NO_DEPRECATE
167#define _CRT_NONSTDC_NO_DEPRECATE
172#error Sorry, Visual Studio versions prior to 2015 are not supported
175#pragma comment(lib, "ws2_32.lib")
185#define S_ISREG(m) (((m) & S_IFREG) == S_IFREG)
189#define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR)
200#ifndef WSA_FLAG_NO_HANDLE_INHERIT
201#define WSA_FLAG_NO_HANDLE_INHERIT 0x80
205#ifdef CPPHTTPLIB_USE_POLL
206#define poll(fds, nfds, timeout) WSAPoll(fds, nfds, timeout)
211#include <arpa/inet.h>
212#if !defined(_AIX) && !defined(__MVS__)
218#define NI_MAXHOST 1025
223#include <netinet/in.h>
227#include <netinet/tcp.h>
228#ifdef CPPHTTPLIB_USE_POLL
234#include <sys/select.h>
235#include <sys/socket.h>
240#ifndef INVALID_SOCKET
241#define INVALID_SOCKET (-1)
251#include <condition_variable>
271#include <unordered_map>
272#include <unordered_set>
275#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
283#undef X509_EXTENSIONS
284#undef PKCS7_SIGNER_INFO
287#pragma comment(lib, "crypt32.lib")
289#elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && defined(__APPLE__)
290#include <TargetConditionals.h>
294#define Ptr esphome_mactypes_Ptr
295#include <CoreFoundation/CoreFoundation.h>
296#include <Security/Security.h>
301#include <openssl/err.h>
302#include <openssl/evp.h>
303#include <openssl/ssl.h>
304#include <openssl/x509v3.h>
306#if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
307#include <openssl/applink.c>
313#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
314#if OPENSSL_VERSION_NUMBER < 0x1010107f
315#error Please use OpenSSL or a current version of BoringSSL
317#define SSL_get1_peer_certificate SSL_get_peer_certificate
318#elif OPENSSL_VERSION_NUMBER < 0x30000000L
319#error Sorry, OpenSSL versions prior to 3.0.0 are not supported
324#ifdef CPPHTTPLIB_ZLIB_SUPPORT
328#ifdef CPPHTTPLIB_BROTLI_SUPPORT
329#include <brotli/decode.h>
330#include <brotli/encode.h>
348template<
class T,
class... Args>
349typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>
::type make_unique(Args &&...args) {
350 return std::unique_ptr<T>(
new T(std::forward<Args>(args)...));
354typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>
::type make_unique(std::size_t n) {
355 typedef typename std::remove_extent<T>::type RT;
356 return std::unique_ptr<T>(
new RT[n]);
359namespace case_ignore {
361inline unsigned char to_lower(
int c) {
362 const static unsigned char table[256] = {
363 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
364 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43,
365 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97,
366 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
367 120, 121, 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109,
368 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131,
369 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153,
370 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175,
371 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226, 227, 228, 229,
372 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 215, 248, 249, 250, 251,
373 252, 253, 254, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
374 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255,
376 return table[(
unsigned char) (
char) c];
379inline bool equal(
const std::string &a,
const std::string &b) {
380 return a.size() == b.size() &&
381 std::equal(a.begin(), a.end(), b.begin(), [](
char ca,
char cb) { return to_lower(ca) == to_lower(cb); });
385 bool operator()(
const std::string &a,
const std::string &b)
const {
return equal(a, b); }
389 size_t operator()(
const std::string &
key)
const {
return hash_core(
key.data(),
key.size(), 0); }
391 size_t hash_core(
const char *s,
size_t l,
size_t h)
const {
393 : hash_core(s + 1,
l - 1,
396 (((std::numeric_limits<size_t>::max)() >> 6) &
h * 33) ^
397 static_cast<unsigned char>(to_lower(*s)));
407 explicit scope_exit(std::function<
void(
void)> &&f) : exit_function(std::move(f)), execute_on_destruction{
true} {}
409 scope_exit(scope_exit &&rhs) noexcept
410 : exit_function(std::move(rhs.exit_function)), execute_on_destruction{rhs.execute_on_destruction} {
415 if (execute_on_destruction) {
416 this->exit_function();
420 void release() { this->execute_on_destruction =
false; }
423 scope_exit(
const scope_exit &) =
delete;
424 void operator=(
const scope_exit &) =
delete;
425 scope_exit &operator=(scope_exit &&) =
delete;
427 std::function<void(
void)> exit_function;
428 bool execute_on_destruction;
436 SwitchingProtocol_101 = 101,
437 Processing_102 = 102,
438 EarlyHints_103 = 103,
444 NonAuthoritativeInformation_203 = 203,
446 ResetContent_205 = 205,
447 PartialContent_206 = 206,
448 MultiStatus_207 = 207,
449 AlreadyReported_208 = 208,
453 MultipleChoices_300 = 300,
454 MovedPermanently_301 = 301,
457 NotModified_304 = 304,
460 TemporaryRedirect_307 = 307,
461 PermanentRedirect_308 = 308,
464 BadRequest_400 = 400,
465 Unauthorized_401 = 401,
466 PaymentRequired_402 = 402,
469 MethodNotAllowed_405 = 405,
470 NotAcceptable_406 = 406,
471 ProxyAuthenticationRequired_407 = 407,
472 RequestTimeout_408 = 408,
475 LengthRequired_411 = 411,
476 PreconditionFailed_412 = 412,
477 PayloadTooLarge_413 = 413,
478 UriTooLong_414 = 414,
479 UnsupportedMediaType_415 = 415,
480 RangeNotSatisfiable_416 = 416,
481 ExpectationFailed_417 = 417,
483 MisdirectedRequest_421 = 421,
484 UnprocessableContent_422 = 422,
486 FailedDependency_424 = 424,
488 UpgradeRequired_426 = 426,
489 PreconditionRequired_428 = 428,
490 TooManyRequests_429 = 429,
491 RequestHeaderFieldsTooLarge_431 = 431,
492 UnavailableForLegalReasons_451 = 451,
495 InternalServerError_500 = 500,
496 NotImplemented_501 = 501,
497 BadGateway_502 = 502,
498 ServiceUnavailable_503 = 503,
499 GatewayTimeout_504 = 504,
500 HttpVersionNotSupported_505 = 505,
501 VariantAlsoNegotiates_506 = 506,
502 InsufficientStorage_507 = 507,
503 LoopDetected_508 = 508,
504 NotExtended_510 = 510,
505 NetworkAuthenticationRequired_511 = 511,
509 std::unordered_multimap<std::string, std::string, detail::case_ignore::hash, detail::case_ignore::equal_to>;
511using Params = std::multimap<std::string, std::string>;
512using Match = std::smatch;
514using Progress = std::function<bool(uint64_t current, uint64_t total)>;
517using ResponseHandler = std::function<bool(
const Response &response)>;
519struct MultipartFormData {
522 std::string filename;
523 std::string content_type;
525using MultipartFormDataItems = std::vector<MultipartFormData>;
526using MultipartFormDataMap = std::multimap<std::string, MultipartFormData>;
530 DataSink() : os(&sb_), sb_(*
this) {}
532 DataSink(
const DataSink &) =
delete;
533 DataSink &operator=(
const DataSink &) =
delete;
534 DataSink(DataSink &&) =
delete;
535 DataSink &operator=(DataSink &&) =
delete;
537 std::function<bool(
const char *data,
size_t data_len)> write;
538 std::function<bool()> is_writable;
539 std::function<void()> done;
540 std::function<void(
const Headers &
trailer)> done_with_trailer;
544 class data_sink_streambuf final :
public std::streambuf {
546 explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
549 std::streamsize xsputn(
const char *s, std::streamsize n)
override {
550 sink_.write(s,
static_cast<size_t>(n));
558 data_sink_streambuf sb_;
561using ContentProvider = std::function<bool(
size_t offset,
size_t length, DataSink &sink)>;
563using ContentProviderWithoutLength = std::function<bool(
size_t offset, DataSink &sink)>;
565using ContentProviderResourceReleaser = std::function<void(
bool success)>;
567struct MultipartFormDataProvider {
569 ContentProviderWithoutLength provider;
570 std::string filename;
571 std::string content_type;
573using MultipartFormDataProviderItems = std::vector<MultipartFormDataProvider>;
575using ContentReceiverWithProgress =
576 std::function<bool(
const char *data,
size_t data_length, uint64_t offset, uint64_t total_length)>;
578using ContentReceiver = std::function<bool(
const char *data,
size_t data_length)>;
580using MultipartContentHeader = std::function<bool(
const MultipartFormData &file)>;
584 using Reader = std::function<bool(ContentReceiver receiver)>;
585 using MultipartReader = std::function<bool(MultipartContentHeader header, ContentReceiver receiver)>;
587 ContentReader(Reader reader, MultipartReader multipart_reader)
588 : reader_(std::move(reader)), multipart_reader_(std::move(multipart_reader)) {}
590 bool operator()(MultipartContentHeader header, ContentReceiver receiver)
const {
591 return multipart_reader_(std::move(header), std::move(receiver));
594 bool operator()(ContentReceiver receiver)
const {
return reader_(std::move(receiver)); }
597 MultipartReader multipart_reader_;
600using Range = std::pair<ssize_t, ssize_t>;
601using Ranges = std::vector<Range>;
610 std::string remote_addr;
611 int remote_port = -1;
612 std::string local_addr;
618 MultipartFormDataMap files;
621 std::unordered_map<std::string, std::string> path_params;
624 ResponseHandler response_handler;
625 ContentReceiverWithProgress content_receiver;
627#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
628 const SSL *ssl =
nullptr;
631 bool has_header(
const std::string &
key)
const;
632 std::string get_header_value(
const std::string &
key,
const char *def =
"",
size_t id = 0)
const;
633 uint64_t get_header_value_u64(
const std::string &
key, uint64_t def = 0,
size_t id = 0)
const;
634 size_t get_header_value_count(
const std::string &
key)
const;
635 void set_header(
const std::string &
key,
const std::string &
val);
637 bool has_param(
const std::string &
key)
const;
638 std::string get_param_value(
const std::string &
key,
size_t id = 0)
const;
639 size_t get_param_value_count(
const std::string &
key)
const;
641 bool is_multipart_form_data()
const;
643 bool has_file(
const std::string &
key)
const;
644 MultipartFormData get_file_value(
const std::string &
key)
const;
645 std::vector<MultipartFormData> get_file_values(
const std::string &
key)
const;
648 size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
649 size_t content_length_ = 0;
650 ContentProvider content_provider_;
651 bool is_chunked_content_provider_ =
false;
652 size_t authorization_count_ = 0;
661 std::string location;
663 bool has_header(
const std::string &
key)
const;
664 std::string get_header_value(
const std::string &
key,
const char *def =
"",
size_t id = 0)
const;
665 uint64_t get_header_value_u64(
const std::string &
key, uint64_t def = 0,
size_t id = 0)
const;
666 size_t get_header_value_count(
const std::string &
key)
const;
667 void set_header(
const std::string &
key,
const std::string &
val);
669 void set_redirect(
const std::string &url,
int status = StatusCode::Found_302);
670 void set_content(
const char *s,
size_t n,
const std::string &content_type);
671 void set_content(
const std::string &s,
const std::string &content_type);
672 void set_content(std::string &&s,
const std::string &content_type);
674 void set_content_provider(
size_t length,
const std::string &content_type, ContentProvider provider,
675 ContentProviderResourceReleaser resource_releaser =
nullptr);
677 void set_content_provider(
const std::string &content_type, ContentProviderWithoutLength provider,
678 ContentProviderResourceReleaser resource_releaser =
nullptr);
680 void set_chunked_content_provider(
const std::string &content_type, ContentProviderWithoutLength provider,
681 ContentProviderResourceReleaser resource_releaser =
nullptr);
683 void set_file_content(
const std::string &path,
const std::string &content_type);
684 void set_file_content(
const std::string &path);
686 Response() =
default;
687 Response(
const Response &) =
default;
688 Response &operator=(
const Response &) =
default;
689 Response(Response &&) =
default;
690 Response &operator=(Response &&) =
default;
692 if (content_provider_resource_releaser_) {
693 content_provider_resource_releaser_(content_provider_success_);
698 size_t content_length_ = 0;
699 ContentProvider content_provider_;
700 ContentProviderResourceReleaser content_provider_resource_releaser_;
701 bool is_chunked_content_provider_ =
false;
702 bool content_provider_success_ =
false;
703 std::string file_content_path_;
704 std::string file_content_content_type_;
709 virtual ~Stream() =
default;
711 virtual bool is_readable()
const = 0;
712 virtual bool is_writable()
const = 0;
714 virtual ssize_t read(
char *ptr,
size_t size) = 0;
715 virtual ssize_t write(
const char *ptr,
size_t size) = 0;
716 virtual void get_remote_ip_and_port(std::string &ip,
int &port)
const = 0;
717 virtual void get_local_ip_and_port(std::string &ip,
int &port)
const = 0;
718 virtual socket_t socket()
const = 0;
720 ssize_t write(
const char *ptr);
721 ssize_t write(
const std::string &s);
726 TaskQueue() =
default;
727 virtual ~TaskQueue() =
default;
729 virtual bool enqueue(std::function<
void()> fn) = 0;
730 virtual void shutdown() = 0;
732 virtual void on_idle() {}
735class ThreadPool final :
public TaskQueue {
737 explicit ThreadPool(
size_t n,
size_t mqr = 0) : shutdown_(
false), max_queued_requests_(mqr) {
739 threads_.emplace_back(worker(*
this));
744 ThreadPool(
const ThreadPool &) =
delete;
745 ~ThreadPool()
override =
default;
747 bool enqueue(std::function<
void()> fn)
override {
749 std::unique_lock<std::mutex>
lock(mutex_);
750 if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
753 jobs_.push_back(std::move(fn));
760 void shutdown()
override {
763 std::unique_lock<std::mutex>
lock(mutex_);
770 for (
auto &t : threads_) {
777 explicit worker(ThreadPool &pool) : pool_(pool) {}
781 std::function<void()> fn;
783 std::unique_lock<std::mutex>
lock(pool_.mutex_);
785 pool_.cond_.wait(
lock, [&] {
return !pool_.jobs_.empty() || pool_.shutdown_; });
787 if (pool_.shutdown_ && pool_.jobs_.empty()) {
791 fn = pool_.jobs_.front();
792 pool_.jobs_.pop_front();
795 assert(
true ==
static_cast<bool>(fn));
799#if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && !defined(LIBRESSL_VERSION_NUMBER)
800 OPENSSL_thread_stop();
806 friend struct worker;
808 std::vector<std::thread> threads_;
809 std::list<std::function<void()>> jobs_;
812 size_t max_queued_requests_ = 0;
814 std::condition_variable cond_;
818using Logger = std::function<void(
const Request &,
const Response &)>;
820using SocketOptions = std::function<void(
socket_t sock)>;
822void default_socket_options(
socket_t sock);
824const char *status_message(
int status);
826std::string get_bearer_token_auth(
const Request &req);
832 virtual ~MatcherBase() =
default;
835 virtual bool match(Request &request)
const = 0;
856class PathParamsMatcher final :
public MatcherBase {
858 PathParamsMatcher(
const std::string &pattern);
860 bool match(Request &request)
const override;
866 static constexpr char separator =
'/';
871 std::vector<std::string> static_fragments_;
874 std::vector<std::string> param_names_;
885class RegexMatcher final :
public MatcherBase {
887 RegexMatcher(
const std::string &pattern) : regex_(pattern) {}
889 bool match(Request &request)
const override;
895ssize_t write_headers(Stream &strm,
const Headers &headers);
901 using Handler = std::function<void(
const Request &, Response &)>;
903 using ExceptionHandler = std::function<void(
const Request &, Response &, std::exception_ptr ep)>;
905 enum class HandlerResponse {
909 using HandlerWithResponse = std::function<HandlerResponse(
const Request &, Response &)>;
911 using HandlerWithContentReader =
912 std::function<void(
const Request &, Response &,
const ContentReader &content_reader)>;
914 using Expect100ContinueHandler = std::function<int(
const Request &, Response &)>;
920 virtual bool is_valid()
const;
922 Server &Get(
const std::string &pattern, Handler handler);
923 Server &Post(
const std::string &pattern, Handler handler);
924 Server &Post(
const std::string &pattern, HandlerWithContentReader handler);
925 Server &Put(
const std::string &pattern, Handler handler);
926 Server &Put(
const std::string &pattern, HandlerWithContentReader handler);
927 Server &Patch(
const std::string &pattern, Handler handler);
928 Server &Patch(
const std::string &pattern, HandlerWithContentReader handler);
929 Server &Delete(
const std::string &pattern, Handler handler);
930 Server &Delete(
const std::string &pattern, HandlerWithContentReader handler);
931 Server &Options(
const std::string &pattern, Handler handler);
933 bool set_base_dir(
const std::string &dir,
const std::string &mount_point = std::string());
934 bool set_mount_point(
const std::string &mount_point,
const std::string &dir, Headers headers = Headers());
935 bool remove_mount_point(
const std::string &mount_point);
936 Server &set_file_extension_and_mimetype_mapping(
const std::string &ext,
const std::string &mime);
937 Server &set_default_file_mimetype(
const std::string &mime);
938 Server &set_file_request_handler(Handler handler);
940 template<
class ErrorHandlerFunc> Server &set_error_handler(ErrorHandlerFunc &&handler) {
941 return set_error_handler_core(std::forward<ErrorHandlerFunc>(handler),
942 std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
945 Server &set_exception_handler(ExceptionHandler handler);
946 Server &set_pre_routing_handler(HandlerWithResponse handler);
947 Server &set_post_routing_handler(Handler handler);
949 Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
950 Server &set_logger(Logger logger);
952 Server &set_address_family(
int family);
953 Server &set_tcp_nodelay(
bool on);
954 Server &set_ipv6_v6only(
bool on);
955 Server &set_socket_options(SocketOptions socket_options);
957 Server &set_default_headers(Headers headers);
958 Server &set_header_writer(std::function<
ssize_t(Stream &, Headers &)>
const &writer);
960 Server &set_keep_alive_max_count(
size_t count);
961 Server &set_keep_alive_timeout(time_t sec);
963 Server &set_read_timeout(time_t sec, time_t usec = 0);
964 template<
class Rep,
class Period> Server &set_read_timeout(
const std::chrono::duration<Rep, Period> &
duration);
966 Server &set_write_timeout(time_t sec, time_t usec = 0);
967 template<
class Rep,
class Period> Server &set_write_timeout(
const std::chrono::duration<Rep, Period> &
duration);
969 Server &set_idle_interval(time_t sec, time_t usec = 0);
970 template<
class Rep,
class Period> Server &set_idle_interval(
const std::chrono::duration<Rep, Period> &
duration);
972 Server &set_payload_max_length(
size_t length);
974 bool bind_to_port(
const std::string &host,
int port,
int socket_flags = 0);
975 int bind_to_any_port(
const std::string &host,
int socket_flags = 0);
976 bool listen_after_bind();
978 bool listen(
const std::string &host,
int port,
int socket_flags = 0);
980 bool is_running()
const;
981 void wait_until_ready()
const;
985 std::function<TaskQueue *(void)> new_task_queue;
988 bool process_request(Stream &strm,
const std::string &remote_addr,
int remote_port,
const std::string &local_addr,
989 int local_port,
bool close_connection,
bool &connection_closed,
990 const std::function<
void(Request &)> &setup_request);
992 std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
993 size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
994 time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
995 time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
996 time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
997 time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
998 time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
999 time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
1000 time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
1001 size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
1004 using Handlers = std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
1005 using HandlersForContentReader =
1006 std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, HandlerWithContentReader>>;
1008 static std::unique_ptr<detail::MatcherBase> make_matcher(
const std::string &pattern);
1010 Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
1011 Server &set_error_handler_core(Handler handler, std::false_type);
1013 socket_t create_server_socket(
const std::string &host,
int port,
int socket_flags,
1014 SocketOptions socket_options)
const;
1015 int bind_internal(
const std::string &host,
int port,
int socket_flags);
1016 bool listen_internal();
1018 bool routing(Request &req, Response &res, Stream &strm);
1019 bool handle_file_request(
const Request &req, Response &res,
bool head =
false);
1020 bool dispatch_request(Request &req, Response &res,
const Handlers &handlers)
const;
1021 bool dispatch_request_for_content_reader(Request &req, Response &res, ContentReader content_reader,
1022 const HandlersForContentReader &handlers)
const;
1024 bool parse_request_line(
const char *s, Request &req)
const;
1025 void apply_ranges(
const Request &req, Response &res, std::string &content_type, std::string &boundary)
const;
1026 bool write_response(Stream &strm,
bool close_connection, Request &req, Response &res);
1027 bool write_response_with_content(Stream &strm,
bool close_connection,
const Request &req, Response &res);
1028 bool write_response_core(Stream &strm,
bool close_connection,
const Request &req, Response &res,
1029 bool need_apply_ranges);
1030 bool write_content_with_provider(Stream &strm,
const Request &req, Response &res,
const std::string &boundary,
1031 const std::string &content_type);
1032 bool read_content(Stream &strm, Request &req, Response &res);
1033 bool read_content_with_content_receiver(Stream &strm, Request &req, Response &res, ContentReceiver receiver,
1034 MultipartContentHeader multipart_header, ContentReceiver multipart_receiver);
1035 bool read_content_core(Stream &strm, Request &req, Response &res, ContentReceiver receiver,
1036 MultipartContentHeader multipart_header, ContentReceiver multipart_receiver)
const;
1038 virtual bool process_and_close_socket(
socket_t sock);
1040 std::atomic<bool> is_running_{
false};
1041 std::atomic<bool> is_decommisioned{
false};
1043 struct MountPointEntry {
1044 std::string mount_point;
1045 std::string base_dir;
1048 std::vector<MountPointEntry> base_dirs_;
1049 std::map<std::string, std::string> file_extension_and_mimetype_map_;
1050 std::string default_file_mimetype_ =
"application/octet-stream";
1051 Handler file_request_handler_;
1053 Handlers get_handlers_;
1054 Handlers post_handlers_;
1055 HandlersForContentReader post_handlers_for_content_reader_;
1056 Handlers put_handlers_;
1057 HandlersForContentReader put_handlers_for_content_reader_;
1058 Handlers patch_handlers_;
1059 HandlersForContentReader patch_handlers_for_content_reader_;
1060 Handlers delete_handlers_;
1061 HandlersForContentReader delete_handlers_for_content_reader_;
1062 Handlers options_handlers_;
1064 HandlerWithResponse error_handler_;
1065 ExceptionHandler exception_handler_;
1066 HandlerWithResponse pre_routing_handler_;
1067 Handler post_routing_handler_;
1068 Expect100ContinueHandler expect_100_continue_handler_;
1072 int address_family_ = AF_UNSPEC;
1073 bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
1074 bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
1075 SocketOptions socket_options_ = default_socket_options;
1077 Headers default_headers_;
1078 std::function<
ssize_t(Stream &, Headers &)> header_writer_ = detail::write_headers;
1088 ExceedRedirectCount,
1092 SSLServerVerification,
1093 SSLServerHostnameVerification,
1094 UnsupportedMultipartBoundaryChars,
1100 SSLPeerCouldBeClosed_,
1103std::string to_string(Error error);
1105std::ostream &operator<<(std::ostream &os,
const Error &obj);
1110 Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers = Headers{})
1111 : res_(std::move(res)), err_(err), request_headers_(std::move(request_headers)) {}
1113 operator bool()
const {
return res_ !=
nullptr; }
1114 bool operator==(std::nullptr_t)
const {
return res_ ==
nullptr; }
1115 bool operator!=(std::nullptr_t)
const {
return res_ !=
nullptr; }
1116 const Response &value()
const {
return *res_; }
1117 Response &value() {
return *res_; }
1118 const Response &operator*()
const {
return *res_; }
1119 Response &operator*() {
return *res_; }
1120 const Response *operator->()
const {
return res_.get(); }
1121 Response *operator->() {
return res_.get(); }
1124 Error error()
const {
return err_; }
1127 bool has_request_header(
const std::string &
key)
const;
1128 std::string get_request_header_value(
const std::string &
key,
const char *def =
"",
size_t id = 0)
const;
1129 uint64_t get_request_header_value_u64(
const std::string &
key, uint64_t def = 0,
size_t id = 0)
const;
1130 size_t get_request_header_value_count(
const std::string &
key)
const;
1133 std::unique_ptr<Response> res_;
1134 Error err_ = Error::Unknown;
1135 Headers request_headers_;
1140 explicit ClientImpl(
const std::string &host);
1142 explicit ClientImpl(
const std::string &host,
int port);
1144 explicit ClientImpl(
const std::string &host,
int port,
const std::string &client_cert_path,
1145 const std::string &client_key_path);
1147 virtual ~ClientImpl();
1149 virtual bool is_valid()
const;
1151 Result Get(
const std::string &path);
1152 Result Get(
const std::string &path,
const Headers &headers);
1153 Result Get(
const std::string &path, Progress progress);
1154 Result Get(
const std::string &path,
const Headers &headers, Progress progress);
1155 Result Get(
const std::string &path, ContentReceiver content_receiver);
1156 Result Get(
const std::string &path,
const Headers &headers, ContentReceiver content_receiver);
1157 Result Get(
const std::string &path, ContentReceiver content_receiver, Progress progress);
1158 Result Get(
const std::string &path,
const Headers &headers, ContentReceiver content_receiver, Progress progress);
1159 Result Get(
const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver);
1160 Result Get(
const std::string &path,
const Headers &headers, ResponseHandler response_handler,
1161 ContentReceiver content_receiver);
1162 Result Get(
const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver,
1164 Result Get(
const std::string &path,
const Headers &headers, ResponseHandler response_handler,
1165 ContentReceiver content_receiver, Progress progress);
1167 Result Get(
const std::string &path,
const Params ¶ms,
const Headers &headers, Progress progress =
nullptr);
1168 Result Get(
const std::string &path,
const Params ¶ms,
const Headers &headers, ContentReceiver content_receiver,
1169 Progress progress =
nullptr);
1170 Result Get(
const std::string &path,
const Params ¶ms,
const Headers &headers, ResponseHandler response_handler,
1171 ContentReceiver content_receiver, Progress progress =
nullptr);
1173 Result Head(
const std::string &path);
1174 Result Head(
const std::string &path,
const Headers &headers);
1176 Result Post(
const std::string &path);
1177 Result Post(
const std::string &path,
const Headers &headers);
1178 Result Post(
const std::string &path,
const char *body,
size_t content_length,
const std::string &content_type);
1179 Result Post(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
1180 const std::string &content_type);
1181 Result Post(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
1182 const std::string &content_type, Progress progress);
1183 Result Post(
const std::string &path,
const std::string &body,
const std::string &content_type);
1184 Result Post(
const std::string &path,
const std::string &body,
const std::string &content_type, Progress progress);
1185 Result Post(
const std::string &path,
const Headers &headers,
const std::string &body,
1186 const std::string &content_type);
1187 Result Post(
const std::string &path,
const Headers &headers,
const std::string &body,
const std::string &content_type,
1189 Result Post(
const std::string &path,
size_t content_length, ContentProvider content_provider,
1190 const std::string &content_type);
1191 Result Post(
const std::string &path, ContentProviderWithoutLength content_provider,
const std::string &content_type);
1192 Result Post(
const std::string &path,
const Headers &headers,
size_t content_length, ContentProvider content_provider,
1193 const std::string &content_type);
1194 Result Post(
const std::string &path,
const Headers &headers, ContentProviderWithoutLength content_provider,
1195 const std::string &content_type);
1196 Result Post(
const std::string &path,
const Params ¶ms);
1197 Result Post(
const std::string &path,
const Headers &headers,
const Params ¶ms);
1198 Result Post(
const std::string &path,
const Headers &headers,
const Params ¶ms, Progress progress);
1199 Result Post(
const std::string &path,
const MultipartFormDataItems &items);
1200 Result Post(
const std::string &path,
const Headers &headers,
const MultipartFormDataItems &items);
1201 Result Post(
const std::string &path,
const Headers &headers,
const MultipartFormDataItems &items,
1202 const std::string &boundary);
1203 Result Post(
const std::string &path,
const Headers &headers,
const MultipartFormDataItems &items,
1204 const MultipartFormDataProviderItems &provider_items);
1206 Result Put(
const std::string &path);
1207 Result Put(
const std::string &path,
const char *body,
size_t content_length,
const std::string &content_type);
1208 Result Put(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
1209 const std::string &content_type);
1210 Result Put(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
1211 const std::string &content_type, Progress progress);
1212 Result Put(
const std::string &path,
const std::string &body,
const std::string &content_type);
1213 Result Put(
const std::string &path,
const std::string &body,
const std::string &content_type, Progress progress);
1214 Result Put(
const std::string &path,
const Headers &headers,
const std::string &body,
const std::string &content_type);
1215 Result Put(
const std::string &path,
const Headers &headers,
const std::string &body,
const std::string &content_type,
1217 Result Put(
const std::string &path,
size_t content_length, ContentProvider content_provider,
1218 const std::string &content_type);
1219 Result Put(
const std::string &path, ContentProviderWithoutLength content_provider,
const std::string &content_type);
1220 Result Put(
const std::string &path,
const Headers &headers,
size_t content_length, ContentProvider content_provider,
1221 const std::string &content_type);
1222 Result Put(
const std::string &path,
const Headers &headers, ContentProviderWithoutLength content_provider,
1223 const std::string &content_type);
1224 Result Put(
const std::string &path,
const Params ¶ms);
1225 Result Put(
const std::string &path,
const Headers &headers,
const Params ¶ms);
1226 Result Put(
const std::string &path,
const Headers &headers,
const Params ¶ms, Progress progress);
1227 Result Put(
const std::string &path,
const MultipartFormDataItems &items);
1228 Result Put(
const std::string &path,
const Headers &headers,
const MultipartFormDataItems &items);
1229 Result Put(
const std::string &path,
const Headers &headers,
const MultipartFormDataItems &items,
1230 const std::string &boundary);
1231 Result Put(
const std::string &path,
const Headers &headers,
const MultipartFormDataItems &items,
1232 const MultipartFormDataProviderItems &provider_items);
1234 Result Patch(
const std::string &path);
1235 Result Patch(
const std::string &path,
const char *body,
size_t content_length,
const std::string &content_type);
1236 Result Patch(
const std::string &path,
const char *body,
size_t content_length,
const std::string &content_type,
1238 Result Patch(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
1239 const std::string &content_type);
1240 Result Patch(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
1241 const std::string &content_type, Progress progress);
1242 Result Patch(
const std::string &path,
const std::string &body,
const std::string &content_type);
1243 Result Patch(
const std::string &path,
const std::string &body,
const std::string &content_type, Progress progress);
1244 Result Patch(
const std::string &path,
const Headers &headers,
const std::string &body,
1245 const std::string &content_type);
1246 Result Patch(
const std::string &path,
const Headers &headers,
const std::string &body,
1247 const std::string &content_type, Progress progress);
1248 Result Patch(
const std::string &path,
size_t content_length, ContentProvider content_provider,
1249 const std::string &content_type);
1250 Result Patch(
const std::string &path, ContentProviderWithoutLength content_provider,
const std::string &content_type);
1251 Result Patch(
const std::string &path,
const Headers &headers,
size_t content_length, ContentProvider content_provider,
1252 const std::string &content_type);
1253 Result Patch(
const std::string &path,
const Headers &headers, ContentProviderWithoutLength content_provider,
1254 const std::string &content_type);
1256 Result Delete(
const std::string &path);
1257 Result Delete(
const std::string &path,
const Headers &headers);
1258 Result Delete(
const std::string &path,
const char *body,
size_t content_length,
const std::string &content_type);
1259 Result Delete(
const std::string &path,
const char *body,
size_t content_length,
const std::string &content_type,
1261 Result Delete(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
1262 const std::string &content_type);
1263 Result Delete(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
1264 const std::string &content_type, Progress progress);
1265 Result Delete(
const std::string &path,
const std::string &body,
const std::string &content_type);
1266 Result Delete(
const std::string &path,
const std::string &body,
const std::string &content_type, Progress progress);
1267 Result Delete(
const std::string &path,
const Headers &headers,
const std::string &body,
1268 const std::string &content_type);
1269 Result Delete(
const std::string &path,
const Headers &headers,
const std::string &body,
1270 const std::string &content_type, Progress progress);
1272 Result Options(
const std::string &path);
1273 Result Options(
const std::string &path,
const Headers &headers);
1275 bool send(Request &req, Response &res, Error &error);
1276 Result send(
const Request &req);
1280 std::string host()
const;
1283 size_t is_socket_open()
const;
1286 void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
1288 void set_default_headers(Headers headers);
1290 void set_header_writer(std::function<
ssize_t(Stream &, Headers &)>
const &writer);
1292 void set_address_family(
int family);
1293 void set_tcp_nodelay(
bool on);
1294 void set_ipv6_v6only(
bool on);
1295 void set_socket_options(SocketOptions socket_options);
1297 void set_connection_timeout(time_t sec, time_t usec = 0);
1298 template<
class Rep,
class Period>
void set_connection_timeout(
const std::chrono::duration<Rep, Period> &
duration);
1300 void set_read_timeout(time_t sec, time_t usec = 0);
1301 template<
class Rep,
class Period>
void set_read_timeout(
const std::chrono::duration<Rep, Period> &
duration);
1303 void set_write_timeout(time_t sec, time_t usec = 0);
1304 template<
class Rep,
class Period>
void set_write_timeout(
const std::chrono::duration<Rep, Period> &
duration);
1306 void set_basic_auth(
const std::string &username,
const std::string &password);
1307 void set_bearer_token_auth(
const std::string &token);
1308#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
1309 void set_digest_auth(
const std::string &username,
const std::string &password);
1312 void set_keep_alive(
bool on);
1313 void set_follow_location(
bool on);
1315 void set_url_encode(
bool on);
1317 void set_compress(
bool on);
1319 void set_decompress(
bool on);
1321 void set_interface(
const std::string &intf);
1323 void set_proxy(
const std::string &host,
int port);
1324 void set_proxy_basic_auth(
const std::string &username,
const std::string &password);
1325 void set_proxy_bearer_token_auth(
const std::string &token);
1326#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
1327 void set_proxy_digest_auth(
const std::string &username,
const std::string &password);
1330#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
1331 void set_ca_cert_path(
const std::string &ca_cert_file_path,
const std::string &ca_cert_dir_path = std::string());
1332 void set_ca_cert_store(X509_STORE *ca_cert_store);
1333 X509_STORE *create_ca_cert_store(
const char *ca_cert, std::size_t size)
const;
1336#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
1337 void enable_server_certificate_verification(
bool enabled);
1338 void enable_server_hostname_verification(
bool enabled);
1339 void set_server_certificate_verifier(std::function<
bool(SSL *ssl)> verifier);
1342 void set_logger(Logger logger);
1347#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
1351 bool is_open()
const {
return sock != INVALID_SOCKET; }
1354 virtual bool create_and_connect_socket(Socket &socket, Error &error);
1363 virtual void shutdown_ssl(Socket &socket,
bool shutdown_gracefully);
1364 void shutdown_socket(Socket &socket)
const;
1365 void close_socket(Socket &socket);
1367 bool process_request(Stream &strm, Request &req, Response &res,
bool close_connection, Error &error);
1369 bool write_content_with_provider(Stream &strm,
const Request &req, Error &error)
const;
1371 void copy_settings(
const ClientImpl &rhs);
1374 const std::string host_;
1376 const std::string host_and_port_;
1380 mutable std::mutex socket_mutex_;
1381 std::recursive_mutex request_mutex_;
1384 size_t socket_requests_in_flight_ = 0;
1385 std::thread::id socket_requests_are_from_thread_ = std::thread::id();
1386 bool socket_should_be_closed_when_request_is_done_ =
false;
1389 std::map<std::string, std::string> addr_map_;
1392 Headers default_headers_;
1395 std::function<
ssize_t(Stream &, Headers &)> header_writer_ = detail::write_headers;
1398 std::string client_cert_path_;
1399 std::string client_key_path_;
1401 time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
1402 time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
1403 time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
1404 time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
1405 time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
1406 time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
1408 std::string basic_auth_username_;
1409 std::string basic_auth_password_;
1410 std::string bearer_token_auth_token_;
1411#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
1412 std::string digest_auth_username_;
1413 std::string digest_auth_password_;
1416 bool keep_alive_ =
false;
1417 bool follow_location_ =
false;
1419 bool url_encode_ =
true;
1421 int address_family_ = AF_UNSPEC;
1422 bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
1423 bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
1424 SocketOptions socket_options_ =
nullptr;
1426 bool compress_ =
false;
1427 bool decompress_ =
true;
1429 std::string interface_;
1431 std::string proxy_host_;
1432 int proxy_port_ = -1;
1434 std::string proxy_basic_auth_username_;
1435 std::string proxy_basic_auth_password_;
1436 std::string proxy_bearer_token_auth_token_;
1437#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
1438 std::string proxy_digest_auth_username_;
1439 std::string proxy_digest_auth_password_;
1442#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
1443 std::string ca_cert_file_path_;
1444 std::string ca_cert_dir_path_;
1446 X509_STORE *ca_cert_store_ =
nullptr;
1449#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
1450 bool server_certificate_verification_ =
true;
1451 bool server_hostname_verification_ =
true;
1452 std::function<bool(SSL *ssl)> server_certificate_verifier_;
1458 bool send_(Request &req, Response &res, Error &error);
1459 Result send_(Request &&req);
1461#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
1462 bool is_ssl_peer_could_be_closed(SSL *ssl)
const;
1464 socket_t create_client_socket(Error &error)
const;
1465 bool read_response_line(Stream &strm,
const Request &req, Response &res)
const;
1466 bool write_request(Stream &strm, Request &req,
bool close_connection, Error &error);
1467 bool redirect(Request &req, Response &res, Error &error);
1468 bool handle_request(Stream &strm, Request &req, Response &res,
bool close_connection, Error &error);
1469 std::unique_ptr<Response> send_with_content_provider(Request &req,
const char *body,
size_t content_length,
1470 ContentProvider content_provider,
1471 ContentProviderWithoutLength content_provider_without_length,
1472 const std::string &content_type, Error &error);
1473 Result send_with_content_provider(
const std::string &method,
const std::string &path,
const Headers &headers,
1474 const char *body,
size_t content_length, ContentProvider content_provider,
1475 ContentProviderWithoutLength content_provider_without_length,
1476 const std::string &content_type, Progress progress);
1477 ContentProviderWithoutLength get_multipart_content_provider(
1478 const std::string &boundary,
const MultipartFormDataItems &items,
1479 const MultipartFormDataProviderItems &provider_items)
const;
1481 std::string adjust_host_string(
const std::string &host)
const;
1483 virtual bool process_socket(
const Socket &socket, std::function<
bool(Stream &strm)> callback);
1484 virtual bool is_ssl()
const;
1490 explicit Client(
const std::string &scheme_host_port);
1492 explicit Client(
const std::string &scheme_host_port,
const std::string &client_cert_path,
1493 const std::string &client_key_path);
1496 explicit Client(
const std::string &host,
int port);
1498 explicit Client(
const std::string &host,
int port,
const std::string &client_cert_path,
1499 const std::string &client_key_path);
1501 Client(Client &&) =
default;
1502 Client &operator=(Client &&) =
default;
1506 bool is_valid()
const;
1508 Result Get(
const std::string &path);
1509 Result Get(
const std::string &path,
const Headers &headers);
1510 Result Get(
const std::string &path, Progress progress);
1511 Result Get(
const std::string &path,
const Headers &headers, Progress progress);
1512 Result Get(
const std::string &path, ContentReceiver content_receiver);
1513 Result Get(
const std::string &path,
const Headers &headers, ContentReceiver content_receiver);
1514 Result Get(
const std::string &path, ContentReceiver content_receiver, Progress progress);
1515 Result Get(
const std::string &path,
const Headers &headers, ContentReceiver content_receiver, Progress progress);
1516 Result Get(
const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver);
1517 Result Get(
const std::string &path,
const Headers &headers, ResponseHandler response_handler,
1518 ContentReceiver content_receiver);
1519 Result Get(
const std::string &path,
const Headers &headers, ResponseHandler response_handler,
1520 ContentReceiver content_receiver, Progress progress);
1521 Result Get(
const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver,
1524 Result Get(
const std::string &path,
const Params ¶ms,
const Headers &headers, Progress progress =
nullptr);
1525 Result Get(
const std::string &path,
const Params ¶ms,
const Headers &headers, ContentReceiver content_receiver,
1526 Progress progress =
nullptr);
1527 Result Get(
const std::string &path,
const Params ¶ms,
const Headers &headers, ResponseHandler response_handler,
1528 ContentReceiver content_receiver, Progress progress =
nullptr);
1530 Result Head(
const std::string &path);
1531 Result Head(
const std::string &path,
const Headers &headers);
1533 Result Post(
const std::string &path);
1534 Result Post(
const std::string &path,
const Headers &headers);
1535 Result Post(
const std::string &path,
const char *body,
size_t content_length,
const std::string &content_type);
1536 Result Post(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
1537 const std::string &content_type);
1538 Result Post(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
1539 const std::string &content_type, Progress progress);
1540 Result Post(
const std::string &path,
const std::string &body,
const std::string &content_type);
1541 Result Post(
const std::string &path,
const std::string &body,
const std::string &content_type, Progress progress);
1542 Result Post(
const std::string &path,
const Headers &headers,
const std::string &body,
1543 const std::string &content_type);
1544 Result Post(
const std::string &path,
const Headers &headers,
const std::string &body,
const std::string &content_type,
1546 Result Post(
const std::string &path,
size_t content_length, ContentProvider content_provider,
1547 const std::string &content_type);
1548 Result Post(
const std::string &path, ContentProviderWithoutLength content_provider,
const std::string &content_type);
1549 Result Post(
const std::string &path,
const Headers &headers,
size_t content_length, ContentProvider content_provider,
1550 const std::string &content_type);
1551 Result Post(
const std::string &path,
const Headers &headers, ContentProviderWithoutLength content_provider,
1552 const std::string &content_type);
1553 Result Post(
const std::string &path,
const Params ¶ms);
1554 Result Post(
const std::string &path,
const Headers &headers,
const Params ¶ms);
1555 Result Post(
const std::string &path,
const Headers &headers,
const Params ¶ms, Progress progress);
1556 Result Post(
const std::string &path,
const MultipartFormDataItems &items);
1557 Result Post(
const std::string &path,
const Headers &headers,
const MultipartFormDataItems &items);
1558 Result Post(
const std::string &path,
const Headers &headers,
const MultipartFormDataItems &items,
1559 const std::string &boundary);
1560 Result Post(
const std::string &path,
const Headers &headers,
const MultipartFormDataItems &items,
1561 const MultipartFormDataProviderItems &provider_items);
1563 Result Put(
const std::string &path);
1564 Result Put(
const std::string &path,
const char *body,
size_t content_length,
const std::string &content_type);
1565 Result Put(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
1566 const std::string &content_type);
1567 Result Put(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
1568 const std::string &content_type, Progress progress);
1569 Result Put(
const std::string &path,
const std::string &body,
const std::string &content_type);
1570 Result Put(
const std::string &path,
const std::string &body,
const std::string &content_type, Progress progress);
1571 Result Put(
const std::string &path,
const Headers &headers,
const std::string &body,
const std::string &content_type);
1572 Result Put(
const std::string &path,
const Headers &headers,
const std::string &body,
const std::string &content_type,
1574 Result Put(
const std::string &path,
size_t content_length, ContentProvider content_provider,
1575 const std::string &content_type);
1576 Result Put(
const std::string &path, ContentProviderWithoutLength content_provider,
const std::string &content_type);
1577 Result Put(
const std::string &path,
const Headers &headers,
size_t content_length, ContentProvider content_provider,
1578 const std::string &content_type);
1579 Result Put(
const std::string &path,
const Headers &headers, ContentProviderWithoutLength content_provider,
1580 const std::string &content_type);
1581 Result Put(
const std::string &path,
const Params ¶ms);
1582 Result Put(
const std::string &path,
const Headers &headers,
const Params ¶ms);
1583 Result Put(
const std::string &path,
const Headers &headers,
const Params ¶ms, Progress progress);
1584 Result Put(
const std::string &path,
const MultipartFormDataItems &items);
1585 Result Put(
const std::string &path,
const Headers &headers,
const MultipartFormDataItems &items);
1586 Result Put(
const std::string &path,
const Headers &headers,
const MultipartFormDataItems &items,
1587 const std::string &boundary);
1588 Result Put(
const std::string &path,
const Headers &headers,
const MultipartFormDataItems &items,
1589 const MultipartFormDataProviderItems &provider_items);
1591 Result Patch(
const std::string &path);
1592 Result Patch(
const std::string &path,
const char *body,
size_t content_length,
const std::string &content_type);
1593 Result Patch(
const std::string &path,
const char *body,
size_t content_length,
const std::string &content_type,
1595 Result Patch(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
1596 const std::string &content_type);
1597 Result Patch(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
1598 const std::string &content_type, Progress progress);
1599 Result Patch(
const std::string &path,
const std::string &body,
const std::string &content_type);
1600 Result Patch(
const std::string &path,
const std::string &body,
const std::string &content_type, Progress progress);
1601 Result Patch(
const std::string &path,
const Headers &headers,
const std::string &body,
1602 const std::string &content_type);
1603 Result Patch(
const std::string &path,
const Headers &headers,
const std::string &body,
1604 const std::string &content_type, Progress progress);
1605 Result Patch(
const std::string &path,
size_t content_length, ContentProvider content_provider,
1606 const std::string &content_type);
1607 Result Patch(
const std::string &path, ContentProviderWithoutLength content_provider,
const std::string &content_type);
1608 Result Patch(
const std::string &path,
const Headers &headers,
size_t content_length, ContentProvider content_provider,
1609 const std::string &content_type);
1610 Result Patch(
const std::string &path,
const Headers &headers, ContentProviderWithoutLength content_provider,
1611 const std::string &content_type);
1613 Result Delete(
const std::string &path);
1614 Result Delete(
const std::string &path,
const Headers &headers);
1615 Result Delete(
const std::string &path,
const char *body,
size_t content_length,
const std::string &content_type);
1616 Result Delete(
const std::string &path,
const char *body,
size_t content_length,
const std::string &content_type,
1618 Result Delete(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
1619 const std::string &content_type);
1620 Result Delete(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
1621 const std::string &content_type, Progress progress);
1622 Result Delete(
const std::string &path,
const std::string &body,
const std::string &content_type);
1623 Result Delete(
const std::string &path,
const std::string &body,
const std::string &content_type, Progress progress);
1624 Result Delete(
const std::string &path,
const Headers &headers,
const std::string &body,
1625 const std::string &content_type);
1626 Result Delete(
const std::string &path,
const Headers &headers,
const std::string &body,
1627 const std::string &content_type, Progress progress);
1629 Result Options(
const std::string &path);
1630 Result Options(
const std::string &path,
const Headers &headers);
1632 bool send(Request &req, Response &res, Error &error);
1633 Result send(
const Request &req);
1637 std::string host()
const;
1640 size_t is_socket_open()
const;
1643 void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
1645 void set_default_headers(Headers headers);
1647 void set_header_writer(std::function<
ssize_t(Stream &, Headers &)>
const &writer);
1649 void set_address_family(
int family);
1650 void set_tcp_nodelay(
bool on);
1651 void set_socket_options(SocketOptions socket_options);
1653 void set_connection_timeout(time_t sec, time_t usec = 0);
1654 template<
class Rep,
class Period>
void set_connection_timeout(
const std::chrono::duration<Rep, Period> &
duration);
1656 void set_read_timeout(time_t sec, time_t usec = 0);
1657 template<
class Rep,
class Period>
void set_read_timeout(
const std::chrono::duration<Rep, Period> &
duration);
1659 void set_write_timeout(time_t sec, time_t usec = 0);
1660 template<
class Rep,
class Period>
void set_write_timeout(
const std::chrono::duration<Rep, Period> &
duration);
1662 void set_basic_auth(
const std::string &username,
const std::string &password);
1663 void set_bearer_token_auth(
const std::string &token);
1664#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
1665 void set_digest_auth(
const std::string &username,
const std::string &password);
1668 void set_keep_alive(
bool on);
1669 void set_follow_location(
bool on);
1671 void set_url_encode(
bool on);
1673 void set_compress(
bool on);
1675 void set_decompress(
bool on);
1677 void set_interface(
const std::string &intf);
1679 void set_proxy(
const std::string &host,
int port);
1680 void set_proxy_basic_auth(
const std::string &username,
const std::string &password);
1681 void set_proxy_bearer_token_auth(
const std::string &token);
1682#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
1683 void set_proxy_digest_auth(
const std::string &username,
const std::string &password);
1686#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
1687 void enable_server_certificate_verification(
bool enabled);
1688 void enable_server_hostname_verification(
bool enabled);
1689 void set_server_certificate_verifier(std::function<
bool(SSL *ssl)> verifier);
1692 void set_logger(Logger logger);
1695#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
1696 void set_ca_cert_path(
const std::string &ca_cert_file_path,
const std::string &ca_cert_dir_path = std::string());
1698 void set_ca_cert_store(X509_STORE *ca_cert_store);
1699 void load_ca_cert_store(
const char *ca_cert, std::size_t size);
1701 long get_openssl_verify_result()
const;
1703 SSL_CTX *ssl_context()
const;
1707 std::unique_ptr<ClientImpl> cli_;
1709#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
1710 bool is_ssl_ =
false;
1714#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
1715class SSLServer :
public Server {
1717 SSLServer(
const char *cert_path,
const char *private_key_path,
const char *client_ca_cert_file_path =
nullptr,
1718 const char *client_ca_cert_dir_path =
nullptr,
const char *private_key_password =
nullptr);
1720 SSLServer(X509 *cert, EVP_PKEY *private_key, X509_STORE *client_ca_cert_store =
nullptr);
1722 SSLServer(
const std::function<
bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback);
1724 ~SSLServer()
override;
1726 bool is_valid()
const override;
1728 SSL_CTX *ssl_context()
const;
1730 void update_certs(X509 *cert, EVP_PKEY *private_key, X509_STORE *client_ca_cert_store =
nullptr);
1733 bool process_and_close_socket(
socket_t sock)
override;
1736 std::mutex ctx_mutex_;
1739class SSLClient final :
public ClientImpl {
1741 explicit SSLClient(
const std::string &host);
1743 explicit SSLClient(
const std::string &host,
int port);
1745 explicit SSLClient(
const std::string &host,
int port,
const std::string &client_cert_path,
1746 const std::string &client_key_path,
const std::string &private_key_password = std::string());
1748 explicit SSLClient(
const std::string &host,
int port, X509 *client_cert, EVP_PKEY *client_key,
1749 const std::string &private_key_password = std::string());
1751 ~SSLClient()
override;
1753 bool is_valid()
const override;
1755 void set_ca_cert_store(X509_STORE *ca_cert_store);
1756 void load_ca_cert_store(
const char *ca_cert, std::size_t size);
1758 long get_openssl_verify_result()
const;
1760 SSL_CTX *ssl_context()
const;
1763 bool create_and_connect_socket(Socket &socket, Error &error)
override;
1764 void shutdown_ssl(Socket &socket,
bool shutdown_gracefully)
override;
1765 void shutdown_ssl_impl(Socket &socket,
bool shutdown_gracefully);
1767 bool process_socket(
const Socket &socket, std::function<
bool(Stream &strm)> callback)
override;
1768 bool is_ssl()
const override;
1770 bool connect_with_proxy(Socket &sock, Response &res,
bool &success, Error &error);
1771 bool initialize_ssl(Socket &socket, Error &error);
1775 bool verify_host(X509 *server_cert)
const;
1776 bool verify_host_with_subject_alt_name(X509 *server_cert)
const;
1777 bool verify_host_with_common_name(X509 *server_cert)
const;
1778 bool check_host_name(
const char *pattern,
size_t pattern_len)
const;
1781 std::mutex ctx_mutex_;
1782 std::once_flag initialize_cert_;
1784 std::vector<std::string> host_components_;
1786 long verify_result_ = 0;
1788 friend class ClientImpl;
1798template<
typename T,
typename U>
inline void duration_to_sec_and_usec(
const T &
duration, U callback) {
1799 auto sec = std::chrono::duration_cast<std::chrono::seconds>(
duration).count();
1800 auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
duration - std::chrono::seconds(sec)).count();
1801 callback(
static_cast<time_t
>(sec),
static_cast<time_t
>(usec));
1804inline uint64_t get_header_value_u64(
const Headers &headers,
const std::string &
key, uint64_t def,
size_t id) {
1805 auto rng = headers.equal_range(
key);
1806 auto it = rng.first;
1807 std::advance(it,
static_cast<ssize_t>(
id));
1808 if (it != rng.second) {
1809 return std::strtoull(it->second.data(),
nullptr, 10);
1816inline uint64_t Request::get_header_value_u64(
const std::string &
key, uint64_t def,
size_t id)
const {
1817 return detail::get_header_value_u64(headers,
key, def,
id);
1820inline uint64_t Response::get_header_value_u64(
const std::string &
key, uint64_t def,
size_t id)
const {
1821 return detail::get_header_value_u64(headers,
key, def,
id);
1824inline void default_socket_options(
socket_t sock) {
1827 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
reinterpret_cast<const char *
>(&opt),
sizeof(opt));
1828 setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
reinterpret_cast<const char *
>(&opt),
sizeof(opt));
1831 setsockopt(sock, SOL_SOCKET, SO_REUSEPORT,
reinterpret_cast<const void *
>(&opt),
sizeof(opt));
1833 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
reinterpret_cast<const void *
>(&opt),
sizeof(opt));
1838inline const char *status_message(
int status) {
1840 case StatusCode::Continue_100:
1842 case StatusCode::SwitchingProtocol_101:
1843 return "Switching Protocol";
1844 case StatusCode::Processing_102:
1845 return "Processing";
1846 case StatusCode::EarlyHints_103:
1847 return "Early Hints";
1848 case StatusCode::OK_200:
1850 case StatusCode::Created_201:
1852 case StatusCode::Accepted_202:
1854 case StatusCode::NonAuthoritativeInformation_203:
1855 return "Non-Authoritative Information";
1856 case StatusCode::NoContent_204:
1857 return "No Content";
1858 case StatusCode::ResetContent_205:
1859 return "Reset Content";
1860 case StatusCode::PartialContent_206:
1861 return "Partial Content";
1862 case StatusCode::MultiStatus_207:
1863 return "Multi-Status";
1864 case StatusCode::AlreadyReported_208:
1865 return "Already Reported";
1866 case StatusCode::IMUsed_226:
1868 case StatusCode::MultipleChoices_300:
1869 return "Multiple Choices";
1870 case StatusCode::MovedPermanently_301:
1871 return "Moved Permanently";
1872 case StatusCode::Found_302:
1874 case StatusCode::SeeOther_303:
1876 case StatusCode::NotModified_304:
1877 return "Not Modified";
1878 case StatusCode::UseProxy_305:
1880 case StatusCode::unused_306:
1882 case StatusCode::TemporaryRedirect_307:
1883 return "Temporary Redirect";
1884 case StatusCode::PermanentRedirect_308:
1885 return "Permanent Redirect";
1886 case StatusCode::BadRequest_400:
1887 return "Bad Request";
1888 case StatusCode::Unauthorized_401:
1889 return "Unauthorized";
1890 case StatusCode::PaymentRequired_402:
1891 return "Payment Required";
1892 case StatusCode::Forbidden_403:
1894 case StatusCode::NotFound_404:
1896 case StatusCode::MethodNotAllowed_405:
1897 return "Method Not Allowed";
1898 case StatusCode::NotAcceptable_406:
1899 return "Not Acceptable";
1900 case StatusCode::ProxyAuthenticationRequired_407:
1901 return "Proxy Authentication Required";
1902 case StatusCode::RequestTimeout_408:
1903 return "Request Timeout";
1904 case StatusCode::Conflict_409:
1906 case StatusCode::Gone_410:
1908 case StatusCode::LengthRequired_411:
1909 return "Length Required";
1910 case StatusCode::PreconditionFailed_412:
1911 return "Precondition Failed";
1912 case StatusCode::PayloadTooLarge_413:
1913 return "Payload Too Large";
1914 case StatusCode::UriTooLong_414:
1915 return "URI Too Long";
1916 case StatusCode::UnsupportedMediaType_415:
1917 return "Unsupported Media Type";
1918 case StatusCode::RangeNotSatisfiable_416:
1919 return "Range Not Satisfiable";
1920 case StatusCode::ExpectationFailed_417:
1921 return "Expectation Failed";
1922 case StatusCode::ImATeapot_418:
1923 return "I'm a teapot";
1924 case StatusCode::MisdirectedRequest_421:
1925 return "Misdirected Request";
1926 case StatusCode::UnprocessableContent_422:
1927 return "Unprocessable Content";
1928 case StatusCode::Locked_423:
1930 case StatusCode::FailedDependency_424:
1931 return "Failed Dependency";
1932 case StatusCode::TooEarly_425:
1934 case StatusCode::UpgradeRequired_426:
1935 return "Upgrade Required";
1936 case StatusCode::PreconditionRequired_428:
1937 return "Precondition Required";
1938 case StatusCode::TooManyRequests_429:
1939 return "Too Many Requests";
1940 case StatusCode::RequestHeaderFieldsTooLarge_431:
1941 return "Request Header Fields Too Large";
1942 case StatusCode::UnavailableForLegalReasons_451:
1943 return "Unavailable For Legal Reasons";
1944 case StatusCode::NotImplemented_501:
1945 return "Not Implemented";
1946 case StatusCode::BadGateway_502:
1947 return "Bad Gateway";
1948 case StatusCode::ServiceUnavailable_503:
1949 return "Service Unavailable";
1950 case StatusCode::GatewayTimeout_504:
1951 return "Gateway Timeout";
1952 case StatusCode::HttpVersionNotSupported_505:
1953 return "HTTP Version Not Supported";
1954 case StatusCode::VariantAlsoNegotiates_506:
1955 return "Variant Also Negotiates";
1956 case StatusCode::InsufficientStorage_507:
1957 return "Insufficient Storage";
1958 case StatusCode::LoopDetected_508:
1959 return "Loop Detected";
1960 case StatusCode::NotExtended_510:
1961 return "Not Extended";
1962 case StatusCode::NetworkAuthenticationRequired_511:
1963 return "Network Authentication Required";
1966 case StatusCode::InternalServerError_500:
1967 return "Internal Server Error";
1971inline std::string get_bearer_token_auth(
const Request &req) {
1972 if (req.has_header(
"Authorization")) {
1973 static std::string BearerHeaderPrefix =
"Bearer ";
1974 return req.get_header_value(
"Authorization").substr(BearerHeaderPrefix.length());
1979template<
class Rep,
class Period>
1980inline Server &Server::set_read_timeout(
const std::chrono::duration<Rep, Period> &
duration) {
1981 detail::duration_to_sec_and_usec(
duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
1985template<
class Rep,
class Period>
1986inline Server &Server::set_write_timeout(
const std::chrono::duration<Rep, Period> &
duration) {
1987 detail::duration_to_sec_and_usec(
duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
1991template<
class Rep,
class Period>
1992inline Server &Server::set_idle_interval(
const std::chrono::duration<Rep, Period> &
duration) {
1993 detail::duration_to_sec_and_usec(
duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
1997inline std::string to_string(
const Error error) {
1999 case Error::Success:
2000 return "Success (no error)";
2001 case Error::Connection:
2002 return "Could not establish connection";
2003 case Error::BindIPAddress:
2004 return "Failed to bind IP address";
2006 return "Failed to read connection";
2008 return "Failed to write connection";
2009 case Error::ExceedRedirectCount:
2010 return "Maximum redirect count exceeded";
2011 case Error::Canceled:
2012 return "Connection handling canceled";
2013 case Error::SSLConnection:
2014 return "SSL connection failed";
2015 case Error::SSLLoadingCerts:
2016 return "SSL certificate loading failed";
2017 case Error::SSLServerVerification:
2018 return "SSL server verification failed";
2019 case Error::SSLServerHostnameVerification:
2020 return "SSL server hostname verification failed";
2021 case Error::UnsupportedMultipartBoundaryChars:
2022 return "Unsupported HTTP multipart boundary characters";
2023 case Error::Compression:
2024 return "Compression failed";
2025 case Error::ConnectionTimeout:
2026 return "Connection timed out";
2027 case Error::ProxyConnection:
2028 return "Proxy connection failed";
2029 case Error::Unknown:
2038inline std::ostream &operator<<(std::ostream &os,
const Error &obj) {
2039 os << to_string(obj);
2040 os <<
" (" <<
static_cast<std::underlying_type<Error>::type
>(obj) <<
')';
2044inline uint64_t Result::get_request_header_value_u64(
const std::string &
key, uint64_t def,
size_t id)
const {
2045 return detail::get_header_value_u64(request_headers_,
key, def,
id);
2048template<
class Rep,
class Period>
2049inline void ClientImpl::set_connection_timeout(
const std::chrono::duration<Rep, Period> &
duration) {
2050 detail::duration_to_sec_and_usec(
duration, [&](time_t sec, time_t usec) { set_connection_timeout(sec, usec); });
2053template<
class Rep,
class Period>
2054inline void ClientImpl::set_read_timeout(
const std::chrono::duration<Rep, Period> &
duration) {
2055 detail::duration_to_sec_and_usec(
duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
2058template<
class Rep,
class Period>
2059inline void ClientImpl::set_write_timeout(
const std::chrono::duration<Rep, Period> &
duration) {
2060 detail::duration_to_sec_and_usec(
duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
2063template<
class Rep,
class Period>
2064inline void Client::set_connection_timeout(
const std::chrono::duration<Rep, Period> &
duration) {
2065 cli_->set_connection_timeout(
duration);
2068template<
class Rep,
class Period>
2069inline void Client::set_read_timeout(
const std::chrono::duration<Rep, Period> &
duration) {
2073template<
class Rep,
class Period>
2074inline void Client::set_write_timeout(
const std::chrono::duration<Rep, Period> &
duration) {
2083std::string hosted_at(
const std::string &hostname);
2085void hosted_at(
const std::string &hostname, std::vector<std::string> &addrs);
2087std::string append_query_params(
const std::string &path,
const Params ¶ms);
2089std::pair<std::string, std::string> make_range_header(
const Ranges &ranges);
2091std::pair<std::string, std::string> make_basic_authentication_header(
const std::string &username,
2092 const std::string &password,
2093 bool is_proxy =
false);
2098inline std::wstring u8string_to_wstring(
const char *s) {
2100 auto len =
static_cast<int>(strlen(s));
2101 auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s,
len,
nullptr, 0);
2104 wlen = ::MultiByteToWideChar(CP_UTF8, 0, s,
len,
const_cast<LPWSTR
>(
reinterpret_cast<LPCWSTR
>(ws.data())), wlen);
2105 if (wlen !=
static_cast<int>(ws.size())) {
2114 FileStat(
const std::string &path);
2115 bool is_file()
const;
2116 bool is_dir()
const;
2127std::string encode_query_param(
const std::string &value);
2129std::string decode_url(
const std::string &s,
bool convert_plus_to_space);
2131void read_file(
const std::string &path, std::string &
out);
2133std::string trim_copy(
const std::string &s);
2135void divide(
const char *data, std::size_t size,
char d,
2136 std::function<
void(
const char *, std::size_t,
const char *, std::size_t)> fn);
2138void divide(
const std::string &str,
char d,
2139 std::function<
void(
const char *, std::size_t,
const char *, std::size_t)> fn);
2141void split(
const char *b,
const char *e,
char d, std::function<
void(
const char *,
const char *)> fn);
2143void split(
const char *b,
const char *e,
char d,
size_t m, std::function<
void(
const char *,
const char *)> fn);
2145bool process_client_socket(
socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
2146 time_t write_timeout_usec, std::function<
bool(Stream &)> callback);
2148socket_t create_client_socket(
const std::string &host,
const std::string &ip,
int port,
int address_family,
2149 bool tcp_nodelay,
bool ipv6_v6only, SocketOptions socket_options,
2150 time_t connection_timeout_sec, time_t connection_timeout_usec, time_t read_timeout_sec,
2151 time_t read_timeout_usec, time_t write_timeout_sec, time_t write_timeout_usec,
2152 const std::string &intf, Error &error);
2154const char *get_header_value(
const Headers &headers,
const std::string &
key,
const char *def,
size_t id);
2156std::string params_to_query_str(
const Params ¶ms);
2158void parse_query_text(
const char *data, std::size_t size, Params ¶ms);
2160void parse_query_text(
const std::string &s, Params ¶ms);
2162bool parse_multipart_boundary(
const std::string &content_type, std::string &boundary);
2164bool parse_range_header(
const std::string &s, Ranges &ranges);
2172enum class EncodingType { None = 0, Gzip, Brotli };
2174EncodingType encoding_type(
const Request &req,
const Response &res);
2176class BufferStream final :
public Stream {
2178 BufferStream() =
default;
2179 ~BufferStream()
override =
default;
2181 bool is_readable()
const override;
2182 bool is_writable()
const override;
2183 ssize_t read(
char *ptr,
size_t size)
override;
2184 ssize_t write(
const char *ptr,
size_t size)
override;
2185 void get_remote_ip_and_port(std::string &ip,
int &port)
const override;
2186 void get_local_ip_and_port(std::string &ip,
int &port)
const override;
2189 const std::string &get_buffer()
const;
2198 virtual ~compressor() =
default;
2200 typedef std::function<bool(
const char *data,
size_t data_len)> Callback;
2201 virtual bool compress(
const char *data,
size_t data_length,
bool last, Callback callback) = 0;
2206 virtual ~decompressor() =
default;
2208 virtual bool is_valid()
const = 0;
2210 typedef std::function<bool(
const char *data,
size_t data_len)> Callback;
2211 virtual bool decompress(
const char *data,
size_t data_length, Callback callback) = 0;
2214class nocompressor final :
public compressor {
2216 ~nocompressor()
override =
default;
2218 bool compress(
const char *data,
size_t data_length,
bool , Callback callback)
override;
2221#ifdef CPPHTTPLIB_ZLIB_SUPPORT
2222class gzip_compressor final :
public compressor {
2225 ~gzip_compressor()
override;
2227 bool compress(
const char *data,
size_t data_length,
bool last, Callback callback)
override;
2230 bool is_valid_ =
false;
2234class gzip_decompressor final :
public decompressor {
2236 gzip_decompressor();
2237 ~gzip_decompressor()
override;
2239 bool is_valid()
const override;
2241 bool decompress(
const char *data,
size_t data_length, Callback callback)
override;
2244 bool is_valid_ =
false;
2249#ifdef CPPHTTPLIB_BROTLI_SUPPORT
2250class brotli_compressor final :
public compressor {
2252 brotli_compressor();
2253 ~brotli_compressor();
2255 bool compress(
const char *data,
size_t data_length,
bool last, Callback callback)
override;
2258 BrotliEncoderState *state_ =
nullptr;
2261class brotli_decompressor final :
public decompressor {
2263 brotli_decompressor();
2264 ~brotli_decompressor();
2266 bool is_valid()
const override;
2268 bool decompress(
const char *data,
size_t data_length, Callback callback)
override;
2271 BrotliDecoderResult decoder_r;
2272 BrotliDecoderState *decoder_s =
nullptr;
2278class stream_line_reader {
2280 stream_line_reader(Stream &strm,
char *fixed_buffer,
size_t fixed_buffer_size);
2281 const char *ptr()
const;
2282 size_t size()
const;
2283 bool end_with_crlf()
const;
2287 void append(
char c);
2290 char *fixed_buffer_;
2291 const size_t fixed_buffer_size_;
2292 size_t fixed_buffer_used_size_ = 0;
2293 std::string glowable_buffer_;
2298 mmap(
const char *path);
2301 bool open(
const char *path);
2304 bool is_open()
const;
2305 size_t size()
const;
2306 const char *data()
const;
2310 HANDLE hFile_ = NULL;
2311 HANDLE hMapping_ = NULL;
2316 void *addr_ =
nullptr;
2317 bool is_open_empty_file =
false;
2330inline bool is_hex(
char c,
int &v) {
2331 if (0x20 <= c && isdigit(c)) {
2334 }
else if (
'A' <= c && c <=
'F') {
2337 }
else if (
'a' <= c && c <=
'f') {
2344inline bool from_hex_to_i(
const std::string &s,
size_t i,
size_t cnt,
int &
val) {
2345 if (i >= s.size()) {
2350 for (; cnt; i++, cnt--) {
2355 if (is_hex(s[i], v)) {
2364inline std::string from_i_to_hex(
size_t n) {
2365 static const auto charset =
"0123456789abcdef";
2368 ret = charset[n & 15] +
ret;
2374inline size_t to_utf8(
int code,
char *buff) {
2375 if (code < 0x0080) {
2376 buff[0] =
static_cast<char>(code & 0x7F);
2378 }
else if (code < 0x0800) {
2379 buff[0] =
static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
2380 buff[1] =
static_cast<char>(0x80 | (code & 0x3F));
2382 }
else if (code < 0xD800) {
2383 buff[0] =
static_cast<char>(0xE0 | ((code >> 12) & 0xF));
2384 buff[1] =
static_cast<char>(0x80 | ((code >> 6) & 0x3F));
2385 buff[2] =
static_cast<char>(0x80 | (code & 0x3F));
2387 }
else if (code < 0xE000) {
2389 }
else if (code < 0x10000) {
2390 buff[0] =
static_cast<char>(0xE0 | ((code >> 12) & 0xF));
2391 buff[1] =
static_cast<char>(0x80 | ((code >> 6) & 0x3F));
2392 buff[2] =
static_cast<char>(0x80 | (code & 0x3F));
2394 }
else if (code < 0x110000) {
2395 buff[0] =
static_cast<char>(0xF0 | ((code >> 18) & 0x7));
2396 buff[1] =
static_cast<char>(0x80 | ((code >> 12) & 0x3F));
2397 buff[2] =
static_cast<char>(0x80 | ((code >> 6) & 0x3F));
2398 buff[3] =
static_cast<char>(0x80 | (code & 0x3F));
2408inline std::string base64_encode(
const std::string &in) {
2409 static const auto lookup =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2412 out.reserve(in.size());
2421 out.push_back(lookup[(
val >> valb) & 0x3F]);
2427 out.push_back(lookup[((
val << 8) >> (valb + 8)) & 0x3F]);
2430 while (
out.size() % 4) {
2437inline bool is_valid_path(
const std::string &path) {
2442 while (i < path.size() && path[i] ==
'/') {
2446 while (i < path.size()) {
2449 while (i < path.size() && path[i] !=
'/') {
2450 if (path[i] ==
'\0') {
2452 }
else if (path[i] ==
'\\') {
2461 if (!path.compare(beg,
len,
".")) {
2463 }
else if (!path.compare(beg,
len,
"..")) {
2473 while (i < path.size() && path[i] ==
'/') {
2481inline FileStat::FileStat(
const std::string &path) {
2483 auto wpath = u8string_to_wstring(path.c_str());
2484 ret_ = _wstat(wpath.c_str(), &st_);
2486 ret_ = stat(path.c_str(), &st_);
2489inline bool FileStat::is_file()
const {
return ret_ >= 0 && S_ISREG(st_.st_mode); }
2490inline bool FileStat::is_dir()
const {
return ret_ >= 0 && S_ISDIR(st_.st_mode); }
2492inline std::string encode_query_param(
const std::string &value) {
2493 std::ostringstream escaped;
2495 escaped << std::hex;
2497 for (
auto c : value) {
2498 if (std::isalnum(
static_cast<uint8_t
>(c)) || c ==
'-' || c ==
'_' || c ==
'.' || c ==
'!' || c ==
'~' || c ==
'*' ||
2499 c ==
'\'' || c ==
'(' || c ==
')') {
2502 escaped << std::uppercase;
2503 escaped << '%' << std::setw(2) << static_cast<int>(
static_cast<unsigned char>(c));
2504 escaped << std::nouppercase;
2508 return escaped.str();
2511inline std::string encode_url(
const std::string &s) {
2513 result.reserve(s.size());
2515 for (
size_t i = 0; s[i]; i++) {
2540 auto c =
static_cast<uint8_t
>(s[i]);
2544 auto len = snprintf(hex,
sizeof(hex) - 1,
"%02X", c);
2546 result.append(hex,
static_cast<size_t>(
len));
2557inline std::string decode_url(
const std::string &s,
bool convert_plus_to_space) {
2560 for (
size_t i = 0; i < s.size(); i++) {
2561 if (s[i] ==
'%' && i + 1 < s.size()) {
2562 if (s[i + 1] ==
'u') {
2564 if (from_hex_to_i(s, i + 2, 4,
val)) {
2567 size_t len = to_utf8(
val, buff);
2569 result.append(buff,
len);
2577 if (from_hex_to_i(s, i + 1, 2,
val)) {
2579 result +=
static_cast<char>(
val);
2585 }
else if (convert_plus_to_space && s[i] ==
'+') {
2595inline void read_file(
const std::string &path, std::string &
out) {
2596 std::ifstream fs(path, std::ios_base::binary);
2597 fs.seekg(0, std::ios_base::end);
2598 auto size = fs.tellg();
2600 out.resize(
static_cast<size_t>(size));
2601 fs.read(&
out[0],
static_cast<std::streamsize
>(size));
2604inline std::string file_extension(
const std::string &path) {
2606 static auto re = std::regex(
"\\.([a-zA-Z0-9]+)$");
2607 if (std::regex_search(path,
m, re)) {
2610 return std::string();
2613inline bool is_space_or_tab(
char c) {
return c ==
' ' || c ==
'\t'; }
2615inline std::pair<size_t, size_t> trim(
const char *b,
const char *e,
size_t left,
size_t right) {
2616 while (b + left < e && is_space_or_tab(b[left])) {
2619 while (right > 0 && is_space_or_tab(b[right - 1])) {
2622 return std::make_pair(left, right);
2625inline std::string trim_copy(
const std::string &s) {
2626 auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
2627 return s.substr(r.first, r.second - r.first);
2630inline std::string trim_double_quotes_copy(
const std::string &s) {
2631 if (s.length() >= 2 && s.front() ==
'"' && s.back() ==
'"') {
2632 return s.substr(1, s.size() - 2);
2637inline void divide(
const char *data, std::size_t size,
char d,
2638 std::function<
void(
const char *, std::size_t,
const char *, std::size_t)> fn) {
2639 const auto it = std::find(data, data + size, d);
2640 const auto found =
static_cast<std::size_t
>(it != data + size);
2641 const auto lhs_data = data;
2642 const auto lhs_size =
static_cast<std::size_t
>(it - data);
2643 const auto rhs_data = it + found;
2644 const auto rhs_size = size - lhs_size - found;
2646 fn(lhs_data, lhs_size, rhs_data, rhs_size);
2649inline void divide(
const std::string &str,
char d,
2650 std::function<
void(
const char *, std::size_t,
const char *, std::size_t)> fn) {
2651 divide(str.data(), str.size(), d, std::move(fn));
2654inline void split(
const char *b,
const char *e,
char d, std::function<
void(
const char *,
const char *)> fn) {
2655 return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
2658inline void split(
const char *b,
const char *e,
char d,
size_t m, std::function<
void(
const char *,
const char *)> fn) {
2663 while (e ? (b + i < e) : (b[i] !=
'\0')) {
2664 if (b[i] == d &&
count <
m) {
2665 auto r = trim(b, e, beg, i);
2666 if (r.first < r.second) {
2667 fn(&b[r.first], &b[r.second]);
2676 auto r = trim(b, e, beg, i);
2677 if (r.first < r.second) {
2678 fn(&b[r.first], &b[r.second]);
2683inline stream_line_reader::stream_line_reader(Stream &strm,
char *fixed_buffer,
size_t fixed_buffer_size)
2684 : strm_(strm), fixed_buffer_(fixed_buffer), fixed_buffer_size_(fixed_buffer_size) {}
2686inline const char *stream_line_reader::ptr()
const {
2687 if (glowable_buffer_.empty()) {
2688 return fixed_buffer_;
2690 return glowable_buffer_.data();
2694inline size_t stream_line_reader::size()
const {
2695 if (glowable_buffer_.empty()) {
2696 return fixed_buffer_used_size_;
2698 return glowable_buffer_.size();
2702inline bool stream_line_reader::end_with_crlf()
const {
2703 auto end = ptr() + size();
2704 return size() >= 2 &&
end[-2] ==
'\r' &&
end[-1] ==
'\n';
2707inline bool stream_line_reader::getline() {
2708 fixed_buffer_used_size_ = 0;
2709 glowable_buffer_.clear();
2711#ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
2715 for (
size_t i = 0;; i++) {
2717 auto n = strm_.read(&
byte, 1);
2721 }
else if (n == 0) {
2731#ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
2736 if (prev_byte ==
'\r' &&
byte ==
'\n') {
2746inline void stream_line_reader::append(
char c) {
2747 if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
2748 fixed_buffer_[fixed_buffer_used_size_++] = c;
2749 fixed_buffer_[fixed_buffer_used_size_] =
'\0';
2751 if (glowable_buffer_.empty()) {
2752 assert(fixed_buffer_[fixed_buffer_used_size_] ==
'\0');
2753 glowable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
2755 glowable_buffer_ += c;
2759inline mmap::mmap(
const char *path) { open(path); }
2761inline mmap::~mmap() { close(); }
2763inline bool mmap::open(
const char *path) {
2767 auto wpath = u8string_to_wstring(path);
2768 if (wpath.empty()) {
2772#if _WIN32_WINNT >= _WIN32_WINNT_WIN8
2773 hFile_ = ::CreateFile2(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, NULL);
2776 ::CreateFileW(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
2779 if (hFile_ == INVALID_HANDLE_VALUE) {
2783 LARGE_INTEGER size{};
2784 if (!::GetFileSizeEx(hFile_, &size)) {
2790 if (
static_cast<ULONGLONG
>(size.QuadPart) > (std::numeric_limits<
decltype(size_)>::max)()) {
2794 size_ =
static_cast<size_t>(size.QuadPart);
2796#if _WIN32_WINNT >= _WIN32_WINNT_WIN8
2797 hMapping_ = ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
2799 hMapping_ = ::CreateFileMappingW(hFile_, NULL, PAGE_READONLY, 0, 0, NULL);
2803 if (hMapping_ == NULL && size_ == 0) {
2805 is_open_empty_file =
true;
2809 if (hMapping_ == NULL) {
2814#if _WIN32_WINNT >= _WIN32_WINNT_WIN8
2815 addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
2817 addr_ = ::MapViewOfFile(hMapping_, FILE_MAP_READ, 0, 0, 0);
2820 if (addr_ ==
nullptr) {
2825 fd_ = ::open(path, O_RDONLY);
2831 if (fstat(fd_, &sb) == -1) {
2835 size_ =
static_cast<size_t>(sb.st_size);
2837 addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
2840 if (addr_ == MAP_FAILED && size_ == 0) {
2842 is_open_empty_file =
true;
2850inline bool mmap::is_open()
const {
return is_open_empty_file ? true : addr_ !=
nullptr; }
2852inline size_t mmap::size()
const {
return size_; }
2854inline const char *mmap::data()
const {
return is_open_empty_file ?
"" :
static_cast<const char *
>(addr_); }
2856inline void mmap::close() {
2859 ::UnmapViewOfFile(addr_);
2864 ::CloseHandle(hMapping_);
2868 if (hFile_ != INVALID_HANDLE_VALUE) {
2869 ::CloseHandle(hFile_);
2870 hFile_ = INVALID_HANDLE_VALUE;
2873 is_open_empty_file =
false;
2875 if (addr_ !=
nullptr) {
2876 munmap(addr_, size_);
2887inline int close_socket(
socket_t sock) {
2889 return closesocket(sock);
2895template<
typename T>
inline ssize_t handle_EINTR(T fn) {
2899 if (res < 0 && errno == EINTR) {
2900 std::this_thread::sleep_for(std::chrono::microseconds{1});
2909 return handle_EINTR([&]() {
2912 static_cast<char *
>(ptr),
static_cast<int>(size),
2921 return handle_EINTR([&]() {
2924 static_cast<const char *
>(ptr),
static_cast<int>(size),
2933#ifdef CPPHTTPLIB_USE_POLL
2934 struct pollfd pfd_read;
2936 pfd_read.events = POLLIN;
2938 auto timeout =
static_cast<int>(sec * 1000 + usec / 1000);
2940 return handle_EINTR([&]() {
return poll(&pfd_read, 1, timeout); });
2943 if (sock >= FD_SETSIZE) {
2953 tv.tv_sec =
static_cast<long>(sec);
2954 tv.tv_usec =
static_cast<decltype(tv.tv_usec)
>(usec);
2956 return handle_EINTR([&]() {
return select(
static_cast<int>(sock + 1), &fds,
nullptr,
nullptr, &tv); });
2961#ifdef CPPHTTPLIB_USE_POLL
2962 struct pollfd pfd_read;
2964 pfd_read.events = POLLOUT;
2966 auto timeout =
static_cast<int>(sec * 1000 + usec / 1000);
2968 return handle_EINTR([&]() {
return poll(&pfd_read, 1, timeout); });
2971 if (sock >= FD_SETSIZE) {
2981 tv.tv_sec =
static_cast<long>(sec);
2982 tv.tv_usec =
static_cast<decltype(tv.tv_usec)
>(usec);
2984 return handle_EINTR([&]() {
return select(
static_cast<int>(sock + 1),
nullptr, &fds,
nullptr, &tv); });
2988inline Error wait_until_socket_is_ready(
socket_t sock, time_t sec, time_t usec) {
2989#ifdef CPPHTTPLIB_USE_POLL
2990 struct pollfd pfd_read;
2992 pfd_read.events = POLLIN | POLLOUT;
2994 auto timeout =
static_cast<int>(sec * 1000 + usec / 1000);
2996 auto poll_res = handle_EINTR([&]() {
return poll(&pfd_read, 1, timeout); });
2998 if (poll_res == 0) {
2999 return Error::ConnectionTimeout;
3002 if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
3005 auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
reinterpret_cast<char *
>(&error), &
len);
3006 auto successful = res >= 0 && !error;
3007 return successful ? Error::Success : Error::Connection;
3010 return Error::Connection;
3013 if (sock >= FD_SETSIZE) {
3014 return Error::Connection;
3020 FD_SET(sock, &fdsr);
3026 tv.tv_sec =
static_cast<long>(sec);
3027 tv.tv_usec =
static_cast<decltype(tv.tv_usec)
>(usec);
3029 auto ret = handle_EINTR([&]() {
return select(
static_cast<int>(sock + 1), &fdsr, &fdsw, &fdse, &tv); });
3032 return Error::ConnectionTimeout;
3035 if (
ret > 0 && (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) {
3038 auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
reinterpret_cast<char *
>(&error), &
len);
3039 auto successful = res >= 0 && !error;
3040 return successful ? Error::Success : Error::Connection;
3042 return Error::Connection;
3046inline bool is_socket_alive(
socket_t sock) {
3047 const auto val = detail::select_read(sock, 0, 0);
3050 }
else if (
val < 0 && errno == EBADF) {
3054 return detail::read_socket(sock, &buf[0],
sizeof(buf), MSG_PEEK) > 0;
3057class SocketStream final :
public Stream {
3059 SocketStream(
socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
3060 time_t write_timeout_usec);
3061 ~SocketStream()
override;
3063 bool is_readable()
const override;
3064 bool is_writable()
const override;
3065 ssize_t read(
char *ptr,
size_t size)
override;
3066 ssize_t write(
const char *ptr,
size_t size)
override;
3067 void get_remote_ip_and_port(std::string &ip,
int &port)
const override;
3068 void get_local_ip_and_port(std::string &ip,
int &port)
const override;
3073 time_t read_timeout_sec_;
3074 time_t read_timeout_usec_;
3075 time_t write_timeout_sec_;
3076 time_t write_timeout_usec_;
3078 std::vector<char> read_buff_;
3079 size_t read_buff_off_ = 0;
3080 size_t read_buff_content_size_ = 0;
3082 static const size_t read_buff_size_ = 1024l * 4;
3085#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
3086class SSLSocketStream final :
public Stream {
3088 SSLSocketStream(
socket_t sock, SSL *ssl, time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
3089 time_t write_timeout_usec);
3090 ~SSLSocketStream()
override;
3092 bool is_readable()
const override;
3093 bool is_writable()
const override;
3094 ssize_t read(
char *ptr,
size_t size)
override;
3095 ssize_t write(
const char *ptr,
size_t size)
override;
3096 void get_remote_ip_and_port(std::string &ip,
int &port)
const override;
3097 void get_local_ip_and_port(std::string &ip,
int &port)
const override;
3103 time_t read_timeout_sec_;
3104 time_t read_timeout_usec_;
3105 time_t write_timeout_sec_;
3106 time_t write_timeout_usec_;
3110inline bool keep_alive(
const std::atomic<socket_t> &svr_sock,
socket_t sock, time_t keep_alive_timeout_sec) {
3111 using namespace std::chrono;
3113 const auto interval_usec = CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
3116 if (select_read(sock, 0, interval_usec) > 0) {
3120 const auto start = steady_clock::now() - microseconds{interval_usec};
3121 const auto timeout = seconds{keep_alive_timeout_sec};
3124 if (svr_sock == INVALID_SOCKET) {
3128 auto val = select_read(sock, 0, interval_usec);
3131 }
else if (
val == 0) {
3132 if (steady_clock::now() - start > timeout) {
3144inline bool process_server_socket_core(
const std::atomic<socket_t> &svr_sock,
socket_t sock,
3145 size_t keep_alive_max_count, time_t keep_alive_timeout_sec, T callback) {
3146 assert(keep_alive_max_count > 0);
3148 auto count = keep_alive_max_count;
3149 while (
count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
3150 auto close_connection =
count == 1;
3151 auto connection_closed =
false;
3152 ret = callback(close_connection, connection_closed);
3153 if (!
ret || connection_closed) {
3162inline bool process_server_socket(
const std::atomic<socket_t> &svr_sock,
socket_t sock,
size_t keep_alive_max_count,
3163 time_t keep_alive_timeout_sec, time_t read_timeout_sec, time_t read_timeout_usec,
3164 time_t write_timeout_sec, time_t write_timeout_usec, T callback) {
3165 return process_server_socket_core(svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
3166 [&](
bool close_connection,
bool &connection_closed) {
3167 SocketStream strm(sock, read_timeout_sec, read_timeout_usec, write_timeout_sec,
3168 write_timeout_usec);
3169 return callback(strm, close_connection, connection_closed);
3173inline bool process_client_socket(
socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
3174 time_t write_timeout_sec, time_t write_timeout_usec,
3175 std::function<
bool(Stream &)> callback) {
3176 SocketStream strm(sock, read_timeout_sec, read_timeout_usec, write_timeout_sec, write_timeout_usec);
3177 return callback(strm);
3180inline int shutdown_socket(
socket_t sock) {
3182 return shutdown(sock, SD_BOTH);
3184 return shutdown(sock, SHUT_RDWR);
3188inline std::string escape_abstract_namespace_unix_domain(
const std::string &s) {
3189 if (s.size() > 1 && s[0] ==
'\0') {
3197inline std::string unescape_abstract_namespace_unix_domain(
const std::string &s) {
3198 if (s.size() > 1 && s[0] ==
'@') {
3206template<
typename BindOrConnect>
3207socket_t create_socket(
const std::string &host,
const std::string &ip,
int port,
int address_family,
int socket_flags,
3208 bool tcp_nodelay,
bool ipv6_v6only, SocketOptions socket_options,
3209 BindOrConnect bind_or_connect) {
3211 const char *node =
nullptr;
3212 struct addrinfo hints;
3213 struct addrinfo *result;
3215 memset(&hints, 0,
sizeof(
struct addrinfo));
3216 hints.ai_socktype = SOCK_STREAM;
3217 hints.ai_protocol = IPPROTO_IP;
3222 hints.ai_family = AF_UNSPEC;
3223 hints.ai_flags = AI_NUMERICHOST;
3225 if (!host.empty()) {
3226 node = host.c_str();
3228 hints.ai_family = address_family;
3229 hints.ai_flags = socket_flags;
3233 if (hints.ai_family == AF_UNIX) {
3234 const auto addrlen = host.length();
3235 if (addrlen >
sizeof(sockaddr_un::sun_path)) {
3236 return INVALID_SOCKET;
3240 auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC, hints.ai_protocol);
3242 auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
3245 if (sock != INVALID_SOCKET) {
3247 addr.sun_family = AF_UNIX;
3249 auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
3250 std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
3252 hints.ai_addr =
reinterpret_cast<sockaddr *
>(&addr);
3253 hints.ai_addrlen =
static_cast<socklen_t>(
sizeof(addr) -
sizeof(addr.sun_path) + addrlen);
3256 fcntl(sock, F_SETFD, FD_CLOEXEC);
3259 if (socket_options) {
3260 socket_options(sock);
3264 if (!bind_or_connect(sock, hints, dummy)) {
3266 sock = INVALID_SOCKET;
3273 auto service = std::to_string(port);
3275 if (getaddrinfo(node, service.c_str(), &hints, &result)) {
3276#if defined __linux__ && !defined __ANDROID__
3279 return INVALID_SOCKET;
3281 auto se = detail::scope_exit([&] { freeaddrinfo(result); });
3283 for (
auto rp = result; rp; rp = rp->ai_next) {
3286 auto sock = WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol,
nullptr, 0,
3287 WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
3302 if (sock == INVALID_SOCKET) {
3303 sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
3308 auto sock = socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
3310 auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
3314 if (sock == INVALID_SOCKET) {
3318#if !defined _WIN32 && !defined SOCK_CLOEXEC
3319 if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
3328 setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
reinterpret_cast<const char *
>(&opt),
sizeof(opt));
3330 setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
reinterpret_cast<const void *
>(&opt),
sizeof(opt));
3334 if (rp->ai_family == AF_INET6) {
3335 auto opt = ipv6_v6only ? 1 : 0;
3337 setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY,
reinterpret_cast<const char *
>(&opt),
sizeof(opt));
3339 setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY,
reinterpret_cast<const void *
>(&opt),
sizeof(opt));
3343 if (socket_options) {
3344 socket_options(sock);
3349 if (bind_or_connect(sock, *rp, quit)) {
3360 return INVALID_SOCKET;
3363inline void set_nonblocking(
socket_t sock,
bool nonblocking) {
3365 auto flags = nonblocking ? 1UL : 0UL;
3366 ioctlsocket(sock, FIONBIO, &
flags);
3368 auto flags = fcntl(sock, F_GETFL, 0);
3369 fcntl(sock, F_SETFL, nonblocking ? (
flags | O_NONBLOCK) : (
flags & (~O_NONBLOCK)));
3373inline bool is_connection_error() {
3375 return WSAGetLastError() != WSAEWOULDBLOCK;
3377 return errno != EINPROGRESS;
3381inline bool bind_ip_address(
socket_t sock,
const std::string &host) {
3382 struct addrinfo hints;
3383 struct addrinfo *result;
3385 memset(&hints, 0,
sizeof(
struct addrinfo));
3386 hints.ai_family = AF_UNSPEC;
3387 hints.ai_socktype = SOCK_STREAM;
3388 hints.ai_protocol = 0;
3390 if (getaddrinfo(host.c_str(),
"0", &hints, &result)) {
3393 auto se = detail::scope_exit([&] { freeaddrinfo(result); });
3396 for (
auto rp = result; rp; rp = rp->ai_next) {
3397 const auto &ai = *rp;
3398 if (!::bind(sock, ai.ai_addr,
static_cast<socklen_t>(ai.ai_addrlen))) {
3407#if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
3412inline std::string if2ip(
int address_family,
const std::string &ifn) {
3413 struct ifaddrs *ifap;
3415 auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
3417 std::string addr_candidate;
3418 for (
auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
3419 if (ifa->ifa_addr && ifn == ifa->ifa_name &&
3420 (AF_UNSPEC == address_family || ifa->ifa_addr->sa_family == address_family)) {
3421 if (ifa->ifa_addr->sa_family == AF_INET) {
3422 auto sa =
reinterpret_cast<struct
sockaddr_in *
>(ifa->ifa_addr);
3423 char buf[INET_ADDRSTRLEN];
3424 if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
3425 return std::string(buf, INET_ADDRSTRLEN);
3427 }
else if (ifa->ifa_addr->sa_family == AF_INET6) {
3428 auto sa =
reinterpret_cast<struct
sockaddr_in6 *
>(ifa->ifa_addr);
3429 if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
3430 char buf[INET6_ADDRSTRLEN] = {};
3431 if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
3433 auto s6_addr_head = sa->sin6_addr.s6_addr[0];
3434 if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
3435 addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
3437 return std::string(buf, INET6_ADDRSTRLEN);
3444 return addr_candidate;
3448inline socket_t create_client_socket(
const std::string &host,
const std::string &ip,
int port,
int address_family,
3449 bool tcp_nodelay,
bool ipv6_v6only, SocketOptions socket_options,
3450 time_t connection_timeout_sec, time_t connection_timeout_usec,
3451 time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
3452 time_t write_timeout_usec,
const std::string &intf, Error &error) {
3453 auto sock = create_socket(
3454 host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only, std::move(socket_options),
3455 [&](
socket_t sock2,
struct addrinfo &ai,
bool &quit) ->
bool {
3456 if (!intf.empty()) {
3458 auto ip_from_if = if2ip(address_family, intf);
3459 if (ip_from_if.empty()) {
3462 if (!bind_ip_address(sock2, ip_from_if)) {
3463 error = Error::BindIPAddress;
3469 set_nonblocking(sock2,
true);
3471 auto ret = ::connect(sock2, ai.ai_addr,
static_cast<socklen_t>(ai.ai_addrlen));
3474 if (is_connection_error()) {
3475 error = Error::Connection;
3478 error = wait_until_socket_is_ready(sock2, connection_timeout_sec, connection_timeout_usec);
3479 if (error != Error::Success) {
3480 if (error == Error::ConnectionTimeout) {
3487 set_nonblocking(sock2,
false);
3491 auto timeout =
static_cast<uint32_t>(read_timeout_sec * 1000 + read_timeout_usec / 1000);
3492 setsockopt(sock2, SOL_SOCKET, SO_RCVTIMEO,
reinterpret_cast<const char *
>(&timeout),
sizeof(timeout));
3495 tv.tv_sec =
static_cast<long>(read_timeout_sec);
3496 tv.tv_usec =
static_cast<decltype(tv.tv_usec)
>(read_timeout_usec);
3497 setsockopt(sock2, SOL_SOCKET, SO_RCVTIMEO,
reinterpret_cast<const void *
>(&tv),
sizeof(tv));
3503 auto timeout =
static_cast<uint32_t>(write_timeout_sec * 1000 + write_timeout_usec / 1000);
3504 setsockopt(sock2, SOL_SOCKET, SO_SNDTIMEO,
reinterpret_cast<const char *
>(&timeout),
sizeof(timeout));
3507 tv.tv_sec =
static_cast<long>(write_timeout_sec);
3508 tv.tv_usec =
static_cast<decltype(tv.tv_usec)
>(write_timeout_usec);
3509 setsockopt(sock2, SOL_SOCKET, SO_SNDTIMEO,
reinterpret_cast<const void *
>(&tv),
sizeof(tv));
3513 error = Error::Success;
3517 if (sock != INVALID_SOCKET) {
3518 error = Error::Success;
3520 if (error == Error::Success) {
3521 error = Error::Connection;
3530 port = ntohs(
reinterpret_cast<const struct
sockaddr_in *
>(&addr)->sin_port);
3531 }
else if (addr.
ss_family == AF_INET6) {
3532 port = ntohs(
reinterpret_cast<const struct
sockaddr_in6 *
>(&addr)->sin6_port);
3537 std::array<char, NI_MAXHOST> ipstr{};
3538 if (getnameinfo(
reinterpret_cast<const struct
sockaddr *
>(&addr),
addr_len, ipstr.data(),
3539 static_cast<socklen_t>(ipstr.size()),
nullptr, 0, NI_NUMERICHOST)) {
3547inline void get_local_ip_and_port(
socket_t sock, std::string &ip,
int &port) {
3550 if (!getsockname(sock,
reinterpret_cast<struct
sockaddr *
>(&addr), &
addr_len)) {
3551 get_ip_and_port(addr,
addr_len, ip, port);
3555inline void get_remote_ip_and_port(
socket_t sock, std::string &ip,
int &port) {
3559 if (!getpeername(sock,
reinterpret_cast<struct
sockaddr *
>(&addr), &
addr_len)) {
3562#if defined(__linux__)
3565 if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &
len) == 0) {
3568#elif defined(SOL_LOCAL) && defined(SO_PEERPID)
3571 if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &
len) == 0) {
3578 get_ip_and_port(addr,
addr_len, ip, port);
3582inline constexpr unsigned int str2tag_core(
const char *s,
size_t l,
unsigned int h) {
3587 (((std::numeric_limits<unsigned int>::max)() >> 6) &
h * 33) ^
static_cast<unsigned char>(*s));
3590inline unsigned int str2tag(
const std::string &s) {
return str2tag_core(s.data(), s.size(), 0); }
3594inline constexpr unsigned int operator""_t(
const char *s,
size_t l) {
return str2tag_core(s,
l, 0); }
3598inline std::string find_content_type(
const std::string &path,
const std::map<std::string, std::string> &user_data,
3599 const std::string &default_content_type) {
3600 auto ext = file_extension(path);
3602 auto it = user_data.find(ext);
3603 if (it != user_data.end()) {
3607 using udl::operator
""_t;
3609 switch (str2tag(ext)) {
3611 return default_content_type;
3622 return "text/javascript";
3624 return "text/plain";
3629 return "image/apng";
3631 return "image/avif";
3639 return "image/svg+xml";
3641 return "image/webp";
3643 return "image/x-icon";
3645 return "image/tiff";
3647 return "image/tiff";
3650 return "image/jpeg";
3655 return "video/mpeg";
3657 return "video/webm";
3662 return "audio/mpeg";
3664 return "audio/webm";
3666 return "audio/wave";
3675 return "font/woff2";
3678 return "application/x-7z-compressed";
3680 return "application/atom+xml";
3682 return "application/pdf";
3684 return "application/json";
3686 return "application/rss+xml";
3688 return "application/x-tar";
3691 return "application/xhtml+xml";
3693 return "application/xslt+xml";
3695 return "application/xml";
3697 return "application/gzip";
3699 return "application/zip";
3701 return "application/wasm";
3705inline bool can_compress_content_type(
const std::string &content_type) {
3706 using udl::operator
""_t;
3708 auto tag = str2tag(content_type);
3711 case "image/svg+xml"_t:
3712 case "application/javascript"_t:
3713 case "application/json"_t:
3714 case "application/xml"_t:
3715 case "application/protobuf"_t:
3716 case "application/xhtml+xml"_t:
3719 case "text/event-stream"_t:
3723 return !content_type.rfind(
"text/", 0);
3727inline EncodingType encoding_type(
const Request &req,
const Response &res) {
3728 auto ret = detail::can_compress_content_type(res.get_header_value(
"Content-Type"));
3730 return EncodingType::None;
3733 const auto &s = req.get_header_value(
"Accept-Encoding");
3736#ifdef CPPHTTPLIB_BROTLI_SUPPORT
3738 ret = s.find(
"br") != std::string::npos;
3740 return EncodingType::Brotli;
3744#ifdef CPPHTTPLIB_ZLIB_SUPPORT
3746 ret = s.find(
"gzip") != std::string::npos;
3748 return EncodingType::Gzip;
3752 return EncodingType::None;
3755inline bool nocompressor::compress(
const char *data,
size_t data_length,
bool , Callback callback) {
3759 return callback(data, data_length);
3762#ifdef CPPHTTPLIB_ZLIB_SUPPORT
3763inline gzip_compressor::gzip_compressor() {
3764 std::memset(&strm_, 0,
sizeof(strm_));
3765 strm_.zalloc = Z_NULL;
3766 strm_.zfree = Z_NULL;
3767 strm_.opaque = Z_NULL;
3769 is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY) == Z_OK;
3772inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
3774inline bool gzip_compressor::compress(
const char *data,
size_t data_length,
bool last, Callback callback) {
3778 constexpr size_t max_avail_in = (std::numeric_limits<
decltype(strm_.avail_in)>::max)();
3780 strm_.avail_in =
static_cast<decltype(strm_.avail_in)
>((std::min) (data_length, max_avail_in));
3781 strm_.next_in =
const_cast<Bytef *
>(
reinterpret_cast<const Bytef *
>(data));
3783 data_length -= strm_.avail_in;
3784 data += strm_.avail_in;
3786 auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
3789 std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
3791 strm_.avail_out =
static_cast<uInt
>(buff.size());
3792 strm_.next_out =
reinterpret_cast<Bytef *
>(buff.data());
3794 ret = deflate(&strm_, flush);
3795 if (
ret == Z_STREAM_ERROR) {
3799 if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
3802 }
while (strm_.avail_out == 0);
3804 assert((flush == Z_FINISH &&
ret == Z_STREAM_END) || (flush == Z_NO_FLUSH &&
ret == Z_OK));
3805 assert(strm_.avail_in == 0);
3806 }
while (data_length > 0);
3811inline gzip_decompressor::gzip_decompressor() {
3812 std::memset(&strm_, 0,
sizeof(strm_));
3813 strm_.zalloc = Z_NULL;
3814 strm_.zfree = Z_NULL;
3815 strm_.opaque = Z_NULL;
3821 is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
3824inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
3826inline bool gzip_decompressor::is_valid()
const {
return is_valid_; }
3828inline bool gzip_decompressor::decompress(
const char *data,
size_t data_length, Callback callback) {
3834 constexpr size_t max_avail_in = (std::numeric_limits<
decltype(strm_.avail_in)>::max)();
3836 strm_.avail_in =
static_cast<decltype(strm_.avail_in)
>((std::min) (data_length, max_avail_in));
3837 strm_.next_in =
const_cast<Bytef *
>(
reinterpret_cast<const Bytef *
>(data));
3839 data_length -= strm_.avail_in;
3840 data += strm_.avail_in;
3842 std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
3843 while (strm_.avail_in > 0 &&
ret == Z_OK) {
3844 strm_.avail_out = static_cast<uInt>(buff.size());
3845 strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
3847 ret = inflate(&strm_, Z_NO_FLUSH);
3849 assert(ret != Z_STREAM_ERROR);
3858 if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
3863 if (
ret != Z_OK &&
ret != Z_STREAM_END) {
3867 }
while (data_length > 0);
3873#ifdef CPPHTTPLIB_BROTLI_SUPPORT
3874inline brotli_compressor::brotli_compressor() { state_ = BrotliEncoderCreateInstance(
nullptr,
nullptr,
nullptr); }
3876inline brotli_compressor::~brotli_compressor() { BrotliEncoderDestroyInstance(state_); }
3878inline bool brotli_compressor::compress(
const char *data,
size_t data_length,
bool last, Callback callback) {
3879 std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
3881 auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
3882 auto available_in = data_length;
3883 auto next_in =
reinterpret_cast<const uint8_t *
>(data);
3887 if (BrotliEncoderIsFinished(state_)) {
3891 if (!available_in) {
3896 auto available_out = buff.size();
3897 auto next_out = buff.data();
3899 if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in, &available_out, &next_out,
nullptr)) {
3903 auto output_bytes = buff.size() - available_out;
3905 callback(
reinterpret_cast<const char *
>(buff.data()), output_bytes);
3912inline brotli_decompressor::brotli_decompressor() {
3913 decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
3914 decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT : BROTLI_DECODER_RESULT_ERROR;
3917inline brotli_decompressor::~brotli_decompressor() {
3919 BrotliDecoderDestroyInstance(decoder_s);
3923inline bool brotli_decompressor::is_valid()
const {
return decoder_s; }
3925inline bool brotli_decompressor::decompress(
const char *data,
size_t data_length, Callback callback) {
3926 if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS || decoder_r == BROTLI_DECODER_RESULT_ERROR) {
3930 auto next_in =
reinterpret_cast<const uint8_t *
>(data);
3931 size_t avail_in = data_length;
3934 decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
3936 std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
3937 while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
3938 char *next_out = buff.data();
3939 size_t avail_out = buff.size();
3941 decoder_r = BrotliDecoderDecompressStream(decoder_s, &avail_in, &next_in, &avail_out,
3942 reinterpret_cast<uint8_t **
>(&next_out), &total_out);
3944 if (decoder_r == BROTLI_DECODER_RESULT_ERROR) {
3948 if (!callback(buff.data(), buff.size() - avail_out)) {
3953 return decoder_r == BROTLI_DECODER_RESULT_SUCCESS || decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
3957inline bool has_header(
const Headers &headers,
const std::string &
key) {
return headers.find(
key) != headers.end(); }
3959inline const char *get_header_value(
const Headers &headers,
const std::string &
key,
const char *def,
size_t id) {
3960 auto rng = headers.equal_range(
key);
3961 auto it = rng.first;
3962 std::advance(it,
static_cast<ssize_t>(
id));
3963 if (it != rng.second) {
3964 return it->second.c_str();
3969template<
typename T>
inline bool parse_header(
const char *beg,
const char *
end, T fn) {
3971 while (beg <
end && is_space_or_tab(
end[-1])) {
3976 while (p <
end && *p !=
':') {
3990 while (p <
end && is_space_or_tab(*p)) {
3995 auto key_len = key_end - beg;
4000 auto key = std::string(beg, key_end);
4001 auto val = case_ignore::equal(
key,
"Location") ? std::string(p,
end) : decode_url(std::string(p,
end),
false);
4011 static const std::string CR_LF_NUL(
"\r\n\0", 3);
4012 if (
val.find_first_of(CR_LF_NUL) != std::string::npos) {
4023inline bool read_headers(Stream &strm, Headers &headers) {
4024 const auto bufsiz = 2048;
4026 stream_line_reader line_reader(strm, buf, bufsiz);
4029 if (!line_reader.getline()) {
4034 auto line_terminator_len = 2;
4035 if (line_reader.end_with_crlf()) {
4037 if (line_reader.size() == 2) {
4041#ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
4043 if (line_reader.size() == 1) {
4046 line_terminator_len = 1;
4052 if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) {
4057 auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
4059 if (!parse_header(line_reader.ptr(),
end,
4060 [&](
const std::string &
key, std::string &
val) { headers.emplace(key, val); })) {
4068inline bool read_content_with_length(Stream &strm, uint64_t
len, Progress progress, ContentReceiverWithProgress
out) {
4069 char buf[CPPHTTPLIB_RECV_BUFSIZ];
4073 auto read_len =
static_cast<size_t>(
len - r);
4074 auto n = strm.read(buf, (std::min) (read_len, CPPHTTPLIB_RECV_BUFSIZ));
4079 if (!
out(buf,
static_cast<size_t>(n), r,
len)) {
4082 r +=
static_cast<uint64_t
>(n);
4085 if (!progress(r,
len)) {
4094inline void skip_content_with_length(Stream &strm, uint64_t
len) {
4095 char buf[CPPHTTPLIB_RECV_BUFSIZ];
4098 auto read_len =
static_cast<size_t>(
len - r);
4099 auto n = strm.read(buf, (std::min) (read_len, CPPHTTPLIB_RECV_BUFSIZ));
4103 r +=
static_cast<uint64_t
>(n);
4107inline bool read_content_without_length(Stream &strm, ContentReceiverWithProgress
out) {
4108 char buf[CPPHTTPLIB_RECV_BUFSIZ];
4111 auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
4116 if (!
out(buf,
static_cast<size_t>(n), r, 0)) {
4119 r +=
static_cast<uint64_t
>(n);
4125template<
typename T>
inline bool read_content_chunked(Stream &strm, T &
x, ContentReceiverWithProgress
out) {
4126 const auto bufsiz = 16;
4129 stream_line_reader line_reader(strm, buf, bufsiz);
4131 if (!line_reader.getline()) {
4135 unsigned long chunk_len;
4139 chunk_len = std::strtoul(line_reader.ptr(), &end_ptr, 16);
4141 if (end_ptr == line_reader.ptr()) {
4144 if (chunk_len == ULONG_MAX) {
4148 if (chunk_len == 0) {
4152 if (!read_content_with_length(strm, chunk_len,
nullptr,
out)) {
4156 if (!line_reader.getline()) {
4160 if (strcmp(line_reader.ptr(),
"\r\n") != 0) {
4164 if (!line_reader.getline()) {
4169 assert(chunk_len == 0);
4183 if (!line_reader.getline()) {
4187 while (strcmp(line_reader.ptr(),
"\r\n") != 0) {
4188 if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) {
4193 constexpr auto line_terminator_len = 2;
4194 auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
4196 parse_header(line_reader.ptr(),
end,
4197 [&](
const std::string &
key,
const std::string &
val) { x.headers.emplace(key, val); });
4199 if (!line_reader.getline()) {
4207inline bool is_chunked_transfer_encoding(
const Headers &headers) {
4208 return case_ignore::equal(get_header_value(headers,
"Transfer-Encoding",
"", 0),
"chunked");
4211template<
typename T,
typename U>
4212bool prepare_content_receiver(T &
x,
int &
status, ContentReceiverWithProgress receiver,
bool decompress, U callback) {
4214 std::string encoding =
x.get_header_value(
"Content-Encoding");
4215 std::unique_ptr<decompressor> decompressor;
4217 if (encoding ==
"gzip" || encoding ==
"deflate") {
4218#ifdef CPPHTTPLIB_ZLIB_SUPPORT
4219 decompressor = detail::make_unique<gzip_decompressor>();
4221 status = StatusCode::UnsupportedMediaType_415;
4224 }
else if (encoding.find(
"br") != std::string::npos) {
4225#ifdef CPPHTTPLIB_BROTLI_SUPPORT
4226 decompressor = detail::make_unique<brotli_decompressor>();
4228 status = StatusCode::UnsupportedMediaType_415;
4234 if (decompressor->is_valid()) {
4235 ContentReceiverWithProgress
out = [&](
const char *buf,
size_t n, uint64_t off, uint64_t
len) {
4236 return decompressor->decompress(buf, n,
4237 [&](
const char *buf2,
size_t n2) {
return receiver(buf2, n2, off,
len); });
4239 return callback(std::move(
out));
4241 status = StatusCode::InternalServerError_500;
4247 ContentReceiverWithProgress
out = [&](
const char *buf,
size_t n, uint64_t off, uint64_t
len) {
4248 return receiver(buf, n, off,
len);
4250 return callback(std::move(
out));
4254bool read_content(Stream &strm, T &
x,
size_t payload_max_length,
int &
status, Progress progress,
4255 ContentReceiverWithProgress receiver,
bool decompress) {
4256 return prepare_content_receiver(
4257 x,
status, std::move(receiver), decompress, [&](
const ContentReceiverWithProgress &
out) {
4259 auto exceed_payload_max_length =
false;
4261 if (is_chunked_transfer_encoding(
x.headers)) {
4262 ret = read_content_chunked(strm,
x,
out);
4263 }
else if (!has_header(
x.headers,
"Content-Length")) {
4264 ret = read_content_without_length(strm,
out);
4266 auto len = get_header_value_u64(
x.headers,
"Content-Length", 0, 0);
4267 if (
len > payload_max_length) {
4268 exceed_payload_max_length =
true;
4269 skip_content_with_length(strm,
len);
4271 }
else if (
len > 0) {
4272 ret = read_content_with_length(strm,
len, std::move(progress),
out);
4277 status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413 : StatusCode::BadRequest_400;
4283inline ssize_t write_request_line(Stream &strm,
const std::string &method,
const std::string &path) {
4284 std::string s = method;
4287 s +=
" HTTP/1.1\r\n";
4288 return strm.write(s.data(), s.size());
4291inline ssize_t write_response_line(Stream &strm,
int status) {
4292 std::string s =
"HTTP/1.1 ";
4293 s += std::to_string(
status);
4295 s += httplib::status_message(
status);
4297 return strm.write(s.data(), s.size());
4300inline ssize_t write_headers(Stream &strm,
const Headers &headers) {
4302 for (
const auto &
x : headers) {
4309 auto len = strm.write(s.data(), s.size());
4315 auto len = strm.write(
"\r\n");
4323inline bool write_data(Stream &strm,
const char *d,
size_t l) {
4325 while (offset <
l) {
4326 auto length = strm.write(d + offset,
l - offset);
4330 offset +=
static_cast<size_t>(
length);
4336inline bool write_content(Stream &strm,
const ContentProvider &content_provider,
size_t offset,
size_t length,
4337 T is_shutting_down, Error &error) {
4338 size_t end_offset = offset +
length;
4342 data_sink.write = [&](
const char *d,
size_t l) ->
bool {
4344 if (strm.is_writable() && write_data(strm, d,
l)) {
4353 data_sink.is_writable = [&]() ->
bool {
return strm.is_writable(); };
4355 while (offset < end_offset && !is_shutting_down()) {
4356 if (!strm.is_writable()) {
4357 error = Error::Write;
4359 }
else if (!content_provider(offset, end_offset - offset, data_sink)) {
4360 error = Error::Canceled;
4363 error = Error::Write;
4368 error = Error::Success;
4373inline bool write_content(Stream &strm,
const ContentProvider &content_provider,
size_t offset,
size_t length,
4374 const T &is_shutting_down) {
4375 auto error = Error::Success;
4376 return write_content(strm, content_provider, offset,
length, is_shutting_down, error);
4380inline bool write_content_without_length(Stream &strm,
const ContentProvider &content_provider,
4381 const T &is_shutting_down) {
4383 auto data_available =
true;
4387 data_sink.write = [&](
const char *d,
size_t l) ->
bool {
4390 if (!strm.is_writable() || !write_data(strm, d,
l)) {
4397 data_sink.is_writable = [&]() ->
bool {
return strm.is_writable(); };
4399 data_sink.done = [&](void) { data_available =
false; };
4401 while (data_available && !is_shutting_down()) {
4402 if (!strm.is_writable()) {
4404 }
else if (!content_provider(offset, 0, data_sink)) {
4413template<
typename T,
typename U>
4414inline bool write_content_chunked(Stream &strm,
const ContentProvider &content_provider,
const T &is_shutting_down,
4415 U &compressor, Error &error) {
4417 auto data_available =
true;
4421 data_sink.write = [&](
const char *d,
size_t l) ->
bool {
4423 data_available =
l > 0;
4426 std::string payload;
4427 if (compressor.compress(d,
l,
false, [&](
const char *data,
size_t data_len) {
4428 payload.append(data, data_len);
4431 if (!payload.empty()) {
4433 auto chunk = from_i_to_hex(payload.size()) +
"\r\n" + payload +
"\r\n";
4434 if (!strm.is_writable() || !write_data(strm, chunk.data(), chunk.size())) {
4445 data_sink.is_writable = [&]() ->
bool {
return strm.is_writable(); };
4447 auto done_with_trailer = [&](
const Headers *
trailer) {
4452 data_available =
false;
4454 std::string payload;
4455 if (!compressor.compress(
nullptr, 0,
true, [&](
const char *data,
size_t data_len) {
4456 payload.append(data, data_len);
4463 if (!payload.empty()) {
4465 auto chunk = from_i_to_hex(payload.size()) +
"\r\n" + payload +
"\r\n";
4466 if (!strm.is_writable() || !write_data(strm, chunk.data(), chunk.size())) {
4472 static const std::string done_marker(
"0\r\n");
4473 if (!write_data(strm, done_marker.data(), done_marker.size())) {
4479 for (
const auto &kv : *
trailer) {
4480 std::string field_line = kv.first +
": " + kv.second +
"\r\n";
4481 if (!write_data(strm, field_line.data(), field_line.size())) {
4487 static const std::string crlf(
"\r\n");
4488 if (!write_data(strm, crlf.data(), crlf.size())) {
4493 data_sink.done = [&](void) { done_with_trailer(
nullptr); };
4495 data_sink.done_with_trailer = [&](
const Headers &
trailer) { done_with_trailer(&
trailer); };
4497 while (data_available && !is_shutting_down()) {
4498 if (!strm.is_writable()) {
4499 error = Error::Write;
4501 }
else if (!content_provider(offset, 0, data_sink)) {
4502 error = Error::Canceled;
4505 error = Error::Write;
4510 error = Error::Success;
4514template<
typename T,
typename U>
4515inline bool write_content_chunked(Stream &strm,
const ContentProvider &content_provider,
const T &is_shutting_down,
4517 auto error = Error::Success;
4518 return write_content_chunked(strm, content_provider, is_shutting_down, compressor, error);
4522inline bool redirect(T &cli, Request &req, Response &res,
const std::string &path,
const std::string &location,
4524 Request new_req = req;
4525 new_req.path = path;
4526 new_req.redirect_count_ -= 1;
4528 if (res.status == StatusCode::SeeOther_303 && (req.method !=
"GET" && req.method !=
"HEAD")) {
4529 new_req.method =
"GET";
4530 new_req.body.clear();
4531 new_req.headers.clear();
4536 auto ret = cli.send(new_req, new_res, error);
4541 if (res.location.empty()) {
4542 res.location = location;
4548inline std::string params_to_query_str(
const Params ¶ms) {
4551 for (
auto it = params.begin(); it != params.end(); ++it) {
4552 if (it != params.begin()) {
4557 query += encode_query_param(it->second);
4562inline void parse_query_text(
const char *data, std::size_t size, Params ¶ms) {
4563 std::set<std::string> cache;
4564 split(data, data + size,
'&', [&](
const char *b,
const char *e) {
4565 std::string kv(b, e);
4566 if (cache.find(kv) != cache.end()) {
4569 cache.insert(std::move(kv));
4573 divide(b,
static_cast<std::size_t
>(e - b),
'=',
4574 [&](
const char *lhs_data, std::size_t lhs_size,
const char *rhs_data, std::size_t rhs_size) {
4575 key.assign(lhs_data, lhs_size);
4576 val.assign(rhs_data, rhs_size);
4580 params.emplace(decode_url(
key,
true), decode_url(
val,
true));
4585inline void parse_query_text(
const std::string &s, Params ¶ms) { parse_query_text(s.data(), s.size(), params); }
4587inline bool parse_multipart_boundary(
const std::string &content_type, std::string &boundary) {
4588 auto boundary_keyword =
"boundary=";
4589 auto pos = content_type.find(boundary_keyword);
4590 if (pos == std::string::npos) {
4593 auto end = content_type.find(
';', pos);
4594 auto beg = pos + strlen(boundary_keyword);
4595 boundary = trim_double_quotes_copy(content_type.substr(beg,
end - beg));
4596 return !boundary.empty();
4599inline void parse_disposition_params(
const std::string &s, Params ¶ms) {
4600 std::set<std::string> cache;
4601 split(s.data(), s.data() + s.size(),
';', [&](
const char *b,
const char *e) {
4602 std::string kv(b, e);
4603 if (cache.find(kv) != cache.end()) {
4610 split(b, e,
'=', [&](
const char *b2,
const char *e2) {
4619 params.emplace(trim_double_quotes_copy((key)), trim_double_quotes_copy((val)));
4624#ifdef CPPHTTPLIB_NO_EXCEPTIONS
4625inline bool parse_range_header(
const std::string &s, Ranges &ranges) {
4627inline bool parse_range_header(
const std::string &s, Ranges &ranges)
try {
4629 auto is_valid = [](
const std::string &str) {
4630 return std::all_of(str.cbegin(), str.cend(), [](
unsigned char c) { return std::isdigit(c); });
4633 if (s.size() > 7 && s.compare(0, 6,
"bytes=") == 0) {
4634 const auto pos =
static_cast<size_t>(6);
4635 const auto len =
static_cast<size_t>(s.size() - 6);
4636 auto all_valid_ranges =
true;
4637 split(&s[pos], &s[pos +
len],
',', [&](
const char *b,
const char *e) {
4638 if (!all_valid_ranges) {
4642 const auto it = std::find(b, e,
'-');
4644 all_valid_ranges =
false;
4648 const auto lhs = std::string(b, it);
4649 const auto rhs = std::string(it + 1, e);
4650 if (!is_valid(lhs) || !is_valid(rhs)) {
4651 all_valid_ranges =
false;
4655 const auto first =
static_cast<ssize_t>(lhs.empty() ? -1 : std::stoll(lhs));
4656 const auto last =
static_cast<ssize_t>(rhs.empty() ? -1 : std::stoll(rhs));
4657 if ((first == -1 && last == -1) || (first != -1 && last != -1 && first > last)) {
4658 all_valid_ranges =
false;
4662 ranges.emplace_back(first, last);
4664 return all_valid_ranges && !ranges.empty();
4667#ifdef CPPHTTPLIB_NO_EXCEPTIONS
4675class MultipartFormDataParser {
4677 MultipartFormDataParser() =
default;
4679 void set_boundary(std::string &&boundary) {
4680 boundary_ = boundary;
4681 dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
4682 crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
4685 bool is_valid()
const {
return is_valid_; }
4687 bool parse(
const char *buf,
size_t n,
const ContentReceiver &content_callback,
4688 const MultipartContentHeader &header_callback) {
4691 while (buf_size() > 0) {
4694 buf_erase(buf_find(dash_boundary_crlf_));
4695 if (dash_boundary_crlf_.size() > buf_size()) {
4698 if (!buf_start_with(dash_boundary_crlf_)) {
4701 buf_erase(dash_boundary_crlf_.size());
4711 auto pos = buf_find(crlf_);
4712 if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) {
4715 while (pos < buf_size()) {
4718 if (!header_callback(file_)) {
4722 buf_erase(crlf_.size());
4727 const auto header = buf_head(pos);
4729 if (!parse_header(header.data(), header.data() + header.size(),
4730 [&](
const std::string &,
const std::string &) {})) {
4735 static const std::string header_content_type =
"Content-Type:";
4737 if (start_with_case_ignore(header, header_content_type)) {
4738 file_.content_type = trim_copy(header.substr(header_content_type.size()));
4740 static const std::regex re_content_disposition(R
"~(^Content-Disposition:\s*form-data;\s*(.*)$)~",
4741 std::regex_constants::icase);
4744 if (std::regex_match(header,
m, re_content_disposition)) {
4746 parse_disposition_params(
m[1], params);
4748 auto it = params.find(
"name");
4749 if (it != params.end()) {
4750 file_.name = it->second;
4756 it = params.find(
"filename");
4757 if (it != params.end()) {
4758 file_.filename = it->second;
4761 it = params.find(
"filename*");
4762 if (it != params.end()) {
4764 static const std::regex re_rfc5987_encoding(R
"~(^UTF-8''(.+?)$)~", std::regex_constants::icase);
4767 if (std::regex_match(it->second, m2, re_rfc5987_encoding)) {
4768 file_.filename = decode_url(m2[1],
false);
4776 buf_erase(pos + crlf_.size());
4777 pos = buf_find(crlf_);
4785 if (crlf_dash_boundary_.size() > buf_size()) {
4788 auto pos = buf_find(crlf_dash_boundary_);
4789 if (pos < buf_size()) {
4790 if (!content_callback(buf_data(), pos)) {
4794 buf_erase(pos + crlf_dash_boundary_.size());
4797 auto len = buf_size() - crlf_dash_boundary_.size();
4799 if (!content_callback(buf_data(),
len)) {
4810 if (crlf_.size() > buf_size()) {
4813 if (buf_start_with(crlf_)) {
4814 buf_erase(crlf_.size());
4817 if (dash_.size() > buf_size()) {
4820 if (buf_start_with(dash_)) {
4821 buf_erase(dash_.size());
4823 buf_erase(buf_size());
4837 void clear_file_info() {
4839 file_.filename.clear();
4840 file_.content_type.clear();
4843 bool start_with_case_ignore(
const std::string &a,
const std::string &b)
const {
4844 if (a.size() <
b.size()) {
4847 for (
size_t i = 0; i <
b.size(); i++) {
4848 if (case_ignore::to_lower(a[i]) != case_ignore::to_lower(b[i])) {
4855 const std::string dash_ =
"--";
4856 const std::string crlf_ =
"\r\n";
4857 std::string boundary_;
4858 std::string dash_boundary_crlf_;
4859 std::string crlf_dash_boundary_;
4862 bool is_valid_ =
false;
4863 MultipartFormData file_;
4866 bool start_with(
const std::string &a,
size_t spos,
size_t epos,
const std::string &b)
const {
4867 if (epos - spos <
b.size()) {
4870 for (
size_t i = 0; i <
b.size(); i++) {
4871 if (a[i + spos] != b[i]) {
4878 size_t buf_size()
const {
return buf_epos_ - buf_spos_; }
4880 const char *buf_data()
const {
return &buf_[buf_spos_]; }
4882 std::string buf_head(
size_t l)
const {
return buf_.substr(buf_spos_,
l); }
4884 bool buf_start_with(
const std::string &s)
const {
return start_with(buf_, buf_spos_, buf_epos_, s); }
4886 size_t buf_find(
const std::string &s)
const {
4889 size_t off = buf_spos_;
4890 while (off < buf_epos_) {
4893 if (pos == buf_epos_) {
4896 if (buf_[pos] == c) {
4902 auto remaining_size = buf_epos_ -
pos;
4903 if (s.size() > remaining_size) {
4907 if (start_with(buf_, pos, buf_epos_, s)) {
4908 return pos - buf_spos_;
4917 void buf_append(
const char *data,
size_t n) {
4918 auto remaining_size = buf_size();
4919 if (remaining_size > 0 && buf_spos_ > 0) {
4920 for (
size_t i = 0; i < remaining_size; i++) {
4921 buf_[i] = buf_[buf_spos_ + i];
4925 buf_epos_ = remaining_size;
4927 if (remaining_size + n > buf_.size()) {
4928 buf_.resize(remaining_size + n);
4931 for (
size_t i = 0; i < n; i++) {
4932 buf_[buf_epos_ + i] =
data[i];
4937 void buf_erase(
size_t size) { buf_spos_ +=
size; }
4940 size_t buf_spos_ = 0;
4941 size_t buf_epos_ = 0;
4944inline std::string random_string(
size_t length) {
4945 static const char data[] =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
4950 static std::random_device seed_gen;
4953 static std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
4955 static std::mt19937 engine(seed_sequence);
4958 for (
size_t i = 0; i <
length; i++) {
4959 result +=
data[engine() % (
sizeof(
data) - 1)];
4964inline std::string make_multipart_data_boundary() {
4965 return "--cpp-httplib-multipart-data-" + detail::random_string(16);
4968inline bool is_multipart_boundary_chars_valid(
const std::string &boundary) {
4970 for (
size_t i = 0; i < boundary.size(); i++) {
4971 auto c = boundary[i];
4972 if (!std::isalnum(c) && c !=
'-' && c !=
'_') {
4981inline std::string serialize_multipart_formdata_item_begin(
const T &item,
const std::string &boundary) {
4982 std::string body =
"--" + boundary +
"\r\n";
4983 body +=
"Content-Disposition: form-data; name=\"" + item.name +
"\"";
4984 if (!item.filename.empty()) {
4985 body +=
"; filename=\"" + item.filename +
"\"";
4988 if (!item.content_type.empty()) {
4989 body +=
"Content-Type: " + item.content_type +
"\r\n";
4996inline std::string serialize_multipart_formdata_item_end() {
return "\r\n"; }
4998inline std::string serialize_multipart_formdata_finish(
const std::string &boundary) {
4999 return "--" + boundary +
"--\r\n";
5002inline std::string serialize_multipart_formdata_get_content_type(
const std::string &boundary) {
5003 return "multipart/form-data; boundary=" + boundary;
5006inline std::string serialize_multipart_formdata(
const MultipartFormDataItems &items,
const std::string &boundary,
5007 bool finish =
true) {
5010 for (
const auto &item : items) {
5011 body += serialize_multipart_formdata_item_begin(item, boundary);
5012 body += item.content + serialize_multipart_formdata_item_end();
5016 body += serialize_multipart_formdata_finish(boundary);
5022inline bool range_error(Request &req, Response &res) {
5023 if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
5024 ssize_t contant_len =
static_cast<ssize_t>(res.content_length_ ? res.content_length_ : res.body.size());
5028 size_t overwrapping_count = 0;
5035 if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) {
5039 for (
auto &r : req.ranges) {
5040 auto &first_pos = r.first;
5041 auto &last_pos = r.second;
5043 if (first_pos == -1 && last_pos == -1) {
5045 last_pos = contant_len;
5048 if (first_pos == -1) {
5049 first_pos = contant_len - last_pos;
5050 last_pos = contant_len - 1;
5053 if (last_pos == -1) {
5054 last_pos = contant_len - 1;
5058 if (!(0 <= first_pos && first_pos <= last_pos && last_pos <= contant_len - 1)) {
5063 if (first_pos <= prev_first_pos) {
5068 if (first_pos <= prev_last_pos) {
5069 overwrapping_count++;
5070 if (overwrapping_count > 2) {
5075 prev_first_pos = (std::max) (prev_first_pos, first_pos);
5076 prev_last_pos = (std::max) (prev_last_pos, last_pos);
5083inline std::pair<size_t, size_t> get_range_offset_and_length(Range r,
size_t content_length) {
5084 assert(r.first != -1 && r.second != -1);
5085 assert(0 <= r.first && r.first <
static_cast<ssize_t>(content_length));
5086 assert(r.first <= r.second && r.second <
static_cast<ssize_t>(content_length));
5087 (void) (content_length);
5088 return std::make_pair(r.first,
static_cast<size_t>(r.second - r.first) + 1);
5091inline std::string make_content_range_header_field(
const std::pair<size_t, size_t> &offset_and_length,
5092 size_t content_length) {
5093 auto st = offset_and_length.first;
5094 auto ed = st + offset_and_length.second - 1;
5096 std::string field =
"bytes ";
5097 field += std::to_string(st);
5099 field += std::to_string(ed);
5101 field += std::to_string(content_length);
5105template<
typename SToken,
typename CToken,
typename Content>
5106bool process_multipart_ranges_data(
const Request &req,
const std::string &boundary,
const std::string &content_type,
5107 size_t content_length, SToken stoken, CToken ctoken, Content content) {
5108 for (
size_t i = 0; i < req.ranges.size(); i++) {
5112 if (!content_type.empty()) {
5113 ctoken(
"Content-Type: ");
5114 stoken(content_type);
5118 auto offset_and_length = get_range_offset_and_length(req.ranges[i], content_length);
5120 ctoken(
"Content-Range: ");
5121 stoken(make_content_range_header_field(offset_and_length, content_length));
5125 if (!content(offset_and_length.first, offset_and_length.second)) {
5138inline void make_multipart_ranges_data(
const Request &req, Response &res,
const std::string &boundary,
5139 const std::string &content_type,
size_t content_length, std::string &data) {
5140 process_multipart_ranges_data(
5141 req, boundary, content_type, content_length, [&](
const std::string &token) {
data += token; },
5142 [&](
const std::string &token) {
data += token; },
5143 [&](
size_t offset,
size_t length) {
5144 assert(offset +
length <= content_length);
5150inline size_t get_multipart_ranges_data_length(
const Request &req,
const std::string &boundary,
5151 const std::string &content_type,
size_t content_length) {
5152 size_t data_length = 0;
5154 process_multipart_ranges_data(
5155 req, boundary, content_type, content_length, [&](
const std::string &token) { data_length += token.size(); },
5156 [&](
const std::string &token) { data_length += token.size(); },
5157 [&](
size_t ,
size_t length) {
5166inline bool write_multipart_ranges_data(Stream &strm,
const Request &req, Response &res,
const std::string &boundary,
5167 const std::string &content_type,
size_t content_length,
5168 const T &is_shutting_down) {
5169 return process_multipart_ranges_data(
5170 req, boundary, content_type, content_length, [&](
const std::string &token) { strm.write(token); },
5171 [&](
const std::string &token) { strm.write(token); },
5172 [&](
size_t offset,
size_t length) {
5173 return write_content(strm, res.content_provider_, offset,
length, is_shutting_down);
5177inline bool expect_content(
const Request &req) {
5178 if (req.method ==
"POST" || req.method ==
"PUT" || req.method ==
"PATCH" || req.method ==
"PRI" ||
5179 req.method ==
"DELETE") {
5186inline bool has_crlf(
const std::string &s) {
5189 if (*p ==
'\r' || *p ==
'\n') {
5197#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
5198inline std::string message_digest(
const std::string &s,
const EVP_MD *algo) {
5199 auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(EVP_MD_CTX_new(), EVP_MD_CTX_free);
5201 unsigned int hash_length = 0;
5202 unsigned char hash[EVP_MAX_MD_SIZE];
5204 EVP_DigestInit_ex(context.get(), algo,
nullptr);
5205 EVP_DigestUpdate(context.get(), s.c_str(), s.size());
5206 EVP_DigestFinal_ex(context.get(), hash, &hash_length);
5208 std::stringstream ss;
5209 for (
auto i = 0u; i < hash_length; ++i) {
5210 ss << std::hex << std::setw(2) << std::setfill('0') << static_cast<unsigned int>(hash[i]);
5216inline std::string MD5(
const std::string &s) {
return message_digest(s, EVP_md5()); }
5218inline std::string SHA_256(
const std::string &s) {
return message_digest(s, EVP_sha256()); }
5220inline std::string SHA_512(
const std::string &s) {
return message_digest(s, EVP_sha512()); }
5223#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
5227inline bool load_system_certs_on_windows(X509_STORE *store) {
5228 auto hStore = CertOpenSystemStoreW((HCRYPTPROV_LEGACY) NULL, L
"ROOT");
5233 auto result =
false;
5234 PCCERT_CONTEXT pContext = NULL;
5235 while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
nullptr) {
5236 auto encoded_cert =
static_cast<const unsigned char *
>(pContext->pbCertEncoded);
5238 auto x509 = d2i_X509(NULL, &encoded_cert, pContext->cbCertEncoded);
5240 X509_STORE_add_cert(store, x509);
5246 CertFreeCertificateContext(pContext);
5247 CertCloseStore(hStore, 0);
5251#elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && defined(__APPLE__)
5253template<
typename T>
using CFObjectPtr = std::unique_ptr<typename std::remove_pointer<T>::type, void (*)(CFTypeRef)>;
5255inline void cf_object_ptr_deleter(CFTypeRef obj) {
5261inline bool retrieve_certs_from_keychain(CFObjectPtr<CFArrayRef> &certs) {
5262 CFStringRef keys[] = {kSecClass, kSecMatchLimit, kSecReturnRef};
5263 CFTypeRef values[] = {kSecClassCertificate, kSecMatchLimitAll, kCFBooleanTrue};
5265 CFObjectPtr<CFDictionaryRef> query(
5266 CFDictionaryCreate(
nullptr,
reinterpret_cast<const void **
>(keys), values,
sizeof(keys) /
sizeof(keys[0]),
5267 &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks),
5268 cf_object_ptr_deleter);
5274 CFTypeRef security_items =
nullptr;
5275 if (SecItemCopyMatching(query.get(), &security_items) != errSecSuccess ||
5276 CFArrayGetTypeID() != CFGetTypeID(security_items)) {
5280 certs.reset(
reinterpret_cast<CFArrayRef
>(security_items));
5284inline bool retrieve_root_certs_from_keychain(CFObjectPtr<CFArrayRef> &certs) {
5285 CFArrayRef root_security_items =
nullptr;
5286 if (SecTrustCopyAnchorCertificates(&root_security_items) != errSecSuccess) {
5290 certs.reset(root_security_items);
5294inline bool add_certs_to_x509_store(CFArrayRef certs, X509_STORE *store) {
5295 auto result =
false;
5296 for (
auto i = 0; i < CFArrayGetCount(certs); ++i) {
5297 const auto cert =
reinterpret_cast<const __SecCertificate *
>(CFArrayGetValueAtIndex(certs, i));
5299 if (SecCertificateGetTypeID() != CFGetTypeID(cert)) {
5303 CFDataRef cert_data =
nullptr;
5304 if (SecItemExport(cert, kSecFormatX509Cert, 0,
nullptr, &cert_data) != errSecSuccess) {
5308 CFObjectPtr<CFDataRef> cert_data_ptr(cert_data, cf_object_ptr_deleter);
5310 auto encoded_cert =
static_cast<const unsigned char *
>(CFDataGetBytePtr(cert_data_ptr.get()));
5312 auto x509 = d2i_X509(NULL, &encoded_cert, CFDataGetLength(cert_data_ptr.get()));
5315 X509_STORE_add_cert(store, x509);
5324inline bool load_system_certs_on_macos(X509_STORE *store) {
5325 auto result =
false;
5326 CFObjectPtr<CFArrayRef> certs(
nullptr, cf_object_ptr_deleter);
5327 if (retrieve_certs_from_keychain(certs) && certs) {
5328 result = add_certs_to_x509_store(certs.get(), store);
5331 if (retrieve_root_certs_from_keychain(certs) && certs) {
5332 result = add_certs_to_x509_store(certs.get(), store) || result;
5346 if (WSAStartup(0x0002, &wsaData) == 0)
5355 bool is_valid_ =
false;
5358static WSInit wsinit_;
5361#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
5362inline std::pair<std::string, std::string> make_digest_authentication_header(
5363 const Request &req,
const std::map<std::string, std::string> &auth,
size_t cnonce_count,
const std::string &cnonce,
5364 const std::string &username,
const std::string &password,
bool is_proxy =
false) {
5367 std::stringstream ss;
5368 ss << std::setfill(
'0') << std::setw(8) << std::hex << cnonce_count;
5373 if (auth.find(
"qop") != auth.end()) {
5374 qop = auth.at(
"qop");
5375 if (qop.find(
"auth-int") != std::string::npos) {
5377 }
else if (qop.find(
"auth") != std::string::npos) {
5384 std::string algo =
"MD5";
5385 if (auth.find(
"algorithm") != auth.end()) {
5386 algo = auth.at(
"algorithm");
5389 std::string response;
5391 auto H = algo ==
"SHA-256" ? detail::SHA_256 : algo ==
"SHA-512" ? detail::SHA_512 : detail::MD5;
5393 auto A1 = username +
":" + auth.at(
"realm") +
":" + password;
5395 auto A2 = req.method +
":" + req.path;
5396 if (qop ==
"auth-int") {
5397 A2 +=
":" + H(req.body);
5401 response = H(H(A1) +
":" + auth.at(
"nonce") +
":" + H(A2));
5403 response = H(H(A1) +
":" + auth.at(
"nonce") +
":" + nc +
":" + cnonce +
":" + qop +
":" + H(A2));
5407 auto opaque = (auth.find(
"opaque") != auth.end()) ? auth.at(
"opaque") :
"";
5410 "Digest username=\"" + username +
"\", realm=\"" + auth.at(
"realm") +
"\", nonce=\"" + auth.at(
"nonce") +
5411 "\", uri=\"" + req.path +
"\", algorithm=" + algo +
5412 (qop.empty() ?
", response=\"" :
", qop=" + qop +
", nc=" + nc +
", cnonce=\"" + cnonce +
"\", response=\"") +
5413 response +
"\"" + (opaque.empty() ?
"" :
", opaque=\"" + opaque +
"\"");
5415 auto key = is_proxy ?
"Proxy-Authorization" :
"Authorization";
5416 return std::make_pair(
key, field);
5420inline bool parse_www_authenticate(
const Response &res, std::map<std::string, std::string> &auth,
bool is_proxy) {
5421 auto auth_key = is_proxy ?
"Proxy-Authenticate" :
"WWW-Authenticate";
5422 if (res.has_header(auth_key)) {
5423 static auto re = std::regex(R
"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
5424 auto s = res.get_header_value(auth_key);
5425 auto pos = s.find(
' ');
5426 if (pos != std::string::npos) {
5427 auto type = s.substr(0, pos);
5428 if (
type ==
"Basic") {
5430 }
else if (
type ==
"Digest") {
5431 s = s.substr(pos + 1);
5432 auto beg = std::sregex_iterator(s.begin(), s.end(), re);
5433 for (
auto i = beg; i != std::sregex_iterator(); ++i) {
5435 auto key = s.substr(
static_cast<size_t>(
m.position(1)),
static_cast<size_t>(
m.length(1)));
5436 auto val =
m.length(2) > 0 ? s.substr(
static_cast<size_t>(
m.position(2)),
static_cast<size_t>(
m.length(2)))
5437 : s.substr(
static_cast<size_t>(
m.position(3)),
static_cast<size_t>(
m.length(3)));
5447class ContentProviderAdapter {
5449 explicit ContentProviderAdapter(ContentProviderWithoutLength &&content_provider)
5450 : content_provider_(content_provider) {}
5452 bool operator()(
size_t offset,
size_t, DataSink &sink) {
return content_provider_(offset, sink); }
5455 ContentProviderWithoutLength content_provider_;
5460inline std::string hosted_at(
const std::string &hostname) {
5461 std::vector<std::string> addrs;
5462 hosted_at(hostname, addrs);
5463 if (addrs.empty()) {
5464 return std::string();
5469inline void hosted_at(
const std::string &hostname, std::vector<std::string> &addrs) {
5470 struct addrinfo hints;
5471 struct addrinfo *result;
5473 memset(&hints, 0,
sizeof(
struct addrinfo));
5474 hints.ai_family = AF_UNSPEC;
5475 hints.ai_socktype = SOCK_STREAM;
5476 hints.ai_protocol = 0;
5478 if (getaddrinfo(hostname.c_str(),
nullptr, &hints, &result)) {
5479#if defined __linux__ && !defined __ANDROID__
5484 auto se = detail::scope_exit([&] { freeaddrinfo(result); });
5486 for (
auto rp = result; rp; rp = rp->ai_next) {
5487 const auto &addr = *
reinterpret_cast<struct
sockaddr_storage *
>(rp->ai_addr);
5490 if (detail::get_ip_and_port(addr,
sizeof(
struct sockaddr_storage), ip, dummy)) {
5491 addrs.push_back(ip);
5496inline std::string append_query_params(
const std::string &path,
const Params ¶ms) {
5497 std::string path_with_query = path;
5498 const static std::regex re(
"[^?]+\\?.*");
5499 auto delm = std::regex_match(path, re) ?
'&' :
'?';
5500 path_with_query += delm + detail::params_to_query_str(params);
5501 return path_with_query;
5505inline std::pair<std::string, std::string> make_range_header(
const Ranges &ranges) {
5506 std::string field =
"bytes=";
5508 for (
const auto &r : ranges) {
5512 if (r.first != -1) {
5513 field += std::to_string(r.first);
5516 if (r.second != -1) {
5517 field += std::to_string(r.second);
5521 return std::make_pair(
"Range", std::move(field));
5524inline std::pair<std::string, std::string> make_basic_authentication_header(
const std::string &username,
5525 const std::string &password,
5527 auto field =
"Basic " + detail::base64_encode(username +
":" + password);
5528 auto key = is_proxy ?
"Proxy-Authorization" :
"Authorization";
5529 return std::make_pair(
key, std::move(field));
5532inline std::pair<std::string, std::string> make_bearer_token_authentication_header(
const std::string &token,
5533 bool is_proxy =
false) {
5534 auto field =
"Bearer " + token;
5535 auto key = is_proxy ?
"Proxy-Authorization" :
"Authorization";
5536 return std::make_pair(
key, std::move(field));
5540inline bool Request::has_header(
const std::string &
key)
const {
return detail::has_header(headers,
key); }
5542inline std::string Request::get_header_value(
const std::string &
key,
const char *def,
size_t id)
const {
5543 return detail::get_header_value(headers,
key, def,
id);
5546inline size_t Request::get_header_value_count(
const std::string &
key)
const {
5547 auto r = headers.equal_range(
key);
5548 return static_cast<size_t>(std::distance(r.first, r.second));
5551inline void Request::set_header(
const std::string &
key,
const std::string &
val) {
5552 if (!detail::has_crlf(
key) && !detail::has_crlf(
val)) {
5553 headers.emplace(
key,
val);
5557inline bool Request::has_param(
const std::string &
key)
const {
return params.find(
key) != params.end(); }
5559inline std::string Request::get_param_value(
const std::string &
key,
size_t id)
const {
5560 auto rng = params.equal_range(
key);
5561 auto it = rng.first;
5562 std::advance(it,
static_cast<ssize_t>(
id));
5563 if (it != rng.second) {
5566 return std::string();
5569inline size_t Request::get_param_value_count(
const std::string &
key)
const {
5570 auto r = params.equal_range(
key);
5571 return static_cast<size_t>(std::distance(r.first, r.second));
5574inline bool Request::is_multipart_form_data()
const {
5575 const auto &content_type = get_header_value(
"Content-Type");
5576 return !content_type.rfind(
"multipart/form-data", 0);
5579inline bool Request::has_file(
const std::string &
key)
const {
return files.find(
key) != files.end(); }
5581inline MultipartFormData Request::get_file_value(
const std::string &
key)
const {
5582 auto it = files.find(
key);
5583 if (it != files.end()) {
5586 return MultipartFormData();
5589inline std::vector<MultipartFormData> Request::get_file_values(
const std::string &
key)
const {
5590 std::vector<MultipartFormData> values;
5591 auto rng = files.equal_range(
key);
5592 for (
auto it = rng.first; it != rng.second; it++) {
5593 values.push_back(it->second);
5599inline bool Response::has_header(
const std::string &
key)
const {
return headers.find(
key) != headers.end(); }
5601inline std::string Response::get_header_value(
const std::string &
key,
const char *def,
size_t id)
const {
5602 return detail::get_header_value(headers,
key, def,
id);
5605inline size_t Response::get_header_value_count(
const std::string &
key)
const {
5606 auto r = headers.equal_range(
key);
5607 return static_cast<size_t>(std::distance(r.first, r.second));
5610inline void Response::set_header(
const std::string &
key,
const std::string &
val) {
5611 if (!detail::has_crlf(
key) && !detail::has_crlf(
val)) {
5612 headers.emplace(
key,
val);
5616inline void Response::set_redirect(
const std::string &url,
int stat) {
5617 if (!detail::has_crlf(url)) {
5618 set_header(
"Location", url);
5619 if (300 <= stat && stat < 400) {
5622 this->
status = StatusCode::Found_302;
5627inline void Response::set_content(
const char *s,
size_t n,
const std::string &content_type) {
5630 auto rng = headers.equal_range(
"Content-Type");
5631 headers.erase(rng.first, rng.second);
5632 set_header(
"Content-Type", content_type);
5635inline void Response::set_content(
const std::string &s,
const std::string &content_type) {
5636 set_content(s.data(), s.size(), content_type);
5639inline void Response::set_content(std::string &&s,
const std::string &content_type) {
5640 body = std::move(s);
5642 auto rng = headers.equal_range(
"Content-Type");
5643 headers.erase(rng.first, rng.second);
5644 set_header(
"Content-Type", content_type);
5647inline void Response::set_content_provider(
size_t in_length,
const std::string &content_type, ContentProvider provider,
5648 ContentProviderResourceReleaser resource_releaser) {
5649 set_header(
"Content-Type", content_type);
5650 content_length_ = in_length;
5651 if (in_length > 0) {
5652 content_provider_ = std::move(provider);
5654 content_provider_resource_releaser_ = std::move(resource_releaser);
5655 is_chunked_content_provider_ =
false;
5658inline void Response::set_content_provider(
const std::string &content_type, ContentProviderWithoutLength provider,
5659 ContentProviderResourceReleaser resource_releaser) {
5660 set_header(
"Content-Type", content_type);
5661 content_length_ = 0;
5662 content_provider_ = detail::ContentProviderAdapter(std::move(provider));
5663 content_provider_resource_releaser_ = std::move(resource_releaser);
5664 is_chunked_content_provider_ =
false;
5667inline void Response::set_chunked_content_provider(
const std::string &content_type,
5668 ContentProviderWithoutLength provider,
5669 ContentProviderResourceReleaser resource_releaser) {
5670 set_header(
"Content-Type", content_type);
5671 content_length_ = 0;
5672 content_provider_ = detail::ContentProviderAdapter(std::move(provider));
5673 content_provider_resource_releaser_ = std::move(resource_releaser);
5674 is_chunked_content_provider_ =
true;
5677inline void Response::set_file_content(
const std::string &path,
const std::string &content_type) {
5678 file_content_path_ = path;
5679 file_content_content_type_ = content_type;
5682inline void Response::set_file_content(
const std::string &path) { file_content_path_ = path; }
5685inline bool Result::has_request_header(
const std::string &
key)
const {
5686 return request_headers_.find(
key) != request_headers_.end();
5689inline std::string Result::get_request_header_value(
const std::string &
key,
const char *def,
size_t id)
const {
5690 return detail::get_header_value(request_headers_,
key, def,
id);
5693inline size_t Result::get_request_header_value_count(
const std::string &
key)
const {
5694 auto r = request_headers_.equal_range(
key);
5695 return static_cast<size_t>(std::distance(r.first, r.second));
5699inline ssize_t Stream::write(
const char *ptr) {
return write(ptr, strlen(ptr)); }
5701inline ssize_t Stream::write(
const std::string &s) {
return write(s.data(), s.size()); }
5706inline SocketStream::SocketStream(
socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
5707 time_t write_timeout_sec, time_t write_timeout_usec)
5709 read_timeout_sec_(read_timeout_sec),
5710 read_timeout_usec_(read_timeout_usec),
5711 write_timeout_sec_(write_timeout_sec),
5712 write_timeout_usec_(write_timeout_usec),
5713 read_buff_(read_buff_size_, 0) {}
5715inline SocketStream::~SocketStream() =
default;
5717inline bool SocketStream::is_readable()
const {
return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0; }
5719inline bool SocketStream::is_writable()
const {
5720 return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 && is_socket_alive(sock_);
5723inline ssize_t SocketStream::read(
char *ptr,
size_t size) {
5725 size = (std::min) (size,
static_cast<size_t>((std::numeric_limits<int>::max)()));
5727 size = (std::min) (size,
static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
5730 if (read_buff_off_ < read_buff_content_size_) {
5731 auto remaining_size = read_buff_content_size_ - read_buff_off_;
5732 if (size <= remaining_size) {
5733 memcpy(ptr, read_buff_.data() + read_buff_off_, size);
5734 read_buff_off_ +=
size;
5737 memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
5738 read_buff_off_ += remaining_size;
5739 return static_cast<ssize_t>(remaining_size);
5743 if (!is_readable()) {
5748 read_buff_content_size_ = 0;
5750 if (size < read_buff_size_) {
5751 auto n = read_socket(sock_, read_buff_.data(), read_buff_size_, CPPHTTPLIB_RECV_FLAGS);
5754 }
else if (n <=
static_cast<ssize_t>(size)) {
5755 memcpy(ptr, read_buff_.data(),
static_cast<size_t>(n));
5758 memcpy(ptr, read_buff_.data(), size);
5759 read_buff_off_ =
size;
5760 read_buff_content_size_ =
static_cast<size_t>(n);
5764 return read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
5768inline ssize_t SocketStream::write(
const char *ptr,
size_t size) {
5769 if (!is_writable()) {
5773#if defined(_WIN32) && !defined(_WIN64)
5774 size = (std::min) (size,
static_cast<size_t>((std::numeric_limits<int>::max)()));
5777 return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
5780inline void SocketStream::get_remote_ip_and_port(std::string &ip,
int &port)
const {
5781 return detail::get_remote_ip_and_port(sock_, ip, port);
5784inline void SocketStream::get_local_ip_and_port(std::string &ip,
int &port)
const {
5785 return detail::get_local_ip_and_port(sock_, ip, port);
5788inline socket_t SocketStream::socket()
const {
return sock_; }
5791inline bool BufferStream::is_readable()
const {
return true; }
5793inline bool BufferStream::is_writable()
const {
return true; }
5795inline ssize_t BufferStream::read(
char *ptr,
size_t size) {
5796#if defined(_MSC_VER) && _MSC_VER < 1910
5801 position +=
static_cast<size_t>(len_read);
5802 return static_cast<ssize_t>(len_read);
5805inline ssize_t BufferStream::write(
const char *ptr,
size_t size) {
5806 buffer.append(ptr, size);
5810inline void BufferStream::get_remote_ip_and_port(std::string & ,
int & )
const {}
5812inline void BufferStream::get_local_ip_and_port(std::string & ,
int & )
const {}
5814inline socket_t BufferStream::socket()
const {
return 0; }
5816inline const std::string &BufferStream::get_buffer()
const {
return buffer; }
5818inline PathParamsMatcher::PathParamsMatcher(
const std::string &pattern) {
5819 static constexpr char marker[] =
"/:";
5822 std::size_t last_param_end = 0;
5824#ifndef CPPHTTPLIB_NO_EXCEPTIONS
5829 std::unordered_set<std::string> param_name_set;
5833 const auto marker_pos = pattern.find(marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
5834 if (marker_pos == std::string::npos) {
5838 static_fragments_.push_back(pattern.substr(last_param_end, marker_pos - last_param_end + 1));
5840 const auto param_name_start = marker_pos + 2;
5842 auto sep_pos = pattern.find(separator, param_name_start);
5843 if (sep_pos == std::string::npos) {
5844 sep_pos = pattern.length();
5847 auto param_name = pattern.substr(param_name_start, sep_pos - param_name_start);
5849#ifndef CPPHTTPLIB_NO_EXCEPTIONS
5850 if (param_name_set.find(param_name) != param_name_set.cend()) {
5852 "Encountered path parameter '" + param_name +
"' multiple times in route pattern '" + pattern +
"'.";
5853 throw std::invalid_argument(msg);
5857 param_names_.push_back(std::move(param_name));
5859 last_param_end = sep_pos + 1;
5862 if (last_param_end < pattern.length()) {
5863 static_fragments_.push_back(pattern.substr(last_param_end));
5867inline bool PathParamsMatcher::match(Request &request)
const {
5868 request.matches = std::smatch();
5869 request.path_params.clear();
5870 request.path_params.reserve(param_names_.size());
5873 std::size_t starting_pos = 0;
5874 for (
size_t i = 0; i < static_fragments_.size(); ++i) {
5875 const auto &fragment = static_fragments_[i];
5877 if (starting_pos + fragment.length() > request.path.length()) {
5883 if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(), fragment.length()) != 0) {
5887 starting_pos += fragment.length();
5892 if (i >= param_names_.size()) {
5896 auto sep_pos = request.path.find(separator, starting_pos);
5897 if (sep_pos == std::string::npos) {
5898 sep_pos = request.path.length();
5901 const auto ¶m_name = param_names_[i];
5903 request.path_params.emplace(param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
5906 starting_pos = sep_pos + 1;
5909 return starting_pos >= request.path.length();
5912inline bool RegexMatcher::match(Request &request)
const {
5913 request.path_params.clear();
5914 return std::regex_match(request.path, request.matches, regex_);
5920inline Server::Server() : new_task_queue([] {
return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }) {
5922 signal(SIGPIPE, SIG_IGN);
5926inline Server::~Server() =
default;
5928inline std::unique_ptr<detail::MatcherBase> Server::make_matcher(
const std::string &pattern) {
5929 if (pattern.find(
"/:") != std::string::npos) {
5930 return detail::make_unique<detail::PathParamsMatcher>(pattern);
5932 return detail::make_unique<detail::RegexMatcher>(pattern);
5936inline Server &Server::Get(
const std::string &pattern, Handler handler) {
5937 get_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
5941inline Server &Server::Post(
const std::string &pattern, Handler handler) {
5942 post_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
5946inline Server &Server::Post(
const std::string &pattern, HandlerWithContentReader handler) {
5947 post_handlers_for_content_reader_.emplace_back(make_matcher(pattern), std::move(handler));
5951inline Server &Server::Put(
const std::string &pattern, Handler handler) {
5952 put_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
5956inline Server &Server::Put(
const std::string &pattern, HandlerWithContentReader handler) {
5957 put_handlers_for_content_reader_.emplace_back(make_matcher(pattern), std::move(handler));
5961inline Server &Server::Patch(
const std::string &pattern, Handler handler) {
5962 patch_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
5966inline Server &Server::Patch(
const std::string &pattern, HandlerWithContentReader handler) {
5967 patch_handlers_for_content_reader_.emplace_back(make_matcher(pattern), std::move(handler));
5971inline Server &Server::Delete(
const std::string &pattern, Handler handler) {
5972 delete_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
5976inline Server &Server::Delete(
const std::string &pattern, HandlerWithContentReader handler) {
5977 delete_handlers_for_content_reader_.emplace_back(make_matcher(pattern), std::move(handler));
5981inline Server &Server::Options(
const std::string &pattern, Handler handler) {
5982 options_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
5986inline bool Server::set_base_dir(
const std::string &dir,
const std::string &mount_point) {
5987 return set_mount_point(mount_point, dir);
5990inline bool Server::set_mount_point(
const std::string &mount_point,
const std::string &dir, Headers headers) {
5991 detail::FileStat stat(dir);
5992 if (stat.is_dir()) {
5993 std::string mnt = !mount_point.empty() ? mount_point :
"/";
5994 if (!mnt.empty() && mnt[0] ==
'/') {
5995 base_dirs_.push_back({mnt, dir, std::move(headers)});
6002inline bool Server::remove_mount_point(
const std::string &mount_point) {
6003 for (
auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
6004 if (it->mount_point == mount_point) {
6005 base_dirs_.erase(it);
6012inline Server &Server::set_file_extension_and_mimetype_mapping(
const std::string &ext,
const std::string &mime) {
6013 file_extension_and_mimetype_map_[ext] = mime;
6017inline Server &Server::set_default_file_mimetype(
const std::string &mime) {
6018 default_file_mimetype_ = mime;
6022inline Server &Server::set_file_request_handler(Handler handler) {
6023 file_request_handler_ = std::move(handler);
6027inline Server &Server::set_error_handler_core(HandlerWithResponse handler, std::true_type) {
6028 error_handler_ = std::move(handler);
6032inline Server &Server::set_error_handler_core(Handler handler, std::false_type) {
6033 error_handler_ = [handler](
const Request &req, Response &res) {
6035 return HandlerResponse::Handled;
6040inline Server &Server::set_exception_handler(ExceptionHandler handler) {
6041 exception_handler_ = std::move(handler);
6045inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
6046 pre_routing_handler_ = std::move(handler);
6050inline Server &Server::set_post_routing_handler(Handler handler) {
6051 post_routing_handler_ = std::move(handler);
6055inline Server &Server::set_logger(Logger logger) {
6056 logger_ = std::move(logger);
6060inline Server &Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
6061 expect_100_continue_handler_ = std::move(handler);
6065inline Server &Server::set_address_family(
int family) {
6066 address_family_ = family;
6070inline Server &Server::set_tcp_nodelay(
bool on) {
6075inline Server &Server::set_ipv6_v6only(
bool on) {
6080inline Server &Server::set_socket_options(SocketOptions socket_options) {
6081 socket_options_ = std::move(socket_options);
6085inline Server &Server::set_default_headers(Headers headers) {
6086 default_headers_ = std::move(headers);
6090inline Server &Server::set_header_writer(std::function<
ssize_t(Stream &, Headers &)>
const &writer) {
6091 header_writer_ = writer;
6095inline Server &Server::set_keep_alive_max_count(
size_t count) {
6096 keep_alive_max_count_ =
count;
6100inline Server &Server::set_keep_alive_timeout(time_t sec) {
6101 keep_alive_timeout_sec_ = sec;
6105inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
6106 read_timeout_sec_ = sec;
6107 read_timeout_usec_ = usec;
6111inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
6112 write_timeout_sec_ = sec;
6113 write_timeout_usec_ = usec;
6117inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
6118 idle_interval_sec_ = sec;
6119 idle_interval_usec_ = usec;
6123inline Server &Server::set_payload_max_length(
size_t length) {
6124 payload_max_length_ =
length;
6128inline bool Server::bind_to_port(
const std::string &host,
int port,
int socket_flags) {
6129 auto ret = bind_internal(host, port, socket_flags);
6131 is_decommisioned =
true;
6135inline int Server::bind_to_any_port(
const std::string &host,
int socket_flags) {
6136 auto ret = bind_internal(host, 0, socket_flags);
6138 is_decommisioned =
true;
6143inline bool Server::listen_after_bind() {
return listen_internal(); }
6145inline bool Server::listen(
const std::string &host,
int port,
int socket_flags) {
6146 return bind_to_port(host, port, socket_flags) && listen_internal();
6149inline bool Server::is_running()
const {
return is_running_; }
6151inline void Server::wait_until_ready()
const {
6152 while (!is_running_ && !is_decommisioned) {
6153 std::this_thread::sleep_for(std::chrono::milliseconds{1});
6157inline void Server::stop() {
6159 assert(svr_sock_ != INVALID_SOCKET);
6160 std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
6161 detail::shutdown_socket(sock);
6162 detail::close_socket(sock);
6164 is_decommisioned =
false;
6167inline void Server::decommission() { is_decommisioned =
true; }
6169inline bool Server::parse_request_line(
const char *s, Request &req)
const {
6170 auto len = strlen(s);
6171 if (
len < 2 || s[
len - 2] !=
'\r' || s[
len - 1] !=
'\n') {
6179 detail::split(s, s +
len,
' ', [&](
const char *b,
const char *e) {
6182 req.method = std::string(b, e);
6185 req.target = std::string(b, e);
6188 req.version = std::string(b, e);
6201 static const std::set<std::string> methods{
"GET",
"HEAD",
"POST",
"PUT",
"DELETE",
6202 "CONNECT",
"OPTIONS",
"TRACE",
"PATCH",
"PRI"};
6204 if (methods.find(req.method) == methods.end()) {
6208 if (req.version !=
"HTTP/1.1" && req.version !=
"HTTP/1.0") {
6214 for (
size_t i = 0; i < req.target.size(); i++) {
6215 if (req.target[i] ==
'#') {
6216 req.target.erase(i);
6221 detail::divide(req.target,
'?',
6222 [&](
const char *lhs_data, std::size_t lhs_size,
const char *rhs_data, std::size_t rhs_size) {
6223 req.path = detail::decode_url(std::string(lhs_data, lhs_size), false);
6224 detail::parse_query_text(rhs_data, rhs_size, req.params);
6231inline bool Server::write_response(Stream &strm,
bool close_connection, Request &req, Response &res) {
6235 return write_response_core(strm, close_connection, req, res,
false);
6238inline bool Server::write_response_with_content(Stream &strm,
bool close_connection,
const Request &req,
6240 return write_response_core(strm, close_connection, req, res,
true);
6243inline bool Server::write_response_core(Stream &strm,
bool close_connection,
const Request &req, Response &res,
6244 bool need_apply_ranges) {
6245 assert(res.status != -1);
6247 if (400 <= res.status && error_handler_ && error_handler_(req, res) == HandlerResponse::Handled) {
6248 need_apply_ranges =
true;
6251 std::string content_type;
6252 std::string boundary;
6253 if (need_apply_ranges) {
6254 apply_ranges(req, res, content_type, boundary);
6258 if (close_connection || req.get_header_value(
"Connection") ==
"close") {
6259 res.set_header(
"Connection",
"close");
6261 std::string s =
"timeout=";
6262 s += std::to_string(keep_alive_timeout_sec_);
6264 s += std::to_string(keep_alive_max_count_);
6265 res.set_header(
"Keep-Alive", s);
6268 if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) && !res.has_header(
"Content-Type")) {
6269 res.set_header(
"Content-Type",
"text/plain");
6272 if (res.body.empty() && !res.content_length_ && !res.content_provider_ && !res.has_header(
"Content-Length")) {
6273 res.set_header(
"Content-Length",
"0");
6276 if (req.method ==
"HEAD" && !res.has_header(
"Accept-Ranges")) {
6277 res.set_header(
"Accept-Ranges",
"bytes");
6280 if (post_routing_handler_) {
6281 post_routing_handler_(req, res);
6286 detail::BufferStream bstrm;
6287 if (!detail::write_response_line(bstrm, res.status)) {
6290 if (!header_writer_(bstrm, res.headers)) {
6295 auto &
data = bstrm.get_buffer();
6296 detail::write_data(strm,
data.data(),
data.size());
6301 if (req.method !=
"HEAD") {
6302 if (!res.body.empty()) {
6303 if (!detail::write_data(strm, res.body.data(), res.body.size())) {
6306 }
else if (res.content_provider_) {
6307 if (write_content_with_provider(strm, req, res, boundary, content_type)) {
6308 res.content_provider_success_ =
true;
6323inline bool Server::write_content_with_provider(Stream &strm,
const Request &req, Response &res,
6324 const std::string &boundary,
const std::string &content_type) {
6325 auto is_shutting_down = [
this]() {
return this->svr_sock_ == INVALID_SOCKET; };
6327 if (res.content_length_ > 0) {
6328 if (req.ranges.empty()) {
6329 return detail::write_content(strm, res.content_provider_, 0, res.content_length_, is_shutting_down);
6330 }
else if (req.ranges.size() == 1) {
6331 auto offset_and_length = detail::get_range_offset_and_length(req.ranges[0], res.content_length_);
6333 return detail::write_content(strm, res.content_provider_, offset_and_length.first, offset_and_length.second,
6336 return detail::write_multipart_ranges_data(strm, req, res, boundary, content_type, res.content_length_,
6340 if (res.is_chunked_content_provider_) {
6341 auto type = detail::encoding_type(req, res);
6343 std::unique_ptr<detail::compressor> compressor;
6344 if (
type == detail::EncodingType::Gzip) {
6345#ifdef CPPHTTPLIB_ZLIB_SUPPORT
6346 compressor = detail::make_unique<detail::gzip_compressor>();
6348 }
else if (
type == detail::EncodingType::Brotli) {
6349#ifdef CPPHTTPLIB_BROTLI_SUPPORT
6350 compressor = detail::make_unique<detail::brotli_compressor>();
6353 compressor = detail::make_unique<detail::nocompressor>();
6355 assert(compressor !=
nullptr);
6357 return detail::write_content_chunked(strm, res.content_provider_, is_shutting_down, *compressor);
6359 return detail::write_content_without_length(strm, res.content_provider_, is_shutting_down);
6364inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
6365 MultipartFormDataMap::iterator cur;
6366 auto file_count = 0;
6367 if (read_content_core(
6370 [&](
const char *buf,
size_t n) {
6371 if (req.body.size() + n > req.body.max_size()) {
6374 req.body.append(buf, n);
6378 [&](
const MultipartFormData &file) {
6379 if (file_count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
6382 cur = req.files.emplace(file.name, file);
6385 [&](
const char *buf,
size_t n) {
6386 auto &content = cur->second.content;
6387 if (content.size() + n > content.max_size()) {
6390 content.append(buf, n);
6393 const auto &content_type = req.get_header_value(
"Content-Type");
6394 if (!content_type.find(
"application/x-www-form-urlencoded")) {
6395 if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
6396 res.status = StatusCode::PayloadTooLarge_413;
6399 detail::parse_query_text(req.body, req.params);
6406inline bool Server::read_content_with_content_receiver(Stream &strm, Request &req, Response &res,
6407 ContentReceiver receiver,
6408 MultipartContentHeader multipart_header,
6409 ContentReceiver multipart_receiver) {
6410 return read_content_core(strm, req, res, std::move(receiver), std::move(multipart_header),
6411 std::move(multipart_receiver));
6414inline bool Server::read_content_core(Stream &strm, Request &req, Response &res, ContentReceiver receiver,
6415 MultipartContentHeader multipart_header,
6416 ContentReceiver multipart_receiver)
const {
6417 detail::MultipartFormDataParser multipart_form_data_parser;
6418 ContentReceiverWithProgress
out;
6420 if (req.is_multipart_form_data()) {
6421 const auto &content_type = req.get_header_value(
"Content-Type");
6422 std::string boundary;
6423 if (!detail::parse_multipart_boundary(content_type, boundary)) {
6424 res.status = StatusCode::BadRequest_400;
6428 multipart_form_data_parser.set_boundary(std::move(boundary));
6429 out = [&](
const char *buf,
size_t n, uint64_t , uint64_t ) {
6441 return multipart_form_data_parser.parse(buf, n, multipart_receiver, multipart_header);
6444 out = [receiver](
const char *buf,
size_t n, uint64_t , uint64_t ) {
return receiver(buf, n); };
6447 if (req.method ==
"DELETE" && !req.has_header(
"Content-Length")) {
6451 if (!detail::read_content(strm, req, payload_max_length_, res.status,
nullptr,
out,
true)) {
6455 if (req.is_multipart_form_data()) {
6456 if (!multipart_form_data_parser.is_valid()) {
6457 res.status = StatusCode::BadRequest_400;
6465inline bool Server::handle_file_request(
const Request &req, Response &res,
bool head) {
6466 for (
const auto &entry : base_dirs_) {
6468 if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
6469 std::string sub_path =
"/" + req.path.substr(entry.mount_point.size());
6470 if (detail::is_valid_path(sub_path)) {
6471 auto path = entry.base_dir + sub_path;
6472 if (path.back() ==
'/') {
6473 path +=
"index.html";
6476 detail::FileStat stat(path);
6478 if (stat.is_dir()) {
6479 res.set_redirect(sub_path +
"/", StatusCode::MovedPermanently_301);
6483 if (stat.is_file()) {
6484 for (
const auto &kv : entry.headers) {
6485 res.set_header(kv.first, kv.second);
6488 auto mm = std::make_shared<detail::mmap>(path.c_str());
6489 if (!mm->is_open()) {
6493 res.set_content_provider(
6494 mm->size(), detail::find_content_type(path, file_extension_and_mimetype_map_, default_file_mimetype_),
6495 [mm](
size_t offset,
size_t length, DataSink &sink) ->
bool {
6496 sink.write(mm->data() + offset, length);
6500 if (!head && file_request_handler_) {
6501 file_request_handler_(req, res);
6512inline socket_t Server::create_server_socket(
const std::string &host,
int port,
int socket_flags,
6513 SocketOptions socket_options)
const {
6514 return detail::create_socket(host, std::string(), port, address_family_, socket_flags, tcp_nodelay_, ipv6_v6only_,
6515 std::move(socket_options),
6516 [](
socket_t sock,
struct addrinfo &ai,
bool & ) ->
bool {
6517 if (::bind(sock, ai.ai_addr,
static_cast<socklen_t>(ai.ai_addrlen))) {
6520 if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
6527inline int Server::bind_internal(
const std::string &host,
int port,
int socket_flags) {
6528 if (is_decommisioned) {
6536 svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
6537 if (svr_sock_ == INVALID_SOCKET) {
6544 if (getsockname(svr_sock_,
reinterpret_cast<struct
sockaddr *
>(&addr), &
addr_len) == -1) {
6547 if (addr.ss_family == AF_INET) {
6548 return ntohs(
reinterpret_cast<struct
sockaddr_in *
>(&addr)->sin_port);
6549 }
else if (addr.ss_family == AF_INET6) {
6550 return ntohs(
reinterpret_cast<struct
sockaddr_in6 *
>(&addr)->sin6_port);
6559inline bool Server::listen_internal() {
6560 if (is_decommisioned) {
6566 auto se = detail::scope_exit([&]() { is_running_ =
false; });
6569 std::unique_ptr<TaskQueue> task_queue(new_task_queue());
6571 while (svr_sock_ != INVALID_SOCKET) {
6573 if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
6575 auto val = detail::select_read(svr_sock_, idle_interval_sec_, idle_interval_usec_);
6577 task_queue->on_idle();
6587 socket_t sock = WSAAccept(svr_sock_,
nullptr,
nullptr,
nullptr, 0);
6588#elif defined SOCK_CLOEXEC
6589 socket_t sock = accept4(svr_sock_,
nullptr,
nullptr, SOCK_CLOEXEC);
6591 socket_t sock = accept(svr_sock_,
nullptr,
nullptr);
6594 if (sock == INVALID_SOCKET) {
6595 if (errno == EMFILE) {
6598 std::this_thread::sleep_for(std::chrono::microseconds{1});
6600 }
else if (errno == EINTR || errno == EAGAIN) {
6603 if (svr_sock_ != INVALID_SOCKET) {
6604 detail::close_socket(svr_sock_);
6614 auto timeout =
static_cast<uint32_t>(read_timeout_sec_ * 1000 + read_timeout_usec_ / 1000);
6615 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,
reinterpret_cast<const char *
>(&timeout),
sizeof(timeout));
6618 tv.tv_sec =
static_cast<long>(read_timeout_sec_);
6619 tv.tv_usec =
static_cast<decltype(tv.tv_usec)
>(read_timeout_usec_);
6620 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,
reinterpret_cast<const void *
>(&tv),
sizeof(tv));
6625 auto timeout =
static_cast<uint32_t>(write_timeout_sec_ * 1000 + write_timeout_usec_ / 1000);
6626 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO,
reinterpret_cast<const char *
>(&timeout),
sizeof(timeout));
6629 tv.tv_sec =
static_cast<long>(write_timeout_sec_);
6630 tv.tv_usec =
static_cast<decltype(tv.tv_usec)
>(write_timeout_usec_);
6631 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO,
reinterpret_cast<const void *
>(&tv),
sizeof(tv));
6635 if (!task_queue->enqueue([
this, sock]() { process_and_close_socket(sock); })) {
6636 detail::shutdown_socket(sock);
6637 detail::close_socket(sock);
6641 task_queue->shutdown();
6644 is_decommisioned = !
ret;
6648inline bool Server::routing(Request &req, Response &res, Stream &strm) {
6649 if (pre_routing_handler_ && pre_routing_handler_(req, res) == HandlerResponse::Handled) {
6654 auto is_head_request = req.method ==
"HEAD";
6655 if ((req.method ==
"GET" || is_head_request) && handle_file_request(req, res, is_head_request)) {
6659 if (detail::expect_content(req)) {
6662 ContentReader reader(
6663 [&](ContentReceiver receiver) {
6664 return read_content_with_content_receiver(strm, req, res, std::move(receiver),
nullptr,
nullptr);
6666 [&](MultipartContentHeader header, ContentReceiver receiver) {
6667 return read_content_with_content_receiver(strm, req, res,
nullptr, std::move(header), std::move(receiver));
6670 if (req.method ==
"POST") {
6671 if (dispatch_request_for_content_reader(req, res, std::move(reader), post_handlers_for_content_reader_)) {
6674 }
else if (req.method ==
"PUT") {
6675 if (dispatch_request_for_content_reader(req, res, std::move(reader), put_handlers_for_content_reader_)) {
6678 }
else if (req.method ==
"PATCH") {
6679 if (dispatch_request_for_content_reader(req, res, std::move(reader), patch_handlers_for_content_reader_)) {
6682 }
else if (req.method ==
"DELETE") {
6683 if (dispatch_request_for_content_reader(req, res, std::move(reader), delete_handlers_for_content_reader_)) {
6690 if (!read_content(strm, req, res)) {
6696 if (req.method ==
"GET" || req.method ==
"HEAD") {
6697 return dispatch_request(req, res, get_handlers_);
6698 }
else if (req.method ==
"POST") {
6699 return dispatch_request(req, res, post_handlers_);
6700 }
else if (req.method ==
"PUT") {
6701 return dispatch_request(req, res, put_handlers_);
6702 }
else if (req.method ==
"DELETE") {
6703 return dispatch_request(req, res, delete_handlers_);
6704 }
else if (req.method ==
"OPTIONS") {
6705 return dispatch_request(req, res, options_handlers_);
6706 }
else if (req.method ==
"PATCH") {
6707 return dispatch_request(req, res, patch_handlers_);
6710 res.status = StatusCode::BadRequest_400;
6714inline bool Server::dispatch_request(Request &req, Response &res,
const Handlers &handlers)
const {
6715 for (
const auto &
x : handlers) {
6716 const auto &matcher =
x.first;
6717 const auto &handler =
x.second;
6719 if (matcher->match(req)) {
6727inline void Server::apply_ranges(
const Request &req, Response &res, std::string &content_type,
6728 std::string &boundary)
const {
6729 if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
6730 auto it = res.headers.find(
"Content-Type");
6731 if (it != res.headers.end()) {
6732 content_type = it->second;
6733 res.headers.erase(it);
6736 boundary = detail::make_multipart_data_boundary();
6738 res.set_header(
"Content-Type",
"multipart/byteranges; boundary=" + boundary);
6741 auto type = detail::encoding_type(req, res);
6743 if (res.body.empty()) {
6744 if (res.content_length_ > 0) {
6746 if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
6747 length = res.content_length_;
6748 }
else if (req.ranges.size() == 1) {
6749 auto offset_and_length = detail::get_range_offset_and_length(req.ranges[0], res.content_length_);
6751 length = offset_and_length.second;
6753 auto content_range = detail::make_content_range_header_field(offset_and_length, res.content_length_);
6754 res.set_header(
"Content-Range", content_range);
6756 length = detail::get_multipart_ranges_data_length(req, boundary, content_type, res.content_length_);
6758 res.set_header(
"Content-Length", std::to_string(
length));
6760 if (res.content_provider_) {
6761 if (res.is_chunked_content_provider_) {
6762 res.set_header(
"Transfer-Encoding",
"chunked");
6763 if (
type == detail::EncodingType::Gzip) {
6764 res.set_header(
"Content-Encoding",
"gzip");
6765 }
else if (
type == detail::EncodingType::Brotli) {
6766 res.set_header(
"Content-Encoding",
"br");
6772 if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
6774 }
else if (req.ranges.size() == 1) {
6775 auto offset_and_length = detail::get_range_offset_and_length(req.ranges[0], res.body.size());
6776 auto offset = offset_and_length.first;
6777 auto length = offset_and_length.second;
6779 auto content_range = detail::make_content_range_header_field(offset_and_length, res.body.size());
6780 res.set_header(
"Content-Range", content_range);
6782 assert(offset +
length <= res.body.size());
6783 res.body = res.body.substr(offset,
length);
6786 detail::make_multipart_ranges_data(req, res, boundary, content_type, res.body.size(), data);
6787 res.body.swap(data);
6790 if (
type != detail::EncodingType::None) {
6791 std::unique_ptr<detail::compressor> compressor;
6792 std::string content_encoding;
6794 if (
type == detail::EncodingType::Gzip) {
6795#ifdef CPPHTTPLIB_ZLIB_SUPPORT
6796 compressor = detail::make_unique<detail::gzip_compressor>();
6797 content_encoding =
"gzip";
6799 }
else if (
type == detail::EncodingType::Brotli) {
6800#ifdef CPPHTTPLIB_BROTLI_SUPPORT
6801 compressor = detail::make_unique<detail::brotli_compressor>();
6802 content_encoding =
"br";
6807 std::string compressed;
6808 if (compressor->compress(res.body.data(), res.body.size(),
true, [&](
const char *data,
size_t data_len) {
6809 compressed.append(data, data_len);
6812 res.body.swap(compressed);
6813 res.set_header(
"Content-Encoding", content_encoding);
6818 auto length = std::to_string(res.body.size());
6819 res.set_header(
"Content-Length",
length);
6823inline bool Server::dispatch_request_for_content_reader(Request &req, Response &res, ContentReader content_reader,
6824 const HandlersForContentReader &handlers)
const {
6825 for (
const auto &
x : handlers) {
6826 const auto &matcher =
x.first;
6827 const auto &handler =
x.second;
6829 if (matcher->match(req)) {
6830 handler(req, res, content_reader);
6837inline bool Server::process_request(Stream &strm,
const std::string &remote_addr,
int remote_port,
6838 const std::string &local_addr,
int local_port,
bool close_connection,
6839 bool &connection_closed,
const std::function<
void(Request &)> &setup_request) {
6840 std::array<char, 2048> buf{};
6842 detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
6845 if (!line_reader.getline()) {
6852 res.version =
"HTTP/1.1";
6853 res.headers = default_headers_;
6858#ifndef CPPHTTPLIB_USE_POLL
6860 if (strm.socket() >= FD_SETSIZE) {
6862 detail::read_headers(strm, dummy);
6863 res.status = StatusCode::InternalServerError_500;
6864 return write_response(strm, close_connection, req, res);
6870 if (line_reader.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
6872 detail::read_headers(strm, dummy);
6873 res.status = StatusCode::UriTooLong_414;
6874 return write_response(strm, close_connection, req, res);
6878 if (!parse_request_line(line_reader.ptr(), req) || !detail::read_headers(strm, req.headers)) {
6879 res.status = StatusCode::BadRequest_400;
6880 return write_response(strm, close_connection, req, res);
6883 if (req.get_header_value(
"Connection") ==
"close") {
6884 connection_closed =
true;
6887 if (req.version ==
"HTTP/1.0" && req.get_header_value(
"Connection") !=
"Keep-Alive") {
6888 connection_closed =
true;
6891 req.remote_addr = remote_addr;
6892 req.remote_port = remote_port;
6893 req.set_header(
"REMOTE_ADDR", req.remote_addr);
6894 req.set_header(
"REMOTE_PORT", std::to_string(req.remote_port));
6896 req.local_addr = local_addr;
6897 req.local_port = local_port;
6898 req.set_header(
"LOCAL_ADDR", req.local_addr);
6899 req.set_header(
"LOCAL_PORT", std::to_string(req.local_port));
6901 if (req.has_header(
"Range")) {
6902 const auto &range_header_value = req.get_header_value(
"Range");
6903 if (!detail::parse_range_header(range_header_value, req.ranges)) {
6904 res.status = StatusCode::RangeNotSatisfiable_416;
6905 return write_response(strm, close_connection, req, res);
6909 if (setup_request) {
6913 if (req.get_header_value(
"Expect") ==
"100-continue") {
6914 int status = StatusCode::Continue_100;
6915 if (expect_100_continue_handler_) {
6916 status = expect_100_continue_handler_(req, res);
6919 case StatusCode::Continue_100:
6920 case StatusCode::ExpectationFailed_417:
6921 detail::write_response_line(strm,
status);
6925 connection_closed =
true;
6926 return write_response(strm,
true, req, res);
6931 auto routed =
false;
6932#ifdef CPPHTTPLIB_NO_EXCEPTIONS
6933 routed = routing(req, res, strm);
6936 routed = routing(req, res, strm);
6937 }
catch (std::exception &e) {
6938 if (exception_handler_) {
6939 auto ep = std::current_exception();
6940 exception_handler_(req, res, ep);
6943 res.status = StatusCode::InternalServerError_500;
6946 for (
size_t i = 0; s[i]; i++) {
6959 res.set_header(
"EXCEPTION_WHAT",
val);
6962 if (exception_handler_) {
6963 auto ep = std::current_exception();
6964 exception_handler_(req, res, ep);
6967 res.status = StatusCode::InternalServerError_500;
6968 res.set_header(
"EXCEPTION_WHAT",
"UNKNOWN");
6973 if (res.status == -1) {
6974 res.status = req.ranges.empty() ? StatusCode::OK_200 : StatusCode::PartialContent_206;
6977 if (detail::range_error(req, res)) {
6979 res.content_length_ = 0;
6980 res.content_provider_ =
nullptr;
6981 res.status = StatusCode::RangeNotSatisfiable_416;
6982 return write_response(strm, close_connection, req, res);
6986 if (!res.file_content_path_.empty()) {
6987 const auto &path = res.file_content_path_;
6988 auto mm = std::make_shared<detail::mmap>(path.c_str());
6989 if (!mm->is_open()) {
6991 res.content_length_ = 0;
6992 res.content_provider_ =
nullptr;
6993 res.status = StatusCode::NotFound_404;
6994 return write_response(strm, close_connection, req, res);
6997 auto content_type = res.file_content_content_type_;
6998 if (content_type.empty()) {
6999 content_type = detail::find_content_type(path, file_extension_and_mimetype_map_, default_file_mimetype_);
7002 res.set_content_provider(mm->size(), content_type, [mm](
size_t offset,
size_t length, DataSink &sink) ->
bool {
7003 sink.write(mm->data() + offset, length);
7008 return write_response_with_content(strm, close_connection, req, res);
7010 if (res.status == -1) {
7011 res.status = StatusCode::NotFound_404;
7014 return write_response(strm, close_connection, req, res);
7018inline bool Server::is_valid()
const {
return true; }
7020inline bool Server::process_and_close_socket(
socket_t sock) {
7021 std::string remote_addr;
7022 int remote_port = 0;
7023 detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
7025 std::string local_addr;
7027 detail::get_local_ip_and_port(sock, local_addr, local_port);
7029 auto ret = detail::process_server_socket(
7030 svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_, read_timeout_sec_, read_timeout_usec_,
7031 write_timeout_sec_, write_timeout_usec_, [&](Stream &strm,
bool close_connection,
bool &connection_closed) {
7032 return process_request(strm, remote_addr, remote_port, local_addr, local_port, close_connection,
7033 connection_closed,
nullptr);
7036 detail::shutdown_socket(sock);
7037 detail::close_socket(sock);
7042inline ClientImpl::ClientImpl(
const std::string &host) : ClientImpl(
host, 80,
std::string(),
std::string()) {}
7044inline ClientImpl::ClientImpl(
const std::string &host,
int port)
7045 : ClientImpl(
host, port,
std::string(),
std::string()) {}
7047inline ClientImpl::ClientImpl(
const std::string &host,
int port,
const std::string &client_cert_path,
7048 const std::string &client_key_path)
7049 : host_(detail::escape_abstract_namespace_unix_domain(
host)),
7051 host_and_port_(adjust_host_string(host_) +
":" +
std::to_string(port)),
7052 client_cert_path_(client_cert_path),
7053 client_key_path_(client_key_path) {}
7055inline ClientImpl::~ClientImpl() {
7056 std::lock_guard<std::mutex> guard(socket_mutex_);
7057 shutdown_socket(socket_);
7058 close_socket(socket_);
7061inline bool ClientImpl::is_valid()
const {
return true; }
7063inline void ClientImpl::copy_settings(
const ClientImpl &rhs) {
7064 client_cert_path_ = rhs.client_cert_path_;
7065 client_key_path_ = rhs.client_key_path_;
7066 connection_timeout_sec_ = rhs.connection_timeout_sec_;
7067 read_timeout_sec_ = rhs.read_timeout_sec_;
7068 read_timeout_usec_ = rhs.read_timeout_usec_;
7069 write_timeout_sec_ = rhs.write_timeout_sec_;
7070 write_timeout_usec_ = rhs.write_timeout_usec_;
7071 basic_auth_username_ = rhs.basic_auth_username_;
7072 basic_auth_password_ = rhs.basic_auth_password_;
7073 bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
7074#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
7075 digest_auth_username_ = rhs.digest_auth_username_;
7076 digest_auth_password_ = rhs.digest_auth_password_;
7078 keep_alive_ = rhs.keep_alive_;
7079 follow_location_ = rhs.follow_location_;
7080 url_encode_ = rhs.url_encode_;
7081 address_family_ = rhs.address_family_;
7082 tcp_nodelay_ = rhs.tcp_nodelay_;
7083 ipv6_v6only_ = rhs.ipv6_v6only_;
7084 socket_options_ = rhs.socket_options_;
7085 compress_ = rhs.compress_;
7086 decompress_ = rhs.decompress_;
7087 interface_ = rhs.interface_;
7088 proxy_host_ = rhs.proxy_host_;
7089 proxy_port_ = rhs.proxy_port_;
7090 proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
7091 proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
7092 proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
7093#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
7094 proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
7095 proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
7097#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
7098 ca_cert_file_path_ = rhs.ca_cert_file_path_;
7099 ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
7100 ca_cert_store_ = rhs.ca_cert_store_;
7102#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
7103 server_certificate_verification_ = rhs.server_certificate_verification_;
7104 server_hostname_verification_ = rhs.server_hostname_verification_;
7105 server_certificate_verifier_ = rhs.server_certificate_verifier_;
7107 logger_ = rhs.logger_;
7110inline socket_t ClientImpl::create_client_socket(Error &error)
const {
7111 if (!proxy_host_.empty() && proxy_port_ != -1) {
7112 return detail::create_client_socket(proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
7113 ipv6_v6only_, socket_options_, connection_timeout_sec_,
7114 connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
7115 write_timeout_sec_, write_timeout_usec_, interface_, error);
7120 auto it = addr_map_.find(host_);
7121 if (it != addr_map_.end()) {
7125 return detail::create_client_socket(host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_, socket_options_,
7126 connection_timeout_sec_, connection_timeout_usec_, read_timeout_sec_,
7127 read_timeout_usec_, write_timeout_sec_, write_timeout_usec_, interface_, error);
7130inline bool ClientImpl::create_and_connect_socket(Socket &socket, Error &error) {
7131 auto sock = create_client_socket(error);
7132 if (sock == INVALID_SOCKET) {
7139inline void ClientImpl::shutdown_ssl(Socket & ,
bool ) {
7142 assert(socket_requests_in_flight_ == 0 || socket_requests_are_from_thread_ == std::this_thread::get_id());
7145inline void ClientImpl::shutdown_socket(Socket &socket)
const {
7146 if (
socket.sock == INVALID_SOCKET) {
7149 detail::shutdown_socket(
socket.sock);
7152inline void ClientImpl::close_socket(Socket &socket) {
7159 assert(socket_requests_in_flight_ == 0 || socket_requests_are_from_thread_ == std::this_thread::get_id());
7162#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
7163 assert(
socket.ssl ==
nullptr);
7165 if (
socket.sock == INVALID_SOCKET) {
7168 detail::close_socket(
socket.sock);
7169 socket.sock = INVALID_SOCKET;
7172inline bool ClientImpl::read_response_line(Stream &strm,
const Request &req, Response &res)
const {
7173 std::array<char, 2048> buf{};
7175 detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
7177 if (!line_reader.getline()) {
7181#ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
7182 const static std::regex re(
"(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
7184 const static std::regex re(
"(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
7188 if (!std::regex_match(line_reader.ptr(),
m, re)) {
7189 return req.method ==
"CONNECT";
7191 res.version = std::string(
m[1]);
7192 res.status = std::stoi(std::string(
m[2]));
7193 res.reason = std::string(
m[3]);
7196 while (res.status == StatusCode::Continue_100) {
7197 if (!line_reader.getline()) {
7200 if (!line_reader.getline()) {
7204 if (!std::regex_match(line_reader.ptr(),
m, re)) {
7207 res.version = std::string(
m[1]);
7208 res.status = std::stoi(std::string(
m[2]));
7209 res.reason = std::string(
m[3]);
7215inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
7216 std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
7217 auto ret = send_(req, res, error);
7218 if (error == Error::SSLPeerCouldBeClosed_) {
7220 ret = send_(req, res, error);
7225#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
7226inline bool ClientImpl::is_ssl_peer_could_be_closed(SSL *ssl)
const {
7228 return !SSL_peek(ssl, buf, 1) && SSL_get_error(ssl, 0) == SSL_ERROR_ZERO_RETURN;
7232inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
7234 std::lock_guard<std::mutex> guard(socket_mutex_);
7238 socket_should_be_closed_when_request_is_done_ =
false;
7240 auto is_alive =
false;
7241 if (socket_.is_open()) {
7242 is_alive = detail::is_socket_alive(socket_.sock);
7244#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
7245 if (is_alive && is_ssl()) {
7246 if (is_ssl_peer_could_be_closed(socket_.ssl)) {
7257 const bool shutdown_gracefully =
false;
7258 shutdown_ssl(socket_, shutdown_gracefully);
7259 shutdown_socket(socket_);
7260 close_socket(socket_);
7265 if (!create_and_connect_socket(socket_, error)) {
7269#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
7272 auto &scli =
static_cast<SSLClient &
>(*this);
7273 if (!proxy_host_.empty() && proxy_port_ != -1) {
7274 auto success =
false;
7275 if (!scli.connect_with_proxy(socket_, res, success, error)) {
7280 if (!scli.initialize_ssl(socket_, error)) {
7290 if (socket_requests_in_flight_ > 1) {
7291 assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
7293 socket_requests_in_flight_ += 1;
7294 socket_requests_are_from_thread_ = std::this_thread::get_id();
7297 for (
const auto &header : default_headers_) {
7298 if (req.headers.find(header.first) == req.headers.end()) {
7299 req.headers.insert(header);
7304 auto close_connection = !keep_alive_;
7306 auto se = detail::scope_exit([&]() {
7308 std::lock_guard<std::mutex> guard(socket_mutex_);
7309 socket_requests_in_flight_ -= 1;
7310 if (socket_requests_in_flight_ <= 0) {
7311 assert(socket_requests_in_flight_ == 0);
7312 socket_requests_are_from_thread_ = std::thread::id();
7315 if (socket_should_be_closed_when_request_is_done_ || close_connection || !
ret) {
7316 shutdown_ssl(socket_,
true);
7317 shutdown_socket(socket_);
7318 close_socket(socket_);
7322 ret = process_socket(socket_, [&](Stream &strm) {
return handle_request(strm, req, res, close_connection, error); });
7325 if (error == Error::Success) {
7326 error = Error::Unknown;
7333inline Result ClientImpl::send(
const Request &req) {
7335 return send_(std::move(req2));
7338inline Result ClientImpl::send_(Request &&req) {
7339 auto res = detail::make_unique<Response>();
7340 auto error = Error::Success;
7341 auto ret =
send(req, *res, error);
7342 return Result{
ret ? std::move(res) : nullptr, error,
std::move(req.headers)};
7345inline bool ClientImpl::handle_request(Stream &strm, Request &req, Response &res,
bool close_connection, Error &error) {
7346 if (req.path.empty()) {
7347 error = Error::Connection;
7351 auto req_save = req;
7355 if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) {
7357 req2.path =
"http://" + host_and_port_ + req.path;
7358 ret = process_request(strm, req2, res, close_connection, error);
7360 req.path = req_save.path;
7362 ret = process_request(strm, req, res, close_connection, error);
7369 if (res.get_header_value(
"Connection") ==
"close" ||
7370 (res.version ==
"HTTP/1.0" && res.reason !=
"Connection established")) {
7378 std::lock_guard<std::mutex> guard(socket_mutex_);
7379 shutdown_ssl(socket_,
true);
7380 shutdown_socket(socket_);
7381 close_socket(socket_);
7384 if (300 < res.status && res.status < 400 && follow_location_) {
7386 ret = redirect(req, res, error);
7389#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
7390 if ((res.status == StatusCode::Unauthorized_401 || res.status == StatusCode::ProxyAuthenticationRequired_407) &&
7391 req.authorization_count_ < 5) {
7392 auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
7393 const auto &username = is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
7394 const auto &password = is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
7396 if (!username.empty() && !password.empty()) {
7397 std::map<std::string, std::string> auth;
7398 if (detail::parse_www_authenticate(res, auth, is_proxy)) {
7399 Request new_req = req;
7400 new_req.authorization_count_ += 1;
7401 new_req.headers.erase(is_proxy ?
"Proxy-Authorization" :
"Authorization");
7402 new_req.headers.insert(detail::make_digest_authentication_header(
7403 req, auth, new_req.authorization_count_, detail::random_string(10), username, password, is_proxy));
7407 ret =
send(new_req, new_res, error);
7419inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
7420 if (req.redirect_count_ == 0) {
7421 error = Error::ExceedRedirectCount;
7425 auto location = res.get_header_value(
"location");
7426 if (location.empty()) {
7430 const static std::regex re(
7431 R
"((?:(https?):)?(?://(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*)(\?[^#]*)?(?:#.*)?)");
7434 if (!std::regex_match(location,
m, re)) {
7438 auto scheme = is_ssl() ?
"https" :
"http";
7440 auto next_scheme =
m[1].str();
7441 auto next_host =
m[2].str();
7442 if (next_host.empty()) {
7443 next_host =
m[3].str();
7445 auto port_str =
m[4].str();
7446 auto next_path =
m[5].str();
7447 auto next_query =
m[6].str();
7449 auto next_port = port_;
7450 if (!port_str.empty()) {
7451 next_port = std::stoi(port_str);
7452 }
else if (!next_scheme.empty()) {
7453 next_port = next_scheme ==
"https" ? 443 : 80;
7456 if (next_scheme.empty()) {
7457 next_scheme = scheme;
7459 if (next_host.empty()) {
7462 if (next_path.empty()) {
7466 auto path = detail::decode_url(next_path,
true) + next_query;
7468 if (next_scheme == scheme && next_host == host_ && next_port == port_) {
7469 return detail::redirect(*
this, req, res, path, location, error);
7471 if (next_scheme ==
"https") {
7472#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
7473 SSLClient cli(next_host, next_port);
7474 cli.copy_settings(*
this);
7475 if (ca_cert_store_) {
7476 cli.set_ca_cert_store(ca_cert_store_);
7478 return detail::redirect(cli, req, res, path, location, error);
7483 ClientImpl cli(next_host, next_port);
7484 cli.copy_settings(*
this);
7485 return detail::redirect(cli, req, res, path, location, error);
7490inline bool ClientImpl::write_content_with_provider(Stream &strm,
const Request &req, Error &error)
const {
7491 auto is_shutting_down = []() {
return false; };
7493 if (req.is_chunked_content_provider_) {
7495 std::unique_ptr<detail::compressor> compressor;
7496#ifdef CPPHTTPLIB_ZLIB_SUPPORT
7498 compressor = detail::make_unique<detail::gzip_compressor>();
7502 compressor = detail::make_unique<detail::nocompressor>();
7505 return detail::write_content_chunked(strm, req.content_provider_, is_shutting_down, *compressor, error);
7507 return detail::write_content(strm, req.content_provider_, 0, req.content_length_, is_shutting_down, error);
7511inline bool ClientImpl::write_request(Stream &strm, Request &req,
bool close_connection, Error &error) {
7513 if (close_connection) {
7514 if (!req.has_header(
"Connection")) {
7515 req.set_header(
"Connection",
"close");
7519 if (!req.has_header(
"Host")) {
7522 req.set_header(
"Host", host_);
7524 req.set_header(
"Host", host_and_port_);
7528 req.set_header(
"Host", host_);
7530 req.set_header(
"Host", host_and_port_);
7535 if (!req.has_header(
"Accept")) {
7536 req.set_header(
"Accept",
"*/*");
7539 if (!req.content_receiver) {
7540 if (!req.has_header(
"Accept-Encoding")) {
7541 std::string accept_encoding;
7542#ifdef CPPHTTPLIB_BROTLI_SUPPORT
7543 accept_encoding =
"br";
7545#ifdef CPPHTTPLIB_ZLIB_SUPPORT
7546 if (!accept_encoding.empty()) {
7547 accept_encoding +=
", ";
7549 accept_encoding +=
"gzip, deflate";
7551 req.set_header(
"Accept-Encoding", accept_encoding);
7554#ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
7555 if (!req.has_header(
"User-Agent")) {
7556 auto agent = std::string(
"cpp-httplib/") + CPPHTTPLIB_VERSION;
7557 req.set_header(
"User-Agent", agent);
7562 if (req.body.empty()) {
7563 if (req.content_provider_) {
7564 if (!req.is_chunked_content_provider_) {
7565 if (!req.has_header(
"Content-Length")) {
7566 auto length = std::to_string(req.content_length_);
7567 req.set_header(
"Content-Length",
length);
7571 if (req.method ==
"POST" || req.method ==
"PUT" || req.method ==
"PATCH") {
7572 req.set_header(
"Content-Length",
"0");
7576 if (!req.has_header(
"Content-Type")) {
7577 req.set_header(
"Content-Type",
"text/plain");
7580 if (!req.has_header(
"Content-Length")) {
7581 auto length = std::to_string(req.body.size());
7582 req.set_header(
"Content-Length",
length);
7586 if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
7587 if (!req.has_header(
"Authorization")) {
7588 req.headers.insert(make_basic_authentication_header(basic_auth_username_, basic_auth_password_,
false));
7592 if (!proxy_basic_auth_username_.empty() && !proxy_basic_auth_password_.empty()) {
7593 if (!req.has_header(
"Proxy-Authorization")) {
7595 make_basic_authentication_header(proxy_basic_auth_username_, proxy_basic_auth_password_,
true));
7599 if (!bearer_token_auth_token_.empty()) {
7600 if (!req.has_header(
"Authorization")) {
7601 req.headers.insert(make_bearer_token_authentication_header(bearer_token_auth_token_,
false));
7605 if (!proxy_bearer_token_auth_token_.empty()) {
7606 if (!req.has_header(
"Proxy-Authorization")) {
7607 req.headers.insert(make_bearer_token_authentication_header(proxy_bearer_token_auth_token_,
true));
7613 detail::BufferStream bstrm;
7615 const auto &path_with_query = req.params.empty() ? req.path : append_query_params(req.path, req.params);
7617 const auto &path = url_encode_ ? detail::encode_url(path_with_query) : path_with_query;
7619 detail::write_request_line(bstrm, req.method, path);
7621 header_writer_(bstrm, req.headers);
7624 auto &
data = bstrm.get_buffer();
7625 if (!detail::write_data(strm,
data.data(),
data.size())) {
7626 error = Error::Write;
7632 if (req.body.empty()) {
7633 return write_content_with_provider(strm, req, error);
7636 if (!detail::write_data(strm, req.body.data(), req.body.size())) {
7637 error = Error::Write;
7644inline std::unique_ptr<Response> ClientImpl::send_with_content_provider(
7645 Request &req,
const char *body,
size_t content_length, ContentProvider content_provider,
7646 ContentProviderWithoutLength content_provider_without_length,
const std::string &content_type, Error &error) {
7647 if (!content_type.empty()) {
7648 req.set_header(
"Content-Type", content_type);
7651#ifdef CPPHTTPLIB_ZLIB_SUPPORT
7653 req.set_header(
"Content-Encoding",
"gzip");
7657#ifdef CPPHTTPLIB_ZLIB_SUPPORT
7658 if (compress_ && !content_provider_without_length) {
7660 detail::gzip_compressor compressor;
7662 if (content_provider) {
7667 data_sink.write = [&](
const char *
data,
size_t data_len) ->
bool {
7669 auto last = offset + data_len == content_length;
7672 compressor.compress(data, data_len, last, [&](
const char *compressed_data,
size_t compressed_data_len) {
7673 req.body.append(compressed_data, compressed_data_len);
7686 while (ok && offset < content_length) {
7687 if (!content_provider(offset, content_length - offset, data_sink)) {
7688 error = Error::Canceled;
7693 if (!compressor.compress(body, content_length,
true, [&](
const char *data,
size_t data_len) {
7694 req.body.append(data, data_len);
7697 error = Error::Compression;
7704 if (content_provider) {
7705 req.content_length_ = content_length;
7706 req.content_provider_ = std::move(content_provider);
7707 req.is_chunked_content_provider_ =
false;
7708 }
else if (content_provider_without_length) {
7709 req.content_length_ = 0;
7710 req.content_provider_ = detail::ContentProviderAdapter(std::move(content_provider_without_length));
7711 req.is_chunked_content_provider_ =
true;
7712 req.set_header(
"Transfer-Encoding",
"chunked");
7714 req.body.assign(body, content_length);
7718 auto res = detail::make_unique<Response>();
7719 return send(req, *res, error) ? std::move(res) : nullptr;
7722inline Result ClientImpl::send_with_content_provider(
const std::string &method,
const std::string &path,
7723 const Headers &headers,
const char *body,
size_t content_length,
7724 ContentProvider content_provider,
7725 ContentProviderWithoutLength content_provider_without_length,
7726 const std::string &content_type, Progress progress) {
7728 req.method = method;
7729 req.headers = headers;
7731 req.progress = progress;
7733 auto error = Error::Success;
7735 auto res = send_with_content_provider(req, body, content_length, std::move(content_provider),
7736 std::move(content_provider_without_length), content_type, error);
7738 return Result{std::move(res), error, std::move(req.headers)};
7741inline std::string ClientImpl::adjust_host_string(
const std::string &host)
const {
7742 if (
host.find(
':') != std::string::npos) {
7743 return "[" +
host +
"]";
7748inline bool ClientImpl::process_request(Stream &strm, Request &req, Response &res,
bool close_connection,
7751 if (!write_request(strm, req, close_connection, error)) {
7755#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
7757 auto is_proxy_enabled = !proxy_host_.empty() && proxy_port_ != -1;
7758 if (!is_proxy_enabled) {
7759 if (is_ssl_peer_could_be_closed(socket_.ssl)) {
7760 error = Error::SSLPeerCouldBeClosed_;
7768 if (!read_response_line(strm, req, res) || !detail::read_headers(strm, res.headers)) {
7769 error = Error::Read;
7774 if ((res.status != StatusCode::NoContent_204) && req.method !=
"HEAD" && req.method !=
"CONNECT") {
7775 auto redirect = 300 < res.status && res.status < 400 && follow_location_;
7777 if (req.response_handler && !redirect) {
7778 if (!req.response_handler(res)) {
7779 error = Error::Canceled;
7785 req.content_receiver
7786 ?
static_cast<ContentReceiverWithProgress
>([&](
const char *buf,
size_t n, uint64_t off, uint64_t
len) {
7790 auto ret = req.content_receiver(buf, n, off,
len);
7792 error = Error::Canceled;
7796 : static_cast<ContentReceiverWithProgress>(
7797 [&](const char *buf, size_t n, uint64_t , uint64_t ) {
7798 assert(res.body.size() + n <= res.body.max_size());
7799 res.body.append(buf, n);
7803 auto progress = [&](uint64_t current, uint64_t total) {
7804 if (!req.progress || redirect) {
7807 auto ret = req.progress(current, total);
7809 error = Error::Canceled;
7814 if (res.has_header(
"Content-Length")) {
7815 if (!req.content_receiver) {
7816 auto len = res.get_header_value_u64(
"Content-Length");
7817 if (
len > res.body.max_size()) {
7818 error = Error::Read;
7821 res.body.reserve(
len);
7826 if (!detail::read_content(strm, res, (std::numeric_limits<size_t>::max)(), dummy_status, std::move(progress),
7827 std::move(
out), decompress_)) {
7828 if (error != Error::Canceled) {
7829 error = Error::Read;
7843inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
7844 const std::string &boundary,
const MultipartFormDataItems &items,
7845 const MultipartFormDataProviderItems &provider_items)
const {
7846 size_t cur_item = 0;
7847 size_t cur_start = 0;
7850 return [&, cur_item, cur_start](
size_t offset, DataSink &sink)
mutable ->
bool {
7851 if (!offset && !items.empty()) {
7852 sink.os << detail::serialize_multipart_formdata(items, boundary,
false);
7854 }
else if (cur_item < provider_items.size()) {
7856 const auto &begin = detail::serialize_multipart_formdata_item_begin(provider_items[cur_item], boundary);
7857 offset += begin.size();
7863 auto has_data =
true;
7864 cur_sink.write = sink.write;
7865 cur_sink.done = [&]() { has_data =
false; };
7867 if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
7872 sink.os << detail::serialize_multipart_formdata_item_end();
7878 sink.os << detail::serialize_multipart_formdata_finish(boundary);
7885inline bool ClientImpl::process_socket(
const Socket &socket, std::function<
bool(Stream &strm)> callback) {
7886 return detail::process_client_socket(
socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
7887 write_timeout_usec_, std::move(callback));
7890inline bool ClientImpl::is_ssl()
const {
return false; }
7892inline Result ClientImpl::Get(
const std::string &path) {
return Get(path, Headers(), Progress()); }
7894inline Result ClientImpl::Get(
const std::string &path, Progress progress) {
7895 return Get(path, Headers(), std::move(progress));
7898inline Result ClientImpl::Get(
const std::string &path,
const Headers &headers) {
7899 return Get(path, headers, Progress());
7902inline Result ClientImpl::Get(
const std::string &path,
const Headers &headers, Progress progress) {
7906 req.headers = headers;
7907 req.progress = std::move(progress);
7909 return send_(std::move(req));
7912inline Result ClientImpl::Get(
const std::string &path, ContentReceiver content_receiver) {
7913 return Get(path, Headers(),
nullptr, std::move(content_receiver),
nullptr);
7916inline Result ClientImpl::Get(
const std::string &path, ContentReceiver content_receiver, Progress progress) {
7917 return Get(path, Headers(),
nullptr, std::move(content_receiver), std::move(progress));
7920inline Result ClientImpl::Get(
const std::string &path,
const Headers &headers, ContentReceiver content_receiver) {
7921 return Get(path, headers,
nullptr, std::move(content_receiver),
nullptr);
7924inline Result ClientImpl::Get(
const std::string &path,
const Headers &headers, ContentReceiver content_receiver,
7925 Progress progress) {
7926 return Get(path, headers,
nullptr, std::move(content_receiver), std::move(progress));
7929inline Result ClientImpl::Get(
const std::string &path, ResponseHandler response_handler,
7930 ContentReceiver content_receiver) {
7931 return Get(path, Headers(), std::move(response_handler), std::move(content_receiver),
nullptr);
7934inline Result ClientImpl::Get(
const std::string &path,
const Headers &headers, ResponseHandler response_handler,
7935 ContentReceiver content_receiver) {
7936 return Get(path, headers, std::move(response_handler), std::move(content_receiver),
nullptr);
7939inline Result ClientImpl::Get(
const std::string &path, ResponseHandler response_handler,
7940 ContentReceiver content_receiver, Progress progress) {
7941 return Get(path, Headers(), std::move(response_handler), std::move(content_receiver), std::move(progress));
7944inline Result ClientImpl::Get(
const std::string &path,
const Headers &headers, ResponseHandler response_handler,
7945 ContentReceiver content_receiver, Progress progress) {
7949 req.headers = headers;
7950 req.response_handler = std::move(response_handler);
7951 req.content_receiver = [content_receiver](
const char *
data,
size_t data_length, uint64_t ,
7952 uint64_t ) {
return content_receiver(data, data_length); };
7953 req.progress = std::move(progress);
7955 return send_(std::move(req));
7958inline Result ClientImpl::Get(
const std::string &path,
const Params ¶ms,
const Headers &headers,
7959 Progress progress) {
7960 if (params.empty()) {
7961 return Get(path, headers);
7964 std::string path_with_query = append_query_params(path, params);
7965 return Get(path_with_query, headers, std::move(progress));
7968inline Result ClientImpl::Get(
const std::string &path,
const Params ¶ms,
const Headers &headers,
7969 ContentReceiver content_receiver, Progress progress) {
7970 return Get(path, params, headers,
nullptr, std::move(content_receiver), std::move(progress));
7973inline Result ClientImpl::Get(
const std::string &path,
const Params ¶ms,
const Headers &headers,
7974 ResponseHandler response_handler, ContentReceiver content_receiver, Progress progress) {
7975 if (params.empty()) {
7976 return Get(path, headers, std::move(response_handler), std::move(content_receiver), std::move(progress));
7979 std::string path_with_query = append_query_params(path, params);
7980 return Get(path_with_query, headers, std::move(response_handler), std::move(content_receiver), std::move(progress));
7983inline Result ClientImpl::Head(
const std::string &path) {
return Head(path, Headers()); }
7985inline Result ClientImpl::Head(
const std::string &path,
const Headers &headers) {
7987 req.method =
"HEAD";
7988 req.headers = headers;
7991 return send_(std::move(req));
7994inline Result ClientImpl::Post(
const std::string &path) {
return Post(path, std::string(), std::string()); }
7996inline Result ClientImpl::Post(
const std::string &path,
const Headers &headers) {
7997 return Post(path, headers,
nullptr, 0, std::string());
8000inline Result ClientImpl::Post(
const std::string &path,
const char *body,
size_t content_length,
8001 const std::string &content_type) {
8002 return Post(path, Headers(), body, content_length, content_type,
nullptr);
8005inline Result ClientImpl::Post(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
8006 const std::string &content_type) {
8007 return send_with_content_provider(
"POST", path, headers, body, content_length,
nullptr,
nullptr, content_type,
8011inline Result ClientImpl::Post(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
8012 const std::string &content_type, Progress progress) {
8013 return send_with_content_provider(
"POST", path, headers, body, content_length,
nullptr,
nullptr, content_type,
8017inline Result ClientImpl::Post(
const std::string &path,
const std::string &body,
const std::string &content_type) {
8018 return Post(path, Headers(), body, content_type);
8021inline Result ClientImpl::Post(
const std::string &path,
const std::string &body,
const std::string &content_type,
8022 Progress progress) {
8023 return Post(path, Headers(), body, content_type, progress);
8026inline Result ClientImpl::Post(
const std::string &path,
const Headers &headers,
const std::string &body,
8027 const std::string &content_type) {
8028 return send_with_content_provider(
"POST", path, headers, body.data(), body.size(),
nullptr,
nullptr, content_type,
8032inline Result ClientImpl::Post(
const std::string &path,
const Headers &headers,
const std::string &body,
8033 const std::string &content_type, Progress progress) {
8034 return send_with_content_provider(
"POST", path, headers, body.data(), body.size(),
nullptr,
nullptr, content_type,
8038inline Result ClientImpl::Post(
const std::string &path,
const Params ¶ms) {
return Post(path, Headers(), params); }
8040inline Result ClientImpl::Post(
const std::string &path,
size_t content_length, ContentProvider content_provider,
8041 const std::string &content_type) {
8042 return Post(path, Headers(), content_length, std::move(content_provider), content_type);
8045inline Result ClientImpl::Post(
const std::string &path, ContentProviderWithoutLength content_provider,
8046 const std::string &content_type) {
8047 return Post(path, Headers(), std::move(content_provider), content_type);
8050inline Result ClientImpl::Post(
const std::string &path,
const Headers &headers,
size_t content_length,
8051 ContentProvider content_provider,
const std::string &content_type) {
8052 return send_with_content_provider(
"POST", path, headers,
nullptr, content_length, std::move(content_provider),
8053 nullptr, content_type,
nullptr);
8056inline Result ClientImpl::Post(
const std::string &path,
const Headers &headers,
8057 ContentProviderWithoutLength content_provider,
const std::string &content_type) {
8058 return send_with_content_provider(
"POST", path, headers,
nullptr, 0,
nullptr, std::move(content_provider),
8059 content_type,
nullptr);
8062inline Result ClientImpl::Post(
const std::string &path,
const Headers &headers,
const Params ¶ms) {
8063 auto query = detail::params_to_query_str(params);
8064 return Post(path, headers, query,
"application/x-www-form-urlencoded");
8067inline Result ClientImpl::Post(
const std::string &path,
const Headers &headers,
const Params ¶ms,
8068 Progress progress) {
8069 auto query = detail::params_to_query_str(params);
8070 return Post(path, headers, query,
"application/x-www-form-urlencoded", progress);
8073inline Result ClientImpl::Post(
const std::string &path,
const MultipartFormDataItems &items) {
8074 return Post(path, Headers(), items);
8077inline Result ClientImpl::Post(
const std::string &path,
const Headers &headers,
const MultipartFormDataItems &items) {
8078 const auto &boundary = detail::make_multipart_data_boundary();
8079 const auto &content_type = detail::serialize_multipart_formdata_get_content_type(boundary);
8080 const auto &body = detail::serialize_multipart_formdata(items, boundary);
8081 return Post(path, headers, body, content_type);
8084inline Result ClientImpl::Post(
const std::string &path,
const Headers &headers,
const MultipartFormDataItems &items,
8085 const std::string &boundary) {
8086 if (!detail::is_multipart_boundary_chars_valid(boundary)) {
8087 return Result{
nullptr, Error::UnsupportedMultipartBoundaryChars};
8090 const auto &content_type = detail::serialize_multipart_formdata_get_content_type(boundary);
8091 const auto &body = detail::serialize_multipart_formdata(items, boundary);
8092 return Post(path, headers, body, content_type);
8095inline Result ClientImpl::Post(
const std::string &path,
const Headers &headers,
const MultipartFormDataItems &items,
8096 const MultipartFormDataProviderItems &provider_items) {
8097 const auto &boundary = detail::make_multipart_data_boundary();
8098 const auto &content_type = detail::serialize_multipart_formdata_get_content_type(boundary);
8099 return send_with_content_provider(
"POST", path, headers,
nullptr, 0,
nullptr,
8100 get_multipart_content_provider(boundary, items, provider_items), content_type,
8104inline Result ClientImpl::Put(
const std::string &path) {
return Put(path, std::string(), std::string()); }
8106inline Result ClientImpl::Put(
const std::string &path,
const char *body,
size_t content_length,
8107 const std::string &content_type) {
8108 return Put(path, Headers(), body, content_length, content_type);
8111inline Result ClientImpl::Put(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
8112 const std::string &content_type) {
8113 return send_with_content_provider(
"PUT", path, headers, body, content_length,
nullptr,
nullptr, content_type,
8117inline Result ClientImpl::Put(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
8118 const std::string &content_type, Progress progress) {
8119 return send_with_content_provider(
"PUT", path, headers, body, content_length,
nullptr,
nullptr, content_type,
8123inline Result ClientImpl::Put(
const std::string &path,
const std::string &body,
const std::string &content_type) {
8124 return Put(path, Headers(), body, content_type);
8127inline Result ClientImpl::Put(
const std::string &path,
const std::string &body,
const std::string &content_type,
8128 Progress progress) {
8129 return Put(path, Headers(), body, content_type, progress);
8132inline Result ClientImpl::Put(
const std::string &path,
const Headers &headers,
const std::string &body,
8133 const std::string &content_type) {
8134 return send_with_content_provider(
"PUT", path, headers, body.data(), body.size(),
nullptr,
nullptr, content_type,
8138inline Result ClientImpl::Put(
const std::string &path,
const Headers &headers,
const std::string &body,
8139 const std::string &content_type, Progress progress) {
8140 return send_with_content_provider(
"PUT", path, headers, body.data(), body.size(),
nullptr,
nullptr, content_type,
8144inline Result ClientImpl::Put(
const std::string &path,
size_t content_length, ContentProvider content_provider,
8145 const std::string &content_type) {
8146 return Put(path, Headers(), content_length, std::move(content_provider), content_type);
8149inline Result ClientImpl::Put(
const std::string &path, ContentProviderWithoutLength content_provider,
8150 const std::string &content_type) {
8151 return Put(path, Headers(), std::move(content_provider), content_type);
8154inline Result ClientImpl::Put(
const std::string &path,
const Headers &headers,
size_t content_length,
8155 ContentProvider content_provider,
const std::string &content_type) {
8156 return send_with_content_provider(
"PUT", path, headers,
nullptr, content_length, std::move(content_provider),
nullptr,
8157 content_type,
nullptr);
8160inline Result ClientImpl::Put(
const std::string &path,
const Headers &headers,
8161 ContentProviderWithoutLength content_provider,
const std::string &content_type) {
8162 return send_with_content_provider(
"PUT", path, headers,
nullptr, 0,
nullptr, std::move(content_provider),
8163 content_type,
nullptr);
8166inline Result ClientImpl::Put(
const std::string &path,
const Params ¶ms) {
return Put(path, Headers(), params); }
8168inline Result ClientImpl::Put(
const std::string &path,
const Headers &headers,
const Params ¶ms) {
8169 auto query = detail::params_to_query_str(params);
8170 return Put(path, headers, query,
"application/x-www-form-urlencoded");
8173inline Result ClientImpl::Put(
const std::string &path,
const Headers &headers,
const Params ¶ms,
8174 Progress progress) {
8175 auto query = detail::params_to_query_str(params);
8176 return Put(path, headers, query,
"application/x-www-form-urlencoded", progress);
8179inline Result ClientImpl::Put(
const std::string &path,
const MultipartFormDataItems &items) {
8180 return Put(path, Headers(), items);
8183inline Result ClientImpl::Put(
const std::string &path,
const Headers &headers,
const MultipartFormDataItems &items) {
8184 const auto &boundary = detail::make_multipart_data_boundary();
8185 const auto &content_type = detail::serialize_multipart_formdata_get_content_type(boundary);
8186 const auto &body = detail::serialize_multipart_formdata(items, boundary);
8187 return Put(path, headers, body, content_type);
8190inline Result ClientImpl::Put(
const std::string &path,
const Headers &headers,
const MultipartFormDataItems &items,
8191 const std::string &boundary) {
8192 if (!detail::is_multipart_boundary_chars_valid(boundary)) {
8193 return Result{
nullptr, Error::UnsupportedMultipartBoundaryChars};
8196 const auto &content_type = detail::serialize_multipart_formdata_get_content_type(boundary);
8197 const auto &body = detail::serialize_multipart_formdata(items, boundary);
8198 return Put(path, headers, body, content_type);
8201inline Result ClientImpl::Put(
const std::string &path,
const Headers &headers,
const MultipartFormDataItems &items,
8202 const MultipartFormDataProviderItems &provider_items) {
8203 const auto &boundary = detail::make_multipart_data_boundary();
8204 const auto &content_type = detail::serialize_multipart_formdata_get_content_type(boundary);
8205 return send_with_content_provider(
"PUT", path, headers,
nullptr, 0,
nullptr,
8206 get_multipart_content_provider(boundary, items, provider_items), content_type,
8209inline Result ClientImpl::Patch(
const std::string &path) {
return Patch(path, std::string(), std::string()); }
8211inline Result ClientImpl::Patch(
const std::string &path,
const char *body,
size_t content_length,
8212 const std::string &content_type) {
8213 return Patch(path, Headers(), body, content_length, content_type);
8216inline Result ClientImpl::Patch(
const std::string &path,
const char *body,
size_t content_length,
8217 const std::string &content_type, Progress progress) {
8218 return Patch(path, Headers(), body, content_length, content_type, progress);
8221inline Result ClientImpl::Patch(
const std::string &path,
const Headers &headers,
const char *body,
8222 size_t content_length,
const std::string &content_type) {
8223 return Patch(path, headers, body, content_length, content_type,
nullptr);
8226inline Result ClientImpl::Patch(
const std::string &path,
const Headers &headers,
const char *body,
8227 size_t content_length,
const std::string &content_type, Progress progress) {
8228 return send_with_content_provider(
"PATCH", path, headers, body, content_length,
nullptr,
nullptr, content_type,
8232inline Result ClientImpl::Patch(
const std::string &path,
const std::string &body,
const std::string &content_type) {
8233 return Patch(path, Headers(), body, content_type);
8236inline Result ClientImpl::Patch(
const std::string &path,
const std::string &body,
const std::string &content_type,
8237 Progress progress) {
8238 return Patch(path, Headers(), body, content_type, progress);
8241inline Result ClientImpl::Patch(
const std::string &path,
const Headers &headers,
const std::string &body,
8242 const std::string &content_type) {
8243 return Patch(path, headers, body, content_type,
nullptr);
8246inline Result ClientImpl::Patch(
const std::string &path,
const Headers &headers,
const std::string &body,
8247 const std::string &content_type, Progress progress) {
8248 return send_with_content_provider(
"PATCH", path, headers, body.data(), body.size(),
nullptr,
nullptr, content_type,
8252inline Result ClientImpl::Patch(
const std::string &path,
size_t content_length, ContentProvider content_provider,
8253 const std::string &content_type) {
8254 return Patch(path, Headers(), content_length, std::move(content_provider), content_type);
8257inline Result ClientImpl::Patch(
const std::string &path, ContentProviderWithoutLength content_provider,
8258 const std::string &content_type) {
8259 return Patch(path, Headers(), std::move(content_provider), content_type);
8262inline Result ClientImpl::Patch(
const std::string &path,
const Headers &headers,
size_t content_length,
8263 ContentProvider content_provider,
const std::string &content_type) {
8264 return send_with_content_provider(
"PATCH", path, headers,
nullptr, content_length, std::move(content_provider),
8265 nullptr, content_type,
nullptr);
8268inline Result ClientImpl::Patch(
const std::string &path,
const Headers &headers,
8269 ContentProviderWithoutLength content_provider,
const std::string &content_type) {
8270 return send_with_content_provider(
"PATCH", path, headers,
nullptr, 0,
nullptr, std::move(content_provider),
8271 content_type,
nullptr);
8274inline Result ClientImpl::Delete(
const std::string &path) {
8275 return Delete(path, Headers(), std::string(), std::string());
8278inline Result ClientImpl::Delete(
const std::string &path,
const Headers &headers) {
8279 return Delete(path, headers, std::string(), std::string());
8282inline Result ClientImpl::Delete(
const std::string &path,
const char *body,
size_t content_length,
8283 const std::string &content_type) {
8284 return Delete(path, Headers(), body, content_length, content_type);
8287inline Result ClientImpl::Delete(
const std::string &path,
const char *body,
size_t content_length,
8288 const std::string &content_type, Progress progress) {
8289 return Delete(path, Headers(), body, content_length, content_type, progress);
8292inline Result ClientImpl::Delete(
const std::string &path,
const Headers &headers,
const char *body,
8293 size_t content_length,
const std::string &content_type) {
8294 return Delete(path, headers, body, content_length, content_type,
nullptr);
8297inline Result ClientImpl::Delete(
const std::string &path,
const Headers &headers,
const char *body,
8298 size_t content_length,
const std::string &content_type, Progress progress) {
8300 req.method =
"DELETE";
8301 req.headers = headers;
8303 req.progress = progress;
8305 if (!content_type.empty()) {
8306 req.set_header(
"Content-Type", content_type);
8308 req.body.assign(body, content_length);
8310 return send_(std::move(req));
8313inline Result ClientImpl::Delete(
const std::string &path,
const std::string &body,
const std::string &content_type) {
8314 return Delete(path, Headers(), body.data(), body.size(), content_type);
8317inline Result ClientImpl::Delete(
const std::string &path,
const std::string &body,
const std::string &content_type,
8318 Progress progress) {
8319 return Delete(path, Headers(), body.data(), body.size(), content_type, progress);
8322inline Result ClientImpl::Delete(
const std::string &path,
const Headers &headers,
const std::string &body,
8323 const std::string &content_type) {
8324 return Delete(path, headers, body.data(), body.size(), content_type);
8327inline Result ClientImpl::Delete(
const std::string &path,
const Headers &headers,
const std::string &body,
8328 const std::string &content_type, Progress progress) {
8329 return Delete(path, headers, body.data(), body.size(), content_type, progress);
8332inline Result ClientImpl::Options(
const std::string &path) {
return Options(path, Headers()); }
8334inline Result ClientImpl::Options(
const std::string &path,
const Headers &headers) {
8336 req.method =
"OPTIONS";
8337 req.headers = headers;
8340 return send_(std::move(req));
8343inline void ClientImpl::stop() {
8344 std::lock_guard<std::mutex> guard(socket_mutex_);
8351 if (socket_requests_in_flight_ > 0) {
8352 shutdown_socket(socket_);
8356 socket_should_be_closed_when_request_is_done_ =
true;
8361 shutdown_ssl(socket_,
true);
8362 shutdown_socket(socket_);
8363 close_socket(socket_);
8366inline std::string ClientImpl::host()
const {
return host_; }
8368inline int ClientImpl::port()
const {
return port_; }
8370inline size_t ClientImpl::is_socket_open()
const {
8371 std::lock_guard<std::mutex> guard(socket_mutex_);
8372 return socket_.is_open();
8375inline socket_t ClientImpl::socket()
const {
return socket_.sock; }
8377inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
8378 connection_timeout_sec_ = sec;
8379 connection_timeout_usec_ = usec;
8382inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
8383 read_timeout_sec_ = sec;
8384 read_timeout_usec_ = usec;
8387inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
8388 write_timeout_sec_ = sec;
8389 write_timeout_usec_ = usec;
8392inline void ClientImpl::set_basic_auth(
const std::string &username,
const std::string &password) {
8393 basic_auth_username_ = username;
8394 basic_auth_password_ = password;
8397inline void ClientImpl::set_bearer_token_auth(
const std::string &token) { bearer_token_auth_token_ = token; }
8399#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
8400inline void ClientImpl::set_digest_auth(
const std::string &username,
const std::string &password) {
8401 digest_auth_username_ = username;
8402 digest_auth_password_ = password;
8406inline void ClientImpl::set_keep_alive(
bool on) { keep_alive_ = on; }
8408inline void ClientImpl::set_follow_location(
bool on) { follow_location_ = on; }
8410inline void ClientImpl::set_url_encode(
bool on) { url_encode_ = on; }
8412inline void ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
8413 addr_map_ = std::move(addr_map);
8416inline void ClientImpl::set_default_headers(Headers headers) { default_headers_ = std::move(headers); }
8418inline void ClientImpl::set_header_writer(std::function<
ssize_t(Stream &, Headers &)>
const &writer) {
8419 header_writer_ = writer;
8422inline void ClientImpl::set_address_family(
int family) { address_family_ = family; }
8424inline void ClientImpl::set_tcp_nodelay(
bool on) { tcp_nodelay_ = on; }
8426inline void ClientImpl::set_ipv6_v6only(
bool on) { ipv6_v6only_ = on; }
8428inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
8429 socket_options_ = std::move(socket_options);
8432inline void ClientImpl::set_compress(
bool on) { compress_ = on; }
8434inline void ClientImpl::set_decompress(
bool on) { decompress_ = on; }
8436inline void ClientImpl::set_interface(
const std::string &intf) { interface_ = intf; }
8438inline void ClientImpl::set_proxy(
const std::string &host,
int port) {
8443inline void ClientImpl::set_proxy_basic_auth(
const std::string &username,
const std::string &password) {
8444 proxy_basic_auth_username_ = username;
8445 proxy_basic_auth_password_ = password;
8448inline void ClientImpl::set_proxy_bearer_token_auth(
const std::string &token) {
8449 proxy_bearer_token_auth_token_ = token;
8452#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
8453inline void ClientImpl::set_proxy_digest_auth(
const std::string &username,
const std::string &password) {
8454 proxy_digest_auth_username_ = username;
8455 proxy_digest_auth_password_ = password;
8458inline void ClientImpl::set_ca_cert_path(
const std::string &ca_cert_file_path,
const std::string &ca_cert_dir_path) {
8459 ca_cert_file_path_ = ca_cert_file_path;
8460 ca_cert_dir_path_ = ca_cert_dir_path;
8463inline void ClientImpl::set_ca_cert_store(X509_STORE *ca_cert_store) {
8464 if (ca_cert_store && ca_cert_store != ca_cert_store_) {
8465 ca_cert_store_ = ca_cert_store;
8469inline X509_STORE *ClientImpl::create_ca_cert_store(
const char *ca_cert, std::size_t size)
const {
8470 auto mem = BIO_new_mem_buf(ca_cert,
static_cast<int>(size));
8471 auto se = detail::scope_exit([&] { BIO_free_all(mem); });
8476 auto inf = PEM_X509_INFO_read_bio(mem,
nullptr,
nullptr,
nullptr);
8481 auto cts = X509_STORE_new();
8483 for (
auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
8484 auto itmp = sk_X509_INFO_value(inf, i);
8490 X509_STORE_add_cert(cts, itmp->x509);
8493 X509_STORE_add_crl(cts, itmp->crl);
8498 sk_X509_INFO_pop_free(inf, X509_INFO_free);
8502inline void ClientImpl::enable_server_certificate_verification(
bool enabled) {
8503 server_certificate_verification_ = enabled;
8506inline void ClientImpl::enable_server_hostname_verification(
bool enabled) { server_hostname_verification_ = enabled; }
8508inline void ClientImpl::set_server_certificate_verifier(std::function<
bool(SSL *ssl)> verifier) {
8509 server_certificate_verifier_ = verifier;
8513inline void ClientImpl::set_logger(Logger logger) { logger_ = std::move(logger); }
8518#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
8521template<
typename U,
typename V>
8522inline SSL *ssl_new(
socket_t sock, SSL_CTX *ctx, std::mutex &ctx_mutex, U SSL_connect_or_accept, V
setup) {
8525 std::lock_guard<std::mutex> guard(ctx_mutex);
8530 set_nonblocking(sock,
true);
8531 auto bio = BIO_new_socket(
static_cast<int>(sock), BIO_NOCLOSE);
8532 BIO_set_nbio(bio, 1);
8533 SSL_set_bio(ssl, bio, bio);
8535 if (!
setup(ssl) || SSL_connect_or_accept(ssl) != 1) {
8538 std::lock_guard<std::mutex> guard(ctx_mutex);
8541 set_nonblocking(sock,
false);
8544 BIO_set_nbio(bio, 0);
8545 set_nonblocking(sock,
false);
8551inline void ssl_delete(std::mutex &ctx_mutex, SSL *ssl,
socket_t sock,
bool shutdown_gracefully) {
8556 if (shutdown_gracefully) {
8563 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,
reinterpret_cast<const void *
>(&tv),
sizeof(tv));
8565 auto ret = SSL_shutdown(ssl);
8567 std::this_thread::sleep_for(std::chrono::milliseconds{100});
8568 ret = SSL_shutdown(ssl);
8573 std::lock_guard<std::mutex> guard(ctx_mutex);
8578bool ssl_connect_or_accept_nonblocking(
socket_t sock, SSL *ssl, U ssl_connect_or_accept, time_t timeout_sec,
8579 time_t timeout_usec) {
8581 while ((res = ssl_connect_or_accept(ssl)) != 1) {
8582 auto err = SSL_get_error(ssl, res);
8584 case SSL_ERROR_WANT_READ:
8585 if (select_read(sock, timeout_sec, timeout_usec) > 0) {
8589 case SSL_ERROR_WANT_WRITE:
8590 if (select_write(sock, timeout_sec, timeout_usec) > 0) {
8603inline bool process_server_socket_ssl(
const std::atomic<socket_t> &svr_sock, SSL *ssl,
socket_t sock,
8604 size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
8605 time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
8606 time_t write_timeout_usec, T callback) {
8607 return process_server_socket_core(svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
8608 [&](
bool close_connection,
bool &connection_closed) {
8609 SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
8610 write_timeout_sec, write_timeout_usec);
8611 return callback(strm, close_connection, connection_closed);
8616inline bool process_client_socket_ssl(SSL *ssl,
socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
8617 time_t write_timeout_sec, time_t write_timeout_usec, T callback) {
8618 SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec, write_timeout_sec, write_timeout_usec);
8619 return callback(strm);
8624 SSLInit() { OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL); }
8628inline SSLSocketStream::SSLSocketStream(
socket_t sock, SSL *ssl, time_t read_timeout_sec, time_t read_timeout_usec,
8629 time_t write_timeout_sec, time_t write_timeout_usec)
8632 read_timeout_sec_(read_timeout_sec),
8633 read_timeout_usec_(read_timeout_usec),
8634 write_timeout_sec_(write_timeout_sec),
8635 write_timeout_usec_(write_timeout_usec) {
8636 SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
8639inline SSLSocketStream::~SSLSocketStream() =
default;
8641inline bool SSLSocketStream::is_readable()
const {
8642 return detail::select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
8645inline bool SSLSocketStream::is_writable()
const {
8646 return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 && is_socket_alive(sock_);
8649inline ssize_t SSLSocketStream::read(
char *ptr,
size_t size) {
8650 if (SSL_pending(ssl_) > 0) {
8651 return SSL_read(ssl_, ptr,
static_cast<int>(size));
8652 }
else if (is_readable()) {
8653 auto ret = SSL_read(ssl_, ptr,
static_cast<int>(size));
8655 auto err = SSL_get_error(ssl_,
ret);
8659 (err == SSL_ERROR_WANT_READ || (err == SSL_ERROR_SYSCALL && WSAGetLastError() == WSAETIMEDOUT))) {
8661 while (--n >= 0 && err == SSL_ERROR_WANT_READ) {
8663 if (SSL_pending(ssl_) > 0) {
8664 return SSL_read(ssl_, ptr,
static_cast<int>(size));
8665 }
else if (is_readable()) {
8666 std::this_thread::sleep_for(std::chrono::microseconds{10});
8667 ret = SSL_read(ssl_, ptr,
static_cast<int>(size));
8671 err = SSL_get_error(ssl_,
ret);
8682inline ssize_t SSLSocketStream::write(
const char *ptr,
size_t size) {
8683 if (is_writable()) {
8684 auto handle_size =
static_cast<int>(std::min<size_t>(size, (std::numeric_limits<int>::max)()));
8686 auto ret = SSL_write(ssl_, ptr,
static_cast<int>(handle_size));
8688 auto err = SSL_get_error(ssl_,
ret);
8692 (err == SSL_ERROR_WANT_WRITE || (err == SSL_ERROR_SYSCALL && WSAGetLastError() == WSAETIMEDOUT))) {
8694 while (--n >= 0 && err == SSL_ERROR_WANT_WRITE) {
8696 if (is_writable()) {
8697 std::this_thread::sleep_for(std::chrono::microseconds{10});
8698 ret = SSL_write(ssl_, ptr,
static_cast<int>(handle_size));
8702 err = SSL_get_error(ssl_,
ret);
8713inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
int &port)
const {
8714 detail::get_remote_ip_and_port(sock_, ip, port);
8717inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
int &port)
const {
8718 detail::get_local_ip_and_port(sock_, ip, port);
8721inline socket_t SSLSocketStream::socket()
const {
return sock_; }
8723static SSLInit sslinit_;
8728inline SSLServer::SSLServer(
const char *cert_path,
const char *private_key_path,
const char *client_ca_cert_file_path,
8729 const char *client_ca_cert_dir_path,
const char *private_key_password) {
8730 ctx_ = SSL_CTX_new(TLS_server_method());
8733 SSL_CTX_set_options(ctx_, SSL_OP_NO_COMPRESSION | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
8735 SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
8737 if (private_key_password !=
nullptr && (private_key_password[0] !=
'\0')) {
8738 SSL_CTX_set_default_passwd_cb_userdata(ctx_,
reinterpret_cast<void *
>(
const_cast<char *
>(private_key_password)));
8741 if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 ||
8742 SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) != 1 ||
8743 SSL_CTX_check_private_key(ctx_) != 1) {
8746 }
else if (client_ca_cert_file_path || client_ca_cert_dir_path) {
8747 SSL_CTX_load_verify_locations(ctx_, client_ca_cert_file_path, client_ca_cert_dir_path);
8749 SSL_CTX_set_verify(ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
nullptr);
8754inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key, X509_STORE *client_ca_cert_store) {
8755 ctx_ = SSL_CTX_new(TLS_server_method());
8758 SSL_CTX_set_options(ctx_, SSL_OP_NO_COMPRESSION | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
8760 SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
8762 if (SSL_CTX_use_certificate(ctx_, cert) != 1 || SSL_CTX_use_PrivateKey(ctx_, private_key) != 1) {
8765 }
else if (client_ca_cert_store) {
8766 SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
8768 SSL_CTX_set_verify(ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
nullptr);
8773inline SSLServer::SSLServer(
const std::function<
bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback) {
8774 ctx_ = SSL_CTX_new(TLS_method());
8776 if (!setup_ssl_ctx_callback(*ctx_)) {
8783inline SSLServer::~SSLServer() {
8789inline bool SSLServer::is_valid()
const {
return ctx_; }
8791inline SSL_CTX *SSLServer::ssl_context()
const {
return ctx_; }
8793inline void SSLServer::update_certs(X509 *cert, EVP_PKEY *private_key, X509_STORE *client_ca_cert_store) {
8794 std::lock_guard<std::mutex> guard(ctx_mutex_);
8796 SSL_CTX_use_certificate(ctx_, cert);
8797 SSL_CTX_use_PrivateKey(ctx_, private_key);
8799 if (client_ca_cert_store !=
nullptr) {
8800 SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
8804inline bool SSLServer::process_and_close_socket(
socket_t sock) {
8805 auto ssl = detail::ssl_new(
8806 sock, ctx_, ctx_mutex_,
8808 return detail::ssl_connect_or_accept_nonblocking(sock, ssl2, SSL_accept, read_timeout_sec_, read_timeout_usec_);
8810 [](SSL * ) {
return true; });
8814 std::string remote_addr;
8815 int remote_port = 0;
8816 detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
8818 std::string local_addr;
8820 detail::get_local_ip_and_port(sock, local_addr, local_port);
8822 ret = detail::process_server_socket_ssl(
8823 svr_sock_, ssl, sock, keep_alive_max_count_, keep_alive_timeout_sec_, read_timeout_sec_, read_timeout_usec_,
8824 write_timeout_sec_, write_timeout_usec_, [&](Stream &strm,
bool close_connection,
bool &connection_closed) {
8825 return process_request(strm, remote_addr, remote_port, local_addr, local_port, close_connection,
8826 connection_closed, [&](Request &req) { req.ssl = ssl; });
8831 const bool shutdown_gracefully =
ret;
8832 detail::ssl_delete(ctx_mutex_, ssl, sock, shutdown_gracefully);
8835 detail::shutdown_socket(sock);
8836 detail::close_socket(sock);
8841inline SSLClient::SSLClient(
const std::string &host) : SSLClient(
host, 443,
std::string(),
std::string()) {}
8843inline SSLClient::SSLClient(
const std::string &host,
int port) : SSLClient(
host, port,
std::string(),
std::string()) {}
8845inline SSLClient::SSLClient(
const std::string &host,
int port,
const std::string &client_cert_path,
8846 const std::string &client_key_path,
const std::string &private_key_password)
8847 : ClientImpl(
host, port, client_cert_path, client_key_path) {
8848 ctx_ = SSL_CTX_new(TLS_client_method());
8850 SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
8852 detail::split(&host_[0], &host_[host_.size()],
'.',
8853 [&](
const char *b,
const char *e) { host_components_.emplace_back(b, e); });
8855 if (!client_cert_path.empty() && !client_key_path.empty()) {
8856 if (!private_key_password.empty()) {
8857 SSL_CTX_set_default_passwd_cb_userdata(
8858 ctx_,
reinterpret_cast<void *
>(
const_cast<char *
>(private_key_password.c_str())));
8861 if (SSL_CTX_use_certificate_file(ctx_, client_cert_path.c_str(), SSL_FILETYPE_PEM) != 1 ||
8862 SSL_CTX_use_PrivateKey_file(ctx_, client_key_path.c_str(), SSL_FILETYPE_PEM) != 1) {
8869inline SSLClient::SSLClient(
const std::string &host,
int port, X509 *client_cert, EVP_PKEY *client_key,
8870 const std::string &private_key_password)
8871 : ClientImpl(
host, port) {
8872 ctx_ = SSL_CTX_new(TLS_client_method());
8874 detail::split(&host_[0], &host_[host_.size()],
'.',
8875 [&](
const char *b,
const char *e) { host_components_.emplace_back(b, e); });
8877 if (client_cert !=
nullptr && client_key !=
nullptr) {
8878 if (!private_key_password.empty()) {
8879 SSL_CTX_set_default_passwd_cb_userdata(
8880 ctx_,
reinterpret_cast<void *
>(
const_cast<char *
>(private_key_password.c_str())));
8883 if (SSL_CTX_use_certificate(ctx_, client_cert) != 1 || SSL_CTX_use_PrivateKey(ctx_, client_key) != 1) {
8890inline SSLClient::~SSLClient() {
8897 shutdown_ssl_impl(socket_,
true);
8900inline bool SSLClient::is_valid()
const {
return ctx_; }
8902inline void SSLClient::set_ca_cert_store(X509_STORE *ca_cert_store) {
8903 if (ca_cert_store) {
8905 if (SSL_CTX_get_cert_store(ctx_) != ca_cert_store) {
8907 SSL_CTX_set_cert_store(ctx_, ca_cert_store);
8910 X509_STORE_free(ca_cert_store);
8915inline void SSLClient::load_ca_cert_store(
const char *ca_cert, std::size_t size) {
8916 set_ca_cert_store(ClientImpl::create_ca_cert_store(ca_cert, size));
8919inline long SSLClient::get_openssl_verify_result()
const {
return verify_result_; }
8921inline SSL_CTX *SSLClient::ssl_context()
const {
return ctx_; }
8923inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
8924 return is_valid() && ClientImpl::create_and_connect_socket(socket, error);
8928inline bool SSLClient::connect_with_proxy(Socket &socket, Response &res,
bool &success, Error &error) {
8931 if (!detail::process_client_socket(
socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
8932 write_timeout_usec_, [&](Stream &strm) {
8934 req2.method =
"CONNECT";
8935 req2.path = host_and_port_;
8936 return process_request(strm, req2, proxy_res, false, error);
8940 shutdown_ssl(socket,
true);
8941 shutdown_socket(socket);
8942 close_socket(socket);
8947 if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
8948 if (!proxy_digest_auth_username_.empty() && !proxy_digest_auth_password_.empty()) {
8949 std::map<std::string, std::string> auth;
8950 if (detail::parse_www_authenticate(proxy_res, auth,
true)) {
8951 proxy_res = Response();
8952 if (!detail::process_client_socket(
socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
8953 write_timeout_usec_, [&](Stream &strm) {
8955 req3.method =
"CONNECT";
8956 req3.path = host_and_port_;
8957 req3.headers.insert(detail::make_digest_authentication_header(
8958 req3, auth, 1, detail::random_string(10), proxy_digest_auth_username_,
8959 proxy_digest_auth_password_, true));
8960 return process_request(strm, req3, proxy_res, false, error);
8964 shutdown_ssl(socket,
true);
8965 shutdown_socket(socket);
8966 close_socket(socket);
8977 if (proxy_res.status != StatusCode::OK_200) {
8978 error = Error::ProxyConnection;
8979 res = std::move(proxy_res);
8982 shutdown_ssl(socket,
true);
8983 shutdown_socket(socket);
8984 close_socket(socket);
8991inline bool SSLClient::load_certs() {
8994 std::call_once(initialize_cert_, [&]() {
8995 std::lock_guard<std::mutex> guard(ctx_mutex_);
8996 if (!ca_cert_file_path_.empty()) {
8997 if (!SSL_CTX_load_verify_locations(ctx_, ca_cert_file_path_.c_str(),
nullptr)) {
9000 }
else if (!ca_cert_dir_path_.empty()) {
9001 if (!SSL_CTX_load_verify_locations(ctx_,
nullptr, ca_cert_dir_path_.c_str())) {
9005 auto loaded =
false;
9007 loaded = detail::load_system_certs_on_windows(SSL_CTX_get_cert_store(ctx_));
9008#elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && defined(__APPLE__)
9010 loaded = detail::load_system_certs_on_macos(SSL_CTX_get_cert_store(ctx_));
9014 SSL_CTX_set_default_verify_paths(ctx_);
9022inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
9023 auto ssl = detail::ssl_new(
9024 socket.sock, ctx_, ctx_mutex_,
9026 if (server_certificate_verification_) {
9027 if (!load_certs()) {
9028 error = Error::SSLLoadingCerts;
9031 SSL_set_verify(ssl2, SSL_VERIFY_NONE, nullptr);
9034 if (!detail::ssl_connect_or_accept_nonblocking(
socket.sock, ssl2, SSL_connect, connection_timeout_sec_,
9035 connection_timeout_usec_)) {
9036 error = Error::SSLConnection;
9040 if (server_certificate_verification_) {
9041 if (server_certificate_verifier_) {
9042 if (!server_certificate_verifier_(ssl2)) {
9043 error = Error::SSLServerVerification;
9047 verify_result_ = SSL_get_verify_result(ssl2);
9049 if (verify_result_ != X509_V_OK) {
9050 error = Error::SSLServerVerification;
9054 auto server_cert = SSL_get1_peer_certificate(ssl2);
9055 auto se = detail::scope_exit([&] { X509_free(server_cert); });
9057 if (server_cert ==
nullptr) {
9058 error = Error::SSLServerVerification;
9062 if (server_hostname_verification_) {
9063 if (!verify_host(server_cert)) {
9064 error = Error::SSLServerHostnameVerification;
9074#if defined(OPENSSL_IS_BORINGSSL)
9075 SSL_set_tlsext_host_name(ssl2, host_.c_str());
9079 SSL_ctrl(ssl2, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
9080 static_cast<void *
>(
const_cast<char *
>(host_.c_str())));
9090 shutdown_socket(socket);
9091 close_socket(socket);
9095inline void SSLClient::shutdown_ssl(Socket &socket,
bool shutdown_gracefully) {
9096 shutdown_ssl_impl(socket, shutdown_gracefully);
9099inline void SSLClient::shutdown_ssl_impl(Socket &socket,
bool shutdown_gracefully) {
9100 if (
socket.sock == INVALID_SOCKET) {
9101 assert(
socket.ssl ==
nullptr);
9105 detail::ssl_delete(ctx_mutex_,
socket.ssl,
socket.sock, shutdown_gracefully);
9108 assert(
socket.ssl ==
nullptr);
9111inline bool SSLClient::process_socket(
const Socket &socket, std::function<
bool(Stream &strm)> callback) {
9113 return detail::process_client_socket_ssl(
socket.ssl,
socket.sock, read_timeout_sec_, read_timeout_usec_,
9114 write_timeout_sec_, write_timeout_usec_, std::move(callback));
9117inline bool SSLClient::is_ssl()
const {
return true; }
9119inline bool SSLClient::verify_host(X509 *server_cert)
const {
9141 return verify_host_with_subject_alt_name(server_cert) || verify_host_with_common_name(server_cert);
9144inline bool SSLClient::verify_host_with_subject_alt_name(X509 *server_cert)
const {
9147 auto type = GEN_DNS;
9149 struct in6_addr addr6{};
9150 struct in_addr addr{};
9154 if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
9156 addr_len =
sizeof(
struct in6_addr);
9157 }
else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
9163 auto alt_names =
static_cast<const struct stack_st_GENERAL_NAME *
>(
9164 X509_get_ext_d2i(server_cert, NID_subject_alt_name,
nullptr,
nullptr));
9167 auto dsn_matched =
false;
9168 auto ip_matched =
false;
9170 auto count = sk_GENERAL_NAME_num(alt_names);
9172 for (
decltype(
count) i = 0; i <
count && !dsn_matched; i++) {
9173 auto val = sk_GENERAL_NAME_value(alt_names, i);
9175 auto name =
reinterpret_cast<const char *
>(ASN1_STRING_get0_data(
val->d.ia5));
9176 auto name_len =
static_cast<size_t>(ASN1_STRING_length(
val->d.ia5));
9180 dsn_matched = check_host_name(name, name_len);
9192 if (dsn_matched || ip_matched) {
9197 GENERAL_NAMES_free(
const_cast<STACK_OF(GENERAL_NAME) *
>(
reinterpret_cast<const STACK_OF(GENERAL_NAME) *
>(alt_names)));
9201inline bool SSLClient::verify_host_with_common_name(X509 *server_cert)
const {
9202 const auto subject_name = X509_get_subject_name(server_cert);
9204 if (subject_name !=
nullptr) {
9206 auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName, name,
sizeof(name));
9208 if (name_len != -1) {
9209 return check_host_name(name,
static_cast<size_t>(name_len));
9216inline bool SSLClient::check_host_name(
const char *pattern,
size_t pattern_len)
const {
9217 if (host_.size() == pattern_len && host_ == pattern) {
9223 std::vector<std::string> pattern_components;
9224 detail::split(&pattern[0], &pattern[pattern_len],
'.',
9225 [&](
const char *b,
const char *e) { pattern_components.emplace_back(b, e); });
9227 if (host_components_.size() != pattern_components.size()) {
9231 auto itr = pattern_components.begin();
9232 for (
const auto &
h : host_components_) {
9234 if (p !=
h && p !=
"*") {
9235 auto partial_match = (p.size() > 0 && p[p.size() - 1] ==
'*' && !p.compare(0, p.size() - 1,
h));
9236 if (!partial_match) {
9248inline Client::Client(
const std::string &scheme_host_port) : Client(scheme_host_port,
std::string(),
std::string()) {}
9250inline Client::Client(
const std::string &scheme_host_port,
const std::string &client_cert_path,
9251 const std::string &client_key_path) {
9252 const static std::regex re(R
"((?:([a-z]+):\/\/)?(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)");
9255 if (std::regex_match(scheme_host_port,
m, re)) {
9256 auto scheme =
m[1].str();
9258#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
9259 if (!scheme.empty() && (scheme !=
"http" && scheme !=
"https")) {
9261 if (!scheme.empty() && scheme !=
"http") {
9263#ifndef CPPHTTPLIB_NO_EXCEPTIONS
9264 std::string msg =
"'" + scheme +
"' scheme is not supported.";
9265 throw std::invalid_argument(msg);
9270 auto is_ssl = scheme ==
"https";
9272 auto host =
m[2].str();
9277 auto port_str =
m[4].str();
9278 auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80);
9281#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
9282 cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path, client_key_path);
9286 cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path, client_key_path);
9291 cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80, client_cert_path, client_key_path);
9295inline Client::Client(
const std::string &host,
int port) : cli_(detail::make_unique<ClientImpl>(
host, port)) {}
9297inline Client::Client(
const std::string &host,
int port,
const std::string &client_cert_path,
9298 const std::string &client_key_path)
9299 : cli_(detail::make_unique<ClientImpl>(
host, port, client_cert_path, client_key_path)) {}
9301inline Client::~Client() =
default;
9303inline bool Client::is_valid()
const {
return cli_ !=
nullptr && cli_->is_valid(); }
9305inline Result Client::Get(
const std::string &path) {
return cli_->Get(path); }
9306inline Result Client::Get(
const std::string &path,
const Headers &headers) {
return cli_->Get(path, headers); }
9307inline Result Client::Get(
const std::string &path, Progress progress) {
return cli_->Get(path, std::move(progress)); }
9308inline Result Client::Get(
const std::string &path,
const Headers &headers, Progress progress) {
9309 return cli_->Get(path, headers, std::move(progress));
9311inline Result Client::Get(
const std::string &path, ContentReceiver content_receiver) {
9312 return cli_->Get(path, std::move(content_receiver));
9314inline Result Client::Get(
const std::string &path,
const Headers &headers, ContentReceiver content_receiver) {
9315 return cli_->Get(path, headers, std::move(content_receiver));
9317inline Result Client::Get(
const std::string &path, ContentReceiver content_receiver, Progress progress) {
9318 return cli_->Get(path, std::move(content_receiver), std::move(progress));
9320inline Result Client::Get(
const std::string &path,
const Headers &headers, ContentReceiver content_receiver,
9321 Progress progress) {
9322 return cli_->Get(path, headers, std::move(content_receiver), std::move(progress));
9324inline Result Client::Get(
const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver) {
9325 return cli_->Get(path, std::move(response_handler), std::move(content_receiver));
9327inline Result Client::Get(
const std::string &path,
const Headers &headers, ResponseHandler response_handler,
9328 ContentReceiver content_receiver) {
9329 return cli_->Get(path, headers, std::move(response_handler), std::move(content_receiver));
9331inline Result Client::Get(
const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver,
9332 Progress progress) {
9333 return cli_->Get(path, std::move(response_handler), std::move(content_receiver), std::move(progress));
9335inline Result Client::Get(
const std::string &path,
const Headers &headers, ResponseHandler response_handler,
9336 ContentReceiver content_receiver, Progress progress) {
9337 return cli_->Get(path, headers, std::move(response_handler), std::move(content_receiver), std::move(progress));
9339inline Result Client::Get(
const std::string &path,
const Params ¶ms,
const Headers &headers, Progress progress) {
9340 return cli_->Get(path, params, headers, std::move(progress));
9342inline Result Client::Get(
const std::string &path,
const Params ¶ms,
const Headers &headers,
9343 ContentReceiver content_receiver, Progress progress) {
9344 return cli_->Get(path, params, headers, std::move(content_receiver), std::move(progress));
9346inline Result Client::Get(
const std::string &path,
const Params ¶ms,
const Headers &headers,
9347 ResponseHandler response_handler, ContentReceiver content_receiver, Progress progress) {
9348 return cli_->Get(path, params, headers, std::move(response_handler), std::move(content_receiver),
9349 std::move(progress));
9352inline Result Client::Head(
const std::string &path) {
return cli_->Head(path); }
9353inline Result Client::Head(
const std::string &path,
const Headers &headers) {
return cli_->Head(path, headers); }
9355inline Result Client::Post(
const std::string &path) {
return cli_->Post(path); }
9356inline Result Client::Post(
const std::string &path,
const Headers &headers) {
return cli_->Post(path, headers); }
9357inline Result Client::Post(
const std::string &path,
const char *body,
size_t content_length,
9358 const std::string &content_type) {
9359 return cli_->Post(path, body, content_length, content_type);
9361inline Result Client::Post(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
9362 const std::string &content_type) {
9363 return cli_->Post(path, headers, body, content_length, content_type);
9365inline Result Client::Post(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
9366 const std::string &content_type, Progress progress) {
9367 return cli_->Post(path, headers, body, content_length, content_type, progress);
9369inline Result Client::Post(
const std::string &path,
const std::string &body,
const std::string &content_type) {
9370 return cli_->Post(path, body, content_type);
9372inline Result Client::Post(
const std::string &path,
const std::string &body,
const std::string &content_type,
9373 Progress progress) {
9374 return cli_->Post(path, body, content_type, progress);
9376inline Result Client::Post(
const std::string &path,
const Headers &headers,
const std::string &body,
9377 const std::string &content_type) {
9378 return cli_->Post(path, headers, body, content_type);
9380inline Result Client::Post(
const std::string &path,
const Headers &headers,
const std::string &body,
9381 const std::string &content_type, Progress progress) {
9382 return cli_->Post(path, headers, body, content_type, progress);
9384inline Result Client::Post(
const std::string &path,
size_t content_length, ContentProvider content_provider,
9385 const std::string &content_type) {
9386 return cli_->Post(path, content_length, std::move(content_provider), content_type);
9388inline Result Client::Post(
const std::string &path, ContentProviderWithoutLength content_provider,
9389 const std::string &content_type) {
9390 return cli_->Post(path, std::move(content_provider), content_type);
9392inline Result Client::Post(
const std::string &path,
const Headers &headers,
size_t content_length,
9393 ContentProvider content_provider,
const std::string &content_type) {
9394 return cli_->Post(path, headers, content_length, std::move(content_provider), content_type);
9396inline Result Client::Post(
const std::string &path,
const Headers &headers,
9397 ContentProviderWithoutLength content_provider,
const std::string &content_type) {
9398 return cli_->Post(path, headers, std::move(content_provider), content_type);
9400inline Result Client::Post(
const std::string &path,
const Params ¶ms) {
return cli_->Post(path, params); }
9401inline Result Client::Post(
const std::string &path,
const Headers &headers,
const Params ¶ms) {
9402 return cli_->Post(path, headers, params);
9404inline Result Client::Post(
const std::string &path,
const Headers &headers,
const Params ¶ms, Progress progress) {
9405 return cli_->Post(path, headers, params, progress);
9407inline Result Client::Post(
const std::string &path,
const MultipartFormDataItems &items) {
9408 return cli_->Post(path, items);
9410inline Result Client::Post(
const std::string &path,
const Headers &headers,
const MultipartFormDataItems &items) {
9411 return cli_->Post(path, headers, items);
9413inline Result Client::Post(
const std::string &path,
const Headers &headers,
const MultipartFormDataItems &items,
9414 const std::string &boundary) {
9415 return cli_->Post(path, headers, items, boundary);
9417inline Result Client::Post(
const std::string &path,
const Headers &headers,
const MultipartFormDataItems &items,
9418 const MultipartFormDataProviderItems &provider_items) {
9419 return cli_->Post(path, headers, items, provider_items);
9421inline Result Client::Put(
const std::string &path) {
return cli_->Put(path); }
9422inline Result Client::Put(
const std::string &path,
const char *body,
size_t content_length,
9423 const std::string &content_type) {
9424 return cli_->Put(path, body, content_length, content_type);
9426inline Result Client::Put(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
9427 const std::string &content_type) {
9428 return cli_->Put(path, headers, body, content_length, content_type);
9430inline Result Client::Put(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
9431 const std::string &content_type, Progress progress) {
9432 return cli_->Put(path, headers, body, content_length, content_type, progress);
9434inline Result Client::Put(
const std::string &path,
const std::string &body,
const std::string &content_type) {
9435 return cli_->Put(path, body, content_type);
9437inline Result Client::Put(
const std::string &path,
const std::string &body,
const std::string &content_type,
9438 Progress progress) {
9439 return cli_->Put(path, body, content_type, progress);
9441inline Result Client::Put(
const std::string &path,
const Headers &headers,
const std::string &body,
9442 const std::string &content_type) {
9443 return cli_->Put(path, headers, body, content_type);
9445inline Result Client::Put(
const std::string &path,
const Headers &headers,
const std::string &body,
9446 const std::string &content_type, Progress progress) {
9447 return cli_->Put(path, headers, body, content_type, progress);
9449inline Result Client::Put(
const std::string &path,
size_t content_length, ContentProvider content_provider,
9450 const std::string &content_type) {
9451 return cli_->Put(path, content_length, std::move(content_provider), content_type);
9453inline Result Client::Put(
const std::string &path, ContentProviderWithoutLength content_provider,
9454 const std::string &content_type) {
9455 return cli_->Put(path, std::move(content_provider), content_type);
9457inline Result Client::Put(
const std::string &path,
const Headers &headers,
size_t content_length,
9458 ContentProvider content_provider,
const std::string &content_type) {
9459 return cli_->Put(path, headers, content_length, std::move(content_provider), content_type);
9461inline Result Client::Put(
const std::string &path,
const Headers &headers,
9462 ContentProviderWithoutLength content_provider,
const std::string &content_type) {
9463 return cli_->Put(path, headers, std::move(content_provider), content_type);
9465inline Result Client::Put(
const std::string &path,
const Params ¶ms) {
return cli_->Put(path, params); }
9466inline Result Client::Put(
const std::string &path,
const Headers &headers,
const Params ¶ms) {
9467 return cli_->Put(path, headers, params);
9469inline Result Client::Put(
const std::string &path,
const Headers &headers,
const Params ¶ms, Progress progress) {
9470 return cli_->Put(path, headers, params, progress);
9472inline Result Client::Put(
const std::string &path,
const MultipartFormDataItems &items) {
9473 return cli_->Put(path, items);
9475inline Result Client::Put(
const std::string &path,
const Headers &headers,
const MultipartFormDataItems &items) {
9476 return cli_->Put(path, headers, items);
9478inline Result Client::Put(
const std::string &path,
const Headers &headers,
const MultipartFormDataItems &items,
9479 const std::string &boundary) {
9480 return cli_->Put(path, headers, items, boundary);
9482inline Result Client::Put(
const std::string &path,
const Headers &headers,
const MultipartFormDataItems &items,
9483 const MultipartFormDataProviderItems &provider_items) {
9484 return cli_->Put(path, headers, items, provider_items);
9486inline Result Client::Patch(
const std::string &path) {
return cli_->Patch(path); }
9487inline Result Client::Patch(
const std::string &path,
const char *body,
size_t content_length,
9488 const std::string &content_type) {
9489 return cli_->Patch(path, body, content_length, content_type);
9491inline Result Client::Patch(
const std::string &path,
const char *body,
size_t content_length,
9492 const std::string &content_type, Progress progress) {
9493 return cli_->Patch(path, body, content_length, content_type, progress);
9495inline Result Client::Patch(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
9496 const std::string &content_type) {
9497 return cli_->Patch(path, headers, body, content_length, content_type);
9499inline Result Client::Patch(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
9500 const std::string &content_type, Progress progress) {
9501 return cli_->Patch(path, headers, body, content_length, content_type, progress);
9503inline Result Client::Patch(
const std::string &path,
const std::string &body,
const std::string &content_type) {
9504 return cli_->Patch(path, body, content_type);
9506inline Result Client::Patch(
const std::string &path,
const std::string &body,
const std::string &content_type,
9507 Progress progress) {
9508 return cli_->Patch(path, body, content_type, progress);
9510inline Result Client::Patch(
const std::string &path,
const Headers &headers,
const std::string &body,
9511 const std::string &content_type) {
9512 return cli_->Patch(path, headers, body, content_type);
9514inline Result Client::Patch(
const std::string &path,
const Headers &headers,
const std::string &body,
9515 const std::string &content_type, Progress progress) {
9516 return cli_->Patch(path, headers, body, content_type, progress);
9518inline Result Client::Patch(
const std::string &path,
size_t content_length, ContentProvider content_provider,
9519 const std::string &content_type) {
9520 return cli_->Patch(path, content_length, std::move(content_provider), content_type);
9522inline Result Client::Patch(
const std::string &path, ContentProviderWithoutLength content_provider,
9523 const std::string &content_type) {
9524 return cli_->Patch(path, std::move(content_provider), content_type);
9526inline Result Client::Patch(
const std::string &path,
const Headers &headers,
size_t content_length,
9527 ContentProvider content_provider,
const std::string &content_type) {
9528 return cli_->Patch(path, headers, content_length, std::move(content_provider), content_type);
9530inline Result Client::Patch(
const std::string &path,
const Headers &headers,
9531 ContentProviderWithoutLength content_provider,
const std::string &content_type) {
9532 return cli_->Patch(path, headers, std::move(content_provider), content_type);
9534inline Result Client::Delete(
const std::string &path) {
return cli_->Delete(path); }
9535inline Result Client::Delete(
const std::string &path,
const Headers &headers) {
return cli_->Delete(path, headers); }
9536inline Result Client::Delete(
const std::string &path,
const char *body,
size_t content_length,
9537 const std::string &content_type) {
9538 return cli_->Delete(path, body, content_length, content_type);
9540inline Result Client::Delete(
const std::string &path,
const char *body,
size_t content_length,
9541 const std::string &content_type, Progress progress) {
9542 return cli_->Delete(path, body, content_length, content_type, progress);
9544inline Result Client::Delete(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
9545 const std::string &content_type) {
9546 return cli_->Delete(path, headers, body, content_length, content_type);
9548inline Result Client::Delete(
const std::string &path,
const Headers &headers,
const char *body,
size_t content_length,
9549 const std::string &content_type, Progress progress) {
9550 return cli_->Delete(path, headers, body, content_length, content_type, progress);
9552inline Result Client::Delete(
const std::string &path,
const std::string &body,
const std::string &content_type) {
9553 return cli_->Delete(path, body, content_type);
9555inline Result Client::Delete(
const std::string &path,
const std::string &body,
const std::string &content_type,
9556 Progress progress) {
9557 return cli_->Delete(path, body, content_type, progress);
9559inline Result Client::Delete(
const std::string &path,
const Headers &headers,
const std::string &body,
9560 const std::string &content_type) {
9561 return cli_->Delete(path, headers, body, content_type);
9563inline Result Client::Delete(
const std::string &path,
const Headers &headers,
const std::string &body,
9564 const std::string &content_type, Progress progress) {
9565 return cli_->Delete(path, headers, body, content_type, progress);
9567inline Result Client::Options(
const std::string &path) {
return cli_->Options(path); }
9568inline Result Client::Options(
const std::string &path,
const Headers &headers) {
return cli_->Options(path, headers); }
9570inline bool Client::send(Request &req, Response &res, Error &error) {
return cli_->send(req, res, error); }
9572inline Result Client::send(
const Request &req) {
return cli_->send(req); }
9574inline void Client::stop() { cli_->stop(); }
9576inline std::string Client::host()
const {
return cli_->host(); }
9578inline int Client::port()
const {
return cli_->port(); }
9580inline size_t Client::is_socket_open()
const {
return cli_->is_socket_open(); }
9582inline socket_t Client::socket()
const {
return cli_->socket(); }
9584inline void Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
9585 cli_->set_hostname_addr_map(std::move(addr_map));
9588inline void Client::set_default_headers(Headers headers) { cli_->set_default_headers(std::move(headers)); }
9590inline void Client::set_header_writer(std::function<
ssize_t(Stream &, Headers &)>
const &writer) {
9591 cli_->set_header_writer(writer);
9594inline void Client::set_address_family(
int family) { cli_->set_address_family(family); }
9596inline void Client::set_tcp_nodelay(
bool on) { cli_->set_tcp_nodelay(on); }
9598inline void Client::set_socket_options(SocketOptions socket_options) {
9599 cli_->set_socket_options(std::move(socket_options));
9602inline void Client::set_connection_timeout(time_t sec, time_t usec) { cli_->set_connection_timeout(sec, usec); }
9604inline void Client::set_read_timeout(time_t sec, time_t usec) { cli_->set_read_timeout(sec, usec); }
9606inline void Client::set_write_timeout(time_t sec, time_t usec) { cli_->set_write_timeout(sec, usec); }
9608inline void Client::set_basic_auth(
const std::string &username,
const std::string &password) {
9609 cli_->set_basic_auth(username, password);
9611inline void Client::set_bearer_token_auth(
const std::string &token) { cli_->set_bearer_token_auth(token); }
9612#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
9613inline void Client::set_digest_auth(
const std::string &username,
const std::string &password) {
9614 cli_->set_digest_auth(username, password);
9618inline void Client::set_keep_alive(
bool on) { cli_->set_keep_alive(on); }
9619inline void Client::set_follow_location(
bool on) { cli_->set_follow_location(on); }
9621inline void Client::set_url_encode(
bool on) { cli_->set_url_encode(on); }
9623inline void Client::set_compress(
bool on) { cli_->set_compress(on); }
9625inline void Client::set_decompress(
bool on) { cli_->set_decompress(on); }
9627inline void Client::set_interface(
const std::string &intf) { cli_->set_interface(intf); }
9629inline void Client::set_proxy(
const std::string &host,
int port) { cli_->set_proxy(host, port); }
9630inline void Client::set_proxy_basic_auth(
const std::string &username,
const std::string &password) {
9631 cli_->set_proxy_basic_auth(username, password);
9633inline void Client::set_proxy_bearer_token_auth(
const std::string &token) { cli_->set_proxy_bearer_token_auth(token); }
9634#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
9635inline void Client::set_proxy_digest_auth(
const std::string &username,
const std::string &password) {
9636 cli_->set_proxy_digest_auth(username, password);
9640#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
9641inline void Client::enable_server_certificate_verification(
bool enabled) {
9642 cli_->enable_server_certificate_verification(enabled);
9645inline void Client::enable_server_hostname_verification(
bool enabled) {
9646 cli_->enable_server_hostname_verification(enabled);
9649inline void Client::set_server_certificate_verifier(std::function<
bool(SSL *ssl)> verifier) {
9650 cli_->set_server_certificate_verifier(verifier);
9654inline void Client::set_logger(Logger logger) { cli_->set_logger(std::move(logger)); }
9656#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
9657inline void Client::set_ca_cert_path(
const std::string &ca_cert_file_path,
const std::string &ca_cert_dir_path) {
9658 cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
9661inline void Client::set_ca_cert_store(X509_STORE *ca_cert_store) {
9663 static_cast<SSLClient &
>(*cli_).set_ca_cert_store(ca_cert_store);
9665 cli_->set_ca_cert_store(ca_cert_store);
9669inline void Client::load_ca_cert_store(
const char *ca_cert, std::size_t size) {
9670 set_ca_cert_store(cli_->create_ca_cert_store(ca_cert, size));
9673inline long Client::get_openssl_verify_result()
const {
9675 return static_cast<SSLClient &
>(*cli_).get_openssl_verify_result();
9680inline SSL_CTX *Client::ssl_context()
const {
9682 return static_cast<SSLClient &
>(*cli_).ssl_context();
9692#if defined(_WIN32) && defined(CPPHTTPLIB_USE_POLL)
std::vector< uint8_t > & out
std::span< const uint8_t > data
std::unique_ptr< Socket > socket(int domain, int type, int protocol)
Create a socket of the given domain, type and protocol.
char host[MAX_ORIGIN_LENGTH+1]
if(!is_valid_sram_ptr(frame))