Debian Codegraph @

third_party/cpp-httplib-0.5.12/httplib.h

raw symbols SCIP
1 //
2 // httplib.h
3 //
4 // Copyright (c) 2020 Yuji Hirose. All rights reserved.
5 // MIT License
6 //
7
8 #ifndef CPPHTTPLIB_HTTPLIB_H
9 #define CPPHTTPLIB_HTTPLIB_H
10
11 /*
12 * Configuration
13 */
14
15 #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
16 #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
17 #endif
18
19 #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND
20 #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND 0
21 #endif
22
23 #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
24 #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 5
25 #endif
26
27 #ifndef CPPHTTPLIB_READ_TIMEOUT_SECOND
28 #define CPPHTTPLIB_READ_TIMEOUT_SECOND 5
29 #endif
30
31 #ifndef CPPHTTPLIB_READ_TIMEOUT_USECOND
32 #define CPPHTTPLIB_READ_TIMEOUT_USECOND 0
33 #endif
34
35 #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
36 #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
37 #endif
38
39 #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
40 #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
41 #endif
42
43 #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
44 #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH ((std::numeric_limits<size_t>::max)())
45 #endif
46
47 #ifndef CPPHTTPLIB_RECV_BUFSIZ
48 #define CPPHTTPLIB_RECV_BUFSIZ size_t(4096u)
49 #endif
50
51 #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
52 #define CPPHTTPLIB_THREAD_POOL_COUNT \
53 ((std::max)(8u, std::thread::hardware_concurrency() - 1))
54 #endif
55
56 /*
57 * Headers
58 */
59
60 #ifdef _WIN32
61 #ifndef _CRT_SECURE_NO_WARNINGS
62 #define _CRT_SECURE_NO_WARNINGS
63 #endif //_CRT_SECURE_NO_WARNINGS
64
65 #ifndef _CRT_NONSTDC_NO_DEPRECATE
66 #define _CRT_NONSTDC_NO_DEPRECATE
67 #endif //_CRT_NONSTDC_NO_DEPRECATE
68
69 #if defined(_MSC_VER)
70 #ifdef _WIN64
71 using ssize_t = __int64;
72 #else
73 using ssize_t = int;
74 #endif
75
76 #if _MSC_VER < 1900
77 #define snprintf _snprintf_s
78 #endif
79 #endif // _MSC_VER
80
81 #ifndef S_ISREG
82 #define S_ISREG(m) (((m)&S_IFREG) == S_IFREG)
83 #endif // S_ISREG
84
85 #ifndef S_ISDIR
86 #define S_ISDIR(m) (((m)&S_IFDIR) == S_IFDIR)
87 #endif // S_ISDIR
88
89 #ifndef NOMINMAX
90 #define NOMINMAX
91 #endif // NOMINMAX
92
93 #include <io.h>
94 #include <winsock2.h>
95 #include <ws2tcpip.h>
96
97 #ifndef WSA_FLAG_NO_HANDLE_INHERIT
98 #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
99 #endif
100
101 #ifdef _MSC_VER
102 #pragma comment(lib, "ws2_32.lib")
103 #endif
104
105 #ifndef strcasecmp
106 #define strcasecmp _stricmp
107 #endif // strcasecmp
108
109 using socket_t = SOCKET;
110 #ifdef CPPHTTPLIB_USE_POLL
111 #define poll(fds, nfds, timeout) WSAPoll(fds, nfds, timeout)
112 #endif
113
114 #else // not _WIN32
115
116 #include <arpa/inet.h>
117 #include <cstring>
118 #include <ifaddrs.h>
119 #include <netdb.h>
120 #include <netinet/in.h>
121 #ifdef CPPHTTPLIB_USE_POLL
122 #include <poll.h>
123 #endif
124 #include <csignal>
125 #include <pthread.h>
126 #include <sys/select.h>
127 #include <sys/socket.h>
128 #include <unistd.h>
129
130 using socket_t = int;
131 #define INVALID_SOCKET (-1)
132 #endif //_WIN32
133
134 #include <array>
135 #include <atomic>
136 #include <cassert>
137 #include <climits>
138 #include <condition_variable>
139 #include <errno.h>
140 #include <fcntl.h>
141 #include <fstream>
142 #include <functional>
143 #include <list>
144 #include <map>
145 #include <memory>
146 #include <mutex>
147 #include <random>
148 #include <regex>
149 #include <string>
150 #include <sys/stat.h>
151 #include <thread>
152
153 #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
154 #include <openssl/err.h>
155 #include <openssl/md5.h>
156 #include <openssl/ssl.h>
157 #include <openssl/x509v3.h>
158
159 #include <iomanip>
160 #include <iostream>
161 #include <sstream>
162
163 // #if OPENSSL_VERSION_NUMBER < 0x1010100fL
164 // #error Sorry, OpenSSL versions prior to 1.1.1 are not supported
165 // #endif
166
167 #if OPENSSL_VERSION_NUMBER < 0x10100000L
168 #include <openssl/crypto.h>
169 inline const unsigned char *ASN1_STRING_get0_data(const ASN1_STRING *asn1) {
170 return M_ASN1_STRING_data(asn1);
171 }
172 #endif
173 #endif
174
175 #ifdef CPPHTTPLIB_ZLIB_SUPPORT
176 #include <zlib.h>
177 #endif
178 /*
179 * Declaration
180 */
181 namespace httplib {
182
183 namespace detail {
184
185 struct ci {
186 bool operator()(const std::string &s1, const std::string &s2) const {
187 return std::lexicographical_compare(
188 s1.begin(), s1.end(), s2.begin(), s2.end(),
189 [](char c1, char c2) { return ::tolower(c1) < ::tolower(c2); });
190 }
191 };
192
193 } // namespace detail
194
195 using Headers = std::multimap<std::string, std::string, detail::ci>;
196
197 using Params = std::multimap<std::string, std::string>;
198 using Match = std::smatch;
199
200 using Progress = std::function<bool(uint64_t current, uint64_t total)>;
201
202 struct Response;
203 using ResponseHandler = std::function<bool(const Response &response)>;
204
205 struct MultipartFormData {
206 std::string name;
207 std::string content;
208 std::string filename;
209 std::string content_type;
210 };
211 using MultipartFormDataItems = std::vector<MultipartFormData>;
212 using MultipartFormDataMap = std::multimap<std::string, MultipartFormData>;
213
214 class DataSink {
215 public:
216 DataSink() = default;
217 DataSink(const DataSink &) = delete;
218 DataSink &operator=(const DataSink &) = delete;
219 DataSink(DataSink &&) = delete;
220 DataSink &operator=(DataSink &&) = delete;
221
222 std::function<void(const char *data, size_t data_len)> write;
223 std::function<void()> done;
224 std::function<bool()> is_writable;
225 };
226
227 using ContentProvider =
228 std::function<void(size_t offset, size_t length, DataSink &sink)>;
229
230 using ContentReceiver =
231 std::function<bool(const char *data, size_t data_length)>;
232
233 using MultipartContentHeader =
234 std::function<bool(const MultipartFormData &file)>;
235
236 class ContentReader {
237 public:
238 using Reader = std::function<bool(ContentReceiver receiver)>;
239 using MultipartReader = std::function<bool(MultipartContentHeader header,
240 ContentReceiver receiver)>;
241
242 ContentReader(Reader reader, MultipartReader muitlpart_reader)
243 : reader_(reader), muitlpart_reader_(muitlpart_reader) {}
244
245 bool operator()(MultipartContentHeader header,
246 ContentReceiver receiver) const {
247 return muitlpart_reader_(header, receiver);
248 }
249
250 bool operator()(ContentReceiver receiver) const { return reader_(receiver); }
251
252 Reader reader_;
253 MultipartReader muitlpart_reader_;
254 };
255
256 using Range = std::pair<ssize_t, ssize_t>;
257 using Ranges = std::vector<Range>;
258
259 struct Request {
260 std::string method;
261 std::string path;
262 Headers headers;
263 std::string body;
264
265 std::string remote_addr;
266 int remote_port = -1;
267
268 // for server
269 std::string version;
270 std::string target;
271 Params params;
272 MultipartFormDataMap files;
273 Ranges ranges;
274 Match matches;
275
276 // for client
277 size_t redirect_count = CPPHTTPLIB_REDIRECT_MAX_COUNT;
278 ResponseHandler response_handler;
279 ContentReceiver content_receiver;
280 Progress progress;
281
282 #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
283 const SSL *ssl;
284 #endif
285
286 bool has_header(const char *key) const;
287 std::string get_header_value(const char *key, size_t id = 0) const;
288 size_t get_header_value_count(const char *key) const;
289 void set_header(const char *key, const char *val);
290 void set_header(const char *key, const std::string &val);
291
292 bool has_param(const char *key) const;
293 std::string get_param_value(const char *key, size_t id = 0) const;
294 size_t get_param_value_count(const char *key) const;
295
296 bool is_multipart_form_data() const;
297
298 bool has_file(const char *key) const;
299 MultipartFormData get_file_value(const char *key) const;
300
301 // private members...
302 size_t content_length;
303 ContentProvider content_provider;
304 };
305
306 struct Response {
307 std::string version;
308 int status = -1;
309 Headers headers;
310 std::string body;
311
312 bool has_header(const char *key) const;
313 std::string get_header_value(const char *key, size_t id = 0) const;
314 size_t get_header_value_count(const char *key) const;
315 void set_header(const char *key, const char *val);
316 void set_header(const char *key, const std::string &val);
317
318 void set_redirect(const char *url, int status = 302);
319 void set_content(const char *s, size_t n, const char *content_type);
320 void set_content(std::string s, const char *content_type);
321
322 void set_content_provider(
323 size_t length,
324 std::function<void(size_t offset, size_t length, DataSink &sink)>
325 provider,
326 std::function<void()> resource_releaser = [] {});
327
328 void set_chunked_content_provider(
329 std::function<void(size_t offset, DataSink &sink)> provider,
330 std::function<void()> resource_releaser = [] {});
331
332 Response() = default;
333 Response(const Response &) = default;
334 Response &operator=(const Response &) = default;
335 Response(Response &&) = default;
336 Response &operator=(Response &&) = default;
337 ~Response() {
338 if (content_provider_resource_releaser) {
339 content_provider_resource_releaser();
340 }
341 }
342
343 // private members...
344 size_t content_length = 0;
345 ContentProvider content_provider;
346 std::function<void()> content_provider_resource_releaser;
347 };
348
349 class Stream {
350 public:
351 virtual ~Stream() = default;
352
353 virtual bool is_readable() const = 0;
354 virtual bool is_writable() const = 0;
355
356 virtual ssize_t read(char *ptr, size_t size) = 0;
357 virtual ssize_t write(const char *ptr, size_t size) = 0;
358 virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
359
360 template <typename... Args>
361 ssize_t write_format(const char *fmt, const Args &... args);
362 ssize_t write(const char *ptr);
363 ssize_t write(const std::string &s);
364 };
365
366 class TaskQueue {
367 public:
368 TaskQueue() = default;
369 virtual ~TaskQueue() = default;
370
371 virtual void enqueue(std::function<void()> fn) = 0;
372 virtual void shutdown() = 0;
373
374 virtual void on_idle(){};
375 };
376
377 class ThreadPool : public TaskQueue {
378 public:
379 explicit ThreadPool(size_t n) : shutdown_(false) {
380 while (n) {
381 threads_.emplace_back(worker(*this));
382 n--;
383 }
384 }
385
386 ThreadPool(const ThreadPool &) = delete;
387 ~ThreadPool() override = default;
388
389 void enqueue(std::function<void()> fn) override {
390 std::unique_lock<std::mutex> lock(mutex_);
391 jobs_.push_back(fn);
392 cond_.notify_one();
393 }
394
395 void shutdown() override {
396 // Stop all worker threads...
397 {
398 std::unique_lock<std::mutex> lock(mutex_);
399 shutdown_ = true;
400 }
401
402 cond_.notify_all();
403
404 // Join...
405 for (auto &t : threads_) {
406 t.join();
407 }
408 }
409
410 private:
411 struct worker {
412 explicit worker(ThreadPool &pool) : pool_(pool) {}
413
414 void operator()() {
415 for (;;) {
416 std::function<void()> fn;
417 {
418 std::unique_lock<std::mutex> lock(pool_.mutex_);
419
420 pool_.cond_.wait(
421 lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; });
422
423 if (pool_.shutdown_ && pool_.jobs_.empty()) { break; }
424
425 fn = pool_.jobs_.front();
426 pool_.jobs_.pop_front();
427 }
428
429 assert(true == static_cast<bool>(fn));
430 fn();
431 }
432 }
433
434 ThreadPool &pool_;
435 };
436 friend struct worker;
437
438 std::vector<std::thread> threads_;
439 std::list<std::function<void()>> jobs_;
440
441 bool shutdown_;
442
443 std::condition_variable cond_;
444 std::mutex mutex_;
445 };
446
447 using Logger = std::function<void(const Request &, const Response &)>;
448
449 class Server {
450 public:
451 using Handler = std::function<void(const Request &, Response &)>;
452 using HandlerWithContentReader = std::function<void(
453 const Request &, Response &, const ContentReader &content_reader)>;
454 using Expect100ContinueHandler =
455 std::function<int(const Request &, Response &)>;
456
457 Server();
458
459 virtual ~Server();
460
461 virtual bool is_valid() const;
462
463 Server &Get(const char *pattern, Handler handler);
464 Server &Post(const char *pattern, Handler handler);
465 Server &Post(const char *pattern, HandlerWithContentReader handler);
466 Server &Put(const char *pattern, Handler handler);
467 Server &Put(const char *pattern, HandlerWithContentReader handler);
468 Server &Patch(const char *pattern, Handler handler);
469 Server &Patch(const char *pattern, HandlerWithContentReader handler);
470 Server &Delete(const char *pattern, Handler handler);
471 Server &Delete(const char *pattern, HandlerWithContentReader handler);
472 Server &Options(const char *pattern, Handler handler);
473
474 [[deprecated]] bool set_base_dir(const char *dir,
475 const char *mount_point = nullptr);
476 bool set_mount_point(const char *mount_point, const char *dir);
477 bool remove_mount_point(const char *mount_point);
478 void set_file_extension_and_mimetype_mapping(const char *ext,
479 const char *mime);
480 void set_file_request_handler(Handler handler);
481
482 void set_error_handler(Handler handler);
483 void set_logger(Logger logger);
484
485 void set_expect_100_continue_handler(Expect100ContinueHandler handler);
486
487 void set_keep_alive_max_count(size_t count);
488 void set_read_timeout(time_t sec, time_t usec);
489 void set_payload_max_length(size_t length);
490
491 bool bind_to_port(const char *host, int port, int socket_flags = 0);
492 int bind_to_any_port(const char *host, int socket_flags = 0);
493 bool listen_after_bind();
494
495 bool listen(const char *host, int port, int socket_flags = 0);
496
497 bool is_running() const;
498 void stop();
499
500 std::function<TaskQueue *(void)> new_task_queue;
501
502 protected:
503 bool process_request(Stream &strm, bool last_connection,
504 bool &connection_close,
505 const std::function<void(Request &)> &setup_request);
506
507 size_t keep_alive_max_count_;
508 time_t read_timeout_sec_;
509 time_t read_timeout_usec_;
510 size_t payload_max_length_;
511
512 private:
513 using Handlers = std::vector<std::pair<std::regex, Handler>>;
514 using HandlersForContentReader =
515 std::vector<std::pair<std::regex, HandlerWithContentReader>>;
516
517 socket_t create_server_socket(const char *host, int port,
518 int socket_flags) const;
519 int bind_internal(const char *host, int port, int socket_flags);
520 bool listen_internal();
521
522 bool routing(Request &req, Response &res, Stream &strm);
523 bool handle_file_request(Request &req, Response &res, bool head = false);
524 bool dispatch_request(Request &req, Response &res, Handlers &handlers);
525 bool dispatch_request_for_content_reader(Request &req, Response &res,
526 ContentReader content_reader,
527 HandlersForContentReader &handlers);
528
529 bool parse_request_line(const char *s, Request &req);
530 bool write_response(Stream &strm, bool last_connection, const Request &req,
531 Response &res);
532 bool write_content_with_provider(Stream &strm, const Request &req,
533 Response &res, const std::string &boundary,
534 const std::string &content_type);
535 bool read_content(Stream &strm, Request &req, Response &res);
536 bool
537 read_content_with_content_receiver(Stream &strm, Request &req, Response &res,
538 ContentReceiver receiver,
539 MultipartContentHeader multipart_header,
540 ContentReceiver multipart_receiver);
541 bool read_content_core(Stream &strm, Request &req, Response &res,
542 ContentReceiver receiver,
543 MultipartContentHeader mulitpart_header,
544 ContentReceiver multipart_receiver);
545
546 virtual bool process_and_close_socket(socket_t sock);
547
548 std::atomic<bool> is_running_;
549 std::atomic<socket_t> svr_sock_;
550 std::vector<std::pair<std::string, std::string>> base_dirs_;
551 std::map<std::string, std::string> file_extension_and_mimetype_map_;
552 Handler file_request_handler_;
553 Handlers get_handlers_;
554 Handlers post_handlers_;
555 HandlersForContentReader post_handlers_for_content_reader_;
556 Handlers put_handlers_;
557 HandlersForContentReader put_handlers_for_content_reader_;
558 Handlers patch_handlers_;
559 HandlersForContentReader patch_handlers_for_content_reader_;
560 Handlers delete_handlers_;
561 HandlersForContentReader delete_handlers_for_content_reader_;
562 Handlers options_handlers_;
563 Handler error_handler_;
564 Logger logger_;
565 Expect100ContinueHandler expect_100_continue_handler_;
566 };
567
568 class Client {
569 public:
570 explicit Client(const std::string &host, int port = 80,
571 const std::string &client_cert_path = std::string(),
572 const std::string &client_key_path = std::string());
573
574 virtual ~Client();
575
576 virtual bool is_valid() const;
577
578 std::shared_ptr<Response> Get(const char *path);
579
580 std::shared_ptr<Response> Get(const char *path, const Headers &headers);
581
582 std::shared_ptr<Response> Get(const char *path, Progress progress);
583
584 std::shared_ptr<Response> Get(const char *path, const Headers &headers,
585 Progress progress);
586
587 std::shared_ptr<Response> Get(const char *path,
588 ContentReceiver content_receiver);
589
590 std::shared_ptr<Response> Get(const char *path, const Headers &headers,
591 ContentReceiver content_receiver);
592
593 std::shared_ptr<Response>
594 Get(const char *path, ContentReceiver content_receiver, Progress progress);
595
596 std::shared_ptr<Response> Get(const char *path, const Headers &headers,
597 ContentReceiver content_receiver,
598 Progress progress);
599
600 std::shared_ptr<Response> Get(const char *path, const Headers &headers,
601 ResponseHandler response_handler,
602 ContentReceiver content_receiver);
603
604 std::shared_ptr<Response> Get(const char *path, const Headers &headers,
605 ResponseHandler response_handler,
606 ContentReceiver content_receiver,
607 Progress progress);
608
609 std::shared_ptr<Response> Head(const char *path);
610
611 std::shared_ptr<Response> Head(const char *path, const Headers &headers);
612
613 std::shared_ptr<Response> Post(const char *path);
614
615 std::shared_ptr<Response> Post(const char *path, const std::string &body,
616 const char *content_type);
617
618 std::shared_ptr<Response> Post(const char *path, const Headers &headers,
619 const std::string &body,
620 const char *content_type);
621
622 std::shared_ptr<Response> Post(const char *path, size_t content_length,
623 ContentProvider content_provider,
624 const char *content_type);
625
626 std::shared_ptr<Response> Post(const char *path, const Headers &headers,
627 size_t content_length,
628 ContentProvider content_provider,
629 const char *content_type);
630
631 std::shared_ptr<Response> Post(const char *path, const Params &params);
632
633 std::shared_ptr<Response> Post(const char *path, const Headers &headers,
634 const Params &params);
635
636 std::shared_ptr<Response> Post(const char *path,
637 const MultipartFormDataItems &items);
638
639 std::shared_ptr<Response> Post(const char *path, const Headers &headers,
640 const MultipartFormDataItems &items);
641
642 std::shared_ptr<Response> Put(const char *path);
643
644 std::shared_ptr<Response> Put(const char *path, const std::string &body,
645 const char *content_type);
646
647 std::shared_ptr<Response> Put(const char *path, const Headers &headers,
648 const std::string &body,
649 const char *content_type);
650
651 std::shared_ptr<Response> Put(const char *path, size_t content_length,
652 ContentProvider content_provider,
653 const char *content_type);
654
655 std::shared_ptr<Response> Put(const char *path, const Headers &headers,
656 size_t content_length,
657 ContentProvider content_provider,
658 const char *content_type);
659
660 std::shared_ptr<Response> Put(const char *path, const Params &params);
661
662 std::shared_ptr<Response> Put(const char *path, const Headers &headers,
663 const Params &params);
664
665 std::shared_ptr<Response> Patch(const char *path, const std::string &body,
666 const char *content_type);
667
668 std::shared_ptr<Response> Patch(const char *path, const Headers &headers,
669 const std::string &body,
670 const char *content_type);
671
672 std::shared_ptr<Response> Patch(const char *path, size_t content_length,
673 ContentProvider content_provider,
674 const char *content_type);
675
676 std::shared_ptr<Response> Patch(const char *path, const Headers &headers,
677 size_t content_length,
678 ContentProvider content_provider,
679 const char *content_type);
680
681 std::shared_ptr<Response> Delete(const char *path);
682
683 std::shared_ptr<Response> Delete(const char *path, const std::string &body,
684 const char *content_type);
685
686 std::shared_ptr<Response> Delete(const char *path, const Headers &headers);
687
688 std::shared_ptr<Response> Delete(const char *path, const Headers &headers,
689 const std::string &body,
690 const char *content_type);
691
692 std::shared_ptr<Response> Options(const char *path);
693
694 std::shared_ptr<Response> Options(const char *path, const Headers &headers);
695
696 bool send(const Request &req, Response &res);
697
698 bool send(const std::vector<Request> &requests,
699 std::vector<Response> &responses);
700
701 void stop();
702
703 void set_timeout_sec(time_t timeout_sec);
704
705 void set_read_timeout(time_t sec, time_t usec);
706
707 void set_keep_alive_max_count(size_t count);
708
709 void set_basic_auth(const char *username, const char *password);
710
711 #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
712 void set_digest_auth(const char *username, const char *password);
713 #endif
714
715 void set_follow_location(bool on);
716
717 void set_compress(bool on);
718
719 void set_interface(const char *intf);
720
721 void set_proxy(const char *host, int port);
722
723 void set_proxy_basic_auth(const char *username, const char *password);
724
725 #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
726 void set_proxy_digest_auth(const char *username, const char *password);
727 #endif
728
729 void set_logger(Logger logger);
730
731 protected:
732 bool process_request(Stream &strm, const Request &req, Response &res,
733 bool last_connection, bool &connection_close);
734
735 std::atomic<socket_t> sock_;
736
737 const std::string host_;
738 const int port_;
739 const std::string host_and_port_;
740
741 // Settings
742 std::string client_cert_path_;
743 std::string client_key_path_;
744
745 time_t timeout_sec_ = 300;
746 time_t read_timeout_sec_ = CPPHTTPLIB_READ_TIMEOUT_SECOND;
747 time_t read_timeout_usec_ = CPPHTTPLIB_READ_TIMEOUT_USECOND;
748
749 size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
750
751 std::string basic_auth_username_;
752 std::string basic_auth_password_;
753 #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
754 std::string digest_auth_username_;
755 std::string digest_auth_password_;
756 #endif
757
758 bool follow_location_ = false;
759
760 bool compress_ = false;
761
762 std::string interface_;
763
764 std::string proxy_host_;
765 int proxy_port_;
766
767 std::string proxy_basic_auth_username_;
768 std::string proxy_basic_auth_password_;
769 #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
770 std::string proxy_digest_auth_username_;
771 std::string proxy_digest_auth_password_;
772 #endif
773
774 Logger logger_;
775
776 void copy_settings(const Client &rhs) {
777 client_cert_path_ = rhs.client_cert_path_;
778 client_key_path_ = rhs.client_key_path_;
779 timeout_sec_ = rhs.timeout_sec_;
780 read_timeout_sec_ = rhs.read_timeout_sec_;
781 read_timeout_usec_ = rhs.read_timeout_usec_;
782 keep_alive_max_count_ = rhs.keep_alive_max_count_;
783 basic_auth_username_ = rhs.basic_auth_username_;
784 basic_auth_password_ = rhs.basic_auth_password_;
785 #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
786 digest_auth_username_ = rhs.digest_auth_username_;
787 digest_auth_password_ = rhs.digest_auth_password_;
788 #endif
789 follow_location_ = rhs.follow_location_;
790 compress_ = rhs.compress_;
791 interface_ = rhs.interface_;
792 proxy_host_ = rhs.proxy_host_;
793 proxy_port_ = rhs.proxy_port_;
794 proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
795 proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
796 #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
797 proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
798 proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
799 #endif
800 logger_ = rhs.logger_;
801 }
802
803 private:
804 socket_t create_client_socket() const;
805 bool read_response_line(Stream &strm, Response &res);
806 bool write_request(Stream &strm, const Request &req, bool last_connection);
807 bool redirect(const Request &req, Response &res);
808 bool handle_request(Stream &strm, const Request &req, Response &res,
809 bool last_connection, bool &connection_close);
810 #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
811 bool connect(socket_t sock, Response &res, bool &error);
812 #endif
813
814 std::shared_ptr<Response> send_with_content_provider(
815 const char *method, const char *path, const Headers &headers,
816 const std::string &body, size_t content_length,
817 ContentProvider content_provider, const char *content_type);
818
819 virtual bool process_and_close_socket(
820 socket_t sock, size_t request_count,
821 std::function<bool(Stream &strm, bool last_connection,
822 bool &connection_close)>
823 callback);
824
825 virtual bool is_ssl() const;
826 };
827
828 inline void Get(std::vector<Request> &requests, const char *path,
829 const Headers &headers) {
830 Request req;
831 req.method = "GET";
832 req.path = path;
833 req.headers = headers;
834 requests.emplace_back(std::move(req));
835 }
836
837 inline void Get(std::vector<Request> &requests, const char *path) {
838 Get(requests, path, Headers());
839 }
840
841 inline void Post(std::vector<Request> &requests, const char *path,
842 const Headers &headers, const std::string &body,
843 const char *content_type) {
844 Request req;
845 req.method = "POST";
846 req.path = path;
847 req.headers = headers;
848 if (content_type) { req.headers.emplace("Content-Type", content_type); }
849 req.body = body;
850 requests.emplace_back(std::move(req));
851 }
852
853 inline void Post(std::vector<Request> &requests, const char *path,
854 const std::string &body, const char *content_type) {
855 Post(requests, path, Headers(), body, content_type);
856 }
857
858 #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
859 class SSLServer : public Server {
860 public:
861 SSLServer(const char *cert_path, const char *private_key_path,
862 const char *client_ca_cert_file_path = nullptr,
863 const char *client_ca_cert_dir_path = nullptr);
864
865 SSLServer(X509 *cert, EVP_PKEY *private_key,
866 X509_STORE *client_ca_cert_store = nullptr);
867
868 ~SSLServer() override;
869
870 bool is_valid() const override;
871
872 private:
873 bool process_and_close_socket(socket_t sock) override;
874
875 SSL_CTX *ctx_;
876 std::mutex ctx_mutex_;
877 };
878
879 class SSLClient : public Client {
880 public:
881 explicit SSLClient(const std::string &host, int port = 443,
882 const std::string &client_cert_path = std::string(),
883 const std::string &client_key_path = std::string());
884
885 SSLClient(const std::string &host, int port, X509 *client_cert,
886 EVP_PKEY *client_key);
887
888 ~SSLClient() override;
889
890 bool is_valid() const override;
891
892 void set_ca_cert_path(const char *ca_ceert_file_path,
893 const char *ca_cert_dir_path = nullptr);
894
895 void set_ca_cert_store(X509_STORE *ca_cert_store);
896
897 void enable_server_certificate_verification(bool enabled);
898
899 long get_openssl_verify_result() const;
900
901 SSL_CTX *ssl_context() const;
902
903 private:
904 bool process_and_close_socket(
905 socket_t sock, size_t request_count,
906 std::function<bool(Stream &strm, bool last_connection,
907 bool &connection_close)>
908 callback) override;
909 bool is_ssl() const override;
910
911 bool verify_host(X509 *server_cert) const;
912 bool verify_host_with_subject_alt_name(X509 *server_cert) const;
913 bool verify_host_with_common_name(X509 *server_cert) const;
914 bool check_host_name(const char *pattern, size_t pattern_len) const;
915
916 SSL_CTX *ctx_;
917 std::mutex ctx_mutex_;
918 std::vector<std::string> host_components_;
919
920 std::string ca_cert_file_path_;
921 std::string ca_cert_dir_path_;
922 X509_STORE *ca_cert_store_ = nullptr;
923 bool server_certificate_verification_ = false;
924 long verify_result_ = 0;
925 };
926 #endif
927
928 // ----------------------------------------------------------------------------
929
930 /*
931 * Implementation
932 */
933
934 namespace detail {
935
936 inline bool is_hex(char c, int &v) {
937 if (0x20 <= c && isdigit(c)) {
938 v = c - '0';
939 return true;
940 } else if ('A' <= c && c <= 'F') {
941 v = c - 'A' + 10;
942 return true;
943 } else if ('a' <= c && c <= 'f') {
944 v = c - 'a' + 10;
945 return true;
946 }
947 return false;
948 }
949
950 inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
951 int &val) {
952 if (i >= s.size()) { return false; }
953
954 val = 0;
955 for (; cnt; i++, cnt--) {
956 if (!s[i]) { return false; }
957 int v = 0;
958 if (is_hex(s[i], v)) {
959 val = val * 16 + v;
960 } else {
961 return false;
962 }
963 }
964 return true;
965 }
966
967 inline std::string from_i_to_hex(size_t n) {
968 const char *charset = "0123456789abcdef";
969 std::string ret;
970 do {
971 ret = charset[n & 15] + ret;
972 n >>= 4;
973 } while (n > 0);
974 return ret;
975 }
976
977 inline size_t to_utf8(int code, char *buff) {
978 if (code < 0x0080) {
979 buff[0] = (code & 0x7F);
980 return 1;
981 } else if (code < 0x0800) {
982 buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
983 buff[1] = static_cast<char>(0x80 | (code & 0x3F));
984 return 2;
985 } else if (code < 0xD800) {
986 buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
987 buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
988 buff[2] = static_cast<char>(0x80 | (code & 0x3F));
989 return 3;
990 } else if (code < 0xE000) { // D800 - DFFF is invalid...
991 return 0;
992 } else if (code < 0x10000) {
993 buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
994 buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
995 buff[2] = static_cast<char>(0x80 | (code & 0x3F));
996 return 3;
997 } else if (code < 0x110000) {
998 buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
999 buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
1000 buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
1001 buff[3] = static_cast<char>(0x80 | (code & 0x3F));
1002 return 4;
1003 }
1004
1005 // NOTREACHED
1006 return 0;
1007 }
1008
1009 // NOTE: This code came up with the following stackoverflow post:
1010 // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
1011 inline std::string base64_encode(const std::string &in) {
1012 static const auto lookup =
1013 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1014
1015 std::string out;
1016 out.reserve(in.size());
1017
1018 int val = 0;
1019 int valb = -6;
1020
1021 for (auto c : in) {
1022 val = (val << 8) + static_cast<uint8_t>(c);
1023 valb += 8;
1024 while (valb >= 0) {
1025 out.push_back(lookup[(val >> valb) & 0x3F]);
1026 valb -= 6;
1027 }
1028 }
1029
1030 if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
1031
1032 while (out.size() % 4) {
1033 out.push_back('=');
1034 }
1035
1036 return out;
1037 }
1038
1039 inline bool is_file(const std::string &path) {
1040 struct stat st;
1041 return stat(path.c_str(), &st) >= 0 && S_ISREG(st.st_mode);
1042 }
1043
1044 inline bool is_dir(const std::string &path) {
1045 struct stat st;
1046 return stat(path.c_str(), &st) >= 0 && S_ISDIR(st.st_mode);
1047 }
1048
1049 inline bool is_valid_path(const std::string &path) {
1050 size_t level = 0;
1051 size_t i = 0;
1052
1053 // Skip slash
1054 while (i < path.size() && path[i] == '/') {
1055 i++;
1056 }
1057
1058 while (i < path.size()) {
1059 // Read component
1060 auto beg = i;
1061 while (i < path.size() && path[i] != '/') {
1062 i++;
1063 }
1064
1065 auto len = i - beg;
1066 assert(len > 0);
1067
1068 if (!path.compare(beg, len, ".")) {
1069 ;
1070 } else if (!path.compare(beg, len, "..")) {
1071 if (level == 0) { return false; }
1072 level--;
1073 } else {
1074 level++;
1075 }
1076
1077 // Skip slash
1078 while (i < path.size() && path[i] == '/') {
1079 i++;
1080 }
1081 }
1082
1083 return true;
1084 }
1085
1086 inline void read_file(const std::string &path, std::string &out) {
1087 std::ifstream fs(path, std::ios_base::binary);
1088 fs.seekg(0, std::ios_base::end);
1089 auto size = fs.tellg();
1090 fs.seekg(0);
1091 out.resize(static_cast<size_t>(size));
1092 fs.read(&out[0], size);
1093 }
1094
1095 inline std::string file_extension(const std::string &path) {
1096 std::smatch m;
1097 static auto re = std::regex("\\.([a-zA-Z0-9]+)$");
1098 if (std::regex_search(path, m, re)) { return m[1].str(); }
1099 return std::string();
1100 }
1101
1102 template <class Fn> void split(const char *b, const char *e, char d, Fn fn) {
1103 int i = 0;
1104 int beg = 0;
1105
1106 while (e ? (b + i != e) : (b[i] != '\0')) {
1107 if (b[i] == d) {
1108 fn(&b[beg], &b[i]);
1109 beg = i + 1;
1110 }
1111 i++;
1112 }
1113
1114 if (i) { fn(&b[beg], &b[i]); }
1115 }
1116
1117 // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
1118 // to store data. The call can set memory on stack for performance.
1119 class stream_line_reader {
1120 public:
1121 stream_line_reader(Stream &strm, char *fixed_buffer, size_t fixed_buffer_size)
1122 : strm_(strm), fixed_buffer_(fixed_buffer),
1123 fixed_buffer_size_(fixed_buffer_size) {}
1124
1125 const char *ptr() const {
1126 if (glowable_buffer_.empty()) {
1127 return fixed_buffer_;
1128 } else {
1129 return glowable_buffer_.data();
1130 }
1131 }
1132
1133 size_t size() const {
1134 if (glowable_buffer_.empty()) {
1135 return fixed_buffer_used_size_;
1136 } else {
1137 return glowable_buffer_.size();
1138 }
1139 }
1140
1141 bool end_with_crlf() const {
1142 auto end = ptr() + size();
1143 return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
1144 }
1145
1146 bool getline() {
1147 fixed_buffer_used_size_ = 0;
1148 glowable_buffer_.clear();
1149
1150 for (size_t i = 0;; i++) {
1151 char byte;
1152 auto n = strm_.read(&byte, 1);
1153
1154 if (n < 0) {
1155 return false;
1156 } else if (n == 0) {
1157 if (i == 0) {
1158 return false;
1159 } else {
1160 break;
1161 }
1162 }
1163
1164 append(byte);
1165
1166 if (byte == '\n') { break; }
1167 }
1168
1169 return true;
1170 }
1171
1172 private:
1173 void append(char c) {
1174 if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
1175 fixed_buffer_[fixed_buffer_used_size_++] = c;
1176 fixed_buffer_[fixed_buffer_used_size_] = '\0';
1177 } else {
1178 if (glowable_buffer_.empty()) {
1179 assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
1180 glowable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
1181 }
1182 glowable_buffer_ += c;
1183 }
1184 }
1185
1186 Stream &strm_;
1187 char *fixed_buffer_;
1188 const size_t fixed_buffer_size_;
1189 size_t fixed_buffer_used_size_ = 0;
1190 std::string glowable_buffer_;
1191 };
1192
1193 inline int close_socket(socket_t sock) {
1194 #ifdef _WIN32
1195 return closesocket(sock);
1196 #else
1197 return close(sock);
1198 #endif
1199 }
1200
1201 template <typename T>
1202 inline ssize_t handle_EINTR(T fn) {
1203 ssize_t res = false;
1204 while (true) {
1205 res = fn();
1206 if (res < 0 && errno == EINTR) {
1207 continue;
1208 }
1209 break;
1210 }
1211 return res;
1212 }
1213
1214 #define HANDLE_EINTR(method, ...) (handle_EINTR([&]() { return method(__VA_ARGS__); }))
1215
1216 inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
1217 #ifdef CPPHTTPLIB_USE_POLL
1218 struct pollfd pfd_read;
1219 pfd_read.fd = sock;
1220 pfd_read.events = POLLIN;
1221
1222 auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
1223
1224 return HANDLE_EINTR(poll, &pfd_read, 1, timeout);
1225 #else
1226 fd_set fds;
1227 FD_ZERO(&fds);
1228 FD_SET(sock, &fds);
1229
1230 timeval tv;
1231 tv.tv_sec = static_cast<long>(sec);
1232 tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
1233
1234 return HANDLE_EINTR(select, static_cast<int>(sock + 1), &fds, nullptr, nullptr, &tv);
1235 #endif
1236 }
1237
1238 inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
1239 #ifdef CPPHTTPLIB_USE_POLL
1240 struct pollfd pfd_read;
1241 pfd_read.fd = sock;
1242 pfd_read.events = POLLOUT;
1243
1244 auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
1245
1246 return HANDLE_EINTR(poll, &pfd_read, 1, timeout);
1247 #else
1248 fd_set fds;
1249 FD_ZERO(&fds);
1250 FD_SET(sock, &fds);
1251
1252 timeval tv;
1253 tv.tv_sec = static_cast<long>(sec);
1254 tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
1255
1256 return HANDLE_EINTR(select, static_cast<int>(sock + 1), nullptr, &fds, nullptr, &tv);
1257 #endif
1258 }
1259
1260 inline bool wait_until_socket_is_ready(socket_t sock, time_t sec, time_t usec) {
1261 #ifdef CPPHTTPLIB_USE_POLL
1262 struct pollfd pfd_read;
1263 pfd_read.fd = sock;
1264 pfd_read.events = POLLIN | POLLOUT;
1265
1266 auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
1267
1268 auto poll_res = HANDLE_EINTR(poll, &pfd_read, 1, timeout);
1269 if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
1270 int error = 0;
1271 socklen_t len = sizeof(error);
1272 auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
1273 reinterpret_cast<char *>(&error), &len);
1274 return res >= 0 && !error;
1275 }
1276 return false;
1277 #else
1278 fd_set fdsr;
1279 FD_ZERO(&fdsr);
1280 FD_SET(sock, &fdsr);
1281
1282 auto fdsw = fdsr;
1283 auto fdse = fdsr;
1284
1285 timeval tv;
1286 tv.tv_sec = static_cast<long>(sec);
1287 tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
1288
1289 if (HANDLE_EINTR(select, static_cast<int>(sock + 1), &fdsr, &fdsw, &fdse, &tv) > 0 &&
1290 (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) {
1291 int error = 0;
1292 socklen_t len = sizeof(error);
1293 return getsockopt(sock, SOL_SOCKET, SO_ERROR,
1294 reinterpret_cast<char *>(&error), &len) >= 0 &&
1295 !error;
1296 }
1297 return false;
1298 #endif
1299 }
1300
1301 class SocketStream : public Stream {
1302 public:
1303 SocketStream(socket_t sock, time_t read_timeout_sec,
1304 time_t read_timeout_usec);
1305 ~SocketStream() override;
1306
1307 bool is_readable() const override;
1308 bool is_writable() const override;
1309 ssize_t read(char *ptr, size_t size) override;
1310 ssize_t write(const char *ptr, size_t size) override;
1311 void get_remote_ip_and_port(std::string &ip, int &port) const override;
1312
1313 private:
1314 socket_t sock_;
1315 time_t read_timeout_sec_;
1316 time_t read_timeout_usec_;
1317 };
1318
1319 #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
1320 class SSLSocketStream : public Stream {
1321 public:
1322 SSLSocketStream(socket_t sock, SSL *ssl, time_t read_timeout_sec,
1323 time_t read_timeout_usec);
1324 ~SSLSocketStream() override;
1325
1326 bool is_readable() const override;
1327 bool is_writable() const override;
1328 ssize_t read(char *ptr, size_t size) override;
1329 ssize_t write(const char *ptr, size_t size) override;
1330 void get_remote_ip_and_port(std::string &ip, int &port) const override;
1331
1332 private:
1333 socket_t sock_;
1334 SSL *ssl_;
1335 time_t read_timeout_sec_;
1336 time_t read_timeout_usec_;
1337 };
1338 #endif
1339
1340 class BufferStream : public Stream {
1341 public:
1342 BufferStream() = default;
1343 ~BufferStream() override = default;
1344
1345 bool is_readable() const override;
1346 bool is_writable() const override;
1347 ssize_t read(char *ptr, size_t size) override;
1348 ssize_t write(const char *ptr, size_t size) override;
1349 void get_remote_ip_and_port(std::string &ip, int &port) const override;
1350
1351 const std::string &get_buffer() const;
1352
1353 private:
1354 std::string buffer;
1355 size_t position = 0;
1356 };
1357
1358 template <typename T>
1359 inline bool process_socket(bool is_client_request, socket_t sock,
1360 size_t keep_alive_max_count, time_t read_timeout_sec,
1361 time_t read_timeout_usec, T callback) {
1362 assert(keep_alive_max_count > 0);
1363
1364 auto ret = false;
1365
1366 if (keep_alive_max_count > 1) {
1367 auto count = keep_alive_max_count;
1368 while (count > 0 &&
1369 (is_client_request ||
1370 select_read(sock, CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND,
1371 CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND) > 0)) {
1372 SocketStream strm(sock, read_timeout_sec, read_timeout_usec);
1373 auto last_connection = count == 1;
1374 auto connection_close = false;
1375
1376 ret = callback(strm, last_connection, connection_close);
1377 if (!ret || connection_close) { break; }
1378
1379 count--;
1380 }
1381 } else { // keep_alive_max_count is 0 or 1
1382 SocketStream strm(sock, read_timeout_sec, read_timeout_usec);
1383 auto dummy_connection_close = false;
1384 ret = callback(strm, true, dummy_connection_close);
1385 }
1386
1387 return ret;
1388 }
1389
1390 template <typename T>
1391 inline bool process_and_close_socket(bool is_client_request, socket_t sock,
1392 size_t keep_alive_max_count,
1393 time_t read_timeout_sec,
1394 time_t read_timeout_usec, T callback) {
1395 auto ret = process_socket(is_client_request, sock, keep_alive_max_count,
1396 read_timeout_sec, read_timeout_usec, callback);
1397 close_socket(sock);
1398 return ret;
1399 }
1400
1401 inline int shutdown_socket(socket_t sock) {
1402 #ifdef _WIN32
1403 return shutdown(sock, SD_BOTH);
1404 #else
1405 return shutdown(sock, SHUT_RDWR);
1406 #endif
1407 }
1408
1409 template <typename Fn>
1410 socket_t create_socket(const char *host, int port, Fn fn,
1411 int socket_flags = 0) {
1412 #ifdef _WIN32
1413 #define SO_SYNCHRONOUS_NONALERT 0x20
1414 #define SO_OPENTYPE 0x7008
1415
1416 int opt = SO_SYNCHRONOUS_NONALERT;
1417 setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char *)&opt,
1418 sizeof(opt));
1419 #endif
1420
1421 // Get address info
1422 struct addrinfo hints;
1423 struct addrinfo *result;
1424
1425 memset(&hints, 0, sizeof(struct addrinfo));
1426 hints.ai_family = AF_UNSPEC;
1427 hints.ai_socktype = SOCK_STREAM;
1428 hints.ai_flags = socket_flags;
1429 hints.ai_protocol = 0;
1430
1431 auto service = std::to_string(port);
1432
1433 if (getaddrinfo(host, service.c_str(), &hints, &result)) {
1434 return INVALID_SOCKET;
1435 }
1436
1437 for (auto rp = result; rp; rp = rp->ai_next) {
1438 // Create a socket
1439 #ifdef _WIN32
1440 auto sock = WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol,
1441 nullptr, 0, WSA_FLAG_NO_HANDLE_INHERIT);
1442 /**
1443 * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
1444 * and above the socket creation fails on older Windows Systems.
1445 *
1446 * Let's try to create a socket the old way in this case.
1447 *
1448 * Reference:
1449 * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
1450 *
1451 * WSA_FLAG_NO_HANDLE_INHERIT:
1452 * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
1453 * SP1, and later
1454 *
1455 */
1456 if (sock == INVALID_SOCKET) {
1457 sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
1458 }
1459 #else
1460 auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
1461 #endif
1462 if (sock == INVALID_SOCKET) { continue; }
1463
1464 #ifndef _WIN32
1465 if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) { continue; }
1466 #endif
1467
1468 // Make 'reuse address' option available
1469 int yes = 1;
1470 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char *>(&yes),
1471 sizeof(yes));
1472 #ifdef SO_REUSEPORT
1473 setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, reinterpret_cast<char *>(&yes),
1474 sizeof(yes));
1475 #endif
1476
1477 // bind or connect
1478 if (fn(sock, *rp)) {
1479 freeaddrinfo(result);
1480 return sock;
1481 }
1482
1483 close_socket(sock);
1484 }
1485
1486 freeaddrinfo(result);
1487 return INVALID_SOCKET;
1488 }
1489
1490 inline void set_nonblocking(socket_t sock, bool nonblocking) {
1491 #ifdef _WIN32
1492 auto flags = nonblocking ? 1UL : 0UL;
1493 ioctlsocket(sock, FIONBIO, &flags);
1494 #else
1495 auto flags = fcntl(sock, F_GETFL, 0);
1496 fcntl(sock, F_SETFL,
1497 nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
1498 #endif
1499 }
1500
1501 inline bool is_connection_error() {
1502 #ifdef _WIN32
1503 return WSAGetLastError() != WSAEWOULDBLOCK;
1504 #else
1505 return errno != EINPROGRESS;
1506 #endif
1507 }
1508
1509 inline bool bind_ip_address(socket_t sock, const char *host) {
1510 struct addrinfo hints;
1511 struct addrinfo *result;
1512
1513 memset(&hints, 0, sizeof(struct addrinfo));
1514 hints.ai_family = AF_UNSPEC;
1515 hints.ai_socktype = SOCK_STREAM;
1516 hints.ai_protocol = 0;
1517
1518 if (getaddrinfo(host, "0", &hints, &result)) { return false; }
1519
1520 auto ret = false;
1521 for (auto rp = result; rp; rp = rp->ai_next) {
1522 const auto &ai = *rp;
1523 if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
1524 ret = true;
1525 break;
1526 }
1527 }
1528
1529 freeaddrinfo(result);
1530 return ret;
1531 }
1532
1533 #ifndef _WIN32
1534 inline std::string if2ip(const std::string &ifn) {
1535 struct ifaddrs *ifap;
1536 getifaddrs(&ifap);
1537 for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
1538 if (ifa->ifa_addr && ifn == ifa->ifa_name) {
1539 if (ifa->ifa_addr->sa_family == AF_INET) {
1540 auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
1541 char buf[INET_ADDRSTRLEN];
1542 if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
1543 freeifaddrs(ifap);
1544 return std::string(buf, INET_ADDRSTRLEN);
1545 }
1546 }
1547 }
1548 }
1549 freeifaddrs(ifap);
1550 return std::string();
1551 }
1552 #endif
1553
1554 inline socket_t create_client_socket(const char *host, int port,
1555 time_t timeout_sec,
1556 const std::string &intf) {
1557 return create_socket(
1558 host, port, [&](socket_t sock, struct addrinfo &ai) -> bool {
1559 if (!intf.empty()) {
1560 #ifndef _WIN32
1561 auto ip = if2ip(intf);
1562 if (ip.empty()) { ip = intf; }
1563 if (!bind_ip_address(sock, ip.c_str())) { return false; }
1564 #endif
1565 }
1566
1567 set_nonblocking(sock, true);
1568
1569 auto ret =
1570 ::connect(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
1571 if (ret < 0) {
1572 if (is_connection_error() ||
1573 !wait_until_socket_is_ready(sock, timeout_sec, 0)) {
1574 close_socket(sock);
1575 return false;
1576 }
1577 }
1578
1579 set_nonblocking(sock, false);
1580 return true;
1581 });
1582 }
1583
1584 inline void get_remote_ip_and_port(const struct sockaddr_storage &addr,
1585 socklen_t addr_len, std::string &ip,
1586 int &port) {
1587 if (addr.ss_family == AF_INET) {
1588 port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
1589 } else if (addr.ss_family == AF_INET6) {
1590 port =
1591 ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
1592 }
1593
1594 std::array<char, NI_MAXHOST> ipstr{};
1595 if (!getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
1596 ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
1597 0, NI_NUMERICHOST)) {
1598 ip = ipstr.data();
1599 }
1600 }
1601
1602 inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
1603 struct sockaddr_storage addr;
1604 socklen_t addr_len = sizeof(addr);
1605
1606 if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
1607 &addr_len)) {
1608 get_remote_ip_and_port(addr, addr_len, ip, port);
1609 }
1610 }
1611
1612 inline const char *
1613 find_content_type(const std::string &path,
1614 const std::map<std::string, std::string> &user_data) {
1615 auto ext = file_extension(path);
1616
1617 auto it = user_data.find(ext);
1618 if (it != user_data.end()) { return it->second.c_str(); }
1619
1620 if (ext == "txt") {
1621 return "text/plain";
1622 } else if (ext == "html" || ext == "htm") {
1623 return "text/html";
1624 } else if (ext == "css") {
1625 return "text/css";
1626 } else if (ext == "jpeg" || ext == "jpg") {
1627 return "image/jpg";
1628 } else if (ext == "png") {
1629 return "image/png";
1630 } else if (ext == "gif") {
1631 return "image/gif";
1632 } else if (ext == "svg") {
1633 return "image/svg+xml";
1634 } else if (ext == "ico") {
1635 return "image/x-icon";
1636 } else if (ext == "json") {
1637 return "application/json";
1638 } else if (ext == "pdf") {
1639 return "application/pdf";
1640 } else if (ext == "js") {
1641 return "application/javascript";
1642 } else if (ext == "wasm") {
1643 return "application/wasm";
1644 } else if (ext == "xml") {
1645 return "application/xml";
1646 } else if (ext == "xhtml") {
1647 return "application/xhtml+xml";
1648 }
1649 return nullptr;
1650 }
1651
1652 inline const char *status_message(int status) {
1653 switch (status) {
1654 case 100: return "Continue";
1655 case 101: return "Switching Protocol";
1656 case 102: return "Processing";
1657 case 103: return "Early Hints";
1658 case 200: return "OK";
1659 case 201: return "Created";
1660 case 202: return "Accepted";
1661 case 203: return "Non-Authoritative Information";
1662 case 204: return "No Content";
1663 case 205: return "Reset Content";
1664 case 206: return "Partial Content";
1665 case 207: return "Multi-Status";
1666 case 208: return "Already Reported";
1667 case 226: return "IM Used";
1668 case 300: return "Multiple Choice";
1669 case 301: return "Moved Permanently";
1670 case 302: return "Found";
1671 case 303: return "See Other";
1672 case 304: return "Not Modified";
1673 case 305: return "Use Proxy";
1674 case 306: return "unused";
1675 case 307: return "Temporary Redirect";
1676 case 308: return "Permanent Redirect";
1677 case 400: return "Bad Request";
1678 case 401: return "Unauthorized";
1679 case 402: return "Payment Required";
1680 case 403: return "Forbidden";
1681 case 404: return "Not Found";
1682 case 405: return "Method Not Allowed";
1683 case 406: return "Not Acceptable";
1684 case 407: return "Proxy Authentication Required";
1685 case 408: return "Request Timeout";
1686 case 409: return "Conflict";
1687 case 410: return "Gone";
1688 case 411: return "Length Required";
1689 case 412: return "Precondition Failed";
1690 case 413: return "Payload Too Large";
1691 case 414: return "URI Too Long";
1692 case 415: return "Unsupported Media Type";
1693 case 416: return "Range Not Satisfiable";
1694 case 417: return "Expectation Failed";
1695 case 418: return "I'm a teapot";
1696 case 421: return "Misdirected Request";
1697 case 422: return "Unprocessable Entity";
1698 case 423: return "Locked";
1699 case 424: return "Failed Dependency";
1700 case 425: return "Too Early";
1701 case 426: return "Upgrade Required";
1702 case 428: return "Precondition Required";
1703 case 429: return "Too Many Requests";
1704 case 431: return "Request Header Fields Too Large";
1705 case 451: return "Unavailable For Legal Reasons";
1706 case 501: return "Not Implemented";
1707 case 502: return "Bad Gateway";
1708 case 503: return "Service Unavailable";
1709 case 504: return "Gateway Timeout";
1710 case 505: return "HTTP Version Not Supported";
1711 case 506: return "Variant Also Negotiates";
1712 case 507: return "Insufficient Storage";
1713 case 508: return "Loop Detected";
1714 case 510: return "Not Extended";
1715 case 511: return "Network Authentication Required";
1716
1717 default:
1718 case 500: return "Internal Server Error";
1719 }
1720 }
1721
1722 #ifdef CPPHTTPLIB_ZLIB_SUPPORT
1723 inline bool can_compress(const std::string &content_type) {
1724 return !content_type.find("text/") || content_type == "image/svg+xml" ||
1725 content_type == "application/javascript" ||
1726 content_type == "application/json" ||
1727 content_type == "application/xml" ||
1728 content_type == "application/xhtml+xml";
1729 }
1730
1731 inline bool compress(std::string &content) {
1732 z_stream strm;
1733 strm.zalloc = Z_NULL;
1734 strm.zfree = Z_NULL;
1735 strm.opaque = Z_NULL;
1736
1737 auto ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
1738 Z_DEFAULT_STRATEGY);
1739 if (ret != Z_OK) { return false; }
1740
1741 strm.avail_in = static_cast<decltype(strm.avail_in)>(content.size());
1742 strm.next_in =
1743 const_cast<Bytef *>(reinterpret_cast<const Bytef *>(content.data()));
1744
1745 std::string compressed;
1746
1747 std::array<char, 16384> buff{};
1748 do {
1749 strm.avail_out = buff.size();
1750 strm.next_out = reinterpret_cast<Bytef *>(buff.data());
1751 ret = deflate(&strm, Z_FINISH);
1752 assert(ret != Z_STREAM_ERROR);
1753 compressed.append(buff.data(), buff.size() - strm.avail_out);
1754 } while (strm.avail_out == 0);
1755
1756 assert(ret == Z_STREAM_END);
1757 assert(strm.avail_in == 0);
1758
1759 content.swap(compressed);
1760
1761 deflateEnd(&strm);
1762 return true;
1763 }
1764
1765 class decompressor {
1766 public:
1767 decompressor() {
1768 std::memset(&strm, 0, sizeof(strm));
1769 strm.zalloc = Z_NULL;
1770 strm.zfree = Z_NULL;
1771 strm.opaque = Z_NULL;
1772
1773 // 15 is the value of wbits, which should be at the maximum possible value
1774 // to ensure that any gzip stream can be decoded. The offset of 32 specifies
1775 // that the stream type should be automatically detected either gzip or
1776 // deflate.
1777 is_valid_ = inflateInit2(&strm, 32 + 15) == Z_OK;
1778 }
1779
1780 ~decompressor() { inflateEnd(&strm); }
1781
1782 bool is_valid() const { return is_valid_; }
1783
1784 template <typename T>
1785 bool decompress(const char *data, size_t data_length, T callback) {
1786 int ret = Z_OK;
1787
1788 strm.avail_in = static_cast<decltype(strm.avail_in)>(data_length);
1789 strm.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
1790
1791 std::array<char, 16384> buff{};
1792 do {
1793 strm.avail_out = buff.size();
1794 strm.next_out = reinterpret_cast<Bytef *>(buff.data());
1795
1796 ret = inflate(&strm, Z_NO_FLUSH);
1797 assert(ret != Z_STREAM_ERROR);
1798 switch (ret) {
1799 case Z_NEED_DICT:
1800 case Z_DATA_ERROR:
1801 case Z_MEM_ERROR: inflateEnd(&strm); return false;
1802 }
1803
1804 if (!callback(buff.data(), buff.size() - strm.avail_out)) {
1805 return false;
1806 }
1807 } while (strm.avail_out == 0);
1808
1809 return ret == Z_OK || ret == Z_STREAM_END;
1810 }
1811
1812 private:
1813 bool is_valid_;
1814 z_stream strm;
1815 };
1816 #endif
1817
1818 inline bool has_header(const Headers &headers, const char *key) {
1819 return headers.find(key) != headers.end();
1820 }
1821
1822 inline const char *get_header_value(const Headers &headers, const char *key,
1823 size_t id = 0, const char *def = nullptr) {
1824 auto it = headers.find(key);
1825 std::advance(it, static_cast<int>(id));
1826 if (it != headers.end()) { return it->second.c_str(); }
1827 return def;
1828 }
1829
1830 inline uint64_t get_header_value_uint64(const Headers &headers, const char *key,
1831 uint64_t def = 0) {
1832 auto it = headers.find(key);
1833 if (it != headers.end()) {
1834 return std::strtoull(it->second.data(), nullptr, 10);
1835 }
1836 return def;
1837 }
1838
1839 inline bool read_headers(Stream &strm, Headers &headers) {
1840 const auto bufsiz = 2048;
1841 char buf[bufsiz];
1842 stream_line_reader line_reader(strm, buf, bufsiz);
1843
1844 for (;;) {
1845 if (!line_reader.getline()) { return false; }
1846
1847 // Check if the line ends with CRLF.
1848 if (line_reader.end_with_crlf()) {
1849 // Blank line indicates end of headers.
1850 if (line_reader.size() == 2) { break; }
1851 } else {
1852 continue; // Skip invalid line.
1853 }
1854
1855 // Skip trailing spaces and tabs.
1856 auto end = line_reader.ptr() + line_reader.size() - 2;
1857 while (line_reader.ptr() < end && (end[-1] == ' ' || end[-1] == '\t')) {
1858 end--;
1859 }
1860
1861 // Horizontal tab and ' ' are considered whitespace and are ignored when on
1862 // the left or right side of the header value:
1863 // - https://stackoverflow.com/questions/50179659/
1864 // - https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html
1865 static const std::regex re(R"(([^:]+):[\t ]*([^\t ].*))");
1866
1867 std::cmatch m;
1868 if (std::regex_match(line_reader.ptr(), end, m, re)) {
1869 auto key = std::string(m[1]);
1870 auto val = std::string(m[2]);
1871 headers.emplace(key, val);
1872 }
1873 }
1874
1875 return true;
1876 }
1877
1878 inline bool read_content_with_length(Stream &strm, uint64_t len,
1879 Progress progress, ContentReceiver out) {
1880 char buf[CPPHTTPLIB_RECV_BUFSIZ];
1881
1882 uint64_t r = 0;
1883 while (r < len) {
1884 auto read_len = static_cast<size_t>(len - r);
1885 auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
1886 if (n <= 0) { return false; }
1887
1888 if (!out(buf, static_cast<size_t>(n))) { return false; }
1889
1890 r += static_cast<uint64_t>(n);
1891
1892 if (progress) {
1893 if (!progress(r, len)) { return false; }
1894 }
1895 }
1896
1897 return true;
1898 }
1899
1900 inline void skip_content_with_length(Stream &strm, uint64_t len) {
1901 char buf[CPPHTTPLIB_RECV_BUFSIZ];
1902 uint64_t r = 0;
1903 while (r < len) {
1904 auto read_len = static_cast<size_t>(len - r);
1905 auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
1906 if (n <= 0) { return; }
1907 r += static_cast<uint64_t>(n);
1908 }
1909 }
1910
1911 inline bool read_content_without_length(Stream &strm, ContentReceiver out) {
1912 char buf[CPPHTTPLIB_RECV_BUFSIZ];
1913 for (;;) {
1914 auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
1915 if (n < 0) {
1916 return false;
1917 } else if (n == 0) {
1918 return true;
1919 }
1920 if (!out(buf, static_cast<size_t>(n))) { return false; }
1921 }
1922
1923 return true;
1924 }
1925
1926 inline bool read_content_chunked(Stream &strm, ContentReceiver out) {
1927 const auto bufsiz = 16;
1928 char buf[bufsiz];
1929
1930 stream_line_reader line_reader(strm, buf, bufsiz);
1931
1932 if (!line_reader.getline()) { return false; }
1933
1934 unsigned long chunk_len;
1935 while (true) {
1936 char *end_ptr;
1937
1938 chunk_len = std::strtoul(line_reader.ptr(), &end_ptr, 16);
1939
1940 if (end_ptr == line_reader.ptr()) { return false; }
1941 if (chunk_len == ULONG_MAX) { return false; }
1942
1943 if (chunk_len == 0) { break; }
1944
1945 if (!read_content_with_length(strm, chunk_len, nullptr, out)) {
1946 return false;
1947 }
1948
1949 if (!line_reader.getline()) { return false; }
1950
1951 if (strcmp(line_reader.ptr(), "\r\n")) { break; }
1952
1953 if (!line_reader.getline()) { return false; }
1954 }
1955
1956 if (chunk_len == 0) {
1957 // Reader terminator after chunks
1958 if (!line_reader.getline() || strcmp(line_reader.ptr(), "\r\n"))
1959 return false;
1960 }
1961
1962 return true;
1963 }
1964
1965 inline bool is_chunked_transfer_encoding(const Headers &headers) {
1966 return !strcasecmp(get_header_value(headers, "Transfer-Encoding", 0, ""),
1967 "chunked");
1968 }
1969
1970 template <typename T>
1971 bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
1972 Progress progress, ContentReceiver receiver) {
1973
1974 ContentReceiver out = [&](const char *buf, size_t n) {
1975 return receiver(buf, n);
1976 };
1977
1978 #ifdef CPPHTTPLIB_ZLIB_SUPPORT
1979 decompressor decompressor;
1980
1981 std::string content_encoding = x.get_header_value("Content-Encoding");
1982 if (content_encoding.find("gzip") != std::string::npos ||
1983 content_encoding.find("deflate") != std::string::npos) {
1984 if (!decompressor.is_valid()) {
1985 status = 500;
1986 return false;
1987 }
1988
1989 out = [&](const char *buf, size_t n) {
1990 return decompressor.decompress(
1991 buf, n, [&](const char *buf, size_t n) { return receiver(buf, n); });
1992 };
1993 }
1994 #else
1995 if (x.get_header_value("Content-Encoding") == "gzip") {
1996 status = 415;
1997 return false;
1998 }
1999 #endif
2000
2001 auto ret = true;
2002 auto exceed_payload_max_length = false;
2003
2004 if (is_chunked_transfer_encoding(x.headers)) {
2005 ret = read_content_chunked(strm, out);
2006 } else if (!has_header(x.headers, "Content-Length")) {
2007 ret = read_content_without_length(strm, out);
2008 } else {
2009 auto len = get_header_value_uint64(x.headers, "Content-Length", 0);
2010 if (len > payload_max_length) {
2011 exceed_payload_max_length = true;
2012 skip_content_with_length(strm, len);
2013 ret = false;
2014 } else if (len > 0) {
2015 ret = read_content_with_length(strm, len, progress, out);
2016 }
2017 }
2018
2019 if (!ret) { status = exceed_payload_max_length ? 413 : 400; }
2020
2021 return ret;
2022 }
2023
2024 template <typename T>
2025 inline ssize_t write_headers(Stream &strm, const T &info,
2026 const Headers &headers) {
2027 ssize_t write_len = 0;
2028 for (const auto &x : info.headers) {
2029 if (x.first == "EXCEPTION_WHAT") { continue; }
2030 auto len =
2031 strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str());
2032 if (len < 0) { return len; }
2033 write_len += len;
2034 }
2035 for (const auto &x : headers) {
2036 auto len =
2037 strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str());
2038 if (len < 0) { return len; }
2039 write_len += len;
2040 }
2041 auto len = strm.write("\r\n");
2042 if (len < 0) { return len; }
2043 write_len += len;
2044 return write_len;
2045 }
2046
2047 inline ssize_t write_content(Stream &strm, ContentProvider content_provider,
2048 size_t offset, size_t length) {
2049 size_t begin_offset = offset;
2050 size_t end_offset = offset + length;
2051 while (offset < end_offset) {
2052 ssize_t written_length = 0;
2053
2054 DataSink data_sink;
2055 data_sink.write = [&](const char *d, size_t l) {
2056 offset += l;
2057 written_length = strm.write(d, l);
2058 };
2059 data_sink.done = [&](void) { written_length = -1; };
2060 data_sink.is_writable = [&](void) { return strm.is_writable(); };
2061
2062 content_provider(offset, end_offset - offset, data_sink);
2063 if (written_length < 0) { return written_length; }
2064 }
2065 return static_cast<ssize_t>(offset - begin_offset);
2066 }
2067
2068 template <typename T>
2069 inline ssize_t write_content_chunked(Stream &strm,
2070 ContentProvider content_provider,
2071 T is_shutting_down) {
2072 size_t offset = 0;
2073 auto data_available = true;
2074 ssize_t total_written_length = 0;
2075 while (data_available && !is_shutting_down()) {
2076 ssize_t written_length = 0;
2077
2078 DataSink data_sink;
2079 data_sink.write = [&](const char *d, size_t l) {
2080 data_available = l > 0;
2081 offset += l;
2082
2083 // Emit chunked response header and footer for each chunk
2084 auto chunk = from_i_to_hex(l) + "\r\n" + std::string(d, l) + "\r\n";
2085 written_length = strm.write(chunk);
2086 };
2087 data_sink.done = [&](void) {
2088 data_available = false;
2089 written_length = strm.write("0\r\n\r\n");
2090 };
2091 data_sink.is_writable = [&](void) { return strm.is_writable(); };
2092
2093 content_provider(offset, 0, data_sink);
2094
2095 if (written_length < 0) { return written_length; }
2096 total_written_length += written_length;
2097 }
2098 return total_written_length;
2099 }
2100
2101 template <typename T>
2102 inline bool redirect(T &cli, const Request &req, Response &res,
2103 const std::string &path) {
2104 Request new_req = req;
2105 new_req.path = path;
2106 new_req.redirect_count -= 1;
2107
2108 if (res.status == 303 && (req.method != "GET" && req.method != "HEAD")) {
2109 new_req.method = "GET";
2110 new_req.body.clear();
2111 new_req.headers.clear();
2112 }
2113
2114 Response new_res;
2115
2116 auto ret = cli.send(new_req, new_res);
2117 if (ret) { res = new_res; }
2118 return ret;
2119 }
2120
2121 inline std::string encode_url(const std::string &s) {
2122 std::string result;
2123
2124 for (size_t i = 0; s[i]; i++) {
2125 switch (s[i]) {
2126 case ' ': result += "%20"; break;
2127 case '+': result += "%2B"; break;
2128 case '\r': result += "%0D"; break;
2129 case '\n': result += "%0A"; break;
2130 case '\'': result += "%27"; break;
2131 case ',': result += "%2C"; break;
2132 // case ':': result += "%3A"; break; // ok? probably...
2133 case ';': result += "%3B"; break;
2134 default:
2135 auto c = static_cast<uint8_t>(s[i]);
2136 if (c >= 0x80) {
2137 result += '%';
2138 char hex[4];
2139 auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
2140 assert(len == 2);
2141 result.append(hex, static_cast<size_t>(len));
2142 } else {
2143 result += s[i];
2144 }
2145 break;
2146 }
2147 }
2148
2149 return result;
2150 }
2151
2152 inline std::string decode_url(const std::string &s,
2153 bool convert_plus_to_space) {
2154 std::string result;
2155
2156 for (size_t i = 0; i < s.size(); i++) {
2157 if (s[i] == '%' && i + 1 < s.size()) {
2158 if (s[i + 1] == 'u') {
2159 int val = 0;
2160 if (from_hex_to_i(s, i + 2, 4, val)) {
2161 // 4 digits Unicode codes
2162 char buff[4];
2163 size_t len = to_utf8(val, buff);
2164 if (len > 0) { result.append(buff, len); }
2165 i += 5; // 'u0000'
2166 } else {
2167 result += s[i];
2168 }
2169 } else {
2170 int val = 0;
2171 if (from_hex_to_i(s, i + 1, 2, val)) {
2172 // 2 digits hex codes
2173 result += static_cast<char>(val);
2174 i += 2; // '00'
2175 } else {
2176 result += s[i];
2177 }
2178 }
2179 } else if (convert_plus_to_space && s[i] == '+') {
2180 result += ' ';
2181 } else {
2182 result += s[i];
2183 }
2184 }
2185
2186 return result;
2187 }
2188
2189 inline std::string params_to_query_str(const Params &params) {
2190 std::string query;
2191
2192 for (auto it = params.begin(); it != params.end(); ++it) {
2193 if (it != params.begin()) { query += "&"; }
2194 query += it->first;
2195 query += "=";
2196 query += detail::encode_url(it->second);
2197 }
2198
2199 return query;
2200 }
2201
2202 inline void parse_query_text(const std::string &s, Params &params) {
2203 split(&s[0], &s[s.size()], '&', [&](const char *b, const char *e) {
2204 std::string key;
2205 std::string val;
2206 split(b, e, '=', [&](const char *b2, const char *e2) {
2207 if (key.empty()) {
2208 key.assign(b2, e2);
2209 } else {
2210 val.assign(b2, e2);
2211 }
2212 });
2213 params.emplace(decode_url(key, true), decode_url(val, true));
2214 });
2215 }
2216
2217 inline bool parse_multipart_boundary(const std::string &content_type,
2218 std::string &boundary) {
2219 auto pos = content_type.find("boundary=");
2220 if (pos == std::string::npos) { return false; }
2221
2222 boundary = content_type.substr(pos + 9);
2223 return true;
2224 }
2225
2226 inline bool parse_range_header(const std::string &s, Ranges &ranges) {
2227 static auto re_first_range = std::regex(R"(bytes=(\d*-\d*(?:,\s*\d*-\d*)*))");
2228 std::smatch m;
2229 if (std::regex_match(s, m, re_first_range)) {
2230 auto pos = static_cast<size_t>(m.position(1));
2231 auto len = static_cast<size_t>(m.length(1));
2232 bool all_valid_ranges = true;
2233 split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
2234 if (!all_valid_ranges) return;
2235 static auto re_another_range = std::regex(R"(\s*(\d*)-(\d*))");
2236 std::cmatch cm;
2237 if (std::regex_match(b, e, cm, re_another_range)) {
2238 ssize_t first = -1;
2239 if (!cm.str(1).empty()) {
2240 first = static_cast<ssize_t>(std::stoll(cm.str(1)));
2241 }
2242
2243 ssize_t last = -1;
2244 if (!cm.str(2).empty()) {
2245 last = static_cast<ssize_t>(std::stoll(cm.str(2)));
2246 }
2247
2248 if (first != -1 && last != -1 && first > last) {
2249 all_valid_ranges = false;
2250 return;
2251 }
2252 ranges.emplace_back(std::make_pair(first, last));
2253 }
2254 });
2255 return all_valid_ranges;
2256 }
2257 return false;
2258 }
2259
2260 class MultipartFormDataParser {
2261 public:
2262 MultipartFormDataParser() = default;
2263
2264 void set_boundary(std::string boundary) { boundary_ = std::move(boundary); }
2265
2266 bool is_valid() const { return is_valid_; }
2267
2268 template <typename T, typename U>
2269 bool parse(const char *buf, size_t n, T content_callback, U header_callback) {
2270 static const std::regex re_content_type(R"(^Content-Type:\s*(.*?)\s*$)",
2271 std::regex_constants::icase);
2272
2273 static const std::regex re_content_disposition(
2274 "^Content-Disposition:\\s*form-data;\\s*name=\"(.*?)\"(?:;\\s*filename="
2275 "\"(.*?)\")?\\s*$",
2276 std::regex_constants::icase);
2277 static const std::string dash_ = "--";
2278 static const std::string crlf_ = "\r\n";
2279
2280 buf_.append(buf, n); // TODO: performance improvement
2281
2282 while (!buf_.empty()) {
2283 switch (state_) {
2284 case 0: { // Initial boundary
2285 auto pattern = dash_ + boundary_ + crlf_;
2286 if (pattern.size() > buf_.size()) { return true; }
2287 auto pos = buf_.find(pattern);
2288 if (pos != 0) {
2289 is_done_ = true;
2290 return false;
2291 }
2292 buf_.erase(0, pattern.size());
2293 off_ += pattern.size();
2294 state_ = 1;
2295 break;
2296 }
2297 case 1: { // New entry
2298 clear_file_info();
2299 state_ = 2;
2300 break;
2301 }
2302 case 2: { // Headers
2303 auto pos = buf_.find(crlf_);
2304 while (pos != std::string::npos) {
2305 // Empty line
2306 if (pos == 0) {
2307 if (!header_callback(file_)) {
2308 is_valid_ = false;
2309 is_done_ = false;
2310 return false;
2311 }
2312 buf_.erase(0, crlf_.size());
2313 off_ += crlf_.size();
2314 state_ = 3;
2315 break;
2316 }
2317
2318 auto header = buf_.substr(0, pos);
2319 {
2320 std::smatch m;
2321 if (std::regex_match(header, m, re_content_type)) {
2322 file_.content_type = m[1];
2323 } else if (std::regex_match(header, m, re_content_disposition)) {
2324 file_.name = m[1];
2325 file_.filename = m[2];
2326 }
2327 }
2328
2329 buf_.erase(0, pos + crlf_.size());
2330 off_ += pos + crlf_.size();
2331 pos = buf_.find(crlf_);
2332 }
2333 break;
2334 }
2335 case 3: { // Body
2336 {
2337 auto pattern = crlf_ + dash_;
2338 if (pattern.size() > buf_.size()) { return true; }
2339
2340 auto pos = buf_.find(pattern);
2341 if (pos == std::string::npos) { pos = buf_.size(); }
2342 if (!content_callback(buf_.data(), pos)) {
2343 is_valid_ = false;
2344 is_done_ = false;
2345 return false;
2346 }
2347
2348 off_ += pos;
2349 buf_.erase(0, pos);
2350 }
2351
2352 {
2353 auto pattern = crlf_ + dash_ + boundary_;
2354 if (pattern.size() > buf_.size()) { return true; }
2355
2356 auto pos = buf_.find(pattern);
2357 if (pos != std::string::npos) {
2358 if (!content_callback(buf_.data(), pos)) {
2359 is_valid_ = false;
2360 is_done_ = false;
2361 return false;
2362 }
2363
2364 off_ += pos + pattern.size();
2365 buf_.erase(0, pos + pattern.size());
2366 state_ = 4;
2367 } else {
2368 if (!content_callback(buf_.data(), pattern.size())) {
2369 is_valid_ = false;
2370 is_done_ = false;
2371 return false;
2372 }
2373
2374 off_ += pattern.size();
2375 buf_.erase(0, pattern.size());
2376 }
2377 }
2378 break;
2379 }
2380 case 4: { // Boundary
2381 if (crlf_.size() > buf_.size()) { return true; }
2382 if (buf_.find(crlf_) == 0) {
2383 buf_.erase(0, crlf_.size());
2384 off_ += crlf_.size();
2385 state_ = 1;
2386 } else {
2387 auto pattern = dash_ + crlf_;
2388 if (pattern.size() > buf_.size()) { return true; }
2389 if (buf_.find(pattern) == 0) {
2390 buf_.erase(0, pattern.size());
2391 off_ += pattern.size();
2392 is_valid_ = true;
2393 state_ = 5;
2394 } else {
2395 is_done_ = true;
2396 return true;
2397 }
2398 }
2399 break;
2400 }
2401 case 5: { // Done
2402 is_valid_ = false;
2403 return false;
2404 }
2405 }
2406 }
2407
2408 return true;
2409 }
2410
2411 private:
2412 void clear_file_info() {
2413 file_.name.clear();
2414 file_.filename.clear();
2415 file_.content_type.clear();
2416 }
2417
2418 std::string boundary_;
2419
2420 std::string buf_;
2421 size_t state_ = 0;
2422 size_t is_valid_ = false;
2423 size_t is_done_ = false;
2424 size_t off_ = 0;
2425 MultipartFormData file_;
2426 };
2427
2428 inline std::string to_lower(const char *beg, const char *end) {
2429 std::string out;
2430 auto it = beg;
2431 while (it != end) {
2432 out += static_cast<char>(::tolower(*it));
2433 it++;
2434 }
2435 return out;
2436 }
2437
2438 inline std::string make_multipart_data_boundary() {
2439 static const char data[] =
2440 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2441
2442 std::random_device seed_gen;
2443 std::mt19937 engine(seed_gen());
2444
2445 std::string result = "--cpp-httplib-multipart-data-";
2446
2447 for (auto i = 0; i < 16; i++) {
2448 result += data[engine() % (sizeof(data) - 1)];
2449 }
2450
2451 return result;
2452 }
2453
2454 inline std::pair<size_t, size_t>
2455 get_range_offset_and_length(const Request &req, size_t content_length,
2456 size_t index) {
2457 auto r = req.ranges[index];
2458
2459 if (r.first == -1 && r.second == -1) {
2460 return std::make_pair(0, content_length);
2461 }
2462
2463 auto slen = static_cast<ssize_t>(content_length);
2464
2465 if (r.first == -1) {
2466 r.first = slen - r.second;
2467 r.second = slen - 1;
2468 }
2469
2470 if (r.second == -1) { r.second = slen - 1; }
2471
2472 return std::make_pair(r.first, r.second - r.first + 1);
2473 }
2474
2475 inline std::string make_content_range_header_field(size_t offset, size_t length,
2476 size_t content_length) {
2477 std::string field = "bytes ";
2478 field += std::to_string(offset);
2479 field += "-";
2480 field += std::to_string(offset + length - 1);
2481 field += "/";
2482 field += std::to_string(content_length);
2483 return field;
2484 }
2485
2486 template <typename SToken, typename CToken, typename Content>
2487 bool process_multipart_ranges_data(const Request &req, Response &res,
2488 const std::string &boundary,
2489 const std::string &content_type,
2490 SToken stoken, CToken ctoken,
2491 Content content) {
2492 for (size_t i = 0; i < req.ranges.size(); i++) {
2493 ctoken("--");
2494 stoken(boundary);
2495 ctoken("\r\n");
2496 if (!content_type.empty()) {
2497 ctoken("Content-Type: ");
2498 stoken(content_type);
2499 ctoken("\r\n");
2500 }
2501
2502 auto offsets = get_range_offset_and_length(req, res.body.size(), i);
2503 auto offset = offsets.first;
2504 auto length = offsets.second;
2505
2506 ctoken("Content-Range: ");
2507 stoken(make_content_range_header_field(offset, length, res.body.size()));
2508 ctoken("\r\n");
2509 ctoken("\r\n");
2510 if (!content(offset, length)) { return false; }
2511 ctoken("\r\n");
2512 }
2513
2514 ctoken("--");
2515 stoken(boundary);
2516 ctoken("--\r\n");
2517
2518 return true;
2519 }
2520
2521 inline std::string make_multipart_ranges_data(const Request &req, Response &res,
2522 const std::string &boundary,
2523 const std::string &content_type) {
2524 std::string data;
2525
2526 process_multipart_ranges_data(
2527 req, res, boundary, content_type,
2528 [&](const std::string &token) { data += token; },
2529 [&](const char *token) { data += token; },
2530 [&](size_t offset, size_t length) {
2531 data += res.body.substr(offset, length);
2532 return true;
2533 });
2534
2535 return data;
2536 }
2537
2538 inline size_t
2539 get_multipart_ranges_data_length(const Request &req, Response &res,
2540 const std::string &boundary,
2541 const std::string &content_type) {
2542 size_t data_length = 0;
2543
2544 process_multipart_ranges_data(
2545 req, res, boundary, content_type,
2546 [&](const std::string &token) { data_length += token.size(); },
2547 [&](const char *token) { data_length += strlen(token); },
2548 [&](size_t /*offset*/, size_t length) {
2549 data_length += length;
2550 return true;
2551 });
2552
2553 return data_length;
2554 }
2555
2556 inline bool write_multipart_ranges_data(Stream &strm, const Request &req,
2557 Response &res,
2558 const std::string &boundary,
2559 const std::string &content_type) {
2560 return process_multipart_ranges_data(
2561 req, res, boundary, content_type,
2562 [&](const std::string &token) { strm.write(token); },
2563 [&](const char *token) { strm.write(token); },
2564 [&](size_t offset, size_t length) {
2565 return write_content(strm, res.content_provider, offset, length) >= 0;
2566 });
2567 }
2568
2569 inline std::pair<size_t, size_t>
2570 get_range_offset_and_length(const Request &req, const Response &res,
2571 size_t index) {
2572 auto r = req.ranges[index];
2573
2574 if (r.second == -1) {
2575 r.second = static_cast<ssize_t>(res.content_length) - 1;
2576 }
2577
2578 return std::make_pair(r.first, r.second - r.first + 1);
2579 }
2580
2581 inline bool expect_content(const Request &req) {
2582 if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
2583 req.method == "PRI" || req.method == "DELETE") {
2584 return true;
2585 }
2586 // TODO: check if Content-Length is set
2587 return false;
2588 }
2589
2590 inline bool has_crlf(const char *s) {
2591 auto p = s;
2592 while (*p) {
2593 if (*p == '\r' || *p == '\n') { return true; }
2594 p++;
2595 }
2596 return false;
2597 }
2598
2599 #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
2600 template <typename CTX, typename Init, typename Update, typename Final>
2601 inline std::string message_digest(const std::string &s, Init init,
2602 Update update, Final final,
2603 size_t digest_length) {
2604 using namespace std;
2605
2606 std::vector<unsigned char> md(digest_length, 0);
2607 CTX ctx;
2608 init(&ctx);
2609 update(&ctx, s.data(), s.size());
2610 final(md.data(), &ctx);
2611
2612 stringstream ss;
2613 for (auto c : md) {
2614 ss << setfill('0') << setw(2) << hex << (unsigned int)c;
2615 }
2616 return ss.str();
2617 }
2618
2619 inline std::string MD5(const std::string &s) {
2620 return message_digest<MD5_CTX>(s, MD5_Init, MD5_Update, MD5_Final,
2621 MD5_DIGEST_LENGTH);
2622 }
2623
2624 inline std::string SHA_256(const std::string &s) {
2625 return message_digest<SHA256_CTX>(s, SHA256_Init, SHA256_Update, SHA256_Final,
2626 SHA256_DIGEST_LENGTH);
2627 }
2628
2629 inline std::string SHA_512(const std::string &s) {
2630 return message_digest<SHA512_CTX>(s, SHA512_Init, SHA512_Update, SHA512_Final,
2631 SHA512_DIGEST_LENGTH);
2632 }
2633 #endif
2634
2635 #ifdef _WIN32
2636 class WSInit {
2637 public:
2638 WSInit() {
2639 WSADATA wsaData;
2640 WSAStartup(0x0002, &wsaData);
2641 }
2642
2643 ~WSInit() { WSACleanup(); }
2644 };
2645
2646 static WSInit wsinit_;
2647 #endif
2648
2649 } // namespace detail
2650
2651 // Header utilities
2652 inline std::pair<std::string, std::string> make_range_header(Ranges ranges) {
2653 std::string field = "bytes=";
2654 auto i = 0;
2655 for (auto r : ranges) {
2656 if (i != 0) { field += ", "; }
2657 if (r.first != -1) { field += std::to_string(r.first); }
2658 field += '-';
2659 if (r.second != -1) { field += std::to_string(r.second); }
2660 i++;
2661 }
2662 return std::make_pair("Range", field);
2663 }
2664
2665 inline std::pair<std::string, std::string>
2666 make_basic_authentication_header(const std::string &username,
2667 const std::string &password,
2668 bool is_proxy = false) {
2669 auto field = "Basic " + detail::base64_encode(username + ":" + password);
2670 auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
2671 return std::make_pair(key, field);
2672 }
2673
2674 #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
2675 inline std::pair<std::string, std::string> make_digest_authentication_header(
2676 const Request &req, const std::map<std::string, std::string> &auth,
2677 size_t cnonce_count, const std::string &cnonce, const std::string &username,
2678 const std::string &password, bool is_proxy = false) {
2679 using namespace std;
2680
2681 string nc;
2682 {
2683 stringstream ss;
2684 ss << setfill('0') << setw(8) << hex << cnonce_count;
2685 nc = ss.str();
2686 }
2687
2688 auto qop = auth.at("qop");
2689 if (qop.find("auth-int") != std::string::npos) {
2690 qop = "auth-int";
2691 } else {
2692 qop = "auth";
2693 }
2694
2695 std::string algo = "MD5";
2696 if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
2697
2698 string response;
2699 {
2700 auto H = algo == "SHA-256"
2701 ? detail::SHA_256
2702 : algo == "SHA-512" ? detail::SHA_512 : detail::MD5;
2703
2704 auto A1 = username + ":" + auth.at("realm") + ":" + password;
2705
2706 auto A2 = req.method + ":" + req.path;
2707 if (qop == "auth-int") { A2 += ":" + H(req.body); }
2708
2709 response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
2710 ":" + qop + ":" + H(A2));
2711 }
2712
2713 auto field = "Digest username=\"hello\", realm=\"" + auth.at("realm") +
2714 "\", nonce=\"" + auth.at("nonce") + "\", uri=\"" + req.path +
2715 "\", algorithm=" + algo + ", qop=" + qop + ", nc=\"" + nc +
2716 "\", cnonce=\"" + cnonce + "\", response=\"" + response + "\"";
2717
2718 auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
2719 return std::make_pair(key, field);
2720 }
2721 #endif
2722
2723 inline bool parse_www_authenticate(const httplib::Response &res,
2724 std::map<std::string, std::string> &auth,
2725 bool is_proxy) {
2726 auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
2727 if (res.has_header(auth_key)) {
2728 static auto re = std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
2729 auto s = res.get_header_value(auth_key);
2730 auto pos = s.find(' ');
2731 if (pos != std::string::npos) {
2732 auto type = s.substr(0, pos);
2733 if (type == "Basic") {
2734 return false;
2735 } else if (type == "Digest") {
2736 s = s.substr(pos + 1);
2737 auto beg = std::sregex_iterator(s.begin(), s.end(), re);
2738 for (auto i = beg; i != std::sregex_iterator(); ++i) {
2739 auto m = *i;
2740 auto key = s.substr(static_cast<size_t>(m.position(1)),
2741 static_cast<size_t>(m.length(1)));
2742 auto val = m.length(2) > 0
2743 ? s.substr(static_cast<size_t>(m.position(2)),
2744 static_cast<size_t>(m.length(2)))
2745 : s.substr(static_cast<size_t>(m.position(3)),
2746 static_cast<size_t>(m.length(3)));
2747 auth[key] = val;
2748 }
2749 return true;
2750 }
2751 }
2752 }
2753 return false;
2754 }
2755
2756 // https://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c/440240#answer-440240
2757 inline std::string random_string(size_t length) {
2758 auto randchar = []() -> char {
2759 const char charset[] = "0123456789"
2760 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2761 "abcdefghijklmnopqrstuvwxyz";
2762 const size_t max_index = (sizeof(charset) - 1);
2763 return charset[static_cast<size_t>(rand()) % max_index];
2764 };
2765 std::string str(length, 0);
2766 std::generate_n(str.begin(), length, randchar);
2767 return str;
2768 }
2769
2770 // Request implementation
2771 inline bool Request::has_header(const char *key) const {
2772 return detail::has_header(headers, key);
2773 }
2774
2775 inline std::string Request::get_header_value(const char *key, size_t id) const {
2776 return detail::get_header_value(headers, key, id, "");
2777 }
2778
2779 inline size_t Request::get_header_value_count(const char *key) const {
2780 auto r = headers.equal_range(key);
2781 return static_cast<size_t>(std::distance(r.first, r.second));
2782 }
2783
2784 inline void Request::set_header(const char *key, const char *val) {
2785 if (!detail::has_crlf(key) && !detail::has_crlf(val)) {
2786 headers.emplace(key, val);
2787 }
2788 }
2789
2790 inline void Request::set_header(const char *key, const std::string &val) {
2791 if (!detail::has_crlf(key) && !detail::has_crlf(val.c_str())) {
2792 headers.emplace(key, val);
2793 }
2794 }
2795
2796 inline bool Request::has_param(const char *key) const {
2797 return params.find(key) != params.end();
2798 }
2799
2800 inline std::string Request::get_param_value(const char *key, size_t id) const {
2801 auto it = params.find(key);
2802 std::advance(it, static_cast<ssize_t>(id));
2803 if (it != params.end()) { return it->second; }
2804 return std::string();
2805 }
2806
2807 inline size_t Request::get_param_value_count(const char *key) const {
2808 auto r = params.equal_range(key);
2809 return static_cast<size_t>(std::distance(r.first, r.second));
2810 }
2811
2812 inline bool Request::is_multipart_form_data() const {
2813 const auto &content_type = get_header_value("Content-Type");
2814 return !content_type.find("multipart/form-data");
2815 }
2816
2817 inline bool Request::has_file(const char *key) const {
2818 return files.find(key) != files.end();
2819 }
2820
2821 inline MultipartFormData Request::get_file_value(const char *key) const {
2822 auto it = files.find(key);
2823 if (it != files.end()) { return it->second; }
2824 return MultipartFormData();
2825 }
2826
2827 // Response implementation
2828 inline bool Response::has_header(const char *key) const {
2829 return headers.find(key) != headers.end();
2830 }
2831
2832 inline std::string Response::get_header_value(const char *key,
2833 size_t id) const {
2834 return detail::get_header_value(headers, key, id, "");
2835 }
2836
2837 inline size_t Response::get_header_value_count(const char *key) const {
2838 auto r = headers.equal_range(key);
2839 return static_cast<size_t>(std::distance(r.first, r.second));
2840 }
2841
2842 inline void Response::set_header(const char *key, const char *val) {
2843 if (!detail::has_crlf(key) && !detail::has_crlf(val)) {
2844 headers.emplace(key, val);
2845 }
2846 }
2847
2848 inline void Response::set_header(const char *key, const std::string &val) {
2849 if (!detail::has_crlf(key) && !detail::has_crlf(val.c_str())) {
2850 headers.emplace(key, val);
2851 }
2852 }
2853
2854 inline void Response::set_redirect(const char *url, int stat) {
2855 if (!detail::has_crlf(url)) {
2856 set_header("Location", url);
2857 if (300 <= stat && stat < 400) {
2858 this->status = stat;
2859 } else {
2860 this->status = 302;
2861 }
2862 }
2863 }
2864
2865 inline void Response::set_content(const char *s, size_t n,
2866 const char *content_type) {
2867 body.assign(s, n);
2868 set_header("Content-Type", content_type);
2869 }
2870
2871 inline void Response::set_content(std::string s, const char *content_type) {
2872 body = std::move(s);
2873 set_header("Content-Type", content_type);
2874 }
2875
2876 inline void Response::set_content_provider(
2877 size_t in_length,
2878 std::function<void(size_t offset, size_t length, DataSink &sink)> provider,
2879 std::function<void()> resource_releaser) {
2880 assert(in_length > 0);
2881 content_length = in_length;
2882 content_provider = [provider](size_t offset, size_t length, DataSink &sink) {
2883 provider(offset, length, sink);
2884 };
2885 content_provider_resource_releaser = resource_releaser;
2886 }
2887
2888 inline void Response::set_chunked_content_provider(
2889 std::function<void(size_t offset, DataSink &sink)> provider,
2890 std::function<void()> resource_releaser) {
2891 content_length = 0;
2892 content_provider = [provider](size_t offset, size_t, DataSink &sink) {
2893 provider(offset, sink);
2894 };
2895 content_provider_resource_releaser = resource_releaser;
2896 }
2897
2898 // Rstream implementation
2899 inline ssize_t Stream::write(const char *ptr) {
2900 return write(ptr, strlen(ptr));
2901 }
2902
2903 inline ssize_t Stream::write(const std::string &s) {
2904 return write(s.data(), s.size());
2905 }
2906
2907 template <typename... Args>
2908 inline ssize_t Stream::write_format(const char *fmt, const Args &... args) {
2909 std::array<char, 2048> buf{};
2910
2911 #if defined(_MSC_VER) && _MSC_VER < 1900
2912 auto sn = _snprintf_s(buf, bufsiz, buf.size() - 1, fmt, args...);
2913 #else
2914 auto sn = snprintf(buf.data(), buf.size() - 1, fmt, args...);
2915 #endif
2916 if (sn <= 0) { return sn; }
2917
2918 auto n = static_cast<size_t>(sn);
2919
2920 if (n >= buf.size() - 1) {
2921 std::vector<char> glowable_buf(buf.size());
2922
2923 while (n >= glowable_buf.size() - 1) {
2924 glowable_buf.resize(glowable_buf.size() * 2);
2925 #if defined(_MSC_VER) && _MSC_VER < 1900
2926 n = static_cast<size_t>(_snprintf_s(&glowable_buf[0], glowable_buf.size(),
2927 glowable_buf.size() - 1, fmt,
2928 args...));
2929 #else
2930 n = static_cast<size_t>(
2931 snprintf(&glowable_buf[0], glowable_buf.size() - 1, fmt, args...));
2932 #endif
2933 }
2934 return write(&glowable_buf[0], n);
2935 } else {
2936 return write(buf.data(), n);
2937 }
2938 }
2939
2940 namespace detail {
2941
2942 // Socket stream implementation
2943 inline SocketStream::SocketStream(socket_t sock, time_t read_timeout_sec,
2944 time_t read_timeout_usec)
2945 : sock_(sock), read_timeout_sec_(read_timeout_sec),
2946 read_timeout_usec_(read_timeout_usec) {}
2947
2948 inline SocketStream::~SocketStream() {}
2949
2950 inline bool SocketStream::is_readable() const {
2951 return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
2952 }
2953
2954 inline bool SocketStream::is_writable() const {
2955 return select_write(sock_, 0, 0) > 0;
2956 }
2957
2958 inline ssize_t SocketStream::read(char *ptr, size_t size) {
2959 if (!is_readable()) { return -1; }
2960
2961 #ifdef _WIN32
2962 if (size > static_cast<size_t>(std::numeric_limits<int>::max())) {
2963 return -1;
2964 }
2965 return recv(sock_, ptr, static_cast<int>(size), 0);
2966 #else
2967 return HANDLE_EINTR(recv, sock_, ptr, size, 0);
2968 #endif
2969 }
2970
2971 inline ssize_t SocketStream::write(const char *ptr, size_t size) {
2972 if (!is_writable()) { return -1; }
2973
2974 #ifdef _WIN32
2975 if (size > static_cast<size_t>(std::numeric_limits<int>::max())) {
2976 return -1;
2977 }
2978 return send(sock_, ptr, static_cast<int>(size), 0);
2979 #else
2980 return HANDLE_EINTR(send, sock_, ptr, size, 0);
2981 #endif
2982 }
2983
2984 inline void SocketStream::get_remote_ip_and_port(std::string &ip,
2985 int &port) const {
2986 return detail::get_remote_ip_and_port(sock_, ip, port);
2987 }
2988
2989 // Buffer stream implementation
2990 inline bool BufferStream::is_readable() const { return true; }
2991
2992 inline bool BufferStream::is_writable() const { return true; }
2993
2994 inline ssize_t BufferStream::read(char *ptr, size_t size) {
2995 #if defined(_MSC_VER) && _MSC_VER < 1900
2996 auto len_read = buffer._Copy_s(ptr, size, size, position);
2997 #else
2998 auto len_read = buffer.copy(ptr, size, position);
2999 #endif
3000 position += static_cast<size_t>(len_read);
3001 return static_cast<ssize_t>(len_read);
3002 }
3003
3004 inline ssize_t BufferStream::write(const char *ptr, size_t size) {
3005 buffer.append(ptr, size);
3006 return static_cast<ssize_t>(size);
3007 }
3008
3009 inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
3010 int & /*port*/) const {}
3011
3012 inline const std::string &BufferStream::get_buffer() const { return buffer; }
3013
3014 } // namespace detail
3015
3016 // HTTP server implementation
3017 inline Server::Server()
3018 : keep_alive_max_count_(CPPHTTPLIB_KEEPALIVE_MAX_COUNT),
3019 read_timeout_sec_(CPPHTTPLIB_READ_TIMEOUT_SECOND),
3020 read_timeout_usec_(CPPHTTPLIB_READ_TIMEOUT_USECOND),
3021 payload_max_length_(CPPHTTPLIB_PAYLOAD_MAX_LENGTH), is_running_(false),
3022 svr_sock_(INVALID_SOCKET) {
3023 #ifndef _WIN32
3024 signal(SIGPIPE, SIG_IGN);
3025 #endif
3026 new_task_queue = [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); };
3027 }
3028
3029 inline Server::~Server() {}
3030
3031 inline Server &Server::Get(const char *pattern, Handler handler) {
3032 get_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
3033 return *this;
3034 }
3035
3036 inline Server &Server::Post(const char *pattern, Handler handler) {
3037 post_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
3038 return *this;
3039 }
3040
3041 inline Server &Server::Post(const char *pattern,
3042 HandlerWithContentReader handler) {
3043 post_handlers_for_content_reader_.push_back(
3044 std::make_pair(std::regex(pattern), handler));
3045 return *this;
3046 }
3047
3048 inline Server &Server::Put(const char *pattern, Handler handler) {
3049 put_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
3050 return *this;
3051 }
3052
3053 inline Server &Server::Put(const char *pattern,
3054 HandlerWithContentReader handler) {
3055 put_handlers_for_content_reader_.push_back(
3056 std::make_pair(std::regex(pattern), handler));
3057 return *this;
3058 }
3059
3060 inline Server &Server::Patch(const char *pattern, Handler handler) {
3061 patch_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
3062 return *this;
3063 }
3064
3065 inline Server &Server::Patch(const char *pattern,
3066 HandlerWithContentReader handler) {
3067 patch_handlers_for_content_reader_.push_back(
3068 std::make_pair(std::regex(pattern), handler));
3069 return *this;
3070 }
3071
3072 inline Server &Server::Delete(const char *pattern, Handler handler) {
3073 delete_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
3074 return *this;
3075 }
3076
3077 inline Server &Server::Delete(const char *pattern,
3078 HandlerWithContentReader handler) {
3079 delete_handlers_for_content_reader_.push_back(
3080 std::make_pair(std::regex(pattern), handler));
3081 return *this;
3082 }
3083
3084 inline Server &Server::Options(const char *pattern, Handler handler) {
3085 options_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
3086 return *this;
3087 }
3088
3089 inline bool Server::set_base_dir(const char *dir, const char *mount_point) {
3090 return set_mount_point(mount_point, dir);
3091 }
3092
3093 inline bool Server::set_mount_point(const char *mount_point, const char *dir) {
3094 if (detail::is_dir(dir)) {
3095 std::string mnt = mount_point ? mount_point : "/";
3096 if (!mnt.empty() && mnt[0] == '/') {
3097 base_dirs_.emplace_back(mnt, dir);
3098 return true;
3099 }
3100 }
3101 return false;
3102 }
3103
3104 inline bool Server::remove_mount_point(const char *mount_point) {
3105 for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
3106 if (it->first == mount_point) {
3107 base_dirs_.erase(it);
3108 return true;
3109 }
3110 }
3111 return false;
3112 }
3113
3114 inline void Server::set_file_extension_and_mimetype_mapping(const char *ext,
3115 const char *mime) {
3116 file_extension_and_mimetype_map_[ext] = mime;
3117 }
3118
3119 inline void Server::set_file_request_handler(Handler handler) {
3120 file_request_handler_ = std::move(handler);
3121 }
3122
3123 inline void Server::set_error_handler(Handler handler) {
3124 error_handler_ = std::move(handler);
3125 }
3126
3127 inline void Server::set_logger(Logger logger) { logger_ = std::move(logger); }
3128
3129 inline void
3130 Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
3131 expect_100_continue_handler_ = std::move(handler);
3132 }
3133
3134 inline void Server::set_keep_alive_max_count(size_t count) {
3135 keep_alive_max_count_ = count;
3136 }
3137
3138 inline void Server::set_read_timeout(time_t sec, time_t usec) {
3139 read_timeout_sec_ = sec;
3140 read_timeout_usec_ = usec;
3141 }
3142
3143 inline void Server::set_payload_max_length(size_t length) {
3144 payload_max_length_ = length;
3145 }
3146
3147 inline bool Server::bind_to_port(const char *host, int port, int socket_flags) {
3148 if (bind_internal(host, port, socket_flags) < 0) return false;
3149 return true;
3150 }
3151 inline int Server::bind_to_any_port(const char *host, int socket_flags) {
3152 return bind_internal(host, 0, socket_flags);
3153 }
3154
3155 inline bool Server::listen_after_bind() { return listen_internal(); }
3156
3157 inline bool Server::listen(const char *host, int port, int socket_flags) {
3158 return bind_to_port(host, port, socket_flags) && listen_internal();
3159 }
3160
3161 inline bool Server::is_running() const { return is_running_; }
3162
3163 inline void Server::stop() {
3164 if (is_running_) {
3165 assert(svr_sock_ != INVALID_SOCKET);
3166 std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
3167 detail::shutdown_socket(sock);
3168 detail::close_socket(sock);
3169 }
3170 }
3171
3172 inline bool Server::parse_request_line(const char *s, Request &req) {
3173 const static std::regex re(
3174 "(GET|HEAD|POST|PUT|DELETE|CONNECT|OPTIONS|TRACE|PATCH|PRI) "
3175 "(([^?]+)(?:\\?(.*?))?) (HTTP/1\\.[01])\r\n");
3176
3177 std::cmatch m;
3178 if (std::regex_match(s, m, re)) {
3179 req.version = std::string(m[5]);
3180 req.method = std::string(m[1]);
3181 req.target = std::string(m[2]);
3182 req.path = detail::decode_url(m[3], false);
3183
3184 // Parse query text
3185 auto len = std::distance(m[4].first, m[4].second);
3186 if (len > 0) { detail::parse_query_text(m[4], req.params); }
3187
3188 return true;
3189 }
3190
3191 return false;
3192 }
3193
3194 inline bool Server::write_response(Stream &strm, bool last_connection,
3195 const Request &req, Response &res) {
3196 assert(res.status != -1);
3197
3198 if (400 <= res.status && error_handler_) { error_handler_(req, res); }
3199
3200 detail::BufferStream bstrm;
3201
3202 // Response line
3203 if (!bstrm.write_format("HTTP/1.1 %d %s\r\n", res.status,
3204 detail::status_message(res.status))) {
3205 return false;
3206 }
3207
3208 // Headers
3209 if (last_connection || req.get_header_value("Connection") == "close") {
3210 res.set_header("Connection", "close");
3211 }
3212
3213 if (!last_connection && req.get_header_value("Connection") == "Keep-Alive") {
3214 res.set_header("Connection", "Keep-Alive");
3215 }
3216
3217 if (!res.has_header("Content-Type") &&
3218 (!res.body.empty() || res.content_length > 0)) {
3219 res.set_header("Content-Type", "text/plain");
3220 }
3221
3222 if (!res.has_header("Accept-Ranges") && req.method == "HEAD") {
3223 res.set_header("Accept-Ranges", "bytes");
3224 }
3225
3226 std::string content_type;
3227 std::string boundary;
3228
3229 if (req.ranges.size() > 1) {
3230 boundary = detail::make_multipart_data_boundary();
3231
3232 auto it = res.headers.find("Content-Type");
3233 if (it != res.headers.end()) {
3234 content_type = it->second;
3235 res.headers.erase(it);
3236 }
3237
3238 res.headers.emplace("Content-Type",
3239 "multipart/byteranges; boundary=" + boundary);
3240 }
3241
3242 if (res.body.empty()) {
3243 if (res.content_length > 0) {
3244 size_t length = 0;
3245 if (req.ranges.empty()) {
3246 length = res.content_length;
3247 } else if (req.ranges.size() == 1) {
3248 auto offsets =
3249 detail::get_range_offset_and_length(req, res.content_length, 0);
3250 auto offset = offsets.first;
3251 length = offsets.second;
3252 auto content_range = detail::make_content_range_header_field(
3253 offset, length, res.content_length);
3254 res.set_header("Content-Range", content_range);
3255 } else {
3256 length = detail::get_multipart_ranges_data_length(req, res, boundary,
3257 content_type);
3258 }
3259 res.set_header("Content-Length", std::to_string(length));
3260 } else {
3261 if (res.content_provider) {
3262 res.set_header("Transfer-Encoding", "chunked");
3263 } else {
3264 res.set_header("Content-Length", "0");
3265 }
3266 }
3267 } else {
3268 if (req.ranges.empty()) {
3269 ;
3270 } else if (req.ranges.size() == 1) {
3271 auto offsets =
3272 detail::get_range_offset_and_length(req, res.body.size(), 0);
3273 auto offset = offsets.first;
3274 auto length = offsets.second;
3275 auto content_range = detail::make_content_range_header_field(
3276 offset, length, res.body.size());
3277 res.set_header("Content-Range", content_range);
3278 res.body = res.body.substr(offset, length);
3279 } else {
3280 res.body =
3281 detail::make_multipart_ranges_data(req, res, boundary, content_type);
3282 }
3283
3284 #ifdef CPPHTTPLIB_ZLIB_SUPPORT
3285 // TODO: 'Accept-Encoding' has gzip, not gzip;q=0
3286 const auto &encodings = req.get_header_value("Accept-Encoding");
3287 if (encodings.find("gzip") != std::string::npos &&
3288 detail::can_compress(res.get_header_value("Content-Type"))) {
3289 if (detail::compress(res.body)) {
3290 res.set_header("Content-Encoding", "gzip");
3291 }
3292 }
3293 #endif
3294
3295 auto length = std::to_string(res.body.size());
3296 res.set_header("Content-Length", length);
3297 }
3298
3299 if (!detail::write_headers(bstrm, res, Headers())) { return false; }
3300
3301 // Flush buffer
3302 auto &data = bstrm.get_buffer();
3303 strm.write(data.data(), data.size());
3304
3305 // Body
3306 if (req.method != "HEAD") {
3307 if (!res.body.empty()) {
3308 if (!strm.write(res.body)) { return false; }
3309 } else if (res.content_provider) {
3310 if (!write_content_with_provider(strm, req, res, boundary,
3311 content_type)) {
3312 return false;
3313 }
3314 }
3315 }
3316
3317 // Log
3318 if (logger_) { logger_(req, res); }
3319
3320 return true;
3321 }
3322
3323 inline bool
3324 Server::write_content_with_provider(Stream &strm, const Request &req,
3325 Response &res, const std::string &boundary,
3326 const std::string &content_type) {
3327 if (res.content_length) {
3328 if (req.ranges.empty()) {
3329 if (detail::write_content(strm, res.content_provider, 0,
3330 res.content_length) < 0) {
3331 return false;
3332 }
3333 } else if (req.ranges.size() == 1) {
3334 auto offsets =
3335 detail::get_range_offset_and_length(req, res.content_length, 0);
3336 auto offset = offsets.first;
3337 auto length = offsets.second;
3338 if (detail::write_content(strm, res.content_provider, offset, length) <
3339 0) {
3340 return false;
3341 }
3342 } else {
3343 if (!detail::write_multipart_ranges_data(strm, req, res, boundary,
3344 content_type)) {
3345 return false;
3346 }
3347 }
3348 } else {
3349 auto is_shutting_down = [this]() {
3350 return this->svr_sock_ == INVALID_SOCKET;
3351 };
3352 if (detail::write_content_chunked(strm, res.content_provider,
3353 is_shutting_down) < 0) {
3354 return false;
3355 }
3356 }
3357 return true;
3358 }
3359
3360 inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
3361 MultipartFormDataMap::iterator cur;
3362 if (read_content_core(
3363 strm, req, res,
3364 // Regular
3365 [&](const char *buf, size_t n) {
3366 if (req.body.size() + n > req.body.max_size()) { return false; }
3367 req.body.append(buf, n);
3368 return true;
3369 },
3370 // Multipart
3371 [&](const MultipartFormData &file) {
3372 cur = req.files.emplace(file.name, file);
3373 return true;
3374 },
3375 [&](const char *buf, size_t n) {
3376 auto &content = cur->second.content;
3377 if (content.size() + n > content.max_size()) { return false; }
3378 content.append(buf, n);
3379 return true;
3380 })) {
3381 const auto &content_type = req.get_header_value("Content-Type");
3382 if (!content_type.find("application/x-www-form-urlencoded")) {
3383 detail::parse_query_text(req.body, req.params);
3384 }
3385 return true;
3386 }
3387 return false;
3388 }
3389
3390 inline bool Server::read_content_with_content_receiver(
3391 Stream &strm, Request &req, Response &res, ContentReceiver receiver,
3392 MultipartContentHeader multipart_header,
3393 ContentReceiver multipart_receiver) {
3394 return read_content_core(strm, req, res, receiver, multipart_header,
3395 multipart_receiver);
3396 }
3397
3398 inline bool Server::read_content_core(Stream &strm, Request &req, Response &res,
3399 ContentReceiver receiver,
3400 MultipartContentHeader mulitpart_header,
3401 ContentReceiver multipart_receiver) {
3402 detail::MultipartFormDataParser multipart_form_data_parser;
3403 ContentReceiver out;
3404
3405 if (req.is_multipart_form_data()) {
3406 const auto &content_type = req.get_header_value("Content-Type");
3407 std::string boundary;
3408 if (!detail::parse_multipart_boundary(content_type, boundary)) {
3409 res.status = 400;
3410 return false;
3411 }
3412
3413 multipart_form_data_parser.set_boundary(std::move(boundary));
3414 out = [&](const char *buf, size_t n) {
3415 return multipart_form_data_parser.parse(buf, n, multipart_receiver,
3416 mulitpart_header);
3417 };
3418 } else {
3419 out = receiver;
3420 }
3421
3422 if (!detail::read_content(strm, req, payload_max_length_, res.status,
3423 Progress(), out)) {
3424 return false;
3425 }
3426
3427 if (req.is_multipart_form_data()) {
3428 if (!multipart_form_data_parser.is_valid()) {
3429 res.status = 400;
3430 return false;
3431 }
3432 }
3433
3434 return true;
3435 }
3436
3437 inline bool Server::handle_file_request(Request &req, Response &res,
3438 bool head) {
3439 for (const auto &kv : base_dirs_) {
3440 const auto &mount_point = kv.first;
3441 const auto &base_dir = kv.second;
3442
3443 // Prefix match
3444 if (!req.path.find(mount_point)) {
3445 std::string sub_path = "/" + req.path.substr(mount_point.size());
3446 if (detail::is_valid_path(sub_path)) {
3447 auto path = base_dir + sub_path;
3448 if (path.back() == '/') { path += "index.html"; }
3449
3450 if (detail::is_file(path)) {
3451 detail::read_file(path, res.body);
3452 auto type =
3453 detail::find_content_type(path, file_extension_and_mimetype_map_);
3454 if (type) { res.set_header("Content-Type", type); }
3455 res.status = 200;
3456 if (!head && file_request_handler_) {
3457 file_request_handler_(req, res);
3458 }
3459 return true;
3460 }
3461 }
3462 }
3463 }
3464 return false;
3465 }
3466
3467 inline socket_t Server::create_server_socket(const char *host, int port,
3468 int socket_flags) const {
3469 return detail::create_socket(
3470 host, port,
3471 [](socket_t sock, struct addrinfo &ai) -> bool {
3472 if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
3473 return false;
3474 }
3475 if (::listen(sock, 5)) { // Listen through 5 channels
3476 return false;
3477 }
3478 return true;
3479 },
3480 socket_flags);
3481 }
3482
3483 inline int Server::bind_internal(const char *host, int port, int socket_flags) {
3484 if (!is_valid()) { return -1; }
3485
3486 svr_sock_ = create_server_socket(host, port, socket_flags);
3487 if (svr_sock_ == INVALID_SOCKET) { return -1; }
3488
3489 if (port == 0) {
3490 struct sockaddr_storage addr;
3491 socklen_t addr_len = sizeof(addr);
3492 if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
3493 &addr_len) == -1) {
3494 return -1;
3495 }
3496 if (addr.ss_family == AF_INET) {
3497 return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
3498 } else if (addr.ss_family == AF_INET6) {
3499 return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
3500 } else {
3501 return -1;
3502 }
3503 } else {
3504 return port;
3505 }
3506 }
3507
3508 inline bool Server::listen_internal() {
3509 auto ret = true;
3510 is_running_ = true;
3511
3512 {
3513 std::unique_ptr<TaskQueue> task_queue(new_task_queue());
3514
3515 for (;;) {
3516 if (svr_sock_ == INVALID_SOCKET) {
3517 // The server socket was closed by 'stop' method.
3518 break;
3519 }
3520
3521 auto val = detail::select_read(svr_sock_, 0, 100000);
3522
3523 if (val == 0) { // Timeout
3524 task_queue->on_idle();
3525 continue;
3526 }
3527
3528 socket_t sock = accept(svr_sock_, nullptr, nullptr);
3529
3530 if (sock == INVALID_SOCKET) {
3531 if (errno == EMFILE) {
3532 // The per-process limit of open file descriptors has been reached.
3533 // Try to accept new connections after a short sleep.
3534 std::this_thread::sleep_for(std::chrono::milliseconds(1));
3535 continue;
3536 }
3537 if (svr_sock_ != INVALID_SOCKET) {
3538 detail::close_socket(svr_sock_);
3539 ret = false;
3540 } else {
3541 ; // The server socket was closed by user.
3542 }
3543 break;
3544 }
3545
3546 #if __cplusplus > 201703L
3547 task_queue->enqueue([=, this]() { process_and_close_socket(sock); });
3548 #else
3549 task_queue->enqueue([=]() { process_and_close_socket(sock); });
3550 #endif
3551 }
3552
3553 task_queue->shutdown();
3554 }
3555
3556 is_running_ = false;
3557 return ret;
3558 }
3559
3560 inline bool Server::routing(Request &req, Response &res, Stream &strm) {
3561 // File handler
3562 bool is_head_request = req.method == "HEAD";
3563 if ((req.method == "GET" || is_head_request) &&
3564 handle_file_request(req, res, is_head_request)) {
3565 return true;
3566 }
3567
3568 if (detail::expect_content(req)) {
3569 // Content reader handler
3570 {
3571 ContentReader reader(
3572 [&](ContentReceiver receiver) {
3573 return read_content_with_content_receiver(strm, req, res, receiver,
3574 nullptr, nullptr);
3575 },
3576 [&](MultipartContentHeader header, ContentReceiver receiver) {
3577 return read_content_with_content_receiver(strm, req, res, nullptr,
3578 header, receiver);
3579 });
3580
3581 if (req.method == "POST") {
3582 if (dispatch_request_for_content_reader(
3583 req, res, reader, post_handlers_for_content_reader_)) {
3584 return true;
3585 }
3586 } else if (req.method == "PUT") {
3587 if (dispatch_request_for_content_reader(
3588 req, res, reader, put_handlers_for_content_reader_)) {
3589 return true;
3590 }
3591 } else if (req.method == "PATCH") {
3592 if (dispatch_request_for_content_reader(
3593 req, res, reader, patch_handlers_for_content_reader_)) {
3594 return true;
3595 }
3596 } else if (req.method == "DELETE") {
3597 if (dispatch_request_for_content_reader(
3598 req, res, reader, delete_handlers_for_content_reader_)) {
3599 return true;
3600 }
3601 }
3602 }
3603
3604 // Read content into `req.body`
3605 if (!read_content(strm, req, res)) { return false; }
3606 }
3607
3608 // Regular handler
3609 if (req.method == "GET" || req.method == "HEAD") {
3610 return dispatch_request(req, res, get_handlers_);
3611 } else if (req.method == "POST") {
3612 return dispatch_request(req, res, post_handlers_);
3613 } else if (req.method == "PUT") {
3614 return dispatch_request(req, res, put_handlers_);
3615 } else if (req.method == "DELETE") {
3616 return dispatch_request(req, res, delete_handlers_);
3617 } else if (req.method == "OPTIONS") {
3618 return dispatch_request(req, res, options_handlers_);
3619 } else if (req.method == "PATCH") {
3620 return dispatch_request(req, res, patch_handlers_);
3621 }
3622
3623 res.status = 400;
3624 return false;
3625 }
3626
3627 inline bool Server::dispatch_request(Request &req, Response &res,
3628 Handlers &handlers) {
3629
3630 try {
3631 for (const auto &x : handlers) {
3632 const auto &pattern = x.first;
3633 const auto &handler = x.second;
3634
3635 if (std::regex_match(req.path, req.matches, pattern)) {
3636 handler(req, res);
3637 return true;
3638 }
3639 }
3640 } catch (const std::exception &ex) {
3641 res.status = 500;
3642 res.set_header("EXCEPTION_WHAT", ex.what());
3643 } catch (...) {
3644 res.status = 500;
3645 res.set_header("EXCEPTION_WHAT", "UNKNOWN");
3646 }
3647 return false;
3648 }
3649
3650 inline bool Server::dispatch_request_for_content_reader(
3651 Request &req, Response &res, ContentReader content_reader,
3652 HandlersForContentReader &handlers) {
3653 for (const auto &x : handlers) {
3654 const auto &pattern = x.first;
3655 const auto &handler = x.second;
3656
3657 if (std::regex_match(req.path, req.matches, pattern)) {
3658 handler(req, res, content_reader);
3659 return true;
3660 }
3661 }
3662 return false;
3663 }
3664
3665 inline bool
3666 Server::process_request(Stream &strm, bool last_connection,
3667 bool &connection_close,
3668 const std::function<void(Request &)> &setup_request) {
3669 std::array<char, 2048> buf{};
3670
3671 detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
3672
3673 // Connection has been closed on client
3674 if (!line_reader.getline()) { return false; }
3675
3676 Request req;
3677 Response res;
3678
3679 res.version = "HTTP/1.1";
3680
3681 // Check if the request URI doesn't exceed the limit
3682 if (line_reader.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
3683 Headers dummy;
3684 detail::read_headers(strm, dummy);
3685 res.status = 414;
3686 return write_response(strm, last_connection, req, res);
3687 }
3688
3689 // Request line and headers
3690 if (!parse_request_line(line_reader.ptr(), req) ||
3691 !detail::read_headers(strm, req.headers)) {
3692 res.status = 400;
3693 return write_response(strm, last_connection, req, res);
3694 }
3695
3696 if (req.get_header_value("Connection") == "close") {
3697 connection_close = true;
3698 }
3699
3700 if (req.version == "HTTP/1.0" &&
3701 req.get_header_value("Connection") != "Keep-Alive") {
3702 connection_close = true;
3703 }
3704
3705 strm.get_remote_ip_and_port(req.remote_addr, req.remote_port);
3706 req.set_header("REMOTE_ADDR", req.remote_addr);
3707 req.set_header("REMOTE_PORT", std::to_string(req.remote_port));
3708
3709 if (req.has_header("Range")) {
3710 const auto &range_header_value = req.get_header_value("Range");
3711 if (!detail::parse_range_header(range_header_value, req.ranges)) {
3712 // TODO: error
3713 }
3714 }
3715
3716 if (setup_request) { setup_request(req); }
3717
3718 if (req.get_header_value("Expect") == "100-continue") {
3719 auto status = 100;
3720 if (expect_100_continue_handler_) {
3721 status = expect_100_continue_handler_(req, res);
3722 }
3723 switch (status) {
3724 case 100:
3725 case 417:
3726 strm.write_format("HTTP/1.1 %d %s\r\n\r\n", status,
3727 detail::status_message(status));
3728 break;
3729 default: return write_response(strm, last_connection, req, res);
3730 }
3731 }
3732
3733 // Rounting
3734 if (routing(req, res, strm)) {
3735 if (res.status == -1) { res.status = req.ranges.empty() ? 200 : 206; }
3736 } else {
3737 if (res.status == -1) { res.status = 404; }
3738 }
3739
3740 return write_response(strm, last_connection, req, res);
3741 }
3742
3743 inline bool Server::is_valid() const { return true; }
3744
3745 inline bool Server::process_and_close_socket(socket_t sock) {
3746 return detail::process_and_close_socket(
3747 false, sock, keep_alive_max_count_, read_timeout_sec_, read_timeout_usec_,
3748 [this](Stream &strm, bool last_connection, bool &connection_close) {
3749 return process_request(strm, last_connection, connection_close,
3750 nullptr);
3751 });
3752 }
3753
3754 // HTTP client implementation
3755 inline Client::Client(const std::string &host, int port,
3756 const std::string &client_cert_path,
3757 const std::string &client_key_path)
3758 : sock_(INVALID_SOCKET), host_(host), port_(port),
3759 host_and_port_(host_ + ":" + std::to_string(port_)),
3760 client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
3761
3762 inline Client::~Client() {}
3763
3764 inline bool Client::is_valid() const { return true; }
3765
3766 inline socket_t Client::create_client_socket() const {
3767 if (!proxy_host_.empty()) {
3768 return detail::create_client_socket(proxy_host_.c_str(), proxy_port_,
3769 timeout_sec_, interface_);
3770 }
3771 return detail::create_client_socket(host_.c_str(), port_, timeout_sec_,
3772 interface_);
3773 }
3774
3775 inline bool Client::read_response_line(Stream &strm, Response &res) {
3776 std::array<char, 2048> buf;
3777
3778 detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
3779
3780 if (!line_reader.getline()) { return false; }
3781
3782 const static std::regex re("(HTTP/1\\.[01]) (\\d+?) .*\r\n");
3783
3784 std::cmatch m;
3785 if (std::regex_match(line_reader.ptr(), m, re)) {
3786 res.version = std::string(m[1]);
3787 res.status = std::stoi(std::string(m[2]));
3788 }
3789
3790 return true;
3791 }
3792
3793 inline bool Client::send(const Request &req, Response &res) {
3794 sock_ = create_client_socket();
3795 if (sock_ == INVALID_SOCKET) { return false; }
3796
3797 #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
3798 if (is_ssl() && !proxy_host_.empty()) {
3799 bool error;
3800 if (!connect(sock_, res, error)) { return error; }
3801 }
3802 #endif
3803
3804 return process_and_close_socket(
3805 sock_, 1,
3806 [&](Stream &strm, bool last_connection, bool &connection_close) {
3807 return handle_request(strm, req, res, last_connection,
3808 connection_close);
3809 });
3810 }
3811
3812 inline bool Client::send(const std::vector<Request> &requests,
3813 std::vector<Response> &responses) {
3814 size_t i = 0;
3815 while (i < requests.size()) {
3816 sock_ = create_client_socket();
3817 if (sock_ == INVALID_SOCKET) { return false; }
3818
3819 #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
3820 if (is_ssl() && !proxy_host_.empty()) {
3821 Response res;
3822 bool error;
3823 if (!connect(sock_, res, error)) { return false; }
3824 }
3825 #endif
3826
3827 if (!process_and_close_socket(sock_, requests.size() - i,
3828 [&](Stream &strm, bool last_connection,
3829 bool &connection_close) -> bool {
3830 auto &req = requests[i++];
3831 auto res = Response();
3832 auto ret = handle_request(strm, req, res,
3833 last_connection,
3834 connection_close);
3835 if (ret) {
3836 responses.emplace_back(std::move(res));
3837 }
3838 return ret;
3839 })) {
3840 return false;
3841 }
3842 }
3843
3844 return true;
3845 }
3846
3847 inline bool Client::handle_request(Stream &strm, const Request &req,
3848 Response &res, bool last_connection,
3849 bool &connection_close) {
3850 if (req.path.empty()) { return false; }
3851
3852 bool ret;
3853
3854 if (!is_ssl() && !proxy_host_.empty()) {
3855 auto req2 = req;
3856 req2.path = "http://" + host_and_port_ + req.path;
3857 ret = process_request(strm, req2, res, last_connection, connection_close);
3858 } else {
3859 ret = process_request(strm, req, res, last_connection, connection_close);
3860 }
3861
3862 if (!ret) { return false; }
3863
3864 if (300 < res.status && res.status < 400 && follow_location_) {
3865 ret = redirect(req, res);
3866 }
3867
3868 #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
3869 if (res.status == 401 || res.status == 407) {
3870 auto is_proxy = res.status == 407;
3871 const auto &username =
3872 is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
3873 const auto &password =
3874 is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
3875
3876 if (!username.empty() && !password.empty()) {
3877 std::map<std::string, std::string> auth;
3878 if (parse_www_authenticate(res, auth, is_proxy)) {
3879 Request new_req = req;
3880 auto key = is_proxy ? "Proxy-Authorization" : "WWW-Authorization";
3881 new_req.headers.erase(key);
3882 new_req.headers.insert(make_digest_authentication_header(
3883 req, auth, 1, random_string(10), username, password, is_proxy));
3884
3885 Response new_res;
3886
3887 ret = send(new_req, new_res);
3888 if (ret) { res = new_res; }
3889 }
3890 }
3891 }
3892 #endif
3893
3894 return ret;
3895 }
3896
3897 #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
3898 inline bool Client::connect(socket_t sock, Response &res, bool &error) {
3899 error = true;
3900 Response res2;
3901
3902 if (!detail::process_socket(
3903 true, sock, 1, read_timeout_sec_, read_timeout_usec_,
3904 [&](Stream &strm, bool /*last_connection*/, bool &connection_close) {
3905 Request req2;
3906 req2.method = "CONNECT";
3907 req2.path = host_and_port_;
3908 return process_request(strm, req2, res2, false, connection_close);
3909 })) {
3910 detail::close_socket(sock);
3911 error = false;
3912 return false;
3913 }
3914
3915 if (res2.status == 407) {
3916 if (!proxy_digest_auth_username_.empty() &&
3917 !proxy_digest_auth_password_.empty()) {
3918 std::map<std::string, std::string> auth;
3919 if (parse_www_authenticate(res2, auth, true)) {
3920 Response res3;
3921 if (!detail::process_socket(
3922 true, sock, 1, read_timeout_sec_, read_timeout_usec_,
3923 [&](Stream &strm, bool /*last_connection*/,
3924 bool &connection_close) {
3925 Request req3;
3926 req3.method = "CONNECT";
3927 req3.path = host_and_port_;
3928 req3.headers.insert(make_digest_authentication_header(
3929 req3, auth, 1, random_string(10),
3930 proxy_digest_auth_username_, proxy_digest_auth_password_,
3931 true));
3932 return process_request(strm, req3, res3, false,
3933 connection_close);
3934 })) {
3935 detail::close_socket(sock);
3936 error = false;
3937 return false;
3938 }
3939 }
3940 } else {
3941 res = res2;
3942 return false;
3943 }
3944 }
3945
3946 return true;
3947 }
3948 #endif
3949
3950 inline bool Client::redirect(const Request &req, Response &res) {
3951 if (req.redirect_count == 0) { return false; }
3952
3953 auto location = res.get_header_value("location");
3954 if (location.empty()) { return false; }
3955
3956 const static std::regex re(
3957 R"(^(?:(https?):)?(?://([^:/?#]*)(?::(\d+))?)?([^?#]*(?:\?[^#]*)?)(?:#.*)?)");
3958
3959 std::smatch m;
3960 if (!std::regex_match(location, m, re)) { return false; }
3961
3962 auto scheme = is_ssl() ? "https" : "http";
3963
3964 auto next_scheme = m[1].str();
3965 auto next_host = m[2].str();
3966 auto port_str = m[3].str();
3967 auto next_path = m[4].str();
3968
3969 auto next_port = port_;
3970 if (!port_str.empty()) {
3971 next_port = std::stoi(port_str);
3972 } else if (!next_scheme.empty()) {
3973 next_port = next_scheme == "https" ? 443 : 80;
3974 }
3975
3976 if (next_scheme.empty()) { next_scheme = scheme; }
3977 if (next_host.empty()) { next_host = host_; }
3978 if (next_path.empty()) { next_path = "/"; }
3979
3980 if (next_scheme == scheme && next_host == host_ && next_port == port_) {
3981 return detail::redirect(*this, req, res, next_path);
3982 } else {
3983 if (next_scheme == "https") {
3984 #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
3985 SSLClient cli(next_host.c_str(), next_port);
3986 cli.copy_settings(*this);
3987 return detail::redirect(cli, req, res, next_path);
3988 #else
3989 return false;
3990 #endif
3991 } else {
3992 Client cli(next_host.c_str(), next_port);
3993 cli.copy_settings(*this);
3994 return detail::redirect(cli, req, res, next_path);
3995 }
3996 }
3997 }
3998
3999 inline bool Client::write_request(Stream &strm, const Request &req,
4000 bool last_connection) {
4001 detail::BufferStream bstrm;
4002
4003 // Request line
4004 const auto &path = detail::encode_url(req.path);
4005
4006 bstrm.write_format("%s %s HTTP/1.1\r\n", req.method.c_str(), path.c_str());
4007
4008 // Additonal headers
4009 Headers headers;
4010 if (last_connection) { headers.emplace("Connection", "close"); }
4011
4012 if (!req.has_header("Host")) {
4013 if (is_ssl()) {
4014 if (port_ == 443) {
4015 headers.emplace("Host", host_);
4016 } else {
4017 headers.emplace("Host", host_and_port_);
4018 }
4019 } else {
4020 if (port_ == 80) {
4021 headers.emplace("Host", host_);
4022 } else {
4023 headers.emplace("Host", host_and_port_);
4024 }
4025 }
4026 }
4027
4028 if (!req.has_header("Accept")) { headers.emplace("Accept", "*/*"); }
4029
4030 if (!req.has_header("User-Agent")) {
4031 headers.emplace("User-Agent", "cpp-httplib/0.5");
4032 }
4033
4034 if (req.body.empty()) {
4035 if (req.content_provider) {
4036 auto length = std::to_string(req.content_length);
4037 headers.emplace("Content-Length", length);
4038 } else {
4039 headers.emplace("Content-Length", "0");
4040 }
4041 } else {
4042 if (!req.has_header("Content-Type")) {
4043 headers.emplace("Content-Type", "text/plain");
4044 }
4045
4046 if (!req.has_header("Content-Length")) {
4047 auto length = std::to_string(req.body.size());
4048 headers.emplace("Content-Length", length);
4049 }
4050 }
4051
4052 if (!basic_auth_username_.empty() && !basic_auth_password_.empty()) {
4053 headers.insert(make_basic_authentication_header(
4054 basic_auth_username_, basic_auth_password_, false));
4055 }
4056
4057 if (!proxy_basic_auth_username_.empty() &&
4058 !proxy_basic_auth_password_.empty()) {
4059 headers.insert(make_basic_authentication_header(
4060 proxy_basic_auth_username_, proxy_basic_auth_password_, true));
4061 }
4062
4063 detail::write_headers(bstrm, req, headers);
4064
4065 // Flush buffer
4066 auto &data = bstrm.get_buffer();
4067 strm.write(data.data(), data.size());
4068
4069 // Body
4070 if (req.body.empty()) {
4071 if (req.content_provider) {
4072 size_t offset = 0;
4073 size_t end_offset = req.content_length;
4074
4075 DataSink data_sink;
4076 data_sink.write = [&](const char *d, size_t l) {
4077 auto written_length = strm.write(d, l);
4078 offset += static_cast<size_t>(written_length);
4079 };
4080 data_sink.is_writable = [&](void) { return strm.is_writable(); };
4081
4082 while (offset < end_offset) {
4083 req.content_provider(offset, end_offset - offset, data_sink);
4084 }
4085 }
4086 } else {
4087 strm.write(req.body);
4088 }
4089
4090 return true;
4091 }
4092
4093 inline std::shared_ptr<Response> Client::send_with_content_provider(
4094 const char *method, const char *path, const Headers &headers,
4095 const std::string &body, size_t content_length,
4096 ContentProvider content_provider, const char *content_type) {
4097 Request req;
4098 req.method = method;
4099 req.headers = headers;
4100 req.path = path;
4101
4102 if (content_type) { req.headers.emplace("Content-Type", content_type); }
4103
4104 #ifdef CPPHTTPLIB_ZLIB_SUPPORT
4105 if (compress_) {
4106 if (content_provider) {
4107 size_t offset = 0;
4108
4109 DataSink data_sink;
4110 data_sink.write = [&](const char *data, size_t data_len) {
4111 req.body.append(data, data_len);
4112 offset += data_len;
4113 };
4114 data_sink.is_writable = [&](void) { return true; };
4115
4116 while (offset < content_length) {
4117 content_provider(offset, content_length - offset, data_sink);
4118 }
4119 } else {
4120 req.body = body;
4121 }
4122
4123 if (!detail::compress(req.body)) { return nullptr; }
4124 req.headers.emplace("Content-Encoding", "gzip");
4125 } else
4126 #endif
4127 {
4128 if (content_provider) {
4129 req.content_length = content_length;
4130 req.content_provider = content_provider;
4131 } else {
4132 req.body = body;
4133 }
4134 }
4135
4136 auto res = std::make_shared<Response>();
4137
4138 return send(req, *res) ? res : nullptr;
4139 }
4140
4141 inline bool Client::process_request(Stream &strm, const Request &req,
4142 Response &res, bool last_connection,
4143 bool &connection_close) {
4144 // Send request
4145 if (!write_request(strm, req, last_connection)) { return false; }
4146
4147 // Receive response and headers
4148 if (!read_response_line(strm, res) ||
4149 !detail::read_headers(strm, res.headers)) {
4150 return false;
4151 }
4152
4153 if (res.get_header_value("Connection") == "close" ||
4154 res.version == "HTTP/1.0") {
4155 connection_close = true;
4156 }
4157
4158 if (req.response_handler) {
4159 if (!req.response_handler(res)) { return false; }
4160 }
4161
4162 // Body
4163 if (req.method != "HEAD" && req.method != "CONNECT") {
4164 auto out =
4165 req.content_receiver
4166 ? static_cast<ContentReceiver>([&](const char *buf, size_t n) {
4167 return req.content_receiver(buf, n);
4168 })
4169 : static_cast<ContentReceiver>([&](const char *buf, size_t n) {
4170 if (res.body.size() + n > res.body.max_size()) { return false; }
4171 res.body.append(buf, n);
4172 return true;
4173 });
4174
4175 int dummy_status;
4176 if (!detail::read_content(strm, res, (std::numeric_limits<size_t>::max)(),
4177 dummy_status, req.progress, out)) {
4178 return false;
4179 }
4180 }
4181
4182 // Log
4183 if (logger_) { logger_(req, res); }
4184
4185 return true;
4186 }
4187
4188 inline bool Client::process_and_close_socket(
4189 socket_t sock, size_t request_count,
4190 std::function<bool(Stream &strm, bool last_connection,
4191 bool &connection_close)>
4192 callback) {
4193 request_count = (std::min)(request_count, keep_alive_max_count_);
4194 return detail::process_and_close_socket(true, sock, request_count,
4195 read_timeout_sec_, read_timeout_usec_,
4196 callback);
4197 }
4198
4199 inline bool Client::is_ssl() const { return false; }
4200
4201 inline std::shared_ptr<Response> Client::Get(const char *path) {
4202 return Get(path, Headers(), Progress());
4203 }
4204
4205 inline std::shared_ptr<Response> Client::Get(const char *path,
4206 Progress progress) {
4207 return Get(path, Headers(), std::move(progress));
4208 }
4209
4210 inline std::shared_ptr<Response> Client::Get(const char *path,
4211 const Headers &headers) {
4212 return Get(path, headers, Progress());
4213 }
4214
4215 inline std::shared_ptr<Response>
4216 Client::Get(const char *path, const Headers &headers, Progress progress) {
4217 Request req;
4218 req.method = "GET";
4219 req.path = path;
4220 req.headers = headers;
4221 req.progress = std::move(progress);
4222
4223 auto res = std::make_shared<Response>();
4224 return send(req, *res) ? res : nullptr;
4225 }
4226
4227 inline std::shared_ptr<Response> Client::Get(const char *path,
4228 ContentReceiver content_receiver) {
4229 return Get(path, Headers(), nullptr, std::move(content_receiver), Progress());
4230 }
4231
4232 inline std::shared_ptr<Response> Client::Get(const char *path,
4233 ContentReceiver content_receiver,
4234 Progress progress) {
4235 return Get(path, Headers(), nullptr, std::move(content_receiver),
4236 std::move(progress));
4237 }
4238
4239 inline std::shared_ptr<Response> Client::Get(const char *path,
4240 const Headers &headers,
4241 ContentReceiver content_receiver) {
4242 return Get(path, headers, nullptr, std::move(content_receiver), Progress());
4243 }
4244
4245 inline std::shared_ptr<Response> Client::Get(const char *path,
4246 const Headers &headers,
4247 ContentReceiver content_receiver,
4248 Progress progress) {
4249 return Get(path, headers, nullptr, std::move(content_receiver),
4250 std::move(progress));
4251 }
4252
4253 inline std::shared_ptr<Response> Client::Get(const char *path,
4254 const Headers &headers,
4255 ResponseHandler response_handler,
4256 ContentReceiver content_receiver) {
4257 return Get(path, headers, std::move(response_handler), content_receiver,
4258 Progress());
4259 }
4260
4261 inline std::shared_ptr<Response> Client::Get(const char *path,
4262 const Headers &headers,
4263 ResponseHandler response_handler,
4264 ContentReceiver content_receiver,
4265 Progress progress) {
4266 Request req;
4267 req.method = "GET";
4268 req.path = path;
4269 req.headers = headers;
4270 req.response_handler = std::move(response_handler);
4271 req.content_receiver = std::move(content_receiver);
4272 req.progress = std::move(progress);
4273
4274 auto res = std::make_shared<Response>();
4275 return send(req, *res) ? res : nullptr;
4276 }
4277
4278 inline std::shared_ptr<Response> Client::Head(const char *path) {
4279 return Head(path, Headers());
4280 }
4281
4282 inline std::shared_ptr<Response> Client::Head(const char *path,
4283 const Headers &headers) {
4284 Request req;
4285 req.method = "HEAD";
4286 req.headers = headers;
4287 req.path = path;
4288
4289 auto res = std::make_shared<Response>();
4290
4291 return send(req, *res) ? res : nullptr;
4292 }
4293
4294 inline std::shared_ptr<Response> Client::Post(const char *path) {
4295 return Post(path, std::string(), nullptr);
4296 }
4297
4298 inline std::shared_ptr<Response> Client::Post(const char *path,
4299 const std::string &body,
4300 const char *content_type) {
4301 return Post(path, Headers(), body, content_type);
4302 }
4303
4304 inline std::shared_ptr<Response> Client::Post(const char *path,
4305 const Headers &headers,
4306 const std::string &body,
4307 const char *content_type) {
4308 return send_with_content_provider("POST", path, headers, body, 0, nullptr,
4309 content_type);
4310 }
4311
4312 inline std::shared_ptr<Response> Client::Post(const char *path,
4313 const Params &params) {
4314 return Post(path, Headers(), params);
4315 }
4316
4317 inline std::shared_ptr<Response> Client::Post(const char *path,
4318 size_t content_length,
4319 ContentProvider content_provider,
4320 const char *content_type) {
4321 return Post(path, Headers(), content_length, content_provider, content_type);
4322 }
4323
4324 inline std::shared_ptr<Response>
4325 Client::Post(const char *path, const Headers &headers, size_t content_length,
4326 ContentProvider content_provider, const char *content_type) {
4327 return send_with_content_provider("POST", path, headers, std::string(),
4328 content_length, content_provider,
4329 content_type);
4330 }
4331
4332 inline std::shared_ptr<Response>
4333 Client::Post(const char *path, const Headers &headers, const Params &params) {
4334 auto query = detail::params_to_query_str(params);
4335 return Post(path, headers, query, "application/x-www-form-urlencoded");
4336 }
4337
4338 inline std::shared_ptr<Response>
4339 Client::Post(const char *path, const MultipartFormDataItems &items) {
4340 return Post(path, Headers(), items);
4341 }
4342
4343 inline std::shared_ptr<Response>
4344 Client::Post(const char *path, const Headers &headers,
4345 const MultipartFormDataItems &items) {
4346 auto boundary = detail::make_multipart_data_boundary();
4347
4348 std::string body;
4349
4350 for (const auto &item : items) {
4351 body += "--" + boundary + "\r\n";
4352 body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
4353 if (!item.filename.empty()) {
4354 body += "; filename=\"" + item.filename + "\"";
4355 }
4356 body += "\r\n";
4357 if (!item.content_type.empty()) {
4358 body += "Content-Type: " + item.content_type + "\r\n";
4359 }
4360 body += "\r\n";
4361 body += item.content + "\r\n";
4362 }
4363
4364 body += "--" + boundary + "--\r\n";
4365
4366 std::string content_type = "multipart/form-data; boundary=" + boundary;
4367 return Post(path, headers, body, content_type.c_str());
4368 }
4369
4370 inline std::shared_ptr<Response> Client::Put(const char *path) {
4371 return Put(path, std::string(), nullptr);
4372 }
4373
4374 inline std::shared_ptr<Response> Client::Put(const char *path,
4375 const std::string &body,
4376 const char *content_type) {
4377 return Put(path, Headers(), body, content_type);
4378 }
4379
4380 inline std::shared_ptr<Response> Client::Put(const char *path,
4381 const Headers &headers,
4382 const std::string &body,
4383 const char *content_type) {
4384 return send_with_content_provider("PUT", path, headers, body, 0, nullptr,
4385 content_type);
4386 }
4387
4388 inline std::shared_ptr<Response> Client::Put(const char *path,
4389 size_t content_length,
4390 ContentProvider content_provider,
4391 const char *content_type) {
4392 return Put(path, Headers(), content_length, content_provider, content_type);
4393 }
4394
4395 inline std::shared_ptr<Response>
4396 Client::Put(const char *path, const Headers &headers, size_t content_length,
4397 ContentProvider content_provider, const char *content_type) {
4398 return send_with_content_provider("PUT", path, headers, std::string(),
4399 content_length, content_provider,
4400 content_type);
4401 }
4402
4403 inline std::shared_ptr<Response> Client::Put(const char *path,
4404 const Params &params) {
4405 return Put(path, Headers(), params);
4406 }
4407
4408 inline std::shared_ptr<Response>
4409 Client::Put(const char *path, const Headers &headers, const Params &params) {
4410 auto query = detail::params_to_query_str(params);
4411 return Put(path, headers, query, "application/x-www-form-urlencoded");
4412 }
4413
4414 inline std::shared_ptr<Response> Client::Patch(const char *path,
4415 const std::string &body,
4416 const char *content_type) {
4417 return Patch(path, Headers(), body, content_type);
4418 }
4419
4420 inline std::shared_ptr<Response> Client::Patch(const char *path,
4421 const Headers &headers,
4422 const std::string &body,
4423 const char *content_type) {
4424 return send_with_content_provider("PATCH", path, headers, body, 0, nullptr,
4425 content_type);
4426 }
4427
4428 inline std::shared_ptr<Response> Client::Patch(const char *path,
4429 size_t content_length,
4430 ContentProvider content_provider,
4431 const char *content_type) {
4432 return Patch(path, Headers(), content_length, content_provider, content_type);
4433 }
4434
4435 inline std::shared_ptr<Response>
4436 Client::Patch(const char *path, const Headers &headers, size_t content_length,
4437 ContentProvider content_provider, const char *content_type) {
4438 return send_with_content_provider("PATCH", path, headers, std::string(),
4439 content_length, content_provider,
4440 content_type);
4441 }
4442
4443 inline std::shared_ptr<Response> Client::Delete(const char *path) {
4444 return Delete(path, Headers(), std::string(), nullptr);
4445 }
4446
4447 inline std::shared_ptr<Response> Client::Delete(const char *path,
4448 const std::string &body,
4449 const char *content_type) {
4450 return Delete(path, Headers(), body, content_type);
4451 }
4452
4453 inline std::shared_ptr<Response> Client::Delete(const char *path,
4454 const Headers &headers) {
4455 return Delete(path, headers, std::string(), nullptr);
4456 }
4457
4458 inline std::shared_ptr<Response> Client::Delete(const char *path,
4459 const Headers &headers,
4460 const std::string &body,
4461 const char *content_type) {
4462 Request req;
4463 req.method = "DELETE";
4464 req.headers = headers;
4465 req.path = path;
4466
4467 if (content_type) { req.headers.emplace("Content-Type", content_type); }
4468 req.body = body;
4469
4470 auto res = std::make_shared<Response>();
4471
4472 return send(req, *res) ? res : nullptr;
4473 }
4474
4475 inline std::shared_ptr<Response> Client::Options(const char *path) {
4476 return Options(path, Headers());
4477 }
4478
4479 inline std::shared_ptr<Response> Client::Options(const char *path,
4480 const Headers &headers) {
4481 Request req;
4482 req.method = "OPTIONS";
4483 req.path = path;
4484 req.headers = headers;
4485
4486 auto res = std::make_shared<Response>();
4487
4488 return send(req, *res) ? res : nullptr;
4489 }
4490
4491 inline void Client::stop() {
4492 if (sock_ != INVALID_SOCKET) {
4493 std::atomic<socket_t> sock(sock_.exchange(INVALID_SOCKET));
4494 detail::shutdown_socket(sock);
4495 detail::close_socket(sock);
4496 }
4497 }
4498
4499 inline void Client::set_timeout_sec(time_t timeout_sec) {
4500 timeout_sec_ = timeout_sec;
4501 }
4502
4503 inline void Client::set_read_timeout(time_t sec, time_t usec) {
4504 read_timeout_sec_ = sec;
4505 read_timeout_usec_ = usec;
4506 }
4507
4508 inline void Client::set_keep_alive_max_count(size_t count) {
4509 keep_alive_max_count_ = count;
4510 }
4511
4512 inline void Client::set_basic_auth(const char *username, const char *password) {
4513 basic_auth_username_ = username;
4514 basic_auth_password_ = password;
4515 }
4516
4517 #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
4518 inline void Client::set_digest_auth(const char *username,
4519 const char *password) {
4520 digest_auth_username_ = username;
4521 digest_auth_password_ = password;
4522 }
4523 #endif
4524
4525 inline void Client::set_follow_location(bool on) { follow_location_ = on; }
4526
4527 inline void Client::set_compress(bool on) { compress_ = on; }
4528
4529 inline void Client::set_interface(const char *intf) { interface_ = intf; }
4530
4531 inline void Client::set_proxy(const char *host, int port) {
4532 proxy_host_ = host;
4533 proxy_port_ = port;
4534 }
4535
4536 inline void Client::set_proxy_basic_auth(const char *username,
4537 const char *password) {
4538 proxy_basic_auth_username_ = username;
4539 proxy_basic_auth_password_ = password;
4540 }
4541
4542 #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
4543 inline void Client::set_proxy_digest_auth(const char *username,
4544 const char *password) {
4545 proxy_digest_auth_username_ = username;
4546 proxy_digest_auth_password_ = password;
4547 }
4548 #endif
4549
4550 inline void Client::set_logger(Logger logger) { logger_ = std::move(logger); }
4551
4552 /*
4553 * SSL Implementation
4554 */
4555 #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
4556 namespace detail {
4557
4558 template <typename U, typename V, typename T>
4559 inline bool process_and_close_socket_ssl(
4560 bool is_client_request, socket_t sock, size_t keep_alive_max_count,
4561 time_t read_timeout_sec, time_t read_timeout_usec, SSL_CTX *ctx,
4562 std::mutex &ctx_mutex, U SSL_connect_or_accept, V setup, T callback) {
4563 assert(keep_alive_max_count > 0);
4564
4565 SSL *ssl = nullptr;
4566 {
4567 std::lock_guard<std::mutex> guard(ctx_mutex);
4568 ssl = SSL_new(ctx);
4569 }
4570
4571 if (!ssl) {
4572 close_socket(sock);
4573 return false;
4574 }
4575
4576 auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
4577 SSL_set_bio(ssl, bio, bio);
4578
4579 if (!setup(ssl)) {
4580 SSL_shutdown(ssl);
4581 {
4582 std::lock_guard<std::mutex> guard(ctx_mutex);
4583 SSL_free(ssl);
4584 }
4585
4586 close_socket(sock);
4587 return false;
4588 }
4589
4590 auto ret = false;
4591
4592 if (SSL_connect_or_accept(ssl) == 1) {
4593 if (keep_alive_max_count > 1) {
4594 auto count = keep_alive_max_count;
4595 while (count > 0 &&
4596 (is_client_request ||
4597 select_read(sock, CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND,
4598 CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND) > 0)) {
4599 SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec);
4600 auto last_connection = count == 1;
4601 auto connection_close = false;
4602
4603 ret = callback(ssl, strm, last_connection, connection_close);
4604 if (!ret || connection_close) { break; }
4605
4606 count--;
4607 }
4608 } else {
4609 SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec);
4610 auto dummy_connection_close = false;
4611 ret = callback(ssl, strm, true, dummy_connection_close);
4612 }
4613 }
4614
4615 if (ret) {
4616 SSL_shutdown(ssl); // shutdown only if not already closed by remote
4617 }
4618 {
4619 std::lock_guard<std::mutex> guard(ctx_mutex);
4620 SSL_free(ssl);
4621 }
4622
4623 close_socket(sock);
4624
4625 return ret;
4626 }
4627
4628 #if OPENSSL_VERSION_NUMBER < 0x10100000L
4629 static std::shared_ptr<std::vector<std::mutex>> openSSL_locks_;
4630
4631 class SSLThreadLocks {
4632 public:
4633 SSLThreadLocks() {
4634 openSSL_locks_ =
4635 std::make_shared<std::vector<std::mutex>>(CRYPTO_num_locks());
4636 CRYPTO_set_locking_callback(locking_callback);
4637 }
4638
4639 ~SSLThreadLocks() { CRYPTO_set_locking_callback(nullptr); }
4640
4641 private:
4642 static void locking_callback(int mode, int type, const char * /*file*/,
4643 int /*line*/) {
4644 auto &lk = (*openSSL_locks_)[static_cast<size_t>(type)];
4645 if (mode & CRYPTO_LOCK) {
4646 lk.lock();
4647 } else {
4648 lk.unlock();
4649 }
4650 }
4651 };
4652
4653 #endif
4654
4655 class SSLInit {
4656 public:
4657 SSLInit() {
4658 #if OPENSSL_VERSION_NUMBER < 0x1010001fL
4659 SSL_load_error_strings();
4660 SSL_library_init();
4661 #else
4662 OPENSSL_init_ssl(
4663 OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
4664 #endif
4665 }
4666
4667 ~SSLInit() {
4668 #if OPENSSL_VERSION_NUMBER < 0x1010001fL
4669 ERR_free_strings();
4670 #endif
4671 }
4672
4673 private:
4674 #if OPENSSL_VERSION_NUMBER < 0x10100000L
4675 SSLThreadLocks thread_init_;
4676 #endif
4677 };
4678
4679 // SSL socket stream implementation
4680 inline SSLSocketStream::SSLSocketStream(socket_t sock, SSL *ssl,
4681 time_t read_timeout_sec,
4682 time_t read_timeout_usec)
4683 : sock_(sock), ssl_(ssl), read_timeout_sec_(read_timeout_sec),
4684 read_timeout_usec_(read_timeout_usec) {}
4685
4686 inline SSLSocketStream::~SSLSocketStream() {}
4687
4688 inline bool SSLSocketStream::is_readable() const {
4689 return detail::select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
4690 }
4691
4692 inline bool SSLSocketStream::is_writable() const {
4693 return detail::select_write(sock_, 0, 0) > 0;
4694 }
4695
4696 inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
4697 if (SSL_pending(ssl_) > 0 ||
4698 select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0) {
4699 return SSL_read(ssl_, ptr, static_cast<int>(size));
4700 }
4701 return -1;
4702 }
4703
4704 inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
4705 if (is_writable()) { return SSL_write(ssl_, ptr, static_cast<int>(size)); }
4706 return -1;
4707 }
4708
4709 inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
4710 int &port) const {
4711 detail::get_remote_ip_and_port(sock_, ip, port);
4712 }
4713
4714 static SSLInit sslinit_;
4715
4716 } // namespace detail
4717
4718 // SSL HTTP server implementation
4719 inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
4720 const char *client_ca_cert_file_path,
4721 const char *client_ca_cert_dir_path) {
4722 ctx_ = SSL_CTX_new(SSLv23_server_method());
4723
4724 if (ctx_) {
4725 SSL_CTX_set_options(ctx_,
4726 SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
4727 SSL_OP_NO_COMPRESSION |
4728 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
4729
4730 // auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
4731 // SSL_CTX_set_tmp_ecdh(ctx_, ecdh);
4732 // EC_KEY_free(ecdh);
4733
4734 if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 ||
4735 SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) !=
4736 1) {
4737 SSL_CTX_free(ctx_);
4738 ctx_ = nullptr;
4739 } else if (client_ca_cert_file_path || client_ca_cert_dir_path) {
4740 // if (client_ca_cert_file_path) {
4741 // auto list = SSL_load_client_CA_file(client_ca_cert_file_path);
4742 // SSL_CTX_set_client_CA_list(ctx_, list);
4743 // }
4744
4745 SSL_CTX_load_verify_locations(ctx_, client_ca_cert_file_path,
4746 client_ca_cert_dir_path);
4747
4748 SSL_CTX_set_verify(
4749 ctx_,
4750 SSL_VERIFY_PEER |
4751 SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
4752 nullptr);
4753 }
4754 }
4755 }
4756
4757 inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key,
4758 X509_STORE *client_ca_cert_store) {
4759 ctx_ = SSL_CTX_new(SSLv23_server_method());
4760
4761 if (ctx_) {
4762 SSL_CTX_set_options(ctx_,
4763 SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
4764 SSL_OP_NO_COMPRESSION |
4765 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
4766
4767 if (SSL_CTX_use_certificate(ctx_, cert) != 1 ||
4768 SSL_CTX_use_PrivateKey(ctx_, private_key) != 1) {
4769 SSL_CTX_free(ctx_);
4770 ctx_ = nullptr;
4771 } else if (client_ca_cert_store) {
4772
4773 SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
4774
4775 SSL_CTX_set_verify(
4776 ctx_,
4777 SSL_VERIFY_PEER |
4778 SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
4779 nullptr);
4780 }
4781 }
4782 }
4783
4784 inline SSLServer::~SSLServer() {
4785 if (ctx_) { SSL_CTX_free(ctx_); }
4786 }
4787
4788 inline bool SSLServer::is_valid() const { return ctx_; }
4789
4790 inline bool SSLServer::process_and_close_socket(socket_t sock) {
4791 return detail::process_and_close_socket_ssl(
4792 false, sock, keep_alive_max_count_, read_timeout_sec_, read_timeout_usec_,
4793 ctx_, ctx_mutex_, SSL_accept, [](SSL * /*ssl*/) { return true; },
4794 [this](SSL *ssl, Stream &strm, bool last_connection,
4795 bool &connection_close) {
4796 return process_request(strm, last_connection, connection_close,
4797 [&](Request &req) { req.ssl = ssl; });
4798 });
4799 }
4800
4801 // SSL HTTP client implementation
4802 inline SSLClient::SSLClient(const std::string &host, int port,
4803 const std::string &client_cert_path,
4804 const std::string &client_key_path)
4805 : Client(host, port, client_cert_path, client_key_path) {
4806 ctx_ = SSL_CTX_new(SSLv23_client_method());
4807
4808 detail::split(&host_[0], &host_[host_.size()], '.',
4809 [&](const char *b, const char *e) {
4810 host_components_.emplace_back(std::string(b, e));
4811 });
4812 if (!client_cert_path.empty() && !client_key_path.empty()) {
4813 if (SSL_CTX_use_certificate_file(ctx_, client_cert_path.c_str(),
4814 SSL_FILETYPE_PEM) != 1 ||
4815 SSL_CTX_use_PrivateKey_file(ctx_, client_key_path.c_str(),
4816 SSL_FILETYPE_PEM) != 1) {
4817 SSL_CTX_free(ctx_);
4818 ctx_ = nullptr;
4819 }
4820 }
4821 }
4822
4823 inline SSLClient::SSLClient(const std::string &host, int port,
4824 X509 *client_cert, EVP_PKEY *client_key)
4825 : Client(host, port) {
4826 ctx_ = SSL_CTX_new(SSLv23_client_method());
4827
4828 detail::split(&host_[0], &host_[host_.size()], '.',
4829 [&](const char *b, const char *e) {
4830 host_components_.emplace_back(std::string(b, e));
4831 });
4832 if (client_cert != nullptr && client_key != nullptr) {
4833 if (SSL_CTX_use_certificate(ctx_, client_cert) != 1 ||
4834 SSL_CTX_use_PrivateKey(ctx_, client_key) != 1) {
4835 SSL_CTX_free(ctx_);
4836 ctx_ = nullptr;
4837 }
4838 }
4839 }
4840
4841 inline SSLClient::~SSLClient() {
4842 if (ctx_) { SSL_CTX_free(ctx_); }
4843 }
4844
4845 inline bool SSLClient::is_valid() const { return ctx_; }
4846
4847 inline void SSLClient::set_ca_cert_path(const char *ca_cert_file_path,
4848 const char *ca_cert_dir_path) {
4849 if (ca_cert_file_path) { ca_cert_file_path_ = ca_cert_file_path; }
4850 if (ca_cert_dir_path) { ca_cert_dir_path_ = ca_cert_dir_path; }
4851 }
4852
4853 inline void SSLClient::set_ca_cert_store(X509_STORE *ca_cert_store) {
4854 if (ca_cert_store) { ca_cert_store_ = ca_cert_store; }
4855 }
4856
4857 inline void SSLClient::enable_server_certificate_verification(bool enabled) {
4858 server_certificate_verification_ = enabled;
4859 }
4860
4861 inline long SSLClient::get_openssl_verify_result() const {
4862 return verify_result_;
4863 }
4864
4865 inline SSL_CTX *SSLClient::ssl_context() const { return ctx_; }
4866
4867 inline bool SSLClient::process_and_close_socket(
4868 socket_t sock, size_t request_count,
4869 std::function<bool(Stream &strm, bool last_connection,
4870 bool &connection_close)>
4871 callback) {
4872
4873 request_count = std::min(request_count, keep_alive_max_count_);
4874
4875 return is_valid() &&
4876 detail::process_and_close_socket_ssl(
4877 true, sock, request_count, read_timeout_sec_, read_timeout_usec_,
4878 ctx_, ctx_mutex_,
4879 [&](SSL *ssl) {
4880 if (ca_cert_file_path_.empty() && ca_cert_store_ == nullptr) {
4881 SSL_CTX_set_verify(ctx_, SSL_VERIFY_NONE, nullptr);
4882 } else if (!ca_cert_file_path_.empty()) {
4883 if (!SSL_CTX_load_verify_locations(
4884 ctx_, ca_cert_file_path_.c_str(), nullptr)) {
4885 return false;
4886 }
4887 SSL_CTX_set_verify(ctx_, SSL_VERIFY_PEER, nullptr);
4888 } else if (ca_cert_store_ != nullptr) {
4889 if (SSL_CTX_get_cert_store(ctx_) != ca_cert_store_) {
4890 SSL_CTX_set_cert_store(ctx_, ca_cert_store_);
4891 }
4892 SSL_CTX_set_verify(ctx_, SSL_VERIFY_PEER, nullptr);
4893 }
4894
4895 if (SSL_connect(ssl) != 1) { return false; }
4896
4897 if (server_certificate_verification_) {
4898 verify_result_ = SSL_get_verify_result(ssl);
4899
4900 if (verify_result_ != X509_V_OK) { return false; }
4901
4902 auto server_cert = SSL_get_peer_certificate(ssl);
4903
4904 if (server_cert == nullptr) { return false; }
4905
4906 if (!verify_host(server_cert)) {
4907 X509_free(server_cert);
4908 return false;
4909 }
4910 X509_free(server_cert);
4911 }
4912
4913 return true;
4914 },
4915 [&](SSL *ssl) {
4916 SSL_set_tlsext_host_name(ssl, host_.c_str());
4917 return true;
4918 },
4919 [&](SSL * /*ssl*/, Stream &strm, bool last_connection,
4920 bool &connection_close) {
4921 return callback(strm, last_connection, connection_close);
4922 });
4923 }
4924
4925 inline bool SSLClient::is_ssl() const { return true; }
4926
4927 inline bool SSLClient::verify_host(X509 *server_cert) const {
4928 /* Quote from RFC2818 section 3.1 "Server Identity"
4929
4930 If a subjectAltName extension of type dNSName is present, that MUST
4931 be used as the identity. Otherwise, the (most specific) Common Name
4932 field in the Subject field of the certificate MUST be used. Although
4933 the use of the Common Name is existing practice, it is deprecated and
4934 Certification Authorities are encouraged to use the dNSName instead.
4935
4936 Matching is performed using the matching rules specified by
4937 [RFC2459]. If more than one identity of a given type is present in
4938 the certificate (e.g., more than one dNSName name, a match in any one
4939 of the set is considered acceptable.) Names may contain the wildcard
4940 character * which is considered to match any single domain name
4941 component or component fragment. E.g., *.a.com matches foo.a.com but
4942 not bar.foo.a.com. f*.com matches foo.com but not bar.com.
4943
4944 In some cases, the URI is specified as an IP address rather than a
4945 hostname. In this case, the iPAddress subjectAltName must be present
4946 in the certificate and must exactly match the IP in the URI.
4947
4948 */
4949 return verify_host_with_subject_alt_name(server_cert) ||
4950 verify_host_with_common_name(server_cert);
4951 }
4952
4953 inline bool
4954 SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
4955 auto ret = false;
4956
4957 auto type = GEN_DNS;
4958
4959 struct in6_addr addr6;
4960 struct in_addr addr;
4961 size_t addr_len = 0;
4962
4963 #ifndef __MINGW32__
4964 if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
4965 type = GEN_IPADD;
4966 addr_len = sizeof(struct in6_addr);
4967 } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
4968 type = GEN_IPADD;
4969 addr_len = sizeof(struct in_addr);
4970 }
4971 #endif
4972
4973 auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
4974 X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
4975
4976 if (alt_names) {
4977 auto dsn_matched = false;
4978 auto ip_mached = false;
4979
4980 auto count = sk_GENERAL_NAME_num(alt_names);
4981
4982 for (auto i = 0; i < count && !dsn_matched; i++) {
4983 auto val = sk_GENERAL_NAME_value(alt_names, i);
4984 if (val->type == type) {
4985 auto name = (const char *)ASN1_STRING_get0_data(val->d.ia5);
4986 auto name_len = (size_t)ASN1_STRING_length(val->d.ia5);
4987
4988 if (strlen(name) == name_len) {
4989 switch (type) {
4990 case GEN_DNS: dsn_matched = check_host_name(name, name_len); break;
4991
4992 case GEN_IPADD:
4993 if (!memcmp(&addr6, name, addr_len) ||
4994 !memcmp(&addr, name, addr_len)) {
4995 ip_mached = true;
4996 }
4997 break;
4998 }
4999 }
5000 }
5001 }
5002
5003 if (dsn_matched || ip_mached) { ret = true; }
5004 }
5005
5006 GENERAL_NAMES_free((STACK_OF(GENERAL_NAME) *)alt_names);
5007
5008 return ret;
5009 }
5010
5011 inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
5012 const auto subject_name = X509_get_subject_name(server_cert);
5013
5014 if (subject_name != nullptr) {
5015 char name[BUFSIZ];
5016 auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
5017 name, sizeof(name));
5018
5019 if (name_len != -1) {
5020 return check_host_name(name, static_cast<size_t>(name_len));
5021 }
5022 }
5023
5024 return false;
5025 }
5026
5027 inline bool SSLClient::check_host_name(const char *pattern,
5028 size_t pattern_len) const {
5029 if (host_.size() == pattern_len && host_ == pattern) { return true; }
5030
5031 // Wildcard match
5032 // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
5033 std::vector<std::string> pattern_components;
5034 detail::split(&pattern[0], &pattern[pattern_len], '.',
5035 [&](const char *b, const char *e) {
5036 pattern_components.emplace_back(std::string(b, e));
5037 });
5038
5039 if (host_components_.size() != pattern_components.size()) { return false; }
5040
5041 auto itr = pattern_components.begin();
5042 for (const auto &h : host_components_) {
5043 auto &p = *itr;
5044 if (p != h && p != "*") {
5045 auto partial_match = (p.size() > 0 && p[p.size() - 1] == '*' &&
5046 !p.compare(0, p.size() - 1, h));
5047 if (!partial_match) { return false; }
5048 }
5049 ++itr;
5050 }
5051
5052 return true;
5053 }
5054 #endif
5055
5056 namespace url {
5057
5058 struct Options {
5059 // TODO: support more options...
5060 bool follow_location = false;
5061 std::string client_cert_path;
5062 std::string client_key_path;
5063
5064 std::string ca_cert_file_path;
5065 std::string ca_cert_dir_path;
5066 bool server_certificate_verification = false;
5067 };
5068
5069 inline std::shared_ptr<Response> Get(const char *url, Options &options) {
5070 const static std::regex re(
5071 R"(^(https?)://([^:/?#]+)(?::(\d+))?([^?#]*(?:\?[^#]*)?)(?:#.*)?)");
5072
5073 std::cmatch m;
5074 if (!std::regex_match(url, m, re)) { return nullptr; }
5075
5076 auto next_scheme = m[1].str();
5077 auto next_host = m[2].str();
5078 auto port_str = m[3].str();
5079 auto next_path = m[4].str();
5080
5081 auto next_port = !port_str.empty() ? std::stoi(port_str)
5082 : (next_scheme == "https" ? 443 : 80);
5083
5084 if (next_path.empty()) { next_path = "/"; }
5085
5086 if (next_scheme == "https") {
5087 #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
5088 SSLClient cli(next_host.c_str(), next_port, options.client_cert_path,
5089 options.client_key_path);
5090 cli.set_follow_location(options.follow_location);
5091 cli.set_ca_cert_path(options.ca_cert_file_path.c_str(),
5092 options.ca_cert_dir_path.c_str());
5093 cli.enable_server_certificate_verification(
5094 options.server_certificate_verification);
5095 return cli.Get(next_path.c_str());
5096 #else
5097 return nullptr;
5098 #endif
5099 } else {
5100 Client cli(next_host.c_str(), next_port, options.client_cert_path,
5101 options.client_key_path);
5102 cli.set_follow_location(options.follow_location);
5103 return cli.Get(next_path.c_str());
5104 }
5105 }
5106
5107 inline std::shared_ptr<Response> Get(const char *url) {
5108 Options options;
5109 return Get(url, options);
5110 }
5111
5112 } // namespace url
5113
5114 namespace detail {
5115
5116 #undef HANDLE_EINTR
5117
5118 } // namespace detail
5119
5120 // ----------------------------------------------------------------------------
5121
5122 } // namespace httplib
5123
5124 #endif // CPPHTTPLIB_HTTPLIB_H
5125