summaryrefslogtreecommitdiff
path: root/externals/httplib/httplib.h
diff options
context:
space:
mode:
Diffstat (limited to 'externals/httplib/httplib.h')
-rw-r--r--externals/httplib/httplib.h2419
1 files changed, 1742 insertions, 677 deletions
diff --git a/externals/httplib/httplib.h b/externals/httplib/httplib.h
index fa2edcc94..e03842e6d 100644
--- a/externals/httplib/httplib.h
+++ b/externals/httplib/httplib.h
@@ -1,7 +1,7 @@
1// 1//
2// httplib.h 2// httplib.h
3// 3//
4// Copyright (c) 2019 Yuji Hirose. All rights reserved. 4// Copyright (c) 2020 Yuji Hirose. All rights reserved.
5// MIT License 5// MIT License
6// 6//
7 7
@@ -11,6 +11,7 @@
11/* 11/*
12 * Configuration 12 * Configuration
13 */ 13 */
14
14#ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 15#ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
15#define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5 16#define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
16#endif 17#endif
@@ -40,7 +41,7 @@
40#endif 41#endif
41 42
42#ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH 43#ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
43#define CPPHTTPLIB_PAYLOAD_MAX_LENGTH (std::numeric_limits<size_t>::max)() 44#define CPPHTTPLIB_PAYLOAD_MAX_LENGTH (std::numeric_limits<size_t>::max())
44#endif 45#endif
45 46
46#ifndef CPPHTTPLIB_RECV_BUFSIZ 47#ifndef CPPHTTPLIB_RECV_BUFSIZ
@@ -48,9 +49,14 @@
48#endif 49#endif
49 50
50#ifndef CPPHTTPLIB_THREAD_POOL_COUNT 51#ifndef CPPHTTPLIB_THREAD_POOL_COUNT
51#define CPPHTTPLIB_THREAD_POOL_COUNT 8 52#define CPPHTTPLIB_THREAD_POOL_COUNT \
53 (std::max(1u, std::thread::hardware_concurrency() - 1))
52#endif 54#endif
53 55
56/*
57 * Headers
58 */
59
54#ifdef _WIN32 60#ifdef _WIN32
55#ifndef _CRT_SECURE_NO_WARNINGS 61#ifndef _CRT_SECURE_NO_WARNINGS
56#define _CRT_SECURE_NO_WARNINGS 62#define _CRT_SECURE_NO_WARNINGS
@@ -62,9 +68,9 @@
62 68
63#if defined(_MSC_VER) 69#if defined(_MSC_VER)
64#ifdef _WIN64 70#ifdef _WIN64
65typedef __int64 ssize_t; 71using ssize_t = __int64;
66#else 72#else
67typedef int ssize_t; 73using ssize_t = int;
68#endif 74#endif
69 75
70#if _MSC_VER < 1900 76#if _MSC_VER < 1900
@@ -100,7 +106,7 @@ typedef int ssize_t;
100#define strcasecmp _stricmp 106#define strcasecmp _stricmp
101#endif // strcasecmp 107#endif // strcasecmp
102 108
103typedef SOCKET socket_t; 109using socket_t = SOCKET;
104#ifdef CPPHTTPLIB_USE_POLL 110#ifdef CPPHTTPLIB_USE_POLL
105#define poll(fds, nfds, timeout) WSAPoll(fds, nfds, timeout) 111#define poll(fds, nfds, timeout) WSAPoll(fds, nfds, timeout)
106#endif 112#endif
@@ -109,23 +115,25 @@ typedef SOCKET socket_t;
109 115
110#include <arpa/inet.h> 116#include <arpa/inet.h>
111#include <cstring> 117#include <cstring>
118#include <ifaddrs.h>
112#include <netdb.h> 119#include <netdb.h>
113#include <netinet/in.h> 120#include <netinet/in.h>
114#ifdef CPPHTTPLIB_USE_POLL 121#ifdef CPPHTTPLIB_USE_POLL
115#include <poll.h> 122#include <poll.h>
116#endif 123#endif
124#include <csignal>
117#include <pthread.h> 125#include <pthread.h>
118#include <signal.h>
119#include <sys/select.h> 126#include <sys/select.h>
120#include <sys/socket.h> 127#include <sys/socket.h>
121#include <unistd.h> 128#include <unistd.h>
122 129
123typedef int socket_t; 130using socket_t = int;
124#define INVALID_SOCKET (-1) 131#define INVALID_SOCKET (-1)
125#endif //_WIN32 132#endif //_WIN32
126 133
127#include <assert.h> 134#include <array>
128#include <atomic> 135#include <atomic>
136#include <cassert>
129#include <condition_variable> 137#include <condition_variable>
130#include <errno.h> 138#include <errno.h>
131#include <fcntl.h> 139#include <fcntl.h>
@@ -143,9 +151,13 @@ typedef int socket_t;
143 151
144#ifdef CPPHTTPLIB_OPENSSL_SUPPORT 152#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
145#include <openssl/err.h> 153#include <openssl/err.h>
154#include <openssl/md5.h>
146#include <openssl/ssl.h> 155#include <openssl/ssl.h>
147#include <openssl/x509v3.h> 156#include <openssl/x509v3.h>
148 157
158#include <iomanip>
159#include <sstream>
160
149// #if OPENSSL_VERSION_NUMBER < 0x1010100fL 161// #if OPENSSL_VERSION_NUMBER < 0x1010100fL
150// #error Sorry, OpenSSL versions prior to 1.1.1 are not supported 162// #error Sorry, OpenSSL versions prior to 1.1.1 are not supported
151// #endif 163// #endif
@@ -162,6 +174,9 @@ inline const unsigned char *ASN1_STRING_get0_data(const ASN1_STRING *asn1) {
162#include <zlib.h> 174#include <zlib.h>
163#endif 175#endif
164 176
177/*
178 * Declaration
179 */
165namespace httplib { 180namespace httplib {
166 181
167namespace detail { 182namespace detail {
@@ -176,37 +191,15 @@ struct ci {
176 191
177} // namespace detail 192} // namespace detail
178 193
179enum class HttpVersion { v1_0 = 0, v1_1 }; 194using Headers = std::multimap<std::string, std::string, detail::ci>;
180
181typedef std::multimap<std::string, std::string, detail::ci> Headers;
182
183typedef std::multimap<std::string, std::string> Params;
184typedef std::smatch Match;
185
186typedef std::function<void(const char *data, size_t data_len)> DataSink;
187
188typedef std::function<void()> Done;
189
190typedef std::function<void(size_t offset, size_t length, DataSink sink,
191 Done done)>
192 ContentProvider;
193 195
194typedef std::function<bool(const char *data, size_t data_length, size_t offset, 196using Params = std::multimap<std::string, std::string>;
195 uint64_t content_length)> 197using Match = std::smatch;
196 ContentReceiver;
197 198
198typedef std::function<bool(uint64_t current, uint64_t total)> Progress; 199using Progress = std::function<bool(uint64_t current, uint64_t total)>;
199 200
200struct Response; 201struct Response;
201typedef std::function<bool(const Response &response)> ResponseHandler; 202using ResponseHandler = std::function<bool(const Response &response)>;
202
203struct MultipartFile {
204 std::string filename;
205 std::string content_type;
206 size_t offset = 0;
207 size_t length = 0;
208};
209typedef std::multimap<std::string, MultipartFile> MultipartFiles;
210 203
211struct MultipartFormData { 204struct MultipartFormData {
212 std::string name; 205 std::string name;
@@ -214,10 +207,53 @@ struct MultipartFormData {
214 std::string filename; 207 std::string filename;
215 std::string content_type; 208 std::string content_type;
216}; 209};
217typedef std::vector<MultipartFormData> MultipartFormDataItems; 210using MultipartFormDataItems = std::vector<MultipartFormData>;
211using MultipartFormDataMap = std::multimap<std::string, MultipartFormData>;
212
213class DataSink {
214public:
215 DataSink() = default;
216 DataSink(const DataSink &) = delete;
217 DataSink &operator=(const DataSink &) = delete;
218 DataSink(DataSink &&) = delete;
219 DataSink &operator=(DataSink &&) = delete;
220
221 std::function<void(const char *data, size_t data_len)> write;
222 std::function<void()> done;
223 std::function<bool()> is_writable;
224};
225
226using ContentProvider =
227 std::function<void(size_t offset, size_t length, DataSink &sink)>;
228
229using ContentReceiver =
230 std::function<bool(const char *data, size_t data_length)>;
231
232using MultipartContentHeader =
233 std::function<bool(const MultipartFormData &file)>;
234
235class ContentReader {
236public:
237 using Reader = std::function<bool(ContentReceiver receiver)>;
238 using MultipartReader = std::function<bool(MultipartContentHeader header,
239 ContentReceiver receiver)>;
240
241 ContentReader(Reader reader, MultipartReader muitlpart_reader)
242 : reader_(reader), muitlpart_reader_(muitlpart_reader) {}
243
244 bool operator()(MultipartContentHeader header,
245 ContentReceiver receiver) const {
246 return muitlpart_reader_(header, receiver);
247 }
248
249 bool operator()(ContentReceiver receiver) const { return reader_(receiver); }
250
251 Reader reader_;
252 MultipartReader muitlpart_reader_;
253};
218 254
219typedef std::pair<ssize_t, ssize_t> Range; 255using Range = std::pair<ssize_t, ssize_t>;
220typedef std::vector<Range> Ranges; 256using Ranges = std::vector<Range>;
221 257
222struct Request { 258struct Request {
223 std::string method; 259 std::string method;
@@ -229,7 +265,7 @@ struct Request {
229 std::string version; 265 std::string version;
230 std::string target; 266 std::string target;
231 Params params; 267 Params params;
232 MultipartFiles files; 268 MultipartFormDataMap files;
233 Ranges ranges; 269 Ranges ranges;
234 Match matches; 270 Match matches;
235 271
@@ -253,13 +289,19 @@ struct Request {
253 std::string get_param_value(const char *key, size_t id = 0) const; 289 std::string get_param_value(const char *key, size_t id = 0) const;
254 size_t get_param_value_count(const char *key) const; 290 size_t get_param_value_count(const char *key) const;
255 291
292 bool is_multipart_form_data() const;
293
256 bool has_file(const char *key) const; 294 bool has_file(const char *key) const;
257 MultipartFile get_file_value(const char *key) const; 295 MultipartFormData get_file_value(const char *key) const;
296
297 // private members...
298 size_t content_length;
299 ContentProvider content_provider;
258}; 300};
259 301
260struct Response { 302struct Response {
261 std::string version; 303 std::string version;
262 int status; 304 int status = -1;
263 Headers headers; 305 Headers headers;
264 std::string body; 306 std::string body;
265 307
@@ -269,106 +311,81 @@ struct Response {
269 void set_header(const char *key, const char *val); 311 void set_header(const char *key, const char *val);
270 void set_header(const char *key, const std::string &val); 312 void set_header(const char *key, const std::string &val);
271 313
272 void set_redirect(const char *uri); 314 void set_redirect(const char *url);
273 void set_content(const char *s, size_t n, const char *content_type); 315 void set_content(const char *s, size_t n, const char *content_type);
274 void set_content(const std::string &s, const char *content_type); 316 void set_content(const std::string &s, const char *content_type);
275 317
276 void set_content_provider( 318 void set_content_provider(
277 size_t length, 319 size_t length,
278 std::function<void(size_t offset, size_t length, DataSink sink)> provider, 320 std::function<void(size_t offset, size_t length, DataSink &sink)>
321 provider,
279 std::function<void()> resource_releaser = [] {}); 322 std::function<void()> resource_releaser = [] {});
280 323
281 void set_chunked_content_provider( 324 void set_chunked_content_provider(
282 std::function<void(size_t offset, DataSink sink, Done done)> provider, 325 std::function<void(size_t offset, DataSink &sink)> provider,
283 std::function<void()> resource_releaser = [] {}); 326 std::function<void()> resource_releaser = [] {});
284 327
285 Response() : status(-1), content_provider_resource_length(0) {} 328 Response() = default;
286 329 Response(const Response &) = default;
330 Response &operator=(const Response &) = default;
331 Response(Response &&) = default;
332 Response &operator=(Response &&) = default;
287 ~Response() { 333 ~Response() {
288 if (content_provider_resource_releaser) { 334 if (content_provider_resource_releaser) {
289 content_provider_resource_releaser(); 335 content_provider_resource_releaser();
290 } 336 }
291 } 337 }
292 338
293 size_t content_provider_resource_length; 339 // private members...
340 size_t content_length = 0;
294 ContentProvider content_provider; 341 ContentProvider content_provider;
295 std::function<void()> content_provider_resource_releaser; 342 std::function<void()> content_provider_resource_releaser;
296}; 343};
297 344
298class Stream { 345class Stream {
299public: 346public:
300 virtual ~Stream() {} 347 virtual ~Stream() = default;
348
349 virtual bool is_readable() const = 0;
350 virtual bool is_writable() const = 0;
351
301 virtual int read(char *ptr, size_t size) = 0; 352 virtual int read(char *ptr, size_t size) = 0;
302 virtual int write(const char *ptr, size_t size1) = 0; 353 virtual int write(const char *ptr, size_t size) = 0;
303 virtual int write(const char *ptr) = 0;
304 virtual int write(const std::string &s) = 0;
305 virtual std::string get_remote_addr() const = 0; 354 virtual std::string get_remote_addr() const = 0;
306 355
307 template <typename... Args> 356 template <typename... Args>
308 int write_format(const char *fmt, const Args &... args); 357 int write_format(const char *fmt, const Args &... args);
309}; 358 int write(const char *ptr);
310 359 int write(const std::string &s);
311class SocketStream : public Stream {
312public:
313 SocketStream(socket_t sock);
314 virtual ~SocketStream();
315
316 virtual int read(char *ptr, size_t size);
317 virtual int write(const char *ptr, size_t size);
318 virtual int write(const char *ptr);
319 virtual int write(const std::string &s);
320 virtual std::string get_remote_addr() const;
321
322private:
323 socket_t sock_;
324};
325
326class BufferStream : public Stream {
327public:
328 BufferStream() {}
329 virtual ~BufferStream() {}
330
331 virtual int read(char *ptr, size_t size);
332 virtual int write(const char *ptr, size_t size);
333 virtual int write(const char *ptr);
334 virtual int write(const std::string &s);
335 virtual std::string get_remote_addr() const;
336
337 const std::string &get_buffer() const;
338
339private:
340 std::string buffer;
341}; 360};
342 361
343class TaskQueue { 362class TaskQueue {
344public: 363public:
345 TaskQueue() {} 364 TaskQueue() = default;
346 virtual ~TaskQueue() {} 365 virtual ~TaskQueue() = default;
347 virtual void enqueue(std::function<void()> fn) = 0; 366 virtual void enqueue(std::function<void()> fn) = 0;
348 virtual void shutdown() = 0; 367 virtual void shutdown() = 0;
349}; 368};
350 369
351#if CPPHTTPLIB_THREAD_POOL_COUNT > 0
352class ThreadPool : public TaskQueue { 370class ThreadPool : public TaskQueue {
353public: 371public:
354 ThreadPool(size_t n) : shutdown_(false) { 372 explicit ThreadPool(size_t n) : shutdown_(false) {
355 while (n) { 373 while (n) {
356 auto t = std::make_shared<std::thread>(worker(*this)); 374 threads_.emplace_back(worker(*this));
357 threads_.push_back(t);
358 n--; 375 n--;
359 } 376 }
360 } 377 }
361 378
362 ThreadPool(const ThreadPool &) = delete; 379 ThreadPool(const ThreadPool &) = delete;
363 virtual ~ThreadPool() {} 380 ~ThreadPool() override = default;
364 381
365 virtual void enqueue(std::function<void()> fn) override { 382 void enqueue(std::function<void()> fn) override {
366 std::unique_lock<std::mutex> lock(mutex_); 383 std::unique_lock<std::mutex> lock(mutex_);
367 jobs_.push_back(fn); 384 jobs_.push_back(fn);
368 cond_.notify_one(); 385 cond_.notify_one();
369 } 386 }
370 387
371 virtual void shutdown() override { 388 void shutdown() override {
372 // Stop all worker threads... 389 // Stop all worker threads...
373 { 390 {
374 std::unique_lock<std::mutex> lock(mutex_); 391 std::unique_lock<std::mutex> lock(mutex_);
@@ -378,14 +395,14 @@ public:
378 cond_.notify_all(); 395 cond_.notify_all();
379 396
380 // Join... 397 // Join...
381 for (auto t : threads_) { 398 for (auto &t : threads_) {
382 t->join(); 399 t.join();
383 } 400 }
384 } 401 }
385 402
386private: 403private:
387 struct worker { 404 struct worker {
388 worker(ThreadPool &pool) : pool_(pool) {} 405 explicit worker(ThreadPool &pool) : pool_(pool) {}
389 406
390 void operator()() { 407 void operator()() {
391 for (;;) { 408 for (;;) {
@@ -411,7 +428,7 @@ private:
411 }; 428 };
412 friend struct worker; 429 friend struct worker;
413 430
414 std::vector<std::shared_ptr<std::thread>> threads_; 431 std::vector<std::thread> threads_;
415 std::list<std::function<void()>> jobs_; 432 std::list<std::function<void()>> jobs_;
416 433
417 bool shutdown_; 434 bool shutdown_;
@@ -419,46 +436,16 @@ private:
419 std::condition_variable cond_; 436 std::condition_variable cond_;
420 std::mutex mutex_; 437 std::mutex mutex_;
421}; 438};
422#else
423class Threads : public TaskQueue {
424public:
425 Threads() : running_threads_(0) {}
426 virtual ~Threads() {}
427
428 virtual void enqueue(std::function<void()> fn) override {
429 std::thread([=]() {
430 {
431 std::lock_guard<std::mutex> guard(running_threads_mutex_);
432 running_threads_++;
433 }
434
435 fn();
436
437 {
438 std::lock_guard<std::mutex> guard(running_threads_mutex_);
439 running_threads_--;
440 }
441 }).detach();
442 }
443
444 virtual void shutdown() override {
445 for (;;) {
446 std::this_thread::sleep_for(std::chrono::milliseconds(10));
447 std::lock_guard<std::mutex> guard(running_threads_mutex_);
448 if (!running_threads_) { break; }
449 }
450 }
451 439
452private: 440using Logger = std::function<void(const Request &, const Response &)>;
453 std::mutex running_threads_mutex_;
454 int running_threads_;
455};
456#endif
457 441
458class Server { 442class Server {
459public: 443public:
460 typedef std::function<void(const Request &, Response &)> Handler; 444 using Handler = std::function<void(const Request &, Response &)>;
461 typedef std::function<void(const Request &, const Response &)> Logger; 445 using HandlerWithContentReader = std::function<void(
446 const Request &, Response &, const ContentReader &content_reader)>;
447 using Expect100ContinueHandler =
448 std::function<int(const Request &, Response &)>;
462 449
463 Server(); 450 Server();
464 451
@@ -468,21 +455,32 @@ public:
468 455
469 Server &Get(const char *pattern, Handler handler); 456 Server &Get(const char *pattern, Handler handler);
470 Server &Post(const char *pattern, Handler handler); 457 Server &Post(const char *pattern, Handler handler);
471 458 Server &Post(const char *pattern, HandlerWithContentReader handler);
472 Server &Put(const char *pattern, Handler handler); 459 Server &Put(const char *pattern, Handler handler);
460 Server &Put(const char *pattern, HandlerWithContentReader handler);
473 Server &Patch(const char *pattern, Handler handler); 461 Server &Patch(const char *pattern, Handler handler);
462 Server &Patch(const char *pattern, HandlerWithContentReader handler);
474 Server &Delete(const char *pattern, Handler handler); 463 Server &Delete(const char *pattern, Handler handler);
475 Server &Options(const char *pattern, Handler handler); 464 Server &Options(const char *pattern, Handler handler);
476 465
477 bool set_base_dir(const char *path); 466 [[deprecated]] bool set_base_dir(const char *dir,
467 const char *mount_point = nullptr);
468 bool set_mount_point(const char *mount_point, const char *dir);
469 bool remove_mount_point(const char *mount_point);
470 void set_file_extension_and_mimetype_mapping(const char *ext,
471 const char *mime);
478 void set_file_request_handler(Handler handler); 472 void set_file_request_handler(Handler handler);
479 473
480 void set_error_handler(Handler handler); 474 void set_error_handler(Handler handler);
481 void set_logger(Logger logger); 475 void set_logger(Logger logger);
482 476
477 void set_expect_100_continue_handler(Expect100ContinueHandler handler);
478
483 void set_keep_alive_max_count(size_t count); 479 void set_keep_alive_max_count(size_t count);
480 void set_read_timeout(time_t sec, time_t usec);
484 void set_payload_max_length(size_t length); 481 void set_payload_max_length(size_t length);
485 482
483 bool bind_to_port(const char *host, int port, int socket_flags = 0);
486 int bind_to_any_port(const char *host, int socket_flags = 0); 484 int bind_to_any_port(const char *host, int socket_flags = 0);
487 bool listen_after_bind(); 485 bool listen_after_bind();
488 486
@@ -496,22 +494,29 @@ public:
496protected: 494protected:
497 bool process_request(Stream &strm, bool last_connection, 495 bool process_request(Stream &strm, bool last_connection,
498 bool &connection_close, 496 bool &connection_close,
499 std::function<void(Request &)> setup_request); 497 const std::function<void(Request &)> &setup_request);
500 498
501 size_t keep_alive_max_count_; 499 size_t keep_alive_max_count_;
500 time_t read_timeout_sec_;
501 time_t read_timeout_usec_;
502 size_t payload_max_length_; 502 size_t payload_max_length_;
503 503
504private: 504private:
505 typedef std::vector<std::pair<std::regex, Handler>> Handlers; 505 using Handlers = std::vector<std::pair<std::regex, Handler>>;
506 using HandlersForContentReader =
507 std::vector<std::pair<std::regex, HandlerWithContentReader>>;
506 508
507 socket_t create_server_socket(const char *host, int port, 509 socket_t create_server_socket(const char *host, int port,
508 int socket_flags) const; 510 int socket_flags) const;
509 int bind_internal(const char *host, int port, int socket_flags); 511 int bind_internal(const char *host, int port, int socket_flags);
510 bool listen_internal(); 512 bool listen_internal();
511 513
512 bool routing(Request &req, Response &res); 514 bool routing(Request &req, Response &res, Stream &strm, bool last_connection);
513 bool handle_file_request(Request &req, Response &res); 515 bool handle_file_request(Request &req, Response &res, bool head = false);
514 bool dispatch_request(Request &req, Response &res, Handlers &handlers); 516 bool dispatch_request(Request &req, Response &res, Handlers &handlers);
517 bool dispatch_request_for_content_reader(Request &req, Response &res,
518 ContentReader content_reader,
519 HandlersForContentReader &handlers);
515 520
516 bool parse_request_line(const char *s, Request &req); 521 bool parse_request_line(const char *s, Request &req);
517 bool write_response(Stream &strm, bool last_connection, const Request &req, 522 bool write_response(Stream &strm, bool last_connection, const Request &req,
@@ -519,26 +524,43 @@ private:
519 bool write_content_with_provider(Stream &strm, const Request &req, 524 bool write_content_with_provider(Stream &strm, const Request &req,
520 Response &res, const std::string &boundary, 525 Response &res, const std::string &boundary,
521 const std::string &content_type); 526 const std::string &content_type);
527 bool read_content(Stream &strm, bool last_connection, Request &req,
528 Response &res);
529 bool read_content_with_content_receiver(
530 Stream &strm, bool last_connection, Request &req, Response &res,
531 ContentReceiver receiver, MultipartContentHeader multipart_header,
532 ContentReceiver multipart_receiver);
533 bool read_content_core(Stream &strm, bool last_connection, Request &req,
534 Response &res, ContentReceiver receiver,
535 MultipartContentHeader mulitpart_header,
536 ContentReceiver multipart_receiver);
522 537
523 virtual bool process_and_close_socket(socket_t sock); 538 virtual bool process_and_close_socket(socket_t sock);
524 539
525 std::atomic<bool> is_running_; 540 std::atomic<bool> is_running_;
526 std::atomic<socket_t> svr_sock_; 541 std::atomic<socket_t> svr_sock_;
527 std::string base_dir_; 542 std::vector<std::pair<std::string, std::string>> base_dirs_;
543 std::map<std::string, std::string> file_extension_and_mimetype_map_;
528 Handler file_request_handler_; 544 Handler file_request_handler_;
529 Handlers get_handlers_; 545 Handlers get_handlers_;
530 Handlers post_handlers_; 546 Handlers post_handlers_;
547 HandlersForContentReader post_handlers_for_content_reader_;
531 Handlers put_handlers_; 548 Handlers put_handlers_;
549 HandlersForContentReader put_handlers_for_content_reader_;
532 Handlers patch_handlers_; 550 Handlers patch_handlers_;
551 HandlersForContentReader patch_handlers_for_content_reader_;
533 Handlers delete_handlers_; 552 Handlers delete_handlers_;
534 Handlers options_handlers_; 553 Handlers options_handlers_;
535 Handler error_handler_; 554 Handler error_handler_;
536 Logger logger_; 555 Logger logger_;
556 Expect100ContinueHandler expect_100_continue_handler_;
537}; 557};
538 558
539class Client { 559class Client {
540public: 560public:
541 Client(const char *host, int port = 80, time_t timeout_sec = 300); 561 explicit Client(const std::string &host, int port = 80,
562 const std::string &client_cert_path = std::string(),
563 const std::string &client_key_path = std::string());
542 564
543 virtual ~Client(); 565 virtual ~Client();
544 566
@@ -586,6 +608,15 @@ public:
586 const std::string &body, 608 const std::string &body,
587 const char *content_type); 609 const char *content_type);
588 610
611 std::shared_ptr<Response> Post(const char *path, size_t content_length,
612 ContentProvider content_provider,
613 const char *content_type);
614
615 std::shared_ptr<Response> Post(const char *path, const Headers &headers,
616 size_t content_length,
617 ContentProvider content_provider,
618 const char *content_type);
619
589 std::shared_ptr<Response> Post(const char *path, const Params &params); 620 std::shared_ptr<Response> Post(const char *path, const Params &params);
590 621
591 std::shared_ptr<Response> Post(const char *path, const Headers &headers, 622 std::shared_ptr<Response> Post(const char *path, const Headers &headers,
@@ -604,6 +635,20 @@ public:
604 const std::string &body, 635 const std::string &body,
605 const char *content_type); 636 const char *content_type);
606 637
638 std::shared_ptr<Response> Put(const char *path, size_t content_length,
639 ContentProvider content_provider,
640 const char *content_type);
641
642 std::shared_ptr<Response> Put(const char *path, const Headers &headers,
643 size_t content_length,
644 ContentProvider content_provider,
645 const char *content_type);
646
647 std::shared_ptr<Response> Put(const char *path, const Params &params);
648
649 std::shared_ptr<Response> Put(const char *path, const Headers &headers,
650 const Params &params);
651
607 std::shared_ptr<Response> Patch(const char *path, const std::string &body, 652 std::shared_ptr<Response> Patch(const char *path, const std::string &body,
608 const char *content_type); 653 const char *content_type);
609 654
@@ -611,6 +656,15 @@ public:
611 const std::string &body, 656 const std::string &body,
612 const char *content_type); 657 const char *content_type);
613 658
659 std::shared_ptr<Response> Patch(const char *path, size_t content_length,
660 ContentProvider content_provider,
661 const char *content_type);
662
663 std::shared_ptr<Response> Patch(const char *path, const Headers &headers,
664 size_t content_length,
665 ContentProvider content_provider,
666 const char *content_type);
667
614 std::shared_ptr<Response> Delete(const char *path); 668 std::shared_ptr<Response> Delete(const char *path);
615 669
616 std::shared_ptr<Response> Delete(const char *path, const std::string &body, 670 std::shared_ptr<Response> Delete(const char *path, const std::string &body,
@@ -631,9 +685,33 @@ public:
631 bool send(const std::vector<Request> &requests, 685 bool send(const std::vector<Request> &requests,
632 std::vector<Response> &responses); 686 std::vector<Response> &responses);
633 687
688 void set_timeout_sec(time_t timeout_sec);
689
690 void set_read_timeout(time_t sec, time_t usec);
691
634 void set_keep_alive_max_count(size_t count); 692 void set_keep_alive_max_count(size_t count);
635 693
636 void follow_location(bool on); 694 void set_basic_auth(const char *username, const char *password);
695
696#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
697 void set_digest_auth(const char *username, const char *password);
698#endif
699
700 void set_follow_location(bool on);
701
702 void set_compress(bool on);
703
704 void set_interface(const char *intf);
705
706 void set_proxy(const char *host, int port);
707
708 void set_proxy_basic_auth(const char *username, const char *password);
709
710#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
711 void set_proxy_digest_auth(const char *username, const char *password);
712#endif
713
714 void set_logger(Logger logger);
637 715
638protected: 716protected:
639 bool process_request(Stream &strm, const Request &req, Response &res, 717 bool process_request(Stream &strm, const Request &req, Response &res,
@@ -641,16 +719,85 @@ protected:
641 719
642 const std::string host_; 720 const std::string host_;
643 const int port_; 721 const int port_;
644 time_t timeout_sec_;
645 const std::string host_and_port_; 722 const std::string host_and_port_;
646 size_t keep_alive_max_count_; 723
647 size_t follow_location_; 724 // Settings
725 std::string client_cert_path_;
726 std::string client_key_path_;
727
728 time_t timeout_sec_ = 300;
729 time_t read_timeout_sec_ = CPPHTTPLIB_READ_TIMEOUT_SECOND;
730 time_t read_timeout_usec_ = CPPHTTPLIB_READ_TIMEOUT_USECOND;
731
732 size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
733
734 std::string basic_auth_username_;
735 std::string basic_auth_password_;
736#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
737 std::string digest_auth_username_;
738 std::string digest_auth_password_;
739#endif
740
741 bool follow_location_ = false;
742
743 bool compress_ = false;
744
745 std::string interface_;
746
747 std::string proxy_host_;
748 int proxy_port_;
749
750 std::string proxy_basic_auth_username_;
751 std::string proxy_basic_auth_password_;
752#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
753 std::string proxy_digest_auth_username_;
754 std::string proxy_digest_auth_password_;
755#endif
756
757 Logger logger_;
758
759 void copy_settings(const Client &rhs) {
760 client_cert_path_ = rhs.client_cert_path_;
761 client_key_path_ = rhs.client_key_path_;
762 timeout_sec_ = rhs.timeout_sec_;
763 read_timeout_sec_ = rhs.read_timeout_sec_;
764 read_timeout_usec_ = rhs.read_timeout_usec_;
765 keep_alive_max_count_ = rhs.keep_alive_max_count_;
766 basic_auth_username_ = rhs.basic_auth_username_;
767 basic_auth_password_ = rhs.basic_auth_password_;
768#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
769 digest_auth_username_ = rhs.digest_auth_username_;
770 digest_auth_password_ = rhs.digest_auth_password_;
771#endif
772 follow_location_ = rhs.follow_location_;
773 compress_ = rhs.compress_;
774 interface_ = rhs.interface_;
775 proxy_host_ = rhs.proxy_host_;
776 proxy_port_ = rhs.proxy_port_;
777 proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
778 proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
779#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
780 proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
781 proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
782#endif
783 logger_ = rhs.logger_;
784 }
648 785
649private: 786private:
650 socket_t create_client_socket() const; 787 socket_t create_client_socket() const;
651 bool read_response_line(Stream &strm, Response &res); 788 bool read_response_line(Stream &strm, Response &res);
652 void write_request(Stream &strm, const Request &req, bool last_connection); 789 bool write_request(Stream &strm, const Request &req, bool last_connection);
653 bool redirect(const Request &req, Response &res); 790 bool redirect(const Request &req, Response &res);
791 bool handle_request(Stream &strm, const Request &req, Response &res,
792 bool last_connection, bool &connection_close);
793#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
794 bool connect(socket_t sock, Response &res, bool &error);
795#endif
796
797 std::shared_ptr<Response> send_with_content_provider(
798 const char *method, const char *path, const Headers &headers,
799 const std::string &body, size_t content_length,
800 ContentProvider content_provider, const char *content_type);
654 801
655 virtual bool process_and_close_socket( 802 virtual bool process_and_close_socket(
656 socket_t sock, size_t request_count, 803 socket_t sock, size_t request_count,
@@ -692,22 +839,6 @@ inline void Post(std::vector<Request> &requests, const char *path,
692} 839}
693 840
694#ifdef CPPHTTPLIB_OPENSSL_SUPPORT 841#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
695class SSLSocketStream : public Stream {
696public:
697 SSLSocketStream(socket_t sock, SSL *ssl);
698 virtual ~SSLSocketStream();
699
700 virtual int read(char *ptr, size_t size);
701 virtual int write(const char *ptr, size_t size);
702 virtual int write(const char *ptr);
703 virtual int write(const std::string &s);
704 virtual std::string get_remote_addr() const;
705
706private:
707 socket_t sock_;
708 SSL *ssl_;
709};
710
711class SSLServer : public Server { 842class SSLServer : public Server {
712public: 843public:
713 SSLServer(const char *cert_path, const char *private_key_path, 844 SSLServer(const char *cert_path, const char *private_key_path,
@@ -727,9 +858,9 @@ private:
727 858
728class SSLClient : public Client { 859class SSLClient : public Client {
729public: 860public:
730 SSLClient(const char *host, int port = 443, time_t timeout_sec = 300, 861 SSLClient(const std::string &host, int port = 443,
731 const char *client_cert_path = nullptr, 862 const std::string &client_cert_path = std::string(),
732 const char *client_key_path = nullptr); 863 const std::string &client_key_path = std::string());
733 864
734 virtual ~SSLClient(); 865 virtual ~SSLClient();
735 866
@@ -737,11 +868,12 @@ public:
737 868
738 void set_ca_cert_path(const char *ca_ceert_file_path, 869 void set_ca_cert_path(const char *ca_ceert_file_path,
739 const char *ca_cert_dir_path = nullptr); 870 const char *ca_cert_dir_path = nullptr);
871
740 void enable_server_certificate_verification(bool enabled); 872 void enable_server_certificate_verification(bool enabled);
741 873
742 long get_openssl_verify_result() const; 874 long get_openssl_verify_result() const;
743 875
744 SSL_CTX* ssl_context() const noexcept; 876 SSL_CTX *ssl_context() const noexcept;
745 877
746private: 878private:
747 virtual bool process_and_close_socket( 879 virtual bool process_and_close_socket(
@@ -759,6 +891,7 @@ private:
759 SSL_CTX *ctx_; 891 SSL_CTX *ctx_;
760 std::mutex ctx_mutex_; 892 std::mutex ctx_mutex_;
761 std::vector<std::string> host_components_; 893 std::vector<std::string> host_components_;
894
762 std::string ca_cert_file_path_; 895 std::string ca_cert_file_path_;
763 std::string ca_cert_dir_path_; 896 std::string ca_cert_dir_path_;
764 bool server_certificate_verification_ = false; 897 bool server_certificate_verification_ = false;
@@ -766,9 +899,12 @@ private:
766}; 899};
767#endif 900#endif
768 901
902// ----------------------------------------------------------------------------
903
769/* 904/*
770 * Implementation 905 * Implementation
771 */ 906 */
907
772namespace detail { 908namespace detail {
773 909
774inline bool is_hex(char c, int &v) { 910inline bool is_hex(char c, int &v) {
@@ -932,8 +1068,8 @@ inline void read_file(const std::string &path, std::string &out) {
932 1068
933inline std::string file_extension(const std::string &path) { 1069inline std::string file_extension(const std::string &path) {
934 std::smatch m; 1070 std::smatch m;
935 auto pat = std::regex("\\.([a-zA-Z0-9]+)$"); 1071 static auto re = std::regex("\\.([a-zA-Z0-9]+)$");
936 if (std::regex_search(path, m, pat)) { return m[1].str(); } 1072 if (std::regex_search(path, m, re)) { return m[1].str(); }
937 return std::string(); 1073 return std::string();
938} 1074}
939 1075
@@ -976,6 +1112,11 @@ public:
976 } 1112 }
977 } 1113 }
978 1114
1115 bool end_with_crlf() const {
1116 auto end = ptr() + size();
1117 return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
1118 }
1119
979 bool getline() { 1120 bool getline() {
980 fixed_buffer_used_size_ = 0; 1121 fixed_buffer_used_size_ = 0;
981 glowable_buffer_.clear(); 1122 glowable_buffer_.clear();
@@ -1019,7 +1160,7 @@ private:
1019 Stream &strm_; 1160 Stream &strm_;
1020 char *fixed_buffer_; 1161 char *fixed_buffer_;
1021 const size_t fixed_buffer_size_; 1162 const size_t fixed_buffer_size_;
1022 size_t fixed_buffer_used_size_; 1163 size_t fixed_buffer_used_size_ = 0;
1023 std::string glowable_buffer_; 1164 std::string glowable_buffer_;
1024}; 1165};
1025 1166
@@ -1053,6 +1194,28 @@ inline int select_read(socket_t sock, time_t sec, time_t usec) {
1053#endif 1194#endif
1054} 1195}
1055 1196
1197inline int select_write(socket_t sock, time_t sec, time_t usec) {
1198#ifdef CPPHTTPLIB_USE_POLL
1199 struct pollfd pfd_read;
1200 pfd_read.fd = sock;
1201 pfd_read.events = POLLOUT;
1202
1203 auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
1204
1205 return poll(&pfd_read, 1, timeout);
1206#else
1207 fd_set fds;
1208 FD_ZERO(&fds);
1209 FD_SET(sock, &fds);
1210
1211 timeval tv;
1212 tv.tv_sec = static_cast<long>(sec);
1213 tv.tv_usec = static_cast<long>(usec);
1214
1215 return select(static_cast<int>(sock + 1), nullptr, &fds, nullptr, &tv);
1216#endif
1217}
1218
1056inline bool wait_until_socket_is_ready(socket_t sock, time_t sec, time_t usec) { 1219inline bool wait_until_socket_is_ready(socket_t sock, time_t sec, time_t usec) {
1057#ifdef CPPHTTPLIB_USE_POLL 1220#ifdef CPPHTTPLIB_USE_POLL
1058 struct pollfd pfd_read; 1221 struct pollfd pfd_read;
@@ -1065,7 +1228,8 @@ inline bool wait_until_socket_is_ready(socket_t sock, time_t sec, time_t usec) {
1065 pfd_read.revents & (POLLIN | POLLOUT)) { 1228 pfd_read.revents & (POLLIN | POLLOUT)) {
1066 int error = 0; 1229 int error = 0;
1067 socklen_t len = sizeof(error); 1230 socklen_t len = sizeof(error);
1068 return getsockopt(sock, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&error), &len) >= 0 && 1231 return getsockopt(sock, SOL_SOCKET, SO_ERROR,
1232 reinterpret_cast<char *>(&error), &len) >= 0 &&
1069 !error; 1233 !error;
1070 } 1234 }
1071 return false; 1235 return false;
@@ -1085,27 +1249,86 @@ inline bool wait_until_socket_is_ready(socket_t sock, time_t sec, time_t usec) {
1085 (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) { 1249 (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) {
1086 int error = 0; 1250 int error = 0;
1087 socklen_t len = sizeof(error); 1251 socklen_t len = sizeof(error);
1088 return getsockopt(sock, SOL_SOCKET, SO_ERROR, (char *)&error, &len) >= 0 && 1252 return getsockopt(sock, SOL_SOCKET, SO_ERROR,
1253 reinterpret_cast<char *>(&error), &len) >= 0 &&
1089 !error; 1254 !error;
1090 } 1255 }
1091 return false; 1256 return false;
1092#endif 1257#endif
1093} 1258}
1094 1259
1260class SocketStream : public Stream {
1261public:
1262 SocketStream(socket_t sock, time_t read_timeout_sec,
1263 time_t read_timeout_usec);
1264 ~SocketStream() override;
1265
1266 bool is_readable() const override;
1267 bool is_writable() const override;
1268 int read(char *ptr, size_t size) override;
1269 int write(const char *ptr, size_t size) override;
1270 std::string get_remote_addr() const override;
1271
1272private:
1273 socket_t sock_;
1274 time_t read_timeout_sec_;
1275 time_t read_timeout_usec_;
1276};
1277
1278#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
1279class SSLSocketStream : public Stream {
1280public:
1281 SSLSocketStream(socket_t sock, SSL *ssl, time_t read_timeout_sec,
1282 time_t read_timeout_usec);
1283 virtual ~SSLSocketStream();
1284
1285 bool is_readable() const override;
1286 bool is_writable() const override;
1287 int read(char *ptr, size_t size) override;
1288 int write(const char *ptr, size_t size) override;
1289 std::string get_remote_addr() const override;
1290
1291private:
1292 socket_t sock_;
1293 SSL *ssl_;
1294 time_t read_timeout_sec_;
1295 time_t read_timeout_usec_;
1296};
1297#endif
1298
1299class BufferStream : public Stream {
1300public:
1301 BufferStream() = default;
1302 ~BufferStream() override = default;
1303
1304 bool is_readable() const override;
1305 bool is_writable() const override;
1306 int read(char *ptr, size_t size) override;
1307 int write(const char *ptr, size_t size) override;
1308 std::string get_remote_addr() const override;
1309
1310 const std::string &get_buffer() const;
1311
1312private:
1313 std::string buffer;
1314 int position = 0;
1315};
1316
1095template <typename T> 1317template <typename T>
1096inline bool process_and_close_socket(bool is_client_request, socket_t sock, 1318inline bool process_socket(bool is_client_request, socket_t sock,
1097 size_t keep_alive_max_count, T callback) { 1319 size_t keep_alive_max_count, time_t read_timeout_sec,
1320 time_t read_timeout_usec, T callback) {
1098 assert(keep_alive_max_count > 0); 1321 assert(keep_alive_max_count > 0);
1099 1322
1100 bool ret = false; 1323 auto ret = false;
1101 1324
1102 if (keep_alive_max_count > 1) { 1325 if (keep_alive_max_count > 1) {
1103 auto count = keep_alive_max_count; 1326 auto count = keep_alive_max_count;
1104 while (count > 0 && 1327 while (count > 0 &&
1105 (is_client_request || 1328 (is_client_request ||
1106 detail::select_read(sock, CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND, 1329 select_read(sock, CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND,
1107 CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND) > 0)) { 1330 CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND) > 0)) {
1108 SocketStream strm(sock); 1331 SocketStream strm(sock, read_timeout_sec, read_timeout_usec);
1109 auto last_connection = count == 1; 1332 auto last_connection = count == 1;
1110 auto connection_close = false; 1333 auto connection_close = false;
1111 1334
@@ -1114,12 +1337,22 @@ inline bool process_and_close_socket(bool is_client_request, socket_t sock,
1114 1337
1115 count--; 1338 count--;
1116 } 1339 }
1117 } else { 1340 } else { // keep_alive_max_count is 0 or 1
1118 SocketStream strm(sock); 1341 SocketStream strm(sock, read_timeout_sec, read_timeout_usec);
1119 auto dummy_connection_close = false; 1342 auto dummy_connection_close = false;
1120 ret = callback(strm, true, dummy_connection_close); 1343 ret = callback(strm, true, dummy_connection_close);
1121 } 1344 }
1122 1345
1346 return ret;
1347}
1348
1349template <typename T>
1350inline bool process_and_close_socket(bool is_client_request, socket_t sock,
1351 size_t keep_alive_max_count,
1352 time_t read_timeout_sec,
1353 time_t read_timeout_usec, T callback) {
1354 auto ret = process_socket(is_client_request, sock, keep_alive_max_count,
1355 read_timeout_sec, read_timeout_usec, callback);
1123 close_socket(sock); 1356 close_socket(sock);
1124 return ret; 1357 return ret;
1125} 1358}
@@ -1165,6 +1398,23 @@ socket_t create_socket(const char *host, int port, Fn fn,
1165#ifdef _WIN32 1398#ifdef _WIN32
1166 auto sock = WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, 1399 auto sock = WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol,
1167 nullptr, 0, WSA_FLAG_NO_HANDLE_INHERIT); 1400 nullptr, 0, WSA_FLAG_NO_HANDLE_INHERIT);
1401 /**
1402 * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
1403 * and above the socket creation fails on older Windows Systems.
1404 *
1405 * Let's try to create a socket the old way in this case.
1406 *
1407 * Reference:
1408 * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
1409 *
1410 * WSA_FLAG_NO_HANDLE_INHERIT:
1411 * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
1412 * SP1, and later
1413 *
1414 */
1415 if (sock == INVALID_SOCKET) {
1416 sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
1417 }
1168#else 1418#else
1169 auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); 1419 auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
1170#endif 1420#endif
@@ -1176,9 +1426,11 @@ socket_t create_socket(const char *host, int port, Fn fn,
1176 1426
1177 // Make 'reuse address' option available 1427 // Make 'reuse address' option available
1178 int yes = 1; 1428 int yes = 1;
1179 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char*>(&yes), sizeof(yes)); 1429 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char *>(&yes),
1430 sizeof(yes));
1180#ifdef SO_REUSEPORT 1431#ifdef SO_REUSEPORT
1181 setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, reinterpret_cast<char*>(&yes), sizeof(yes)); 1432 setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, reinterpret_cast<char *>(&yes),
1433 sizeof(yes));
1182#endif 1434#endif
1183 1435
1184 // bind or connect 1436 // bind or connect
@@ -1213,27 +1465,105 @@ inline bool is_connection_error() {
1213#endif 1465#endif
1214} 1466}
1215 1467
1468inline bool bind_ip_address(socket_t sock, const char *host) {
1469 struct addrinfo hints;
1470 struct addrinfo *result;
1471
1472 memset(&hints, 0, sizeof(struct addrinfo));
1473 hints.ai_family = AF_UNSPEC;
1474 hints.ai_socktype = SOCK_STREAM;
1475 hints.ai_protocol = 0;
1476
1477 if (getaddrinfo(host, "0", &hints, &result)) { return false; }
1478
1479 auto ret = false;
1480 for (auto rp = result; rp; rp = rp->ai_next) {
1481 const auto &ai = *rp;
1482 if (!::bind(sock, ai.ai_addr, static_cast<int>(ai.ai_addrlen))) {
1483 ret = true;
1484 break;
1485 }
1486 }
1487
1488 freeaddrinfo(result);
1489 return ret;
1490}
1491
1492inline std::string if2ip(const std::string &ifn) {
1493#ifndef _WIN32
1494 struct ifaddrs *ifap;
1495 getifaddrs(&ifap);
1496 for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
1497 if (ifa->ifa_addr && ifn == ifa->ifa_name) {
1498 if (ifa->ifa_addr->sa_family == AF_INET) {
1499 auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
1500 char buf[INET_ADDRSTRLEN];
1501 if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
1502 freeifaddrs(ifap);
1503 return std::string(buf, INET_ADDRSTRLEN);
1504 }
1505 }
1506 }
1507 }
1508 freeifaddrs(ifap);
1509#endif
1510 return std::string();
1511}
1512
1513inline socket_t create_client_socket(const char *host, int port,
1514 time_t timeout_sec,
1515 const std::string &intf) {
1516 return create_socket(
1517 host, port, [&](socket_t sock, struct addrinfo &ai) -> bool {
1518 if (!intf.empty()) {
1519 auto ip = if2ip(intf);
1520 if (ip.empty()) { ip = intf; }
1521 if (!bind_ip_address(sock, ip.c_str())) { return false; }
1522 }
1523
1524 set_nonblocking(sock, true);
1525
1526 auto ret = ::connect(sock, ai.ai_addr, static_cast<int>(ai.ai_addrlen));
1527 if (ret < 0) {
1528 if (is_connection_error() ||
1529 !wait_until_socket_is_ready(sock, timeout_sec, 0)) {
1530 close_socket(sock);
1531 return false;
1532 }
1533 }
1534
1535 set_nonblocking(sock, false);
1536 return true;
1537 });
1538}
1539
1216inline std::string get_remote_addr(socket_t sock) { 1540inline std::string get_remote_addr(socket_t sock) {
1217 struct sockaddr_storage addr; 1541 struct sockaddr_storage addr;
1218 socklen_t len = sizeof(addr); 1542 socklen_t len = sizeof(addr);
1219 1543
1220 if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr), &len)) { 1544 if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr), &len)) {
1221 char ipstr[NI_MAXHOST]; 1545 std::array<char, NI_MAXHOST> ipstr{};
1222 1546
1223 if (!getnameinfo(reinterpret_cast<struct sockaddr *>(&addr), len, ipstr, sizeof(ipstr), 1547 if (!getnameinfo(reinterpret_cast<struct sockaddr *>(&addr), len,
1224 nullptr, 0, NI_NUMERICHOST)) { 1548 ipstr.data(), static_cast<unsigned int>(ipstr.size()), nullptr, 0, NI_NUMERICHOST)) {
1225 return ipstr; 1549 return ipstr.data();
1226 } 1550 }
1227 } 1551 }
1228 1552
1229 return std::string(); 1553 return std::string();
1230} 1554}
1231 1555
1232inline const char *find_content_type(const std::string &path) { 1556inline const char *
1557find_content_type(const std::string &path,
1558 const std::map<std::string, std::string> &user_data) {
1233 auto ext = file_extension(path); 1559 auto ext = file_extension(path);
1560
1561 auto it = user_data.find(ext);
1562 if (it != user_data.end()) { return it->second.c_str(); }
1563
1234 if (ext == "txt") { 1564 if (ext == "txt") {
1235 return "text/plain"; 1565 return "text/plain";
1236 } else if (ext == "html") { 1566 } else if (ext == "html" || ext == "htm") {
1237 return "text/html"; 1567 return "text/html";
1238 } else if (ext == "css") { 1568 } else if (ext == "css") {
1239 return "text/css"; 1569 return "text/css";
@@ -1253,6 +1583,8 @@ inline const char *find_content_type(const std::string &path) {
1253 return "application/pdf"; 1583 return "application/pdf";
1254 } else if (ext == "js") { 1584 } else if (ext == "js") {
1255 return "application/javascript"; 1585 return "application/javascript";
1586 } else if (ext == "wasm") {
1587 return "application/wasm";
1256 } else if (ext == "xml") { 1588 } else if (ext == "xml") {
1257 return "application/xml"; 1589 return "application/xml";
1258 } else if (ext == "xhtml") { 1590 } else if (ext == "xhtml") {
@@ -1263,19 +1595,25 @@ inline const char *find_content_type(const std::string &path) {
1263 1595
1264inline const char *status_message(int status) { 1596inline const char *status_message(int status) {
1265 switch (status) { 1597 switch (status) {
1598 case 100: return "Continue";
1266 case 200: return "OK"; 1599 case 200: return "OK";
1600 case 202: return "Accepted";
1601 case 204: return "No Content";
1267 case 206: return "Partial Content"; 1602 case 206: return "Partial Content";
1268 case 301: return "Moved Permanently"; 1603 case 301: return "Moved Permanently";
1269 case 302: return "Found"; 1604 case 302: return "Found";
1270 case 303: return "See Other"; 1605 case 303: return "See Other";
1271 case 304: return "Not Modified"; 1606 case 304: return "Not Modified";
1272 case 400: return "Bad Request"; 1607 case 400: return "Bad Request";
1608 case 401: return "Unauthorized";
1273 case 403: return "Forbidden"; 1609 case 403: return "Forbidden";
1274 case 404: return "Not Found"; 1610 case 404: return "Not Found";
1275 case 413: return "Payload Too Large"; 1611 case 413: return "Payload Too Large";
1276 case 414: return "Request-URI Too Long"; 1612 case 414: return "Request-URI Too Long";
1277 case 415: return "Unsupported Media Type"; 1613 case 415: return "Unsupported Media Type";
1278 case 416: return "Range Not Satisfiable"; 1614 case 416: return "Range Not Satisfiable";
1615 case 417: return "Expectation Failed";
1616 case 503: return "Service Unavailable";
1279 1617
1280 default: 1618 default:
1281 case 500: return "Internal Server Error"; 1619 case 500: return "Internal Server Error";
@@ -1302,18 +1640,18 @@ inline bool compress(std::string &content) {
1302 if (ret != Z_OK) { return false; } 1640 if (ret != Z_OK) { return false; }
1303 1641
1304 strm.avail_in = content.size(); 1642 strm.avail_in = content.size();
1305 strm.next_in = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(content.data())); 1643 strm.next_in =
1644 const_cast<Bytef *>(reinterpret_cast<const Bytef *>(content.data()));
1306 1645
1307 std::string compressed; 1646 std::string compressed;
1308 1647
1309 const auto bufsiz = 16384; 1648 std::array<char, 16384> buff{};
1310 char buff[bufsiz];
1311 do { 1649 do {
1312 strm.avail_out = bufsiz; 1650 strm.avail_out = buff.size();
1313 strm.next_out = reinterpret_cast<Bytef*>(buff); 1651 strm.next_out = reinterpret_cast<Bytef *>(buff.data());
1314 ret = deflate(&strm, Z_FINISH); 1652 ret = deflate(&strm, Z_FINISH);
1315 assert(ret != Z_STREAM_ERROR); 1653 assert(ret != Z_STREAM_ERROR);
1316 compressed.append(buff, bufsiz - strm.avail_out); 1654 compressed.append(buff.data(), buff.size() - strm.avail_out);
1317 } while (strm.avail_out == 0); 1655 } while (strm.avail_out == 0);
1318 1656
1319 assert(ret == Z_STREAM_END); 1657 assert(ret == Z_STREAM_END);
@@ -1347,13 +1685,12 @@ public:
1347 int ret = Z_OK; 1685 int ret = Z_OK;
1348 1686
1349 strm.avail_in = data_length; 1687 strm.avail_in = data_length;
1350 strm.next_in = const_cast<Bytef*>(reinterpret_cast<const Bytef *>(data)); 1688 strm.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
1351 1689
1352 const auto bufsiz = 16384; 1690 std::array<char, 16384> buff{};
1353 char buff[bufsiz];
1354 do { 1691 do {
1355 strm.avail_out = bufsiz; 1692 strm.avail_out = buff.size();
1356 strm.next_out = reinterpret_cast<Bytef*>(buff); 1693 strm.next_out = reinterpret_cast<Bytef *>(buff.data());
1357 1694
1358 ret = inflate(&strm, Z_NO_FLUSH); 1695 ret = inflate(&strm, Z_NO_FLUSH);
1359 assert(ret != Z_STREAM_ERROR); 1696 assert(ret != Z_STREAM_ERROR);
@@ -1363,10 +1700,12 @@ public:
1363 case Z_MEM_ERROR: inflateEnd(&strm); return false; 1700 case Z_MEM_ERROR: inflateEnd(&strm); return false;
1364 } 1701 }
1365 1702
1366 if (!callback(buff, bufsiz - strm.avail_out)) { return false; } 1703 if (!callback(buff.data(), buff.size() - strm.avail_out)) {
1704 return false;
1705 }
1367 } while (strm.avail_out == 0); 1706 } while (strm.avail_out == 0);
1368 1707
1369 return ret == Z_STREAM_END; 1708 return ret == Z_OK || ret == Z_STREAM_END;
1370 } 1709 }
1371 1710
1372private: 1711private:
@@ -1397,18 +1736,35 @@ inline uint64_t get_header_value_uint64(const Headers &headers, const char *key,
1397} 1736}
1398 1737
1399inline bool read_headers(Stream &strm, Headers &headers) { 1738inline bool read_headers(Stream &strm, Headers &headers) {
1400 static std::regex re(R"((.+?):\s*(.+?)\s*\r\n)");
1401
1402 const auto bufsiz = 2048; 1739 const auto bufsiz = 2048;
1403 char buf[bufsiz]; 1740 char buf[bufsiz];
1404 1741 stream_line_reader line_reader(strm, buf, bufsiz);
1405 stream_line_reader reader(strm, buf, bufsiz);
1406 1742
1407 for (;;) { 1743 for (;;) {
1408 if (!reader.getline()) { return false; } 1744 if (!line_reader.getline()) { return false; }
1409 if (!strcmp(reader.ptr(), "\r\n")) { break; } 1745
1746 // Check if the line ends with CRLF.
1747 if (line_reader.end_with_crlf()) {
1748 // Blank line indicates end of headers.
1749 if (line_reader.size() == 2) { break; }
1750 } else {
1751 continue; // Skip invalid line.
1752 }
1753
1754 // Skip trailing spaces and tabs.
1755 auto end = line_reader.ptr() + line_reader.size() - 2;
1756 while (line_reader.ptr() < end && (end[-1] == ' ' || end[-1] == '\t')) {
1757 end--;
1758 }
1759
1760 // Horizontal tab and ' ' are considered whitespace and are ignored when on
1761 // the left or right side of the header value:
1762 // - https://stackoverflow.com/questions/50179659/
1763 // - https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html
1764 static const std::regex re(R"((.+?):[\t ]*(.+))");
1765
1410 std::cmatch m; 1766 std::cmatch m;
1411 if (std::regex_match(reader.ptr(), m, re)) { 1767 if (std::regex_match(line_reader.ptr(), end, m, re)) {
1412 auto key = std::string(m[1]); 1768 auto key = std::string(m[1]);
1413 auto val = std::string(m[2]); 1769 auto val = std::string(m[2]);
1414 headers.emplace(key, val); 1770 headers.emplace(key, val);
@@ -1418,12 +1774,8 @@ inline bool read_headers(Stream &strm, Headers &headers) {
1418 return true; 1774 return true;
1419} 1775}
1420 1776
1421typedef std::function<bool(const char *data, size_t data_length)>
1422 ContentReceiverCore;
1423
1424inline bool read_content_with_length(Stream &strm, uint64_t len, 1777inline bool read_content_with_length(Stream &strm, uint64_t len,
1425 Progress progress, 1778 Progress progress, ContentReceiver out) {
1426 ContentReceiverCore out) {
1427 char buf[CPPHTTPLIB_RECV_BUFSIZ]; 1779 char buf[CPPHTTPLIB_RECV_BUFSIZ];
1428 1780
1429 uint64_t r = 0; 1781 uint64_t r = 0;
@@ -1455,7 +1807,7 @@ inline void skip_content_with_length(Stream &strm, uint64_t len) {
1455 } 1807 }
1456} 1808}
1457 1809
1458inline bool read_content_without_length(Stream &strm, ContentReceiverCore out) { 1810inline bool read_content_without_length(Stream &strm, ContentReceiver out) {
1459 char buf[CPPHTTPLIB_RECV_BUFSIZ]; 1811 char buf[CPPHTTPLIB_RECV_BUFSIZ];
1460 for (;;) { 1812 for (;;) {
1461 auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ); 1813 auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
@@ -1470,33 +1822,34 @@ inline bool read_content_without_length(Stream &strm, ContentReceiverCore out) {
1470 return true; 1822 return true;
1471} 1823}
1472 1824
1473inline bool read_content_chunked(Stream &strm, ContentReceiverCore out) { 1825inline bool read_content_chunked(Stream &strm, ContentReceiver out) {
1474 const auto bufsiz = 16; 1826 const auto bufsiz = 16;
1475 char buf[bufsiz]; 1827 char buf[bufsiz];
1476 1828
1477 stream_line_reader reader(strm, buf, bufsiz); 1829 stream_line_reader line_reader(strm, buf, bufsiz);
1478 1830
1479 if (!reader.getline()) { return false; } 1831 if (!line_reader.getline()) { return false; }
1480 1832
1481 auto chunk_len = std::stoi(reader.ptr(), 0, 16); 1833 auto chunk_len = std::stoi(line_reader.ptr(), 0, 16);
1482 1834
1483 while (chunk_len > 0) { 1835 while (chunk_len > 0) {
1484 if (!read_content_with_length(strm, chunk_len, nullptr, out)) { 1836 if (!read_content_with_length(strm, chunk_len, nullptr, out)) {
1485 return false; 1837 return false;
1486 } 1838 }
1487 1839
1488 if (!reader.getline()) { return false; } 1840 if (!line_reader.getline()) { return false; }
1489 1841
1490 if (strcmp(reader.ptr(), "\r\n")) { break; } 1842 if (strcmp(line_reader.ptr(), "\r\n")) { break; }
1491 1843
1492 if (!reader.getline()) { return false; } 1844 if (!line_reader.getline()) { return false; }
1493 1845
1494 chunk_len = std::stoi(reader.ptr(), 0, 16); 1846 chunk_len = std::stoi(line_reader.ptr(), 0, 16);
1495 } 1847 }
1496 1848
1497 if (chunk_len == 0) { 1849 if (chunk_len == 0) {
1498 // Reader terminator after chunks 1850 // Reader terminator after chunks
1499 if (!reader.getline() || strcmp(reader.ptr(), "\r\n")) return false; 1851 if (!line_reader.getline() || strcmp(line_reader.ptr(), "\r\n"))
1852 return false;
1500 } 1853 }
1501 1854
1502 return true; 1855 return true;
@@ -1509,14 +1862,14 @@ inline bool is_chunked_transfer_encoding(const Headers &headers) {
1509 1862
1510template <typename T> 1863template <typename T>
1511bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status, 1864bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
1512 Progress progress, ContentReceiverCore receiver) { 1865 Progress progress, ContentReceiver receiver) {
1513 1866
1514 ContentReceiverCore out = [&](const char *buf, size_t n) { 1867 ContentReceiver out = [&](const char *buf, size_t n) {
1515 return receiver(buf, n); 1868 return receiver(buf, n);
1516 }; 1869 };
1517 1870
1518#ifdef CPPHTTPLIB_ZLIB_SUPPORT 1871#ifdef CPPHTTPLIB_ZLIB_SUPPORT
1519 detail::decompressor decompressor; 1872 decompressor decompressor;
1520 1873
1521 if (!decompressor.is_valid()) { 1874 if (!decompressor.is_valid()) {
1522 status = 500; 1875 status = 500;
@@ -1586,39 +1939,47 @@ inline ssize_t write_content(Stream &strm, ContentProvider content_provider,
1586 size_t end_offset = offset + length; 1939 size_t end_offset = offset + length;
1587 while (offset < end_offset) { 1940 while (offset < end_offset) {
1588 ssize_t written_length = 0; 1941 ssize_t written_length = 0;
1589 content_provider( 1942
1590 offset, end_offset - offset, 1943 DataSink data_sink;
1591 [&](const char *d, size_t l) { 1944 data_sink.write = [&](const char *d, size_t l) {
1592 offset += l; 1945 offset += l;
1593 written_length = strm.write(d, l); 1946 written_length = strm.write(d, l);
1594 }, 1947 };
1595 [&](void) { written_length = -1; }); 1948 data_sink.done = [&](void) { written_length = -1; };
1949 data_sink.is_writable = [&](void) { return strm.is_writable(); };
1950
1951 content_provider(offset, end_offset - offset, data_sink);
1596 if (written_length < 0) { return written_length; } 1952 if (written_length < 0) { return written_length; }
1597 } 1953 }
1598 return static_cast<ssize_t>(offset - begin_offset); 1954 return static_cast<ssize_t>(offset - begin_offset);
1599} 1955}
1600 1956
1957template <typename T>
1601inline ssize_t write_content_chunked(Stream &strm, 1958inline ssize_t write_content_chunked(Stream &strm,
1602 ContentProvider content_provider) { 1959 ContentProvider content_provider,
1960 T is_shutting_down) {
1603 size_t offset = 0; 1961 size_t offset = 0;
1604 auto data_available = true; 1962 auto data_available = true;
1605 ssize_t total_written_length = 0; 1963 ssize_t total_written_length = 0;
1606 while (data_available) { 1964 while (data_available && !is_shutting_down()) {
1607 ssize_t written_length = 0; 1965 ssize_t written_length = 0;
1608 content_provider( 1966
1609 offset, 0, 1967 DataSink data_sink;
1610 [&](const char *d, size_t l) { 1968 data_sink.write = [&](const char *d, size_t l) {
1611 data_available = l > 0; 1969 data_available = l > 0;
1612 offset += l; 1970 offset += l;
1613 1971
1614 // Emit chunked response header and footer for each chunk 1972 // Emit chunked response header and footer for each chunk
1615 auto chunk = from_i_to_hex(l) + "\r\n" + std::string(d, l) + "\r\n"; 1973 auto chunk = from_i_to_hex(l) + "\r\n" + std::string(d, l) + "\r\n";
1616 written_length = strm.write(chunk); 1974 written_length = strm.write(chunk);
1617 }, 1975 };
1618 [&](void) { 1976 data_sink.done = [&](void) {
1619 data_available = false; 1977 data_available = false;
1620 written_length = strm.write("0\r\n\r\n"); 1978 written_length = strm.write("0\r\n\r\n");
1621 }); 1979 };
1980 data_sink.is_writable = [&](void) { return strm.is_writable(); };
1981
1982 content_provider(offset, 0, data_sink);
1622 1983
1623 if (written_length < 0) { return written_length; } 1984 if (written_length < 0) { return written_length; }
1624 total_written_length += written_length; 1985 total_written_length += written_length;
@@ -1629,17 +1990,12 @@ inline ssize_t write_content_chunked(Stream &strm,
1629template <typename T> 1990template <typename T>
1630inline bool redirect(T &cli, const Request &req, Response &res, 1991inline bool redirect(T &cli, const Request &req, Response &res,
1631 const std::string &path) { 1992 const std::string &path) {
1632 Request new_req; 1993 Request new_req = req;
1633 new_req.method = req.method;
1634 new_req.path = path; 1994 new_req.path = path;
1635 new_req.headers = req.headers; 1995 new_req.redirect_count -= 1;
1636 new_req.body = req.body;
1637 new_req.redirect_count = req.redirect_count - 1;
1638 new_req.response_handler = req.response_handler;
1639 new_req.content_receiver = req.content_receiver;
1640 new_req.progress = req.progress;
1641 1996
1642 Response new_res; 1997 Response new_res;
1998
1643 auto ret = cli.send(new_req, new_res); 1999 auto ret = cli.send(new_req, new_res);
1644 if (ret) { res = new_res; } 2000 if (ret) { res = new_res; }
1645 return ret; 2001 return ret;
@@ -1656,7 +2012,7 @@ inline std::string encode_url(const std::string &s) {
1656 case '\n': result += "%0A"; break; 2012 case '\n': result += "%0A"; break;
1657 case '\'': result += "%27"; break; 2013 case '\'': result += "%27"; break;
1658 case ',': result += "%2C"; break; 2014 case ',': result += "%2C"; break;
1659 case ':': result += "%3A"; break; 2015 // case ':': result += "%3A"; break; // ok? probably...
1660 case ';': result += "%3B"; break; 2016 case ';': result += "%3B"; break;
1661 default: 2017 default:
1662 auto c = static_cast<uint8_t>(s[i]); 2018 auto c = static_cast<uint8_t>(s[i]);
@@ -1716,11 +2072,11 @@ inline void parse_query_text(const std::string &s, Params &params) {
1716 split(&s[0], &s[s.size()], '&', [&](const char *b, const char *e) { 2072 split(&s[0], &s[s.size()], '&', [&](const char *b, const char *e) {
1717 std::string key; 2073 std::string key;
1718 std::string val; 2074 std::string val;
1719 split(b, e, '=', [&](const char *b, const char *e) { 2075 split(b, e, '=', [&](const char *b2, const char *e2) {
1720 if (key.empty()) { 2076 if (key.empty()) {
1721 key.assign(b, e); 2077 key.assign(b2, e2);
1722 } else { 2078 } else {
1723 val.assign(b, e); 2079 val.assign(b2, e2);
1724 } 2080 }
1725 }); 2081 });
1726 params.emplace(key, decode_url(val)); 2082 params.emplace(key, decode_url(val));
@@ -1736,112 +2092,207 @@ inline bool parse_multipart_boundary(const std::string &content_type,
1736 return true; 2092 return true;
1737} 2093}
1738 2094
1739inline bool parse_multipart_formdata(const std::string &boundary, 2095inline bool parse_range_header(const std::string &s, Ranges &ranges) {
1740 const std::string &body, 2096 static auto re_first_range = std::regex(R"(bytes=(\d*-\d*(?:,\s*\d*-\d*)*))");
1741 MultipartFiles &files) { 2097 std::smatch m;
1742 static std::string dash = "--"; 2098 if (std::regex_match(s, m, re_first_range)) {
1743 static std::string crlf = "\r\n"; 2099 auto pos = m.position(1);
1744 2100 auto len = m.length(1);
1745 static std::regex re_content_type("Content-Type: (.*?)", 2101 bool all_valid_ranges = true;
1746 std::regex_constants::icase); 2102 split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
1747 2103 if (!all_valid_ranges) return;
1748 static std::regex re_content_disposition( 2104 static auto re_another_range = std::regex(R"(\s*(\d*)-(\d*))");
1749 "Content-Disposition: form-data; name=\"(.*?)\"(?:; filename=\"(.*?)\")?", 2105 std::cmatch cm;
1750 std::regex_constants::icase); 2106 if (std::regex_match(b, e, cm, re_another_range)) {
1751 2107 ssize_t first = -1;
1752 auto dash_boundary = dash + boundary; 2108 if (!cm.str(1).empty()) {
1753 2109 first = static_cast<ssize_t>(std::stoll(cm.str(1)));
1754 auto pos = body.find(dash_boundary); 2110 }
1755 if (pos != 0) { return false; }
1756
1757 pos += dash_boundary.size();
1758 2111
1759 auto next_pos = body.find(crlf, pos); 2112 ssize_t last = -1;
1760 if (next_pos == std::string::npos) { return false; } 2113 if (!cm.str(2).empty()) {
2114 last = static_cast<ssize_t>(std::stoll(cm.str(2)));
2115 }
1761 2116
1762 pos = next_pos + crlf.size(); 2117 if (first != -1 && last != -1 && first > last) {
2118 all_valid_ranges = false;
2119 return;
2120 }
2121 ranges.emplace_back(std::make_pair(first, last));
2122 }
2123 });
2124 return all_valid_ranges;
2125 }
2126 return false;
2127}
1763 2128
1764 while (pos < body.size()) { 2129class MultipartFormDataParser {
1765 next_pos = body.find(crlf, pos); 2130public:
1766 if (next_pos == std::string::npos) { return false; } 2131 MultipartFormDataParser() {}
1767 2132
1768 std::string name; 2133 void set_boundary(const std::string &boundary) { boundary_ = boundary; }
1769 MultipartFile file;
1770 2134
1771 auto header = body.substr(pos, (next_pos - pos)); 2135 bool is_valid() const { return is_valid_; }
1772 2136
1773 while (pos != next_pos) { 2137 template <typename T, typename U>
1774 std::smatch m; 2138 bool parse(const char *buf, size_t n, T content_callback, U header_callback) {
1775 if (std::regex_match(header, m, re_content_type)) { 2139 static const std::regex re_content_type(R"(^Content-Type:\s*(.*?)\s*$)",
1776 file.content_type = m[1]; 2140 std::regex_constants::icase);
1777 } else if (std::regex_match(header, m, re_content_disposition)) { 2141
1778 name = m[1]; 2142 static const std::regex re_content_disposition(
1779 file.filename = m[2]; 2143 "^Content-Disposition:\\s*form-data;\\s*name=\"(.*?)\"(?:;\\s*filename="
2144 "\"(.*?)\")?\\s*$",
2145 std::regex_constants::icase);
2146
2147 buf_.append(buf, n); // TODO: performance improvement
2148
2149 while (!buf_.empty()) {
2150 switch (state_) {
2151 case 0: { // Initial boundary
2152 auto pattern = dash_ + boundary_ + crlf_;
2153 if (pattern.size() > buf_.size()) { return true; }
2154 auto pos = buf_.find(pattern);
2155 if (pos != 0) {
2156 is_done_ = true;
2157 return false;
2158 }
2159 buf_.erase(0, pattern.size());
2160 off_ += pattern.size();
2161 state_ = 1;
2162 break;
1780 } 2163 }
2164 case 1: { // New entry
2165 clear_file_info();
2166 state_ = 2;
2167 break;
2168 }
2169 case 2: { // Headers
2170 auto pos = buf_.find(crlf_);
2171 while (pos != std::string::npos) {
2172 // Empty line
2173 if (pos == 0) {
2174 if (!header_callback(file_)) {
2175 is_valid_ = false;
2176 is_done_ = false;
2177 return false;
2178 }
2179 buf_.erase(0, crlf_.size());
2180 off_ += crlf_.size();
2181 state_ = 3;
2182 break;
2183 }
1781 2184
1782 pos = next_pos + crlf.size(); 2185 auto header = buf_.substr(0, pos);
1783 2186 {
1784 next_pos = body.find(crlf, pos); 2187 std::smatch m;
1785 if (next_pos == std::string::npos) { return false; } 2188 if (std::regex_match(header, m, re_content_type)) {
1786 2189 file_.content_type = m[1];
1787 header = body.substr(pos, (next_pos - pos)); 2190 } else if (std::regex_match(header, m, re_content_disposition)) {
1788 } 2191 file_.name = m[1];
1789 2192 file_.filename = m[2];
1790 pos = next_pos + crlf.size(); 2193 }
2194 }
1791 2195
1792 next_pos = body.find(crlf + dash_boundary, pos); 2196 buf_.erase(0, pos + crlf_.size());
2197 off_ += pos + crlf_.size();
2198 pos = buf_.find(crlf_);
2199 }
2200 break;
2201 }
2202 case 3: { // Body
2203 {
2204 auto pattern = crlf_ + dash_;
2205 if (pattern.size() > buf_.size()) { return true; }
2206
2207 auto pos = buf_.find(pattern);
2208 if (pos == std::string::npos) { pos = buf_.size(); }
2209 if (!content_callback(buf_.data(), pos)) {
2210 is_valid_ = false;
2211 is_done_ = false;
2212 return false;
2213 }
1793 2214
1794 if (next_pos == std::string::npos) { return false; } 2215 off_ += pos;
2216 buf_.erase(0, pos);
2217 }
1795 2218
1796 file.offset = pos; 2219 {
1797 file.length = next_pos - pos; 2220 auto pattern = crlf_ + dash_ + boundary_;
2221 if (pattern.size() > buf_.size()) { return true; }
2222
2223 auto pos = buf_.find(pattern);
2224 if (pos != std::string::npos) {
2225 if (!content_callback(buf_.data(), pos)) {
2226 is_valid_ = false;
2227 is_done_ = false;
2228 return false;
2229 }
1798 2230
1799 pos = next_pos + crlf.size() + dash_boundary.size(); 2231 off_ += pos + pattern.size();
2232 buf_.erase(0, pos + pattern.size());
2233 state_ = 4;
2234 } else {
2235 if (!content_callback(buf_.data(), pattern.size())) {
2236 is_valid_ = false;
2237 is_done_ = false;
2238 return false;
2239 }
1800 2240
1801 next_pos = body.find(crlf, pos); 2241 off_ += pattern.size();
1802 if (next_pos == std::string::npos) { return false; } 2242 buf_.erase(0, pattern.size());
2243 }
2244 }
2245 break;
2246 }
2247 case 4: { // Boundary
2248 if (crlf_.size() > buf_.size()) { return true; }
2249 if (buf_.find(crlf_) == 0) {
2250 buf_.erase(0, crlf_.size());
2251 off_ += crlf_.size();
2252 state_ = 1;
2253 } else {
2254 auto pattern = dash_ + crlf_;
2255 if (pattern.size() > buf_.size()) { return true; }
2256 if (buf_.find(pattern) == 0) {
2257 buf_.erase(0, pattern.size());
2258 off_ += pattern.size();
2259 is_valid_ = true;
2260 state_ = 5;
2261 } else {
2262 is_done_ = true;
2263 return true;
2264 }
2265 }
2266 break;
2267 }
2268 case 5: { // Done
2269 is_valid_ = false;
2270 return false;
2271 }
2272 }
2273 }
1803 2274
1804 files.emplace(name, file); 2275 return true;
2276 }
1805 2277
1806 pos = next_pos + crlf.size(); 2278private:
2279 void clear_file_info() {
2280 file_.name.clear();
2281 file_.filename.clear();
2282 file_.content_type.clear();
1807 } 2283 }
1808 2284
1809 return true; 2285 const std::string dash_ = "--";
1810} 2286 const std::string crlf_ = "\r\n";
2287 std::string boundary_;
1811 2288
1812inline bool parse_range_header(const std::string &s, Ranges &ranges) { 2289 std::string buf_;
1813 try { 2290 size_t state_ = 0;
1814 static auto re = std::regex(R"(bytes=(\d*-\d*(?:,\s*\d*-\d*)*))"); 2291 size_t is_valid_ = false;
1815 std::smatch m; 2292 size_t is_done_ = false;
1816 if (std::regex_match(s, m, re)) { 2293 size_t off_ = 0;
1817 auto pos = m.position(1); 2294 MultipartFormData file_;
1818 auto len = m.length(1); 2295};
1819 detail::split(&s[pos], &s[pos + len], ',',
1820 [&](const char *b, const char *e) {
1821 static auto re = std::regex(R"(\s*(\d*)-(\d*))");
1822 std::cmatch m;
1823 if (std::regex_match(b, e, m, re)) {
1824 ssize_t first = -1;
1825 if (!m.str(1).empty()) {
1826 first = static_cast<ssize_t>(std::stoll(m.str(1)));
1827 }
1828
1829 ssize_t last = -1;
1830 if (!m.str(2).empty()) {
1831 last = static_cast<ssize_t>(std::stoll(m.str(2)));
1832 }
1833
1834 if (first != -1 && last != -1 && first > last) {
1835 throw std::runtime_error("invalid range error");
1836 }
1837 ranges.emplace_back(std::make_pair(first, last));
1838 }
1839 });
1840 return true;
1841 }
1842 return false;
1843 } catch (...) { return false; }
1844}
1845 2296
1846inline std::string to_lower(const char *beg, const char *end) { 2297inline std::string to_lower(const char *beg, const char *end) {
1847 std::string out; 2298 std::string out;
@@ -1915,7 +2366,7 @@ bool process_multipart_ranges_data(const Request &req, Response &res,
1915 ctoken("\r\n"); 2366 ctoken("\r\n");
1916 } 2367 }
1917 2368
1918 auto offsets = detail::get_range_offset_and_length(req, res.body.size(), i); 2369 auto offsets = get_range_offset_and_length(req, res.body.size(), i);
1919 auto offset = offsets.first; 2370 auto offset = offsets.first;
1920 auto length = offsets.second; 2371 auto length = offsets.second;
1921 2372
@@ -1978,8 +2429,7 @@ inline bool write_multipart_ranges_data(Stream &strm, const Request &req,
1978 [&](const std::string &token) { strm.write(token); }, 2429 [&](const std::string &token) { strm.write(token); },
1979 [&](const char *token) { strm.write(token); }, 2430 [&](const char *token) { strm.write(token); },
1980 [&](size_t offset, size_t length) { 2431 [&](size_t offset, size_t length) {
1981 return detail::write_content(strm, res.content_provider, offset, 2432 return write_content(strm, res.content_provider, offset, length) >= 0;
1982 length) >= 0;
1983 }); 2433 });
1984} 2434}
1985 2435
@@ -1988,11 +2438,56 @@ get_range_offset_and_length(const Request &req, const Response &res,
1988 size_t index) { 2438 size_t index) {
1989 auto r = req.ranges[index]; 2439 auto r = req.ranges[index];
1990 2440
1991 if (r.second == -1) { r.second = res.content_provider_resource_length - 1; } 2441 if (r.second == -1) { r.second = res.content_length - 1; }
1992 2442
1993 return std::make_pair(r.first, r.second - r.first + 1); 2443 return std::make_pair(r.first, r.second - r.first + 1);
1994} 2444}
1995 2445
2446inline bool expect_content(const Request &req) {
2447 if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
2448 req.method == "PRI") {
2449 return true;
2450 }
2451 // TODO: check if Content-Length is set
2452 return false;
2453}
2454
2455#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
2456template <typename CTX, typename Init, typename Update, typename Final>
2457inline std::string message_digest(const std::string &s, Init init,
2458 Update update, Final final,
2459 size_t digest_length) {
2460 using namespace std;
2461
2462 std::vector<unsigned char> md(digest_length, 0);
2463 CTX ctx;
2464 init(&ctx);
2465 update(&ctx, s.data(), s.size());
2466 final(md.data(), &ctx);
2467
2468 stringstream ss;
2469 for (auto c : md) {
2470 ss << setfill('0') << setw(2) << hex << (unsigned int)c;
2471 }
2472 return ss.str();
2473}
2474
2475inline std::string MD5(const std::string &s) {
2476 return message_digest<MD5_CTX>(s, MD5_Init, MD5_Update, MD5_Final,
2477 MD5_DIGEST_LENGTH);
2478}
2479
2480inline std::string SHA_256(const std::string &s) {
2481 return message_digest<SHA256_CTX>(s, SHA256_Init, SHA256_Update, SHA256_Final,
2482 SHA256_DIGEST_LENGTH);
2483}
2484
2485inline std::string SHA_512(const std::string &s) {
2486 return message_digest<SHA512_CTX>(s, SHA512_Init, SHA512_Update, SHA512_Final,
2487 SHA512_DIGEST_LENGTH);
2488}
2489#endif
2490
1996#ifdef _WIN32 2491#ifdef _WIN32
1997class WSInit { 2492class WSInit {
1998public: 2493public:
@@ -2025,9 +2520,103 @@ inline std::pair<std::string, std::string> make_range_header(Ranges ranges) {
2025 2520
2026inline std::pair<std::string, std::string> 2521inline std::pair<std::string, std::string>
2027make_basic_authentication_header(const std::string &username, 2522make_basic_authentication_header(const std::string &username,
2028 const std::string &password) { 2523 const std::string &password,
2524 bool is_proxy = false) {
2029 auto field = "Basic " + detail::base64_encode(username + ":" + password); 2525 auto field = "Basic " + detail::base64_encode(username + ":" + password);
2030 return std::make_pair("Authorization", field); 2526 auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
2527 return std::make_pair(key, field);
2528}
2529
2530#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
2531inline std::pair<std::string, std::string> make_digest_authentication_header(
2532 const Request &req, const std::map<std::string, std::string> &auth,
2533 size_t cnonce_count, const std::string &cnonce, const std::string &username,
2534 const std::string &password, bool is_proxy = false) {
2535 using namespace std;
2536
2537 string nc;
2538 {
2539 stringstream ss;
2540 ss << setfill('0') << setw(8) << hex << cnonce_count;
2541 nc = ss.str();
2542 }
2543
2544 auto qop = auth.at("qop");
2545 if (qop.find("auth-int") != std::string::npos) {
2546 qop = "auth-int";
2547 } else {
2548 qop = "auth";
2549 }
2550
2551 std::string algo = "MD5";
2552 if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
2553
2554 string response;
2555 {
2556 auto H = algo == "SHA-256"
2557 ? detail::SHA_256
2558 : algo == "SHA-512" ? detail::SHA_512 : detail::MD5;
2559
2560 auto A1 = username + ":" + auth.at("realm") + ":" + password;
2561
2562 auto A2 = req.method + ":" + req.path;
2563 if (qop == "auth-int") { A2 += ":" + H(req.body); }
2564
2565 response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
2566 ":" + qop + ":" + H(A2));
2567 }
2568
2569 auto field = "Digest username=\"hello\", realm=\"" + auth.at("realm") +
2570 "\", nonce=\"" + auth.at("nonce") + "\", uri=\"" + req.path +
2571 "\", algorithm=" + algo + ", qop=" + qop + ", nc=\"" + nc +
2572 "\", cnonce=\"" + cnonce + "\", response=\"" + response + "\"";
2573
2574 auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
2575 return std::make_pair(key, field);
2576}
2577#endif
2578
2579inline bool parse_www_authenticate(const httplib::Response &res,
2580 std::map<std::string, std::string> &auth,
2581 bool is_proxy) {
2582 auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
2583 if (res.has_header(auth_key)) {
2584 static auto re = std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
2585 auto s = res.get_header_value(auth_key);
2586 auto pos = s.find(' ');
2587 if (pos != std::string::npos) {
2588 auto type = s.substr(0, pos);
2589 if (type == "Basic") {
2590 return false;
2591 } else if (type == "Digest") {
2592 s = s.substr(pos + 1);
2593 auto beg = std::sregex_iterator(s.begin(), s.end(), re);
2594 for (auto i = beg; i != std::sregex_iterator(); ++i) {
2595 auto m = *i;
2596 auto key = s.substr(m.position(1), m.length(1));
2597 auto val = m.length(2) > 0 ? s.substr(m.position(2), m.length(2))
2598 : s.substr(m.position(3), m.length(3));
2599 auth[key] = val;
2600 }
2601 return true;
2602 }
2603 }
2604 }
2605 return false;
2606}
2607
2608// https://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c/440240#answer-440240
2609inline std::string random_string(size_t length) {
2610 auto randchar = []() -> char {
2611 const char charset[] = "0123456789"
2612 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2613 "abcdefghijklmnopqrstuvwxyz";
2614 const size_t max_index = (sizeof(charset) - 1);
2615 return charset[rand() % max_index];
2616 };
2617 std::string str(length, 0);
2618 std::generate_n(str.begin(), length, randchar);
2619 return str;
2031} 2620}
2032 2621
2033// Request implementation 2622// Request implementation
@@ -2068,14 +2657,19 @@ inline size_t Request::get_param_value_count(const char *key) const {
2068 return std::distance(r.first, r.second); 2657 return std::distance(r.first, r.second);
2069} 2658}
2070 2659
2660inline bool Request::is_multipart_form_data() const {
2661 const auto &content_type = get_header_value("Content-Type");
2662 return !content_type.find("multipart/form-data");
2663}
2664
2071inline bool Request::has_file(const char *key) const { 2665inline bool Request::has_file(const char *key) const {
2072 return files.find(key) != files.end(); 2666 return files.find(key) != files.end();
2073} 2667}
2074 2668
2075inline MultipartFile Request::get_file_value(const char *key) const { 2669inline MultipartFormData Request::get_file_value(const char *key) const {
2076 auto it = files.find(key); 2670 auto it = files.find(key);
2077 if (it != files.end()) { return it->second; } 2671 if (it != files.end()) { return it->second; }
2078 return MultipartFile(); 2672 return MultipartFormData();
2079} 2673}
2080 2674
2081// Response implementation 2675// Response implementation
@@ -2119,40 +2713,47 @@ inline void Response::set_content(const std::string &s,
2119} 2713}
2120 2714
2121inline void Response::set_content_provider( 2715inline void Response::set_content_provider(
2122 size_t length, 2716 size_t in_length,
2123 std::function<void(size_t offset, size_t length, DataSink sink)> provider, 2717 std::function<void(size_t offset, size_t length, DataSink &sink)> provider,
2124 std::function<void()> resource_releaser) { 2718 std::function<void()> resource_releaser) {
2125 assert(length > 0); 2719 assert(in_length > 0);
2126 content_provider_resource_length = length; 2720 content_length = in_length;
2127 content_provider = [provider](size_t offset, size_t length, DataSink sink, 2721 content_provider = [provider](size_t offset, size_t length, DataSink &sink) {
2128 Done) { provider(offset, length, sink); }; 2722 provider(offset, length, sink);
2723 };
2129 content_provider_resource_releaser = resource_releaser; 2724 content_provider_resource_releaser = resource_releaser;
2130} 2725}
2131 2726
2132inline void Response::set_chunked_content_provider( 2727inline void Response::set_chunked_content_provider(
2133 std::function<void(size_t offset, DataSink sink, Done done)> provider, 2728 std::function<void(size_t offset, DataSink &sink)> provider,
2134 std::function<void()> resource_releaser) { 2729 std::function<void()> resource_releaser) {
2135 content_provider_resource_length = 0; 2730 content_length = 0;
2136 content_provider = [provider](size_t offset, size_t, DataSink sink, 2731 content_provider = [provider](size_t offset, size_t, DataSink &sink) {
2137 Done done) { provider(offset, sink, done); }; 2732 provider(offset, sink);
2733 };
2138 content_provider_resource_releaser = resource_releaser; 2734 content_provider_resource_releaser = resource_releaser;
2139} 2735}
2140 2736
2141// Rstream implementation 2737// Rstream implementation
2738inline int Stream::write(const char *ptr) { return write(ptr, strlen(ptr)); }
2739
2740inline int Stream::write(const std::string &s) {
2741 return write(s.data(), s.size());
2742}
2743
2142template <typename... Args> 2744template <typename... Args>
2143inline int Stream::write_format(const char *fmt, const Args &... args) { 2745inline int Stream::write_format(const char *fmt, const Args &... args) {
2144 const auto bufsiz = 2048; 2746 std::array<char, 2048> buf;
2145 char buf[bufsiz];
2146 2747
2147#if defined(_MSC_VER) && _MSC_VER < 1900 2748#if defined(_MSC_VER) && _MSC_VER < 1900
2148 auto n = _snprintf_s(buf, bufsiz, bufsiz - 1, fmt, args...); 2749 auto n = _snprintf_s(buf, bufsiz, buf.size() - 1, fmt, args...);
2149#else 2750#else
2150 auto n = snprintf(buf, bufsiz - 1, fmt, args...); 2751 auto n = snprintf(buf.data(), buf.size() - 1, fmt, args...);
2151#endif 2752#endif
2152 if (n <= 0) { return n; } 2753 if (n <= 0) { return n; }
2153 2754
2154 if (n >= bufsiz - 1) { 2755 if (n >= static_cast<int>(buf.size()) - 1) {
2155 std::vector<char> glowable_buf(bufsiz); 2756 std::vector<char> glowable_buf(buf.size());
2156 2757
2157 while (n >= static_cast<int>(glowable_buf.size() - 1)) { 2758 while (n >= static_cast<int>(glowable_buf.size() - 1)) {
2158 glowable_buf.resize(glowable_buf.size() * 2); 2759 glowable_buf.resize(glowable_buf.size() * 2);
@@ -2165,33 +2766,36 @@ inline int Stream::write_format(const char *fmt, const Args &... args) {
2165 } 2766 }
2166 return write(&glowable_buf[0], n); 2767 return write(&glowable_buf[0], n);
2167 } else { 2768 } else {
2168 return write(buf, n); 2769 return write(buf.data(), n);
2169 } 2770 }
2170} 2771}
2171 2772
2773namespace detail {
2774
2172// Socket stream implementation 2775// Socket stream implementation
2173inline SocketStream::SocketStream(socket_t sock) : sock_(sock) {} 2776inline SocketStream::SocketStream(socket_t sock, time_t read_timeout_sec,
2777 time_t read_timeout_usec)
2778 : sock_(sock), read_timeout_sec_(read_timeout_sec),
2779 read_timeout_usec_(read_timeout_usec) {}
2174 2780
2175inline SocketStream::~SocketStream() {} 2781inline SocketStream::~SocketStream() {}
2176 2782
2177inline int SocketStream::read(char *ptr, size_t size) { 2783inline bool SocketStream::is_readable() const {
2178 if (detail::select_read(sock_, CPPHTTPLIB_READ_TIMEOUT_SECOND, 2784 return detail::select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
2179 CPPHTTPLIB_READ_TIMEOUT_USECOND) > 0) {
2180 return recv(sock_, ptr, static_cast<int>(size), 0);
2181 }
2182 return -1;
2183} 2785}
2184 2786
2185inline int SocketStream::write(const char *ptr, size_t size) { 2787inline bool SocketStream::is_writable() const {
2186 return send(sock_, ptr, static_cast<int>(size), 0); 2788 return detail::select_write(sock_, 0, 0) > 0;
2187} 2789}
2188 2790
2189inline int SocketStream::write(const char *ptr) { 2791inline int SocketStream::read(char *ptr, size_t size) {
2190 return write(ptr, strlen(ptr)); 2792 if (is_readable()) { return recv(sock_, ptr, static_cast<int>(size), 0); }
2793 return -1;
2191} 2794}
2192 2795
2193inline int SocketStream::write(const std::string &s) { 2796inline int SocketStream::write(const char *ptr, size_t size) {
2194 return write(s.data(), s.size()); 2797 if (is_writable()) { return send(sock_, ptr, static_cast<int>(size), 0); }
2798 return -1;
2195} 2799}
2196 2800
2197inline std::string SocketStream::get_remote_addr() const { 2801inline std::string SocketStream::get_remote_addr() const {
@@ -2199,12 +2803,18 @@ inline std::string SocketStream::get_remote_addr() const {
2199} 2803}
2200 2804
2201// Buffer stream implementation 2805// Buffer stream implementation
2806inline bool BufferStream::is_readable() const { return true; }
2807
2808inline bool BufferStream::is_writable() const { return true; }
2809
2202inline int BufferStream::read(char *ptr, size_t size) { 2810inline int BufferStream::read(char *ptr, size_t size) {
2203#if defined(_MSC_VER) && _MSC_VER < 1900 2811#if defined(_MSC_VER) && _MSC_VER < 1900
2204 return static_cast<int>(buffer._Copy_s(ptr, size, size)); 2812 int len_read = static_cast<int>(buffer._Copy_s(ptr, size, size, position));
2205#else 2813#else
2206 return static_cast<int>(buffer.copy(ptr, size)); 2814 int len_read = static_cast<int>(buffer.copy(ptr, size, position));
2207#endif 2815#endif
2816 position += len_read;
2817 return len_read;
2208} 2818}
2209 2819
2210inline int BufferStream::write(const char *ptr, size_t size) { 2820inline int BufferStream::write(const char *ptr, size_t size) {
@@ -2212,33 +2822,23 @@ inline int BufferStream::write(const char *ptr, size_t size) {
2212 return static_cast<int>(size); 2822 return static_cast<int>(size);
2213} 2823}
2214 2824
2215inline int BufferStream::write(const char *ptr) {
2216 return write(ptr, strlen(ptr));
2217}
2218
2219inline int BufferStream::write(const std::string &s) {
2220 return write(s.data(), s.size());
2221}
2222
2223inline std::string BufferStream::get_remote_addr() const { return ""; } 2825inline std::string BufferStream::get_remote_addr() const { return ""; }
2224 2826
2225inline const std::string &BufferStream::get_buffer() const { return buffer; } 2827inline const std::string &BufferStream::get_buffer() const { return buffer; }
2226 2828
2829} // namespace detail
2830
2227// HTTP server implementation 2831// HTTP server implementation
2228inline Server::Server() 2832inline Server::Server()
2229 : keep_alive_max_count_(CPPHTTPLIB_KEEPALIVE_MAX_COUNT), 2833 : keep_alive_max_count_(CPPHTTPLIB_KEEPALIVE_MAX_COUNT),
2834 read_timeout_sec_(CPPHTTPLIB_READ_TIMEOUT_SECOND),
2835 read_timeout_usec_(CPPHTTPLIB_READ_TIMEOUT_USECOND),
2230 payload_max_length_(CPPHTTPLIB_PAYLOAD_MAX_LENGTH), is_running_(false), 2836 payload_max_length_(CPPHTTPLIB_PAYLOAD_MAX_LENGTH), is_running_(false),
2231 svr_sock_(INVALID_SOCKET) { 2837 svr_sock_(INVALID_SOCKET) {
2232#ifndef _WIN32 2838#ifndef _WIN32
2233 signal(SIGPIPE, SIG_IGN); 2839 signal(SIGPIPE, SIG_IGN);
2234#endif 2840#endif
2235 new_task_queue = [] { 2841 new_task_queue = [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); };
2236#if CPPHTTPLIB_THREAD_POOL_COUNT > 0
2237 return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT);
2238#else
2239 return new Threads();
2240#endif
2241 };
2242} 2842}
2243 2843
2244inline Server::~Server() {} 2844inline Server::~Server() {}
@@ -2253,16 +2853,37 @@ inline Server &Server::Post(const char *pattern, Handler handler) {
2253 return *this; 2853 return *this;
2254} 2854}
2255 2855
2856inline Server &Server::Post(const char *pattern,
2857 HandlerWithContentReader handler) {
2858 post_handlers_for_content_reader_.push_back(
2859 std::make_pair(std::regex(pattern), handler));
2860 return *this;
2861}
2862
2256inline Server &Server::Put(const char *pattern, Handler handler) { 2863inline Server &Server::Put(const char *pattern, Handler handler) {
2257 put_handlers_.push_back(std::make_pair(std::regex(pattern), handler)); 2864 put_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
2258 return *this; 2865 return *this;
2259} 2866}
2260 2867
2868inline Server &Server::Put(const char *pattern,
2869 HandlerWithContentReader handler) {
2870 put_handlers_for_content_reader_.push_back(
2871 std::make_pair(std::regex(pattern), handler));
2872 return *this;
2873}
2874
2261inline Server &Server::Patch(const char *pattern, Handler handler) { 2875inline Server &Server::Patch(const char *pattern, Handler handler) {
2262 patch_handlers_.push_back(std::make_pair(std::regex(pattern), handler)); 2876 patch_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
2263 return *this; 2877 return *this;
2264} 2878}
2265 2879
2880inline Server &Server::Patch(const char *pattern,
2881 HandlerWithContentReader handler) {
2882 patch_handlers_for_content_reader_.push_back(
2883 std::make_pair(std::regex(pattern), handler));
2884 return *this;
2885}
2886
2266inline Server &Server::Delete(const char *pattern, Handler handler) { 2887inline Server &Server::Delete(const char *pattern, Handler handler) {
2267 delete_handlers_.push_back(std::make_pair(std::regex(pattern), handler)); 2888 delete_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
2268 return *this; 2889 return *this;
@@ -2273,32 +2894,68 @@ inline Server &Server::Options(const char *pattern, Handler handler) {
2273 return *this; 2894 return *this;
2274} 2895}
2275 2896
2276inline bool Server::set_base_dir(const char *path) { 2897inline bool Server::set_base_dir(const char *dir, const char *mount_point) {
2277 if (detail::is_dir(path)) { 2898 return set_mount_point(mount_point, dir);
2278 base_dir_ = path; 2899}
2279 return true; 2900
2901inline bool Server::set_mount_point(const char *mount_point, const char *dir) {
2902 if (detail::is_dir(dir)) {
2903 std::string mnt = mount_point ? mount_point : "/";
2904 if (!mnt.empty() && mnt[0] == '/') {
2905 base_dirs_.emplace_back(mnt, dir);
2906 return true;
2907 }
2908 }
2909 return false;
2910}
2911
2912inline bool Server::remove_mount_point(const char *mount_point) {
2913 for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
2914 if (it->first == mount_point) {
2915 base_dirs_.erase(it);
2916 return true;
2917 }
2280 } 2918 }
2281 return false; 2919 return false;
2282} 2920}
2283 2921
2922inline void Server::set_file_extension_and_mimetype_mapping(const char *ext,
2923 const char *mime) {
2924 file_extension_and_mimetype_map_[ext] = mime;
2925}
2926
2284inline void Server::set_file_request_handler(Handler handler) { 2927inline void Server::set_file_request_handler(Handler handler) {
2285 file_request_handler_ = handler; 2928 file_request_handler_ = std::move(handler);
2286} 2929}
2287 2930
2288inline void Server::set_error_handler(Handler handler) { 2931inline void Server::set_error_handler(Handler handler) {
2289 error_handler_ = handler; 2932 error_handler_ = std::move(handler);
2290} 2933}
2291 2934
2292inline void Server::set_logger(Logger logger) { logger_ = logger; } 2935inline void Server::set_logger(Logger logger) { logger_ = std::move(logger); }
2936
2937inline void
2938Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
2939 expect_100_continue_handler_ = std::move(handler);
2940}
2293 2941
2294inline void Server::set_keep_alive_max_count(size_t count) { 2942inline void Server::set_keep_alive_max_count(size_t count) {
2295 keep_alive_max_count_ = count; 2943 keep_alive_max_count_ = count;
2296} 2944}
2297 2945
2946inline void Server::set_read_timeout(time_t sec, time_t usec) {
2947 read_timeout_sec_ = sec;
2948 read_timeout_usec_ = usec;
2949}
2950
2298inline void Server::set_payload_max_length(size_t length) { 2951inline void Server::set_payload_max_length(size_t length) {
2299 payload_max_length_ = length; 2952 payload_max_length_ = length;
2300} 2953}
2301 2954
2955inline bool Server::bind_to_port(const char *host, int port, int socket_flags) {
2956 if (bind_internal(host, port, socket_flags) < 0) return false;
2957 return true;
2958}
2302inline int Server::bind_to_any_port(const char *host, int socket_flags) { 2959inline int Server::bind_to_any_port(const char *host, int socket_flags) {
2303 return bind_internal(host, 0, socket_flags); 2960 return bind_internal(host, 0, socket_flags);
2304} 2961}
@@ -2306,8 +2963,7 @@ inline int Server::bind_to_any_port(const char *host, int socket_flags) {
2306inline bool Server::listen_after_bind() { return listen_internal(); } 2963inline bool Server::listen_after_bind() { return listen_internal(); }
2307 2964
2308inline bool Server::listen(const char *host, int port, int socket_flags) { 2965inline bool Server::listen(const char *host, int port, int socket_flags) {
2309 if (bind_internal(host, port, socket_flags) < 0) return false; 2966 return bind_to_port(host, port, socket_flags) && listen_internal();
2310 return listen_internal();
2311} 2967}
2312 2968
2313inline bool Server::is_running() const { return is_running_; } 2969inline bool Server::is_running() const { return is_running_; }
@@ -2322,8 +2978,9 @@ inline void Server::stop() {
2322} 2978}
2323 2979
2324inline bool Server::parse_request_line(const char *s, Request &req) { 2980inline bool Server::parse_request_line(const char *s, Request &req) {
2325 static std::regex re("(GET|HEAD|POST|PUT|DELETE|CONNECT|OPTIONS|TRACE|PATCH|PRI) " 2981 const static std::regex re(
2326 "(([^?]+)(?:\\?(.+?))?) (HTTP/1\\.[01])\r\n"); 2982 "(GET|HEAD|POST|PUT|DELETE|CONNECT|OPTIONS|TRACE|PATCH|PRI) "
2983 "(([^?]+)(?:\\?(.*?))?) (HTTP/1\\.[01])\r\n");
2327 2984
2328 std::cmatch m; 2985 std::cmatch m;
2329 if (std::regex_match(s, m, re)) { 2986 if (std::regex_match(s, m, re)) {
@@ -2348,9 +3005,11 @@ inline bool Server::write_response(Stream &strm, bool last_connection,
2348 3005
2349 if (400 <= res.status && error_handler_) { error_handler_(req, res); } 3006 if (400 <= res.status && error_handler_) { error_handler_(req, res); }
2350 3007
3008 detail::BufferStream bstrm;
3009
2351 // Response line 3010 // Response line
2352 if (!strm.write_format("HTTP/1.1 %d %s\r\n", res.status, 3011 if (!bstrm.write_format("HTTP/1.1 %d %s\r\n", res.status,
2353 detail::status_message(res.status))) { 3012 detail::status_message(res.status))) {
2354 return false; 3013 return false;
2355 } 3014 }
2356 3015
@@ -2363,11 +3022,12 @@ inline bool Server::write_response(Stream &strm, bool last_connection,
2363 res.set_header("Connection", "Keep-Alive"); 3022 res.set_header("Connection", "Keep-Alive");
2364 } 3023 }
2365 3024
2366 if (!res.has_header("Content-Type")) { 3025 if (!res.has_header("Content-Type") &&
3026 (!res.body.empty() || res.content_length > 0)) {
2367 res.set_header("Content-Type", "text/plain"); 3027 res.set_header("Content-Type", "text/plain");
2368 } 3028 }
2369 3029
2370 if (!res.has_header("Accept-Ranges")) { 3030 if (!res.has_header("Accept-Ranges") && req.method == "HEAD") {
2371 res.set_header("Accept-Ranges", "bytes"); 3031 res.set_header("Accept-Ranges", "bytes");
2372 } 3032 }
2373 3033
@@ -2388,17 +3048,17 @@ inline bool Server::write_response(Stream &strm, bool last_connection,
2388 } 3048 }
2389 3049
2390 if (res.body.empty()) { 3050 if (res.body.empty()) {
2391 if (res.content_provider_resource_length > 0) { 3051 if (res.content_length > 0) {
2392 size_t length = 0; 3052 size_t length = 0;
2393 if (req.ranges.empty()) { 3053 if (req.ranges.empty()) {
2394 length = res.content_provider_resource_length; 3054 length = res.content_length;
2395 } else if (req.ranges.size() == 1) { 3055 } else if (req.ranges.size() == 1) {
2396 auto offsets = detail::get_range_offset_and_length( 3056 auto offsets =
2397 req, res.content_provider_resource_length, 0); 3057 detail::get_range_offset_and_length(req, res.content_length, 0);
2398 auto offset = offsets.first; 3058 auto offset = offsets.first;
2399 length = offsets.second; 3059 length = offsets.second;
2400 auto content_range = detail::make_content_range_header_field( 3060 auto content_range = detail::make_content_range_header_field(
2401 offset, length, res.content_provider_resource_length); 3061 offset, length, res.content_length);
2402 res.set_header("Content-Range", content_range); 3062 res.set_header("Content-Range", content_range);
2403 } else { 3063 } else {
2404 length = detail::get_multipart_ranges_data_length(req, res, boundary, 3064 length = detail::get_multipart_ranges_data_length(req, res, boundary,
@@ -2430,7 +3090,7 @@ inline bool Server::write_response(Stream &strm, bool last_connection,
2430 } 3090 }
2431 3091
2432#ifdef CPPHTTPLIB_ZLIB_SUPPORT 3092#ifdef CPPHTTPLIB_ZLIB_SUPPORT
2433 // TODO: 'Accpet-Encoding' has gzip, not gzip;q=0 3093 // TODO: 'Accept-Encoding' has gzip, not gzip;q=0
2434 const auto &encodings = req.get_header_value("Accept-Encoding"); 3094 const auto &encodings = req.get_header_value("Accept-Encoding");
2435 if (encodings.find("gzip") != std::string::npos && 3095 if (encodings.find("gzip") != std::string::npos &&
2436 detail::can_compress(res.get_header_value("Content-Type"))) { 3096 detail::can_compress(res.get_header_value("Content-Type"))) {
@@ -2444,7 +3104,11 @@ inline bool Server::write_response(Stream &strm, bool last_connection,
2444 res.set_header("Content-Length", length); 3104 res.set_header("Content-Length", length);
2445 } 3105 }
2446 3106
2447 if (!detail::write_headers(strm, res, Headers())) { return false; } 3107 if (!detail::write_headers(bstrm, res, Headers())) { return false; }
3108
3109 // Flush buffer
3110 auto &data = bstrm.get_buffer();
3111 strm.write(data.data(), data.size());
2448 3112
2449 // Body 3113 // Body
2450 if (req.method != "HEAD") { 3114 if (req.method != "HEAD") {
@@ -2468,15 +3132,15 @@ inline bool
2468Server::write_content_with_provider(Stream &strm, const Request &req, 3132Server::write_content_with_provider(Stream &strm, const Request &req,
2469 Response &res, const std::string &boundary, 3133 Response &res, const std::string &boundary,
2470 const std::string &content_type) { 3134 const std::string &content_type) {
2471 if (res.content_provider_resource_length) { 3135 if (res.content_length) {
2472 if (req.ranges.empty()) { 3136 if (req.ranges.empty()) {
2473 if (detail::write_content(strm, res.content_provider, 0, 3137 if (detail::write_content(strm, res.content_provider, 0,
2474 res.content_provider_resource_length) < 0) { 3138 res.content_length) < 0) {
2475 return false; 3139 return false;
2476 } 3140 }
2477 } else if (req.ranges.size() == 1) { 3141 } else if (req.ranges.size() == 1) {
2478 auto offsets = detail::get_range_offset_and_length( 3142 auto offsets =
2479 req, res.content_provider_resource_length, 0); 3143 detail::get_range_offset_and_length(req, res.content_length, 0);
2480 auto offset = offsets.first; 3144 auto offset = offsets.first;
2481 auto length = offsets.second; 3145 auto length = offsets.second;
2482 if (detail::write_content(strm, res.content_provider, offset, length) < 3146 if (detail::write_content(strm, res.content_provider, offset, length) <
@@ -2490,29 +3154,123 @@ Server::write_content_with_provider(Stream &strm, const Request &req,
2490 } 3154 }
2491 } 3155 }
2492 } else { 3156 } else {
2493 if (detail::write_content_chunked(strm, res.content_provider) < 0) { 3157 auto is_shutting_down = [this]() {
3158 return this->svr_sock_ == INVALID_SOCKET;
3159 };
3160 if (detail::write_content_chunked(strm, res.content_provider,
3161 is_shutting_down) < 0) {
2494 return false; 3162 return false;
2495 } 3163 }
2496 } 3164 }
2497 return true; 3165 return true;
2498} 3166}
2499 3167
2500inline bool Server::handle_file_request(Request &req, Response &res) { 3168inline bool Server::read_content(Stream &strm, bool last_connection,
2501 if (!base_dir_.empty() && detail::is_valid_path(req.path)) { 3169 Request &req, Response &res) {
2502 std::string path = base_dir_ + req.path; 3170 MultipartFormDataMap::iterator cur;
3171 auto ret = read_content_core(
3172 strm, last_connection, req, res,
3173 // Regular
3174 [&](const char *buf, size_t n) {
3175 if (req.body.size() + n > req.body.max_size()) { return false; }
3176 req.body.append(buf, n);
3177 return true;
3178 },
3179 // Multipart
3180 [&](const MultipartFormData &file) {
3181 cur = req.files.emplace(file.name, file);
3182 return true;
3183 },
3184 [&](const char *buf, size_t n) {
3185 auto &content = cur->second.content;
3186 if (content.size() + n > content.max_size()) { return false; }
3187 content.append(buf, n);
3188 return true;
3189 });
2503 3190
2504 if (!path.empty() && path.back() == '/') { path += "index.html"; } 3191 const auto &content_type = req.get_header_value("Content-Type");
3192 if (!content_type.find("application/x-www-form-urlencoded")) {
3193 detail::parse_query_text(req.body, req.params);
3194 }
2505 3195
2506 if (detail::is_file(path)) { 3196 return ret;
2507 detail::read_file(path, res.body); 3197}
2508 auto type = detail::find_content_type(path); 3198
2509 if (type) { res.set_header("Content-Type", type); } 3199inline bool Server::read_content_with_content_receiver(
2510 res.status = 200; 3200 Stream &strm, bool last_connection, Request &req, Response &res,
2511 if (file_request_handler_) { file_request_handler_(req, res); } 3201 ContentReceiver receiver, MultipartContentHeader multipart_header,
2512 return true; 3202 ContentReceiver multipart_receiver) {
3203 return read_content_core(strm, last_connection, req, res, receiver,
3204 multipart_header, multipart_receiver);
3205}
3206
3207inline bool Server::read_content_core(Stream &strm, bool last_connection,
3208 Request &req, Response &res,
3209 ContentReceiver receiver,
3210 MultipartContentHeader mulitpart_header,
3211 ContentReceiver multipart_receiver) {
3212 detail::MultipartFormDataParser multipart_form_data_parser;
3213 ContentReceiver out;
3214
3215 if (req.is_multipart_form_data()) {
3216 const auto &content_type = req.get_header_value("Content-Type");
3217 std::string boundary;
3218 if (!detail::parse_multipart_boundary(content_type, boundary)) {
3219 res.status = 400;
3220 return write_response(strm, last_connection, req, res);
2513 } 3221 }
3222
3223 multipart_form_data_parser.set_boundary(boundary);
3224 out = [&](const char *buf, size_t n) {
3225 return multipart_form_data_parser.parse(buf, n, multipart_receiver,
3226 mulitpart_header);
3227 };
3228 } else {
3229 out = receiver;
3230 }
3231
3232 if (!detail::read_content(strm, req, payload_max_length_, res.status,
3233 Progress(), out)) {
3234 return write_response(strm, last_connection, req, res);
2514 } 3235 }
2515 3236
3237 if (req.is_multipart_form_data()) {
3238 if (!multipart_form_data_parser.is_valid()) {
3239 res.status = 400;
3240 return write_response(strm, last_connection, req, res);
3241 }
3242 }
3243
3244 return true;
3245}
3246
3247inline bool Server::handle_file_request(Request &req, Response &res,
3248 bool head) {
3249 for (const auto &kv : base_dirs_) {
3250 const auto &mount_point = kv.first;
3251 const auto &base_dir = kv.second;
3252
3253 // Prefix match
3254 if (!req.path.find(mount_point)) {
3255 std::string sub_path = "/" + req.path.substr(mount_point.size());
3256 if (detail::is_valid_path(sub_path)) {
3257 auto path = base_dir + sub_path;
3258 if (path.back() == '/') { path += "index.html"; }
3259
3260 if (detail::is_file(path)) {
3261 detail::read_file(path, res.body);
3262 auto type =
3263 detail::find_content_type(path, file_extension_and_mimetype_map_);
3264 if (type) { res.set_header("Content-Type", type); }
3265 res.status = 200;
3266 if (!head && file_request_handler_) {
3267 file_request_handler_(req, res);
3268 }
3269 return true;
3270 }
3271 }
3272 }
3273 }
2516 return false; 3274 return false;
2517} 3275}
2518 3276
@@ -2605,9 +3363,51 @@ inline bool Server::listen_internal() {
2605 return ret; 3363 return ret;
2606} 3364}
2607 3365
2608inline bool Server::routing(Request &req, Response &res) { 3366inline bool Server::routing(Request &req, Response &res, Stream &strm,
2609 if (req.method == "GET" && handle_file_request(req, res)) { return true; } 3367 bool last_connection) {
3368 // File handler
3369 bool is_head_request = req.method == "HEAD";
3370 if ((req.method == "GET" || is_head_request) &&
3371 handle_file_request(req, res, is_head_request)) {
3372 return true;
3373 }
3374
3375 if (detail::expect_content(req)) {
3376 // Content reader handler
3377 {
3378 ContentReader reader(
3379 [&](ContentReceiver receiver) {
3380 return read_content_with_content_receiver(
3381 strm, last_connection, req, res, receiver, nullptr, nullptr);
3382 },
3383 [&](MultipartContentHeader header, ContentReceiver receiver) {
3384 return read_content_with_content_receiver(
3385 strm, last_connection, req, res, nullptr, header, receiver);
3386 });
3387
3388 if (req.method == "POST") {
3389 if (dispatch_request_for_content_reader(
3390 req, res, reader, post_handlers_for_content_reader_)) {
3391 return true;
3392 }
3393 } else if (req.method == "PUT") {
3394 if (dispatch_request_for_content_reader(
3395 req, res, reader, put_handlers_for_content_reader_)) {
3396 return true;
3397 }
3398 } else if (req.method == "PATCH") {
3399 if (dispatch_request_for_content_reader(
3400 req, res, reader, patch_handlers_for_content_reader_)) {
3401 return true;
3402 }
3403 }
3404 }
2610 3405
3406 // Read content into `req.body`
3407 if (!read_content(strm, last_connection, req, res)) { return false; }
3408 }
3409
3410 // Regular handler
2611 if (req.method == "GET" || req.method == "HEAD") { 3411 if (req.method == "GET" || req.method == "HEAD") {
2612 return dispatch_request(req, res, get_handlers_); 3412 return dispatch_request(req, res, get_handlers_);
2613 } else if (req.method == "POST") { 3413 } else if (req.method == "POST") {
@@ -2640,17 +3440,31 @@ inline bool Server::dispatch_request(Request &req, Response &res,
2640 return false; 3440 return false;
2641} 3441}
2642 3442
3443inline bool Server::dispatch_request_for_content_reader(
3444 Request &req, Response &res, ContentReader content_reader,
3445 HandlersForContentReader &handlers) {
3446 for (const auto &x : handlers) {
3447 const auto &pattern = x.first;
3448 const auto &handler = x.second;
3449
3450 if (std::regex_match(req.path, req.matches, pattern)) {
3451 handler(req, res, content_reader);
3452 return true;
3453 }
3454 }
3455 return false;
3456}
3457
2643inline bool 3458inline bool
2644Server::process_request(Stream &strm, bool last_connection, 3459Server::process_request(Stream &strm, bool last_connection,
2645 bool &connection_close, 3460 bool &connection_close,
2646 std::function<void(Request &)> setup_request) { 3461 const std::function<void(Request &)> &setup_request) {
2647 const auto bufsiz = 2048; 3462 std::array<char, 2048> buf{};
2648 char buf[bufsiz];
2649 3463
2650 detail::stream_line_reader reader(strm, buf, bufsiz); 3464 detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
2651 3465
2652 // Connection has been closed on client 3466 // Connection has been closed on client
2653 if (!reader.getline()) { return false; } 3467 if (!line_reader.getline()) { return false; }
2654 3468
2655 Request req; 3469 Request req;
2656 Response res; 3470 Response res;
@@ -2658,7 +3472,7 @@ Server::process_request(Stream &strm, bool last_connection,
2658 res.version = "HTTP/1.1"; 3472 res.version = "HTTP/1.1";
2659 3473
2660 // Check if the request URI doesn't exceed the limit 3474 // Check if the request URI doesn't exceed the limit
2661 if (reader.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) { 3475 if (line_reader.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
2662 Headers dummy; 3476 Headers dummy;
2663 detail::read_headers(strm, dummy); 3477 detail::read_headers(strm, dummy);
2664 res.status = 414; 3478 res.status = 414;
@@ -2666,7 +3480,7 @@ Server::process_request(Stream &strm, bool last_connection,
2666 } 3480 }
2667 3481
2668 // Request line and headers 3482 // Request line and headers
2669 if (!parse_request_line(reader.ptr(), req) || 3483 if (!parse_request_line(line_reader.ptr(), req) ||
2670 !detail::read_headers(strm, req.headers)) { 3484 !detail::read_headers(strm, req.headers)) {
2671 res.status = 400; 3485 res.status = 400;
2672 return write_response(strm, last_connection, req, res); 3486 return write_response(strm, last_connection, req, res);
@@ -2683,33 +3497,6 @@ Server::process_request(Stream &strm, bool last_connection,
2683 3497
2684 req.set_header("REMOTE_ADDR", strm.get_remote_addr()); 3498 req.set_header("REMOTE_ADDR", strm.get_remote_addr());
2685 3499
2686 // Body
2687 if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" || req.method == "PRI") {
2688 if (!detail::read_content(strm, req, payload_max_length_, res.status,
2689 Progress(), [&](const char *buf, size_t n) {
2690 if (req.body.size() + n > req.body.max_size()) {
2691 return false;
2692 }
2693 req.body.append(buf, n);
2694 return true;
2695 })) {
2696 return write_response(strm, last_connection, req, res);
2697 }
2698
2699 const auto &content_type = req.get_header_value("Content-Type");
2700
2701 if (!content_type.find("application/x-www-form-urlencoded")) {
2702 detail::parse_query_text(req.body, req.params);
2703 } else if (!content_type.find("multipart/form-data")) {
2704 std::string boundary;
2705 if (!detail::parse_multipart_boundary(content_type, boundary) ||
2706 !detail::parse_multipart_formdata(boundary, req.body, req.files)) {
2707 res.status = 400;
2708 return write_response(strm, last_connection, req, res);
2709 }
2710 }
2711 }
2712
2713 if (req.has_header("Range")) { 3500 if (req.has_header("Range")) {
2714 const auto &range_header_value = req.get_header_value("Range"); 3501 const auto &range_header_value = req.get_header_value("Range");
2715 if (!detail::parse_range_header(range_header_value, req.ranges)) { 3502 if (!detail::parse_range_header(range_header_value, req.ranges)) {
@@ -2719,7 +3506,23 @@ Server::process_request(Stream &strm, bool last_connection,
2719 3506
2720 if (setup_request) { setup_request(req); } 3507 if (setup_request) { setup_request(req); }
2721 3508
2722 if (routing(req, res)) { 3509 if (req.get_header_value("Expect") == "100-continue") {
3510 auto status = 100;
3511 if (expect_100_continue_handler_) {
3512 status = expect_100_continue_handler_(req, res);
3513 }
3514 switch (status) {
3515 case 100:
3516 case 417:
3517 strm.write_format("HTTP/1.1 %d %s\r\n\r\n", status,
3518 detail::status_message(status));
3519 break;
3520 default: return write_response(strm, last_connection, req, res);
3521 }
3522 }
3523
3524 // Rounting
3525 if (routing(req, res, strm, last_connection)) {
2723 if (res.status == -1) { res.status = req.ranges.empty() ? 200 : 206; } 3526 if (res.status == -1) { res.status = req.ranges.empty() ? 200 : 206; }
2724 } else { 3527 } else {
2725 if (res.status == -1) { res.status = 404; } 3528 if (res.status == -1) { res.status = 404; }
@@ -2732,7 +3535,7 @@ inline bool Server::is_valid() const { return true; }
2732 3535
2733inline bool Server::process_and_close_socket(socket_t sock) { 3536inline bool Server::process_and_close_socket(socket_t sock) {
2734 return detail::process_and_close_socket( 3537 return detail::process_and_close_socket(
2735 false, sock, keep_alive_max_count_, 3538 false, sock, keep_alive_max_count_, read_timeout_sec_, read_timeout_usec_,
2736 [this](Stream &strm, bool last_connection, bool &connection_close) { 3539 [this](Stream &strm, bool last_connection, bool &connection_close) {
2737 return process_request(strm, last_connection, connection_close, 3540 return process_request(strm, last_connection, connection_close,
2738 nullptr); 3541 nullptr);
@@ -2740,47 +3543,37 @@ inline bool Server::process_and_close_socket(socket_t sock) {
2740} 3543}
2741 3544
2742// HTTP client implementation 3545// HTTP client implementation
2743inline Client::Client(const char *host, int port, time_t timeout_sec) 3546inline Client::Client(const std::string &host, int port,
2744 : host_(host), port_(port), timeout_sec_(timeout_sec), 3547 const std::string &client_cert_path,
3548 const std::string &client_key_path)
3549 : host_(host), port_(port),
2745 host_and_port_(host_ + ":" + std::to_string(port_)), 3550 host_and_port_(host_ + ":" + std::to_string(port_)),
2746 keep_alive_max_count_(CPPHTTPLIB_KEEPALIVE_MAX_COUNT), 3551 client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
2747 follow_location_(false) {}
2748 3552
2749inline Client::~Client() {} 3553inline Client::~Client() {}
2750 3554
2751inline bool Client::is_valid() const { return true; } 3555inline bool Client::is_valid() const { return true; }
2752 3556
2753inline socket_t Client::create_client_socket() const { 3557inline socket_t Client::create_client_socket() const {
2754 return detail::create_socket( 3558 if (!proxy_host_.empty()) {
2755 host_.c_str(), port_, [=](socket_t sock, struct addrinfo &ai) -> bool { 3559 return detail::create_client_socket(proxy_host_.c_str(), proxy_port_,
2756 detail::set_nonblocking(sock, true); 3560 timeout_sec_, interface_);
2757 3561 }
2758 auto ret = connect(sock, ai.ai_addr, static_cast<int>(ai.ai_addrlen)); 3562 return detail::create_client_socket(host_.c_str(), port_, timeout_sec_,
2759 if (ret < 0) { 3563 interface_);
2760 if (detail::is_connection_error() ||
2761 !detail::wait_until_socket_is_ready(sock, timeout_sec_, 0)) {
2762 detail::close_socket(sock);
2763 return false;
2764 }
2765 }
2766
2767 detail::set_nonblocking(sock, false);
2768 return true;
2769 });
2770} 3564}
2771 3565
2772inline bool Client::read_response_line(Stream &strm, Response &res) { 3566inline bool Client::read_response_line(Stream &strm, Response &res) {
2773 const auto bufsiz = 2048; 3567 std::array<char, 2048> buf;
2774 char buf[bufsiz];
2775 3568
2776 detail::stream_line_reader reader(strm, buf, bufsiz); 3569 detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
2777 3570
2778 if (!reader.getline()) { return false; } 3571 if (!line_reader.getline()) { return false; }
2779 3572
2780 const static std::regex re("(HTTP/1\\.[01]) (\\d+?) .*\r\n"); 3573 const static std::regex re("(HTTP/1\\.[01]) (\\d+?) .*\r\n");
2781 3574
2782 std::cmatch m; 3575 std::cmatch m;
2783 if (std::regex_match(reader.ptr(), m, re)) { 3576 if (std::regex_match(line_reader.ptr(), m, re)) {
2784 res.version = std::string(m[1]); 3577 res.version = std::string(m[1]);
2785 res.status = std::stoi(std::string(m[2])); 3578 res.status = std::stoi(std::string(m[2]));
2786 } 3579 }
@@ -2789,22 +3582,21 @@ inline bool Client::read_response_line(Stream &strm, Response &res) {
2789} 3582}
2790 3583
2791inline bool Client::send(const Request &req, Response &res) { 3584inline bool Client::send(const Request &req, Response &res) {
2792 if (req.path.empty()) { return false; }
2793
2794 auto sock = create_client_socket(); 3585 auto sock = create_client_socket();
2795 if (sock == INVALID_SOCKET) { return false; } 3586 if (sock == INVALID_SOCKET) { return false; }
2796 3587
2797 auto ret = process_and_close_socket( 3588#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
2798 sock, 1, [&](Stream &strm, bool last_connection, bool &connection_close) { 3589 if (is_ssl() && !proxy_host_.empty()) {
2799 return process_request(strm, req, res, last_connection, 3590 bool error;
2800 connection_close); 3591 if (!connect(sock, res, error)) { return error; }
2801 });
2802
2803 if (ret && follow_location_ && (300 < res.status && res.status < 400)) {
2804 ret = redirect(req, res);
2805 } 3592 }
3593#endif
2806 3594
2807 return ret; 3595 return process_and_close_socket(
3596 sock, 1, [&](Stream &strm, bool last_connection, bool &connection_close) {
3597 return handle_request(strm, req, res, last_connection,
3598 connection_close);
3599 });
2808} 3600}
2809 3601
2810inline bool Client::send(const std::vector<Request> &requests, 3602inline bool Client::send(const std::vector<Request> &requests,
@@ -2814,32 +3606,136 @@ inline bool Client::send(const std::vector<Request> &requests,
2814 auto sock = create_client_socket(); 3606 auto sock = create_client_socket();
2815 if (sock == INVALID_SOCKET) { return false; } 3607 if (sock == INVALID_SOCKET) { return false; }
2816 3608
2817 if (!process_and_close_socket( 3609#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
2818 sock, requests.size() - i, 3610 if (is_ssl() && !proxy_host_.empty()) {
2819 [&](Stream &strm, bool last_connection, bool &connection_close) -> bool { 3611 Response res;
2820 auto &req = requests[i]; 3612 bool error;
2821 auto res = Response(); 3613 if (!connect(sock, res, error)) { return false; }
2822 i++; 3614 }
3615#endif
3616
3617 if (!process_and_close_socket(sock, requests.size() - i,
3618 [&](Stream &strm, bool last_connection,
3619 bool &connection_close) -> bool {
3620 auto &req = requests[i++];
3621 auto res = Response();
3622 auto ret = handle_request(strm, req, res,
3623 last_connection,
3624 connection_close);
3625 if (ret) {
3626 responses.emplace_back(std::move(res));
3627 }
3628 return ret;
3629 })) {
3630 return false;
3631 }
3632 }
2823 3633
2824 if (req.path.empty()) { return false; } 3634 return true;
2825 auto ret = process_request(strm, req, res, last_connection, 3635}
2826 connection_close); 3636
3637inline bool Client::handle_request(Stream &strm, const Request &req,
3638 Response &res, bool last_connection,
3639 bool &connection_close) {
3640 if (req.path.empty()) { return false; }
3641
3642 bool ret;
3643
3644 if (!is_ssl() && !proxy_host_.empty()) {
3645 auto req2 = req;
3646 req2.path = "http://" + host_and_port_ + req.path;
3647 ret = process_request(strm, req2, res, last_connection, connection_close);
3648 } else {
3649 ret = process_request(strm, req, res, last_connection, connection_close);
3650 }
3651
3652 if (!ret) { return false; }
3653
3654 if (300 < res.status && res.status < 400 && follow_location_) {
3655 ret = redirect(req, res);
3656 }
2827 3657
2828 if (ret && follow_location_ && 3658#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
2829 (300 < res.status && res.status < 400)) { 3659 if (res.status == 401 || res.status == 407) {
2830 ret = redirect(req, res); 3660 auto is_proxy = res.status == 407;
2831 } 3661 const auto &username =
3662 is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
3663 const auto &password =
3664 is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
3665
3666 if (!username.empty() && !password.empty()) {
3667 std::map<std::string, std::string> auth;
3668 if (parse_www_authenticate(res, auth, is_proxy)) {
3669 Request new_req = req;
3670 auto key = is_proxy ? "Proxy-Authorization" : "WWW-Authorization";
3671 new_req.headers.erase(key);
3672 new_req.headers.insert(make_digest_authentication_header(
3673 req, auth, 1, random_string(10), username, password, is_proxy));
3674
3675 Response new_res;
3676
3677 ret = send(new_req, new_res);
3678 if (ret) { res = new_res; }
3679 }
3680 }
3681 }
3682#endif
3683
3684 return ret;
3685}
2832 3686
2833 if (ret) { responses.emplace_back(std::move(res)); } 3687#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
3688inline bool Client::connect(socket_t sock, Response &res, bool &error) {
3689 error = true;
3690 Response res2;
3691
3692 if (!detail::process_socket(
3693 true, sock, 1, read_timeout_sec_, read_timeout_usec_,
3694 [&](Stream &strm, bool /*last_connection*/, bool &connection_close) {
3695 Request req2;
3696 req2.method = "CONNECT";
3697 req2.path = host_and_port_;
3698 return process_request(strm, req2, res2, false, connection_close);
3699 })) {
3700 detail::close_socket(sock);
3701 error = false;
3702 return false;
3703 }
2834 3704
2835 return ret; 3705 if (res2.status == 407) {
2836 })) { 3706 if (!proxy_digest_auth_username_.empty() &&
3707 !proxy_digest_auth_password_.empty()) {
3708 std::map<std::string, std::string> auth;
3709 if (parse_www_authenticate(res2, auth, true)) {
3710 Response res3;
3711 if (!detail::process_socket(
3712 true, sock, 1, read_timeout_sec_, read_timeout_usec_,
3713 [&](Stream &strm, bool /*last_connection*/,
3714 bool &connection_close) {
3715 Request req3;
3716 req3.method = "CONNECT";
3717 req3.path = host_and_port_;
3718 req3.headers.insert(make_digest_authentication_header(
3719 req3, auth, 1, random_string(10),
3720 proxy_digest_auth_username_, proxy_digest_auth_password_,
3721 true));
3722 return process_request(strm, req3, res3, false,
3723 connection_close);
3724 })) {
3725 detail::close_socket(sock);
3726 error = false;
3727 return false;
3728 }
3729 }
3730 } else {
3731 res = res2;
2837 return false; 3732 return false;
2838 } 3733 }
2839 } 3734 }
2840 3735
2841 return true; 3736 return true;
2842} 3737}
3738#endif
2843 3739
2844inline bool Client::redirect(const Request &req, Response &res) { 3740inline bool Client::redirect(const Request &req, Response &res) {
2845 if (req.redirect_count == 0) { return false; } 3741 if (req.redirect_count == 0) { return false; }
@@ -2847,46 +3743,47 @@ inline bool Client::redirect(const Request &req, Response &res) {
2847 auto location = res.get_header_value("location"); 3743 auto location = res.get_header_value("location");
2848 if (location.empty()) { return false; } 3744 if (location.empty()) { return false; }
2849 3745
2850 std::regex re( 3746 const static std::regex re(
2851 R"(^(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*(?:\?[^#]*)?)(?:#.*)?)"); 3747 R"(^(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*(?:\?[^#]*)?)(?:#.*)?)");
2852 3748
3749 std::smatch m;
3750 if (!regex_match(location, m, re)) { return false; }
3751
2853 auto scheme = is_ssl() ? "https" : "http"; 3752 auto scheme = is_ssl() ? "https" : "http";
2854 3753
2855 std::smatch m; 3754 auto next_scheme = m[1].str();
2856 if (regex_match(location, m, re)) { 3755 auto next_host = m[2].str();
2857 auto next_scheme = m[1].str(); 3756 auto next_path = m[3].str();
2858 auto next_host = m[2].str(); 3757 if (next_scheme.empty()) { next_scheme = scheme; }
2859 auto next_path = m[3].str(); 3758 if (next_scheme.empty()) { next_scheme = scheme; }
2860 if (next_host.empty()) { next_host = host_; } 3759 if (next_host.empty()) { next_host = host_; }
2861 if (next_path.empty()) { next_path = "/"; } 3760 if (next_path.empty()) { next_path = "/"; }
2862 3761
2863 if (next_scheme == scheme && next_host == host_) { 3762 if (next_scheme == scheme && next_host == host_) {
2864 return detail::redirect(*this, req, res, next_path); 3763 return detail::redirect(*this, req, res, next_path);
2865 } else { 3764 } else {
2866 if (next_scheme == "https") { 3765 if (next_scheme == "https") {
2867#ifdef CPPHTTPLIB_OPENSSL_SUPPORT 3766#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
2868 SSLClient cli(next_host.c_str()); 3767 SSLClient cli(next_host.c_str());
2869 cli.follow_location(true); 3768 cli.copy_settings(*this);
2870 return detail::redirect(cli, req, res, next_path); 3769 return detail::redirect(cli, req, res, next_path);
2871#else 3770#else
2872 return false; 3771 return false;
2873#endif 3772#endif
2874 } else { 3773 } else {
2875 Client cli(next_host.c_str()); 3774 Client cli(next_host.c_str());
2876 cli.follow_location(true); 3775 cli.copy_settings(*this);
2877 return detail::redirect(cli, req, res, next_path); 3776 return detail::redirect(cli, req, res, next_path);
2878 }
2879 } 3777 }
2880 } 3778 }
2881 return false;
2882} 3779}
2883 3780
2884inline void Client::write_request(Stream &strm, const Request &req, 3781inline bool Client::write_request(Stream &strm, const Request &req,
2885 bool last_connection) { 3782 bool last_connection) {
2886 BufferStream bstrm; 3783 detail::BufferStream bstrm;
2887 3784
2888 // Request line 3785 // Request line
2889 auto path = detail::encode_url(req.path); 3786 const auto &path = detail::encode_url(req.path);
2890 3787
2891 bstrm.write_format("%s %s HTTP/1.1\r\n", req.method.c_str(), path.c_str()); 3788 bstrm.write_format("%s %s HTTP/1.1\r\n", req.method.c_str(), path.c_str());
2892 3789
@@ -2913,11 +3810,14 @@ inline void Client::write_request(Stream &strm, const Request &req,
2913 if (!req.has_header("Accept")) { headers.emplace("Accept", "*/*"); } 3810 if (!req.has_header("Accept")) { headers.emplace("Accept", "*/*"); }
2914 3811
2915 if (!req.has_header("User-Agent")) { 3812 if (!req.has_header("User-Agent")) {
2916 headers.emplace("User-Agent", "cpp-httplib/0.2"); 3813 headers.emplace("User-Agent", "cpp-httplib/0.5");
2917 } 3814 }
2918 3815
2919 if (req.body.empty()) { 3816 if (req.body.empty()) {
2920 if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH") { 3817 if (req.content_provider) {
3818 auto length = std::to_string(req.content_length);
3819 headers.emplace("Content-Length", length);
3820 } else {
2921 headers.emplace("Content-Length", "0"); 3821 headers.emplace("Content-Length", "0");
2922 } 3822 }
2923 } else { 3823 } else {
@@ -2931,21 +3831,100 @@ inline void Client::write_request(Stream &strm, const Request &req,
2931 } 3831 }
2932 } 3832 }
2933 3833
2934 detail::write_headers(bstrm, req, headers); 3834 if (!basic_auth_username_.empty() && !basic_auth_password_.empty()) {
3835 headers.insert(make_basic_authentication_header(
3836 basic_auth_username_, basic_auth_password_, false));
3837 }
2935 3838
2936 // Body 3839 if (!proxy_basic_auth_username_.empty() &&
2937 if (!req.body.empty()) { bstrm.write(req.body); } 3840 !proxy_basic_auth_password_.empty()) {
3841 headers.insert(make_basic_authentication_header(
3842 proxy_basic_auth_username_, proxy_basic_auth_password_, true));
3843 }
3844
3845 detail::write_headers(bstrm, req, headers);
2938 3846
2939 // Flush buffer 3847 // Flush buffer
2940 auto &data = bstrm.get_buffer(); 3848 auto &data = bstrm.get_buffer();
2941 strm.write(data.data(), data.size()); 3849 strm.write(data.data(), data.size());
3850
3851 // Body
3852 if (req.body.empty()) {
3853 if (req.content_provider) {
3854 size_t offset = 0;
3855 size_t end_offset = req.content_length;
3856
3857 DataSink data_sink;
3858 data_sink.write = [&](const char *d, size_t l) {
3859 auto written_length = strm.write(d, l);
3860 offset += written_length;
3861 };
3862 data_sink.is_writable = [&](void) { return strm.is_writable(); };
3863
3864 while (offset < end_offset) {
3865 req.content_provider(offset, end_offset - offset, data_sink);
3866 }
3867 }
3868 } else {
3869 strm.write(req.body);
3870 }
3871
3872 return true;
3873}
3874
3875inline std::shared_ptr<Response> Client::send_with_content_provider(
3876 const char *method, const char *path, const Headers &headers,
3877 const std::string &body, size_t content_length,
3878 ContentProvider content_provider, const char *content_type) {
3879 Request req;
3880 req.method = method;
3881 req.headers = headers;
3882 req.path = path;
3883
3884 req.headers.emplace("Content-Type", content_type);
3885
3886#ifdef CPPHTTPLIB_ZLIB_SUPPORT
3887 if (compress_) {
3888 if (content_provider) {
3889 size_t offset = 0;
3890
3891 DataSink data_sink;
3892 data_sink.write = [&](const char *data, size_t data_len) {
3893 req.body.append(data, data_len);
3894 offset += data_len;
3895 };
3896 data_sink.is_writable = [&](void) { return true; };
3897
3898 while (offset < content_length) {
3899 content_provider(offset, content_length - offset, data_sink);
3900 }
3901 } else {
3902 req.body = body;
3903 }
3904
3905 if (!detail::compress(req.body)) { return nullptr; }
3906 req.headers.emplace("Content-Encoding", "gzip");
3907 } else
3908#endif
3909 {
3910 if (content_provider) {
3911 req.content_length = content_length;
3912 req.content_provider = content_provider;
3913 } else {
3914 req.body = body;
3915 }
3916 }
3917
3918 auto res = std::make_shared<Response>();
3919
3920 return send(req, *res) ? res : nullptr;
2942} 3921}
2943 3922
2944inline bool Client::process_request(Stream &strm, const Request &req, 3923inline bool Client::process_request(Stream &strm, const Request &req,
2945 Response &res, bool last_connection, 3924 Response &res, bool last_connection,
2946 bool &connection_close) { 3925 bool &connection_close) {
2947 // Send request 3926 // Send request
2948 write_request(strm, req, last_connection); 3927 if (!write_request(strm, req, last_connection)) { return false; }
2949 3928
2950 // Receive response and headers 3929 // Receive response and headers
2951 if (!read_response_line(strm, res) || 3930 if (!read_response_line(strm, res) ||
@@ -2963,21 +3942,16 @@ inline bool Client::process_request(Stream &strm, const Request &req,
2963 } 3942 }
2964 3943
2965 // Body 3944 // Body
2966 if (req.method != "HEAD") { 3945 if (req.method != "HEAD" && req.method != "CONNECT") {
2967 detail::ContentReceiverCore out = [&](const char *buf, size_t n) { 3946 ContentReceiver out = [&](const char *buf, size_t n) {
2968 if (res.body.size() + n > res.body.max_size()) { return false; } 3947 if (res.body.size() + n > res.body.max_size()) { return false; }
2969 res.body.append(buf, n); 3948 res.body.append(buf, n);
2970 return true; 3949 return true;
2971 }; 3950 };
2972 3951
2973 if (req.content_receiver) { 3952 if (req.content_receiver) {
2974 auto offset = std::make_shared<size_t>(); 3953 out = [&](const char *buf, size_t n) {
2975 auto length = get_header_value_uint64(res.headers, "Content-Length", 0); 3954 return req.content_receiver(buf, n);
2976 auto receiver = req.content_receiver;
2977 out = [offset, length, receiver](const char *buf, size_t n) {
2978 auto ret = receiver(buf, n, *offset, length);
2979 (*offset) += n;
2980 return ret;
2981 }; 3955 };
2982 } 3956 }
2983 3957
@@ -2988,6 +3962,9 @@ inline bool Client::process_request(Stream &strm, const Request &req,
2988 } 3962 }
2989 } 3963 }
2990 3964
3965 // Log
3966 if (logger_) { logger_(req, res); }
3967
2991 return true; 3968 return true;
2992} 3969}
2993 3970
@@ -2997,25 +3974,25 @@ inline bool Client::process_and_close_socket(
2997 bool &connection_close)> 3974 bool &connection_close)>
2998 callback) { 3975 callback) {
2999 request_count = std::min(request_count, keep_alive_max_count_); 3976 request_count = std::min(request_count, keep_alive_max_count_);
3000 return detail::process_and_close_socket(true, sock, request_count, callback); 3977 return detail::process_and_close_socket(true, sock, request_count,
3978 read_timeout_sec_, read_timeout_usec_,
3979 callback);
3001} 3980}
3002 3981
3003inline bool Client::is_ssl() const { return false; } 3982inline bool Client::is_ssl() const { return false; }
3004 3983
3005inline std::shared_ptr<Response> Client::Get(const char *path) { 3984inline std::shared_ptr<Response> Client::Get(const char *path) {
3006 Progress dummy; 3985 return Get(path, Headers(), Progress());
3007 return Get(path, Headers(), dummy);
3008} 3986}
3009 3987
3010inline std::shared_ptr<Response> Client::Get(const char *path, 3988inline std::shared_ptr<Response> Client::Get(const char *path,
3011 Progress progress) { 3989 Progress progress) {
3012 return Get(path, Headers(), progress); 3990 return Get(path, Headers(), std::move(progress));
3013} 3991}
3014 3992
3015inline std::shared_ptr<Response> Client::Get(const char *path, 3993inline std::shared_ptr<Response> Client::Get(const char *path,
3016 const Headers &headers) { 3994 const Headers &headers) {
3017 Progress dummy; 3995 return Get(path, headers, Progress());
3018 return Get(path, headers, dummy);
3019} 3996}
3020 3997
3021inline std::shared_ptr<Response> 3998inline std::shared_ptr<Response>
@@ -3024,7 +4001,7 @@ Client::Get(const char *path, const Headers &headers, Progress progress) {
3024 req.method = "GET"; 4001 req.method = "GET";
3025 req.path = path; 4002 req.path = path;
3026 req.headers = headers; 4003 req.headers = headers;
3027 req.progress = progress; 4004 req.progress = std::move(progress);
3028 4005
3029 auto res = std::make_shared<Response>(); 4006 auto res = std::make_shared<Response>();
3030 return send(req, *res) ? res : nullptr; 4007 return send(req, *res) ? res : nullptr;
@@ -3032,36 +4009,36 @@ Client::Get(const char *path, const Headers &headers, Progress progress) {
3032 4009
3033inline std::shared_ptr<Response> Client::Get(const char *path, 4010inline std::shared_ptr<Response> Client::Get(const char *path,
3034 ContentReceiver content_receiver) { 4011 ContentReceiver content_receiver) {
3035 Progress dummy; 4012 return Get(path, Headers(), nullptr, std::move(content_receiver), Progress());
3036 return Get(path, Headers(), nullptr, content_receiver, dummy);
3037} 4013}
3038 4014
3039inline std::shared_ptr<Response> Client::Get(const char *path, 4015inline std::shared_ptr<Response> Client::Get(const char *path,
3040 ContentReceiver content_receiver, 4016 ContentReceiver content_receiver,
3041 Progress progress) { 4017 Progress progress) {
3042 return Get(path, Headers(), nullptr, content_receiver, progress); 4018 return Get(path, Headers(), nullptr, std::move(content_receiver),
4019 std::move(progress));
3043} 4020}
3044 4021
3045inline std::shared_ptr<Response> Client::Get(const char *path, 4022inline std::shared_ptr<Response> Client::Get(const char *path,
3046 const Headers &headers, 4023 const Headers &headers,
3047 ContentReceiver content_receiver) { 4024 ContentReceiver content_receiver) {
3048 Progress dummy; 4025 return Get(path, headers, nullptr, std::move(content_receiver), Progress());
3049 return Get(path, headers, nullptr, content_receiver, dummy);
3050} 4026}
3051 4027
3052inline std::shared_ptr<Response> Client::Get(const char *path, 4028inline std::shared_ptr<Response> Client::Get(const char *path,
3053 const Headers &headers, 4029 const Headers &headers,
3054 ContentReceiver content_receiver, 4030 ContentReceiver content_receiver,
3055 Progress progress) { 4031 Progress progress) {
3056 return Get(path, headers, nullptr, content_receiver, progress); 4032 return Get(path, headers, nullptr, std::move(content_receiver),
4033 std::move(progress));
3057} 4034}
3058 4035
3059inline std::shared_ptr<Response> Client::Get(const char *path, 4036inline std::shared_ptr<Response> Client::Get(const char *path,
3060 const Headers &headers, 4037 const Headers &headers,
3061 ResponseHandler response_handler, 4038 ResponseHandler response_handler,
3062 ContentReceiver content_receiver) { 4039 ContentReceiver content_receiver) {
3063 Progress dummy; 4040 return Get(path, headers, std::move(response_handler), content_receiver,
3064 return Get(path, headers, response_handler, content_receiver, dummy); 4041 Progress());
3065} 4042}
3066 4043
3067inline std::shared_ptr<Response> Client::Get(const char *path, 4044inline std::shared_ptr<Response> Client::Get(const char *path,
@@ -3073,9 +4050,9 @@ inline std::shared_ptr<Response> Client::Get(const char *path,
3073 req.method = "GET"; 4050 req.method = "GET";
3074 req.path = path; 4051 req.path = path;
3075 req.headers = headers; 4052 req.headers = headers;
3076 req.response_handler = response_handler; 4053 req.response_handler = std::move(response_handler);
3077 req.content_receiver = content_receiver; 4054 req.content_receiver = std::move(content_receiver);
3078 req.progress = progress; 4055 req.progress = std::move(progress);
3079 4056
3080 auto res = std::make_shared<Response>(); 4057 auto res = std::make_shared<Response>();
3081 return send(req, *res) ? res : nullptr; 4058 return send(req, *res) ? res : nullptr;
@@ -3107,17 +4084,8 @@ inline std::shared_ptr<Response> Client::Post(const char *path,
3107 const Headers &headers, 4084 const Headers &headers,
3108 const std::string &body, 4085 const std::string &body,
3109 const char *content_type) { 4086 const char *content_type) {
3110 Request req; 4087 return send_with_content_provider("POST", path, headers, body, 0, nullptr,
3111 req.method = "POST"; 4088 content_type);
3112 req.headers = headers;
3113 req.path = path;
3114
3115 req.headers.emplace("Content-Type", content_type);
3116 req.body = body;
3117
3118 auto res = std::make_shared<Response>();
3119
3120 return send(req, *res) ? res : nullptr;
3121} 4089}
3122 4090
3123inline std::shared_ptr<Response> Client::Post(const char *path, 4091inline std::shared_ptr<Response> Client::Post(const char *path,
@@ -3125,6 +4093,21 @@ inline std::shared_ptr<Response> Client::Post(const char *path,
3125 return Post(path, Headers(), params); 4093 return Post(path, Headers(), params);
3126} 4094}
3127 4095
4096inline std::shared_ptr<Response> Client::Post(const char *path,
4097 size_t content_length,
4098 ContentProvider content_provider,
4099 const char *content_type) {
4100 return Post(path, Headers(), content_length, content_provider, content_type);
4101}
4102
4103inline std::shared_ptr<Response>
4104Client::Post(const char *path, const Headers &headers, size_t content_length,
4105 ContentProvider content_provider, const char *content_type) {
4106 return send_with_content_provider("POST", path, headers, std::string(),
4107 content_length, content_provider,
4108 content_type);
4109}
4110
3128inline std::shared_ptr<Response> 4111inline std::shared_ptr<Response>
3129Client::Post(const char *path, const Headers &headers, const Params &params) { 4112Client::Post(const char *path, const Headers &headers, const Params &params) {
3130 std::string query; 4113 std::string query;
@@ -3146,35 +4129,28 @@ Client::Post(const char *path, const MultipartFormDataItems &items) {
3146inline std::shared_ptr<Response> 4129inline std::shared_ptr<Response>
3147Client::Post(const char *path, const Headers &headers, 4130Client::Post(const char *path, const Headers &headers,
3148 const MultipartFormDataItems &items) { 4131 const MultipartFormDataItems &items) {
3149 Request req;
3150 req.method = "POST";
3151 req.headers = headers;
3152 req.path = path;
3153
3154 auto boundary = detail::make_multipart_data_boundary(); 4132 auto boundary = detail::make_multipart_data_boundary();
3155 4133
3156 req.headers.emplace("Content-Type", 4134 std::string body;
3157 "multipart/form-data; boundary=" + boundary);
3158 4135
3159 for (const auto &item : items) { 4136 for (const auto &item : items) {
3160 req.body += "--" + boundary + "\r\n"; 4137 body += "--" + boundary + "\r\n";
3161 req.body += "Content-Disposition: form-data; name=\"" + item.name + "\""; 4138 body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
3162 if (!item.filename.empty()) { 4139 if (!item.filename.empty()) {
3163 req.body += "; filename=\"" + item.filename + "\""; 4140 body += "; filename=\"" + item.filename + "\"";
3164 } 4141 }
3165 req.body += "\r\n"; 4142 body += "\r\n";
3166 if (!item.content_type.empty()) { 4143 if (!item.content_type.empty()) {
3167 req.body += "Content-Type: " + item.content_type + "\r\n"; 4144 body += "Content-Type: " + item.content_type + "\r\n";
3168 } 4145 }
3169 req.body += "\r\n"; 4146 body += "\r\n";
3170 req.body += item.content + "\r\n"; 4147 body += item.content + "\r\n";
3171 } 4148 }
3172 4149
3173 req.body += "--" + boundary + "--\r\n"; 4150 body += "--" + boundary + "--\r\n";
3174 4151
3175 auto res = std::make_shared<Response>(); 4152 std::string content_type = "multipart/form-data; boundary=" + boundary;
3176 4153 return Post(path, headers, body, content_type.c_str());
3177 return send(req, *res) ? res : nullptr;
3178} 4154}
3179 4155
3180inline std::shared_ptr<Response> Client::Put(const char *path, 4156inline std::shared_ptr<Response> Client::Put(const char *path,
@@ -3187,17 +4163,41 @@ inline std::shared_ptr<Response> Client::Put(const char *path,
3187 const Headers &headers, 4163 const Headers &headers,
3188 const std::string &body, 4164 const std::string &body,
3189 const char *content_type) { 4165 const char *content_type) {
3190 Request req; 4166 return send_with_content_provider("PUT", path, headers, body, 0, nullptr,
3191 req.method = "PUT"; 4167 content_type);
3192 req.headers = headers; 4168}
3193 req.path = path;
3194 4169
3195 req.headers.emplace("Content-Type", content_type); 4170inline std::shared_ptr<Response> Client::Put(const char *path,
3196 req.body = body; 4171 size_t content_length,
4172 ContentProvider content_provider,
4173 const char *content_type) {
4174 return Put(path, Headers(), content_length, content_provider, content_type);
4175}
3197 4176
3198 auto res = std::make_shared<Response>(); 4177inline std::shared_ptr<Response>
4178Client::Put(const char *path, const Headers &headers, size_t content_length,
4179 ContentProvider content_provider, const char *content_type) {
4180 return send_with_content_provider("PUT", path, headers, std::string(),
4181 content_length, content_provider,
4182 content_type);
4183}
3199 4184
3200 return send(req, *res) ? res : nullptr; 4185inline std::shared_ptr<Response> Client::Put(const char *path,
4186 const Params &params) {
4187 return Put(path, Headers(), params);
4188}
4189
4190inline std::shared_ptr<Response>
4191Client::Put(const char *path, const Headers &headers, const Params &params) {
4192 std::string query;
4193 for (auto it = params.begin(); it != params.end(); ++it) {
4194 if (it != params.begin()) { query += "&"; }
4195 query += it->first;
4196 query += "=";
4197 query += detail::encode_url(it->second);
4198 }
4199
4200 return Put(path, headers, query, "application/x-www-form-urlencoded");
3201} 4201}
3202 4202
3203inline std::shared_ptr<Response> Client::Patch(const char *path, 4203inline std::shared_ptr<Response> Client::Patch(const char *path,
@@ -3210,17 +4210,23 @@ inline std::shared_ptr<Response> Client::Patch(const char *path,
3210 const Headers &headers, 4210 const Headers &headers,
3211 const std::string &body, 4211 const std::string &body,
3212 const char *content_type) { 4212 const char *content_type) {
3213 Request req; 4213 return send_with_content_provider("PATCH", path, headers, body, 0, nullptr,
3214 req.method = "PATCH"; 4214 content_type);
3215 req.headers = headers; 4215}
3216 req.path = path;
3217
3218 req.headers.emplace("Content-Type", content_type);
3219 req.body = body;
3220 4216
3221 auto res = std::make_shared<Response>(); 4217inline std::shared_ptr<Response> Client::Patch(const char *path,
4218 size_t content_length,
4219 ContentProvider content_provider,
4220 const char *content_type) {
4221 return Patch(path, Headers(), content_length, content_provider, content_type);
4222}
3222 4223
3223 return send(req, *res) ? res : nullptr; 4224inline std::shared_ptr<Response>
4225Client::Patch(const char *path, const Headers &headers, size_t content_length,
4226 ContentProvider content_provider, const char *content_type) {
4227 return send_with_content_provider("PATCH", path, headers, std::string(),
4228 content_length, content_provider,
4229 content_type);
3224} 4230}
3225 4231
3226inline std::shared_ptr<Response> Client::Delete(const char *path) { 4232inline std::shared_ptr<Response> Client::Delete(const char *path) {
@@ -3271,11 +4277,58 @@ inline std::shared_ptr<Response> Client::Options(const char *path,
3271 return send(req, *res) ? res : nullptr; 4277 return send(req, *res) ? res : nullptr;
3272} 4278}
3273 4279
4280inline void Client::set_timeout_sec(time_t timeout_sec) {
4281 timeout_sec_ = timeout_sec;
4282}
4283
4284inline void Client::set_read_timeout(time_t sec, time_t usec) {
4285 read_timeout_sec_ = sec;
4286 read_timeout_usec_ = usec;
4287}
4288
3274inline void Client::set_keep_alive_max_count(size_t count) { 4289inline void Client::set_keep_alive_max_count(size_t count) {
3275 keep_alive_max_count_ = count; 4290 keep_alive_max_count_ = count;
3276} 4291}
3277 4292
3278inline void Client::follow_location(bool on) { follow_location_ = on; } 4293inline void Client::set_basic_auth(const char *username, const char *password) {
4294 basic_auth_username_ = username;
4295 basic_auth_password_ = password;
4296}
4297
4298#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
4299inline void Client::set_digest_auth(const char *username,
4300 const char *password) {
4301 digest_auth_username_ = username;
4302 digest_auth_password_ = password;
4303}
4304#endif
4305
4306inline void Client::set_follow_location(bool on) { follow_location_ = on; }
4307
4308inline void Client::set_compress(bool on) { compress_ = on; }
4309
4310inline void Client::set_interface(const char *intf) { interface_ = intf; }
4311
4312inline void Client::set_proxy(const char *host, int port) {
4313 proxy_host_ = host;
4314 proxy_port_ = port;
4315}
4316
4317inline void Client::set_proxy_basic_auth(const char *username,
4318 const char *password) {
4319 proxy_basic_auth_username_ = username;
4320 proxy_basic_auth_password_ = password;
4321}
4322
4323#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
4324inline void Client::set_proxy_digest_auth(const char *username,
4325 const char *password) {
4326 proxy_digest_auth_username_ = username;
4327 proxy_digest_auth_password_ = password;
4328}
4329#endif
4330
4331inline void Client::set_logger(Logger logger) { logger_ = std::move(logger); }
3279 4332
3280/* 4333/*
3281 * SSL Implementation 4334 * SSL Implementation
@@ -3284,11 +4337,10 @@ inline void Client::follow_location(bool on) { follow_location_ = on; }
3284namespace detail { 4337namespace detail {
3285 4338
3286template <typename U, typename V, typename T> 4339template <typename U, typename V, typename T>
3287inline bool process_and_close_socket_ssl(bool is_client_request, socket_t sock, 4340inline bool process_and_close_socket_ssl(
3288 size_t keep_alive_max_count, 4341 bool is_client_request, socket_t sock, size_t keep_alive_max_count,
3289 SSL_CTX *ctx, std::mutex &ctx_mutex, 4342 time_t read_timeout_sec, time_t read_timeout_usec, SSL_CTX *ctx,
3290 U SSL_connect_or_accept, V setup, 4343 std::mutex &ctx_mutex, U SSL_connect_or_accept, V setup, T callback) {
3291 T callback) {
3292 assert(keep_alive_max_count > 0); 4344 assert(keep_alive_max_count > 0);
3293 4345
3294 SSL *ssl = nullptr; 4346 SSL *ssl = nullptr;
@@ -3316,7 +4368,7 @@ inline bool process_and_close_socket_ssl(bool is_client_request, socket_t sock,
3316 return false; 4368 return false;
3317 } 4369 }
3318 4370
3319 bool ret = false; 4371 auto ret = false;
3320 4372
3321 if (SSL_connect_or_accept(ssl) == 1) { 4373 if (SSL_connect_or_accept(ssl) == 1) {
3322 if (keep_alive_max_count > 1) { 4374 if (keep_alive_max_count > 1) {
@@ -3325,7 +4377,7 @@ inline bool process_and_close_socket_ssl(bool is_client_request, socket_t sock,
3325 (is_client_request || 4377 (is_client_request ||
3326 detail::select_read(sock, CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND, 4378 detail::select_read(sock, CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND,
3327 CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND) > 0)) { 4379 CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND) > 0)) {
3328 SSLSocketStream strm(sock, ssl); 4380 SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec);
3329 auto last_connection = count == 1; 4381 auto last_connection = count == 1;
3330 auto connection_close = false; 4382 auto connection_close = false;
3331 4383
@@ -3335,7 +4387,7 @@ inline bool process_and_close_socket_ssl(bool is_client_request, socket_t sock,
3335 count--; 4387 count--;
3336 } 4388 }
3337 } else { 4389 } else {
3338 SSLSocketStream strm(sock, ssl); 4390 SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec);
3339 auto dummy_connection_close = false; 4391 auto dummy_connection_close = false;
3340 ret = callback(ssl, strm, true, dummy_connection_close); 4392 ret = callback(ssl, strm, true, dummy_connection_close);
3341 } 4393 }
@@ -3382,11 +4434,20 @@ private:
3382class SSLInit { 4434class SSLInit {
3383public: 4435public:
3384 SSLInit() { 4436 SSLInit() {
4437#if OPENSSL_VERSION_NUMBER < 0x1010001fL
3385 SSL_load_error_strings(); 4438 SSL_load_error_strings();
3386 SSL_library_init(); 4439 SSL_library_init();
4440#else
4441 OPENSSL_init_ssl(
4442 OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
4443#endif
3387 } 4444 }
3388 4445
3389 ~SSLInit() { ERR_free_strings(); } 4446 ~SSLInit() {
4447#if OPENSSL_VERSION_NUMBER < 0x1010001fL
4448 ERR_free_strings();
4449#endif
4450 }
3390 4451
3391private: 4452private:
3392#if OPENSSL_VERSION_NUMBER < 0x10100000L 4453#if OPENSSL_VERSION_NUMBER < 0x10100000L
@@ -3394,41 +4455,44 @@ private:
3394#endif 4455#endif
3395}; 4456};
3396 4457
3397static SSLInit sslinit_;
3398
3399} // namespace detail
3400
3401// SSL socket stream implementation 4458// SSL socket stream implementation
3402inline SSLSocketStream::SSLSocketStream(socket_t sock, SSL *ssl) 4459inline SSLSocketStream::SSLSocketStream(socket_t sock, SSL *ssl,
3403 : sock_(sock), ssl_(ssl) {} 4460 time_t read_timeout_sec,
4461 time_t read_timeout_usec)
4462 : sock_(sock), ssl_(ssl), read_timeout_sec_(read_timeout_sec),
4463 read_timeout_usec_(read_timeout_usec) {}
3404 4464
3405inline SSLSocketStream::~SSLSocketStream() {} 4465inline SSLSocketStream::~SSLSocketStream() {}
3406 4466
4467inline bool SSLSocketStream::is_readable() const {
4468 return detail::select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
4469}
4470
4471inline bool SSLSocketStream::is_writable() const {
4472 return detail::select_write(sock_, 0, 0) > 0;
4473}
4474
3407inline int SSLSocketStream::read(char *ptr, size_t size) { 4475inline int SSLSocketStream::read(char *ptr, size_t size) {
3408 if (SSL_pending(ssl_) > 0 || 4476 if (SSL_pending(ssl_) > 0 ||
3409 detail::select_read(sock_, CPPHTTPLIB_READ_TIMEOUT_SECOND, 4477 select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0) {
3410 CPPHTTPLIB_READ_TIMEOUT_USECOND) > 0) {
3411 return SSL_read(ssl_, ptr, static_cast<int>(size)); 4478 return SSL_read(ssl_, ptr, static_cast<int>(size));
3412 } 4479 }
3413 return -1; 4480 return -1;
3414} 4481}
3415 4482
3416inline int SSLSocketStream::write(const char *ptr, size_t size) { 4483inline int SSLSocketStream::write(const char *ptr, size_t size) {
3417 return SSL_write(ssl_, ptr, static_cast<int>(size)); 4484 if (is_writable()) { return SSL_write(ssl_, ptr, static_cast<int>(size)); }
3418} 4485 return -1;
3419
3420inline int SSLSocketStream::write(const char *ptr) {
3421 return write(ptr, strlen(ptr));
3422}
3423
3424inline int SSLSocketStream::write(const std::string &s) {
3425 return write(s.data(), s.size());
3426} 4486}
3427 4487
3428inline std::string SSLSocketStream::get_remote_addr() const { 4488inline std::string SSLSocketStream::get_remote_addr() const {
3429 return detail::get_remote_addr(sock_); 4489 return detail::get_remote_addr(sock_);
3430} 4490}
3431 4491
4492static SSLInit sslinit_;
4493
4494} // namespace detail
4495
3432// SSL HTTP server implementation 4496// SSL HTTP server implementation
3433inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path, 4497inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
3434 const char *client_ca_cert_file_path, 4498 const char *client_ca_cert_file_path,
@@ -3476,8 +4540,8 @@ inline bool SSLServer::is_valid() const { return ctx_; }
3476 4540
3477inline bool SSLServer::process_and_close_socket(socket_t sock) { 4541inline bool SSLServer::process_and_close_socket(socket_t sock) {
3478 return detail::process_and_close_socket_ssl( 4542 return detail::process_and_close_socket_ssl(
3479 false, sock, keep_alive_max_count_, ctx_, ctx_mutex_, SSL_accept, 4543 false, sock, keep_alive_max_count_, read_timeout_sec_, read_timeout_usec_,
3480 [](SSL * /*ssl*/) { return true; }, 4544 ctx_, ctx_mutex_, SSL_accept, [](SSL * /*ssl*/) { return true; },
3481 [this](SSL *ssl, Stream &strm, bool last_connection, 4545 [this](SSL *ssl, Stream &strm, bool last_connection,
3482 bool &connection_close) { 4546 bool &connection_close) {
3483 return process_request(strm, last_connection, connection_close, 4547 return process_request(strm, last_connection, connection_close,
@@ -3486,21 +4550,21 @@ inline bool SSLServer::process_and_close_socket(socket_t sock) {
3486} 4550}
3487 4551
3488// SSL HTTP client implementation 4552// SSL HTTP client implementation
3489inline SSLClient::SSLClient(const char *host, int port, time_t timeout_sec, 4553inline SSLClient::SSLClient(const std::string &host, int port,
3490 const char *client_cert_path, 4554 const std::string &client_cert_path,
3491 const char *client_key_path) 4555 const std::string &client_key_path)
3492 : Client(host, port, timeout_sec) { 4556 : Client(host, port, client_cert_path, client_key_path) {
3493 ctx_ = SSL_CTX_new(SSLv23_client_method()); 4557 ctx_ = SSL_CTX_new(SSLv23_client_method());
3494 4558
3495 detail::split(&host_[0], &host_[host_.size()], '.', 4559 detail::split(&host_[0], &host_[host_.size()], '.',
3496 [&](const char *b, const char *e) { 4560 [&](const char *b, const char *e) {
3497 host_components_.emplace_back(std::string(b, e)); 4561 host_components_.emplace_back(std::string(b, e));
3498 }); 4562 });
3499 if (client_cert_path && client_key_path) { 4563 if (!client_cert_path.empty() && !client_key_path.empty()) {
3500 if (SSL_CTX_use_certificate_file(ctx_, client_cert_path, 4564 if (SSL_CTX_use_certificate_file(ctx_, client_cert_path.c_str(),
3501 SSL_FILETYPE_PEM) != 1 || 4565 SSL_FILETYPE_PEM) != 1 ||
3502 SSL_CTX_use_PrivateKey_file(ctx_, client_key_path, SSL_FILETYPE_PEM) != 4566 SSL_CTX_use_PrivateKey_file(ctx_, client_key_path.c_str(),
3503 1) { 4567 SSL_FILETYPE_PEM) != 1) {
3504 SSL_CTX_free(ctx_); 4568 SSL_CTX_free(ctx_);
3505 ctx_ = nullptr; 4569 ctx_ = nullptr;
3506 } 4570 }
@@ -3527,9 +4591,7 @@ inline long SSLClient::get_openssl_verify_result() const {
3527 return verify_result_; 4591 return verify_result_;
3528} 4592}
3529 4593
3530inline SSL_CTX* SSLClient::ssl_context() const noexcept { 4594inline SSL_CTX *SSLClient::ssl_context() const noexcept { return ctx_; }
3531 return ctx_;
3532}
3533 4595
3534inline bool SSLClient::process_and_close_socket( 4596inline bool SSLClient::process_and_close_socket(
3535 socket_t sock, size_t request_count, 4597 socket_t sock, size_t request_count,
@@ -3541,7 +4603,8 @@ inline bool SSLClient::process_and_close_socket(
3541 4603
3542 return is_valid() && 4604 return is_valid() &&
3543 detail::process_and_close_socket_ssl( 4605 detail::process_and_close_socket_ssl(
3544 true, sock, request_count, ctx_, ctx_mutex_, 4606 true, sock, request_count, read_timeout_sec_, read_timeout_usec_,
4607 ctx_, ctx_mutex_,
3545 [&](SSL *ssl) { 4608 [&](SSL *ssl) {
3546 if (ca_cert_file_path_.empty()) { 4609 if (ca_cert_file_path_.empty()) {
3547 SSL_CTX_set_verify(ctx_, SSL_VERIFY_NONE, nullptr); 4610 SSL_CTX_set_verify(ctx_, SSL_VERIFY_NONE, nullptr);
@@ -3712,6 +4775,8 @@ inline bool SSLClient::check_host_name(const char *pattern,
3712} 4775}
3713#endif 4776#endif
3714 4777
4778// ----------------------------------------------------------------------------
4779
3715} // namespace httplib 4780} // namespace httplib
3716 4781
3717#endif // CPPHTTPLIB_HTTPLIB_H 4782#endif // CPPHTTPLIB_HTTPLIB_H