ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
httplib.h
Go to the documentation of this file.
1#pragma once
2
10//
11// httplib.h
12//
13// Copyright (c) 2024 Yuji Hirose. All rights reserved.
14// MIT License
15//
16
17#ifdef USE_HOST
18// Prevent this code being included in main.cpp
19#ifdef USE_HTTP_REQUEST_HOST_H
20
22
23#ifndef CPPHTTPLIB_HTTPLIB_H
24#define CPPHTTPLIB_HTTPLIB_H
25
26#define CPPHTTPLIB_VERSION "0.18.2"
27
28/*
29 * Configuration
30 */
31
32#ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
33#define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
34#endif
35
36#ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND
37#define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000
38#endif
39
40#ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
41#define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100
42#endif
43
44#ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
45#define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
46#endif
47
48#ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
49#define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
50#endif
51
52#ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND
53#define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5
54#endif
55
56#ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND
57#define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0
58#endif
59
60#ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND
61#define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5
62#endif
63
64#ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND
65#define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0
66#endif
67
68#ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND
69#define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300
70#endif
71
72#ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND
73#define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0
74#endif
75
76#ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND
77#define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5
78#endif
79
80#ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND
81#define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0
82#endif
83
84#ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
85#define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
86#endif
87
88#ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
89#ifdef _WIN32
90#define CPPHTTPLIB_IDLE_INTERVAL_USECOND 10000
91#else
92#define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
93#endif
94#endif
95
96#ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
97#define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
98#endif
99
100#ifndef CPPHTTPLIB_HEADER_MAX_LENGTH
101#define CPPHTTPLIB_HEADER_MAX_LENGTH 8192
102#endif
103
104#ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
105#define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
106#endif
107
108#ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT
109#define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024
110#endif
111
112#ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
113#define CPPHTTPLIB_PAYLOAD_MAX_LENGTH ((std::numeric_limits<size_t>::max)())
114#endif
115
116#ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH
117#define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192
118#endif
119
120#ifndef CPPHTTPLIB_RANGE_MAX_COUNT
121#define CPPHTTPLIB_RANGE_MAX_COUNT 1024
122#endif
123
124#ifndef CPPHTTPLIB_TCP_NODELAY
125#define CPPHTTPLIB_TCP_NODELAY false
126#endif
127
128#ifndef CPPHTTPLIB_IPV6_V6ONLY
129#define CPPHTTPLIB_IPV6_V6ONLY false
130#endif
131
132#ifndef CPPHTTPLIB_RECV_BUFSIZ
133#define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u)
134#endif
135
136#ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
137#define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
138#endif
139
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))
143#endif
144
145#ifndef CPPHTTPLIB_RECV_FLAGS
146#define CPPHTTPLIB_RECV_FLAGS 0
147#endif
148
149#ifndef CPPHTTPLIB_SEND_FLAGS
150#define CPPHTTPLIB_SEND_FLAGS 0
151#endif
152
153#ifndef CPPHTTPLIB_LISTEN_BACKLOG
154#define CPPHTTPLIB_LISTEN_BACKLOG 5
155#endif
156
157/*
158 * Headers
159 */
160
161#ifdef _WIN32
162#ifndef _CRT_SECURE_NO_WARNINGS
163#define _CRT_SECURE_NO_WARNINGS
164#endif //_CRT_SECURE_NO_WARNINGS
165
166#ifndef _CRT_NONSTDC_NO_DEPRECATE
167#define _CRT_NONSTDC_NO_DEPRECATE
168#endif //_CRT_NONSTDC_NO_DEPRECATE
169
170#if defined(_MSC_VER)
171#if _MSC_VER < 1900
172#error Sorry, Visual Studio versions prior to 2015 are not supported
173#endif
174
175#pragma comment(lib, "ws2_32.lib")
176
177#ifdef _WIN64
178using ssize_t = __int64;
179#else
180using ssize_t = long;
181#endif
182#endif // _MSC_VER
183
184#ifndef S_ISREG
185#define S_ISREG(m) (((m) & S_IFREG) == S_IFREG)
186#endif // S_ISREG
187
188#ifndef S_ISDIR
189#define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR)
190#endif // S_ISDIR
191
192#ifndef NOMINMAX
193#define NOMINMAX
194#endif // NOMINMAX
195
196#include <io.h>
197#include <winsock2.h>
198#include <ws2tcpip.h>
199
200#ifndef WSA_FLAG_NO_HANDLE_INHERIT
201#define WSA_FLAG_NO_HANDLE_INHERIT 0x80
202#endif
203
204using socket_t = SOCKET;
205#ifdef CPPHTTPLIB_USE_POLL
206#define poll(fds, nfds, timeout) WSAPoll(fds, nfds, timeout)
207#endif
208
209#else // not _WIN32
210
211#include <arpa/inet.h>
212#if !defined(_AIX) && !defined(__MVS__)
213#include <ifaddrs.h>
214#endif
215#ifdef __MVS__
216#include <strings.h>
217#ifndef NI_MAXHOST
218#define NI_MAXHOST 1025
219#endif
220#endif
221#include <net/if.h>
222#include <netdb.h>
223#include <netinet/in.h>
224#ifdef __linux__
225#include <resolv.h>
226#endif
227#include <netinet/tcp.h>
228#ifdef CPPHTTPLIB_USE_POLL
229#include <poll.h>
230#endif
231#include <csignal>
232#include <pthread.h>
233#include <sys/mman.h>
234#include <sys/select.h>
235#include <sys/socket.h>
236#include <sys/un.h>
237#include <unistd.h>
238
239using socket_t = int;
240#ifndef INVALID_SOCKET
241#define INVALID_SOCKET (-1)
242#endif
243#endif //_WIN32
244
245#include <algorithm>
246#include <array>
247#include <atomic>
248#include <cassert>
249#include <cctype>
250#include <climits>
251#include <condition_variable>
252#include <cstring>
253#include <errno.h>
254#include <exception>
255#include <fcntl.h>
256#include <fstream>
257#include <functional>
258#include <iomanip>
259#include <iostream>
260#include <list>
261#include <map>
262#include <memory>
263#include <mutex>
264#include <random>
265#include <regex>
266#include <set>
267#include <sstream>
268#include <string>
269#include <sys/stat.h>
270#include <thread>
271#include <unordered_map>
272#include <unordered_set>
273#include <utility>
274
275#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
276#ifdef _WIN32
277#include <wincrypt.h>
278
279// these are defined in wincrypt.h and it breaks compilation if BoringSSL is
280// used
281#undef X509_NAME
282#undef X509_CERT_PAIR
283#undef X509_EXTENSIONS
284#undef PKCS7_SIGNER_INFO
285
286#ifdef _MSC_VER
287#pragma comment(lib, "crypt32.lib")
288#endif
289#elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && defined(__APPLE__)
290#include <TargetConditionals.h>
291#if TARGET_OS_OSX
292// The precompiled header brings in ArduinoJson.h, whose `using namespace ArduinoJson` makes MacTypes.h's
293// global Ptr ambiguous with ArduinoJson's Ptr class; give the macOS one another name here
294#define Ptr esphome_mactypes_Ptr
295#include <CoreFoundation/CoreFoundation.h>
296#include <Security/Security.h>
297#undef Ptr
298#endif // TARGET_OS_OSX
299#endif // _WIN32
300
301#include <openssl/err.h>
302#include <openssl/evp.h>
303#include <openssl/ssl.h>
304#include <openssl/x509v3.h>
305
306#if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
307#include <openssl/applink.c>
308#endif
309
310#include <iostream>
311#include <sstream>
312
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
316#endif
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
320#endif
321
322#endif
323
324#ifdef CPPHTTPLIB_ZLIB_SUPPORT
325#include <zlib.h>
326#endif
327
328#ifdef CPPHTTPLIB_BROTLI_SUPPORT
329#include <brotli/decode.h>
330#include <brotli/encode.h>
331#endif
332
333/*
334 * Declaration
335 */
336namespace httplib {
337
338namespace detail {
339
340/*
341 * Backport std::make_unique from C++14.
342 *
343 * NOTE: This code came up with the following stackoverflow post:
344 * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
345 *
346 */
347
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)...));
351}
352
353template<class T>
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]);
357}
358
359namespace case_ignore {
360
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,
375 };
376 return table[(unsigned char) (char) c];
377}
378
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); });
382}
383
384struct equal_to {
385 bool operator()(const std::string &a, const std::string &b) const { return equal(a, b); }
386};
387
388struct hash {
389 size_t operator()(const std::string &key) const { return hash_core(key.data(), key.size(), 0); }
390
391 size_t hash_core(const char *s, size_t l, size_t h) const {
392 return (l == 0) ? h
393 : hash_core(s + 1, l - 1,
394 // Unsets the 6 high bits of h, therefore no
395 // overflow happens
396 (((std::numeric_limits<size_t>::max)() >> 6) & h * 33) ^
397 static_cast<unsigned char>(to_lower(*s)));
398 }
399};
400
401} // namespace case_ignore
402
403// This is based on
404// "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
405
406struct scope_exit {
407 explicit scope_exit(std::function<void(void)> &&f) : exit_function(std::move(f)), execute_on_destruction{true} {}
408
409 scope_exit(scope_exit &&rhs) noexcept
410 : exit_function(std::move(rhs.exit_function)), execute_on_destruction{rhs.execute_on_destruction} {
411 rhs.release();
412 }
413
414 ~scope_exit() {
415 if (execute_on_destruction) {
416 this->exit_function();
417 }
418 }
419
420 void release() { this->execute_on_destruction = false; }
421
422 private:
423 scope_exit(const scope_exit &) = delete;
424 void operator=(const scope_exit &) = delete;
425 scope_exit &operator=(scope_exit &&) = delete;
426
427 std::function<void(void)> exit_function;
428 bool execute_on_destruction;
429};
430
431} // namespace detail
432
433enum StatusCode {
434 // Information responses
435 Continue_100 = 100,
436 SwitchingProtocol_101 = 101,
437 Processing_102 = 102,
438 EarlyHints_103 = 103,
439
440 // Successful responses
441 OK_200 = 200,
442 Created_201 = 201,
443 Accepted_202 = 202,
444 NonAuthoritativeInformation_203 = 203,
445 NoContent_204 = 204,
446 ResetContent_205 = 205,
447 PartialContent_206 = 206,
448 MultiStatus_207 = 207,
449 AlreadyReported_208 = 208,
450 IMUsed_226 = 226,
451
452 // Redirection messages
453 MultipleChoices_300 = 300,
454 MovedPermanently_301 = 301,
455 Found_302 = 302,
456 SeeOther_303 = 303,
457 NotModified_304 = 304,
458 UseProxy_305 = 305,
459 unused_306 = 306,
460 TemporaryRedirect_307 = 307,
461 PermanentRedirect_308 = 308,
462
463 // Client error responses
464 BadRequest_400 = 400,
465 Unauthorized_401 = 401,
466 PaymentRequired_402 = 402,
467 Forbidden_403 = 403,
468 NotFound_404 = 404,
469 MethodNotAllowed_405 = 405,
470 NotAcceptable_406 = 406,
471 ProxyAuthenticationRequired_407 = 407,
472 RequestTimeout_408 = 408,
473 Conflict_409 = 409,
474 Gone_410 = 410,
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,
482 ImATeapot_418 = 418,
483 MisdirectedRequest_421 = 421,
484 UnprocessableContent_422 = 422,
485 Locked_423 = 423,
486 FailedDependency_424 = 424,
487 TooEarly_425 = 425,
488 UpgradeRequired_426 = 426,
489 PreconditionRequired_428 = 428,
490 TooManyRequests_429 = 429,
491 RequestHeaderFieldsTooLarge_431 = 431,
492 UnavailableForLegalReasons_451 = 451,
493
494 // Server error responses
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,
506};
507
508using Headers =
509 std::unordered_multimap<std::string, std::string, detail::case_ignore::hash, detail::case_ignore::equal_to>;
510
511using Params = std::multimap<std::string, std::string>;
512using Match = std::smatch;
513
514using Progress = std::function<bool(uint64_t current, uint64_t total)>;
515
516struct Response;
517using ResponseHandler = std::function<bool(const Response &response)>;
518
519struct MultipartFormData {
520 std::string name;
521 std::string content;
522 std::string filename;
523 std::string content_type;
524};
525using MultipartFormDataItems = std::vector<MultipartFormData>;
526using MultipartFormDataMap = std::multimap<std::string, MultipartFormData>;
527
528class DataSink {
529 public:
530 DataSink() : os(&sb_), sb_(*this) {}
531
532 DataSink(const DataSink &) = delete;
533 DataSink &operator=(const DataSink &) = delete;
534 DataSink(DataSink &&) = delete;
535 DataSink &operator=(DataSink &&) = delete;
536
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;
541 std::ostream os;
542
543 private:
544 class data_sink_streambuf final : public std::streambuf {
545 public:
546 explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
547
548 protected:
549 std::streamsize xsputn(const char *s, std::streamsize n) override {
550 sink_.write(s, static_cast<size_t>(n));
551 return n;
552 }
553
554 private:
555 DataSink &sink_;
556 };
557
558 data_sink_streambuf sb_;
559};
560
561using ContentProvider = std::function<bool(size_t offset, size_t length, DataSink &sink)>;
562
563using ContentProviderWithoutLength = std::function<bool(size_t offset, DataSink &sink)>;
564
565using ContentProviderResourceReleaser = std::function<void(bool success)>;
566
567struct MultipartFormDataProvider {
568 std::string name;
569 ContentProviderWithoutLength provider;
570 std::string filename;
571 std::string content_type;
572};
573using MultipartFormDataProviderItems = std::vector<MultipartFormDataProvider>;
574
575using ContentReceiverWithProgress =
576 std::function<bool(const char *data, size_t data_length, uint64_t offset, uint64_t total_length)>;
577
578using ContentReceiver = std::function<bool(const char *data, size_t data_length)>;
579
580using MultipartContentHeader = std::function<bool(const MultipartFormData &file)>;
581
582class ContentReader {
583 public:
584 using Reader = std::function<bool(ContentReceiver receiver)>;
585 using MultipartReader = std::function<bool(MultipartContentHeader header, ContentReceiver receiver)>;
586
587 ContentReader(Reader reader, MultipartReader multipart_reader)
588 : reader_(std::move(reader)), multipart_reader_(std::move(multipart_reader)) {}
589
590 bool operator()(MultipartContentHeader header, ContentReceiver receiver) const {
591 return multipart_reader_(std::move(header), std::move(receiver));
592 }
593
594 bool operator()(ContentReceiver receiver) const { return reader_(std::move(receiver)); }
595
596 Reader reader_;
597 MultipartReader multipart_reader_;
598};
599
600using Range = std::pair<ssize_t, ssize_t>;
601using Ranges = std::vector<Range>;
602
603struct Request {
604 std::string method;
605 std::string path;
606 Params params;
607 Headers headers;
608 std::string body;
609
610 std::string remote_addr;
611 int remote_port = -1;
612 std::string local_addr;
613 int local_port = -1;
614
615 // for server
616 std::string version;
617 std::string target;
618 MultipartFormDataMap files;
619 Ranges ranges;
620 Match matches;
621 std::unordered_map<std::string, std::string> path_params;
622
623 // for client
624 ResponseHandler response_handler;
625 ContentReceiverWithProgress content_receiver;
626 Progress progress;
627#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
628 const SSL *ssl = nullptr;
629#endif
630
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);
636
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;
640
641 bool is_multipart_form_data() const;
642
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;
646
647 // private members...
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;
653};
654
655struct Response {
656 std::string version;
657 int status = -1;
658 std::string reason;
659 Headers headers;
660 std::string body;
661 std::string location; // Redirect location
662
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);
668
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);
673
674 void set_content_provider(size_t length, const std::string &content_type, ContentProvider provider,
675 ContentProviderResourceReleaser resource_releaser = nullptr);
676
677 void set_content_provider(const std::string &content_type, ContentProviderWithoutLength provider,
678 ContentProviderResourceReleaser resource_releaser = nullptr);
679
680 void set_chunked_content_provider(const std::string &content_type, ContentProviderWithoutLength provider,
681 ContentProviderResourceReleaser resource_releaser = nullptr);
682
683 void set_file_content(const std::string &path, const std::string &content_type);
684 void set_file_content(const std::string &path);
685
686 Response() = default;
687 Response(const Response &) = default;
688 Response &operator=(const Response &) = default;
689 Response(Response &&) = default;
690 Response &operator=(Response &&) = default;
691 ~Response() {
692 if (content_provider_resource_releaser_) {
693 content_provider_resource_releaser_(content_provider_success_);
694 }
695 }
696
697 // private members...
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_;
705};
706
707class Stream {
708 public:
709 virtual ~Stream() = default;
710
711 virtual bool is_readable() const = 0;
712 virtual bool is_writable() const = 0;
713
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;
719
720 ssize_t write(const char *ptr);
721 ssize_t write(const std::string &s);
722};
723
724class TaskQueue {
725 public:
726 TaskQueue() = default;
727 virtual ~TaskQueue() = default;
728
729 virtual bool enqueue(std::function<void()> fn) = 0;
730 virtual void shutdown() = 0;
731
732 virtual void on_idle() {}
733};
734
735class ThreadPool final : public TaskQueue {
736 public:
737 explicit ThreadPool(size_t n, size_t mqr = 0) : shutdown_(false), max_queued_requests_(mqr) {
738 while (n) {
739 threads_.emplace_back(worker(*this));
740 n--;
741 }
742 }
743
744 ThreadPool(const ThreadPool &) = delete;
745 ~ThreadPool() override = default;
746
747 bool enqueue(std::function<void()> fn) override {
748 {
749 std::unique_lock<std::mutex> lock(mutex_);
750 if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
751 return false;
752 }
753 jobs_.push_back(std::move(fn));
754 }
755
756 cond_.notify_one();
757 return true;
758 }
759
760 void shutdown() override {
761 // Stop all worker threads...
762 {
763 std::unique_lock<std::mutex> lock(mutex_);
764 shutdown_ = true;
765 }
766
767 cond_.notify_all();
768
769 // Join...
770 for (auto &t : threads_) {
771 t.join();
772 }
773 }
774
775 private:
776 struct worker {
777 explicit worker(ThreadPool &pool) : pool_(pool) {}
778
779 void operator()() {
780 for (;;) {
781 std::function<void()> fn;
782 {
783 std::unique_lock<std::mutex> lock(pool_.mutex_);
784
785 pool_.cond_.wait(lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; });
786
787 if (pool_.shutdown_ && pool_.jobs_.empty()) {
788 break;
789 }
790
791 fn = pool_.jobs_.front();
792 pool_.jobs_.pop_front();
793 }
794
795 assert(true == static_cast<bool>(fn));
796 fn();
797 }
798
799#if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && !defined(LIBRESSL_VERSION_NUMBER)
800 OPENSSL_thread_stop();
801#endif
802 }
803
804 ThreadPool &pool_;
805 };
806 friend struct worker;
807
808 std::vector<std::thread> threads_;
809 std::list<std::function<void()>> jobs_;
810
811 bool shutdown_;
812 size_t max_queued_requests_ = 0;
813
814 std::condition_variable cond_;
815 std::mutex mutex_;
816};
817
818using Logger = std::function<void(const Request &, const Response &)>;
819
820using SocketOptions = std::function<void(socket_t sock)>;
821
822void default_socket_options(socket_t sock);
823
824const char *status_message(int status);
825
826std::string get_bearer_token_auth(const Request &req);
827
828namespace detail {
829
830class MatcherBase {
831 public:
832 virtual ~MatcherBase() = default;
833
834 // Match request path and populate its matches and
835 virtual bool match(Request &request) const = 0;
836};
837
856class PathParamsMatcher final : public MatcherBase {
857 public:
858 PathParamsMatcher(const std::string &pattern);
859
860 bool match(Request &request) const override;
861
862 private:
863 // Treat segment separators as the end of path parameter capture
864 // Does not need to handle query parameters as they are parsed before path
865 // matching
866 static constexpr char separator = '/';
867
868 // Contains static path fragments to match against, excluding the '/' after
869 // path params
870 // Fragments are separated by path params
871 std::vector<std::string> static_fragments_;
872 // Stores the names of the path parameters to be used as keys in the
873 // Request::path_params map
874 std::vector<std::string> param_names_;
875};
876
885class RegexMatcher final : public MatcherBase {
886 public:
887 RegexMatcher(const std::string &pattern) : regex_(pattern) {}
888
889 bool match(Request &request) const override;
890
891 private:
892 std::regex regex_;
893};
894
895ssize_t write_headers(Stream &strm, const Headers &headers);
896
897} // namespace detail
898
899class Server {
900 public:
901 using Handler = std::function<void(const Request &, Response &)>;
902
903 using ExceptionHandler = std::function<void(const Request &, Response &, std::exception_ptr ep)>;
904
905 enum class HandlerResponse {
906 Handled,
907 Unhandled,
908 };
909 using HandlerWithResponse = std::function<HandlerResponse(const Request &, Response &)>;
910
911 using HandlerWithContentReader =
912 std::function<void(const Request &, Response &, const ContentReader &content_reader)>;
913
914 using Expect100ContinueHandler = std::function<int(const Request &, Response &)>;
915
916 Server();
917
918 virtual ~Server();
919
920 virtual bool is_valid() const;
921
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);
932
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);
939
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>{});
943 }
944
945 Server &set_exception_handler(ExceptionHandler handler);
946 Server &set_pre_routing_handler(HandlerWithResponse handler);
947 Server &set_post_routing_handler(Handler handler);
948
949 Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
950 Server &set_logger(Logger logger);
951
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);
956
957 Server &set_default_headers(Headers headers);
958 Server &set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
959
960 Server &set_keep_alive_max_count(size_t count);
961 Server &set_keep_alive_timeout(time_t sec);
962
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);
965
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);
968
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);
971
972 Server &set_payload_max_length(size_t length);
973
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();
977
978 bool listen(const std::string &host, int port, int socket_flags = 0);
979
980 bool is_running() const;
981 void wait_until_ready() const;
982 void stop();
983 void decommission();
984
985 std::function<TaskQueue *(void)> new_task_queue;
986
987 protected:
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);
991
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;
1002
1003 private:
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>>;
1007
1008 static std::unique_ptr<detail::MatcherBase> make_matcher(const std::string &pattern);
1009
1010 Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
1011 Server &set_error_handler_core(Handler handler, std::false_type);
1012
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();
1017
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;
1023
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;
1037
1038 virtual bool process_and_close_socket(socket_t sock);
1039
1040 std::atomic<bool> is_running_{false};
1041 std::atomic<bool> is_decommisioned{false};
1042
1043 struct MountPointEntry {
1044 std::string mount_point;
1045 std::string base_dir;
1046 Headers headers;
1047 };
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_;
1052
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_;
1063
1064 HandlerWithResponse error_handler_;
1065 ExceptionHandler exception_handler_;
1066 HandlerWithResponse pre_routing_handler_;
1067 Handler post_routing_handler_;
1068 Expect100ContinueHandler expect_100_continue_handler_;
1069
1070 Logger logger_;
1071
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;
1076
1077 Headers default_headers_;
1078 std::function<ssize_t(Stream &, Headers &)> header_writer_ = detail::write_headers;
1079};
1080
1081enum class Error {
1082 Success = 0,
1083 Unknown,
1084 Connection,
1085 BindIPAddress,
1086 Read,
1087 Write,
1088 ExceedRedirectCount,
1089 Canceled,
1090 SSLConnection,
1091 SSLLoadingCerts,
1092 SSLServerVerification,
1093 SSLServerHostnameVerification,
1094 UnsupportedMultipartBoundaryChars,
1095 Compression,
1096 ConnectionTimeout,
1097 ProxyConnection,
1098
1099 // For internal use only
1100 SSLPeerCouldBeClosed_,
1101};
1102
1103std::string to_string(Error error);
1104
1105std::ostream &operator<<(std::ostream &os, const Error &obj);
1106
1107class Result {
1108 public:
1109 Result() = default;
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)) {}
1112 // Response
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(); }
1122
1123 // Error
1124 Error error() const { return err_; }
1125
1126 // Request Headers
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;
1131
1132 private:
1133 std::unique_ptr<Response> res_;
1134 Error err_ = Error::Unknown;
1135 Headers request_headers_;
1136};
1137
1138class ClientImpl {
1139 public:
1140 explicit ClientImpl(const std::string &host);
1141
1142 explicit ClientImpl(const std::string &host, int port);
1143
1144 explicit ClientImpl(const std::string &host, int port, const std::string &client_cert_path,
1145 const std::string &client_key_path);
1146
1147 virtual ~ClientImpl();
1148
1149 virtual bool is_valid() const;
1150
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,
1163 Progress progress);
1164 Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler,
1165 ContentReceiver content_receiver, Progress progress);
1166
1167 Result Get(const std::string &path, const Params &params, const Headers &headers, Progress progress = nullptr);
1168 Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver,
1169 Progress progress = nullptr);
1170 Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler,
1171 ContentReceiver content_receiver, Progress progress = nullptr);
1172
1173 Result Head(const std::string &path);
1174 Result Head(const std::string &path, const Headers &headers);
1175
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,
1188 Progress progress);
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 &params);
1197 Result Post(const std::string &path, const Headers &headers, const Params &params);
1198 Result Post(const std::string &path, const Headers &headers, const Params &params, 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);
1205
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,
1216 Progress progress);
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 &params);
1225 Result Put(const std::string &path, const Headers &headers, const Params &params);
1226 Result Put(const std::string &path, const Headers &headers, const Params &params, 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);
1233
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,
1237 Progress progress);
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);
1255
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,
1260 Progress progress);
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);
1271
1272 Result Options(const std::string &path);
1273 Result Options(const std::string &path, const Headers &headers);
1274
1275 bool send(Request &req, Response &res, Error &error);
1276 Result send(const Request &req);
1277
1278 void stop();
1279
1280 std::string host() const;
1281 int port() const;
1282
1283 size_t is_socket_open() const;
1284 socket_t socket() const;
1285
1286 void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
1287
1288 void set_default_headers(Headers headers);
1289
1290 void set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
1291
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);
1296
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);
1299
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);
1302
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);
1305
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);
1310#endif
1311
1312 void set_keep_alive(bool on);
1313 void set_follow_location(bool on);
1314
1315 void set_url_encode(bool on);
1316
1317 void set_compress(bool on);
1318
1319 void set_decompress(bool on);
1320
1321 void set_interface(const std::string &intf);
1322
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);
1328#endif
1329
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;
1334#endif
1335
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);
1340#endif
1341
1342 void set_logger(Logger logger);
1343
1344 protected:
1345 struct Socket {
1346 socket_t sock = INVALID_SOCKET;
1347#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
1348 SSL *ssl = nullptr;
1349#endif
1350
1351 bool is_open() const { return sock != INVALID_SOCKET; }
1352 };
1353
1354 virtual bool create_and_connect_socket(Socket &socket, Error &error);
1355
1356 // All of:
1357 // shutdown_ssl
1358 // shutdown_socket
1359 // close_socket
1360 // should ONLY be called when socket_mutex_ is locked.
1361 // Also, shutdown_ssl and close_socket should also NOT be called concurrently
1362 // with a DIFFERENT thread sending requests using that socket.
1363 virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
1364 void shutdown_socket(Socket &socket) const;
1365 void close_socket(Socket &socket);
1366
1367 bool process_request(Stream &strm, Request &req, Response &res, bool close_connection, Error &error);
1368
1369 bool write_content_with_provider(Stream &strm, const Request &req, Error &error) const;
1370
1371 void copy_settings(const ClientImpl &rhs);
1372
1373 // Socket endpoint information
1374 const std::string host_;
1375 const int port_;
1376 const std::string host_and_port_;
1377
1378 // Current open socket
1379 Socket socket_;
1380 mutable std::mutex socket_mutex_;
1381 std::recursive_mutex request_mutex_;
1382
1383 // These are all protected under socket_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;
1387
1388 // Hostname-IP map
1389 std::map<std::string, std::string> addr_map_;
1390
1391 // Default headers
1392 Headers default_headers_;
1393
1394 // Header writer
1395 std::function<ssize_t(Stream &, Headers &)> header_writer_ = detail::write_headers;
1396
1397 // Settings
1398 std::string client_cert_path_;
1399 std::string client_key_path_;
1400
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;
1407
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_;
1414#endif
1415
1416 bool keep_alive_ = false;
1417 bool follow_location_ = false;
1418
1419 bool url_encode_ = true;
1420
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;
1425
1426 bool compress_ = false;
1427 bool decompress_ = true;
1428
1429 std::string interface_;
1430
1431 std::string proxy_host_;
1432 int proxy_port_ = -1;
1433
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_;
1440#endif
1441
1442#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
1443 std::string ca_cert_file_path_;
1444 std::string ca_cert_dir_path_;
1445
1446 X509_STORE *ca_cert_store_ = nullptr;
1447#endif
1448
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_;
1453#endif
1454
1455 Logger logger_;
1456
1457 private:
1458 bool send_(Request &req, Response &res, Error &error);
1459 Result send_(Request &&req);
1460
1461#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
1462 bool is_ssl_peer_could_be_closed(SSL *ssl) const;
1463#endif
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;
1480
1481 std::string adjust_host_string(const std::string &host) const;
1482
1483 virtual bool process_socket(const Socket &socket, std::function<bool(Stream &strm)> callback);
1484 virtual bool is_ssl() const;
1485};
1486
1487class Client {
1488 public:
1489 // Universal interface
1490 explicit Client(const std::string &scheme_host_port);
1491
1492 explicit Client(const std::string &scheme_host_port, const std::string &client_cert_path,
1493 const std::string &client_key_path);
1494
1495 // HTTP only interface
1496 explicit Client(const std::string &host, int port);
1497
1498 explicit Client(const std::string &host, int port, const std::string &client_cert_path,
1499 const std::string &client_key_path);
1500
1501 Client(Client &&) = default;
1502 Client &operator=(Client &&) = default;
1503
1504 ~Client();
1505
1506 bool is_valid() const;
1507
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,
1522 Progress progress);
1523
1524 Result Get(const std::string &path, const Params &params, const Headers &headers, Progress progress = nullptr);
1525 Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver,
1526 Progress progress = nullptr);
1527 Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler,
1528 ContentReceiver content_receiver, Progress progress = nullptr);
1529
1530 Result Head(const std::string &path);
1531 Result Head(const std::string &path, const Headers &headers);
1532
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,
1545 Progress progress);
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 &params);
1554 Result Post(const std::string &path, const Headers &headers, const Params &params);
1555 Result Post(const std::string &path, const Headers &headers, const Params &params, 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);
1562
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,
1573 Progress progress);
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 &params);
1582 Result Put(const std::string &path, const Headers &headers, const Params &params);
1583 Result Put(const std::string &path, const Headers &headers, const Params &params, 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);
1590
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,
1594 Progress progress);
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);
1612
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,
1617 Progress progress);
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);
1628
1629 Result Options(const std::string &path);
1630 Result Options(const std::string &path, const Headers &headers);
1631
1632 bool send(Request &req, Response &res, Error &error);
1633 Result send(const Request &req);
1634
1635 void stop();
1636
1637 std::string host() const;
1638 int port() const;
1639
1640 size_t is_socket_open() const;
1641 socket_t socket() const;
1642
1643 void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
1644
1645 void set_default_headers(Headers headers);
1646
1647 void set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
1648
1649 void set_address_family(int family);
1650 void set_tcp_nodelay(bool on);
1651 void set_socket_options(SocketOptions socket_options);
1652
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);
1655
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);
1658
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);
1661
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);
1666#endif
1667
1668 void set_keep_alive(bool on);
1669 void set_follow_location(bool on);
1670
1671 void set_url_encode(bool on);
1672
1673 void set_compress(bool on);
1674
1675 void set_decompress(bool on);
1676
1677 void set_interface(const std::string &intf);
1678
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);
1684#endif
1685
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);
1690#endif
1691
1692 void set_logger(Logger logger);
1693
1694 // SSL
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());
1697
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);
1700
1701 long get_openssl_verify_result() const;
1702
1703 SSL_CTX *ssl_context() const;
1704#endif
1705
1706 private:
1707 std::unique_ptr<ClientImpl> cli_;
1708
1709#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
1710 bool is_ssl_ = false;
1711#endif
1712};
1713
1714#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
1715class SSLServer : public Server {
1716 public:
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);
1719
1720 SSLServer(X509 *cert, EVP_PKEY *private_key, X509_STORE *client_ca_cert_store = nullptr);
1721
1722 SSLServer(const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback);
1723
1724 ~SSLServer() override;
1725
1726 bool is_valid() const override;
1727
1728 SSL_CTX *ssl_context() const;
1729
1730 void update_certs(X509 *cert, EVP_PKEY *private_key, X509_STORE *client_ca_cert_store = nullptr);
1731
1732 private:
1733 bool process_and_close_socket(socket_t sock) override;
1734
1735 SSL_CTX *ctx_;
1736 std::mutex ctx_mutex_;
1737};
1738
1739class SSLClient final : public ClientImpl {
1740 public:
1741 explicit SSLClient(const std::string &host);
1742
1743 explicit SSLClient(const std::string &host, int port);
1744
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());
1747
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());
1750
1751 ~SSLClient() override;
1752
1753 bool is_valid() const override;
1754
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);
1757
1758 long get_openssl_verify_result() const;
1759
1760 SSL_CTX *ssl_context() const;
1761
1762 private:
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);
1766
1767 bool process_socket(const Socket &socket, std::function<bool(Stream &strm)> callback) override;
1768 bool is_ssl() const override;
1769
1770 bool connect_with_proxy(Socket &sock, Response &res, bool &success, Error &error);
1771 bool initialize_ssl(Socket &socket, Error &error);
1772
1773 bool load_certs();
1774
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;
1779
1780 SSL_CTX *ctx_;
1781 std::mutex ctx_mutex_;
1782 std::once_flag initialize_cert_;
1783
1784 std::vector<std::string> host_components_;
1785
1786 long verify_result_ = 0;
1787
1788 friend class ClientImpl;
1789};
1790#endif
1791
1792/*
1793 * Implementation of template methods.
1794 */
1795
1796namespace detail {
1797
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));
1802}
1803
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);
1810 }
1811 return def;
1812}
1813
1814} // namespace detail
1815
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);
1818}
1819
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);
1822}
1823
1824inline void default_socket_options(socket_t sock) {
1825 int opt = 1;
1826#ifdef _WIN32
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));
1829#else
1830#ifdef SO_REUSEPORT
1831 setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, reinterpret_cast<const void *>(&opt), sizeof(opt));
1832#else
1833 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const void *>(&opt), sizeof(opt));
1834#endif
1835#endif
1836}
1837
1838inline const char *status_message(int status) {
1839 switch (status) {
1840 case StatusCode::Continue_100:
1841 return "Continue";
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:
1849 return "OK";
1850 case StatusCode::Created_201:
1851 return "Created";
1852 case StatusCode::Accepted_202:
1853 return "Accepted";
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:
1867 return "IM Used";
1868 case StatusCode::MultipleChoices_300:
1869 return "Multiple Choices";
1870 case StatusCode::MovedPermanently_301:
1871 return "Moved Permanently";
1872 case StatusCode::Found_302:
1873 return "Found";
1874 case StatusCode::SeeOther_303:
1875 return "See Other";
1876 case StatusCode::NotModified_304:
1877 return "Not Modified";
1878 case StatusCode::UseProxy_305:
1879 return "Use Proxy";
1880 case StatusCode::unused_306:
1881 return "unused";
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:
1893 return "Forbidden";
1894 case StatusCode::NotFound_404:
1895 return "Not Found";
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:
1905 return "Conflict";
1906 case StatusCode::Gone_410:
1907 return "Gone";
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:
1929 return "Locked";
1930 case StatusCode::FailedDependency_424:
1931 return "Failed Dependency";
1932 case StatusCode::TooEarly_425:
1933 return "Too Early";
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";
1964
1965 default:
1966 case StatusCode::InternalServerError_500:
1967 return "Internal Server Error";
1968 }
1969}
1970
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());
1975 }
1976 return "";
1977}
1978
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); });
1982 return *this;
1983}
1984
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); });
1988 return *this;
1989}
1990
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); });
1994 return *this;
1995}
1996
1997inline std::string to_string(const Error error) {
1998 switch (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";
2005 case Error::Read:
2006 return "Failed to read connection";
2007 case Error::Write:
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:
2030 return "Unknown";
2031 default:
2032 break;
2033 }
2034
2035 return "Invalid";
2036}
2037
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) << ')';
2041 return os;
2042}
2043
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);
2046}
2047
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); });
2051}
2052
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); });
2056}
2057
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); });
2061}
2062
2063template<class Rep, class Period>
2064inline void Client::set_connection_timeout(const std::chrono::duration<Rep, Period> &duration) {
2065 cli_->set_connection_timeout(duration);
2066}
2067
2068template<class Rep, class Period>
2069inline void Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
2070 cli_->set_read_timeout(duration);
2071}
2072
2073template<class Rep, class Period>
2074inline void Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
2075 cli_->set_write_timeout(duration);
2076}
2077
2078/*
2079 * Forward declarations and types that will be part of the .h file if split into
2080 * .h + .cc.
2081 */
2082
2083std::string hosted_at(const std::string &hostname);
2084
2085void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
2086
2087std::string append_query_params(const std::string &path, const Params &params);
2088
2089std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
2090
2091std::pair<std::string, std::string> make_basic_authentication_header(const std::string &username,
2092 const std::string &password,
2093 bool is_proxy = false);
2094
2095namespace detail {
2096
2097#if defined(_WIN32)
2098inline std::wstring u8string_to_wstring(const char *s) {
2099 std::wstring ws;
2100 auto len = static_cast<int>(strlen(s));
2101 auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
2102 if (wlen > 0) {
2103 ws.resize(wlen);
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())) {
2106 ws.clear();
2107 }
2108 }
2109 return ws;
2110}
2111#endif
2112
2113struct FileStat {
2114 FileStat(const std::string &path);
2115 bool is_file() const;
2116 bool is_dir() const;
2117
2118 private:
2119#if defined(_WIN32)
2120 struct _stat st_;
2121#else
2122 struct stat st_;
2123#endif
2124 int ret_ = -1;
2125};
2126
2127std::string encode_query_param(const std::string &value);
2128
2129std::string decode_url(const std::string &s, bool convert_plus_to_space);
2130
2131void read_file(const std::string &path, std::string &out);
2132
2133std::string trim_copy(const std::string &s);
2134
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);
2137
2138void divide(const std::string &str, char d,
2139 std::function<void(const char *, std::size_t, const char *, std::size_t)> fn);
2140
2141void split(const char *b, const char *e, char d, std::function<void(const char *, const char *)> fn);
2142
2143void split(const char *b, const char *e, char d, size_t m, std::function<void(const char *, const char *)> fn);
2144
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);
2147
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);
2153
2154const char *get_header_value(const Headers &headers, const std::string &key, const char *def, size_t id);
2155
2156std::string params_to_query_str(const Params &params);
2157
2158void parse_query_text(const char *data, std::size_t size, Params &params);
2159
2160void parse_query_text(const std::string &s, Params &params);
2161
2162bool parse_multipart_boundary(const std::string &content_type, std::string &boundary);
2163
2164bool parse_range_header(const std::string &s, Ranges &ranges);
2165
2166int close_socket(socket_t sock);
2167
2168ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
2169
2170ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
2171
2172enum class EncodingType { None = 0, Gzip, Brotli };
2173
2174EncodingType encoding_type(const Request &req, const Response &res);
2175
2176class BufferStream final : public Stream {
2177 public:
2178 BufferStream() = default;
2179 ~BufferStream() override = default;
2180
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;
2187 socket_t socket() const override;
2188
2189 const std::string &get_buffer() const;
2190
2191 private:
2192 std::string buffer;
2193 size_t position = 0;
2194};
2195
2196class compressor {
2197 public:
2198 virtual ~compressor() = default;
2199
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;
2202};
2203
2204class decompressor {
2205 public:
2206 virtual ~decompressor() = default;
2207
2208 virtual bool is_valid() const = 0;
2209
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;
2212};
2213
2214class nocompressor final : public compressor {
2215 public:
2216 ~nocompressor() override = default;
2217
2218 bool compress(const char *data, size_t data_length, bool /*last*/, Callback callback) override;
2219};
2220
2221#ifdef CPPHTTPLIB_ZLIB_SUPPORT
2222class gzip_compressor final : public compressor {
2223 public:
2224 gzip_compressor();
2225 ~gzip_compressor() override;
2226
2227 bool compress(const char *data, size_t data_length, bool last, Callback callback) override;
2228
2229 private:
2230 bool is_valid_ = false;
2231 z_stream strm_;
2232};
2233
2234class gzip_decompressor final : public decompressor {
2235 public:
2236 gzip_decompressor();
2237 ~gzip_decompressor() override;
2238
2239 bool is_valid() const override;
2240
2241 bool decompress(const char *data, size_t data_length, Callback callback) override;
2242
2243 private:
2244 bool is_valid_ = false;
2245 z_stream strm_;
2246};
2247#endif
2248
2249#ifdef CPPHTTPLIB_BROTLI_SUPPORT
2250class brotli_compressor final : public compressor {
2251 public:
2252 brotli_compressor();
2253 ~brotli_compressor();
2254
2255 bool compress(const char *data, size_t data_length, bool last, Callback callback) override;
2256
2257 private:
2258 BrotliEncoderState *state_ = nullptr;
2259};
2260
2261class brotli_decompressor final : public decompressor {
2262 public:
2263 brotli_decompressor();
2264 ~brotli_decompressor();
2265
2266 bool is_valid() const override;
2267
2268 bool decompress(const char *data, size_t data_length, Callback callback) override;
2269
2270 private:
2271 BrotliDecoderResult decoder_r;
2272 BrotliDecoderState *decoder_s = nullptr;
2273};
2274#endif
2275
2276// NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
2277// to store data. The call can set memory on stack for performance.
2278class stream_line_reader {
2279 public:
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;
2284 bool getline();
2285
2286 private:
2287 void append(char c);
2288
2289 Stream &strm_;
2290 char *fixed_buffer_;
2291 const size_t fixed_buffer_size_;
2292 size_t fixed_buffer_used_size_ = 0;
2293 std::string glowable_buffer_;
2294};
2295
2296class mmap {
2297 public:
2298 mmap(const char *path);
2299 ~mmap();
2300
2301 bool open(const char *path);
2302 void close();
2303
2304 bool is_open() const;
2305 size_t size() const;
2306 const char *data() const;
2307
2308 private:
2309#if defined(_WIN32)
2310 HANDLE hFile_ = NULL;
2311 HANDLE hMapping_ = NULL;
2312#else
2313 int fd_ = -1;
2314#endif
2315 size_t size_ = 0;
2316 void *addr_ = nullptr;
2317 bool is_open_empty_file = false;
2318};
2319
2320} // namespace detail
2321
2322// ----------------------------------------------------------------------------
2323
2324/*
2325 * Implementation that will be part of the .cc file if split into .h + .cc.
2326 */
2327
2328namespace detail {
2329
2330inline bool is_hex(char c, int &v) {
2331 if (0x20 <= c && isdigit(c)) {
2332 v = c - '0';
2333 return true;
2334 } else if ('A' <= c && c <= 'F') {
2335 v = c - 'A' + 10;
2336 return true;
2337 } else if ('a' <= c && c <= 'f') {
2338 v = c - 'a' + 10;
2339 return true;
2340 }
2341 return false;
2342}
2343
2344inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt, int &val) {
2345 if (i >= s.size()) {
2346 return false;
2347 }
2348
2349 val = 0;
2350 for (; cnt; i++, cnt--) {
2351 if (!s[i]) {
2352 return false;
2353 }
2354 auto v = 0;
2355 if (is_hex(s[i], v)) {
2356 val = val * 16 + v;
2357 } else {
2358 return false;
2359 }
2360 }
2361 return true;
2362}
2363
2364inline std::string from_i_to_hex(size_t n) {
2365 static const auto charset = "0123456789abcdef";
2366 std::string ret;
2367 do {
2368 ret = charset[n & 15] + ret;
2369 n >>= 4;
2370 } while (n > 0);
2371 return ret;
2372}
2373
2374inline size_t to_utf8(int code, char *buff) {
2375 if (code < 0x0080) {
2376 buff[0] = static_cast<char>(code & 0x7F);
2377 return 1;
2378 } else if (code < 0x0800) {
2379 buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
2380 buff[1] = static_cast<char>(0x80 | (code & 0x3F));
2381 return 2;
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));
2386 return 3;
2387 } else if (code < 0xE000) { // D800 - DFFF is invalid...
2388 return 0;
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));
2393 return 3;
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));
2399 return 4;
2400 }
2401
2402 // NOTREACHED
2403 return 0;
2404}
2405
2406// NOTE: This code came up with the following stackoverflow post:
2407// https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
2408inline std::string base64_encode(const std::string &in) {
2409 static const auto lookup = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2410
2411 std::string out;
2412 out.reserve(in.size());
2413
2414 auto val = 0;
2415 auto valb = -6;
2416
2417 for (auto c : in) {
2419 valb += 8;
2420 while (valb >= 0) {
2421 out.push_back(lookup[(val >> valb) & 0x3F]);
2422 valb -= 6;
2423 }
2424 }
2425
2426 if (valb > -6) {
2427 out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]);
2428 }
2429
2430 while (out.size() % 4) {
2431 out.push_back('=');
2432 }
2433
2434 return out;
2435}
2436
2437inline bool is_valid_path(const std::string &path) {
2438 size_t level = 0;
2439 size_t i = 0;
2440
2441 // Skip slash
2442 while (i < path.size() && path[i] == '/') {
2443 i++;
2444 }
2445
2446 while (i < path.size()) {
2447 // Read component
2448 auto beg = i;
2449 while (i < path.size() && path[i] != '/') {
2450 if (path[i] == '\0') {
2451 return false;
2452 } else if (path[i] == '\\') {
2453 return false;
2454 }
2455 i++;
2456 }
2457
2458 auto len = i - beg;
2459 assert(len > 0);
2460
2461 if (!path.compare(beg, len, ".")) {
2462 ;
2463 } else if (!path.compare(beg, len, "..")) {
2464 if (level == 0) {
2465 return false;
2466 }
2467 level--;
2468 } else {
2469 level++;
2470 }
2471
2472 // Skip slash
2473 while (i < path.size() && path[i] == '/') {
2474 i++;
2475 }
2476 }
2477
2478 return true;
2479}
2480
2481inline FileStat::FileStat(const std::string &path) {
2482#if defined(_WIN32)
2483 auto wpath = u8string_to_wstring(path.c_str());
2484 ret_ = _wstat(wpath.c_str(), &st_);
2485#else
2486 ret_ = stat(path.c_str(), &st_);
2487#endif
2488}
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); }
2491
2492inline std::string encode_query_param(const std::string &value) {
2493 std::ostringstream escaped;
2494 escaped.fill('0');
2495 escaped << std::hex;
2496
2497 for (auto c : value) {
2498 if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' || c == '.' || c == '!' || c == '~' || c == '*' ||
2499 c == '\'' || c == '(' || c == ')') {
2500 escaped << c;
2501 } else {
2502 escaped << std::uppercase;
2503 escaped << '%' << std::setw(2) << static_cast<int>(static_cast<unsigned char>(c));
2504 escaped << std::nouppercase;
2505 }
2506 }
2507
2508 return escaped.str();
2509}
2510
2511inline std::string encode_url(const std::string &s) {
2512 std::string result;
2513 result.reserve(s.size());
2514
2515 for (size_t i = 0; s[i]; i++) {
2516 switch (s[i]) {
2517 case ' ':
2518 result += "%20";
2519 break;
2520 case '+':
2521 result += "%2B";
2522 break;
2523 case '\r':
2524 result += "%0D";
2525 break;
2526 case '\n':
2527 result += "%0A";
2528 break;
2529 case '\'':
2530 result += "%27";
2531 break;
2532 case ',':
2533 result += "%2C";
2534 break;
2535 // case ':': result += "%3A"; break; // ok? probably...
2536 case ';':
2537 result += "%3B";
2538 break;
2539 default:
2540 auto c = static_cast<uint8_t>(s[i]);
2541 if (c >= 0x80) {
2542 result += '%';
2543 char hex[4];
2544 auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
2545 assert(len == 2);
2546 result.append(hex, static_cast<size_t>(len));
2547 } else {
2548 result += s[i];
2549 }
2550 break;
2551 }
2552 }
2553
2554 return result;
2555}
2556
2557inline std::string decode_url(const std::string &s, bool convert_plus_to_space) {
2558 std::string result;
2559
2560 for (size_t i = 0; i < s.size(); i++) {
2561 if (s[i] == '%' && i + 1 < s.size()) {
2562 if (s[i + 1] == 'u') {
2563 auto val = 0;
2564 if (from_hex_to_i(s, i + 2, 4, val)) {
2565 // 4 digits Unicode codes
2566 char buff[4];
2567 size_t len = to_utf8(val, buff);
2568 if (len > 0) {
2569 result.append(buff, len);
2570 }
2571 i += 5; // 'u0000'
2572 } else {
2573 result += s[i];
2574 }
2575 } else {
2576 auto val = 0;
2577 if (from_hex_to_i(s, i + 1, 2, val)) {
2578 // 2 digits hex codes
2579 result += static_cast<char>(val);
2580 i += 2; // '00'
2581 } else {
2582 result += s[i];
2583 }
2584 }
2585 } else if (convert_plus_to_space && s[i] == '+') {
2586 result += ' ';
2587 } else {
2588 result += s[i];
2589 }
2590 }
2591
2592 return result;
2593}
2594
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();
2599 fs.seekg(0);
2600 out.resize(static_cast<size_t>(size));
2601 fs.read(&out[0], static_cast<std::streamsize>(size));
2602}
2603
2604inline std::string file_extension(const std::string &path) {
2605 std::smatch m;
2606 static auto re = std::regex("\\.([a-zA-Z0-9]+)$");
2607 if (std::regex_search(path, m, re)) {
2608 return m[1].str();
2609 }
2610 return std::string();
2611}
2612
2613inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
2614
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])) {
2617 left++;
2618 }
2619 while (right > 0 && is_space_or_tab(b[right - 1])) {
2620 right--;
2621 }
2622 return std::make_pair(left, right);
2623}
2624
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);
2628}
2629
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);
2633 }
2634 return s;
2635}
2636
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;
2645
2646 fn(lhs_data, lhs_size, rhs_data, rhs_size);
2647}
2648
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));
2652}
2653
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));
2656}
2657
2658inline void split(const char *b, const char *e, char d, size_t m, std::function<void(const char *, const char *)> fn) {
2659 size_t i = 0;
2660 size_t beg = 0;
2661 size_t count = 1;
2662
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]);
2668 }
2669 beg = i + 1;
2670 count++;
2671 }
2672 i++;
2673 }
2674
2675 if (i) {
2676 auto r = trim(b, e, beg, i);
2677 if (r.first < r.second) {
2678 fn(&b[r.first], &b[r.second]);
2679 }
2680 }
2681}
2682
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) {}
2685
2686inline const char *stream_line_reader::ptr() const {
2687 if (glowable_buffer_.empty()) {
2688 return fixed_buffer_;
2689 } else {
2690 return glowable_buffer_.data();
2691 }
2692}
2693
2694inline size_t stream_line_reader::size() const {
2695 if (glowable_buffer_.empty()) {
2696 return fixed_buffer_used_size_;
2697 } else {
2698 return glowable_buffer_.size();
2699 }
2700}
2701
2702inline bool stream_line_reader::end_with_crlf() const {
2703 auto end = ptr() + size();
2704 return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
2705}
2706
2707inline bool stream_line_reader::getline() {
2708 fixed_buffer_used_size_ = 0;
2709 glowable_buffer_.clear();
2710
2711#ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
2712 char prev_byte = 0;
2713#endif
2714
2715 for (size_t i = 0;; i++) {
2716 char byte;
2717 auto n = strm_.read(&byte, 1);
2718
2719 if (n < 0) {
2720 return false;
2721 } else if (n == 0) {
2722 if (i == 0) {
2723 return false;
2724 } else {
2725 break;
2726 }
2727 }
2728
2729 append(byte);
2730
2731#ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
2732 if (byte == '\n') {
2733 break;
2734 }
2735#else
2736 if (prev_byte == '\r' && byte == '\n') {
2737 break;
2738 }
2739 prev_byte = byte;
2740#endif
2741 }
2742
2743 return true;
2744}
2745
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';
2750 } else {
2751 if (glowable_buffer_.empty()) {
2752 assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
2753 glowable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
2754 }
2755 glowable_buffer_ += c;
2756 }
2757}
2758
2759inline mmap::mmap(const char *path) { open(path); }
2760
2761inline mmap::~mmap() { close(); }
2762
2763inline bool mmap::open(const char *path) {
2764 close();
2765
2766#if defined(_WIN32)
2767 auto wpath = u8string_to_wstring(path);
2768 if (wpath.empty()) {
2769 return false;
2770 }
2771
2772#if _WIN32_WINNT >= _WIN32_WINNT_WIN8
2773 hFile_ = ::CreateFile2(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, NULL);
2774#else
2775 hFile_ =
2776 ::CreateFileW(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
2777#endif
2778
2779 if (hFile_ == INVALID_HANDLE_VALUE) {
2780 return false;
2781 }
2782
2783 LARGE_INTEGER size{};
2784 if (!::GetFileSizeEx(hFile_, &size)) {
2785 return false;
2786 }
2787 // If the following line doesn't compile due to QuadPart, update Windows SDK.
2788 // See:
2789 // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
2790 if (static_cast<ULONGLONG>(size.QuadPart) > (std::numeric_limits<decltype(size_)>::max)()) {
2791 // `size_t` might be 32-bits, on 32-bits Windows.
2792 return false;
2793 }
2794 size_ = static_cast<size_t>(size.QuadPart);
2795
2796#if _WIN32_WINNT >= _WIN32_WINNT_WIN8
2797 hMapping_ = ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
2798#else
2799 hMapping_ = ::CreateFileMappingW(hFile_, NULL, PAGE_READONLY, 0, 0, NULL);
2800#endif
2801
2802 // Special treatment for an empty file...
2803 if (hMapping_ == NULL && size_ == 0) {
2804 close();
2805 is_open_empty_file = true;
2806 return true;
2807 }
2808
2809 if (hMapping_ == NULL) {
2810 close();
2811 return false;
2812 }
2813
2814#if _WIN32_WINNT >= _WIN32_WINNT_WIN8
2815 addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
2816#else
2817 addr_ = ::MapViewOfFile(hMapping_, FILE_MAP_READ, 0, 0, 0);
2818#endif
2819
2820 if (addr_ == nullptr) {
2821 close();
2822 return false;
2823 }
2824#else
2825 fd_ = ::open(path, O_RDONLY);
2826 if (fd_ == -1) {
2827 return false;
2828 }
2829
2830 struct stat sb;
2831 if (fstat(fd_, &sb) == -1) {
2832 close();
2833 return false;
2834 }
2835 size_ = static_cast<size_t>(sb.st_size);
2836
2837 addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
2838
2839 // Special treatment for an empty file...
2840 if (addr_ == MAP_FAILED && size_ == 0) {
2841 close();
2842 is_open_empty_file = true;
2843 return false;
2844 }
2845#endif
2846
2847 return true;
2848}
2849
2850inline bool mmap::is_open() const { return is_open_empty_file ? true : addr_ != nullptr; }
2851
2852inline size_t mmap::size() const { return size_; }
2853
2854inline const char *mmap::data() const { return is_open_empty_file ? "" : static_cast<const char *>(addr_); }
2855
2856inline void mmap::close() {
2857#if defined(_WIN32)
2858 if (addr_) {
2859 ::UnmapViewOfFile(addr_);
2860 addr_ = nullptr;
2861 }
2862
2863 if (hMapping_) {
2864 ::CloseHandle(hMapping_);
2865 hMapping_ = NULL;
2866 }
2867
2868 if (hFile_ != INVALID_HANDLE_VALUE) {
2869 ::CloseHandle(hFile_);
2870 hFile_ = INVALID_HANDLE_VALUE;
2871 }
2872
2873 is_open_empty_file = false;
2874#else
2875 if (addr_ != nullptr) {
2876 munmap(addr_, size_);
2877 addr_ = nullptr;
2878 }
2879
2880 if (fd_ != -1) {
2881 ::close(fd_);
2882 fd_ = -1;
2883 }
2884#endif
2885 size_ = 0;
2886}
2887inline int close_socket(socket_t sock) {
2888#ifdef _WIN32
2889 return closesocket(sock);
2890#else
2891 return close(sock);
2892#endif
2893}
2894
2895template<typename T> inline ssize_t handle_EINTR(T fn) {
2896 ssize_t res = 0;
2897 while (true) {
2898 res = fn();
2899 if (res < 0 && errno == EINTR) {
2900 std::this_thread::sleep_for(std::chrono::microseconds{1});
2901 continue;
2902 }
2903 break;
2904 }
2905 return res;
2906}
2907
2908inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
2909 return handle_EINTR([&]() {
2910 return recv(sock,
2911#ifdef _WIN32
2912 static_cast<char *>(ptr), static_cast<int>(size),
2913#else
2914 ptr, size,
2915#endif
2916 flags);
2917 });
2918}
2919
2920inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags) {
2921 return handle_EINTR([&]() {
2922 return send(sock,
2923#ifdef _WIN32
2924 static_cast<const char *>(ptr), static_cast<int>(size),
2925#else
2926 ptr, size,
2927#endif
2928 flags);
2929 });
2930}
2931
2932inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
2933#ifdef CPPHTTPLIB_USE_POLL
2934 struct pollfd pfd_read;
2935 pfd_read.fd = sock;
2936 pfd_read.events = POLLIN;
2937
2938 auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
2939
2940 return handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); });
2941#else
2942#ifndef _WIN32
2943 if (sock >= FD_SETSIZE) {
2944 return -1;
2945 }
2946#endif
2947
2948 fd_set fds;
2949 FD_ZERO(&fds);
2950 FD_SET(sock, &fds);
2951
2952 timeval tv;
2953 tv.tv_sec = static_cast<long>(sec);
2954 tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
2955
2956 return handle_EINTR([&]() { return select(static_cast<int>(sock + 1), &fds, nullptr, nullptr, &tv); });
2957#endif
2958}
2959
2960inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
2961#ifdef CPPHTTPLIB_USE_POLL
2962 struct pollfd pfd_read;
2963 pfd_read.fd = sock;
2964 pfd_read.events = POLLOUT;
2965
2966 auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
2967
2968 return handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); });
2969#else
2970#ifndef _WIN32
2971 if (sock >= FD_SETSIZE) {
2972 return -1;
2973 }
2974#endif
2975
2976 fd_set fds;
2977 FD_ZERO(&fds);
2978 FD_SET(sock, &fds);
2979
2980 timeval tv;
2981 tv.tv_sec = static_cast<long>(sec);
2982 tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
2983
2984 return handle_EINTR([&]() { return select(static_cast<int>(sock + 1), nullptr, &fds, nullptr, &tv); });
2985#endif
2986}
2987
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;
2991 pfd_read.fd = sock;
2992 pfd_read.events = POLLIN | POLLOUT;
2993
2994 auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
2995
2996 auto poll_res = handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); });
2997
2998 if (poll_res == 0) {
2999 return Error::ConnectionTimeout;
3000 }
3001
3002 if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
3003 auto error = 0;
3004 socklen_t len = sizeof(error);
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;
3008 }
3009
3010 return Error::Connection;
3011#else
3012#ifndef _WIN32
3013 if (sock >= FD_SETSIZE) {
3014 return Error::Connection;
3015 }
3016#endif
3017
3018 fd_set fdsr;
3019 FD_ZERO(&fdsr);
3020 FD_SET(sock, &fdsr);
3021
3022 auto fdsw = fdsr;
3023 auto fdse = fdsr;
3024
3025 timeval tv;
3026 tv.tv_sec = static_cast<long>(sec);
3027 tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
3028
3029 auto ret = handle_EINTR([&]() { return select(static_cast<int>(sock + 1), &fdsr, &fdsw, &fdse, &tv); });
3030
3031 if (ret == 0) {
3032 return Error::ConnectionTimeout;
3033 }
3034
3035 if (ret > 0 && (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) {
3036 auto error = 0;
3037 socklen_t len = sizeof(error);
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;
3041 }
3042 return Error::Connection;
3043#endif
3044}
3045
3046inline bool is_socket_alive(socket_t sock) {
3047 const auto val = detail::select_read(sock, 0, 0);
3048 if (val == 0) {
3049 return true;
3050 } else if (val < 0 && errno == EBADF) {
3051 return false;
3052 }
3053 char buf[1];
3054 return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
3055}
3056
3057class SocketStream final : public Stream {
3058 public:
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;
3062
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;
3069 socket_t socket() const override;
3070
3071 private:
3072 socket_t sock_;
3073 time_t read_timeout_sec_;
3074 time_t read_timeout_usec_;
3075 time_t write_timeout_sec_;
3076 time_t write_timeout_usec_;
3077
3078 std::vector<char> read_buff_;
3079 size_t read_buff_off_ = 0;
3080 size_t read_buff_content_size_ = 0;
3081
3082 static const size_t read_buff_size_ = 1024l * 4;
3083};
3084
3085#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
3086class SSLSocketStream final : public Stream {
3087 public:
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;
3091
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;
3098 socket_t socket() const override;
3099
3100 private:
3101 socket_t sock_;
3102 SSL *ssl_;
3103 time_t read_timeout_sec_;
3104 time_t read_timeout_usec_;
3105 time_t write_timeout_sec_;
3106 time_t write_timeout_usec_;
3107};
3108#endif
3109
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;
3112
3113 const auto interval_usec = CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
3114
3115 // Avoid expensive `steady_clock::now()` call for the first time
3116 if (select_read(sock, 0, interval_usec) > 0) {
3117 return true;
3118 }
3119
3120 const auto start = steady_clock::now() - microseconds{interval_usec};
3121 const auto timeout = seconds{keep_alive_timeout_sec};
3122
3123 while (true) {
3124 if (svr_sock == INVALID_SOCKET) {
3125 break; // Server socket is closed
3126 }
3127
3128 auto val = select_read(sock, 0, interval_usec);
3129 if (val < 0) {
3130 break; // Ssocket error
3131 } else if (val == 0) {
3132 if (steady_clock::now() - start > timeout) {
3133 break; // Timeout
3134 }
3135 } else {
3136 return true; // Ready for read
3137 }
3138 }
3139
3140 return false;
3141}
3142
3143template<typename T>
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);
3147 auto ret = false;
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) {
3154 break;
3155 }
3156 count--;
3157 }
3158 return ret;
3159}
3160
3161template<typename T>
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);
3170 });
3171}
3172
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);
3178}
3179
3180inline int shutdown_socket(socket_t sock) {
3181#ifdef _WIN32
3182 return shutdown(sock, SD_BOTH);
3183#else
3184 return shutdown(sock, SHUT_RDWR);
3185#endif
3186}
3187
3188inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
3189 if (s.size() > 1 && s[0] == '\0') {
3190 auto ret = s;
3191 ret[0] = '@';
3192 return ret;
3193 }
3194 return s;
3195}
3196
3197inline std::string unescape_abstract_namespace_unix_domain(const std::string &s) {
3198 if (s.size() > 1 && s[0] == '@') {
3199 auto ret = s;
3200 ret[0] = '\0';
3201 return ret;
3202 }
3203 return s;
3204}
3205
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) {
3210 // Get address info
3211 const char *node = nullptr;
3212 struct addrinfo hints;
3213 struct addrinfo *result;
3214
3215 memset(&hints, 0, sizeof(struct addrinfo));
3216 hints.ai_socktype = SOCK_STREAM;
3217 hints.ai_protocol = IPPROTO_IP;
3218
3219 if (!ip.empty()) {
3220 node = ip.c_str();
3221 // Ask getaddrinfo to convert IP in c-string to address
3222 hints.ai_family = AF_UNSPEC;
3223 hints.ai_flags = AI_NUMERICHOST;
3224 } else {
3225 if (!host.empty()) {
3226 node = host.c_str();
3227 }
3228 hints.ai_family = address_family;
3229 hints.ai_flags = socket_flags;
3230 }
3231
3232#ifndef _WIN32
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;
3237 }
3238
3239#ifdef SOCK_CLOEXEC
3240 auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC, hints.ai_protocol);
3241#else
3242 auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
3243#endif
3244
3245 if (sock != INVALID_SOCKET) {
3246 sockaddr_un addr{};
3247 addr.sun_family = AF_UNIX;
3248
3249 auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
3250 std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
3251
3252 hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
3253 hints.ai_addrlen = static_cast<socklen_t>(sizeof(addr) - sizeof(addr.sun_path) + addrlen);
3254
3255#ifndef SOCK_CLOEXEC
3256 fcntl(sock, F_SETFD, FD_CLOEXEC);
3257#endif
3258
3259 if (socket_options) {
3260 socket_options(sock);
3261 }
3262
3263 bool dummy;
3264 if (!bind_or_connect(sock, hints, dummy)) {
3265 close_socket(sock);
3266 sock = INVALID_SOCKET;
3267 }
3268 }
3269 return sock;
3270 }
3271#endif
3272
3273 auto service = std::to_string(port);
3274
3275 if (getaddrinfo(node, service.c_str(), &hints, &result)) {
3276#if defined __linux__ && !defined __ANDROID__
3277 res_init();
3278#endif
3279 return INVALID_SOCKET;
3280 }
3281 auto se = detail::scope_exit([&] { freeaddrinfo(result); });
3282
3283 for (auto rp = result; rp; rp = rp->ai_next) {
3284 // Create a socket
3285#ifdef _WIN32
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);
3304 }
3305#else
3306
3307#ifdef SOCK_CLOEXEC
3308 auto sock = socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
3309#else
3310 auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
3311#endif
3312
3313#endif
3314 if (sock == INVALID_SOCKET) {
3315 continue;
3316 }
3317
3318#if !defined _WIN32 && !defined SOCK_CLOEXEC
3319 if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
3320 close_socket(sock);
3321 continue;
3322 }
3323#endif
3324
3325 if (tcp_nodelay) {
3326 auto opt = 1;
3327#ifdef _WIN32
3328 setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<const char *>(&opt), sizeof(opt));
3329#else
3330 setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<const void *>(&opt), sizeof(opt));
3331#endif
3332 }
3333
3334 if (rp->ai_family == AF_INET6) {
3335 auto opt = ipv6_v6only ? 1 : 0;
3336#ifdef _WIN32
3337 setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char *>(&opt), sizeof(opt));
3338#else
3339 setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const void *>(&opt), sizeof(opt));
3340#endif
3341 }
3342
3343 if (socket_options) {
3344 socket_options(sock);
3345 }
3346
3347 // bind or connect
3348 auto quit = false;
3349 if (bind_or_connect(sock, *rp, quit)) {
3350 return sock;
3351 }
3352
3353 close_socket(sock);
3354
3355 if (quit) {
3356 break;
3357 }
3358 }
3359
3360 return INVALID_SOCKET;
3361}
3362
3363inline void set_nonblocking(socket_t sock, bool nonblocking) {
3364#ifdef _WIN32
3365 auto flags = nonblocking ? 1UL : 0UL;
3366 ioctlsocket(sock, FIONBIO, &flags);
3367#else
3368 auto flags = fcntl(sock, F_GETFL, 0);
3369 fcntl(sock, F_SETFL, nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
3370#endif
3371}
3372
3373inline bool is_connection_error() {
3374#ifdef _WIN32
3375 return WSAGetLastError() != WSAEWOULDBLOCK;
3376#else
3377 return errno != EINPROGRESS;
3378#endif
3379}
3380
3381inline bool bind_ip_address(socket_t sock, const std::string &host) {
3382 struct addrinfo hints;
3383 struct addrinfo *result;
3384
3385 memset(&hints, 0, sizeof(struct addrinfo));
3386 hints.ai_family = AF_UNSPEC;
3387 hints.ai_socktype = SOCK_STREAM;
3388 hints.ai_protocol = 0;
3389
3390 if (getaddrinfo(host.c_str(), "0", &hints, &result)) {
3391 return false;
3392 }
3393 auto se = detail::scope_exit([&] { freeaddrinfo(result); });
3394
3395 auto ret = false;
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))) {
3399 ret = true;
3400 break;
3401 }
3402 }
3403
3404 return ret;
3405}
3406
3407#if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
3408#define USE_IF2IP
3409#endif
3410
3411#ifdef USE_IF2IP
3412inline std::string if2ip(int address_family, const std::string &ifn) {
3413 struct ifaddrs *ifap;
3414 getifaddrs(&ifap);
3415 auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
3416
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);
3426 }
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)) {
3432 // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
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);
3436 } else {
3437 return std::string(buf, INET6_ADDRSTRLEN);
3438 }
3439 }
3440 }
3441 }
3442 }
3443 }
3444 return addr_candidate;
3445}
3446#endif
3447
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()) {
3457#ifdef USE_IF2IP
3458 auto ip_from_if = if2ip(address_family, intf);
3459 if (ip_from_if.empty()) {
3460 ip_from_if = intf;
3461 }
3462 if (!bind_ip_address(sock2, ip_from_if)) {
3463 error = Error::BindIPAddress;
3464 return false;
3465 }
3466#endif
3467 }
3468
3469 set_nonblocking(sock2, true);
3470
3471 auto ret = ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
3472
3473 if (ret < 0) {
3474 if (is_connection_error()) {
3475 error = Error::Connection;
3476 return false;
3477 }
3478 error = wait_until_socket_is_ready(sock2, connection_timeout_sec, connection_timeout_usec);
3479 if (error != Error::Success) {
3480 if (error == Error::ConnectionTimeout) {
3481 quit = true;
3482 }
3483 return false;
3484 }
3485 }
3486
3487 set_nonblocking(sock2, false);
3488
3489 {
3490#ifdef _WIN32
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));
3493#else
3494 timeval tv;
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));
3498#endif
3499 }
3500 {
3501
3502#ifdef _WIN32
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));
3505#else
3506 timeval tv;
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));
3510#endif
3511 }
3512
3513 error = Error::Success;
3514 return true;
3515 });
3516
3517 if (sock != INVALID_SOCKET) {
3518 error = Error::Success;
3519 } else {
3520 if (error == Error::Success) {
3521 error = Error::Connection;
3522 }
3523 }
3524
3525 return sock;
3526}
3527
3528inline bool get_ip_and_port(const struct sockaddr_storage &addr, socklen_t addr_len, std::string &ip, int &port) {
3529 if (addr.ss_family == AF_INET) {
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);
3533 } else {
3534 return false;
3535 }
3536
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)) {
3540 return false;
3541 }
3542
3543 ip = ipstr.data();
3544 return true;
3545}
3546
3547inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
3548 struct sockaddr_storage addr;
3549 socklen_t addr_len = sizeof(addr);
3550 if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr), &addr_len)) {
3551 get_ip_and_port(addr, addr_len, ip, port);
3552 }
3553}
3554
3555inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
3556 struct sockaddr_storage addr;
3557 socklen_t addr_len = sizeof(addr);
3558
3559 if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr), &addr_len)) {
3560#ifndef _WIN32
3561 if (addr.ss_family == AF_UNIX) {
3562#if defined(__linux__)
3563 struct ucred ucred;
3564 socklen_t len = sizeof(ucred);
3565 if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
3566 port = ucred.pid;
3567 }
3568#elif defined(SOL_LOCAL) && defined(SO_PEERPID) // __APPLE__
3569 pid_t pid;
3570 socklen_t len = sizeof(pid);
3571 if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
3572 port = pid;
3573 }
3574#endif
3575 return;
3576 }
3577#endif
3578 get_ip_and_port(addr, addr_len, ip, port);
3579 }
3580}
3581
3582inline constexpr unsigned int str2tag_core(const char *s, size_t l, unsigned int h) {
3583 return (l == 0) ? h
3584 : str2tag_core(
3585 s + 1, l - 1,
3586 // Unsets the 6 high bits of h, therefore no overflow happens
3587 (((std::numeric_limits<unsigned int>::max)() >> 6) & h * 33) ^ static_cast<unsigned char>(*s));
3588}
3589
3590inline unsigned int str2tag(const std::string &s) { return str2tag_core(s.data(), s.size(), 0); }
3591
3592namespace udl {
3593
3594inline constexpr unsigned int operator""_t(const char *s, size_t l) { return str2tag_core(s, l, 0); }
3595
3596} // namespace udl
3597
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);
3601
3602 auto it = user_data.find(ext);
3603 if (it != user_data.end()) {
3604 return it->second;
3605 }
3606
3607 using udl::operator""_t;
3608
3609 switch (str2tag(ext)) {
3610 default:
3611 return default_content_type;
3612
3613 case "css"_t:
3614 return "text/css";
3615 case "csv"_t:
3616 return "text/csv";
3617 case "htm"_t:
3618 case "html"_t:
3619 return "text/html";
3620 case "js"_t:
3621 case "mjs"_t:
3622 return "text/javascript";
3623 case "txt"_t:
3624 return "text/plain";
3625 case "vtt"_t:
3626 return "text/vtt";
3627
3628 case "apng"_t:
3629 return "image/apng";
3630 case "avif"_t:
3631 return "image/avif";
3632 case "bmp"_t:
3633 return "image/bmp";
3634 case "gif"_t:
3635 return "image/gif";
3636 case "png"_t:
3637 return "image/png";
3638 case "svg"_t:
3639 return "image/svg+xml";
3640 case "webp"_t:
3641 return "image/webp";
3642 case "ico"_t:
3643 return "image/x-icon";
3644 case "tif"_t:
3645 return "image/tiff";
3646 case "tiff"_t:
3647 return "image/tiff";
3648 case "jpg"_t:
3649 case "jpeg"_t:
3650 return "image/jpeg";
3651
3652 case "mp4"_t:
3653 return "video/mp4";
3654 case "mpeg"_t:
3655 return "video/mpeg";
3656 case "webm"_t:
3657 return "video/webm";
3658
3659 case "mp3"_t:
3660 return "audio/mp3";
3661 case "mpga"_t:
3662 return "audio/mpeg";
3663 case "weba"_t:
3664 return "audio/webm";
3665 case "wav"_t:
3666 return "audio/wave";
3667
3668 case "otf"_t:
3669 return "font/otf";
3670 case "ttf"_t:
3671 return "font/ttf";
3672 case "woff"_t:
3673 return "font/woff";
3674 case "woff2"_t:
3675 return "font/woff2";
3676
3677 case "7z"_t:
3678 return "application/x-7z-compressed";
3679 case "atom"_t:
3680 return "application/atom+xml";
3681 case "pdf"_t:
3682 return "application/pdf";
3683 case "json"_t:
3684 return "application/json";
3685 case "rss"_t:
3686 return "application/rss+xml";
3687 case "tar"_t:
3688 return "application/x-tar";
3689 case "xht"_t:
3690 case "xhtml"_t:
3691 return "application/xhtml+xml";
3692 case "xslt"_t:
3693 return "application/xslt+xml";
3694 case "xml"_t:
3695 return "application/xml";
3696 case "gz"_t:
3697 return "application/gzip";
3698 case "zip"_t:
3699 return "application/zip";
3700 case "wasm"_t:
3701 return "application/wasm";
3702 }
3703}
3704
3705inline bool can_compress_content_type(const std::string &content_type) {
3706 using udl::operator""_t;
3707
3708 auto tag = str2tag(content_type);
3709
3710 switch (tag) {
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:
3717 return true;
3718
3719 case "text/event-stream"_t:
3720 return false;
3721
3722 default:
3723 return !content_type.rfind("text/", 0);
3724 }
3725}
3726
3727inline EncodingType encoding_type(const Request &req, const Response &res) {
3728 auto ret = detail::can_compress_content_type(res.get_header_value("Content-Type"));
3729 if (!ret) {
3730 return EncodingType::None;
3731 }
3732
3733 const auto &s = req.get_header_value("Accept-Encoding");
3734 (void) (s);
3735
3736#ifdef CPPHTTPLIB_BROTLI_SUPPORT
3737 // TODO: 'Accept-Encoding' has br, not br;q=0
3738 ret = s.find("br") != std::string::npos;
3739 if (ret) {
3740 return EncodingType::Brotli;
3741 }
3742#endif
3743
3744#ifdef CPPHTTPLIB_ZLIB_SUPPORT
3745 // TODO: 'Accept-Encoding' has gzip, not gzip;q=0
3746 ret = s.find("gzip") != std::string::npos;
3747 if (ret) {
3748 return EncodingType::Gzip;
3749 }
3750#endif
3751
3752 return EncodingType::None;
3753}
3754
3755inline bool nocompressor::compress(const char *data, size_t data_length, bool /*last*/, Callback callback) {
3756 if (!data_length) {
3757 return true;
3758 }
3759 return callback(data, data_length);
3760}
3761
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;
3768
3769 is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY) == Z_OK;
3770}
3771
3772inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
3773
3774inline bool gzip_compressor::compress(const char *data, size_t data_length, bool last, Callback callback) {
3775 assert(is_valid_);
3776
3777 do {
3778 constexpr size_t max_avail_in = (std::numeric_limits<decltype(strm_.avail_in)>::max)();
3779
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));
3782
3783 data_length -= strm_.avail_in;
3784 data += strm_.avail_in;
3785
3786 auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
3787 auto ret = Z_OK;
3788
3789 std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
3790 do {
3791 strm_.avail_out = static_cast<uInt>(buff.size());
3792 strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
3793
3794 ret = deflate(&strm_, flush);
3795 if (ret == Z_STREAM_ERROR) {
3796 return false;
3797 }
3798
3799 if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
3800 return false;
3801 }
3802 } while (strm_.avail_out == 0);
3803
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);
3807
3808 return true;
3809}
3810
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;
3816
3817 // 15 is the value of wbits, which should be at the maximum possible value
3818 // to ensure that any gzip stream can be decoded. The offset of 32 specifies
3819 // that the stream type should be automatically detected either gzip or
3820 // deflate.
3821 is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
3822}
3823
3824inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
3825
3826inline bool gzip_decompressor::is_valid() const { return is_valid_; }
3827
3828inline bool gzip_decompressor::decompress(const char *data, size_t data_length, Callback callback) {
3829 assert(is_valid_);
3830
3831 auto ret = Z_OK;
3832
3833 do {
3834 constexpr size_t max_avail_in = (std::numeric_limits<decltype(strm_.avail_in)>::max)();
3835
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));
3838
3839 data_length -= strm_.avail_in;
3840 data += strm_.avail_in;
3841
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());
3846
3847 ret = inflate(&strm_, Z_NO_FLUSH);
3848
3849 assert(ret != Z_STREAM_ERROR);
3850 switch (ret) {
3851 case Z_NEED_DICT:
3852 case Z_DATA_ERROR:
3853 case Z_MEM_ERROR:
3854 inflateEnd(&strm_);
3855 return false;
3856 }
3857
3858 if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
3859 return false;
3860 }
3861 }
3862
3863 if (ret != Z_OK && ret != Z_STREAM_END) {
3864 return false;
3865 }
3866
3867 } while (data_length > 0);
3868
3869 return true;
3870}
3871#endif
3872
3873#ifdef CPPHTTPLIB_BROTLI_SUPPORT
3874inline brotli_compressor::brotli_compressor() { state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr); }
3875
3876inline brotli_compressor::~brotli_compressor() { BrotliEncoderDestroyInstance(state_); }
3877
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{};
3880
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);
3884
3885 for (;;) {
3886 if (last) {
3887 if (BrotliEncoderIsFinished(state_)) {
3888 break;
3889 }
3890 } else {
3891 if (!available_in) {
3892 break;
3893 }
3894 }
3895
3896 auto available_out = buff.size();
3897 auto next_out = buff.data();
3898
3899 if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in, &available_out, &next_out, nullptr)) {
3900 return false;
3901 }
3902
3903 auto output_bytes = buff.size() - available_out;
3904 if (output_bytes) {
3905 callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
3906 }
3907 }
3908
3909 return true;
3910}
3911
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;
3915}
3916
3917inline brotli_decompressor::~brotli_decompressor() {
3918 if (decoder_s) {
3919 BrotliDecoderDestroyInstance(decoder_s);
3920 }
3921}
3922
3923inline bool brotli_decompressor::is_valid() const { return decoder_s; }
3924
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) {
3927 return 0;
3928 }
3929
3930 auto next_in = reinterpret_cast<const uint8_t *>(data);
3931 size_t avail_in = data_length;
3932 size_t total_out;
3933
3934 decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
3935
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();
3940
3941 decoder_r = BrotliDecoderDecompressStream(decoder_s, &avail_in, &next_in, &avail_out,
3942 reinterpret_cast<uint8_t **>(&next_out), &total_out);
3943
3944 if (decoder_r == BROTLI_DECODER_RESULT_ERROR) {
3945 return false;
3946 }
3947
3948 if (!callback(buff.data(), buff.size() - avail_out)) {
3949 return false;
3950 }
3951 }
3952
3953 return decoder_r == BROTLI_DECODER_RESULT_SUCCESS || decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
3954}
3955#endif
3956
3957inline bool has_header(const Headers &headers, const std::string &key) { return headers.find(key) != headers.end(); }
3958
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();
3965 }
3966 return def;
3967}
3968
3969template<typename T> inline bool parse_header(const char *beg, const char *end, T fn) {
3970 // Skip trailing spaces and tabs.
3971 while (beg < end && is_space_or_tab(end[-1])) {
3972 end--;
3973 }
3974
3975 auto p = beg;
3976 while (p < end && *p != ':') {
3977 p++;
3978 }
3979
3980 if (p == end) {
3981 return false;
3982 }
3983
3984 auto key_end = p;
3985
3986 if (*p++ != ':') {
3987 return false;
3988 }
3989
3990 while (p < end && is_space_or_tab(*p)) {
3991 p++;
3992 }
3993
3994 if (p <= end) {
3995 auto key_len = key_end - beg;
3996 if (!key_len) {
3997 return false;
3998 }
3999
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);
4002
4003 // NOTE: From RFC 9110:
4004 // Field values containing CR, LF, or NUL characters are
4005 // invalid and dangerous, due to the varying ways that
4006 // implementations might parse and interpret those
4007 // characters; a recipient of CR, LF, or NUL within a field
4008 // value MUST either reject the message or replace each of
4009 // those characters with SP before further processing or
4010 // forwarding of that message.
4011 static const std::string CR_LF_NUL("\r\n\0", 3);
4012 if (val.find_first_of(CR_LF_NUL) != std::string::npos) {
4013 return false;
4014 }
4015
4016 fn(key, val);
4017 return true;
4018 }
4019
4020 return false;
4021}
4022
4023inline bool read_headers(Stream &strm, Headers &headers) {
4024 const auto bufsiz = 2048;
4025 char buf[bufsiz];
4026 stream_line_reader line_reader(strm, buf, bufsiz);
4027
4028 for (;;) {
4029 if (!line_reader.getline()) {
4030 return false;
4031 }
4032
4033 // Check if the line ends with CRLF.
4034 auto line_terminator_len = 2;
4035 if (line_reader.end_with_crlf()) {
4036 // Blank line indicates end of headers.
4037 if (line_reader.size() == 2) {
4038 break;
4039 }
4040 } else {
4041#ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
4042 // Blank line indicates end of headers.
4043 if (line_reader.size() == 1) {
4044 break;
4045 }
4046 line_terminator_len = 1;
4047#else
4048 continue; // Skip invalid line.
4049#endif
4050 }
4051
4052 if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) {
4053 return false;
4054 }
4055
4056 // Exclude line terminator
4057 auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
4058
4059 if (!parse_header(line_reader.ptr(), end,
4060 [&](const std::string &key, std::string &val) { headers.emplace(key, val); })) {
4061 return false;
4062 }
4063 }
4064
4065 return true;
4066}
4067
4068inline bool read_content_with_length(Stream &strm, uint64_t len, Progress progress, ContentReceiverWithProgress out) {
4069 char buf[CPPHTTPLIB_RECV_BUFSIZ];
4070
4071 uint64_t r = 0;
4072 while (r < len) {
4073 auto read_len = static_cast<size_t>(len - r);
4074 auto n = strm.read(buf, (std::min) (read_len, CPPHTTPLIB_RECV_BUFSIZ));
4075 if (n <= 0) {
4076 return false;
4077 }
4078
4079 if (!out(buf, static_cast<size_t>(n), r, len)) {
4080 return false;
4081 }
4082 r += static_cast<uint64_t>(n);
4083
4084 if (progress) {
4085 if (!progress(r, len)) {
4086 return false;
4087 }
4088 }
4089 }
4090
4091 return true;
4092}
4093
4094inline void skip_content_with_length(Stream &strm, uint64_t len) {
4095 char buf[CPPHTTPLIB_RECV_BUFSIZ];
4096 uint64_t r = 0;
4097 while (r < len) {
4098 auto read_len = static_cast<size_t>(len - r);
4099 auto n = strm.read(buf, (std::min) (read_len, CPPHTTPLIB_RECV_BUFSIZ));
4100 if (n <= 0) {
4101 return;
4102 }
4103 r += static_cast<uint64_t>(n);
4104 }
4105}
4106
4107inline bool read_content_without_length(Stream &strm, ContentReceiverWithProgress out) {
4108 char buf[CPPHTTPLIB_RECV_BUFSIZ];
4109 uint64_t r = 0;
4110 for (;;) {
4111 auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
4112 if (n <= 0) {
4113 return true;
4114 }
4115
4116 if (!out(buf, static_cast<size_t>(n), r, 0)) {
4117 return false;
4118 }
4119 r += static_cast<uint64_t>(n);
4120 }
4121
4122 return true;
4123}
4124
4125template<typename T> inline bool read_content_chunked(Stream &strm, T &x, ContentReceiverWithProgress out) {
4126 const auto bufsiz = 16;
4127 char buf[bufsiz];
4128
4129 stream_line_reader line_reader(strm, buf, bufsiz);
4130
4131 if (!line_reader.getline()) {
4132 return false;
4133 }
4134
4135 unsigned long chunk_len;
4136 while (true) {
4137 char *end_ptr;
4138
4139 chunk_len = std::strtoul(line_reader.ptr(), &end_ptr, 16);
4140
4141 if (end_ptr == line_reader.ptr()) {
4142 return false;
4143 }
4144 if (chunk_len == ULONG_MAX) {
4145 return false;
4146 }
4147
4148 if (chunk_len == 0) {
4149 break;
4150 }
4151
4152 if (!read_content_with_length(strm, chunk_len, nullptr, out)) {
4153 return false;
4154 }
4155
4156 if (!line_reader.getline()) {
4157 return false;
4158 }
4159
4160 if (strcmp(line_reader.ptr(), "\r\n") != 0) {
4161 return false;
4162 }
4163
4164 if (!line_reader.getline()) {
4165 return false;
4166 }
4167 }
4168
4169 assert(chunk_len == 0);
4170
4171 // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentiones "The chunked
4172 // transfer coding is complete when a chunk with a chunk-size of zero is
4173 // received, possibly followed by a trailer section, and finally terminated by
4174 // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
4175 //
4176 // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
4177 // does't care for the existence of the final CRLF. In other words, it seems
4178 // to be ok whether the final CRLF exists or not in the chunked data.
4179 // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
4180 //
4181 // According to the reference code in RFC 9112, cpp-htpplib now allows
4182 // chuncked transfer coding data without the final CRLF.
4183 if (!line_reader.getline()) {
4184 return true;
4185 }
4186
4187 while (strcmp(line_reader.ptr(), "\r\n") != 0) {
4188 if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) {
4189 return false;
4190 }
4191
4192 // Exclude line terminator
4193 constexpr auto line_terminator_len = 2;
4194 auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
4195
4196 parse_header(line_reader.ptr(), end,
4197 [&](const std::string &key, const std::string &val) { x.headers.emplace(key, val); });
4198
4199 if (!line_reader.getline()) {
4200 return false;
4201 }
4202 }
4203
4204 return true;
4205}
4206
4207inline bool is_chunked_transfer_encoding(const Headers &headers) {
4208 return case_ignore::equal(get_header_value(headers, "Transfer-Encoding", "", 0), "chunked");
4209}
4210
4211template<typename T, typename U>
4212bool prepare_content_receiver(T &x, int &status, ContentReceiverWithProgress receiver, bool decompress, U callback) {
4213 if (decompress) {
4214 std::string encoding = x.get_header_value("Content-Encoding");
4215 std::unique_ptr<decompressor> decompressor;
4216
4217 if (encoding == "gzip" || encoding == "deflate") {
4218#ifdef CPPHTTPLIB_ZLIB_SUPPORT
4219 decompressor = detail::make_unique<gzip_decompressor>();
4220#else
4221 status = StatusCode::UnsupportedMediaType_415;
4222 return false;
4223#endif
4224 } else if (encoding.find("br") != std::string::npos) {
4225#ifdef CPPHTTPLIB_BROTLI_SUPPORT
4226 decompressor = detail::make_unique<brotli_decompressor>();
4227#else
4228 status = StatusCode::UnsupportedMediaType_415;
4229 return false;
4230#endif
4231 }
4232
4233 if (decompressor) {
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); });
4238 };
4239 return callback(std::move(out));
4240 } else {
4241 status = StatusCode::InternalServerError_500;
4242 return false;
4243 }
4244 }
4245 }
4246
4247 ContentReceiverWithProgress out = [&](const char *buf, size_t n, uint64_t off, uint64_t len) {
4248 return receiver(buf, n, off, len);
4249 };
4250 return callback(std::move(out));
4251}
4252
4253template<typename T>
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) {
4258 auto ret = true;
4259 auto exceed_payload_max_length = false;
4260
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);
4265 } else {
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);
4270 ret = false;
4271 } else if (len > 0) {
4272 ret = read_content_with_length(strm, len, std::move(progress), out);
4273 }
4274 }
4275
4276 if (!ret) {
4277 status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413 : StatusCode::BadRequest_400;
4278 }
4279 return ret;
4280 });
4281}
4282
4283inline ssize_t write_request_line(Stream &strm, const std::string &method, const std::string &path) {
4284 std::string s = method;
4285 s += " ";
4286 s += path;
4287 s += " HTTP/1.1\r\n";
4288 return strm.write(s.data(), s.size());
4289}
4290
4291inline ssize_t write_response_line(Stream &strm, int status) {
4292 std::string s = "HTTP/1.1 ";
4293 s += std::to_string(status);
4294 s += " ";
4295 s += httplib::status_message(status);
4296 s += "\r\n";
4297 return strm.write(s.data(), s.size());
4298}
4299
4300inline ssize_t write_headers(Stream &strm, const Headers &headers) {
4301 ssize_t write_len = 0;
4302 for (const auto &x : headers) {
4303 std::string s;
4304 s = x.first;
4305 s += ": ";
4306 s += x.second;
4307 s += "\r\n";
4308
4309 auto len = strm.write(s.data(), s.size());
4310 if (len < 0) {
4311 return len;
4312 }
4313 write_len += len;
4314 }
4315 auto len = strm.write("\r\n");
4316 if (len < 0) {
4317 return len;
4318 }
4319 write_len += len;
4320 return write_len;
4321}
4322
4323inline bool write_data(Stream &strm, const char *d, size_t l) {
4324 size_t offset = 0;
4325 while (offset < l) {
4326 auto length = strm.write(d + offset, l - offset);
4327 if (length < 0) {
4328 return false;
4329 }
4330 offset += static_cast<size_t>(length);
4331 }
4332 return true;
4333}
4334
4335template<typename T>
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;
4339 auto ok = true;
4340 DataSink data_sink;
4341
4342 data_sink.write = [&](const char *d, size_t l) -> bool {
4343 if (ok) {
4344 if (strm.is_writable() && write_data(strm, d, l)) {
4345 offset += l;
4346 } else {
4347 ok = false;
4348 }
4349 }
4350 return ok;
4351 };
4352
4353 data_sink.is_writable = [&]() -> bool { return strm.is_writable(); };
4354
4355 while (offset < end_offset && !is_shutting_down()) {
4356 if (!strm.is_writable()) {
4357 error = Error::Write;
4358 return false;
4359 } else if (!content_provider(offset, end_offset - offset, data_sink)) {
4360 error = Error::Canceled;
4361 return false;
4362 } else if (!ok) {
4363 error = Error::Write;
4364 return false;
4365 }
4366 }
4367
4368 error = Error::Success;
4369 return true;
4370}
4371
4372template<typename T>
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);
4377}
4378
4379template<typename T>
4380inline bool write_content_without_length(Stream &strm, const ContentProvider &content_provider,
4381 const T &is_shutting_down) {
4382 size_t offset = 0;
4383 auto data_available = true;
4384 auto ok = true;
4385 DataSink data_sink;
4386
4387 data_sink.write = [&](const char *d, size_t l) -> bool {
4388 if (ok) {
4389 offset += l;
4390 if (!strm.is_writable() || !write_data(strm, d, l)) {
4391 ok = false;
4392 }
4393 }
4394 return ok;
4395 };
4396
4397 data_sink.is_writable = [&]() -> bool { return strm.is_writable(); };
4398
4399 data_sink.done = [&](void) { data_available = false; };
4400
4401 while (data_available && !is_shutting_down()) {
4402 if (!strm.is_writable()) {
4403 return false;
4404 } else if (!content_provider(offset, 0, data_sink)) {
4405 return false;
4406 } else if (!ok) {
4407 return false;
4408 }
4409 }
4410 return true;
4411}
4412
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) {
4416 size_t offset = 0;
4417 auto data_available = true;
4418 auto ok = true;
4419 DataSink data_sink;
4420
4421 data_sink.write = [&](const char *d, size_t l) -> bool {
4422 if (ok) {
4423 data_available = l > 0;
4424 offset += l;
4425
4426 std::string payload;
4427 if (compressor.compress(d, l, false, [&](const char *data, size_t data_len) {
4428 payload.append(data, data_len);
4429 return true;
4430 })) {
4431 if (!payload.empty()) {
4432 // Emit chunked response header and footer for each chunk
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())) {
4435 ok = false;
4436 }
4437 }
4438 } else {
4439 ok = false;
4440 }
4441 }
4442 return ok;
4443 };
4444
4445 data_sink.is_writable = [&]() -> bool { return strm.is_writable(); };
4446
4447 auto done_with_trailer = [&](const Headers *trailer) {
4448 if (!ok) {
4449 return;
4450 }
4451
4452 data_available = false;
4453
4454 std::string payload;
4455 if (!compressor.compress(nullptr, 0, true, [&](const char *data, size_t data_len) {
4456 payload.append(data, data_len);
4457 return true;
4458 })) {
4459 ok = false;
4460 return;
4461 }
4462
4463 if (!payload.empty()) {
4464 // Emit chunked response header and footer for each chunk
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())) {
4467 ok = false;
4468 return;
4469 }
4470 }
4471
4472 static const std::string done_marker("0\r\n");
4473 if (!write_data(strm, done_marker.data(), done_marker.size())) {
4474 ok = false;
4475 }
4476
4477 // Trailer
4478 if (trailer) {
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())) {
4482 ok = false;
4483 }
4484 }
4485 }
4486
4487 static const std::string crlf("\r\n");
4488 if (!write_data(strm, crlf.data(), crlf.size())) {
4489 ok = false;
4490 }
4491 };
4492
4493 data_sink.done = [&](void) { done_with_trailer(nullptr); };
4494
4495 data_sink.done_with_trailer = [&](const Headers &trailer) { done_with_trailer(&trailer); };
4496
4497 while (data_available && !is_shutting_down()) {
4498 if (!strm.is_writable()) {
4499 error = Error::Write;
4500 return false;
4501 } else if (!content_provider(offset, 0, data_sink)) {
4502 error = Error::Canceled;
4503 return false;
4504 } else if (!ok) {
4505 error = Error::Write;
4506 return false;
4507 }
4508 }
4509
4510 error = Error::Success;
4511 return true;
4512}
4513
4514template<typename T, typename U>
4515inline bool write_content_chunked(Stream &strm, const ContentProvider &content_provider, const T &is_shutting_down,
4516 U &compressor) {
4517 auto error = Error::Success;
4518 return write_content_chunked(strm, content_provider, is_shutting_down, compressor, error);
4519}
4520
4521template<typename T>
4522inline bool redirect(T &cli, Request &req, Response &res, const std::string &path, const std::string &location,
4523 Error &error) {
4524 Request new_req = req;
4525 new_req.path = path;
4526 new_req.redirect_count_ -= 1;
4527
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();
4532 }
4533
4534 Response new_res;
4535
4536 auto ret = cli.send(new_req, new_res, error);
4537 if (ret) {
4538 req = new_req;
4539 res = new_res;
4540
4541 if (res.location.empty()) {
4542 res.location = location;
4543 }
4544 }
4545 return ret;
4546}
4547
4548inline std::string params_to_query_str(const Params &params) {
4549 std::string query;
4550
4551 for (auto it = params.begin(); it != params.end(); ++it) {
4552 if (it != params.begin()) {
4553 query += "&";
4554 }
4555 query += it->first;
4556 query += "=";
4557 query += encode_query_param(it->second);
4558 }
4559 return query;
4560}
4561
4562inline void parse_query_text(const char *data, std::size_t size, Params &params) {
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()) {
4567 return;
4568 }
4569 cache.insert(std::move(kv));
4570
4571 std::string key;
4572 std::string val;
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);
4577 });
4578
4579 if (!key.empty()) {
4580 params.emplace(decode_url(key, true), decode_url(val, true));
4581 }
4582 });
4583}
4584
4585inline void parse_query_text(const std::string &s, Params &params) { parse_query_text(s.data(), s.size(), params); }
4586
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) {
4591 return false;
4592 }
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();
4597}
4598
4599inline void parse_disposition_params(const std::string &s, Params &params) {
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()) {
4604 return;
4605 }
4606 cache.insert(kv);
4607
4608 std::string key;
4609 std::string val;
4610 split(b, e, '=', [&](const char *b2, const char *e2) {
4611 if (key.empty()) {
4612 key.assign(b2, e2);
4613 } else {
4614 val.assign(b2, e2);
4615 }
4616 });
4617
4618 if (!key.empty()) {
4619 params.emplace(trim_double_quotes_copy((key)), trim_double_quotes_copy((val)));
4620 }
4621 });
4622}
4623
4624#ifdef CPPHTTPLIB_NO_EXCEPTIONS
4625inline bool parse_range_header(const std::string &s, Ranges &ranges) {
4626#else
4627inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
4628#endif
4629 auto is_valid = [](const std::string &str) {
4630 return std::all_of(str.cbegin(), str.cend(), [](unsigned char c) { return std::isdigit(c); });
4631 };
4632
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) {
4639 return;
4640 }
4641
4642 const auto it = std::find(b, e, '-');
4643 if (it == e) {
4644 all_valid_ranges = false;
4645 return;
4646 }
4647
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;
4652 return;
4653 }
4654
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;
4659 return;
4660 }
4661
4662 ranges.emplace_back(first, last);
4663 });
4664 return all_valid_ranges && !ranges.empty();
4665 }
4666 return false;
4667#ifdef CPPHTTPLIB_NO_EXCEPTIONS
4668}
4669#else
4670} catch (...) {
4671 return false;
4672}
4673#endif
4674
4675class MultipartFormDataParser {
4676 public:
4677 MultipartFormDataParser() = default;
4678
4679 void set_boundary(std::string &&boundary) {
4680 boundary_ = boundary;
4681 dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
4682 crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
4683 }
4684
4685 bool is_valid() const { return is_valid_; }
4686
4687 bool parse(const char *buf, size_t n, const ContentReceiver &content_callback,
4688 const MultipartContentHeader &header_callback) {
4689 buf_append(buf, n);
4690
4691 while (buf_size() > 0) {
4692 switch (state_) {
4693 case 0: { // Initial boundary
4694 buf_erase(buf_find(dash_boundary_crlf_));
4695 if (dash_boundary_crlf_.size() > buf_size()) {
4696 return true;
4697 }
4698 if (!buf_start_with(dash_boundary_crlf_)) {
4699 return false;
4700 }
4701 buf_erase(dash_boundary_crlf_.size());
4702 state_ = 1;
4703 break;
4704 }
4705 case 1: { // New entry
4706 clear_file_info();
4707 state_ = 2;
4708 break;
4709 }
4710 case 2: { // Headers
4711 auto pos = buf_find(crlf_);
4712 if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) {
4713 return false;
4714 }
4715 while (pos < buf_size()) {
4716 // Empty line
4717 if (pos == 0) {
4718 if (!header_callback(file_)) {
4719 is_valid_ = false;
4720 return false;
4721 }
4722 buf_erase(crlf_.size());
4723 state_ = 3;
4724 break;
4725 }
4726
4727 const auto header = buf_head(pos);
4728
4729 if (!parse_header(header.data(), header.data() + header.size(),
4730 [&](const std::string &, const std::string &) {})) {
4731 is_valid_ = false;
4732 return false;
4733 }
4734
4735 static const std::string header_content_type = "Content-Type:";
4736
4737 if (start_with_case_ignore(header, header_content_type)) {
4738 file_.content_type = trim_copy(header.substr(header_content_type.size()));
4739 } else {
4740 static const std::regex re_content_disposition(R"~(^Content-Disposition:\s*form-data;\s*(.*)$)~",
4741 std::regex_constants::icase);
4742
4743 std::smatch m;
4744 if (std::regex_match(header, m, re_content_disposition)) {
4745 Params params;
4746 parse_disposition_params(m[1], params);
4747
4748 auto it = params.find("name");
4749 if (it != params.end()) {
4750 file_.name = it->second;
4751 } else {
4752 is_valid_ = false;
4753 return false;
4754 }
4755
4756 it = params.find("filename");
4757 if (it != params.end()) {
4758 file_.filename = it->second;
4759 }
4760
4761 it = params.find("filename*");
4762 if (it != params.end()) {
4763 // Only allow UTF-8 enconnding...
4764 static const std::regex re_rfc5987_encoding(R"~(^UTF-8''(.+?)$)~", std::regex_constants::icase);
4765
4766 std::smatch m2;
4767 if (std::regex_match(it->second, m2, re_rfc5987_encoding)) {
4768 file_.filename = decode_url(m2[1], false); // override...
4769 } else {
4770 is_valid_ = false;
4771 return false;
4772 }
4773 }
4774 }
4775 }
4776 buf_erase(pos + crlf_.size());
4777 pos = buf_find(crlf_);
4778 }
4779 if (state_ != 3) {
4780 return true;
4781 }
4782 break;
4783 }
4784 case 3: { // Body
4785 if (crlf_dash_boundary_.size() > buf_size()) {
4786 return true;
4787 }
4788 auto pos = buf_find(crlf_dash_boundary_);
4789 if (pos < buf_size()) {
4790 if (!content_callback(buf_data(), pos)) {
4791 is_valid_ = false;
4792 return false;
4793 }
4794 buf_erase(pos + crlf_dash_boundary_.size());
4795 state_ = 4;
4796 } else {
4797 auto len = buf_size() - crlf_dash_boundary_.size();
4798 if (len > 0) {
4799 if (!content_callback(buf_data(), len)) {
4800 is_valid_ = false;
4801 return false;
4802 }
4803 buf_erase(len);
4804 }
4805 return true;
4806 }
4807 break;
4808 }
4809 case 4: { // Boundary
4810 if (crlf_.size() > buf_size()) {
4811 return true;
4812 }
4813 if (buf_start_with(crlf_)) {
4814 buf_erase(crlf_.size());
4815 state_ = 1;
4816 } else {
4817 if (dash_.size() > buf_size()) {
4818 return true;
4819 }
4820 if (buf_start_with(dash_)) {
4821 buf_erase(dash_.size());
4822 is_valid_ = true;
4823 buf_erase(buf_size()); // Remove epilogue
4824 } else {
4825 return true;
4826 }
4827 }
4828 break;
4829 }
4830 }
4831 }
4832
4833 return true;
4834 }
4835
4836 private:
4837 void clear_file_info() {
4838 file_.name.clear();
4839 file_.filename.clear();
4840 file_.content_type.clear();
4841 }
4842
4843 bool start_with_case_ignore(const std::string &a, const std::string &b) const {
4844 if (a.size() < b.size()) {
4845 return false;
4846 }
4847 for (size_t i = 0; i < b.size(); i++) {
4848 if (case_ignore::to_lower(a[i]) != case_ignore::to_lower(b[i])) {
4849 return false;
4850 }
4851 }
4852 return true;
4853 }
4854
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_;
4860
4861 size_t state_ = 0;
4862 bool is_valid_ = false;
4863 MultipartFormData file_;
4864
4865 // Buffer
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()) {
4868 return false;
4869 }
4870 for (size_t i = 0; i < b.size(); i++) {
4871 if (a[i + spos] != b[i]) {
4872 return false;
4873 }
4874 }
4875 return true;
4876 }
4877
4878 size_t buf_size() const { return buf_epos_ - buf_spos_; }
4879
4880 const char *buf_data() const { return &buf_[buf_spos_]; }
4881
4882 std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
4883
4884 bool buf_start_with(const std::string &s) const { return start_with(buf_, buf_spos_, buf_epos_, s); }
4885
4886 size_t buf_find(const std::string &s) const {
4887 auto c = s.front();
4888
4889 size_t off = buf_spos_;
4890 while (off < buf_epos_) {
4891 auto pos = off;
4892 while (true) {
4893 if (pos == buf_epos_) {
4894 return buf_size();
4895 }
4896 if (buf_[pos] == c) {
4897 break;
4898 }
4899 pos++;
4900 }
4901
4902 auto remaining_size = buf_epos_ - pos;
4903 if (s.size() > remaining_size) {
4904 return buf_size();
4905 }
4906
4907 if (start_with(buf_, pos, buf_epos_, s)) {
4908 return pos - buf_spos_;
4909 }
4910
4911 off = pos + 1;
4912 }
4913
4914 return buf_size();
4915 }
4916
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];
4922 }
4923 }
4924 buf_spos_ = 0;
4925 buf_epos_ = remaining_size;
4926
4927 if (remaining_size + n > buf_.size()) {
4928 buf_.resize(remaining_size + n);
4929 }
4930
4931 for (size_t i = 0; i < n; i++) {
4932 buf_[buf_epos_ + i] = data[i];
4933 }
4934 buf_epos_ += n;
4935 }
4936
4937 void buf_erase(size_t size) { buf_spos_ += size; }
4938
4939 std::string buf_;
4940 size_t buf_spos_ = 0;
4941 size_t buf_epos_ = 0;
4942};
4943
4944inline std::string random_string(size_t length) {
4945 static const char data[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
4946
4947 // std::random_device might actually be deterministic on some
4948 // platforms, but due to lack of support in the c++ standard library,
4949 // doing better requires either some ugly hacks or breaking portability.
4950 static std::random_device seed_gen;
4951
4952 // Request 128 bits of entropy for initialization
4953 static std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
4954
4955 static std::mt19937 engine(seed_sequence);
4956
4957 std::string result;
4958 for (size_t i = 0; i < length; i++) {
4959 result += data[engine() % (sizeof(data) - 1)];
4960 }
4961 return result;
4962}
4963
4964inline std::string make_multipart_data_boundary() {
4965 return "--cpp-httplib-multipart-data-" + detail::random_string(16);
4966}
4967
4968inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
4969 auto valid = true;
4970 for (size_t i = 0; i < boundary.size(); i++) {
4971 auto c = boundary[i];
4972 if (!std::isalnum(c) && c != '-' && c != '_') {
4973 valid = false;
4974 break;
4975 }
4976 }
4977 return valid;
4978}
4979
4980template<typename T>
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 + "\"";
4986 }
4987 body += "\r\n";
4988 if (!item.content_type.empty()) {
4989 body += "Content-Type: " + item.content_type + "\r\n";
4990 }
4991 body += "\r\n";
4992
4993 return body;
4994}
4995
4996inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
4997
4998inline std::string serialize_multipart_formdata_finish(const std::string &boundary) {
4999 return "--" + boundary + "--\r\n";
5000}
5001
5002inline std::string serialize_multipart_formdata_get_content_type(const std::string &boundary) {
5003 return "multipart/form-data; boundary=" + boundary;
5004}
5005
5006inline std::string serialize_multipart_formdata(const MultipartFormDataItems &items, const std::string &boundary,
5007 bool finish = true) {
5008 std::string body;
5009
5010 for (const auto &item : items) {
5011 body += serialize_multipart_formdata_item_begin(item, boundary);
5012 body += item.content + serialize_multipart_formdata_item_end();
5013 }
5014
5015 if (finish) {
5016 body += serialize_multipart_formdata_finish(boundary);
5017 }
5018
5019 return body;
5020}
5021
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());
5025
5026 ssize_t prev_first_pos = -1;
5027 ssize_t prev_last_pos = -1;
5028 size_t overwrapping_count = 0;
5029
5030 // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
5031 // 'HTTP Semantics' to avoid potential denial-of-service attacks.
5032 // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
5033
5034 // Too many ranges
5035 if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) {
5036 return true;
5037 }
5038
5039 for (auto &r : req.ranges) {
5040 auto &first_pos = r.first;
5041 auto &last_pos = r.second;
5042
5043 if (first_pos == -1 && last_pos == -1) {
5044 first_pos = 0;
5045 last_pos = contant_len;
5046 }
5047
5048 if (first_pos == -1) {
5049 first_pos = contant_len - last_pos;
5050 last_pos = contant_len - 1;
5051 }
5052
5053 if (last_pos == -1) {
5054 last_pos = contant_len - 1;
5055 }
5056
5057 // Range must be within content length
5058 if (!(0 <= first_pos && first_pos <= last_pos && last_pos <= contant_len - 1)) {
5059 return true;
5060 }
5061
5062 // Ranges must be in ascending order
5063 if (first_pos <= prev_first_pos) {
5064 return true;
5065 }
5066
5067 // Request must not have more than two overlapping ranges
5068 if (first_pos <= prev_last_pos) {
5069 overwrapping_count++;
5070 if (overwrapping_count > 2) {
5071 return true;
5072 }
5073 }
5074
5075 prev_first_pos = (std::max) (prev_first_pos, first_pos);
5076 prev_last_pos = (std::max) (prev_last_pos, last_pos);
5077 }
5078 }
5079
5080 return false;
5081}
5082
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);
5089}
5090
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;
5095
5096 std::string field = "bytes ";
5097 field += std::to_string(st);
5098 field += "-";
5099 field += std::to_string(ed);
5100 field += "/";
5101 field += std::to_string(content_length);
5102 return field;
5103}
5104
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++) {
5109 ctoken("--");
5110 stoken(boundary);
5111 ctoken("\r\n");
5112 if (!content_type.empty()) {
5113 ctoken("Content-Type: ");
5114 stoken(content_type);
5115 ctoken("\r\n");
5116 }
5117
5118 auto offset_and_length = get_range_offset_and_length(req.ranges[i], content_length);
5119
5120 ctoken("Content-Range: ");
5121 stoken(make_content_range_header_field(offset_and_length, content_length));
5122 ctoken("\r\n");
5123 ctoken("\r\n");
5124
5125 if (!content(offset_and_length.first, offset_and_length.second)) {
5126 return false;
5127 }
5128 ctoken("\r\n");
5129 }
5130
5131 ctoken("--");
5132 stoken(boundary);
5133 ctoken("--");
5134
5135 return true;
5136}
5137
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);
5145 data += res.body.substr(offset, length);
5146 return true;
5147 });
5148}
5149
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;
5153
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 /*offset*/, size_t length) {
5158 data_length += length;
5159 return true;
5160 });
5161
5162 return data_length;
5163}
5164
5165template<typename T>
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);
5174 });
5175}
5176
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") {
5180 return true;
5181 }
5182 // TODO: check if Content-Length is set
5183 return false;
5184}
5185
5186inline bool has_crlf(const std::string &s) {
5187 auto p = s.c_str();
5188 while (*p) {
5189 if (*p == '\r' || *p == '\n') {
5190 return true;
5191 }
5192 p++;
5193 }
5194 return false;
5195}
5196
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);
5200
5201 unsigned int hash_length = 0;
5202 unsigned char hash[EVP_MAX_MD_SIZE];
5203
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);
5207
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]);
5211 }
5212
5213 return ss.str();
5214}
5215
5216inline std::string MD5(const std::string &s) { return message_digest(s, EVP_md5()); }
5217
5218inline std::string SHA_256(const std::string &s) { return message_digest(s, EVP_sha256()); }
5219
5220inline std::string SHA_512(const std::string &s) { return message_digest(s, EVP_sha512()); }
5221#endif
5222
5223#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
5224#ifdef _WIN32
5225// NOTE: This code came up with the following stackoverflow post:
5226// https://stackoverflow.com/questions/9507184/can-openssl-on-windows-use-the-system-certificate-store
5227inline bool load_system_certs_on_windows(X509_STORE *store) {
5228 auto hStore = CertOpenSystemStoreW((HCRYPTPROV_LEGACY) NULL, L"ROOT");
5229 if (!hStore) {
5230 return false;
5231 }
5232
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);
5237
5238 auto x509 = d2i_X509(NULL, &encoded_cert, pContext->cbCertEncoded);
5239 if (x509) {
5240 X509_STORE_add_cert(store, x509);
5241 X509_free(x509);
5242 result = true;
5243 }
5244 }
5245
5246 CertFreeCertificateContext(pContext);
5247 CertCloseStore(hStore, 0);
5248
5249 return result;
5250}
5251#elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && defined(__APPLE__)
5252#if TARGET_OS_OSX
5253template<typename T> using CFObjectPtr = std::unique_ptr<typename std::remove_pointer<T>::type, void (*)(CFTypeRef)>;
5254
5255inline void cf_object_ptr_deleter(CFTypeRef obj) {
5256 if (obj) {
5257 CFRelease(obj);
5258 }
5259}
5260
5261inline bool retrieve_certs_from_keychain(CFObjectPtr<CFArrayRef> &certs) {
5262 CFStringRef keys[] = {kSecClass, kSecMatchLimit, kSecReturnRef};
5263 CFTypeRef values[] = {kSecClassCertificate, kSecMatchLimitAll, kCFBooleanTrue};
5264
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);
5269
5270 if (!query) {
5271 return false;
5272 }
5273
5274 CFTypeRef security_items = nullptr;
5275 if (SecItemCopyMatching(query.get(), &security_items) != errSecSuccess ||
5276 CFArrayGetTypeID() != CFGetTypeID(security_items)) {
5277 return false;
5278 }
5279
5280 certs.reset(reinterpret_cast<CFArrayRef>(security_items));
5281 return true;
5282}
5283
5284inline bool retrieve_root_certs_from_keychain(CFObjectPtr<CFArrayRef> &certs) {
5285 CFArrayRef root_security_items = nullptr;
5286 if (SecTrustCopyAnchorCertificates(&root_security_items) != errSecSuccess) {
5287 return false;
5288 }
5289
5290 certs.reset(root_security_items);
5291 return true;
5292}
5293
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));
5298
5299 if (SecCertificateGetTypeID() != CFGetTypeID(cert)) {
5300 continue;
5301 }
5302
5303 CFDataRef cert_data = nullptr;
5304 if (SecItemExport(cert, kSecFormatX509Cert, 0, nullptr, &cert_data) != errSecSuccess) {
5305 continue;
5306 }
5307
5308 CFObjectPtr<CFDataRef> cert_data_ptr(cert_data, cf_object_ptr_deleter);
5309
5310 auto encoded_cert = static_cast<const unsigned char *>(CFDataGetBytePtr(cert_data_ptr.get()));
5311
5312 auto x509 = d2i_X509(NULL, &encoded_cert, CFDataGetLength(cert_data_ptr.get()));
5313
5314 if (x509) {
5315 X509_STORE_add_cert(store, x509);
5316 X509_free(x509);
5317 result = true;
5318 }
5319 }
5320
5321 return result;
5322}
5323
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);
5329 }
5330
5331 if (retrieve_root_certs_from_keychain(certs) && certs) {
5332 result = add_certs_to_x509_store(certs.get(), store) || result;
5333 }
5334
5335 return result;
5336}
5337#endif // TARGET_OS_OSX
5338#endif // _WIN32
5339#endif // CPPHTTPLIB_OPENSSL_SUPPORT
5340
5341#ifdef _WIN32
5342class WSInit {
5343 public:
5344 WSInit() {
5345 WSADATA wsaData;
5346 if (WSAStartup(0x0002, &wsaData) == 0)
5347 is_valid_ = true;
5348 }
5349
5350 ~WSInit() {
5351 if (is_valid_)
5352 WSACleanup();
5353 }
5354
5355 bool is_valid_ = false;
5356};
5357
5358static WSInit wsinit_;
5359#endif
5360
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) {
5365 std::string nc;
5366 {
5367 std::stringstream ss;
5368 ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
5369 nc = ss.str();
5370 }
5371
5372 std::string qop;
5373 if (auth.find("qop") != auth.end()) {
5374 qop = auth.at("qop");
5375 if (qop.find("auth-int") != std::string::npos) {
5376 qop = "auth-int";
5377 } else if (qop.find("auth") != std::string::npos) {
5378 qop = "auth";
5379 } else {
5380 qop.clear();
5381 }
5382 }
5383
5384 std::string algo = "MD5";
5385 if (auth.find("algorithm") != auth.end()) {
5386 algo = auth.at("algorithm");
5387 }
5388
5389 std::string response;
5390 {
5391 auto H = algo == "SHA-256" ? detail::SHA_256 : algo == "SHA-512" ? detail::SHA_512 : detail::MD5;
5392
5393 auto A1 = username + ":" + auth.at("realm") + ":" + password;
5394
5395 auto A2 = req.method + ":" + req.path;
5396 if (qop == "auth-int") {
5397 A2 += ":" + H(req.body);
5398 }
5399
5400 if (qop.empty()) {
5401 response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
5402 } else {
5403 response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce + ":" + qop + ":" + H(A2));
5404 }
5405 }
5406
5407 auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
5408
5409 auto field =
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 + "\"");
5414
5415 auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
5416 return std::make_pair(key, field);
5417}
5418#endif
5419
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") {
5429 return false;
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) {
5434 const auto &m = *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)));
5438 auth[key] = val;
5439 }
5440 return true;
5441 }
5442 }
5443 }
5444 return false;
5445}
5446
5447class ContentProviderAdapter {
5448 public:
5449 explicit ContentProviderAdapter(ContentProviderWithoutLength &&content_provider)
5450 : content_provider_(content_provider) {}
5451
5452 bool operator()(size_t offset, size_t, DataSink &sink) { return content_provider_(offset, sink); }
5453
5454 private:
5455 ContentProviderWithoutLength content_provider_;
5456};
5457
5458} // namespace detail
5459
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();
5465 }
5466 return addrs[0];
5467}
5468
5469inline void hosted_at(const std::string &hostname, std::vector<std::string> &addrs) {
5470 struct addrinfo hints;
5471 struct addrinfo *result;
5472
5473 memset(&hints, 0, sizeof(struct addrinfo));
5474 hints.ai_family = AF_UNSPEC;
5475 hints.ai_socktype = SOCK_STREAM;
5476 hints.ai_protocol = 0;
5477
5478 if (getaddrinfo(hostname.c_str(), nullptr, &hints, &result)) {
5479#if defined __linux__ && !defined __ANDROID__
5480 res_init();
5481#endif
5482 return;
5483 }
5484 auto se = detail::scope_exit([&] { freeaddrinfo(result); });
5485
5486 for (auto rp = result; rp; rp = rp->ai_next) {
5487 const auto &addr = *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
5488 std::string ip;
5489 auto dummy = -1;
5490 if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip, dummy)) {
5491 addrs.push_back(ip);
5492 }
5493 }
5494}
5495
5496inline std::string append_query_params(const std::string &path, const Params &params) {
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;
5502}
5503
5504// Header utilities
5505inline std::pair<std::string, std::string> make_range_header(const Ranges &ranges) {
5506 std::string field = "bytes=";
5507 auto i = 0;
5508 for (const auto &r : ranges) {
5509 if (i != 0) {
5510 field += ", ";
5511 }
5512 if (r.first != -1) {
5513 field += std::to_string(r.first);
5514 }
5515 field += '-';
5516 if (r.second != -1) {
5517 field += std::to_string(r.second);
5518 }
5519 i++;
5520 }
5521 return std::make_pair("Range", std::move(field));
5522}
5523
5524inline std::pair<std::string, std::string> make_basic_authentication_header(const std::string &username,
5525 const std::string &password,
5526 bool is_proxy) {
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));
5530}
5531
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));
5537}
5538
5539// Request implementation
5540inline bool Request::has_header(const std::string &key) const { return detail::has_header(headers, key); }
5541
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);
5544}
5545
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));
5549}
5550
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);
5554 }
5555}
5556
5557inline bool Request::has_param(const std::string &key) const { return params.find(key) != params.end(); }
5558
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) {
5564 return it->second;
5565 }
5566 return std::string();
5567}
5568
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));
5572}
5573
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);
5577}
5578
5579inline bool Request::has_file(const std::string &key) const { return files.find(key) != files.end(); }
5580
5581inline MultipartFormData Request::get_file_value(const std::string &key) const {
5582 auto it = files.find(key);
5583 if (it != files.end()) {
5584 return it->second;
5585 }
5586 return MultipartFormData();
5587}
5588
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);
5594 }
5595 return values;
5596}
5597
5598// Response implementation
5599inline bool Response::has_header(const std::string &key) const { return headers.find(key) != headers.end(); }
5600
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);
5603}
5604
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));
5608}
5609
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);
5613 }
5614}
5615
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) {
5620 this->status = stat;
5621 } else {
5622 this->status = StatusCode::Found_302;
5623 }
5624 }
5625}
5626
5627inline void Response::set_content(const char *s, size_t n, const std::string &content_type) {
5628 body.assign(s, n);
5629
5630 auto rng = headers.equal_range("Content-Type");
5631 headers.erase(rng.first, rng.second);
5632 set_header("Content-Type", content_type);
5633}
5634
5635inline void Response::set_content(const std::string &s, const std::string &content_type) {
5636 set_content(s.data(), s.size(), content_type);
5637}
5638
5639inline void Response::set_content(std::string &&s, const std::string &content_type) {
5640 body = std::move(s);
5641
5642 auto rng = headers.equal_range("Content-Type");
5643 headers.erase(rng.first, rng.second);
5644 set_header("Content-Type", content_type);
5645}
5646
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);
5653 }
5654 content_provider_resource_releaser_ = std::move(resource_releaser);
5655 is_chunked_content_provider_ = false;
5656}
5657
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;
5665}
5666
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;
5675}
5676
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;
5680}
5681
5682inline void Response::set_file_content(const std::string &path) { file_content_path_ = path; }
5683
5684// Result implementation
5685inline bool Result::has_request_header(const std::string &key) const {
5686 return request_headers_.find(key) != request_headers_.end();
5687}
5688
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);
5691}
5692
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));
5696}
5697
5698// Stream implementation
5699inline ssize_t Stream::write(const char *ptr) { return write(ptr, strlen(ptr)); }
5700
5701inline ssize_t Stream::write(const std::string &s) { return write(s.data(), s.size()); }
5702
5703namespace detail {
5704
5705// Socket stream implementation
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)
5708 : sock_(sock),
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) {}
5714
5715inline SocketStream::~SocketStream() = default;
5716
5717inline bool SocketStream::is_readable() const { return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0; }
5718
5719inline bool SocketStream::is_writable() const {
5720 return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 && is_socket_alive(sock_);
5721}
5722
5723inline ssize_t SocketStream::read(char *ptr, size_t size) {
5724#ifdef _WIN32
5725 size = (std::min) (size, static_cast<size_t>((std::numeric_limits<int>::max)()));
5726#else
5727 size = (std::min) (size, static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
5728#endif
5729
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;
5735 return static_cast<ssize_t>(size);
5736 } else {
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);
5740 }
5741 }
5742
5743 if (!is_readable()) {
5744 return -1;
5745 }
5746
5747 read_buff_off_ = 0;
5748 read_buff_content_size_ = 0;
5749
5750 if (size < read_buff_size_) {
5751 auto n = read_socket(sock_, read_buff_.data(), read_buff_size_, CPPHTTPLIB_RECV_FLAGS);
5752 if (n <= 0) {
5753 return n;
5754 } else if (n <= static_cast<ssize_t>(size)) {
5755 memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
5756 return n;
5757 } else {
5758 memcpy(ptr, read_buff_.data(), size);
5759 read_buff_off_ = size;
5760 read_buff_content_size_ = static_cast<size_t>(n);
5761 return static_cast<ssize_t>(size);
5762 }
5763 } else {
5764 return read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
5765 }
5766}
5767
5768inline ssize_t SocketStream::write(const char *ptr, size_t size) {
5769 if (!is_writable()) {
5770 return -1;
5771 }
5772
5773#if defined(_WIN32) && !defined(_WIN64)
5774 size = (std::min) (size, static_cast<size_t>((std::numeric_limits<int>::max)()));
5775#endif
5776
5777 return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
5778}
5779
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);
5782}
5783
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);
5786}
5787
5788inline socket_t SocketStream::socket() const { return sock_; }
5789
5790// Buffer stream implementation
5791inline bool BufferStream::is_readable() const { return true; }
5792
5793inline bool BufferStream::is_writable() const { return true; }
5794
5795inline ssize_t BufferStream::read(char *ptr, size_t size) {
5796#if defined(_MSC_VER) && _MSC_VER < 1910
5797 auto len_read = buffer._Copy_s(ptr, size, size, position);
5798#else
5799 auto len_read = buffer.copy(ptr, size, position);
5800#endif
5801 position += static_cast<size_t>(len_read);
5802 return static_cast<ssize_t>(len_read);
5803}
5804
5805inline ssize_t BufferStream::write(const char *ptr, size_t size) {
5806 buffer.append(ptr, size);
5807 return static_cast<ssize_t>(size);
5808}
5809
5810inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/, int & /*port*/) const {}
5811
5812inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/, int & /*port*/) const {}
5813
5814inline socket_t BufferStream::socket() const { return 0; }
5815
5816inline const std::string &BufferStream::get_buffer() const { return buffer; }
5817
5818inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern) {
5819 static constexpr char marker[] = "/:";
5820
5821 // One past the last ending position of a path param substring
5822 std::size_t last_param_end = 0;
5823
5824#ifndef CPPHTTPLIB_NO_EXCEPTIONS
5825 // Needed to ensure that parameter names are unique during matcher
5826 // construction
5827 // If exceptions are disabled, only last duplicate path
5828 // parameter will be set
5829 std::unordered_set<std::string> param_name_set;
5830#endif
5831
5832 while (true) {
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) {
5835 break;
5836 }
5837
5838 static_fragments_.push_back(pattern.substr(last_param_end, marker_pos - last_param_end + 1));
5839
5840 const auto param_name_start = marker_pos + 2;
5841
5842 auto sep_pos = pattern.find(separator, param_name_start);
5843 if (sep_pos == std::string::npos) {
5844 sep_pos = pattern.length();
5845 }
5846
5847 auto param_name = pattern.substr(param_name_start, sep_pos - param_name_start);
5848
5849#ifndef CPPHTTPLIB_NO_EXCEPTIONS
5850 if (param_name_set.find(param_name) != param_name_set.cend()) {
5851 std::string msg =
5852 "Encountered path parameter '" + param_name + "' multiple times in route pattern '" + pattern + "'.";
5853 throw std::invalid_argument(msg);
5854 }
5855#endif
5856
5857 param_names_.push_back(std::move(param_name));
5858
5859 last_param_end = sep_pos + 1;
5860 }
5861
5862 if (last_param_end < pattern.length()) {
5863 static_fragments_.push_back(pattern.substr(last_param_end));
5864 }
5865}
5866
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());
5871
5872 // One past the position at which the path matched the pattern last time
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];
5876
5877 if (starting_pos + fragment.length() > request.path.length()) {
5878 return false;
5879 }
5880
5881 // Avoid unnecessary allocation by using strncmp instead of substr +
5882 // comparison
5883 if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(), fragment.length()) != 0) {
5884 return false;
5885 }
5886
5887 starting_pos += fragment.length();
5888
5889 // Should only happen when we have a static fragment after a param
5890 // Example: '/users/:id/subscriptions'
5891 // The 'subscriptions' fragment here does not have a corresponding param
5892 if (i >= param_names_.size()) {
5893 continue;
5894 }
5895
5896 auto sep_pos = request.path.find(separator, starting_pos);
5897 if (sep_pos == std::string::npos) {
5898 sep_pos = request.path.length();
5899 }
5900
5901 const auto &param_name = param_names_[i];
5902
5903 request.path_params.emplace(param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
5904
5905 // Mark everything up to '/' as matched
5906 starting_pos = sep_pos + 1;
5907 }
5908 // Returns false if the path is longer than the pattern
5909 return starting_pos >= request.path.length();
5910}
5911
5912inline bool RegexMatcher::match(Request &request) const {
5913 request.path_params.clear();
5914 return std::regex_match(request.path, request.matches, regex_);
5915}
5916
5917} // namespace detail
5918
5919// HTTP server implementation
5920inline Server::Server() : new_task_queue([] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }) {
5921#ifndef _WIN32
5922 signal(SIGPIPE, SIG_IGN);
5923#endif
5924}
5925
5926inline Server::~Server() = default;
5927
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);
5931 } else {
5932 return detail::make_unique<detail::RegexMatcher>(pattern);
5933 }
5934}
5935
5936inline Server &Server::Get(const std::string &pattern, Handler handler) {
5937 get_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
5938 return *this;
5939}
5940
5941inline Server &Server::Post(const std::string &pattern, Handler handler) {
5942 post_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
5943 return *this;
5944}
5945
5946inline Server &Server::Post(const std::string &pattern, HandlerWithContentReader handler) {
5947 post_handlers_for_content_reader_.emplace_back(make_matcher(pattern), std::move(handler));
5948 return *this;
5949}
5950
5951inline Server &Server::Put(const std::string &pattern, Handler handler) {
5952 put_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
5953 return *this;
5954}
5955
5956inline Server &Server::Put(const std::string &pattern, HandlerWithContentReader handler) {
5957 put_handlers_for_content_reader_.emplace_back(make_matcher(pattern), std::move(handler));
5958 return *this;
5959}
5960
5961inline Server &Server::Patch(const std::string &pattern, Handler handler) {
5962 patch_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
5963 return *this;
5964}
5965
5966inline Server &Server::Patch(const std::string &pattern, HandlerWithContentReader handler) {
5967 patch_handlers_for_content_reader_.emplace_back(make_matcher(pattern), std::move(handler));
5968 return *this;
5969}
5970
5971inline Server &Server::Delete(const std::string &pattern, Handler handler) {
5972 delete_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
5973 return *this;
5974}
5975
5976inline Server &Server::Delete(const std::string &pattern, HandlerWithContentReader handler) {
5977 delete_handlers_for_content_reader_.emplace_back(make_matcher(pattern), std::move(handler));
5978 return *this;
5979}
5980
5981inline Server &Server::Options(const std::string &pattern, Handler handler) {
5982 options_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
5983 return *this;
5984}
5985
5986inline bool Server::set_base_dir(const std::string &dir, const std::string &mount_point) {
5987 return set_mount_point(mount_point, dir);
5988}
5989
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)});
5996 return true;
5997 }
5998 }
5999 return false;
6000}
6001
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);
6006 return true;
6007 }
6008 }
6009 return false;
6010}
6011
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;
6014 return *this;
6015}
6016
6017inline Server &Server::set_default_file_mimetype(const std::string &mime) {
6018 default_file_mimetype_ = mime;
6019 return *this;
6020}
6021
6022inline Server &Server::set_file_request_handler(Handler handler) {
6023 file_request_handler_ = std::move(handler);
6024 return *this;
6025}
6026
6027inline Server &Server::set_error_handler_core(HandlerWithResponse handler, std::true_type) {
6028 error_handler_ = std::move(handler);
6029 return *this;
6030}
6031
6032inline Server &Server::set_error_handler_core(Handler handler, std::false_type) {
6033 error_handler_ = [handler](const Request &req, Response &res) {
6034 handler(req, res);
6035 return HandlerResponse::Handled;
6036 };
6037 return *this;
6038}
6039
6040inline Server &Server::set_exception_handler(ExceptionHandler handler) {
6041 exception_handler_ = std::move(handler);
6042 return *this;
6043}
6044
6045inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
6046 pre_routing_handler_ = std::move(handler);
6047 return *this;
6048}
6049
6050inline Server &Server::set_post_routing_handler(Handler handler) {
6051 post_routing_handler_ = std::move(handler);
6052 return *this;
6053}
6054
6055inline Server &Server::set_logger(Logger logger) {
6056 logger_ = std::move(logger);
6057 return *this;
6058}
6059
6060inline Server &Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
6061 expect_100_continue_handler_ = std::move(handler);
6062 return *this;
6063}
6064
6065inline Server &Server::set_address_family(int family) {
6066 address_family_ = family;
6067 return *this;
6068}
6069
6070inline Server &Server::set_tcp_nodelay(bool on) {
6071 tcp_nodelay_ = on;
6072 return *this;
6073}
6074
6075inline Server &Server::set_ipv6_v6only(bool on) {
6076 ipv6_v6only_ = on;
6077 return *this;
6078}
6079
6080inline Server &Server::set_socket_options(SocketOptions socket_options) {
6081 socket_options_ = std::move(socket_options);
6082 return *this;
6083}
6084
6085inline Server &Server::set_default_headers(Headers headers) {
6086 default_headers_ = std::move(headers);
6087 return *this;
6088}
6089
6090inline Server &Server::set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer) {
6091 header_writer_ = writer;
6092 return *this;
6093}
6094
6095inline Server &Server::set_keep_alive_max_count(size_t count) {
6096 keep_alive_max_count_ = count;
6097 return *this;
6098}
6099
6100inline Server &Server::set_keep_alive_timeout(time_t sec) {
6101 keep_alive_timeout_sec_ = sec;
6102 return *this;
6103}
6104
6105inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
6106 read_timeout_sec_ = sec;
6107 read_timeout_usec_ = usec;
6108 return *this;
6109}
6110
6111inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
6112 write_timeout_sec_ = sec;
6113 write_timeout_usec_ = usec;
6114 return *this;
6115}
6116
6117inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
6118 idle_interval_sec_ = sec;
6119 idle_interval_usec_ = usec;
6120 return *this;
6121}
6122
6123inline Server &Server::set_payload_max_length(size_t length) {
6124 payload_max_length_ = length;
6125 return *this;
6126}
6127
6128inline bool Server::bind_to_port(const std::string &host, int port, int socket_flags) {
6129 auto ret = bind_internal(host, port, socket_flags);
6130 if (ret == -1) {
6131 is_decommisioned = true;
6132 }
6133 return ret >= 0;
6134}
6135inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
6136 auto ret = bind_internal(host, 0, socket_flags);
6137 if (ret == -1) {
6138 is_decommisioned = true;
6139 }
6140 return ret;
6141}
6142
6143inline bool Server::listen_after_bind() { return listen_internal(); }
6144
6145inline bool Server::listen(const std::string &host, int port, int socket_flags) {
6146 return bind_to_port(host, port, socket_flags) && listen_internal();
6147}
6148
6149inline bool Server::is_running() const { return is_running_; }
6150
6151inline void Server::wait_until_ready() const {
6152 while (!is_running_ && !is_decommisioned) {
6153 std::this_thread::sleep_for(std::chrono::milliseconds{1});
6154 }
6155}
6156
6157inline void Server::stop() {
6158 if (is_running_) {
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);
6163 }
6164 is_decommisioned = false;
6165}
6166
6167inline void Server::decommission() { is_decommisioned = true; }
6168
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') {
6172 return false;
6173 }
6174 len -= 2;
6175
6176 {
6177 size_t count = 0;
6178
6179 detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
6180 switch (count) {
6181 case 0:
6182 req.method = std::string(b, e);
6183 break;
6184 case 1:
6185 req.target = std::string(b, e);
6186 break;
6187 case 2:
6188 req.version = std::string(b, e);
6189 break;
6190 default:
6191 break;
6192 }
6193 count++;
6194 });
6195
6196 if (count != 3) {
6197 return false;
6198 }
6199 }
6200
6201 static const std::set<std::string> methods{"GET", "HEAD", "POST", "PUT", "DELETE",
6202 "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
6203
6204 if (methods.find(req.method) == methods.end()) {
6205 return false;
6206 }
6207
6208 if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
6209 return false;
6210 }
6211
6212 {
6213 // Skip URL fragment
6214 for (size_t i = 0; i < req.target.size(); i++) {
6215 if (req.target[i] == '#') {
6216 req.target.erase(i);
6217 break;
6218 }
6219 }
6220
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);
6225 });
6226 }
6227
6228 return true;
6229}
6230
6231inline bool Server::write_response(Stream &strm, bool close_connection, Request &req, Response &res) {
6232 // NOTE: `req.ranges` should be empty, otherwise it will be applied
6233 // incorrectly to the error content.
6234 req.ranges.clear();
6235 return write_response_core(strm, close_connection, req, res, false);
6236}
6237
6238inline bool Server::write_response_with_content(Stream &strm, bool close_connection, const Request &req,
6239 Response &res) {
6240 return write_response_core(strm, close_connection, req, res, true);
6241}
6242
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);
6246
6247 if (400 <= res.status && error_handler_ && error_handler_(req, res) == HandlerResponse::Handled) {
6248 need_apply_ranges = true;
6249 }
6250
6251 std::string content_type;
6252 std::string boundary;
6253 if (need_apply_ranges) {
6254 apply_ranges(req, res, content_type, boundary);
6255 }
6256
6257 // Prepare additional headers
6258 if (close_connection || req.get_header_value("Connection") == "close") {
6259 res.set_header("Connection", "close");
6260 } else {
6261 std::string s = "timeout=";
6262 s += std::to_string(keep_alive_timeout_sec_);
6263 s += ", max=";
6264 s += std::to_string(keep_alive_max_count_);
6265 res.set_header("Keep-Alive", s);
6266 }
6267
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");
6270 }
6271
6272 if (res.body.empty() && !res.content_length_ && !res.content_provider_ && !res.has_header("Content-Length")) {
6273 res.set_header("Content-Length", "0");
6274 }
6275
6276 if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
6277 res.set_header("Accept-Ranges", "bytes");
6278 }
6279
6280 if (post_routing_handler_) {
6281 post_routing_handler_(req, res);
6282 }
6283
6284 // Response line and headers
6285 {
6286 detail::BufferStream bstrm;
6287 if (!detail::write_response_line(bstrm, res.status)) {
6288 return false;
6289 }
6290 if (!header_writer_(bstrm, res.headers)) {
6291 return false;
6292 }
6293
6294 // Flush buffer
6295 auto &data = bstrm.get_buffer();
6296 detail::write_data(strm, data.data(), data.size());
6297 }
6298
6299 // Body
6300 auto ret = true;
6301 if (req.method != "HEAD") {
6302 if (!res.body.empty()) {
6303 if (!detail::write_data(strm, res.body.data(), res.body.size())) {
6304 ret = false;
6305 }
6306 } else if (res.content_provider_) {
6307 if (write_content_with_provider(strm, req, res, boundary, content_type)) {
6308 res.content_provider_success_ = true;
6309 } else {
6310 ret = false;
6311 }
6312 }
6313 }
6314
6315 // Log
6316 if (logger_) {
6317 logger_(req, res);
6318 }
6319
6320 return ret;
6321}
6322
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; };
6326
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_);
6332
6333 return detail::write_content(strm, res.content_provider_, offset_and_length.first, offset_and_length.second,
6334 is_shutting_down);
6335 } else {
6336 return detail::write_multipart_ranges_data(strm, req, res, boundary, content_type, res.content_length_,
6337 is_shutting_down);
6338 }
6339 } else {
6340 if (res.is_chunked_content_provider_) {
6341 auto type = detail::encoding_type(req, res);
6342
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>();
6347#endif
6348 } else if (type == detail::EncodingType::Brotli) {
6349#ifdef CPPHTTPLIB_BROTLI_SUPPORT
6350 compressor = detail::make_unique<detail::brotli_compressor>();
6351#endif
6352 } else {
6353 compressor = detail::make_unique<detail::nocompressor>();
6354 }
6355 assert(compressor != nullptr);
6356
6357 return detail::write_content_chunked(strm, res.content_provider_, is_shutting_down, *compressor);
6358 } else {
6359 return detail::write_content_without_length(strm, res.content_provider_, is_shutting_down);
6360 }
6361 }
6362}
6363
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(
6368 strm, req, res,
6369 // Regular
6370 [&](const char *buf, size_t n) {
6371 if (req.body.size() + n > req.body.max_size()) {
6372 return false;
6373 }
6374 req.body.append(buf, n);
6375 return true;
6376 },
6377 // Multipart
6378 [&](const MultipartFormData &file) {
6379 if (file_count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
6380 return false;
6381 }
6382 cur = req.files.emplace(file.name, file);
6383 return true;
6384 },
6385 [&](const char *buf, size_t n) {
6386 auto &content = cur->second.content;
6387 if (content.size() + n > content.max_size()) {
6388 return false;
6389 }
6390 content.append(buf, n);
6391 return true;
6392 })) {
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; // NOTE: should be 414?
6397 return false;
6398 }
6399 detail::parse_query_text(req.body, req.params);
6400 }
6401 return true;
6402 }
6403 return false;
6404}
6405
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));
6412}
6413
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;
6419
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;
6425 return false;
6426 }
6427
6428 multipart_form_data_parser.set_boundary(std::move(boundary));
6429 out = [&](const char *buf, size_t n, uint64_t /*off*/, uint64_t /*len*/) {
6430 /* For debug
6431 size_t pos = 0;
6432 while (pos < n) {
6433 auto read_size = (std::min)<size_t>(1, n - pos);
6434 auto ret = multipart_form_data_parser.parse(
6435 buf + pos, read_size, multipart_receiver, multipart_header);
6436 if (!ret) { return false; }
6437 pos += read_size;
6438 }
6439 return true;
6440 */
6441 return multipart_form_data_parser.parse(buf, n, multipart_receiver, multipart_header);
6442 };
6443 } else {
6444 out = [receiver](const char *buf, size_t n, uint64_t /*off*/, uint64_t /*len*/) { return receiver(buf, n); };
6445 }
6446
6447 if (req.method == "DELETE" && !req.has_header("Content-Length")) {
6448 return true;
6449 }
6450
6451 if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr, out, true)) {
6452 return false;
6453 }
6454
6455 if (req.is_multipart_form_data()) {
6456 if (!multipart_form_data_parser.is_valid()) {
6457 res.status = StatusCode::BadRequest_400;
6458 return false;
6459 }
6460 }
6461
6462 return true;
6463}
6464
6465inline bool Server::handle_file_request(const Request &req, Response &res, bool head) {
6466 for (const auto &entry : base_dirs_) {
6467 // Prefix match
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";
6474 }
6475
6476 detail::FileStat stat(path);
6477
6478 if (stat.is_dir()) {
6479 res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
6480 return true;
6481 }
6482
6483 if (stat.is_file()) {
6484 for (const auto &kv : entry.headers) {
6485 res.set_header(kv.first, kv.second);
6486 }
6487
6488 auto mm = std::make_shared<detail::mmap>(path.c_str());
6489 if (!mm->is_open()) {
6490 return false;
6491 }
6492
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);
6497 return true;
6498 });
6499
6500 if (!head && file_request_handler_) {
6501 file_request_handler_(req, res);
6502 }
6503
6504 return true;
6505 }
6506 }
6507 }
6508 }
6509 return false;
6510}
6511
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 & /*quit*/) -> bool {
6517 if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
6518 return false;
6519 }
6520 if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
6521 return false;
6522 }
6523 return true;
6524 });
6525}
6526
6527inline int Server::bind_internal(const std::string &host, int port, int socket_flags) {
6528 if (is_decommisioned) {
6529 return -1;
6530 }
6531
6532 if (!is_valid()) {
6533 return -1;
6534 }
6535
6536 svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
6537 if (svr_sock_ == INVALID_SOCKET) {
6538 return -1;
6539 }
6540
6541 if (port == 0) {
6542 struct sockaddr_storage addr;
6543 socklen_t addr_len = sizeof(addr);
6544 if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr), &addr_len) == -1) {
6545 return -1;
6546 }
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);
6551 } else {
6552 return -1;
6553 }
6554 } else {
6555 return port;
6556 }
6557}
6558
6559inline bool Server::listen_internal() {
6560 if (is_decommisioned) {
6561 return false;
6562 }
6563
6564 auto ret = true;
6565 is_running_ = true;
6566 auto se = detail::scope_exit([&]() { is_running_ = false; });
6567
6568 {
6569 std::unique_ptr<TaskQueue> task_queue(new_task_queue());
6570
6571 while (svr_sock_ != INVALID_SOCKET) {
6572#ifndef _WIN32
6573 if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
6574#endif
6575 auto val = detail::select_read(svr_sock_, idle_interval_sec_, idle_interval_usec_);
6576 if (val == 0) { // Timeout
6577 task_queue->on_idle();
6578 continue;
6579 }
6580#ifndef _WIN32
6581 }
6582#endif
6583
6584#if defined _WIN32
6585 // sockets conneced via WASAccept inherit flags NO_HANDLE_INHERIT,
6586 // OVERLAPPED
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);
6590#else
6591 socket_t sock = accept(svr_sock_, nullptr, nullptr);
6592#endif
6593
6594 if (sock == INVALID_SOCKET) {
6595 if (errno == EMFILE) {
6596 // The per-process limit of open file descriptors has been reached.
6597 // Try to accept new connections after a short sleep.
6598 std::this_thread::sleep_for(std::chrono::microseconds{1});
6599 continue;
6600 } else if (errno == EINTR || errno == EAGAIN) {
6601 continue;
6602 }
6603 if (svr_sock_ != INVALID_SOCKET) {
6604 detail::close_socket(svr_sock_);
6605 ret = false;
6606 } else {
6607 ; // The server socket was closed by user.
6608 }
6609 break;
6610 }
6611
6612 {
6613#ifdef _WIN32
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));
6616#else
6617 timeval tv;
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));
6621#endif
6622 }
6623 {
6624#ifdef _WIN32
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));
6627#else
6628 timeval tv;
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));
6632#endif
6633 }
6634
6635 if (!task_queue->enqueue([this, sock]() { process_and_close_socket(sock); })) {
6636 detail::shutdown_socket(sock);
6637 detail::close_socket(sock);
6638 }
6639 }
6640
6641 task_queue->shutdown();
6642 }
6643
6644 is_decommisioned = !ret;
6645 return ret;
6646}
6647
6648inline bool Server::routing(Request &req, Response &res, Stream &strm) {
6649 if (pre_routing_handler_ && pre_routing_handler_(req, res) == HandlerResponse::Handled) {
6650 return true;
6651 }
6652
6653 // File handler
6654 auto is_head_request = req.method == "HEAD";
6655 if ((req.method == "GET" || is_head_request) && handle_file_request(req, res, is_head_request)) {
6656 return true;
6657 }
6658
6659 if (detail::expect_content(req)) {
6660 // Content reader handler
6661 {
6662 ContentReader reader(
6663 [&](ContentReceiver receiver) {
6664 return read_content_with_content_receiver(strm, req, res, std::move(receiver), nullptr, nullptr);
6665 },
6666 [&](MultipartContentHeader header, ContentReceiver receiver) {
6667 return read_content_with_content_receiver(strm, req, res, nullptr, std::move(header), std::move(receiver));
6668 });
6669
6670 if (req.method == "POST") {
6671 if (dispatch_request_for_content_reader(req, res, std::move(reader), post_handlers_for_content_reader_)) {
6672 return true;
6673 }
6674 } else if (req.method == "PUT") {
6675 if (dispatch_request_for_content_reader(req, res, std::move(reader), put_handlers_for_content_reader_)) {
6676 return true;
6677 }
6678 } else if (req.method == "PATCH") {
6679 if (dispatch_request_for_content_reader(req, res, std::move(reader), patch_handlers_for_content_reader_)) {
6680 return true;
6681 }
6682 } else if (req.method == "DELETE") {
6683 if (dispatch_request_for_content_reader(req, res, std::move(reader), delete_handlers_for_content_reader_)) {
6684 return true;
6685 }
6686 }
6687 }
6688
6689 // Read content into `req.body`
6690 if (!read_content(strm, req, res)) {
6691 return false;
6692 }
6693 }
6694
6695 // Regular handler
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_);
6708 }
6709
6710 res.status = StatusCode::BadRequest_400;
6711 return false;
6712}
6713
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;
6718
6719 if (matcher->match(req)) {
6720 handler(req, res);
6721 return true;
6722 }
6723 }
6724 return false;
6725}
6726
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);
6734 }
6735
6736 boundary = detail::make_multipart_data_boundary();
6737
6738 res.set_header("Content-Type", "multipart/byteranges; boundary=" + boundary);
6739 }
6740
6741 auto type = detail::encoding_type(req, res);
6742
6743 if (res.body.empty()) {
6744 if (res.content_length_ > 0) {
6745 size_t 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_);
6750
6751 length = offset_and_length.second;
6752
6753 auto content_range = detail::make_content_range_header_field(offset_and_length, res.content_length_);
6754 res.set_header("Content-Range", content_range);
6755 } else {
6756 length = detail::get_multipart_ranges_data_length(req, boundary, content_type, res.content_length_);
6757 }
6758 res.set_header("Content-Length", std::to_string(length));
6759 } else {
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");
6767 }
6768 }
6769 }
6770 }
6771 } else {
6772 if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
6773 ;
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;
6778
6779 auto content_range = detail::make_content_range_header_field(offset_and_length, res.body.size());
6780 res.set_header("Content-Range", content_range);
6781
6782 assert(offset + length <= res.body.size());
6783 res.body = res.body.substr(offset, length);
6784 } else {
6785 std::string data;
6786 detail::make_multipart_ranges_data(req, res, boundary, content_type, res.body.size(), data);
6787 res.body.swap(data);
6788 }
6789
6790 if (type != detail::EncodingType::None) {
6791 std::unique_ptr<detail::compressor> compressor;
6792 std::string content_encoding;
6793
6794 if (type == detail::EncodingType::Gzip) {
6795#ifdef CPPHTTPLIB_ZLIB_SUPPORT
6796 compressor = detail::make_unique<detail::gzip_compressor>();
6797 content_encoding = "gzip";
6798#endif
6799 } else if (type == detail::EncodingType::Brotli) {
6800#ifdef CPPHTTPLIB_BROTLI_SUPPORT
6801 compressor = detail::make_unique<detail::brotli_compressor>();
6802 content_encoding = "br";
6803#endif
6804 }
6805
6806 if (compressor) {
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);
6810 return true;
6811 })) {
6812 res.body.swap(compressed);
6813 res.set_header("Content-Encoding", content_encoding);
6814 }
6815 }
6816 }
6817
6818 auto length = std::to_string(res.body.size());
6819 res.set_header("Content-Length", length);
6820 }
6821}
6822
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;
6828
6829 if (matcher->match(req)) {
6830 handler(req, res, content_reader);
6831 return true;
6832 }
6833 }
6834 return false;
6835}
6836
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{};
6841
6842 detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
6843
6844 // Connection has been closed on client
6845 if (!line_reader.getline()) {
6846 return false;
6847 }
6848
6849 Request req;
6850
6851 Response res;
6852 res.version = "HTTP/1.1";
6853 res.headers = default_headers_;
6854
6855#ifdef _WIN32
6856 // TODO: Increase FD_SETSIZE statically (libzmq), dynamically (MySQL).
6857#else
6858#ifndef CPPHTTPLIB_USE_POLL
6859 // Socket file descriptor exceeded FD_SETSIZE...
6860 if (strm.socket() >= FD_SETSIZE) {
6861 Headers dummy;
6862 detail::read_headers(strm, dummy);
6863 res.status = StatusCode::InternalServerError_500;
6864 return write_response(strm, close_connection, req, res);
6865 }
6866#endif
6867#endif
6868
6869 // Check if the request URI doesn't exceed the limit
6870 if (line_reader.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
6871 Headers dummy;
6872 detail::read_headers(strm, dummy);
6873 res.status = StatusCode::UriTooLong_414;
6874 return write_response(strm, close_connection, req, res);
6875 }
6876
6877 // Request line and headers
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);
6881 }
6882
6883 if (req.get_header_value("Connection") == "close") {
6884 connection_closed = true;
6885 }
6886
6887 if (req.version == "HTTP/1.0" && req.get_header_value("Connection") != "Keep-Alive") {
6888 connection_closed = true;
6889 }
6890
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));
6895
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));
6900
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);
6906 }
6907 }
6908
6909 if (setup_request) {
6910 setup_request(req);
6911 }
6912
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);
6917 }
6918 switch (status) {
6919 case StatusCode::Continue_100:
6920 case StatusCode::ExpectationFailed_417:
6921 detail::write_response_line(strm, status);
6922 strm.write("\r\n");
6923 break;
6924 default:
6925 connection_closed = true;
6926 return write_response(strm, true, req, res);
6927 }
6928 }
6929
6930 // Routing
6931 auto routed = false;
6932#ifdef CPPHTTPLIB_NO_EXCEPTIONS
6933 routed = routing(req, res, strm);
6934#else
6935 try {
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);
6941 routed = true;
6942 } else {
6943 res.status = StatusCode::InternalServerError_500;
6944 std::string val;
6945 auto s = e.what();
6946 for (size_t i = 0; s[i]; i++) {
6947 switch (s[i]) {
6948 case '\r':
6949 val += "\\r";
6950 break;
6951 case '\n':
6952 val += "\\n";
6953 break;
6954 default:
6955 val += s[i];
6956 break;
6957 }
6958 }
6959 res.set_header("EXCEPTION_WHAT", val);
6960 }
6961 } catch (...) {
6962 if (exception_handler_) {
6963 auto ep = std::current_exception();
6964 exception_handler_(req, res, ep);
6965 routed = true;
6966 } else {
6967 res.status = StatusCode::InternalServerError_500;
6968 res.set_header("EXCEPTION_WHAT", "UNKNOWN");
6969 }
6970 }
6971#endif
6972 if (routed) {
6973 if (res.status == -1) {
6974 res.status = req.ranges.empty() ? StatusCode::OK_200 : StatusCode::PartialContent_206;
6975 }
6976
6977 if (detail::range_error(req, res)) {
6978 res.body.clear();
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);
6983 }
6984
6985 // Serve file content by using a content provider
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()) {
6990 res.body.clear();
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);
6995 }
6996
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_);
7000 }
7001
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);
7004 return true;
7005 });
7006 }
7007
7008 return write_response_with_content(strm, close_connection, req, res);
7009 } else {
7010 if (res.status == -1) {
7011 res.status = StatusCode::NotFound_404;
7012 }
7013
7014 return write_response(strm, close_connection, req, res);
7015 }
7016}
7017
7018inline bool Server::is_valid() const { return true; }
7019
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);
7024
7025 std::string local_addr;
7026 int local_port = 0;
7027 detail::get_local_ip_and_port(sock, local_addr, local_port);
7028
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);
7034 });
7035
7036 detail::shutdown_socket(sock);
7037 detail::close_socket(sock);
7038 return ret;
7039}
7040
7041// HTTP client implementation
7042inline ClientImpl::ClientImpl(const std::string &host) : ClientImpl(host, 80, std::string(), std::string()) {}
7043
7044inline ClientImpl::ClientImpl(const std::string &host, int port)
7045 : ClientImpl(host, port, std::string(), std::string()) {}
7046
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)),
7050 port_(port),
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) {}
7054
7055inline ClientImpl::~ClientImpl() {
7056 std::lock_guard<std::mutex> guard(socket_mutex_);
7057 shutdown_socket(socket_);
7058 close_socket(socket_);
7059}
7060
7061inline bool ClientImpl::is_valid() const { return true; }
7062
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_;
7077#endif
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_;
7096#endif
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_;
7101#endif
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_;
7106#endif
7107 logger_ = rhs.logger_;
7108}
7109
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);
7116 }
7117
7118 // Check is custom IP specified for host_
7119 std::string ip;
7120 auto it = addr_map_.find(host_);
7121 if (it != addr_map_.end()) {
7122 ip = it->second;
7123 }
7124
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);
7128}
7129
7130inline bool ClientImpl::create_and_connect_socket(Socket &socket, Error &error) {
7131 auto sock = create_client_socket(error);
7132 if (sock == INVALID_SOCKET) {
7133 return false;
7134 }
7135 socket.sock = sock;
7136 return true;
7137}
7138
7139inline void ClientImpl::shutdown_ssl(Socket & /*socket*/, bool /*shutdown_gracefully*/) {
7140 // If there are any requests in flight from threads other than us, then it's
7141 // a thread-unsafe race because individual ssl* objects are not thread-safe.
7142 assert(socket_requests_in_flight_ == 0 || socket_requests_are_from_thread_ == std::this_thread::get_id());
7143}
7144
7145inline void ClientImpl::shutdown_socket(Socket &socket) const {
7146 if (socket.sock == INVALID_SOCKET) {
7147 return;
7148 }
7149 detail::shutdown_socket(socket.sock);
7150}
7151
7152inline void ClientImpl::close_socket(Socket &socket) {
7153 // If there are requests in flight in another thread, usually closing
7154 // the socket will be fine and they will simply receive an error when
7155 // using the closed socket, but it is still a bug since rarely the OS
7156 // may reassign the socket id to be used for a new socket, and then
7157 // suddenly they will be operating on a live socket that is different
7158 // than the one they intended!
7159 assert(socket_requests_in_flight_ == 0 || socket_requests_are_from_thread_ == std::this_thread::get_id());
7160
7161 // It is also a bug if this happens while SSL is still active
7162#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
7163 assert(socket.ssl == nullptr);
7164#endif
7165 if (socket.sock == INVALID_SOCKET) {
7166 return;
7167 }
7168 detail::close_socket(socket.sock);
7169 socket.sock = INVALID_SOCKET;
7170}
7171
7172inline bool ClientImpl::read_response_line(Stream &strm, const Request &req, Response &res) const {
7173 std::array<char, 2048> buf{};
7174
7175 detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
7176
7177 if (!line_reader.getline()) {
7178 return false;
7179 }
7180
7181#ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
7182 const static std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
7183#else
7184 const static std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
7185#endif
7186
7187 std::cmatch m;
7188 if (!std::regex_match(line_reader.ptr(), m, re)) {
7189 return req.method == "CONNECT";
7190 }
7191 res.version = std::string(m[1]);
7192 res.status = std::stoi(std::string(m[2]));
7193 res.reason = std::string(m[3]);
7194
7195 // Ignore '100 Continue'
7196 while (res.status == StatusCode::Continue_100) {
7197 if (!line_reader.getline()) {
7198 return false;
7199 } // CRLF
7200 if (!line_reader.getline()) {
7201 return false;
7202 } // next response line
7203
7204 if (!std::regex_match(line_reader.ptr(), m, re)) {
7205 return false;
7206 }
7207 res.version = std::string(m[1]);
7208 res.status = std::stoi(std::string(m[2]));
7209 res.reason = std::string(m[3]);
7210 }
7211
7212 return true;
7213}
7214
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_) {
7219 assert(!ret);
7220 ret = send_(req, res, error);
7221 }
7222 return ret;
7223}
7224
7225#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
7226inline bool ClientImpl::is_ssl_peer_could_be_closed(SSL *ssl) const {
7227 char buf[1];
7228 return !SSL_peek(ssl, buf, 1) && SSL_get_error(ssl, 0) == SSL_ERROR_ZERO_RETURN;
7229}
7230#endif
7231
7232inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
7233 {
7234 std::lock_guard<std::mutex> guard(socket_mutex_);
7235
7236 // Set this to false immediately - if it ever gets set to true by the end of
7237 // the request, we know another thread instructed us to close the socket.
7238 socket_should_be_closed_when_request_is_done_ = false;
7239
7240 auto is_alive = false;
7241 if (socket_.is_open()) {
7242 is_alive = detail::is_socket_alive(socket_.sock);
7243
7244#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
7245 if (is_alive && is_ssl()) {
7246 if (is_ssl_peer_could_be_closed(socket_.ssl)) {
7247 is_alive = false;
7248 }
7249 }
7250#endif
7251
7252 if (!is_alive) {
7253 // Attempt to avoid sigpipe by shutting down nongracefully if it seems
7254 // like the other side has already closed the connection Also, there
7255 // cannot be any requests in flight from other threads since we locked
7256 // request_mutex_, so safe to close everything immediately
7257 const bool shutdown_gracefully = false;
7258 shutdown_ssl(socket_, shutdown_gracefully);
7259 shutdown_socket(socket_);
7260 close_socket(socket_);
7261 }
7262 }
7263
7264 if (!is_alive) {
7265 if (!create_and_connect_socket(socket_, error)) {
7266 return false;
7267 }
7268
7269#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
7270 // TODO: refactoring
7271 if (is_ssl()) {
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)) {
7276 return success;
7277 }
7278 }
7279
7280 if (!scli.initialize_ssl(socket_, error)) {
7281 return false;
7282 }
7283 }
7284#endif
7285 }
7286
7287 // Mark the current socket as being in use so that it cannot be closed by
7288 // anyone else while this request is ongoing, even though we will be
7289 // releasing the mutex.
7290 if (socket_requests_in_flight_ > 1) {
7291 assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
7292 }
7293 socket_requests_in_flight_ += 1;
7294 socket_requests_are_from_thread_ = std::this_thread::get_id();
7295 }
7296
7297 for (const auto &header : default_headers_) {
7298 if (req.headers.find(header.first) == req.headers.end()) {
7299 req.headers.insert(header);
7300 }
7301 }
7302
7303 auto ret = false;
7304 auto close_connection = !keep_alive_;
7305
7306 auto se = detail::scope_exit([&]() {
7307 // Briefly lock mutex in order to mark that a request is no longer ongoing
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();
7313 }
7314
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_);
7319 }
7320 });
7321
7322 ret = process_socket(socket_, [&](Stream &strm) { return handle_request(strm, req, res, close_connection, error); });
7323
7324 if (!ret) {
7325 if (error == Error::Success) {
7326 error = Error::Unknown;
7327 }
7328 }
7329
7330 return ret;
7331}
7332
7333inline Result ClientImpl::send(const Request &req) {
7334 auto req2 = req;
7335 return send_(std::move(req2));
7336}
7337
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)};
7343}
7344
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;
7348 return false;
7349 }
7350
7351 auto req_save = req;
7352
7353 bool ret;
7354
7355 if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) {
7356 auto req2 = req;
7357 req2.path = "http://" + host_and_port_ + req.path;
7358 ret = process_request(strm, req2, res, close_connection, error);
7359 req = req2;
7360 req.path = req_save.path;
7361 } else {
7362 ret = process_request(strm, req, res, close_connection, error);
7363 }
7364
7365 if (!ret) {
7366 return false;
7367 }
7368
7369 if (res.get_header_value("Connection") == "close" ||
7370 (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
7371 // TODO this requires a not-entirely-obvious chain of calls to be correct
7372 // for this to be safe.
7373
7374 // This is safe to call because handle_request is only called by send_
7375 // which locks the request mutex during the process. It would be a bug
7376 // to call it from a different thread since it's a thread-safety issue
7377 // to do these things to the socket if another thread is using the socket.
7378 std::lock_guard<std::mutex> guard(socket_mutex_);
7379 shutdown_ssl(socket_, true);
7380 shutdown_socket(socket_);
7381 close_socket(socket_);
7382 }
7383
7384 if (300 < res.status && res.status < 400 && follow_location_) {
7385 req = req_save;
7386 ret = redirect(req, res, error);
7387 }
7388
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_;
7395
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));
7404
7405 Response new_res;
7406
7407 ret = send(new_req, new_res, error);
7408 if (ret) {
7409 res = new_res;
7410 }
7411 }
7412 }
7413 }
7414#endif
7415
7416 return ret;
7417}
7418
7419inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
7420 if (req.redirect_count_ == 0) {
7421 error = Error::ExceedRedirectCount;
7422 return false;
7423 }
7424
7425 auto location = res.get_header_value("location");
7426 if (location.empty()) {
7427 return false;
7428 }
7429
7430 const static std::regex re(
7431 R"((?:(https?):)?(?://(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*)(\?[^#]*)?(?:#.*)?)");
7432
7433 std::smatch m;
7434 if (!std::regex_match(location, m, re)) {
7435 return false;
7436 }
7437
7438 auto scheme = is_ssl() ? "https" : "http";
7439
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();
7444 }
7445 auto port_str = m[4].str();
7446 auto next_path = m[5].str();
7447 auto next_query = m[6].str();
7448
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;
7454 }
7455
7456 if (next_scheme.empty()) {
7457 next_scheme = scheme;
7458 }
7459 if (next_host.empty()) {
7460 next_host = host_;
7461 }
7462 if (next_path.empty()) {
7463 next_path = "/";
7464 }
7465
7466 auto path = detail::decode_url(next_path, true) + next_query;
7467
7468 if (next_scheme == scheme && next_host == host_ && next_port == port_) {
7469 return detail::redirect(*this, req, res, path, location, error);
7470 } else {
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_);
7477 }
7478 return detail::redirect(cli, req, res, path, location, error);
7479#else
7480 return false;
7481#endif
7482 } else {
7483 ClientImpl cli(next_host, next_port);
7484 cli.copy_settings(*this);
7485 return detail::redirect(cli, req, res, path, location, error);
7486 }
7487 }
7488}
7489
7490inline bool ClientImpl::write_content_with_provider(Stream &strm, const Request &req, Error &error) const {
7491 auto is_shutting_down = []() { return false; };
7492
7493 if (req.is_chunked_content_provider_) {
7494 // TODO: Brotli support
7495 std::unique_ptr<detail::compressor> compressor;
7496#ifdef CPPHTTPLIB_ZLIB_SUPPORT
7497 if (compress_) {
7498 compressor = detail::make_unique<detail::gzip_compressor>();
7499 } else
7500#endif
7501 {
7502 compressor = detail::make_unique<detail::nocompressor>();
7503 }
7504
7505 return detail::write_content_chunked(strm, req.content_provider_, is_shutting_down, *compressor, error);
7506 } else {
7507 return detail::write_content(strm, req.content_provider_, 0, req.content_length_, is_shutting_down, error);
7508 }
7509}
7510
7511inline bool ClientImpl::write_request(Stream &strm, Request &req, bool close_connection, Error &error) {
7512 // Prepare additional headers
7513 if (close_connection) {
7514 if (!req.has_header("Connection")) {
7515 req.set_header("Connection", "close");
7516 }
7517 }
7518
7519 if (!req.has_header("Host")) {
7520 if (is_ssl()) {
7521 if (port_ == 443) {
7522 req.set_header("Host", host_);
7523 } else {
7524 req.set_header("Host", host_and_port_);
7525 }
7526 } else {
7527 if (port_ == 80) {
7528 req.set_header("Host", host_);
7529 } else {
7530 req.set_header("Host", host_and_port_);
7531 }
7532 }
7533 }
7534
7535 if (!req.has_header("Accept")) {
7536 req.set_header("Accept", "*/*");
7537 }
7538
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";
7544#endif
7545#ifdef CPPHTTPLIB_ZLIB_SUPPORT
7546 if (!accept_encoding.empty()) {
7547 accept_encoding += ", ";
7548 }
7549 accept_encoding += "gzip, deflate";
7550#endif
7551 req.set_header("Accept-Encoding", accept_encoding);
7552 }
7553
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);
7558 }
7559#endif
7560 };
7561
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);
7568 }
7569 }
7570 } else {
7571 if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH") {
7572 req.set_header("Content-Length", "0");
7573 }
7574 }
7575 } else {
7576 if (!req.has_header("Content-Type")) {
7577 req.set_header("Content-Type", "text/plain");
7578 }
7579
7580 if (!req.has_header("Content-Length")) {
7581 auto length = std::to_string(req.body.size());
7582 req.set_header("Content-Length", length);
7583 }
7584 }
7585
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));
7589 }
7590 }
7591
7592 if (!proxy_basic_auth_username_.empty() && !proxy_basic_auth_password_.empty()) {
7593 if (!req.has_header("Proxy-Authorization")) {
7594 req.headers.insert(
7595 make_basic_authentication_header(proxy_basic_auth_username_, proxy_basic_auth_password_, true));
7596 }
7597 }
7598
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));
7602 }
7603 }
7604
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));
7608 }
7609 }
7610
7611 // Request line and headers
7612 {
7613 detail::BufferStream bstrm;
7614
7615 const auto &path_with_query = req.params.empty() ? req.path : append_query_params(req.path, req.params);
7616
7617 const auto &path = url_encode_ ? detail::encode_url(path_with_query) : path_with_query;
7618
7619 detail::write_request_line(bstrm, req.method, path);
7620
7621 header_writer_(bstrm, req.headers);
7622
7623 // Flush buffer
7624 auto &data = bstrm.get_buffer();
7625 if (!detail::write_data(strm, data.data(), data.size())) {
7626 error = Error::Write;
7627 return false;
7628 }
7629 }
7630
7631 // Body
7632 if (req.body.empty()) {
7633 return write_content_with_provider(strm, req, error);
7634 }
7635
7636 if (!detail::write_data(strm, req.body.data(), req.body.size())) {
7637 error = Error::Write;
7638 return false;
7639 }
7640
7641 return true;
7642}
7643
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);
7649 }
7650
7651#ifdef CPPHTTPLIB_ZLIB_SUPPORT
7652 if (compress_) {
7653 req.set_header("Content-Encoding", "gzip");
7654 }
7655#endif
7656
7657#ifdef CPPHTTPLIB_ZLIB_SUPPORT
7658 if (compress_ && !content_provider_without_length) {
7659 // TODO: Brotli support
7660 detail::gzip_compressor compressor;
7661
7662 if (content_provider) {
7663 auto ok = true;
7664 size_t offset = 0;
7665 DataSink data_sink;
7666
7667 data_sink.write = [&](const char *data, size_t data_len) -> bool {
7668 if (ok) {
7669 auto last = offset + data_len == content_length;
7670
7671 auto ret =
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);
7674 return true;
7675 });
7676
7677 if (ret) {
7678 offset += data_len;
7679 } else {
7680 ok = false;
7681 }
7682 }
7683 return ok;
7684 };
7685
7686 while (ok && offset < content_length) {
7687 if (!content_provider(offset, content_length - offset, data_sink)) {
7688 error = Error::Canceled;
7689 return nullptr;
7690 }
7691 }
7692 } else {
7693 if (!compressor.compress(body, content_length, true, [&](const char *data, size_t data_len) {
7694 req.body.append(data, data_len);
7695 return true;
7696 })) {
7697 error = Error::Compression;
7698 return nullptr;
7699 }
7700 }
7701 } else
7702#endif
7703 {
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");
7713 } else {
7714 req.body.assign(body, content_length);
7715 }
7716 }
7717
7718 auto res = detail::make_unique<Response>();
7719 return send(req, *res, error) ? std::move(res) : nullptr;
7720}
7721
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) {
7727 Request req;
7728 req.method = method;
7729 req.headers = headers;
7730 req.path = path;
7731 req.progress = progress;
7732
7733 auto error = Error::Success;
7734
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);
7737
7738 return Result{std::move(res), error, std::move(req.headers)};
7739}
7740
7741inline std::string ClientImpl::adjust_host_string(const std::string &host) const {
7742 if (host.find(':') != std::string::npos) {
7743 return "[" + host + "]";
7744 }
7745 return host;
7746}
7747
7748inline bool ClientImpl::process_request(Stream &strm, Request &req, Response &res, bool close_connection,
7749 Error &error) {
7750 // Send request
7751 if (!write_request(strm, req, close_connection, error)) {
7752 return false;
7753 }
7754
7755#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
7756 if (is_ssl()) {
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_;
7761 return false;
7762 }
7763 }
7764 }
7765#endif
7766
7767 // Receive response and headers
7768 if (!read_response_line(strm, req, res) || !detail::read_headers(strm, res.headers)) {
7769 error = Error::Read;
7770 return false;
7771 }
7772
7773 // Body
7774 if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" && req.method != "CONNECT") {
7775 auto redirect = 300 < res.status && res.status < 400 && follow_location_;
7776
7777 if (req.response_handler && !redirect) {
7778 if (!req.response_handler(res)) {
7779 error = Error::Canceled;
7780 return false;
7781 }
7782 }
7783
7784 auto out =
7785 req.content_receiver
7786 ? static_cast<ContentReceiverWithProgress>([&](const char *buf, size_t n, uint64_t off, uint64_t len) {
7787 if (redirect) {
7788 return true;
7789 }
7790 auto ret = req.content_receiver(buf, n, off, len);
7791 if (!ret) {
7792 error = Error::Canceled;
7793 }
7794 return ret;
7795 })
7796 : static_cast<ContentReceiverWithProgress>(
7797 [&](const char *buf, size_t n, uint64_t /*off*/, uint64_t /*len*/) {
7798 assert(res.body.size() + n <= res.body.max_size());
7799 res.body.append(buf, n);
7800 return true;
7801 });
7802
7803 auto progress = [&](uint64_t current, uint64_t total) {
7804 if (!req.progress || redirect) {
7805 return true;
7806 }
7807 auto ret = req.progress(current, total);
7808 if (!ret) {
7809 error = Error::Canceled;
7810 }
7811 return ret;
7812 };
7813
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;
7819 return false;
7820 }
7821 res.body.reserve(len);
7822 }
7823 }
7824
7825 int dummy_status;
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;
7830 }
7831 return false;
7832 }
7833 }
7834
7835 // Log
7836 if (logger_) {
7837 logger_(req, res);
7838 }
7839
7840 return true;
7841}
7842
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;
7848 // cur_item and cur_start are copied to within the std::function and maintain
7849 // state between successive calls
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);
7853 return true;
7854 } else if (cur_item < provider_items.size()) {
7855 if (!cur_start) {
7856 const auto &begin = detail::serialize_multipart_formdata_item_begin(provider_items[cur_item], boundary);
7857 offset += begin.size();
7858 cur_start = offset;
7859 sink.os << begin;
7860 }
7861
7862 DataSink cur_sink;
7863 auto has_data = true;
7864 cur_sink.write = sink.write;
7865 cur_sink.done = [&]() { has_data = false; };
7866
7867 if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
7868 return false;
7869 }
7870
7871 if (!has_data) {
7872 sink.os << detail::serialize_multipart_formdata_item_end();
7873 cur_item++;
7874 cur_start = 0;
7875 }
7876 return true;
7877 } else {
7878 sink.os << detail::serialize_multipart_formdata_finish(boundary);
7879 sink.done();
7880 return true;
7881 }
7882 };
7883}
7884
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));
7888}
7889
7890inline bool ClientImpl::is_ssl() const { return false; }
7891
7892inline Result ClientImpl::Get(const std::string &path) { return Get(path, Headers(), Progress()); }
7893
7894inline Result ClientImpl::Get(const std::string &path, Progress progress) {
7895 return Get(path, Headers(), std::move(progress));
7896}
7897
7898inline Result ClientImpl::Get(const std::string &path, const Headers &headers) {
7899 return Get(path, headers, Progress());
7900}
7901
7902inline Result ClientImpl::Get(const std::string &path, const Headers &headers, Progress progress) {
7903 Request req;
7904 req.method = "GET";
7905 req.path = path;
7906 req.headers = headers;
7907 req.progress = std::move(progress);
7908
7909 return send_(std::move(req));
7910}
7911
7912inline Result ClientImpl::Get(const std::string &path, ContentReceiver content_receiver) {
7913 return Get(path, Headers(), nullptr, std::move(content_receiver), nullptr);
7914}
7915
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));
7918}
7919
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);
7922}
7923
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));
7927}
7928
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);
7932}
7933
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);
7937}
7938
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));
7942}
7943
7944inline Result ClientImpl::Get(const std::string &path, const Headers &headers, ResponseHandler response_handler,
7945 ContentReceiver content_receiver, Progress progress) {
7946 Request req;
7947 req.method = "GET";
7948 req.path = path;
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 /*offset*/,
7952 uint64_t /*total_length*/) { return content_receiver(data, data_length); };
7953 req.progress = std::move(progress);
7954
7955 return send_(std::move(req));
7956}
7957
7958inline Result ClientImpl::Get(const std::string &path, const Params &params, const Headers &headers,
7959 Progress progress) {
7960 if (params.empty()) {
7961 return Get(path, headers);
7962 }
7963
7964 std::string path_with_query = append_query_params(path, params);
7965 return Get(path_with_query, headers, std::move(progress));
7966}
7967
7968inline Result ClientImpl::Get(const std::string &path, const Params &params, const Headers &headers,
7969 ContentReceiver content_receiver, Progress progress) {
7970 return Get(path, params, headers, nullptr, std::move(content_receiver), std::move(progress));
7971}
7972
7973inline Result ClientImpl::Get(const std::string &path, const Params &params, 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));
7977 }
7978
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));
7981}
7982
7983inline Result ClientImpl::Head(const std::string &path) { return Head(path, Headers()); }
7984
7985inline Result ClientImpl::Head(const std::string &path, const Headers &headers) {
7986 Request req;
7987 req.method = "HEAD";
7988 req.headers = headers;
7989 req.path = path;
7990
7991 return send_(std::move(req));
7992}
7993
7994inline Result ClientImpl::Post(const std::string &path) { return Post(path, std::string(), std::string()); }
7995
7996inline Result ClientImpl::Post(const std::string &path, const Headers &headers) {
7997 return Post(path, headers, nullptr, 0, std::string());
7998}
7999
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);
8003}
8004
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,
8008 nullptr);
8009}
8010
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,
8014 progress);
8015}
8016
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);
8019}
8020
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);
8024}
8025
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,
8029 nullptr);
8030}
8031
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,
8035 progress);
8036}
8037
8038inline Result ClientImpl::Post(const std::string &path, const Params &params) { return Post(path, Headers(), params); }
8039
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);
8043}
8044
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);
8048}
8049
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);
8054}
8055
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);
8060}
8061
8062inline Result ClientImpl::Post(const std::string &path, const Headers &headers, const Params &params) {
8063 auto query = detail::params_to_query_str(params);
8064 return Post(path, headers, query, "application/x-www-form-urlencoded");
8065}
8066
8067inline Result ClientImpl::Post(const std::string &path, const Headers &headers, const Params &params,
8068 Progress progress) {
8069 auto query = detail::params_to_query_str(params);
8070 return Post(path, headers, query, "application/x-www-form-urlencoded", progress);
8071}
8072
8073inline Result ClientImpl::Post(const std::string &path, const MultipartFormDataItems &items) {
8074 return Post(path, Headers(), items);
8075}
8076
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);
8082}
8083
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};
8088 }
8089
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);
8093}
8094
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,
8101 nullptr);
8102}
8103
8104inline Result ClientImpl::Put(const std::string &path) { return Put(path, std::string(), std::string()); }
8105
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);
8109}
8110
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,
8114 nullptr);
8115}
8116
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,
8120 progress);
8121}
8122
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);
8125}
8126
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);
8130}
8131
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,
8135 nullptr);
8136}
8137
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,
8141 progress);
8142}
8143
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);
8147}
8148
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);
8152}
8153
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);
8158}
8159
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);
8164}
8165
8166inline Result ClientImpl::Put(const std::string &path, const Params &params) { return Put(path, Headers(), params); }
8167
8168inline Result ClientImpl::Put(const std::string &path, const Headers &headers, const Params &params) {
8169 auto query = detail::params_to_query_str(params);
8170 return Put(path, headers, query, "application/x-www-form-urlencoded");
8171}
8172
8173inline Result ClientImpl::Put(const std::string &path, const Headers &headers, const Params &params,
8174 Progress progress) {
8175 auto query = detail::params_to_query_str(params);
8176 return Put(path, headers, query, "application/x-www-form-urlencoded", progress);
8177}
8178
8179inline Result ClientImpl::Put(const std::string &path, const MultipartFormDataItems &items) {
8180 return Put(path, Headers(), items);
8181}
8182
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);
8188}
8189
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};
8194 }
8195
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);
8199}
8200
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,
8207 nullptr);
8208}
8209inline Result ClientImpl::Patch(const std::string &path) { return Patch(path, std::string(), std::string()); }
8210
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);
8214}
8215
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);
8219}
8220
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);
8224}
8225
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,
8229 progress);
8230}
8231
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);
8234}
8235
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);
8239}
8240
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);
8244}
8245
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,
8249 progress);
8250}
8251
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);
8255}
8256
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);
8260}
8261
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);
8266}
8267
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);
8272}
8273
8274inline Result ClientImpl::Delete(const std::string &path) {
8275 return Delete(path, Headers(), std::string(), std::string());
8276}
8277
8278inline Result ClientImpl::Delete(const std::string &path, const Headers &headers) {
8279 return Delete(path, headers, std::string(), std::string());
8280}
8281
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);
8285}
8286
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);
8290}
8291
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);
8295}
8296
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) {
8299 Request req;
8300 req.method = "DELETE";
8301 req.headers = headers;
8302 req.path = path;
8303 req.progress = progress;
8304
8305 if (!content_type.empty()) {
8306 req.set_header("Content-Type", content_type);
8307 }
8308 req.body.assign(body, content_length);
8309
8310 return send_(std::move(req));
8311}
8312
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);
8315}
8316
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);
8320}
8321
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);
8325}
8326
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);
8330}
8331
8332inline Result ClientImpl::Options(const std::string &path) { return Options(path, Headers()); }
8333
8334inline Result ClientImpl::Options(const std::string &path, const Headers &headers) {
8335 Request req;
8336 req.method = "OPTIONS";
8337 req.headers = headers;
8338 req.path = path;
8339
8340 return send_(std::move(req));
8341}
8342
8343inline void ClientImpl::stop() {
8344 std::lock_guard<std::mutex> guard(socket_mutex_);
8345
8346 // If there is anything ongoing right now, the ONLY thread-safe thing we can
8347 // do is to shutdown_socket, so that threads using this socket suddenly
8348 // discover they can't read/write any more and error out. Everything else
8349 // (closing the socket, shutting ssl down) is unsafe because these actions are
8350 // not thread-safe.
8351 if (socket_requests_in_flight_ > 0) {
8352 shutdown_socket(socket_);
8353
8354 // Aside from that, we set a flag for the socket to be closed when we're
8355 // done.
8356 socket_should_be_closed_when_request_is_done_ = true;
8357 return;
8358 }
8359
8360 // Otherwise, still holding the mutex, we can shut everything down ourselves
8361 shutdown_ssl(socket_, true);
8362 shutdown_socket(socket_);
8363 close_socket(socket_);
8364}
8365
8366inline std::string ClientImpl::host() const { return host_; }
8367
8368inline int ClientImpl::port() const { return port_; }
8369
8370inline size_t ClientImpl::is_socket_open() const {
8371 std::lock_guard<std::mutex> guard(socket_mutex_);
8372 return socket_.is_open();
8373}
8374
8375inline socket_t ClientImpl::socket() const { return socket_.sock; }
8376
8377inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
8378 connection_timeout_sec_ = sec;
8379 connection_timeout_usec_ = usec;
8380}
8381
8382inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
8383 read_timeout_sec_ = sec;
8384 read_timeout_usec_ = usec;
8385}
8386
8387inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
8388 write_timeout_sec_ = sec;
8389 write_timeout_usec_ = usec;
8390}
8391
8392inline void ClientImpl::set_basic_auth(const std::string &username, const std::string &password) {
8393 basic_auth_username_ = username;
8394 basic_auth_password_ = password;
8395}
8396
8397inline void ClientImpl::set_bearer_token_auth(const std::string &token) { bearer_token_auth_token_ = token; }
8398
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;
8403}
8404#endif
8405
8406inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
8407
8408inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
8409
8410inline void ClientImpl::set_url_encode(bool on) { url_encode_ = on; }
8411
8412inline void ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
8413 addr_map_ = std::move(addr_map);
8414}
8415
8416inline void ClientImpl::set_default_headers(Headers headers) { default_headers_ = std::move(headers); }
8417
8418inline void ClientImpl::set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer) {
8419 header_writer_ = writer;
8420}
8421
8422inline void ClientImpl::set_address_family(int family) { address_family_ = family; }
8423
8424inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
8425
8426inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
8427
8428inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
8429 socket_options_ = std::move(socket_options);
8430}
8431
8432inline void ClientImpl::set_compress(bool on) { compress_ = on; }
8433
8434inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
8435
8436inline void ClientImpl::set_interface(const std::string &intf) { interface_ = intf; }
8437
8438inline void ClientImpl::set_proxy(const std::string &host, int port) {
8439 proxy_host_ = host;
8440 proxy_port_ = port;
8441}
8442
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;
8446}
8447
8448inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
8449 proxy_bearer_token_auth_token_ = token;
8450}
8451
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;
8456}
8457
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;
8461}
8462
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;
8466 }
8467}
8468
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); });
8472 if (!mem) {
8473 return nullptr;
8474 }
8475
8476 auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
8477 if (!inf) {
8478 return nullptr;
8479 }
8480
8481 auto cts = X509_STORE_new();
8482 if (cts) {
8483 for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
8484 auto itmp = sk_X509_INFO_value(inf, i);
8485 if (!itmp) {
8486 continue;
8487 }
8488
8489 if (itmp->x509) {
8490 X509_STORE_add_cert(cts, itmp->x509);
8491 }
8492 if (itmp->crl) {
8493 X509_STORE_add_crl(cts, itmp->crl);
8494 }
8495 }
8496 }
8497
8498 sk_X509_INFO_pop_free(inf, X509_INFO_free);
8499 return cts;
8500}
8501
8502inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
8503 server_certificate_verification_ = enabled;
8504}
8505
8506inline void ClientImpl::enable_server_hostname_verification(bool enabled) { server_hostname_verification_ = enabled; }
8507
8508inline void ClientImpl::set_server_certificate_verifier(std::function<bool(SSL *ssl)> verifier) {
8509 server_certificate_verifier_ = verifier;
8510}
8511#endif
8512
8513inline void ClientImpl::set_logger(Logger logger) { logger_ = std::move(logger); }
8514
8515/*
8516 * SSL Implementation
8517 */
8518#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
8519namespace detail {
8520
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) {
8523 SSL *ssl = nullptr;
8524 {
8525 std::lock_guard<std::mutex> guard(ctx_mutex);
8526 ssl = SSL_new(ctx);
8527 }
8528
8529 if (ssl) {
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);
8534
8535 if (!setup(ssl) || SSL_connect_or_accept(ssl) != 1) {
8536 SSL_shutdown(ssl);
8537 {
8538 std::lock_guard<std::mutex> guard(ctx_mutex);
8539 SSL_free(ssl);
8540 }
8541 set_nonblocking(sock, false);
8542 return nullptr;
8543 }
8544 BIO_set_nbio(bio, 0);
8545 set_nonblocking(sock, false);
8546 }
8547
8548 return ssl;
8549}
8550
8551inline void ssl_delete(std::mutex &ctx_mutex, SSL *ssl, socket_t sock, bool shutdown_gracefully) {
8552 // sometimes we may want to skip this to try to avoid SIGPIPE if we know
8553 // the remote has closed the network connection
8554 // Note that it is not always possible to avoid SIGPIPE, this is merely a
8555 // best-efforts.
8556 if (shutdown_gracefully) {
8557#ifdef _WIN32
8558 SSL_shutdown(ssl);
8559#else
8560 timeval tv;
8561 tv.tv_sec = 1;
8562 tv.tv_usec = 0;
8563 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const void *>(&tv), sizeof(tv));
8564
8565 auto ret = SSL_shutdown(ssl);
8566 while (ret == 0) {
8567 std::this_thread::sleep_for(std::chrono::milliseconds{100});
8568 ret = SSL_shutdown(ssl);
8569 }
8570#endif
8571 }
8572
8573 std::lock_guard<std::mutex> guard(ctx_mutex);
8574 SSL_free(ssl);
8575}
8576
8577template<typename U>
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) {
8580 auto res = 0;
8581 while ((res = ssl_connect_or_accept(ssl)) != 1) {
8582 auto err = SSL_get_error(ssl, res);
8583 switch (err) {
8584 case SSL_ERROR_WANT_READ:
8585 if (select_read(sock, timeout_sec, timeout_usec) > 0) {
8586 continue;
8587 }
8588 break;
8589 case SSL_ERROR_WANT_WRITE:
8590 if (select_write(sock, timeout_sec, timeout_usec) > 0) {
8591 continue;
8592 }
8593 break;
8594 default:
8595 break;
8596 }
8597 return false;
8598 }
8599 return true;
8600}
8601
8602template<typename T>
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);
8612 });
8613}
8614
8615template<typename T>
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);
8620}
8621
8622class SSLInit {
8623 public:
8624 SSLInit() { OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL); }
8625};
8626
8627// SSL socket stream implementation
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)
8630 : sock_(sock),
8631 ssl_(ssl),
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);
8637}
8638
8639inline SSLSocketStream::~SSLSocketStream() = default;
8640
8641inline bool SSLSocketStream::is_readable() const {
8642 return detail::select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
8643}
8644
8645inline bool SSLSocketStream::is_writable() const {
8646 return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 && is_socket_alive(sock_);
8647}
8648
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));
8654 if (ret < 0) {
8655 auto err = SSL_get_error(ssl_, ret);
8656 auto n = 1000;
8657#ifdef _WIN32
8658 while (--n >= 0 &&
8659 (err == SSL_ERROR_WANT_READ || (err == SSL_ERROR_SYSCALL && WSAGetLastError() == WSAETIMEDOUT))) {
8660#else
8661 while (--n >= 0 && err == SSL_ERROR_WANT_READ) {
8662#endif
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));
8668 if (ret >= 0) {
8669 return ret;
8670 }
8671 err = SSL_get_error(ssl_, ret);
8672 } else {
8673 return -1;
8674 }
8675 }
8676 }
8677 return ret;
8678 }
8679 return -1;
8680}
8681
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)()));
8685
8686 auto ret = SSL_write(ssl_, ptr, static_cast<int>(handle_size));
8687 if (ret < 0) {
8688 auto err = SSL_get_error(ssl_, ret);
8689 auto n = 1000;
8690#ifdef _WIN32
8691 while (--n >= 0 &&
8692 (err == SSL_ERROR_WANT_WRITE || (err == SSL_ERROR_SYSCALL && WSAGetLastError() == WSAETIMEDOUT))) {
8693#else
8694 while (--n >= 0 && err == SSL_ERROR_WANT_WRITE) {
8695#endif
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));
8699 if (ret >= 0) {
8700 return ret;
8701 }
8702 err = SSL_get_error(ssl_, ret);
8703 } else {
8704 return -1;
8705 }
8706 }
8707 }
8708 return ret;
8709 }
8710 return -1;
8711}
8712
8713inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip, int &port) const {
8714 detail::get_remote_ip_and_port(sock_, ip, port);
8715}
8716
8717inline void SSLSocketStream::get_local_ip_and_port(std::string &ip, int &port) const {
8718 detail::get_local_ip_and_port(sock_, ip, port);
8719}
8720
8721inline socket_t SSLSocketStream::socket() const { return sock_; }
8722
8723static SSLInit sslinit_;
8724
8725} // namespace detail
8726
8727// SSL HTTP server implementation
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());
8731
8732 if (ctx_) {
8733 SSL_CTX_set_options(ctx_, SSL_OP_NO_COMPRESSION | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
8734
8735 SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
8736
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)));
8739 }
8740
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) {
8744 SSL_CTX_free(ctx_);
8745 ctx_ = nullptr;
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);
8748
8749 SSL_CTX_set_verify(ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
8750 }
8751 }
8752}
8753
8754inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key, X509_STORE *client_ca_cert_store) {
8755 ctx_ = SSL_CTX_new(TLS_server_method());
8756
8757 if (ctx_) {
8758 SSL_CTX_set_options(ctx_, SSL_OP_NO_COMPRESSION | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
8759
8760 SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
8761
8762 if (SSL_CTX_use_certificate(ctx_, cert) != 1 || SSL_CTX_use_PrivateKey(ctx_, private_key) != 1) {
8763 SSL_CTX_free(ctx_);
8764 ctx_ = nullptr;
8765 } else if (client_ca_cert_store) {
8766 SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
8767
8768 SSL_CTX_set_verify(ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
8769 }
8770 }
8771}
8772
8773inline SSLServer::SSLServer(const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback) {
8774 ctx_ = SSL_CTX_new(TLS_method());
8775 if (ctx_) {
8776 if (!setup_ssl_ctx_callback(*ctx_)) {
8777 SSL_CTX_free(ctx_);
8778 ctx_ = nullptr;
8779 }
8780 }
8781}
8782
8783inline SSLServer::~SSLServer() {
8784 if (ctx_) {
8785 SSL_CTX_free(ctx_);
8786 }
8787}
8788
8789inline bool SSLServer::is_valid() const { return ctx_; }
8790
8791inline SSL_CTX *SSLServer::ssl_context() const { return ctx_; }
8792
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_);
8795
8796 SSL_CTX_use_certificate(ctx_, cert);
8797 SSL_CTX_use_PrivateKey(ctx_, private_key);
8798
8799 if (client_ca_cert_store != nullptr) {
8800 SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
8801 }
8802}
8803
8804inline bool SSLServer::process_and_close_socket(socket_t sock) {
8805 auto ssl = detail::ssl_new(
8806 sock, ctx_, ctx_mutex_,
8807 [&](SSL *ssl2) {
8808 return detail::ssl_connect_or_accept_nonblocking(sock, ssl2, SSL_accept, read_timeout_sec_, read_timeout_usec_);
8809 },
8810 [](SSL * /*ssl2*/) { return true; });
8811
8812 auto ret = false;
8813 if (ssl) {
8814 std::string remote_addr;
8815 int remote_port = 0;
8816 detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
8817
8818 std::string local_addr;
8819 int local_port = 0;
8820 detail::get_local_ip_and_port(sock, local_addr, local_port);
8821
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; });
8827 });
8828
8829 // Shutdown gracefully if the result seemed successful, non-gracefully if
8830 // the connection appeared to be closed.
8831 const bool shutdown_gracefully = ret;
8832 detail::ssl_delete(ctx_mutex_, ssl, sock, shutdown_gracefully);
8833 }
8834
8835 detail::shutdown_socket(sock);
8836 detail::close_socket(sock);
8837 return ret;
8838}
8839
8840// SSL HTTP client implementation
8841inline SSLClient::SSLClient(const std::string &host) : SSLClient(host, 443, std::string(), std::string()) {}
8842
8843inline SSLClient::SSLClient(const std::string &host, int port) : SSLClient(host, port, std::string(), std::string()) {}
8844
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());
8849
8850 SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
8851
8852 detail::split(&host_[0], &host_[host_.size()], '.',
8853 [&](const char *b, const char *e) { host_components_.emplace_back(b, e); });
8854
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())));
8859 }
8860
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) {
8863 SSL_CTX_free(ctx_);
8864 ctx_ = nullptr;
8865 }
8866 }
8867}
8868
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());
8873
8874 detail::split(&host_[0], &host_[host_.size()], '.',
8875 [&](const char *b, const char *e) { host_components_.emplace_back(b, e); });
8876
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())));
8881 }
8882
8883 if (SSL_CTX_use_certificate(ctx_, client_cert) != 1 || SSL_CTX_use_PrivateKey(ctx_, client_key) != 1) {
8884 SSL_CTX_free(ctx_);
8885 ctx_ = nullptr;
8886 }
8887 }
8888}
8889
8890inline SSLClient::~SSLClient() {
8891 if (ctx_) {
8892 SSL_CTX_free(ctx_);
8893 }
8894 // Make sure to shut down SSL since shutdown_ssl will resolve to the
8895 // base function rather than the derived function once we get to the
8896 // base class destructor, and won't free the SSL (causing a leak).
8897 shutdown_ssl_impl(socket_, true);
8898}
8899
8900inline bool SSLClient::is_valid() const { return ctx_; }
8901
8902inline void SSLClient::set_ca_cert_store(X509_STORE *ca_cert_store) {
8903 if (ca_cert_store) {
8904 if (ctx_) {
8905 if (SSL_CTX_get_cert_store(ctx_) != ca_cert_store) {
8906 // Free memory allocated for old cert and use new store `ca_cert_store`
8907 SSL_CTX_set_cert_store(ctx_, ca_cert_store);
8908 }
8909 } else {
8910 X509_STORE_free(ca_cert_store);
8911 }
8912 }
8913}
8914
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));
8917}
8918
8919inline long SSLClient::get_openssl_verify_result() const { return verify_result_; }
8920
8921inline SSL_CTX *SSLClient::ssl_context() const { return ctx_; }
8922
8923inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
8924 return is_valid() && ClientImpl::create_and_connect_socket(socket, error);
8925}
8926
8927// Assumes that socket_mutex_ is locked and that there are no requests in flight
8928inline bool SSLClient::connect_with_proxy(Socket &socket, Response &res, bool &success, Error &error) {
8929 success = true;
8930 Response proxy_res;
8931 if (!detail::process_client_socket(socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
8932 write_timeout_usec_, [&](Stream &strm) {
8933 Request req2;
8934 req2.method = "CONNECT";
8935 req2.path = host_and_port_;
8936 return process_request(strm, req2, proxy_res, false, error);
8937 })) {
8938 // Thread-safe to close everything because we are assuming there are no
8939 // requests in flight
8940 shutdown_ssl(socket, true);
8941 shutdown_socket(socket);
8942 close_socket(socket);
8943 success = false;
8944 return false;
8945 }
8946
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) {
8954 Request req3;
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);
8961 })) {
8962 // Thread-safe to close everything because we are assuming there are
8963 // no requests in flight
8964 shutdown_ssl(socket, true);
8965 shutdown_socket(socket);
8966 close_socket(socket);
8967 success = false;
8968 return false;
8969 }
8970 }
8971 }
8972 }
8973
8974 // If status code is not 200, proxy request is failed.
8975 // Set error to ProxyConnection and return proxy response
8976 // as the response of the request
8977 if (proxy_res.status != StatusCode::OK_200) {
8978 error = Error::ProxyConnection;
8979 res = std::move(proxy_res);
8980 // Thread-safe to close everything because we are assuming there are
8981 // no requests in flight
8982 shutdown_ssl(socket, true);
8983 shutdown_socket(socket);
8984 close_socket(socket);
8985 return false;
8986 }
8987
8988 return true;
8989}
8990
8991inline bool SSLClient::load_certs() {
8992 auto ret = true;
8993
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)) {
8998 ret = false;
8999 }
9000 } else if (!ca_cert_dir_path_.empty()) {
9001 if (!SSL_CTX_load_verify_locations(ctx_, nullptr, ca_cert_dir_path_.c_str())) {
9002 ret = false;
9003 }
9004 } else {
9005 auto loaded = false;
9006#ifdef _WIN32
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__)
9009#if TARGET_OS_OSX
9010 loaded = detail::load_system_certs_on_macos(SSL_CTX_get_cert_store(ctx_));
9011#endif // TARGET_OS_OSX
9012#endif // _WIN32
9013 if (!loaded) {
9014 SSL_CTX_set_default_verify_paths(ctx_);
9015 }
9016 }
9017 });
9018
9019 return ret;
9020}
9021
9022inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
9023 auto ssl = detail::ssl_new(
9024 socket.sock, ctx_, ctx_mutex_,
9025 [&](SSL *ssl2) {
9026 if (server_certificate_verification_) {
9027 if (!load_certs()) {
9028 error = Error::SSLLoadingCerts;
9029 return false;
9030 }
9031 SSL_set_verify(ssl2, SSL_VERIFY_NONE, nullptr);
9032 }
9033
9034 if (!detail::ssl_connect_or_accept_nonblocking(socket.sock, ssl2, SSL_connect, connection_timeout_sec_,
9035 connection_timeout_usec_)) {
9036 error = Error::SSLConnection;
9037 return false;
9038 }
9039
9040 if (server_certificate_verification_) {
9041 if (server_certificate_verifier_) {
9042 if (!server_certificate_verifier_(ssl2)) {
9043 error = Error::SSLServerVerification;
9044 return false;
9045 }
9046 } else {
9047 verify_result_ = SSL_get_verify_result(ssl2);
9048
9049 if (verify_result_ != X509_V_OK) {
9050 error = Error::SSLServerVerification;
9051 return false;
9052 }
9053
9054 auto server_cert = SSL_get1_peer_certificate(ssl2);
9055 auto se = detail::scope_exit([&] { X509_free(server_cert); });
9056
9057 if (server_cert == nullptr) {
9058 error = Error::SSLServerVerification;
9059 return false;
9060 }
9061
9062 if (server_hostname_verification_) {
9063 if (!verify_host(server_cert)) {
9064 error = Error::SSLServerHostnameVerification;
9065 return false;
9066 }
9067 }
9068 }
9069 }
9070
9071 return true;
9072 },
9073 [&](SSL *ssl2) {
9074#if defined(OPENSSL_IS_BORINGSSL)
9075 SSL_set_tlsext_host_name(ssl2, host_.c_str());
9076#else
9077 // NOTE: Direct call instead of using the OpenSSL macro to suppress
9078 // -Wold-style-cast warning
9079 SSL_ctrl(ssl2, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
9080 static_cast<void *>(const_cast<char *>(host_.c_str())));
9081#endif
9082 return true;
9083 });
9084
9085 if (ssl) {
9086 socket.ssl = ssl;
9087 return true;
9088 }
9089
9090 shutdown_socket(socket);
9091 close_socket(socket);
9092 return false;
9093}
9094
9095inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
9096 shutdown_ssl_impl(socket, shutdown_gracefully);
9097}
9098
9099inline void SSLClient::shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully) {
9100 if (socket.sock == INVALID_SOCKET) {
9101 assert(socket.ssl == nullptr);
9102 return;
9103 }
9104 if (socket.ssl) {
9105 detail::ssl_delete(ctx_mutex_, socket.ssl, socket.sock, shutdown_gracefully);
9106 socket.ssl = nullptr;
9107 }
9108 assert(socket.ssl == nullptr);
9109}
9110
9111inline bool SSLClient::process_socket(const Socket &socket, std::function<bool(Stream &strm)> callback) {
9112 assert(socket.ssl);
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));
9115}
9116
9117inline bool SSLClient::is_ssl() const { return true; }
9118
9119inline bool SSLClient::verify_host(X509 *server_cert) const {
9120 /* Quote from RFC2818 section 3.1 "Server Identity"
9121
9122 If a subjectAltName extension of type dNSName is present, that MUST
9123 be used as the identity. Otherwise, the (most specific) Common Name
9124 field in the Subject field of the certificate MUST be used. Although
9125 the use of the Common Name is existing practice, it is deprecated and
9126 Certification Authorities are encouraged to use the dNSName instead.
9127
9128 Matching is performed using the matching rules specified by
9129 [RFC2459]. If more than one identity of a given type is present in
9130 the certificate (e.g., more than one dNSName name, a match in any one
9131 of the set is considered acceptable.) Names may contain the wildcard
9132 character * which is considered to match any single domain name
9133 component or component fragment. E.g., *.a.com matches foo.a.com but
9134 not bar.foo.a.com. f*.com matches foo.com but not bar.com.
9135
9136 In some cases, the URI is specified as an IP address rather than a
9137 hostname. In this case, the iPAddress subjectAltName must be present
9138 in the certificate and must exactly match the IP in the URI.
9139
9140 */
9141 return verify_host_with_subject_alt_name(server_cert) || verify_host_with_common_name(server_cert);
9142}
9143
9144inline bool SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
9145 auto ret = false;
9146
9147 auto type = GEN_DNS;
9148
9149 struct in6_addr addr6{};
9150 struct in_addr addr{};
9151 size_t addr_len = 0;
9152
9153#ifndef __MINGW32__
9154 if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
9155 type = GEN_IPADD;
9156 addr_len = sizeof(struct in6_addr);
9157 } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
9158 type = GEN_IPADD;
9159 addr_len = sizeof(struct in_addr);
9160 }
9161#endif
9162
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));
9165
9166 if (alt_names) {
9167 auto dsn_matched = false;
9168 auto ip_matched = false;
9169
9170 auto count = sk_GENERAL_NAME_num(alt_names);
9171
9172 for (decltype(count) i = 0; i < count && !dsn_matched; i++) {
9173 auto val = sk_GENERAL_NAME_value(alt_names, i);
9174 if (val->type == type) {
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));
9177
9178 switch (type) {
9179 case GEN_DNS:
9180 dsn_matched = check_host_name(name, name_len);
9181 break;
9182
9183 case GEN_IPADD:
9184 if (!memcmp(&addr6, name, addr_len) || !memcmp(&addr, name, addr_len)) {
9185 ip_matched = true;
9186 }
9187 break;
9188 }
9189 }
9190 }
9191
9192 if (dsn_matched || ip_matched) {
9193 ret = true;
9194 }
9195 }
9196
9197 GENERAL_NAMES_free(const_cast<STACK_OF(GENERAL_NAME) *>(reinterpret_cast<const STACK_OF(GENERAL_NAME) *>(alt_names)));
9198 return ret;
9199}
9200
9201inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
9202 const auto subject_name = X509_get_subject_name(server_cert);
9203
9204 if (subject_name != nullptr) {
9205 char name[BUFSIZ];
9206 auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName, name, sizeof(name));
9207
9208 if (name_len != -1) {
9209 return check_host_name(name, static_cast<size_t>(name_len));
9210 }
9211 }
9212
9213 return false;
9214}
9215
9216inline bool SSLClient::check_host_name(const char *pattern, size_t pattern_len) const {
9217 if (host_.size() == pattern_len && host_ == pattern) {
9218 return true;
9219 }
9220
9221 // Wildcard match
9222 // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
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); });
9226
9227 if (host_components_.size() != pattern_components.size()) {
9228 return false;
9229 }
9230
9231 auto itr = pattern_components.begin();
9232 for (const auto &h : host_components_) {
9233 auto &p = *itr;
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) {
9237 return false;
9238 }
9239 }
9240 ++itr;
9241 }
9242
9243 return true;
9244}
9245#endif
9246
9247// Universal client implementation
9248inline Client::Client(const std::string &scheme_host_port) : Client(scheme_host_port, std::string(), std::string()) {}
9249
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+))?)");
9253
9254 std::smatch m;
9255 if (std::regex_match(scheme_host_port, m, re)) {
9256 auto scheme = m[1].str();
9257
9258#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
9259 if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
9260#else
9261 if (!scheme.empty() && scheme != "http") {
9262#endif
9263#ifndef CPPHTTPLIB_NO_EXCEPTIONS
9264 std::string msg = "'" + scheme + "' scheme is not supported.";
9265 throw std::invalid_argument(msg);
9266#endif
9267 return;
9268 }
9269
9270 auto is_ssl = scheme == "https";
9271
9272 auto host = m[2].str();
9273 if (host.empty()) {
9274 host = m[3].str();
9275 }
9276
9277 auto port_str = m[4].str();
9278 auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80);
9279
9280 if (is_ssl) {
9281#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
9282 cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path, client_key_path);
9283 is_ssl_ = is_ssl;
9284#endif
9285 } else {
9286 cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path, client_key_path);
9287 }
9288 } else {
9289 // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
9290 // if port param below changes.
9291 cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80, client_cert_path, client_key_path);
9292 }
9293} // namespace detail
9294
9295inline Client::Client(const std::string &host, int port) : cli_(detail::make_unique<ClientImpl>(host, port)) {}
9296
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)) {}
9300
9301inline Client::~Client() = default;
9302
9303inline bool Client::is_valid() const { return cli_ != nullptr && cli_->is_valid(); }
9304
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));
9310}
9311inline Result Client::Get(const std::string &path, ContentReceiver content_receiver) {
9312 return cli_->Get(path, std::move(content_receiver));
9313}
9314inline Result Client::Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver) {
9315 return cli_->Get(path, headers, std::move(content_receiver));
9316}
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));
9319}
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));
9323}
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));
9326}
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));
9330}
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));
9334}
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));
9338}
9339inline Result Client::Get(const std::string &path, const Params &params, const Headers &headers, Progress progress) {
9340 return cli_->Get(path, params, headers, std::move(progress));
9341}
9342inline Result Client::Get(const std::string &path, const Params &params, const Headers &headers,
9343 ContentReceiver content_receiver, Progress progress) {
9344 return cli_->Get(path, params, headers, std::move(content_receiver), std::move(progress));
9345}
9346inline Result Client::Get(const std::string &path, const Params &params, 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));
9350}
9351
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); }
9354
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);
9360}
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);
9364}
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);
9368}
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);
9371}
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);
9375}
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);
9379}
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);
9383}
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);
9387}
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);
9391}
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);
9395}
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);
9399}
9400inline Result Client::Post(const std::string &path, const Params &params) { return cli_->Post(path, params); }
9401inline Result Client::Post(const std::string &path, const Headers &headers, const Params &params) {
9402 return cli_->Post(path, headers, params);
9403}
9404inline Result Client::Post(const std::string &path, const Headers &headers, const Params &params, Progress progress) {
9405 return cli_->Post(path, headers, params, progress);
9406}
9407inline Result Client::Post(const std::string &path, const MultipartFormDataItems &items) {
9408 return cli_->Post(path, items);
9409}
9410inline Result Client::Post(const std::string &path, const Headers &headers, const MultipartFormDataItems &items) {
9411 return cli_->Post(path, headers, items);
9412}
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);
9416}
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);
9420}
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);
9425}
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);
9429}
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);
9433}
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);
9436}
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);
9440}
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);
9444}
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);
9448}
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);
9452}
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);
9456}
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);
9460}
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);
9464}
9465inline Result Client::Put(const std::string &path, const Params &params) { return cli_->Put(path, params); }
9466inline Result Client::Put(const std::string &path, const Headers &headers, const Params &params) {
9467 return cli_->Put(path, headers, params);
9468}
9469inline Result Client::Put(const std::string &path, const Headers &headers, const Params &params, Progress progress) {
9470 return cli_->Put(path, headers, params, progress);
9471}
9472inline Result Client::Put(const std::string &path, const MultipartFormDataItems &items) {
9473 return cli_->Put(path, items);
9474}
9475inline Result Client::Put(const std::string &path, const Headers &headers, const MultipartFormDataItems &items) {
9476 return cli_->Put(path, headers, items);
9477}
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);
9481}
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);
9485}
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);
9490}
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);
9494}
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);
9498}
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);
9502}
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);
9505}
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);
9509}
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);
9513}
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);
9517}
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);
9521}
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);
9525}
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);
9529}
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);
9533}
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);
9539}
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);
9543}
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);
9547}
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);
9551}
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);
9554}
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);
9558}
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);
9562}
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);
9566}
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); }
9569
9570inline bool Client::send(Request &req, Response &res, Error &error) { return cli_->send(req, res, error); }
9571
9572inline Result Client::send(const Request &req) { return cli_->send(req); }
9573
9574inline void Client::stop() { cli_->stop(); }
9575
9576inline std::string Client::host() const { return cli_->host(); }
9577
9578inline int Client::port() const { return cli_->port(); }
9579
9580inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
9581
9582inline socket_t Client::socket() const { return cli_->socket(); }
9583
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));
9586}
9587
9588inline void Client::set_default_headers(Headers headers) { cli_->set_default_headers(std::move(headers)); }
9589
9590inline void Client::set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer) {
9591 cli_->set_header_writer(writer);
9592}
9593
9594inline void Client::set_address_family(int family) { cli_->set_address_family(family); }
9595
9596inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
9597
9598inline void Client::set_socket_options(SocketOptions socket_options) {
9599 cli_->set_socket_options(std::move(socket_options));
9600}
9601
9602inline void Client::set_connection_timeout(time_t sec, time_t usec) { cli_->set_connection_timeout(sec, usec); }
9603
9604inline void Client::set_read_timeout(time_t sec, time_t usec) { cli_->set_read_timeout(sec, usec); }
9605
9606inline void Client::set_write_timeout(time_t sec, time_t usec) { cli_->set_write_timeout(sec, usec); }
9607
9608inline void Client::set_basic_auth(const std::string &username, const std::string &password) {
9609 cli_->set_basic_auth(username, password);
9610}
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);
9615}
9616#endif
9617
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); }
9620
9621inline void Client::set_url_encode(bool on) { cli_->set_url_encode(on); }
9622
9623inline void Client::set_compress(bool on) { cli_->set_compress(on); }
9624
9625inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
9626
9627inline void Client::set_interface(const std::string &intf) { cli_->set_interface(intf); }
9628
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);
9632}
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);
9637}
9638#endif
9639
9640#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
9641inline void Client::enable_server_certificate_verification(bool enabled) {
9642 cli_->enable_server_certificate_verification(enabled);
9643}
9644
9645inline void Client::enable_server_hostname_verification(bool enabled) {
9646 cli_->enable_server_hostname_verification(enabled);
9647}
9648
9649inline void Client::set_server_certificate_verifier(std::function<bool(SSL *ssl)> verifier) {
9650 cli_->set_server_certificate_verifier(verifier);
9651}
9652#endif
9653
9654inline void Client::set_logger(Logger logger) { cli_->set_logger(std::move(logger)); }
9655
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);
9659}
9660
9661inline void Client::set_ca_cert_store(X509_STORE *ca_cert_store) {
9662 if (is_ssl_) {
9663 static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
9664 } else {
9665 cli_->set_ca_cert_store(ca_cert_store);
9666 }
9667}
9668
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));
9671}
9672
9673inline long Client::get_openssl_verify_result() const {
9674 if (is_ssl_) {
9675 return static_cast<SSLClient &>(*cli_).get_openssl_verify_result();
9676 }
9677 return -1; // NOTE: -1 doesn't match any of X509_V_ERR_???
9678}
9679
9680inline SSL_CTX *Client::ssl_context() const {
9681 if (is_ssl_) {
9682 return static_cast<SSLClient &>(*cli_).ssl_context();
9683 }
9684 return nullptr;
9685}
9686#endif
9687
9688// ----------------------------------------------------------------------------
9689
9690} // namespace httplib
9691
9692#if defined(_WIN32) && defined(CPPHTTPLIB_USE_POLL)
9693#undef poll
9694#endif
9695
9696#endif // CPPHTTPLIB_HTTPLIB_H
9697#endif // USE_HTTP_REQUEST_HOST_H
9698
9699#endif
uint8_t l
Definition bl0906.h:0
uint8_t m
Definition bl0906.h:1
uint8_t h
Definition bl0906.h:2
uint8_t status
Definition bl0942.h:8
float position
Definition cover.h:0
uint16_t flags
uint16_t addr_len
uint8_t type
const char * key
void setup()
std::vector< uint8_t > & out
Definition gif.cpp:49
unsigned count
Definition gif.cpp:51
uint32_t buffer
Definition gif.cpp:50
uint32_t socklen_t
Definition headers.h:109
__int64 ssize_t
Definition httplib.h:178
SOCKET socket_t
Definition httplib.h:204
int ret
mopeka_std_values val[3]
uint8_t duration
Definition msa3xx.h:0
esp_err_t send(const uint8_t *mac, const uint8_t *data, uint16_t size)
static float float b
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]
size_t size_t pos
Definition helpers.h:1333
STL namespace.
bool valid
static void uint32_t
if(!is_valid_sram_ptr(frame))
sa_family_t ss_family
Definition headers.h:104
uint8_t end[39]
Definition sun_gtil2.cpp:17
uint32_t len
uint16_t trailer
uint16_t length
Definition tt21100.cpp:0
uint16_t x
Definition tt21100.cpp:5
SemaphoreHandle_t lock