-
Notifications
You must be signed in to change notification settings - Fork 1
/
httplib.h
2451 lines (2010 loc) · 60.3 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) 2017 Yuji Hirose. All rights reserved.
// MIT License
//
#ifndef CPPHTTPLIB_HTTPLIB_H
#define CPPHTTPLIB_HTTPLIB_H
#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) && _MSC_VER < 1900
#define snprintf _snprintf_s
#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
#define NOMINMAX
#include <io.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#ifndef strcasecmp
#define strcasecmp _stricmp
#endif //strcasecmp
typedef SOCKET socket_t;
#else
#include <pthread.h>
#include <unistd.h>
#include <netdb.h>
#include <cstring>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <sys/socket.h>
#include <sys/select.h>
typedef int socket_t;
#define INVALID_SOCKET (-1)
#endif //_WIN32
#include <fstream>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <regex>
#include <string>
#include <thread>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>
#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
#include <openssl/ssl.h>
#endif
#ifdef CPPHTTPLIB_ZLIB_SUPPORT
#include <zlib.h>
#endif
/*
* Configuration
*/
#define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
#define CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND 0
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 };
typedef std::multimap<std::string, std::string, detail::ci> Headers;
template<typename uint64_t, typename... Args>
std::pair<std::string, std::string> make_range_header(uint64_t value, Args... args);
typedef std::multimap<std::string, std::string> Params;
typedef std::smatch Match;
typedef std::function<bool (uint64_t current, uint64_t total)> Progress;
struct MultipartFile {
std::string filename;
std::string content_type;
size_t offset = 0;
size_t length = 0;
};
typedef std::multimap<std::string, MultipartFile> MultipartFiles;
struct Request {
std::string version;
std::string method;
std::string target;
std::string path;
Headers headers;
std::string body;
Params params;
MultipartFiles files;
Match matches;
Progress progress;
bool has_header(const char* key) const;
std::string get_header_value(const char* key) const;
void set_header(const char* key, const char* val);
bool has_param(const char* key) const;
std::string get_param_value(const char* key) const;
bool has_file(const char* key) const;
MultipartFile get_file_value(const char* key) const;
};
struct Response {
std::string version;
int status;
Headers headers;
std::string body;
std::function<std::string (uint64_t offset)> streamcb;
bool has_header(const char* key) const;
std::string get_header_value(const char* key) const;
void set_header(const char* key, const char* val);
void set_redirect(const char* uri);
void set_content(const char* s, size_t n, const char* content_type);
void set_content(const std::string& s, const char* content_type);
Response() : status(-1) {}
};
class Stream {
public:
virtual ~Stream() {}
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 std::string get_remote_addr() const = 0;
template <typename ...Args>
void write_format(const char* fmt, const Args& ...args);
};
class SocketStream : public Stream {
public:
SocketStream(socket_t sock);
virtual ~SocketStream();
virtual int read(char* ptr, size_t size);
virtual int write(const char* ptr, size_t size);
virtual int write(const char* ptr);
virtual std::string get_remote_addr() const;
private:
socket_t sock_;
};
class BufferStream : public Stream {
public:
BufferStream() {}
virtual ~BufferStream() {}
virtual int read(char* ptr, size_t size);
virtual int write(const char* ptr, size_t size);
virtual int write(const char* ptr);
virtual std::string get_remote_addr() const;
const std::string& get_buffer() const;
private:
std::string buffer;
};
class Server {
public:
typedef std::function<void (const Request&, Response&)> Handler;
typedef std::function<void (const Request&, const Response&)> Logger;
Server();
virtual ~Server();
virtual bool is_valid() const;
Server& Get(const char* pattern, Handler handler);
Server& Post(const char* pattern, Handler handler);
Server& Put(const char* pattern, Handler handler);
Server& Delete(const char* pattern, Handler handler);
Server& Options(const char* pattern, Handler handler);
bool set_base_dir(const char* path);
void set_error_handler(Handler handler);
void set_logger(Logger logger);
void set_keep_alive_max_count(size_t count);
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();
protected:
bool process_request(Stream& strm, bool last_connection, bool& connection_close);
size_t keep_alive_max_count_;
private:
typedef std::vector<std::pair<std::regex, Handler>> Handlers;
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);
bool handle_file_request(Request& req, Response& res);
bool dispatch_request(Request& req, Response& res, Handlers& handlers);
bool parse_request_line(const char* s, Request& req);
void write_response(Stream& strm, bool last_connection, const Request& req, Response& res);
virtual bool read_and_close_socket(socket_t sock);
bool is_running_;
socket_t svr_sock_;
std::string base_dir_;
Handlers get_handlers_;
Handlers post_handlers_;
Handlers put_handlers_;
Handlers delete_handlers_;
Handlers options_handlers_;
Handler error_handler_;
Logger logger_;
// TODO: Use thread pool...
std::mutex running_threads_mutex_;
int running_threads_;
};
class Client {
public:
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, Progress progress = nullptr);
std::shared_ptr<Response> Get(const char* path, const Headers& headers, Progress progress = nullptr);
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);
std::shared_ptr<Response> Post(const char* path, const Headers& headers, const std::string& body, const char* content_type);
std::shared_ptr<Response> Post(const char* path, const Params& params);
std::shared_ptr<Response> Post(const char* path, const Headers& headers, const Params& params);
std::shared_ptr<Response> Put(const char* path, const std::string& body, const char* content_type);
std::shared_ptr<Response> Put(const char* path, const Headers& headers, const std::string& body, const char* content_type);
std::shared_ptr<Response> Delete(const char* path);
std::shared_ptr<Response> Delete(const char* path, const Headers& headers);
std::shared_ptr<Response> Options(const char* path);
std::shared_ptr<Response> Options(const char* path, const Headers& headers);
bool send(Request& req, Response& res);
protected:
bool process_request(Stream& strm, Request& req, Response& res, bool& connection_close);
const std::string host_;
const int port_;
time_t timeout_sec_;
const std::string host_and_port_;
private:
socket_t create_client_socket() const;
bool read_response_line(Stream& strm, Response& res);
void write_request(Stream& strm, Request& req);
virtual bool read_and_close_socket(socket_t sock, Request& req, Response& res);
};
#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
class SSLSocketStream : public Stream {
public:
SSLSocketStream(socket_t sock, SSL* ssl);
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 std::string get_remote_addr() const;
private:
socket_t sock_;
SSL* ssl_;
};
class SSLServer : public Server {
public:
SSLServer(
const char* cert_path, const char* private_key_path);
virtual ~SSLServer();
virtual bool is_valid() const;
private:
virtual bool read_and_close_socket(socket_t sock);
SSL_CTX* ctx_;
std::mutex ctx_mutex_;
};
class SSLClient : public Client {
public:
SSLClient(
const char* host,
int port = 80,
time_t timeout_sec = 300);
virtual ~SSLClient();
virtual bool is_valid() const;
private:
virtual bool read_and_close_socket(socket_t sock, Request& req, Response& res);
SSL_CTX* ctx_;
std::mutex ctx_mutex_;
};
#endif
/*
* Implementation
*/
namespace detail {
template <class Fn>
void split(const char* b, const char* e, char d, Fn fn)
{
int i = 0;
int beg = 0;
while (e ? (b + i != e) : (b[i] != '\0')) {
if (b[i] == d) {
fn(&b[beg], &b[i]);
beg = i + 1;
}
i++;
}
if (i) {
fn(&b[beg], &b[i]);
}
}
// NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
// to store data. The call can set memory on stack for performance.
class stream_line_reader {
public:
stream_line_reader(Stream& strm, char* fixed_buffer, size_t fixed_buffer_size)
: strm_(strm)
, fixed_buffer_(fixed_buffer)
, fixed_buffer_size_(fixed_buffer_size) {
}
const char* ptr() const {
if (glowable_buffer_.empty()) {
return fixed_buffer_;
} else {
return glowable_buffer_.data();
}
}
bool getline() {
fixed_buffer_used_size_ = 0;
glowable_buffer_.clear();
for (size_t i = 0; ; i++) {
char byte;
auto n = strm_.read(&byte, 1);
if (n < 0) {
return false;
} else if (n == 0) {
if (i == 0) {
return false;
} else {
break;
}
}
append(byte);
if (byte == '\n') {
break;
}
}
return true;
}
private:
void append(char c) {
if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
fixed_buffer_[fixed_buffer_used_size_++] = c;
fixed_buffer_[fixed_buffer_used_size_] = '\0';
} else {
if (glowable_buffer_.empty()) {
assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
glowable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
}
glowable_buffer_ += c;
}
}
Stream& strm_;
char* fixed_buffer_;
const size_t fixed_buffer_size_;
size_t fixed_buffer_used_size_;
std::string glowable_buffer_;
};
inline int close_socket(socket_t sock)
{
#ifdef _WIN32
return closesocket(sock);
#else
return close(sock);
#endif
}
inline int select_read(socket_t sock, time_t sec, time_t usec)
{
fd_set fds;
FD_ZERO(&fds);
FD_SET(sock, &fds);
timeval tv;
tv.tv_sec = sec;
tv.tv_usec = usec;
return select(sock + 1, &fds, NULL, NULL, &tv);
}
inline bool wait_until_socket_is_ready(socket_t sock, time_t sec, time_t usec)
{
fd_set fdsr;
FD_ZERO(&fdsr);
FD_SET(sock, &fdsr);
auto fdsw = fdsr;
auto fdse = fdsr;
timeval tv;
tv.tv_sec = sec;
tv.tv_usec = usec;
if (select(sock + 1, &fdsr, &fdsw, &fdse, &tv) < 0) {
return false;
} else if (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw)) {
int error = 0;
socklen_t len = sizeof(error);
if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (char*)&error, &len) < 0 || error) {
return false;
}
} else {
return false;
}
return true;
}
template <typename T>
inline bool read_and_close_socket(socket_t sock, size_t keep_alive_max_count, T callback)
{
bool ret = false;
if (keep_alive_max_count > 0) {
auto count = keep_alive_max_count;
while (count > 0 &&
detail::select_read(sock,
CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND,
CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND) > 0) {
SocketStream strm(sock);
auto last_connection = count == 1;
auto connection_close = false;
ret = callback(strm, last_connection, connection_close);
if (!ret || connection_close) {
break;
}
count--;
}
} else {
SocketStream strm(sock);
auto dummy_connection_close = false;
ret = callback(strm, true, dummy_connection_close);
}
close_socket(sock);
return ret;
}
inline int shutdown_socket(socket_t sock)
{
#ifdef _WIN32
return shutdown(sock, SD_BOTH);
#else
return shutdown(sock, SHUT_RDWR);
#endif
}
template <typename Fn>
socket_t create_socket(const char* host, int port, Fn fn, int socket_flags = 0)
{
#ifdef _WIN32
#define SO_SYNCHRONOUS_NONALERT 0x20
#define SO_OPENTYPE 0x7008
int opt = SO_SYNCHRONOUS_NONALERT;
setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char*)&opt, sizeof(opt));
#endif
// Get address info
struct addrinfo hints;
struct addrinfo *result;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = socket_flags;
hints.ai_protocol = 0;
auto service = std::to_string(port);
if (getaddrinfo(host, service.c_str(), &hints, &result)) {
return INVALID_SOCKET;
}
for (auto rp = result; rp; rp = rp->ai_next) {
// Create a socket
auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sock == INVALID_SOCKET) {
continue;
}
// Make 'reuse address' option available
int yes = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(yes));
// bind or connect
if (fn(sock, *rp)) {
freeaddrinfo(result);
return sock;
}
close_socket(sock);
}
freeaddrinfo(result);
return INVALID_SOCKET;
}
inline void set_nonblocking(socket_t sock, bool nonblocking)
{
#ifdef _WIN32
auto flags = nonblocking ? 1UL : 0UL;
ioctlsocket(sock, FIONBIO, &flags);
#else
auto flags = fcntl(sock, F_GETFL, 0);
fcntl(sock, F_SETFL, nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
#endif
}
inline bool is_connection_error()
{
#ifdef _WIN32
return WSAGetLastError() != WSAEWOULDBLOCK;
#else
return errno != EINPROGRESS;
#endif
}
inline std::string get_remote_addr(socket_t sock) {
struct sockaddr_storage addr;
socklen_t len = sizeof(addr);
if (!getpeername(sock, (struct sockaddr*)&addr, &len)) {
char ipstr[NI_MAXHOST];
if (!getnameinfo((struct sockaddr*)&addr, len,
ipstr, sizeof(ipstr), nullptr, 0, NI_NUMERICHOST)) {
return ipstr;
}
}
return std::string();
}
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++;
}
while (i < path.size()) {
// Read component
auto beg = i;
while (i < path.size() && path[i] != '/') {
i++;
}
auto len = i - beg;
assert(len > 0);
if (!path.compare(beg, len, ".")) {
;
} else if (!path.compare(beg, len, "..")) {
if (level == 0) {
return false;
}
level--;
} else {
level++;
}
// Skip slash
while (i < path.size() && path[i] == '/') {
i++;
}
}
return true;
}
inline void read_file(const std::string& path, std::string& out)
{
std::ifstream fs(path, std::ios_base::binary);
fs.seekg(0, std::ios_base::end);
auto size = fs.tellg();
fs.seekg(0);
out.resize(static_cast<size_t>(size));
fs.read(&out[0], size);
}
inline std::string file_extension(const std::string& path)
{
std::smatch m;
auto pat = std::regex("\\.([a-zA-Z0-9]+)$");
if (std::regex_search(path, m, pat)) {
return m[1].str();
}
return std::string();
}
inline const char* find_content_type(const std::string& path)
{
auto ext = file_extension(path);
if (ext == "txt") {
return "text/plain";
} else if (ext == "html") {
return "text/html";
} else if (ext == "css") {
return "text/css";
} else if (ext == "jpeg" || ext == "jpg") {
return "image/jpg";
} else if (ext == "png") {
return "image/png";
} else if (ext == "gif") {
return "image/gif";
} else if (ext == "svg") {
return "image/svg+xml";
} else if (ext == "ico") {
return "image/x-icon";
} else if (ext == "json") {
return "application/json";
} else if (ext == "pdf") {
return "application/pdf";
} else if (ext == "js") {
return "application/javascript";
} else if (ext == "xml") {
return "application/xml";
} else if (ext == "xhtml") {
return "application/xhtml+xml";
}
return nullptr;
}
inline const char* status_message(int status)
{
switch (status) {
case 200: return "OK";
case 301: return "Moved Permanently";
case 302: return "Found";
case 303: return "See Other";
case 304: return "Not Modified";
case 400: return "Bad Request";
case 403: return "Forbidden";
case 404: return "Not Found";
case 415: return "Unsupported Media Type";
default:
case 500: return "Internal Server Error";
}
}
inline bool has_header(const Headers& headers, const char* key)
{
return headers.find(key) != headers.end();
}
inline const char* get_header_value(
const Headers& headers, const char* key, const char* def = nullptr)
{
auto it = headers.find(key);
if (it != headers.end()) {
return it->second.c_str();
}
return def;
}
inline int get_header_value_int(const Headers& headers, const char* key, int def = 0)
{
auto it = headers.find(key);
if (it != headers.end()) {
return std::stoi(it->second);
}
return def;
}
inline bool read_headers(Stream& strm, Headers& headers)
{
static std::regex re(R"((.+?):\s*(.+?)\s*\r\n)");
const auto bufsiz = 2048;
char buf[bufsiz];
stream_line_reader reader(strm, buf, bufsiz);
for (;;) {
if (!reader.getline()) {
return false;
}
if (!strcmp(reader.ptr(), "\r\n")) {
break;
}
std::cmatch m;
if (std::regex_match(reader.ptr(), m, re)) {
auto key = std::string(m[1]);
auto val = std::string(m[2]);
headers.emplace(key, val);
}
}
return true;
}
inline bool read_content_with_length(Stream& strm, std::string& out, size_t len, Progress progress)
{
out.assign(len, 0);
size_t r = 0;
while (r < len){
auto n = strm.read(&out[r], len - r);
if (n <= 0) {
return false;
}
r += n;
if (progress) {
if (!progress(r, len)) {
return false;
}
}
}
return true;
}
inline bool read_content_without_length(Stream& strm, std::string& out)
{
for (;;) {
char byte;
auto n = strm.read(&byte, 1);
if (n < 0) {
return false;
} else if (n == 0) {
return true;
}
out += byte;
}
return true;
}
inline bool read_content_chunked(Stream& strm, std::string& out)
{
const auto bufsiz = 16;
char buf[bufsiz];
stream_line_reader reader(strm, buf, bufsiz);
if (!reader.getline()) {
return false;
}
auto chunk_len = std::stoi(reader.ptr(), 0, 16);
while (chunk_len > 0){
std::string chunk;
if (!read_content_with_length(strm, chunk, chunk_len, nullptr)) {
return false;
}
if (!reader.getline()) {
return false;
}
if (strcmp(reader.ptr(), "\r\n")) {
break;
}
out += chunk;
if (!reader.getline()) {
return false;
}
chunk_len = std::stoi(reader.ptr(), 0, 16);
}
if (chunk_len == 0) {
// Reader terminator after chunks
if (!reader.getline() || strcmp(reader.ptr(), "\r\n"))
return false;
}
return true;
}
template <typename T>
bool read_content(Stream& strm, T& x, Progress progress = Progress())
{
if (has_header(x.headers, "Content-Length")) {
auto len = get_header_value_int(x.headers, "Content-Length", 0);
if (len == 0) {
const auto& encoding = get_header_value(x.headers, "Transfer-Encoding", "");
if (!strcasecmp(encoding, "chunked")) {
return read_content_chunked(strm, x.body);
}
}
return read_content_with_length(strm, x.body, len, progress);
} else {
const auto& encoding = get_header_value(x.headers, "Transfer-Encoding", "");
if (!strcasecmp(encoding, "chunked")) {
return read_content_chunked(strm, x.body);
}
return read_content_without_length(strm, x.body);
}
return true;
}
template <typename T>
inline void write_headers(Stream& strm, const T& info)
{
for (const auto& x: info.headers) {
strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str());
}
strm.write("\r\n");
}
inline std::string encode_url(const std::string& s)
{
std::string result;
for (auto i = 0; s[i]; i++) {
switch (s[i]) {
case ' ': result += "%20"; break;
case '+': result += "%2B"; break;
case '\'': result += "%27"; break;
case ',': result += "%2C"; break;
case ':': result += "%3A"; break;
case ';': result += "%3B"; break;
default:
auto c = static_cast<uint8_t>(s[i]);
if (c >= 0x80) {
result += '%';
char hex[4];
size_t len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
assert(len == 2);
result.append(hex, len);
} else {
result += s[i];
}
break;
}
}
return result;
}
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(uint64_t n)
{
const char *charset = "0123456789abcdef";
std::string ret;