-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathnativeHTTP.h
More file actions
1753 lines (1534 loc) · 77.4 KB
/
nativeHTTP.h
File metadata and controls
1753 lines (1534 loc) · 77.4 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
// ABDO10_DZ (C) nativeHTTP/3.0.0
#pragma once
#ifndef nativeHTTP_H_
#define nativeHTTP_H_
#include <string>
#include <vector>
#include <map>
#include <memory>
#include <iostream>
#include <sstream>
#include <fstream>
#include <algorithm>
#include <random>
#include <chrono>
#include <functional>
#include <thread>
#include <atomic>
#include <future> // for std::async, std::future
#include <iomanip>
#include <ctime>
#include <cctype>
#include <regex>
#include <mutex>
#include <condition_variable> // optional but harmless
// Feature flags - FIXED: Disable HTTP3 by default
#ifndef NATIVE_HTTP_DEBUG
#define NATIVE_HTTP_DEBUG 1
#endif
#ifndef NATIVE_HTTP_WEBSOCKET_MINIMAL
#define NATIVE_HTTP_WEBSOCKET_MINIMAL 0 // 0 for full WebSocket implementation
#endif
#ifndef NATIVE_HTTP_HTTP3_SUPPORT
#define NATIVE_HTTP_HTTP3_SUPPORT 0 // HTTP/3 support disabled (requires external libs)
#endif
#ifndef NATIVE_HTTP_LOG_FILE
#define NATIVE_HTTP_LOG_FILE "nativehttp.log"
#endif
// Platform detection
#if defined(_WIN32) || defined(_WIN64)
#define NATIVE_HTTP_WINDOWS 1
#define SECURITY_WIN32 // Fix for SSPI
#ifndef WINVER
#define WINVER 0x0602
#endif
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0602
#endif
#include <windows.h>
#include <wincrypt.h>
#include <winhttp.h>
#include <sspi.h>
#ifndef WINHTTP_WEB_SOCKET_BINARY_BUFFER_TYPE
#define WINHTTP_WEB_SOCKET_BINARY_BUFFER_TYPE WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE
#endif
/* ping/pong are not part of WinHTTP buffer type enum — map them for compilation.
Choose BINARY_MESSAGE or UTF8_MESSAGE depending on whether you want ping/pong payloads
to be sent as binary or text. BINARY_MESSAGE is a safe default here. */
#ifndef WINHTTP_WEB_SOCKET_PING_BUFFER_TYPE
#define WINHTTP_WEB_SOCKET_PING_BUFFER_TYPE WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE
#endif
#ifndef WINHTTP_WEB_SOCKET_PONG_BUFFER_TYPE
#define WINHTTP_WEB_SOCKET_PONG_BUFFER_TYPE WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE
#endif
// ... (compatibility defines remain the same)
#ifndef WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE
#define WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE ((WINHTTP_WEB_SOCKET_BUFFER_TYPE)1)
#endif
// ... (other compatibility defines remain the same)
// FIX: Add missing HTTP2 flags for older Windows SDK
#ifndef WINHTTP_FLAG_HTTP2
#define WINHTTP_FLAG_HTTP2 0x02000000
#endif
#ifndef WINHTTP_FLAG_HTTP1
#define WINHTTP_FLAG_HTTP1 0x00000000
#endif
#pragma comment(lib, "winhttp.lib")
#pragma comment(lib, "secur32.lib")
#pragma comment(lib, "crypt32.lib")
#elif defined(__linux__) || defined(__unix__)
#define NATIVE_HTTP_LINUX 1
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <fcntl.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/sha.h>
#include <openssl/hmac.h>
#include <openssl/evp.h>
#endif
// HTTP/3 support (conditional) - FIXED: Only include if enabled
#if NATIVE_HTTP_HTTP3_SUPPORT
#ifdef _WIN32
#include <msquic.h>
#else
#include <quiche.h>
#endif
#endif
namespace nativeHTTP {
// Enhanced logging with levels
class Logger {
public:
enum Level { DEBUG_LEVEL, INFO_LEVEL, WARNING_LEVEL, ERROR_LEVEL };
private:
static std::ofstream log_file;
static bool file_initialized;
static Level log_level;
static void ensure_file_open() {
if (!file_initialized) {
log_file.open(NATIVE_HTTP_LOG_FILE, std::ios::app);
file_initialized = true;
if (log_file.is_open()) {
log_file << "\n=== nativeHTTP Enhanced Log Started ===" << std::endl;
}
}
}
static std::string get_current_time() {
auto now = std::chrono::system_clock::now();
auto time_t = std::chrono::system_clock::to_time_t(now);
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
now.time_since_epoch()) % 1000;
std::stringstream ss;
ss << std::put_time(std::localtime(&time_t), "%Y-%m-%d %H:%M:%S");
ss << "." << std::setfill('0') << std::setw(3) << ms.count();
return ss.str();
}
static std::string level_to_string(Level level) {
switch (level) {
case DEBUG_LEVEL: return "DEBUG";
case INFO_LEVEL: return "INFO";
case WARNING_LEVEL: return "WARN";
case ERROR_LEVEL: return "ERROR";
default: return "UNKNOWN";
}
}
public:
static void set_level(Level level) { log_level = level; }
static void log(Level level, const std::string& message) {
if (level < log_level) return;
std::string formatted = "[" + get_current_time() + "] [" + level_to_string(level) + "] " + message;
#if NATIVE_HTTP_DEBUG
if (level == ERROR_LEVEL) {
std::cerr << formatted << std::endl;
} else {
std::cout << formatted << std::endl;
}
#else
ensure_file_open();
if (log_file.is_open()) {
log_file << formatted << std::endl;
}
#endif
}
static void debug(const std::string& message) { log(DEBUG_LEVEL, message); }
static void info(const std::string& message) { log(INFO_LEVEL, message); }
static void warning(const std::string& message) { log(WARNING_LEVEL, message); }
static void error(const std::string& message) { log(ERROR_LEVEL, message); }
#ifdef _WIN32
static void log_last_error(const std::string& context, Level level = ERROR_LEVEL) {
DWORD error_code = GetLastError();
LPSTR error_message = nullptr;
DWORD size = FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR)&error_message, 0, NULL);
std::string msg = context + " (Error " + std::to_string(error_code) + "): " +
(error_message ? error_message : "Unknown error");
log(level, msg);
if (error_message) LocalFree(error_message);
}
#endif
};
// Initialize static members
std::ofstream Logger::log_file;
bool Logger::file_initialized = false;
Logger::Level Logger::log_level = Logger::INFO_LEVEL;
// Enhanced constants
namespace constants {
const std::string DEFAULT_USER_AGENT = "nativeHTTP/2.1.6";
const int DEFAULT_TIMEOUT_MS = 30000;
const int MAX_REDIRECTS = 10;
const size_t BUFFER_SIZE = 16384;
const size_t MAX_HEADER_SIZE = 8192;
// WebSocket constants
enum class WebSocketOpcode {
CONTINUATION = 0x0,
TEXT = 0x1,
BINARY = 0x2,
CLOSE = 0x8,
PING = 0x9,
PONG = 0xA
};
// HTTP versions
enum class HttpVersion {
HTTP1_0,
HTTP1_1,
HTTP2_0,
HTTP3_0
};
// SSL/TLS versions
enum class SslVersion {
SSLv2,
SSLv3,
TLSv1_0,
TLSv1_1,
TLSv1_2,
TLSv1_3,
AUTO
};
}
// Enhanced utility functions
namespace utils {
inline std::string to_lower(const std::string& str) {
std::string result = str;
std::transform(result.begin(), result.end(), result.begin(),
[](unsigned char c) { return std::tolower(c); });
return result;
}
inline std::string to_upper(const std::string& str) {
std::string result = str;
std::transform(result.begin(), result.end(), result.begin(),
[](unsigned char c) { return std::toupper(c); });
return result;
}
inline std::string trim(const std::string& str) {
size_t start = str.find_first_not_of(" \t\r\n");
if (start == std::string::npos) return "";
size_t end = str.find_last_not_of(" \t\r\n");
return str.substr(start, end - start + 1);
}
inline std::vector<std::string> split(const std::string& str, char delimiter) {
std::vector<std::string> tokens;
std::stringstream ss(str);
std::string token;
while (std::getline(ss, token, delimiter)) {
token = trim(token);
if (!token.empty()) tokens.push_back(token);
}
return tokens;
}
inline bool starts_with(const std::string& str, const std::string& prefix) {
return str.size() >= prefix.size() && str.compare(0, prefix.size(), prefix) == 0;
}
inline bool ends_with(const std::string& str, const std::string& suffix) {
return str.size() >= suffix.size() &&
str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
}
inline std::string url_encode(const std::string& value) {
std::ostringstream escaped;
escaped.fill('0');
escaped << std::hex;
for (char c : value) {
if (std::isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
escaped << c;
} else {
escaped << '%' << std::setw(2) << int(static_cast<unsigned char>(c));
}
}
return escaped.str();
}
inline std::string url_decode(const std::string& value) {
std::string result;
result.reserve(value.size());
for (size_t i = 0; i < value.size(); ++i) {
if (value[i] == '%' && i + 2 < value.size()) {
int hex_value;
std::istringstream hex_stream(value.substr(i + 1, 2));
if (hex_stream >> std::hex >> hex_value) {
result += static_cast<char>(hex_value);
i += 2;
} else {
result += value[i];
}
} else if (value[i] == '+') {
result += ' ';
} else {
result += value[i];
}
}
return result;
}
inline std::string join(const std::vector<std::string>& elements, const std::string& delimiter) {
std::ostringstream oss;
for (size_t i = 0; i < elements.size(); ++i) {
if (i != 0) oss << delimiter;
oss << elements[i];
}
return oss.str();
}
// NEW: Split headers by semicolon for multiple headers in one -H option
inline std::vector<std::string> split_headers(const std::string& header_line) {
std::vector<std::string> headers;
std::stringstream ss(header_line);
std::string header;
while (std::getline(ss, header, ';')) {
header = trim(header);
if (!header.empty()) {
headers.push_back(header);
}
}
return headers;
}
}
// Enhanced Unicode support
namespace unicode {
#ifdef _WIN32
inline std::string to_utf8(const std::wstring& wstr) {
if (wstr.empty()) return std::string();
int size_needed = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), (int)wstr.size(), NULL, 0, NULL, NULL);
if (size_needed <= 0) return std::string();
std::string out;
out.resize(size_needed);
int converted = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), (int)wstr.size(), &out[0], size_needed, NULL, NULL);
if (converted <= 0) return std::string();
return out;
}
inline std::wstring from_utf8(const std::string& str) {
if (str.empty()) return std::wstring();
int size_needed = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int)str.size(), NULL, 0);
if (size_needed <= 0) return std::wstring();
std::wstring out;
out.resize(size_needed);
int converted = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int)str.size(), &out[0], size_needed);
if (converted <= 0) return std::wstring();
return out;
}
#else
inline std::string to_utf8(const std::wstring& wstr) {
std::string result;
result.reserve(wstr.size());
for (wchar_t wc : wstr) {
if (wc <= 0x7F) result += static_cast<char>(wc);
}
return result;
}
inline std::wstring from_utf8(const std::string& str) {
std::wstring result;
result.reserve(str.size());
for (char c : str) result += static_cast<wchar_t>(c);
return result;
}
#endif
// Enhanced Base64 with URL-safe variant
inline std::string base64_encode(const std::string& data, bool url_safe = false) {
static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static const std::string base64_url_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
const std::string& chars = url_safe ? base64_url_chars : base64_chars;
std::string result;
int i = 0, j = 0;
uint8_t char_array_3[3], char_array_4[4];
size_t in_len = data.size();
const uint8_t* bytes_to_encode = (const uint8_t*)data.data();
while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (i = 0; i < 4; i++) result += chars[char_array_4[i]];
i = 0;
}
}
if (i) {
for (j = i; j < 3; j++) char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; j < i + 1; j++) result += chars[char_array_4[j]];
while (i++ < 3) result += url_safe ? "" : "=";
}
return result;
}
// HMAC-SHA256 for AWS and OAuth
inline std::string hmac_sha256(const std::string& key, const std::string& data) {
#ifdef _WIN32
HCRYPTPROV hProv = 0;
HCRYPTKEY hKey = 0;
HCRYPTHASH hHash = 0;
BYTE pbHash[32];
DWORD dwHashLen = 32;
std::string result;
if (CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) {
struct {
BLOBHEADER hdr;
DWORD keySize;
BYTE keyData[64];
} keyBlob;
keyBlob.hdr.bType = PLAINTEXTKEYBLOB;
keyBlob.hdr.bVersion = CUR_BLOB_VERSION;
keyBlob.hdr.reserved = 0;
keyBlob.hdr.aiKeyAlg = CALG_RC2;
keyBlob.keySize = (DWORD)key.size();
memcpy(keyBlob.keyData, key.c_str(), key.size());
if (CryptImportKey(hProv, (BYTE*)&keyBlob, sizeof(keyBlob), 0, 0, &hKey)) {
if (CryptCreateHash(hProv, CALG_HMAC, hKey, 0, &hHash)) {
HMAC_INFO hmacInfo;
hmacInfo.HashAlgid = CALG_SHA_256;
hmacInfo.pbInnerString = 0;
hmacInfo.cbInnerString = 0;
hmacInfo.pbOuterString = 0;
hmacInfo.cbOuterString = 0;
if (CryptSetHashParam(hHash, HP_HMAC_INFO, (BYTE*)&hmacInfo, 0)) {
if (CryptHashData(hHash, (BYTE*)data.c_str(), (DWORD)data.length(), 0)) {
if (CryptGetHashParam(hHash, HP_HASHVAL, pbHash, &dwHashLen, 0)) {
result.assign((char*)pbHash, dwHashLen);
}
}
}
CryptDestroyHash(hHash);
}
CryptDestroyKey(hKey);
}
CryptReleaseContext(hProv, 0);
}
return result;
#else
unsigned char hash[32];
HMAC_CTX* ctx = HMAC_CTX_new();
HMAC_Init_ex(ctx, key.c_str(), key.length(), EVP_sha256(), NULL);
HMAC_Update(ctx, (unsigned char*)data.c_str(), data.length());
unsigned int len;
HMAC_Final(ctx, hash, &len);
HMAC_CTX_free(ctx);
return std::string((char*)hash, len);
#endif
}
inline std::string generate_random_string(size_t length, const std::string& charset = "") {
std::string chars = charset.empty() ?
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" : charset;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, chars.size() - 1);
std::string result;
result.reserve(length);
for (size_t i = 0; i < length; ++i) result += chars[dis(gen)];
return result;
}
}
// Enhanced URL parsing with query parameter support
struct ParsedURL {
std::string protocol;
std::string host;
int port;
std::string path;
std::string query;
std::string fragment;
std::map<std::string, std::string> query_params;
bool valid;
ParsedURL() : port(0), valid(false) {}
static ParsedURL parse(const std::string& url) {
ParsedURL result;
size_t protocol_end = url.find("://");
if (protocol_end != std::string::npos) {
result.protocol = url.substr(0, protocol_end);
size_t host_start = protocol_end + 3;
size_t path_start = url.find('/', host_start);
size_t query_start = url.find('?', host_start);
size_t fragment_start = url.find('#', host_start);
// Extract host and port
size_t host_end = std::min({path_start, query_start, fragment_start});
if (host_end == std::string::npos) host_end = url.length();
std::string host_port = url.substr(host_start, host_end - host_start);
size_t colon_pos = host_port.find(':');
if (colon_pos != std::string::npos) {
result.host = host_port.substr(0, colon_pos);
try {
result.port = std::stoi(host_port.substr(colon_pos + 1));
} catch (...) {
result.port = (result.protocol == "https") ? 443 : 80;
}
} else {
result.host = host_port;
result.port = (result.protocol == "https") ? 443 : 80;
}
// Extract path
if (path_start != std::string::npos) {
size_t path_end = std::min(query_start, fragment_start);
if (path_end == std::string::npos) path_end = url.length();
result.path = url.substr(path_start, path_end - path_start);
} else {
result.path = "/";
}
// Extract query
if (query_start != std::string::npos) {
size_t query_end = fragment_start;
if (query_end == std::string::npos) query_end = url.length();
result.query = url.substr(query_start + 1, query_end - query_start - 1);
}
// Extract fragment
if (fragment_start != std::string::npos) {
result.fragment = url.substr(fragment_start + 1);
}
}
// Parse query parameters
if (!result.query.empty()) {
auto pairs = utils::split(result.query, '&');
for (const auto& pair : pairs) {
auto key_value = utils::split(pair, '=');
if (key_value.size() == 2) {
result.query_params[utils::url_decode(key_value[0])] =
utils::url_decode(key_value[1]);
} else if (key_value.size() == 1) {
result.query_params[utils::url_decode(key_value[0])] = "";
}
}
}
result.valid = true;
return result;
}
std::string build_query() const {
std::vector<std::string> pairs;
for (const auto& param : query_params) {
pairs.push_back(utils::url_encode(param.first) + "=" +
utils::url_encode(param.second));
}
return utils::join(pairs, "&");
}
std::string to_string() const {
std::string result = protocol + "://" + host;
if ((protocol == "http" && port != 80) ||
(protocol == "https" && port != 443) ||
(protocol != "http" && protocol != "https")) {
result += ":" + std::to_string(port);
}
result += path;
if (!query.empty()) result += "?" + query;
if (!fragment.empty()) result += "#" + fragment;
return result;
}
};
// Enhanced Proxy configuration with authentication
struct ProxyConfig {
enum class AuthMethod {
NONE,
BASIC,
DIGEST,
NTLM,
NEGOTIATE,
BEARER,
AWS4_HMAC_SHA256
};
std::string host;
int port;
std::string username;
std::string password;
std::string type;
AuthMethod auth_method;
std::string realm;
std::string nonce;
std::string aws_region;
std::string aws_service;
ProxyConfig() : port(8080), auth_method(AuthMethod::NONE) {}
bool enabled() const { return !host.empty(); }
std::string get_auth_header(const std::string& method, const std::string& url) const {
(void)method; (void)url; // Fix unused parameter warnings
if (auth_method == AuthMethod::BASIC) {
std::string credentials = username + ":" + password;
return "Proxy-Authorization: Basic " + unicode::base64_encode(credentials);
}
else if (auth_method == AuthMethod::BEARER) {
return "Proxy-Authorization: Bearer " + password;
}
return "";
}
};
// Enhanced Cookie management with SameSite support
class CookieJar {
public:
struct Cookie {
std::string name;
std::string value;
std::string domain;
std::string path;
std::chrono::system_clock::time_point expires;
bool secure = false;
bool http_only = false;
std::string same_site;
bool is_expired() const {
return expires < std::chrono::system_clock::now();
}
bool matches(const std::string& url_domain, const std::string& url_path, bool is_secure) const {
if (is_expired()) return false;
if (secure && !is_secure) return false;
if (same_site == "None" && !is_secure) return false;
if (url_domain.length() < domain.length()) return false;
if (url_domain.substr(url_domain.length() - domain.length()) != domain) return false;
return url_path.find(path) == 0;
}
std::string to_string() const {
return name + "=" + value;
}
};
void add_cookie(const Cookie& cookie) {
cookies.erase(std::remove_if(cookies.begin(), cookies.end(),
[&](const Cookie& c) {
return c.name == cookie.name && c.domain == cookie.domain && c.path == cookie.path;
}), cookies.end());
cookies.push_back(cookie);
}
std::vector<Cookie> get_cookies_for_url(const std::string& url, bool is_secure) const {
ParsedURL parsed = ParsedURL::parse(url);
if (!parsed.valid) return {};
std::vector<Cookie> result;
for (const auto& cookie : cookies) {
if (cookie.matches(parsed.host, parsed.path, is_secure)) {
result.push_back(cookie);
}
}
return result;
}
std::string get_cookie_header(const std::string& url, bool is_secure) const {
auto cookies_for_url = get_cookies_for_url(url, is_secure);
std::vector<std::string> cookie_strings;
for (const auto& cookie : cookies_for_url) {
cookie_strings.push_back(cookie.to_string());
}
return utils::join(cookie_strings, "; ");
}
void save_to_file(const std::string& filename) const {
std::ofstream file(filename);
if (file.is_open()) {
for (const auto& cookie : cookies) {
file << cookie.domain << "\t"
<< (cookie.secure ? "TRUE" : "FALSE") << "\t"
<< cookie.path << "\t"
<< (cookie.secure ? "TRUE" : "FALSE") << "\t"
<< std::chrono::duration_cast<std::chrono::seconds>(
cookie.expires.time_since_epoch()).count() << "\t"
<< cookie.name << "\t"
<< cookie.value << "\n";
}
}
}
void load_from_file(const std::string& filename) {
std::ifstream file(filename);
if (file.is_open()) {
cookies.clear();
std::string line;
while (std::getline(file, line)) {
auto fields = utils::split(line, '\t');
if (fields.size() >= 6) {
Cookie cookie;
cookie.domain = fields[0];
cookie.secure = (fields[1] == "TRUE");
cookie.path = fields[2];
try {
auto expires_sec = std::stoll(fields[4]);
cookie.expires = std::chrono::system_clock::time_point(
std::chrono::seconds(expires_sec));
} catch (...) {}
cookie.name = fields[5];
cookie.value = fields.size() > 6 ? fields[6] : "";
cookies.push_back(cookie);
}
}
}
}
private:
std::vector<Cookie> cookies;
};
// Enhanced Multipart form data with dynamic content type support
// Enhanced Multipart form data with dynamic content type support
class MultipartFormData {
public:
struct Part {
// FIXED: Simplified constructors to avoid ambiguity
// Text part constructor
Part(const std::string& n, const std::string& v)
: name(n), value(v), content_type("text/plain"), is_text(true) {}
// Binary data part constructor
Part(const std::string& n, const std::vector<uint8_t>& d,
const std::string& fn, const std::string& ct)
: name(n), data(d), filename(fn), content_type(ct), is_binary(true) {}
// File part constructor
Part(const std::string& n, const std::string& filepath,
const std::string& fn, const std::string& ct)
: name(n), file_path(filepath), filename(fn.empty() ?
filepath.substr(filepath.find_last_of("/\\") + 1) : fn),
content_type(ct.empty() ? detect_content_type(filename) : ct),
is_file(true) {}
private:
static std::string detect_content_type(const std::string& filename) {
if (utils::ends_with(filename, ".jpg") || utils::ends_with(filename, ".jpeg"))
return "image/jpeg";
else if (utils::ends_with(filename, ".png"))
return "image/png";
else if (utils::ends_with(filename, ".gif"))
return "image/gif";
else if (utils::ends_with(filename, ".pdf"))
return "application/pdf";
else if (utils::ends_with(filename, ".json"))
return "application/json";
else if (utils::ends_with(filename, ".xml"))
return "application/xml";
else if (utils::ends_with(filename, ".html") || utils::ends_with(filename, ".htm"))
return "text/html";
else if (utils::ends_with(filename, ".txt"))
return "text/plain";
else if (utils::ends_with(filename, ".csv"))
return "text/csv";
else
return "application/octet-stream";
}
public:
// Member variables in clear order
std::string name;
std::string value;
std::string filename;
std::string content_type;
std::vector<uint8_t> data;
std::string file_path;
bool is_text = false;
bool is_binary = false;
bool is_file = false;
};
MultipartFormData() : boundary("----NativeHTTPBoundary" + unicode::generate_random_string(16)) {}
// FIXED: Use direct constructor calls to avoid ambiguity
void add_text(const std::string& name, const std::string& value) {
parts.emplace_back(name, value);
}
void add_file(const std::string& name, const std::vector<uint8_t>& data,
const std::string& filename = "", const std::string& content_type = "application/octet-stream") {
parts.emplace_back(name, data, filename, content_type);
}
void add_file(const std::string& name, const std::string& filepath,
const std::string& filename = "", const std::string& content_type = "") {
parts.emplace_back(name, filepath, filename, content_type);
}
std::string get_content_type() const {
return "multipart/form-data; boundary=" + boundary;
}
std::vector<uint8_t> build_body() const {
std::vector<uint8_t> body;
const std::string crlf = "\r\n";
for (const auto& part : parts) {
std::string header = "--" + boundary + crlf;
header += "Content-Disposition: form-data; name=\"" + part.name + "\"";
if (!part.filename.empty()) {
header += "; filename=\"" + part.filename + "\"";
}
header += crlf;
if (!part.content_type.empty()) {
header += "Content-Type: " + part.content_type + crlf;
}
header += crlf;
body.insert(body.end(), header.begin(), header.end());
if (part.is_binary && !part.data.empty()) {
body.insert(body.end(), part.data.begin(), part.data.end());
} else if (part.is_file && !part.file_path.empty()) {
std::ifstream file(part.file_path, std::ios::binary);
if (file) {
body.insert(body.end(),
std::istreambuf_iterator<char>(file),
std::istreambuf_iterator<char>());
}
} else if (part.is_text) {
body.insert(body.end(), part.value.begin(), part.value.end());
}
body.insert(body.end(), crlf.begin(), crlf.end());
}
std::string footer = "--" + boundary + "--" + crlf;
body.insert(body.end(), footer.begin(), footer.end());
return body;
}
size_t get_content_length() const {
size_t length = 0;
for (const auto& part : parts) {
length += boundary.length() + 6;
length += 38 + part.name.length();
if (!part.filename.empty()) length += 12 + part.filename.length();
if (!part.content_type.empty()) length += 16 + part.content_type.length();
length += 4;
if (part.is_binary) {
length += part.data.size();
} else if (part.is_file) {
std::ifstream file(part.file_path, std::ios::binary | std::ios::ate);
if (file) length += file.tellg();
} else if (part.is_text) {
length += part.value.length();
}
length += 2;
}
length += boundary.length() + 6;
return length;
}
private:
std::string boundary;
std::vector<Part> parts;
};
// SSL/TLS Configuration
struct SSLConfig {
constants::SslVersion min_version = constants::SslVersion::TLSv1_2;
constants::SslVersion max_version = constants::SslVersion::TLSv1_3;
bool verify_peer = true;
bool verify_hostname = true;
std::string ca_cert_file;
std::string client_cert_file;
std::string client_key_file;
std::string cipher_list;
std::string curves;
void set_modern_tls() {
min_version = constants::SslVersion::TLSv1_2;
max_version = constants::SslVersion::TLSv1_3;
cipher_list = "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:"
"ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384";
}
void set_compatible_tls() {
min_version = constants::SslVersion::TLSv1_0;
max_version = constants::SslVersion::TLSv1_3;
cipher_list = "DEFAULT";
}
};
// Enhanced Client class with advanced features
class Client {
public:
struct Response {
int status_code = 0;
std::string status_text;
std::vector<std::string> request_headers;
std::vector<std::string> response_headers;
std::vector<uint8_t> body;
std::string url;
std::string error_message;
double elapsed_time = 0;
constants::HttpVersion http_version = constants::HttpVersion::HTTP1_1;
size_t uploaded_bytes = 0;
size_t downloaded_bytes = 0;
std::string effective_url;
std::string get_body_text() const {
return std::string(body.begin(), body.end());
}
std::string get_header(const std::string& name) const {
std::string lower_name = utils::to_lower(name);
for (const auto& header : response_headers) {
size_t colon = header.find(':');
if (colon != std::string::npos) {
std::string header_name = utils::trim(header.substr(0, colon));
if (utils::to_lower(header_name) == lower_name) {
return utils::trim(header.substr(colon + 1));
}
}
}
return "";
}
std::map<std::string, std::string> get_headers_map() const {
std::map<std::string, std::string> headers_map;
for (const auto& header : response_headers) {
size_t colon = header.find(':');
if (colon != std::string::npos) {
std::string name = utils::trim(header.substr(0, colon));
std::string value = utils::trim(header.substr(colon + 1));
headers_map[utils::to_lower(name)] = value;
}
}
return headers_map;
}
std::string get_headers_string() const {
std::stringstream ss;
ss << "HTTP/" << (http_version == constants::HttpVersion::HTTP1_0 ? "1.0" :
http_version == constants::HttpVersion::HTTP2_0 ? "2.0" :
http_version == constants::HttpVersion::HTTP3_0 ? "3.0" : "1.1")
<< " " << status_code << " " << status_text << "\r\n";
for (const auto& header : response_headers) {
ss << header << "\r\n";
}
ss << "\r\n";
return ss.str();
}
bool success() const { return status_code >= 200 && status_code < 300; }
bool redirect() const { return status_code >= 300 && status_code < 400; }
bool client_error() const { return status_code >= 400 && status_code < 500; }
bool server_error() const { return status_code >= 500 && status_code < 600; }
};