-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpolyweb.cpp
More file actions
1045 lines (945 loc) · 43.2 KB
/
polyweb.cpp
File metadata and controls
1045 lines (945 loc) · 43.2 KB
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
#include "polyweb.hpp"
#include <algorithm>
#include <bitset>
#include <charconv>
#include <codecvt>
#include <iomanip>
#include <iterator>
#include <locale>
#include <sstream>
#include <string.h>
#include <wchar.h>
namespace pw {
tp::ThreadPool thread_pool(std::max<unsigned int>(std::thread::hardware_concurrency(), 16));
namespace detail {
thread_local int last_error = PW_ESUCCESS;
static constexpr char base64_alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
void reverse_memcpy(char* __restrict dest, const char* __restrict src, size_t size) {
for (size_t i = 0; i < size; ++i) {
dest[i] = src[size - 1 - i];
}
}
void reverse_memmove(char* dest, const char* src, size_t size) {
if (dest >= src && dest < src + size) {
char* buf = new char[size];
for (size_t i = 0; i < size; ++i) {
buf[i] = src[size - 1 - i];
}
memcpy(dest, buf, size);
delete[] buf;
} else {
reverse_memcpy(dest, src, size);
}
}
} // namespace detail
void reverse_memcpy(void* __restrict dest, const void* __restrict src, size_t size) {
detail::reverse_memcpy((char*) dest, (const char*) src, size);
}
void reverse_memmove(void* dest, const void* src, size_t size) {
detail::reverse_memmove((char*) dest, (const char*) src, size);
}
std::string strerror(int error) {
const static std::string error_strings[] = {
"Success", // PW_ESUCCESS
"Network error", // PW_ENET
"Web error", // PW_EWEB
};
if (error >= 0 && error <= 2) {
return error_strings[error];
}
return "Unknown error";
}
std::string universal_strerror(int error) {
std::string base_error = strerror(error);
std::string specific_error;
switch (error) {
case PW_ENET:
specific_error = pn::universal_strerror();
break;
default:
return base_error;
}
return base_error + ": " + specific_error;
}
std::string build_date(time_t rawtime) {
#ifdef _WIN32
struct tm timeinfo = *gmtime(&rawtime);
#else
struct tm timeinfo;
gmtime_r(&rawtime, &timeinfo);
#endif
std::ostringstream ss;
ss.imbue(std::locale("C"));
ss << std::put_time(&timeinfo, "%a, %d %b %Y %H:%M:%S GMT");
return ss.str();
}
time_t parse_date(const std::string& date) {
struct tm timeinfo = {0};
std::istringstream ss(date);
ss.imbue(std::locale("C"));
ss >> std::get_time(&timeinfo, "%a, %d %b %Y %H:%M:%S GMT");
#ifdef _WIN32
return _mkgmtime(&timeinfo);
#else
return timegm(&timeinfo);
#endif
}
std::string base64_encode(const unsigned char* data, size_t size) {
std::string ret;
ret.reserve(size + (size / 3));
size_t i = 0;
for (; i + 3 <= size; i += 3) {
std::bitset<24> bits((((uint32_t) data[i]) << 16) | (((uint32_t) data[i + 1]) << 8) | data[i + 2]);
ret.insert(ret.end(),
{
detail::base64_alphabet[(bits >> 18).to_ulong()],
detail::base64_alphabet[((bits >> 12) & std::bitset<24>(0x3F)).to_ulong()],
detail::base64_alphabet[((bits >> 6) & std::bitset<24>(0x3F)).to_ulong()],
detail::base64_alphabet[(bits & std::bitset<24>(0x3F)).to_ulong()],
});
}
if (size_t leftover = size - i) {
switch (leftover) {
case 1: {
std::bitset<12> bits(((uint32_t) data[i]) << 4);
ret.insert(ret.end(),
{
detail::base64_alphabet[(bits >> 6).to_ulong()],
detail::base64_alphabet[(bits & std::bitset<12>(0x3F)).to_ulong()],
'=',
'=',
});
break;
}
case 2: {
std::bitset<18> bits((((uint32_t) data[i]) << 10) | (((uint32_t) data[i + 1]) << 2));
ret.insert(ret.end(),
{
detail::base64_alphabet[(bits >> 12).to_ulong()],
detail::base64_alphabet[((bits >> 6) & std::bitset<18>(0x3F)).to_ulong()],
detail::base64_alphabet[(bits & std::bitset<18>(0x3F)).to_ulong()],
'=',
});
break;
}
}
}
return ret;
}
std::string base64_encode(const char* data, size_t size) {
return base64_encode((const unsigned char*) data, size);
}
std::vector<char> base64_decode(pn::StringView str) {
std::vector<uint8_t> indices;
indices.reserve(str.size());
for (char c : str) {
if (const char* ptr = strchr(detail::base64_alphabet, c)) {
indices.push_back(ptr - detail::base64_alphabet);
} else {
break;
}
}
std::vector<char> ret;
ret.reserve(indices.size() * 6 / 8);
size_t i = 0;
for (; i + 4 <= indices.size(); i += 4) {
std::bitset<24> bits((((uint32_t) indices[i]) << 18) | (((uint32_t) indices[i + 1]) << 12) | (((uint32_t) indices[i + 2]) << 6) | indices[i + 3]);
ret.insert(ret.end(),
{
(char) (bits >> 16).to_ulong(),
(char) ((bits >> 8) & std::bitset<24>(0xFF)).to_ulong(),
(char) (bits & std::bitset<24>(0xFF)).to_ulong(),
});
}
if (size_t leftover = indices.size() - i) {
switch (leftover) {
case 2: {
std::bitset<12> bits((((uint32_t) indices[i]) << 6) | indices[i + 1]);
ret.push_back((bits >> 4).to_ulong());
break;
}
case 3: {
std::bitset<18> bits((((uint32_t) indices[i]) << 12) | (((uint32_t) indices[i + 1]) << 6) | indices[i + 2]);
ret.insert(ret.end(),
{
(char) (bits >> 10).to_ulong(),
(char) ((bits >> 2) & std::bitset<18>(0xFF)).to_ulong(),
});
break;
}
}
}
return ret;
}
std::string percent_encode(pn::StringView str, bool plus_as_space, bool allow_slash) {
std::string ret;
ret.reserve(str.size());
for (char c : str) {
static constexpr char allowed_characters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~@:";
if (plus_as_space && c == ' ') {
ret.push_back('+');
} else if (allow_slash && c == '/') {
ret.push_back('/');
} else if (c == '\0' || strchr(allowed_characters, c) == nullptr) {
unsigned char upper_nibble = (unsigned char) (c & 0xF0) >> 4;
unsigned char lower_nibble = c & 0xF;
ret.push_back('%');
ret.push_back(upper_nibble < 10 ? '0' + upper_nibble : 'A' + upper_nibble - 10);
ret.push_back(lower_nibble < 10 ? '0' + lower_nibble : 'A' + lower_nibble - 10);
} else {
ret.push_back(c);
}
}
return ret;
}
std::string percent_decode(pn::StringView str, bool plus_as_space) {
std::string ret;
ret.reserve(str.size());
int reading_percent = 0;
unsigned char current_character;
for (char c : str) {
if (!reading_percent) {
if (c == '%') {
reading_percent = 2;
current_character = 0;
} else if (plus_as_space && c == '+') {
ret.push_back(' ');
} else {
ret.push_back(c);
}
} else {
unsigned char nibble;
if (c >= '0' && c <= '9') {
nibble = c - '0';
} else {
nibble = toupper((unsigned char) c) - 'A' + 10;
}
current_character |= nibble << ((reading_percent - 1) * 4);
if (!--reading_percent) {
ret.push_back(current_character);
}
}
}
return ret;
}
std::wstring xml_escape(pn::WStringView wstr) {
std::wstring ret;
ret.reserve(wstr.size() + (wstr.size() / 10));
for (wchar_t wc : wstr) {
static constexpr wchar_t allowed_characters[] = L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";
if (wcschr(allowed_characters, wc)) {
ret.push_back(wc);
} else {
std::wostringstream ss;
ss << L"&#" << +wc << L';';
ret += ss.str();
}
}
return ret;
}
std::string xml_escape(const std::string& str) {
static thread_local std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
return converter.to_bytes(xml_escape(converter.from_bytes(str)));
}
std::string status_code_to_reason_phrase(uint16_t status_code) {
const static std::unordered_map<uint16_t, std::string> conversion_mapping = {
{100, "Continue"},
{101, "Switching Protocols"},
{200, "OK"},
{201, "Created"},
{202, "Accepted"},
{203, "Non-Authoritative Information"},
{204, "No Content"},
{205, "Reset Content"},
{206, "Partial Content"},
{300, "Multiple Choices"},
{301, "Moved Permanently"},
{302, "Found"},
{303, "See Other"},
{304, "Not Modified"},
{305, "Use Proxy"},
{307, "Temporary Redirect"},
{400, "Bad Request"},
{401, "Unauthorized"},
{402, "Payment Required"},
{403, "Forbidden"},
{404, "Not Found"},
{405, "Method Not Allowed"},
{406, "Not Acceptable"},
{407, "Proxy Authentication Required"},
{408, "Request Time-out"},
{409, "Conflict"},
{410, "Gone"},
{411, "Length Required"},
{412, "Precondition Failed"},
{413, "Request Entity Too Large"},
{414, "Request-URI Too Large"},
{415, "Unsupported Media Type"},
{416, "Requested range not satisfiable"},
{417, "Expectation Failed"},
{418, "I'm a teapot"},
{426, "Upgrade Required"},
{500, "Internal Server Error"},
{501, "Not Implemented"},
{502, "Bad Gateway"},
{503, "Service Unavailable"},
{504, "Gateway Time-out"},
{505, "HTTP Version not supported"},
};
if (auto ret_it = conversion_mapping.find(status_code); ret_it != conversion_mapping.end()) {
return ret_it->second;
} else if (status_code >= 100 && status_code < 600) {
return conversion_mapping.at(status_code / 100 * 100); // Zero out last two digits
}
throw std::out_of_range("Invalid status code");
}
std::string QueryParameters::build() const {
std::string ret;
for (auto it = map.begin(); it != map.end(); ++it) {
if (it != map.begin()) ret.push_back('&');
std::string encoded_key = percent_encode(it->first, false, false);
std::string encoded_value = percent_encode(it->second, false, false);
ret.insert(ret.end(), encoded_key.begin(), encoded_key.end());
ret.push_back('=');
ret.insert(ret.end(), encoded_value.begin(), encoded_value.end());
}
return ret;
}
void QueryParameters::parse(pn::StringView query_string) {
std::vector<std::string> split_query_string = string::split(query_string, '&');
map.clear();
for (const auto& parameter : split_query_string) {
std::vector<std::string> split_parameter = string::split(parameter, '=');
if (split_parameter.size() >= 2) {
map[percent_decode(split_parameter[0], true)] = percent_decode(split_parameter[1], true);
} else if (!split_parameter.empty()) {
map[percent_decode(split_parameter[0], true)]; // Create key with empty value
}
}
}
std::string URLInfo::build() const {
std::string ret = scheme + "://";
if (!credentials.empty()) {
ret += percent_encode(username()) + ':' + percent_encode(password()) + '@';
}
ret += host;
if (path != "/" || !query_parameters->empty()) {
ret += path;
if (!query_parameters->empty()) {
ret += '?' + query_parameters.build();
}
}
return ret;
}
int URLInfo::parse(pn::StringView url) {
size_t offset = 0;
size_t scheme_host_delimiter_pos;
if ((scheme_host_delimiter_pos = url.find("://", offset)) == std::string::npos || scheme_host_delimiter_pos == offset) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
scheme = url.substr(offset, scheme_host_delimiter_pos - offset);
offset = scheme_host_delimiter_pos + 3;
credentials.clear();
size_t credentials_host_delimiter_pos;
if ((credentials_host_delimiter_pos = url.find('@', offset)) != std::string::npos &&
url.find('/', offset) > credentials_host_delimiter_pos) {
if (credentials_host_delimiter_pos == offset) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
credentials = percent_decode(url.substr(offset, credentials_host_delimiter_pos - offset));
offset = credentials_host_delimiter_pos + 1;
}
size_t path_pos;
if ((path_pos = url.find('/', offset)) != std::string::npos) {
if (path_pos == offset) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
host = url.substr(offset, path_pos - offset);
offset = path_pos + 1;
} else {
host = url.substr(offset);
path = '/';
return PN_OK;
}
size_t path_query_string_delimiter_pos;
if ((path_query_string_delimiter_pos = url.find('?', offset)) != std::string::npos) {
if (path_query_string_delimiter_pos == offset) {
path = '/';
} else {
path = '/' + url.substr(offset, path_query_string_delimiter_pos - offset);
}
offset = path_query_string_delimiter_pos + 1;
} else {
path = '/' + url.substr(offset, url.find('#', offset));
return PN_OK;
}
query_parameters.parse(url.substr(offset, url.find('#', offset)));
return PN_OK;
}
unsigned short URLInfo::port() const {
if (size_t hostname_port_delimiter_pos = host.find(':'); hostname_port_delimiter_pos == std::string::npos) {
return string::iequals(scheme, "https") || string::iequals(scheme, "wss") ? 443 : 80;
} else {
std::string port = host.substr(hostname_port_delimiter_pos + 1);
try {
return std::stoi(port);
} catch (...) {
return 80;
}
}
}
std::vector<char> HTTPRequest::build(int parts) const {
std::vector<char> ret;
if (parts & PW_HTTP_MESSAGE_PART_START_LINE) {
ret.insert(ret.end(), method.begin(), method.end());
ret.push_back(' ');
std::string encoded_target = percent_encode(target);
ret.insert(ret.end(), encoded_target.begin(), encoded_target.end());
if (!query_parameters->empty()) {
ret.push_back('?');
std::string query_string = query_parameters.build();
ret.insert(ret.end(), query_string.begin(), query_string.end());
}
ret.push_back(' ');
ret.insert(ret.end(), http_version.begin(), http_version.end());
ret.insert(ret.end(), {'\r', '\n'});
}
if (parts & PW_HTTP_MESSAGE_PART_HEADERS) {
for (const auto& header : headers) {
ret.insert(ret.end(), header.first.begin(), header.first.end());
ret.insert(ret.end(), {':', ' '});
ret.insert(ret.end(), header.second.begin(), header.second.end());
ret.insert(ret.end(), {'\r', '\n'});
}
if (send_cb) {
if (!headers.count("Transfer-Encoding")) {
std::string header = "Transfer-Encoding: chunked\r\n";
ret.insert(ret.end(), header.begin(), header.end());
}
} else if (!body.empty() && !headers.count("Content-Length")) {
std::string header = "Content-Length: " + std::to_string(body.size()) + "\r\n";
ret.insert(ret.end(), header.begin(), header.end());
}
ret.insert(ret.end(), {'\r', '\n'});
}
if (parts & PW_HTTP_MESSAGE_PART_BODY) {
if (send_cb) {
for (;;) {
if (auto chunk = send_cb(); !chunk.empty()) {
std::ostringstream ss;
ss << std::hex << chunk.size() << "\r\n";
std::string str = ss.str();
ret.insert(ret.end(), str.begin(), str.end());
ret.insert(ret.end(), chunk.begin(), chunk.end());
ret.insert(ret.end(), {'\r', '\n'});
} else {
static constexpr char last_chunk[] = "0\r\n\r\n";
ret.insert(ret.end(), last_chunk, last_chunk + 5);
break;
}
}
} else {
ret.insert(ret.end(), body.begin(), body.end());
}
}
return ret;
}
int HTTPRequest::build(pn::tcp::Connection& conn, int parts) const {
auto data = build(send_cb ? parts & ~PW_HTTP_MESSAGE_PART_BODY : parts);
if (pn::ssize_t result = conn.sendall(data.data(), data.size()); result == PN_ERROR) {
detail::set_last_error(PW_ENET);
return PN_ERROR;
} else if ((size_t) result != data.size()) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
if ((parts & PW_HTTP_MESSAGE_PART_BODY) && send_cb) {
for (;;) {
auto chunk = send_cb();
if (!chunk.empty()) {
std::ostringstream ss;
ss << std::hex << chunk.size() << "\r\n";
std::string str = ss.str();
chunk.insert(chunk.begin(), str.begin(), str.end());
chunk.insert(chunk.end(), {'\r', '\n'});
if (pn::ssize_t result = conn.sendall(chunk.data(), chunk.size()); result == PN_ERROR) {
detail::set_last_error(PW_ENET);
return PN_ERROR;
} else if ((size_t) result != chunk.size()) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
} else {
static constexpr char last_chunk[] = "0\r\n\r\n";
if (pn::ssize_t result = conn.sendall(last_chunk, 5); result == PN_ERROR) {
detail::set_last_error(PW_ENET);
return PN_ERROR;
} else if (result != 5) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
break;
}
}
}
return PN_OK;
}
int HTTPRequest::parse(pn::tcp::Connection& conn, pn::tcp::BufReceiver& buf_receiver, int parts, unsigned int header_climit, pn::ssize_t header_name_rlimit, pn::ssize_t header_value_rlimit, pn::ssize_t body_chunk_rlimit, pn::ssize_t body_rlimit, pn::ssize_t misc_rlimit) {
if (parts & PW_HTTP_MESSAGE_PART_START_LINE) {
method.clear();
if (detail::recv_until(conn, buf_receiver, std::back_inserter(method), ' ', misc_rlimit) == PN_ERROR) {
return PN_ERROR;
}
if (method.empty()) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
target.clear();
if (detail::recv_until(conn, buf_receiver, std::back_inserter(target), ' ', misc_rlimit) == PN_ERROR) {
return PN_ERROR;
}
if (target.empty()) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
query_parameters->clear();
if (auto query_string_begin = std::find(target.begin(), target.end(), '?'); query_string_begin != target.end()) {
if (std::next(query_string_begin) != target.end()) {
query_parameters.parse(std::string(std::next(query_string_begin), target.end()));
}
target.resize(std::distance(target.begin(), query_string_begin));
}
target = percent_decode(target);
http_version.clear();
if (detail::recv_until(conn, buf_receiver, std::back_inserter(http_version), "\r\n", misc_rlimit) == PN_ERROR) {
return PN_ERROR;
}
if (http_version.empty()) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
}
if (parts & PW_HTTP_MESSAGE_PART_HEADERS) {
headers.clear();
for (unsigned int i = 0;; ++i) {
if (i > header_climit) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
std::string header_name;
if (detail::recv_until(conn, buf_receiver, std::back_inserter(header_name), ':', header_name_rlimit) == PN_ERROR) {
return PN_ERROR;
}
if (header_name.empty()) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
std::string header_value;
if (detail::recv_until(conn, buf_receiver, std::back_inserter(header_value), "\r\n", header_value_rlimit) == PN_ERROR) {
return PN_ERROR;
}
string::trim(header_value);
headers.insert_or_assign(std::move(header_name), std::move(header_value));
char crlf[2];
if (pn::ssize_t result = buf_receiver.recvall(conn, crlf, 2); result == PN_ERROR) {
detail::set_last_error(PW_ENET);
return PN_ERROR;
} else if (result != 2) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
if (!memcmp("\r\n", crlf, 2)) {
break;
}
buf_receiver.rewind(crlf, 2);
}
}
if (parts & PW_HTTP_MESSAGE_PART_BODY) {
body.clear();
if (auto transfer_encoding_it = headers.find("Transfer-Encoding"); transfer_encoding_it != headers.end()) {
if (string::iequals(transfer_encoding_it->second, "chunked")) {
unsigned long long chunk_size;
do {
std::string chunk_size_string;
if (detail::recv_until(conn, buf_receiver, std::back_inserter(chunk_size_string), "\r\n", misc_rlimit) == PN_ERROR) {
return PN_ERROR;
}
if (chunk_size_string.empty()) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
if (auto result = std::from_chars(chunk_size_string.data(), chunk_size_string.data() + chunk_size_string.size(), chunk_size, 16);
result.ec != std::errc {} || result.ptr != chunk_size_string.data() + chunk_size_string.size()) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
if (chunk_size) {
if (recv_cb) {
for (size_t received = 0; received < chunk_size;) {
std::vector<char> chunk(std::min<size_t>(chunk_size - received, body_chunk_rlimit));
if (pn::ssize_t result = buf_receiver.recvall(conn, chunk.data(), chunk.size()); result == PN_ERROR) {
detail::set_last_error(PW_ENET);
return PN_ERROR;
} else if ((unsigned long long) result != chunk.size()) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
received += chunk.size();
if (!recv_cb(std::move(chunk))) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
}
} else {
size_t end = body.size();
if (end + chunk_size > (unsigned long long) body_rlimit) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
body.resize(end + chunk_size);
if (pn::ssize_t result = buf_receiver.recvall(conn, &body[end], chunk_size); result == PN_ERROR) {
detail::set_last_error(PW_ENET);
return PN_ERROR;
} else if ((unsigned long long) result != chunk_size) {
detail::set_last_error(PW_EWEB);
body.resize(end + result);
return PN_ERROR;
}
}
}
char crlf[2];
if (pn::ssize_t result = buf_receiver.recvall(conn, crlf, 2); result == PN_ERROR) {
detail::set_last_error(PW_ENET);
return PN_ERROR;
} else if (result != 2) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
} while (chunk_size);
} else { // Only chunked transfer encoding is supported atm
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
} else if (auto content_len_it = headers.find("Content-Length"); content_len_it != headers.end()) {
unsigned long long content_len;
try {
content_len = std::stoull(content_len_it->second);
} catch (...) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
if (content_len) {
if (recv_cb) {
for (size_t received = 0; received < content_len;) {
std::vector<char> chunk(std::min<size_t>(content_len - received, body_chunk_rlimit));
if (pn::ssize_t result = buf_receiver.recvall(conn, chunk.data(), chunk.size()); result == PN_ERROR) {
detail::set_last_error(PW_ENET);
return PN_ERROR;
} else if ((unsigned long long) result != chunk.size()) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
received += chunk.size();
if (!recv_cb(std::move(chunk))) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
}
} else {
if (content_len > (unsigned long long) body_rlimit) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
body.resize(content_len);
if (pn::ssize_t result = buf_receiver.recvall(conn, body.data(), content_len); result == PN_ERROR) {
detail::set_last_error(PW_ENET);
return PN_ERROR;
} else if ((unsigned long long) result != content_len) {
detail::set_last_error(PW_EWEB);
body.resize(result);
return PN_ERROR;
}
}
}
}
}
return PN_OK;
}
std::vector<char> HTTPResponse::build(int parts) const {
std::vector<char> ret;
if (parts & PW_HTTP_MESSAGE_PART_START_LINE) {
ret.insert(ret.end(), http_version.begin(), http_version.end());
ret.push_back(' ');
std::string status_code_string = std::to_string(status_code);
ret.insert(ret.end(), status_code_string.begin(), status_code_string.end());
ret.push_back(' ');
ret.insert(ret.end(), reason_phrase.begin(), reason_phrase.end());
ret.insert(ret.end(), {'\r', '\n'});
}
if (parts & PW_HTTP_MESSAGE_PART_HEADERS) {
for (const auto& header : headers) {
ret.insert(ret.end(), header.first.begin(), header.first.end());
ret.insert(ret.end(), {':', ' '});
ret.insert(ret.end(), header.second.begin(), header.second.end());
ret.insert(ret.end(), {'\r', '\n'});
}
if (!headers.count("Date")) {
std::string header = "Date: " + build_date() + "\r\n";
ret.insert(ret.end(), header.begin(), header.end());
}
if (send_cb) {
if (!headers.count("Transfer-Encoding")) {
std::string header = "Transfer-Encoding: chunked\r\n";
ret.insert(ret.end(), header.begin(), header.end());
}
} else if (!headers.count("Content-Length")) {
std::string header = "Content-Length: " + std::to_string(body.size()) + "\r\n";
ret.insert(ret.end(), header.begin(), header.end());
}
ret.insert(ret.end(), {'\r', '\n'});
}
if (parts & PW_HTTP_MESSAGE_PART_BODY) {
if (send_cb) {
for (;;) {
if (auto chunk = send_cb(); !chunk.empty()) {
std::ostringstream ss;
ss << std::hex << chunk.size() << "\r\n";
std::string str = ss.str();
ret.insert(ret.end(), str.begin(), str.end());
ret.insert(ret.end(), chunk.begin(), chunk.end());
ret.insert(ret.end(), {'\r', '\n'});
} else {
static constexpr char last_chunk[] = "0\r\n\r\n";
ret.insert(ret.end(), last_chunk, last_chunk + 5);
break;
}
}
} else {
ret.insert(ret.end(), body.begin(), body.end());
}
}
return ret;
}
int HTTPResponse::build(pn::tcp::Connection& conn, int parts) const {
auto data = build(send_cb ? parts & ~PW_HTTP_MESSAGE_PART_BODY : parts);
if (pn::ssize_t result = conn.sendall(data.data(), data.size()); result == PN_ERROR) {
detail::set_last_error(PW_ENET);
return PN_ERROR;
} else if ((size_t) result != data.size()) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
if ((parts & PW_HTTP_MESSAGE_PART_BODY) && send_cb) {
for (;;) {
auto chunk = send_cb();
if (!chunk.empty()) {
std::ostringstream ss;
ss << std::hex << chunk.size() << "\r\n";
std::string str = ss.str();
chunk.insert(chunk.begin(), str.begin(), str.end());
chunk.insert(chunk.end(), {'\r', '\n'});
if (pn::ssize_t result = conn.sendall(chunk.data(), chunk.size()); result == PN_ERROR) {
detail::set_last_error(PW_ENET);
return PN_ERROR;
} else if ((size_t) result != chunk.size()) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
} else {
static constexpr char last_chunk[] = "0\r\n\r\n";
if (pn::ssize_t result = conn.sendall(last_chunk, 5); result == PN_ERROR) {
detail::set_last_error(PW_ENET);
return PN_ERROR;
} else if (result != 5) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
break;
}
}
}
return PN_OK;
}
int HTTPResponse::parse(pn::tcp::Connection& conn, pn::tcp::BufReceiver& buf_receiver, int parts, unsigned int header_climit, pn::ssize_t header_name_rlimit, pn::ssize_t header_value_rlimit, pn::ssize_t body_chunk_rlimit, pn::ssize_t body_rlimit, pn::ssize_t misc_rlimit) {
if (parts & PW_HTTP_MESSAGE_PART_START_LINE) {
http_version.clear();
if (detail::recv_until(conn, buf_receiver, std::back_inserter(http_version), ' ', misc_rlimit) == PN_ERROR) {
return PN_ERROR;
}
if (http_version.empty()) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
std::string status_code_string;
if (detail::recv_until(conn, buf_receiver, std::back_inserter(status_code_string), ' ', misc_rlimit) == PN_ERROR) {
return PN_ERROR;
}
if (status_code_string.empty()) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
try {
status_code = std::stoi(status_code_string);
} catch (...) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
reason_phrase.clear();
if (detail::recv_until(conn, buf_receiver, std::back_inserter(reason_phrase), "\r\n", misc_rlimit) == PN_ERROR) {
return PN_ERROR;
}
if (reason_phrase.empty()) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
}
if (parts & PW_HTTP_MESSAGE_PART_HEADERS) {
headers.clear();
for (unsigned int i = 0;; ++i) {
if (i > header_climit) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
std::string header_name;
if (detail::recv_until(conn, buf_receiver, std::back_inserter(header_name), ':', header_name_rlimit) == PN_ERROR) {
return PN_ERROR;
}
if (header_name.empty()) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
std::string header_value;
if (detail::recv_until(conn, buf_receiver, std::back_inserter(header_value), "\r\n", header_value_rlimit) == PN_ERROR) {
return PN_ERROR;
}
string::trim(header_value);
headers.insert_or_assign(std::move(header_name), std::move(header_value));
char crlf[2];
if (pn::ssize_t result = buf_receiver.recvall(conn, crlf, 2); result == PN_ERROR) {
detail::set_last_error(PW_ENET);
return PN_ERROR;
} else if (result != 2) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
if (!memcmp("\r\n", crlf, 2)) {
break;
}
buf_receiver.rewind(crlf, 2);
}
}
if (parts & PW_HTTP_MESSAGE_PART_BODY) {
body.clear();
if (auto transfer_encoding_it = headers.find("Transfer-Encoding"); transfer_encoding_it != headers.end()) {
if (string::iequals(transfer_encoding_it->second, "chunked")) {
unsigned long long chunk_size;
do {
std::string chunk_size_string;
if (detail::recv_until(conn, buf_receiver, std::back_inserter(chunk_size_string), "\r\n", misc_rlimit) == PN_ERROR) {
return PN_ERROR;
}
if (chunk_size_string.empty()) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
if (auto result = std::from_chars(chunk_size_string.data(), chunk_size_string.data() + chunk_size_string.size(), chunk_size, 16);
result.ec != std::errc {} || result.ptr != chunk_size_string.data() + chunk_size_string.size()) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
if (chunk_size) {
if (recv_cb) {
for (size_t received = 0; received < chunk_size;) {
std::vector<char> chunk(std::min<size_t>(chunk_size - received, body_chunk_rlimit));
if (pn::ssize_t result = buf_receiver.recvall(conn, chunk.data(), chunk.size()); result == PN_ERROR) {
detail::set_last_error(PW_ENET);
return PN_ERROR;
} else if ((unsigned long long) result != chunk.size()) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
received += chunk.size();
if (!recv_cb(std::move(chunk))) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
}
} else {
size_t end = body.size();
if (end + chunk_size > (unsigned long long) body_rlimit) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
body.resize(end + chunk_size);
if (pn::ssize_t result = buf_receiver.recvall(conn, &body[end], chunk_size); result == PN_ERROR) {
detail::set_last_error(PW_ENET);
return PN_ERROR;
} else if ((unsigned long long) result != chunk_size) {
detail::set_last_error(PW_EWEB);
body.resize(end + result);
return PN_ERROR;
}
}
}
char crlf[2];
if (pn::ssize_t result = buf_receiver.recvall(conn, crlf, 2); result == PN_ERROR) {
detail::set_last_error(PW_ENET);
return PN_ERROR;
} else if (result != 2) {
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
} while (chunk_size);
} else { // Only chunked transfer encoding is supported atm
detail::set_last_error(PW_EWEB);
return PN_ERROR;
}
} else if (auto content_len_it = headers.find("Content-Length"); content_len_it != headers.end()) {
unsigned long long content_len;
try {
content_len = std::stoull(content_len_it->second);