forked from yhirose/cpp-httplib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
httplib.h
4026 lines (3292 loc) · 117 KB
/
httplib.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// httplib.h
//
// Copyright (c) 2019 Yuji Hirose. All rights reserved.
// MIT License
//
#ifndef CPPHTTPLIB_HTTPLIB_H
#define CPPHTTPLIB_HTTPLIB_H
/*
* Configuration
*/
#ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
#define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
#endif
#ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND
#define CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND 0
#endif
#ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
#define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 5
#endif
#ifndef CPPHTTPLIB_READ_TIMEOUT_SECOND
#define CPPHTTPLIB_READ_TIMEOUT_SECOND 5
#endif
#ifndef CPPHTTPLIB_READ_TIMEOUT_USECOND
#define CPPHTTPLIB_READ_TIMEOUT_USECOND 0
#endif
#ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
#define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
#endif
#ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
#define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
#endif
#ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
#define CPPHTTPLIB_PAYLOAD_MAX_LENGTH (std::numeric_limits<size_t>::max)()
#endif
#ifndef CPPHTTPLIB_RECV_BUFSIZ
#define CPPHTTPLIB_RECV_BUFSIZ size_t(4096u)
#endif
#ifndef CPPHTTPLIB_THREAD_POOL_COUNT
#define CPPHTTPLIB_THREAD_POOL_COUNT 8
#endif
/*
* Headers
*/
#ifdef _WIN32
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif //_CRT_SECURE_NO_WARNINGS
#ifndef _CRT_NONSTDC_NO_DEPRECATE
#define _CRT_NONSTDC_NO_DEPRECATE
#endif //_CRT_NONSTDC_NO_DEPRECATE
#if defined(_MSC_VER)
#ifdef _WIN64
using ssize_t = __int64;
#else
using ssize_t = int;
#endif
#if _MSC_VER < 1900
#define snprintf _snprintf_s
#endif
#endif // _MSC_VER
#ifndef S_ISREG
#define S_ISREG(m) (((m)&S_IFREG) == S_IFREG)
#endif // S_ISREG
#ifndef S_ISDIR
#define S_ISDIR(m) (((m)&S_IFDIR) == S_IFDIR)
#endif // S_ISDIR
#ifndef NOMINMAX
#define NOMINMAX
#endif // NOMINMAX
#include <io.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#ifndef WSA_FLAG_NO_HANDLE_INHERIT
#define WSA_FLAG_NO_HANDLE_INHERIT 0x80
#endif
#ifdef _MSC_VER
#pragma comment(lib, "ws2_32.lib")
#endif
#ifndef strcasecmp
#define strcasecmp _stricmp
#endif // strcasecmp
using socket_t = SOCKET;
#ifdef CPPHTTPLIB_USE_POLL
#define poll(fds, nfds, timeout) WSAPoll(fds, nfds, timeout)
#endif
#else // not _WIN32
#include <arpa/inet.h>
#include <cstring>
#include <netdb.h>
#include <netinet/in.h>
#ifdef CPPHTTPLIB_USE_POLL
#include <poll.h>
#endif
#include <pthread.h>
#include <csignal>
#include <sys/select.h>
#include <sys/socket.h>
#include <unistd.h>
using socket_t = int;
#define INVALID_SOCKET (-1)
#endif //_WIN32
#include <cassert>
#include <atomic>
#include <condition_variable>
#include <errno.h>
#include <fcntl.h>
#include <fstream>
#include <functional>
#include <list>
#include <map>
#include <memory>
#include <mutex>
#include <random>
#include <regex>
#include <string>
#include <sys/stat.h>
#include <thread>
#include <array>
#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <openssl/x509v3.h>
// #if OPENSSL_VERSION_NUMBER < 0x1010100fL
// #error Sorry, OpenSSL versions prior to 1.1.1 are not supported
// #endif
#if OPENSSL_VERSION_NUMBER < 0x10100000L
#include <openssl/crypto.h>
inline const unsigned char *ASN1_STRING_get0_data(const ASN1_STRING *asn1) {
return M_ASN1_STRING_data(asn1);
}
#endif
#endif
#ifdef CPPHTTPLIB_ZLIB_SUPPORT
#include <zlib.h>
#endif
/*
* Declaration
*/
namespace httplib {
namespace detail {
struct ci {
bool operator()(const std::string &s1, const std::string &s2) const {
return std::lexicographical_compare(
s1.begin(), s1.end(), s2.begin(), s2.end(),
[](char c1, char c2) { return ::tolower(c1) < ::tolower(c2); });
}
};
} // namespace detail
enum class HttpVersion { v1_0 = 0, v1_1 };
using Headers = std::multimap<std::string, std::string, detail::ci>;
using Params = std::multimap<std::string, std::string>;
using Match = std::smatch;
using DataSink = std::function<void(const char *data, size_t data_len)>;
using Done = std::function<void()>;
using ContentProvider = std::function<void(size_t offset, size_t length, DataSink sink)>;
using ContentProviderWithCloser = std::function<void(size_t offset, size_t length, DataSink sink, Done done)>;
using ContentReceiver = std::function<bool(const char *data, size_t data_length)>;
using ContentReader = std::function<bool(ContentReceiver receiver)>;
using Progress = std::function<bool(uint64_t current, uint64_t total)>;
struct Response;
using ResponseHandler = std::function<bool(const Response &response)>;
struct MultipartFile {
std::string filename;
std::string content_type;
size_t offset = 0;
size_t length = 0;
};
using MultipartFiles = std::multimap<std::string, MultipartFile>;
struct MultipartFormData {
std::string name;
std::string content;
std::string filename;
std::string content_type;
};
using MultipartFormDataItems = std::vector<MultipartFormData>;
using Range = std::pair<ssize_t, ssize_t>;
using Ranges = std::vector<Range>;
struct Request {
std::string method;
std::string path;
Headers headers;
std::string body;
// for server
std::string version;
std::string target;
Params params;
MultipartFiles files;
Ranges ranges;
Match matches;
// for client
size_t redirect_count = CPPHTTPLIB_REDIRECT_MAX_COUNT;
ResponseHandler response_handler;
ContentReceiver content_receiver;
Progress progress;
#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
const SSL *ssl;
#endif
bool has_header(const char *key) const;
std::string get_header_value(const char *key, size_t id = 0) const;
size_t get_header_value_count(const char *key) const;
void set_header(const char *key, const char *val);
void set_header(const char *key, const std::string &val);
bool has_param(const char *key) const;
std::string get_param_value(const char *key, size_t id = 0) const;
size_t get_param_value_count(const char *key) const;
bool has_file(const char *key) const;
MultipartFile get_file_value(const char *key) const;
// private members...
size_t content_length;
ContentProvider content_provider;
};
struct Response {
std::string version;
int status;
Headers headers;
std::string body;
bool has_header(const char *key) const;
std::string get_header_value(const char *key, size_t id = 0) const;
size_t get_header_value_count(const char *key) const;
void set_header(const char *key, const char *val);
void set_header(const char *key, const std::string &val);
void set_redirect(const char *url);
void set_content(const char *s, size_t n, const char *content_type);
void set_content(const std::string &s, const char *content_type);
void set_content_provider(
size_t length,
std::function<void(size_t offset, size_t length, DataSink sink)> provider,
std::function<void()> resource_releaser = [] {});
void set_chunked_content_provider(
std::function<void(size_t offset, DataSink sink, Done done)> provider,
std::function<void()> resource_releaser = [] {});
Response() : status(-1), content_length(0) {}
~Response() {
if (content_provider_resource_releaser) {
content_provider_resource_releaser();
}
}
// private members...
size_t content_length;
ContentProviderWithCloser content_provider;
std::function<void()> content_provider_resource_releaser;
};
class Stream {
public:
virtual ~Stream() = default;
virtual int read(char *ptr, size_t size) = 0;
virtual int write(const char *ptr, size_t size1) = 0;
virtual int write(const char *ptr) = 0;
virtual int write(const std::string &s) = 0;
virtual std::string get_remote_addr() const = 0;
template <typename... Args>
int write_format(const char *fmt, const Args &... args);
};
class SocketStream : public Stream {
public:
SocketStream(socket_t sock, time_t read_timeout_sec,
time_t read_timeout_usec);
~SocketStream() override;
int read(char *ptr, size_t size) override;
int write(const char *ptr, size_t size) override;
int write(const char *ptr) override;
int write(const std::string &s) override;
std::string get_remote_addr() const override;
private:
socket_t sock_;
time_t read_timeout_sec_;
time_t read_timeout_usec_;
};
class BufferStream : public Stream {
public:
BufferStream() = default;
~BufferStream() override = default;
int read(char *ptr, size_t size) override;
int write(const char *ptr, size_t size) override;
int write(const char *ptr) override;
int write(const std::string &s) override;
std::string get_remote_addr() const override;
const std::string &get_buffer() const;
private:
std::string buffer;
};
class TaskQueue {
public:
TaskQueue() = default;
virtual ~TaskQueue() = default;
virtual void enqueue(std::function<void()> fn) = 0;
virtual void shutdown() = 0;
};
#if CPPHTTPLIB_THREAD_POOL_COUNT > 0
class ThreadPool : public TaskQueue {
public:
explicit ThreadPool(size_t n) : shutdown_(false) {
while (n) {
threads_.emplace_back(worker(*this));
n--;
}
}
ThreadPool(const ThreadPool &) = delete;
~ThreadPool() override = default;
void enqueue(std::function<void()> fn) override {
std::unique_lock<std::mutex> lock(mutex_);
jobs_.push_back(fn);
cond_.notify_one();
}
void shutdown() override {
// Stop all worker threads...
{
std::unique_lock<std::mutex> lock(mutex_);
shutdown_ = true;
}
cond_.notify_all();
// Join...
for (auto& t : threads_) {
t.join();
}
}
private:
struct worker {
explicit worker(ThreadPool &pool) : pool_(pool) {}
void operator()() {
for (;;) {
std::function<void()> fn;
{
std::unique_lock<std::mutex> lock(pool_.mutex_);
pool_.cond_.wait(
lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; });
if (pool_.shutdown_ && pool_.jobs_.empty()) { break; }
fn = pool_.jobs_.front();
pool_.jobs_.pop_front();
}
assert(true == static_cast<bool>(fn));
fn();
}
}
ThreadPool &pool_;
};
friend struct worker;
std::vector<std::thread> threads_;
std::list<std::function<void()>> jobs_;
bool shutdown_;
std::condition_variable cond_;
std::mutex mutex_;
};
#elif CPPHTTPLIB_THREAD_POOL_COUNT == 0
class Threads : public TaskQueue {
public:
Threads() : running_threads_(0) {}
virtual ~Threads() {}
virtual void enqueue(std::function<void()> fn) override {
std::thread([=]() {
{
std::lock_guard<std::mutex> guard(running_threads_mutex_);
running_threads_++;
}
fn();
{
std::lock_guard<std::mutex> guard(running_threads_mutex_);
running_threads_--;
}
}).detach();
}
virtual void shutdown() override {
for (;;) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
std::lock_guard<std::mutex> guard(running_threads_mutex_);
if (!running_threads_) { break; }
}
}
private:
std::mutex running_threads_mutex_;
int running_threads_;
};
#else
class NoThread : public TaskQueue {
public:
NoThread() {}
virtual ~NoThread() {}
virtual void enqueue(std::function<void()> fn) override {
fn();
}
virtual void shutdown() override {
}
};
#endif
class Server {
public:
using Handler = std::function<void(const Request &, Response &)>;
using HandlerWithContentReader = std::function<void(const Request &, Response &,
const ContentReader &content_reader)>;
using Logger = std::function<void(const Request &, const Response &)>;
Server();
virtual ~Server();
virtual bool is_valid() const;
Server &Get(const char *pattern, Handler handler);
Server &Post(const char *pattern, Handler handler);
Server &Post(const char *pattern, HandlerWithContentReader handler);
Server &Put(const char *pattern, Handler handler);
Server &Put(const char *pattern, HandlerWithContentReader handler);
Server &Patch(const char *pattern, Handler handler);
Server &Patch(const char *pattern, HandlerWithContentReader handler);
Server &Delete(const char *pattern, Handler handler);
Server &Options(const char *pattern, Handler handler);
bool set_base_dir(const char *path);
void set_file_request_handler(Handler handler);
void set_error_handler(Handler handler);
void set_logger(Logger logger);
void set_keep_alive_max_count(size_t count);
void set_read_timeout(time_t sec, time_t usec);
void set_payload_max_length(size_t length);
bool bind_to_port(const char *host, int port, int socket_flags = 0);
int bind_to_any_port(const char *host, int socket_flags = 0);
bool listen_after_bind();
bool listen(const char *host, int port, int socket_flags = 0);
bool is_running() const;
void stop();
std::function<TaskQueue *(void)> new_task_queue;
protected:
bool process_request(Stream &strm, bool last_connection,
bool &connection_close,
const std::function<void(Request &)>& setup_request);
size_t keep_alive_max_count_;
time_t read_timeout_sec_;
time_t read_timeout_usec_;
size_t payload_max_length_;
private:
using Handlers = std::vector<std::pair<std::regex, Handler>>;
using HandersForContentReader = std::vector<std::pair<std::regex, HandlerWithContentReader>>;
socket_t create_server_socket(const char *host, int port,
int socket_flags) const;
int bind_internal(const char *host, int port, int socket_flags);
bool listen_internal();
bool routing(Request &req, Response &res, Stream &strm, bool last_connection);
bool handle_file_request(Request &req, Response &res);
bool dispatch_request(Request &req, Response &res, Handlers &handlers);
bool dispatch_request_for_content_reader(Request &req, Response &res,
ContentReader content_reader,
HandersForContentReader &handlers);
bool parse_request_line(const char *s, Request &req);
bool write_response(Stream &strm, bool last_connection, const Request &req,
Response &res);
bool write_content_with_provider(Stream &strm, const Request &req,
Response &res, const std::string &boundary,
const std::string &content_type);
bool read_content(Stream &strm, bool last_connection, Request &req,
Response &res);
bool read_content_with_content_receiver(Stream &strm, bool last_connection,
Request &req, Response &res,
ContentReceiver reveiver);
virtual bool process_and_close_socket(socket_t sock);
std::atomic<bool> is_running_;
std::atomic<socket_t> svr_sock_;
std::string base_dir_;
Handler file_request_handler_;
Handlers get_handlers_;
Handlers post_handlers_;
HandersForContentReader post_handlers_for_content_reader;
Handlers put_handlers_;
HandersForContentReader put_handlers_for_content_reader;
Handlers patch_handlers_;
HandersForContentReader patch_handlers_for_content_reader;
Handlers delete_handlers_;
Handlers options_handlers_;
Handler error_handler_;
Logger logger_;
};
class Client {
public:
explicit Client(const char *host, int port = 80, time_t timeout_sec = 300);
virtual ~Client();
virtual bool is_valid() const;
std::shared_ptr<Response> Get(const char *path);
std::shared_ptr<Response> Get(const char *path, const Headers &headers);
std::shared_ptr<Response> Get(const char *path, Progress progress);
std::shared_ptr<Response> Get(const char *path, const Headers &headers,
Progress progress);
std::shared_ptr<Response> Get(const char *path,
ContentReceiver content_receiver);
std::shared_ptr<Response> Get(const char *path, const Headers &headers,
ContentReceiver content_receiver);
std::shared_ptr<Response>
Get(const char *path, ContentReceiver content_receiver, Progress progress);
std::shared_ptr<Response> Get(const char *path, const Headers &headers,
ContentReceiver content_receiver,
Progress progress);
std::shared_ptr<Response> Get(const char *path, const Headers &headers,
ResponseHandler response_handler,
ContentReceiver content_receiver);
std::shared_ptr<Response> Get(const char *path, const Headers &headers,
ResponseHandler response_handler,
ContentReceiver content_receiver,
Progress progress);
std::shared_ptr<Response> Head(const char *path);
std::shared_ptr<Response> Head(const char *path, const Headers &headers);
std::shared_ptr<Response> Post(const char *path, const std::string &body,
const char *content_type,
bool compress = false);
std::shared_ptr<Response> Post(const char *path, const Headers &headers,
const std::string &body,
const char *content_type,
bool compress = false);
std::shared_ptr<Response> Post(const char *path, size_t content_length,
ContentProvider content_provider,
const char *content_type,
bool compress = false);
std::shared_ptr<Response> Post(const char *path, const Headers &headers,
size_t content_length,
ContentProvider content_provider,
const char *content_type,
bool compress = false);
std::shared_ptr<Response> Post(const char *path, const Params ¶ms,
bool compress = false);
std::shared_ptr<Response> Post(const char *path, const Headers &headers,
const Params ¶ms, bool compress = false);
std::shared_ptr<Response> Post(const char *path,
const MultipartFormDataItems &items,
bool compress = false);
std::shared_ptr<Response> Post(const char *path, const Headers &headers,
const MultipartFormDataItems &items,
bool compress = false);
std::shared_ptr<Response> Put(const char *path, const std::string &body,
const char *content_type,
bool compress = false);
std::shared_ptr<Response> Put(const char *path, const Headers &headers,
const std::string &body,
const char *content_type,
bool compress = false);
std::shared_ptr<Response> Put(const char *path, size_t content_length,
ContentProvider content_provider,
const char *content_type,
bool compress = false);
std::shared_ptr<Response> Put(const char *path, const Headers &headers,
size_t content_length,
ContentProvider content_provider,
const char *content_type,
bool compress = false);
std::shared_ptr<Response> Patch(const char *path, const std::string &body,
const char *content_type,
bool compress = false);
std::shared_ptr<Response> Patch(const char *path, const Headers &headers,
const std::string &body,
const char *content_type,
bool compress = false);
std::shared_ptr<Response> Patch(const char *path, size_t content_length,
ContentProvider content_provider,
const char *content_type,
bool compress = false);
std::shared_ptr<Response> Patch(const char *path, const Headers &headers,
size_t content_length,
ContentProvider content_provider,
const char *content_type,
bool compress = false);
std::shared_ptr<Response> Delete(const char *path);
std::shared_ptr<Response> Delete(const char *path, const std::string &body,
const char *content_type);
std::shared_ptr<Response> Delete(const char *path, const Headers &headers);
std::shared_ptr<Response> Delete(const char *path, const Headers &headers,
const std::string &body,
const char *content_type);
std::shared_ptr<Response> Options(const char *path);
std::shared_ptr<Response> Options(const char *path, const Headers &headers);
bool send(const Request &req, Response &res);
bool send(const std::vector<Request> &requests,
std::vector<Response> &responses);
void set_keep_alive_max_count(size_t count);
void set_read_timeout(time_t sec, time_t usec);
void follow_location(bool on);
protected:
bool process_request(Stream &strm, const Request &req, Response &res,
bool last_connection, bool &connection_close);
const std::string host_;
const int port_;
time_t timeout_sec_;
const std::string host_and_port_;
size_t keep_alive_max_count_;
time_t read_timeout_sec_;
time_t read_timeout_usec_;
size_t follow_location_;
private:
socket_t create_client_socket() const;
bool read_response_line(Stream &strm, Response &res);
void write_request(Stream &strm, const Request &req, bool last_connection);
bool redirect(const Request &req, Response &res);
std::shared_ptr<Response>
send_with_content_provider(const char *method, const char *path,
const Headers &headers, const std::string &body,
size_t content_length,
ContentProvider content_provider,
const char *content_type, bool compress);
virtual bool process_and_close_socket(
socket_t sock, size_t request_count,
std::function<bool(Stream &strm, bool last_connection,
bool &connection_close)>
callback);
virtual bool is_ssl() const;
};
inline void Get(std::vector<Request> &requests, const char *path,
const Headers &headers) {
Request req;
req.method = "GET";
req.path = path;
req.headers = headers;
requests.emplace_back(std::move(req));
}
inline void Get(std::vector<Request> &requests, const char *path) {
Get(requests, path, Headers());
}
inline void Post(std::vector<Request> &requests, const char *path,
const Headers &headers, const std::string &body,
const char *content_type) {
Request req;
req.method = "POST";
req.path = path;
req.headers = headers;
req.headers.emplace("Content-Type", content_type);
req.body = body;
requests.emplace_back(std::move(req));
}
inline void Post(std::vector<Request> &requests, const char *path,
const std::string &body, const char *content_type) {
Post(requests, path, Headers(), body, content_type);
}
#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
class SSLSocketStream : public Stream {
public:
SSLSocketStream(socket_t sock, SSL *ssl, time_t read_timeout_sec,
time_t read_timeout_usec);
virtual ~SSLSocketStream();
virtual int read(char *ptr, size_t size);
virtual int write(const char *ptr, size_t size);
virtual int write(const char *ptr);
virtual int write(const std::string &s);
virtual std::string get_remote_addr() const;
private:
socket_t sock_;
SSL *ssl_;
time_t read_timeout_sec_;
time_t read_timeout_usec_;
};
class SSLServer : public Server {
public:
SSLServer(const char *cert_path, const char *private_key_path,
const char *client_ca_cert_file_path = nullptr,
const char *client_ca_cert_dir_path = nullptr);
virtual ~SSLServer();
virtual bool is_valid() const;
private:
virtual bool process_and_close_socket(socket_t sock);
SSL_CTX *ctx_;
std::mutex ctx_mutex_;
};
class SSLClient : public Client {
public:
SSLClient(const char *host, int port = 443, time_t timeout_sec = 300,
const char *client_cert_path = nullptr,
const char *client_key_path = nullptr);
virtual ~SSLClient();
virtual bool is_valid() const;
void set_ca_cert_path(const char *ca_ceert_file_path,
const char *ca_cert_dir_path = nullptr);
void enable_server_certificate_verification(bool enabled);
long get_openssl_verify_result() const;
SSL_CTX *ssl_context() const noexcept;
private:
virtual bool process_and_close_socket(
socket_t sock, size_t request_count,
std::function<bool(Stream &strm, bool last_connection,
bool &connection_close)>
callback);
virtual bool is_ssl() const;
bool verify_host(X509 *server_cert) const;
bool verify_host_with_subject_alt_name(X509 *server_cert) const;
bool verify_host_with_common_name(X509 *server_cert) const;
bool check_host_name(const char *pattern, size_t pattern_len) const;
SSL_CTX *ctx_;
std::mutex ctx_mutex_;
std::vector<std::string> host_components_;
std::string ca_cert_file_path_;
std::string ca_cert_dir_path_;
bool server_certificate_verification_ = false;
long verify_result_ = 0;
};
#endif
/*
* Implementation
*/
namespace detail {
inline bool is_hex(char c, int &v) {
if (0x20 <= c && isdigit(c)) {
v = c - '0';
return true;
} else if ('A' <= c && c <= 'F') {
v = c - 'A' + 10;
return true;
} else if ('a' <= c && c <= 'f') {
v = c - 'a' + 10;
return true;
}
return false;
}
inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
int &val) {
if (i >= s.size()) { return false; }
val = 0;
for (; cnt; i++, cnt--) {
if (!s[i]) { return false; }
int v = 0;
if (is_hex(s[i], v)) {
val = val * 16 + v;
} else {
return false;
}
}
return true;
}
inline std::string from_i_to_hex(size_t n) {
const char *charset = "0123456789abcdef";
std::string ret;
do {
ret = charset[n & 15] + ret;
n >>= 4;
} while (n > 0);
return ret;
}
inline size_t to_utf8(int code, char *buff) {
if (code < 0x0080) {
buff[0] = (code & 0x7F);
return 1;
} else if (code < 0x0800) {
buff[0] = (0xC0 | ((code >> 6) & 0x1F));
buff[1] = (0x80 | (code & 0x3F));
return 2;
} else if (code < 0xD800) {
buff[0] = (0xE0 | ((code >> 12) & 0xF));
buff[1] = (0x80 | ((code >> 6) & 0x3F));
buff[2] = (0x80 | (code & 0x3F));
return 3;
} else if (code < 0xE000) { // D800 - DFFF is invalid...
return 0;
} else if (code < 0x10000) {
buff[0] = (0xE0 | ((code >> 12) & 0xF));
buff[1] = (0x80 | ((code >> 6) & 0x3F));
buff[2] = (0x80 | (code & 0x3F));
return 3;
} else if (code < 0x110000) {
buff[0] = (0xF0 | ((code >> 18) & 0x7));
buff[1] = (0x80 | ((code >> 12) & 0x3F));
buff[2] = (0x80 | ((code >> 6) & 0x3F));
buff[3] = (0x80 | (code & 0x3F));
return 4;
}
// NOTREACHED
return 0;
}
// NOTE: This code came up with the following stackoverflow post:
// https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
inline std::string base64_encode(const std::string &in) {
static const auto lookup =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string out;
out.reserve(in.size());
int val = 0;
int valb = -6;
for (uint8_t c : in) {
val = (val << 8) + c;
valb += 8;
while (valb >= 0) {
out.push_back(lookup[(val >> valb) & 0x3F]);
valb -= 6;
}
}
if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
while (out.size() % 4) {
out.push_back('=');
}
return out;
}
inline bool is_file(const std::string &path) {
struct stat st;
return stat(path.c_str(), &st) >= 0 && S_ISREG(st.st_mode);
}
inline bool is_dir(const std::string &path) {
struct stat st;
return stat(path.c_str(), &st) >= 0 && S_ISDIR(st.st_mode);
}
inline bool is_valid_path(const std::string &path) {
size_t level = 0;
size_t i = 0;
// Skip slash
while (i < path.size() && path[i] == '/') {
i++;
}