Repository navigation
Expand file tree
/
Copy pathdownloadFile.cpp
More file actions
1577 lines (1362 loc) · 53.6 KB
/
Copy pathdownloadFile.cpp
File metadata and controls
1577 lines (1362 loc) · 53.6 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
/*
FILE : downloadFile.cpp
PROJECT : xstore
PROGRAMMER : 951261
DESCRIPTION : Downloads a file. If the file is larger than 4GB, it splits it into multiple parts.
*/
/**
* ----------------------------------------------------------------------------
* XboxTLS Example Client
* ----------------------------------------------------------------------------
* This is a minimal demonstration of the XboxTLS library running on a
* modded Xbox 360. It showcases how to perform a secure TLS 1.2 connection
* to a remote server using the BearSSL cryptographic library (embedded into
* the XboxTLS implementation).
*
* ----------------------------------------------------------------------------
* Features:
* - Initializes the Xbox 360 network stack (XNet, Winsock).
* - Resolves a domain name using Xbox 360's DNS (XNetDnsLookup).
* - Supports TLS 1.2 with both RSA and Elliptic Curve (EC) trust anchors.
* - Performs a secure TLS handshake and sends an HTTPS GET(POST also supported) request.
* - Prints the received HTTP response using XboxTLS_Read and debug output.
*
* ----------------------------------------------------------------------------
* Library Dependencies:
* - XboxTLS (this project's core TLS wrapper).
* - BearSSL (used internally for TLS 1.2, x.509, ECDSA/RSA, HMAC, etc.).
*
* ----------------------------------------------------------------------------
* Trust Anchor Notes:
* This client supports two types of root certificate trust anchors:
* 1. EC (Elliptic Curve) trust anchors - commonly used with modern CAs.
* 2. RSA trust anchors - still widely used for backwards compatibility.
*
* The example provides pre-filled trust anchor values from:
* - Google Trust Services GTS Root R4 (EC P-384)
* - ISRG Root X1 (RSA 2048 / 65537)
*
* ----------------------------------------------------------------------------
* Usage Notes:
* - This client is designed for development/testing on modded Xbox 360 units.
* - Built using the Xbox 360 XDK with support for WinSock and XNet.
* - This implementation assumes you are targeting TLS 1.2 endpoints.
* It does not support TLS 1.3.
*
* ----------------------------------------------------------------------------
* Author: Jakob Rangel
* License: MIT / Open Source
*/
#include <iostream>
#include "XboxTLS.h"
#include "downloadFile.h"
#include "dns.h"
#include "parsing.h"
#include "OutputConsole.h"
#include "githubCert.h"
#include "settings.h"
#include <xtl.h>
#include "goDaddyRootCA.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define ERROR(s) (log_printf("\nERROR: %s\n", s))
#define DEBUG_PRINT(s) (log_printf(s));
unsigned long long outputBufferPointer = 0;
static const unsigned char EC_DN[] = { // GTS ROOT G4 Cert
0x30, 0x47, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
0x02, 0x55, 0x53, 0x31, 0x22, 0x30, 0x20, 0x06, 0x03, 0x55, 0x04, 0x0A,
0x13, 0x19, 0x47, 0x6F, 0x6F, 0x67, 0x6C, 0x65, 0x20, 0x54, 0x72, 0x75,
0x73, 0x74, 0x20, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x20,
0x4C, 0x4C, 0x43, 0x31, 0x14, 0x30, 0x12, 0x06, 0x03, 0x55, 0x04, 0x03,
0x13, 0x0B, 0x47, 0x54, 0x53, 0x20, 0x52, 0x6F, 0x6F, 0x74, 0x20, 0x52,
0x34};
static const unsigned char EC_Q[] = { // GTS ROOT G4 Cert
0x04, 0xF3, 0x74, 0x73, 0xA7, 0x68, 0x8B, 0x60, 0xAE, 0x43, 0xB8, 0x35,
0xC5, 0x81, 0x30, 0x7B, 0x4B, 0x49, 0x9D, 0xFB, 0xC1, 0x61, 0xCE, 0xE6,
0xDE, 0x46, 0xBD, 0x6B, 0xD5, 0x61, 0x18, 0x35, 0xAE, 0x40, 0xDD, 0x73,
0xF7, 0x89, 0x91, 0x30, 0x5A, 0xEB, 0x3C, 0xEE, 0x85, 0x7C, 0xA2, 0x40,
0x76, 0x3B, 0xA9, 0xC6, 0xB8, 0x47, 0xD8, 0x2A, 0xE7, 0x92, 0x91, 0x6A,
0x73, 0xE9, 0xB1, 0x72, 0x39, 0x9F, 0x29, 0x9F, 0xA2, 0x98, 0xD3, 0x5F,
0x5E, 0x58, 0x86, 0x65, 0x0F, 0xA1, 0x84, 0x65, 0x06, 0xD1, 0xDC, 0x8B,
0xC9, 0xC7, 0x73, 0xC8, 0x8C, 0x6A, 0x2F, 0xE5, 0xC4, 0xAB, 0xD1, 0x1D,
0x8A};
static const unsigned char TA0_DN[] = {
0x30, 0x32, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
0x02, 0x55, 0x53, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03, 0x55, 0x04, 0x0A,
0x13, 0x0D, 0x4C, 0x65, 0x74, 0x27, 0x73, 0x20, 0x45, 0x6E, 0x63, 0x72,
0x79, 0x70, 0x74, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x03,
0x13, 0x02, 0x45, 0x37};
static const unsigned char TA0_EC_Q[] = {
0x04, 0x41, 0xE8, 0x04, 0x93, 0x08, 0x58, 0x7F, 0xBE, 0x37, 0x30, 0x0C,
0xC0, 0xA0, 0x41, 0xEA, 0xFE, 0x56, 0xDA, 0x84, 0x93, 0x3E, 0xC9, 0x00,
0xDB, 0xAB, 0x67, 0x12, 0xCF, 0xF9, 0x4F, 0x53, 0x09, 0xE8, 0xA8, 0x2F,
0xAB, 0x29, 0xE5, 0x9F, 0x15, 0x46, 0xF4, 0x5B, 0x62, 0x4E, 0x0F, 0xD4,
0x83, 0x41, 0x99, 0xB7, 0x9F, 0x40, 0x72, 0x45, 0x1C, 0x2C, 0x5C, 0x4A,
0x32, 0xA6, 0xC2, 0xDB, 0xC6, 0x05, 0x6A, 0x65, 0xFF, 0xDA, 0xDA, 0xF0,
0x75, 0xB4, 0x40, 0x3B, 0x14, 0x68, 0x95, 0xB6, 0xA8, 0xE2, 0x6A, 0x71,
0xE2, 0x74, 0x65, 0x51, 0x53, 0xDE, 0x16, 0xD4, 0x1E, 0x27, 0xC1, 0x33,
0xFD};
const unsigned char RSA_DN[] = {
0x30, 0x31, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03,
0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31,
0x13, 0x30, 0x11, 0x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0x75, 0x4d,
0x38, 0xbe, 0x7a, 0x11, 0x3c, 0xdf, 0x71, 0x33, 0x4f, 0x0e, 0x9e, 0x6d, 0xe5, 0xa6, 0x76, 0x7e,
0x3e, 0xf6, 0xf4, 0x91, 0x8a, 0xbe, 0x3d, 0xf4, 0x11, 0xc4, 0x91, 0x0a, 0xe3, 0x5c, 0x2f, 0xbe,
0x2e, 0x27, 0x3e, 0x61, 0x61, 0xb4, 0x12, 0xfa, 0xb9, 0xd4, 0x26, 0x44, 0xbd, 0x1a, 0xd3, 0x12,
0x68, 0x96, 0xa2, 0x92, 0x7a, 0x8b, 0x86, 0x4d, 0x12, 0x29, 0xa1, 0x77, 0x53, 0x4a, 0x9a, 0x35,
0xe2, 0xa1, 0x56, 0x45, 0xc5, 0xf3, 0xd7, 0x70, 0xd7, 0x91, 0x9f, 0x8c, 0x1b, 0xdf, 0x1c, 0x0b,
0xb1, 0x3d, 0xa7, 0xf2, 0xbb, 0xd9, 0x6b, 0x75, 0x8d, 0x2d, 0x7b, 0xc7, 0x19, 0x5b, 0x9f, 0x32,
0xbc, 0x3a, 0x1a, 0xd5, 0xa3, 0x93, 0xb3, 0xf9, 0x75, 0x26, 0x2e, 0x67, 0xf2, 0x77, 0x93, 0x41};
const unsigned char RSA_E[] = {0x01, 0x00, 0x01}; // 65537
static const unsigned char TA0_RSA_DN[] = {
0x30, 0x33, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
0x02, 0x55, 0x53, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03, 0x55, 0x04, 0x0A,
0x13, 0x0D, 0x4C, 0x65, 0x74, 0x27, 0x73, 0x20, 0x45, 0x6E, 0x63, 0x72,
0x79, 0x70, 0x74, 0x31, 0x0C, 0x30, 0x0A, 0x06, 0x03, 0x55, 0x04, 0x03,
0x13, 0x03, 0x52, 0x31, 0x32};
static const unsigned char TA0_RSA_N[] = {
0xDA, 0x98, 0x28, 0x74, 0xAD, 0x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0x23, 0x9D, 0x5E, 0xA3,
0xFE, 0xE8, 0xDB, 0x00, 0xA1, 0xD2, 0xF4, 0xE3, 0x19, 0x4D, 0xF2, 0xEE,
0x7A, 0xF6, 0x27, 0x9E, 0xE5, 0xCD, 0x9C, 0x2D, 0xA2, 0xF2, 0x7F, 0x9C,
0x17, 0xAD, 0xEF, 0x13, 0x37, 0x39, 0xD1, 0xB4, 0xC8, 0x2C, 0x41, 0xD6,
0x86, 0xC0, 0xE9, 0xEC, 0x21, 0xF8, 0x59, 0x1B, 0x7F, 0xB9, 0x3A, 0x7C,
0x9F, 0x5C, 0x01, 0x9D, 0x62, 0x04, 0xC2, 0x28, 0xBD, 0x0A, 0xAD, 0x3C,
0xCA, 0x10, 0xEC, 0x1B};
static const unsigned char TA0_RSA_E[] = {
0x01, 0x00, 0x01};
// Yeah yeah, I know I already have this in 7z decompression
bool FormatBytes(
unsigned long long bytes,
char *output,
size_t outputSize)
{
if (!output || outputSize == 0)
return false;
static const char *units[] =
{
"B", "KB", "MB", "GB", "TB"
};
double value = (double)bytes;
unsigned int unitIndex = 0;
while (value >= 1024.0 && unitIndex < 4)
{
value /= 1024.0;
++unitIndex;
}
int result;
if (unitIndex == 0)
{
result = _snprintf(
output,
outputSize,
"%I64u B",
bytes);
}
else if (value >= 100.0)
{
result = _snprintf(
output,
outputSize,
"%.0f %s",
value,
units[unitIndex]);
}
else if (value >= 10.0)
{
result = _snprintf(
output,
outputSize,
"%.1f %s",
value,
units[unitIndex]);
}
else
{
result = _snprintf(
output,
outputSize,
"%.2f %s",
value,
units[unitIndex]);
}
// Older Microsoft implementations of _snprintf may not terminate
// the output when truncation occurs.
output[outputSize - 1] = '\0';
return result >= 0 && (size_t)result < outputSize;
}
static bool WriteBody(FILE *file, const char *data, int len, unsigned long long *totalWritten, char *outputBuffer)
{
if (len <= 0)
return true;
if (outputBuffer == NULL)
{
if (fwrite(data, 1, len, file) != (size_t)len)
return false;
}
else
{
memcpy(outputBuffer + outputBufferPointer, data, len);
outputBufferPointer += len;
}
*totalWritten += len;
return true;
}
static bool WriteChunkedBody(ChunkedDecodeState *state, FILE *file, const char *data, int len, unsigned long long *totalWritten, char *outputBuffer)
{
int pos = 0;
while (pos < len && state->state != 3)
{
if (state->state == 0)
{
char c = data[pos++];
if (c == '\r')
continue;
if (c == '\n')
{
unsigned long chunkSize;
if (!ParseChunkSize(state->sizeLine, state->sizeLineLen, &chunkSize))
return false;
state->sizeLineLen = 0;
state->remaining = chunkSize;
if (chunkSize == 0)
state->state = 3;
else
state->state = 1;
continue;
}
if (state->sizeLineLen >= (int)sizeof(state->sizeLine))
return false;
state->sizeLine[state->sizeLineLen++] = c;
}
else if (state->state == 1)
{
int bytesToWrite = (int)state->remaining;
int available = len - pos;
if (bytesToWrite > available)
bytesToWrite = available;
if (!WriteBody(file, data + pos, bytesToWrite, totalWritten, outputBuffer))
return false;
pos += bytesToWrite;
state->remaining -= (unsigned long)bytesToWrite;
if (state->remaining == 0)
state->state = 2;
}
else if (state->state == 2)
{
char c = data[pos++];
if (c == '\n')
state->state = 0;
else if (c != '\r')
return false;
}
}
return true;
}
unsigned long long parseContentLength(char *headerBuffer, size_t bufferLength)
{
const char prevChar = headerBuffer[bufferLength - 1];
headerBuffer[bufferLength - 1] = '\0';
const char *contentLengthString = strstr(headerBuffer, "Content-Length: ");
headerBuffer[bufferLength - 1] = prevChar;
if (contentLengthString == NULL)
{ // no content length found in header
return 0;
}
return _atoi64(contentLengthString + strlen("Content-Length: ")); // atoi should automatically stop when it sees the '\n' char
}
unsigned long long parseStatus(char *headerBuffer, size_t bufferLength)
{
const char prevChar = headerBuffer[bufferLength - 1];
headerBuffer[bufferLength - 1] = '\0';
const char *statusString = strstr(headerBuffer, " ");
headerBuffer[bufferLength - 1] = prevChar;
if (statusString == NULL)
{ // no content length found in header
return 0;
}
return _atoi64(statusString + strlen(" ")); // atoi should automatically stop when it sees the '\n' char
}
char *parseLocation(char *headerBuffer, size_t bufferLength, char *redirectURL, size_t urlSize)
{
if (headerBuffer == NULL || redirectURL == NULL || urlSize == 0 || bufferLength == 0)
{
return NULL;
}
redirectURL[0] = '\0';
const char prevChar = headerBuffer[bufferLength - 1];
headerBuffer[bufferLength - 1] = '\0';
const char *statusString = strstr(headerBuffer, "Location: ");
headerBuffer[bufferLength - 1] = prevChar;
if (statusString == NULL)
{ // no content length found in header
return NULL;
}
const char *src = statusString + strlen("Location: ");
size_t i = 0;
while (src[i] != '\0' && src[i] != '\n' && src[i] != '\r')
{
if (i + 1 >= urlSize)
{
redirectURL[0] = '\0';
return NULL;
}
redirectURL[i] = src[i];
i++;
}
redirectURL[i] = '\0';
return redirectURL;
}
static bool CopyTextToBuffer(const char *source, char *destination, unsigned long long *destinationSize)
{
if (source == NULL || destination == NULL || destinationSize == NULL || *destinationSize == 0)
return false;
size_t sourceLength = strlen(source);
size_t capacity = (size_t)*destinationSize;
if (sourceLength >= capacity)
{
destination[0] = '\0';
return false;
}
memcpy(destination, source, sourceLength + 1);
*destinationSize = (unsigned long long)sourceLength;
return true;
}
unsigned long long getClockLong()
{
return (unsigned long long)clock();
}
// Function to check if a string ends with another string
bool endsWith(const std::string &fullString,
const std::string &ending)
{
// Check if the ending string is longer than the full
// string
if (ending.size() > fullString.size())
return false;
// Compare the ending of the full string with the target
// ending
return fullString.compare(fullString.size() - ending.size(),
ending.size(), ending) == 0;
}
int DumpResponse(XboxTLSContext *ctx,
const std::string filename,
char *outputBuffer,
unsigned long long *outputBufferSize,
char *redirectBuffer,
unsigned long long *redirectBufferSize,
void printFunction(const char *_format, ...))
{
unsigned long long outputBufferSizeConst = 0;
int responseCode = 0; // HTTP status code
if (outputBuffer != NULL)
{
outputBufferSizeConst = *outputBufferSize;
}
outputBufferPointer = 0; // Whether writing to a buffer or not, it doesn't hurt to clear this
const unsigned long long BUFFER_SIZE = 4 * 1024 * 1024;
const unsigned long long MAX_FILE_SIZE = 0xF0000000;
char *buffer = (char *)malloc(BUFFER_SIZE);
if (buffer == NULL)
{
ERROR("MALLOC failed");
return EXIT_FAILURE;
}
char *fileBuffer = (char *)malloc(BUFFER_SIZE);
if (fileBuffer == NULL)
{
ERROR("MALLOC failed");
free(buffer);
return EXIT_FAILURE;
}
char headerBuffer[16 * 1024];
unsigned long long headerLen = 0;
bool headersDone = false;
bool chunked = false;
ChunkedDecodeState chunkedState;
int r = 0;
bool writeToBuffer = false; // should we write to a buffer instead of a file???
bool splitFile = false;
if (outputBuffer != NULL)
{
writeToBuffer = true;
}
FILE *file = NULL;
if (!writeToBuffer)
{
if (endsWith(filename, std::string(".001")))
{
splitFile = true;
std::cout << "Split file detected\n";
}
file = fopen(filename.c_str(), "wb");
if (file == NULL)
{
printFunction("Failed to open file %s\n", filename.c_str());
free(buffer);
free(fileBuffer);
return EXIT_FAILURE;
}
setvbuf(file, fileBuffer, _IOFBF, BUFFER_SIZE);
}
InitChunkedDecodeState(&chunkedState);
unsigned long long startTime = (getClockLong() * (unsigned long long)1000) / (CLOCKS_PER_SEC);
unsigned long long endTime = (getClockLong() * (unsigned long long)1000) / (CLOCKS_PER_SEC);
unsigned long long totalWritten = 0;
unsigned long long lastBytesWritten = 0;
unsigned long long KBdownloaded = 0;
unsigned long long totalContentLength = 0;
unsigned long long beginTime = startTime;
unsigned long long bytesWrittenToCurrentFile = 0;
char *splitFilename = NULL;
if (!writeToBuffer)
{
splitFilename = strdup(filename.c_str());
}
while ((!headersDone || writeToBuffer) && (r = XboxTLS_Read(ctx, buffer, BUFFER_SIZE)) > 0)
{
const char *body = buffer;
int bodyLen = r;
if (writeToBuffer && totalWritten + r >= outputBufferSizeConst)
{
printFunction("Output Buffer Exhausted\n");
goto failure;
}
if (!headersDone)
{
int copyLen = r;
int headerEnd;
if (copyLen > (int)sizeof(headerBuffer) - headerLen)
copyLen = (int)sizeof(headerBuffer) - headerLen;
memcpy(headerBuffer + headerLen, buffer, copyLen);
headerLen += copyLen;
headerEnd = FindHeaderEnd(headerBuffer, headerLen);
if (headerEnd < 0)
{
if (headerLen >= (int)sizeof(headerBuffer))
{
printFunction("HTTP headers too large\n");
goto failure;
}
continue;
}
const char tempChar = buffer[r - 1];
buffer[r - 1] = '\0';
// std::cout << buffer << "\n\n";
buffer[r - 1] = tempChar;
headersDone = true;
chunked = HeaderContainsToken(headerBuffer, headerEnd, "Transfer-Encoding", "chunked");
body = headerBuffer + headerEnd;
bodyLen = headerLen - headerEnd;
totalContentLength = parseContentLength(headerBuffer, headerEnd);
int status = parseStatus(headerBuffer, headerEnd);
responseCode = status; // value to return
if (status != 200)
{
printFunction("Status: %d\n", status);
switch (status)
{
case 429:
printFunction("Error: Too many requests \n");
break;
case 404:
printFunction("Error: Page not found\n");
break;
case 302:
{
printFunction("Redirect Found, following\n");
char newURL[1024 * 5];
if (parseLocation(headerBuffer, headerEnd, newURL, sizeof(newURL)) == NULL)
{
printFunction("ERROR: Location header missing or too long\n");
goto failure;
}
if (redirectBuffer != NULL && redirectBufferSize != NULL)
{
if (!CopyTextToBuffer(newURL, redirectBuffer, redirectBufferSize))
{
printFunction("ERROR: Redirect URL buffer too small\n");
goto failure;
}
}
else if (writeToBuffer && outputBuffer != NULL && outputBufferSize != NULL)
{
if (!CopyTextToBuffer(newURL, outputBuffer, outputBufferSize))
{
printFunction("ERROR: Redirect URL buffer too small\n");
goto failure;
}
}
else if (filename.length() > 0 && file != NULL)
{
fprintf(file, "%s\n", newURL);
}
else
{
goto failure;
}
goto redirectSuccess;
break;
}
default:
break;
}
goto failure;
}
}
if (chunked)
{
if (!WriteChunkedBody(&chunkedState, file, body, bodyLen, &totalWritten, outputBuffer))
{
printFunction("Failed to decode chunked HTTP body\n");
goto failure;
}
}
else if (!WriteBody(file, body, bodyLen, &totalWritten, outputBuffer))
{
printFunction("Failed to write to file\n");
goto failure;
}
endTime = (getClockLong() * (unsigned long long)1000) / (CLOCKS_PER_SEC);
if (endTime - startTime >= 1000)
{
int downloadSpeed = (int)((totalWritten * 1000) / (endTime - startTime));
printFunction("Speed: %d Bytes/sec \n", downloadSpeed);
}
}
// Check for chunked download (unlikely)
if (chunked && splitFile)
{
printFunction("\nERROR: chunked split file not supported yet\n");
if (file != NULL)
{
fclose(file);
}
free(buffer);
free(fileBuffer);
free(splitFilename);
return EXIT_FAILURE;
}
while (chunked && (r = XboxTLS_Read(ctx, buffer, BUFFER_SIZE)) > 0) // Chunked download
{
const char *body = buffer;
int bodyLen = r;
if (chunked)
{
if (!WriteChunkedBody(&chunkedState, file, body, bodyLen, &totalWritten, outputBuffer))
{
printFunction("Failed to decode chunked HTTP body _2\n");
break;
}
}
endTime = (getClockLong() * (unsigned long long)1000) / (CLOCKS_PER_SEC);
if (endTime - startTime >= 3000)
{
int downloadSpeed = (int)((totalWritten * 1000) / (endTime - startTime));
printFunction("Speed: %d Bytes/sec \n", downloadSpeed);
}
}
bytesWrittenToCurrentFile = totalWritten;
bool paused = false;
// Check for paused download
XINPUT_STATE state;
ZeroMemory(&state, sizeof(state));
if (!chunked) // When dowloading from Vimms lair, we request that the files is NOT chunked, so this loop 99% of the time should be what is used to download the majority of the file (except the header of course!!!)
{
dprintf("If you wish to pause your download, press the Start button\n");
while ((r = XboxTLS_Read(ctx, buffer, BUFFER_SIZE)) > 0)
{
if (r + bytesWrittenToCurrentFile > MAX_FILE_SIZE && splitFile) // As both XFat and FAT32 only support 4GB files, all downloaded files must be split (file.001, file.002, etc..). Up to 9 parts (.009) is supported
{
printFunction("File overflowed, creating next split file part. ");
size_t bytesThisFile = (size_t)(MAX_FILE_SIZE - bytesWrittenToCurrentFile);
size_t bytesNextFile = (size_t)r - bytesThisFile;
if (bytesThisFile > 0 && fwrite(buffer, 1, bytesThisFile, file) != bytesThisFile)
{
printFunction("Failed to write to file\n");
goto failure;
}
totalWritten += bytesThisFile;
bytesWrittenToCurrentFile += bytesThisFile;
fclose(file);
if (!IncrementSplitFilename(splitFilename))
{
printFunction("\nERROR: failed to increment split filename %s\n\n", splitFilename);
break;
}
file = fopen(splitFilename, "wb");
if (file == NULL)
{
printFunction("\nERROR: failed to open %s\n\n", splitFilename);
ERROR("Faile to open new split file part");
break;
}
setvbuf(file, fileBuffer, _IOFBF, BUFFER_SIZE);
if (bytesNextFile > 0 && fwrite(buffer + bytesThisFile, 1, bytesNextFile, file) != bytesNextFile)
{
printFunction("Failed to write to file\n");
break;
}
totalWritten += bytesNextFile;
r = (int)bytesNextFile;
bytesWrittenToCurrentFile = 0;
bytesWrittenToCurrentFile += bytesNextFile;
printFunction("Created new split file part");
continue;
}
if (fwrite(buffer, sizeof(buffer[0]), r, file) < r)
{
printFunction("Failed to write to file\n");
goto failure;
}
if (XInputGetState(0, &state) == ERROR_SUCCESS) {
if(state.Gamepad.wButtons & XINPUT_GAMEPAD_START) {
paused = true;
dprintf("\nDownload paused. Press Start to resume, or B to cancel the download\nIf you pause for too long, the download may fail to resume\n");
while (state.Gamepad.wButtons & XINPUT_GAMEPAD_START) {
Sleep(50);
if (XInputGetState(0, &state) != ERROR_SUCCESS) {
dprintf("Controller read error\n");
goto failure;
}
}
}
while(paused) {
ZeroMemory(&state, sizeof(state));
// Wait to be unpaused
if (XInputGetState(0, &state) == ERROR_SUCCESS) {
if(state.Gamepad.wButtons & XINPUT_GAMEPAD_START) {
paused = false;
dprintf("Resuming download\n");
while (state.Gamepad.wButtons & XINPUT_GAMEPAD_START) {
Sleep(50);
if (XInputGetState(0, &state) != ERROR_SUCCESS) {
dprintf("Controller read error\n");
goto failure;
}
}
} else if (state.Gamepad.wButtons & XINPUT_GAMEPAD_B) {
dprintf("Download Canceled\n");
responseCode = -67;
goto failure;
}
}
Sleep(100);
}
}
totalWritten += r;
bytesWrittenToCurrentFile += r;
endTime = (getClockLong() * (unsigned long long)1000) / (CLOCKS_PER_SEC);
if (endTime - startTime >= 3000)
{
unsigned long long tempTotalWritten = totalWritten;
if (tempTotalWritten / (endTime - startTime) == 0 || tempTotalWritten / (endTime - beginTime) == 0)
{
std::cout << "Divide by 0 error found\n";
// tempTotalWritten++;
char humanReadableDownloadedBytes[64] = "";
char humanReadableTotalBytes[64] = "";
FormatBytes(tempTotalWritten, humanReadableDownloadedBytes, sizeof(humanReadableDownloadedBytes));
FormatBytes(totalContentLength, humanReadableTotalBytes, sizeof(humanReadableTotalBytes));
printFunction("Downloaded %s out of %s, time: %llu\n", humanReadableDownloadedBytes, humanReadableTotalBytes, (endTime - beginTime) / (unsigned long long)1000);
endTime = (getClockLong() * (unsigned long long)1000) / (CLOCKS_PER_SEC);
startTime = endTime;
lastBytesWritten = tempTotalWritten;
continue;
}
else
{
char humanReadableDownloadedBytes[1024] = "";
char humanReadableTotalBytes[1024] = "";
char humanReadableSpeed[1024] = "";
char humanReadableAverageSpeed[1024] = "";
unsigned long long elapsedTime = (endTime - beginTime) / 1000;
unsigned long long downloadSpeed = ( (tempTotalWritten - lastBytesWritten) * 1000 ) / (endTime - startTime);
unsigned long long averageDownloadSpeed = (tempTotalWritten * 1000) / (endTime - beginTime);
unsigned long long bytesRemaining = totalContentLength - tempTotalWritten;
unsigned long long timeRemaining = bytesRemaining / averageDownloadSpeed;
FormatBytes(tempTotalWritten, humanReadableDownloadedBytes, sizeof(humanReadableDownloadedBytes));
FormatBytes(totalContentLength, humanReadableTotalBytes, sizeof(humanReadableDownloadedBytes));
FormatBytes(downloadSpeed, humanReadableSpeed, sizeof(humanReadableDownloadedBytes));
FormatBytes(averageDownloadSpeed, humanReadableAverageSpeed, sizeof(humanReadableDownloadedBytes));
endTime = (getClockLong() * (unsigned long long)1000) / (CLOCKS_PER_SEC);
startTime = endTime;
lastBytesWritten = tempTotalWritten;
printFunction("Downloaded %s out of %s, Speed: %s/s, Average: %s/s, Time %llu s, Time Remaining %llu:%llu:%llu s\n",
humanReadableDownloadedBytes, humanReadableTotalBytes, humanReadableSpeed, humanReadableAverageSpeed, (endTime - beginTime) / (unsigned long long)1000, timeRemaining / (unsigned long long)3600, (timeRemaining / (unsigned long long)60) % (unsigned long long)60, timeRemaining % (unsigned long long)60);
}
}
}
}
if (outputBufferSize != NULL)
{
*outputBufferSize = totalWritten;
}
if (writeToBuffer)
{
outputBuffer[totalWritten] = '\0';
}
if (totalWritten != totalContentLength && totalContentLength != 0)
{
ERROR("Download has likely failed");
goto failure;
}
redirectSuccess:
if (file != NULL)
fclose(file);
if (splitFilename != NULL)
free(splitFilename);
if (buffer != NULL)
free(buffer);
if (fileBuffer != NULL)
free(fileBuffer);
std::cout << "Download Complete\n";
return responseCode;
failure:
if (responseCode == 200)
{
responseCode = -1;
}
if (file != NULL)
fclose(file);
printFunction("Download Failed\n");
if (splitFilename != NULL)
free(splitFilename);
if (buffer != NULL)
free(buffer);
if (fileBuffer != NULL)
free(fileBuffer);
return responseCode;
}
int addTrustAnchors(XboxTLSContext *ctx)
{
// Set the hash algorithm to use for certificate validation (used by both EC and RSA trust anchors).
// Note: SHA-384 is commonly used with modern certificates (e.g., GTS Root R4, ISRG Root X1),
// but this can be changed to SHA-256, SHA-512, etc., depending on the CA's signature.
ctx->hashAlgo = XboxTLS_Hash_SHA384;
// Step 3.1: Add EC trust anchor (if site uses this key type)
if (!XboxTLS_AddTrustAnchor_EC(ctx, TA0_DN, sizeof(TA0_DN), TA0_EC_Q, sizeof(TA0_EC_Q), XboxTLS_Curve_secp384r1))
{
return EXIT_FAILURE;
}
if (!XboxTLS_AddTrustAnchor_EC(ctx, EC_DN, sizeof(EC_DN), EC_Q, sizeof(EC_Q), XboxTLS_Curve_secp384r1))
{
return EXIT_FAILURE;
}
if (!XboxTLS_AddTrustAnchor_EC(ctx, TA0_DN_GITHUB, sizeof(TA0_DN_GITHUB), TA0_EC_Q_GITHUB, sizeof(TA0_EC_Q_GITHUB), XboxTLS_Curve_secp256r1))
{
return EXIT_FAILURE;
}
if (!XboxTLS_AddTrustAnchor_RSA(ctx, RSA_DN, sizeof(RSA_DN), RSA_N, sizeof(RSA_N), RSA_E, sizeof(RSA_E)))
{
return EXIT_FAILURE;
}
if (!XboxTLS_AddTrustAnchor_RSA(ctx, TA0_RSA_DN, sizeof(TA0_RSA_DN), TA0_RSA_N, sizeof(TA0_RSA_N), TA0_RSA_E, sizeof(TA0_RSA_E)))
{
return EXIT_FAILURE;
}
if (!XboxTLS_AddTrustAnchor_RSA(ctx, IA_TA0_RSA_DN, sizeof(IA_TA0_RSA_DN), IA_TA0_RSA_N, sizeof(IA_TA0_RSA_N), IA_TA0_RSA_E, sizeof(IA_TA0_RSA_E)))
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
static std::string PostHeaderName(std::string name)
{
for (size_t i = 0; i < name.size(); ++i)
name[i] = LowerAscii(name[i]);
return name;
}
static bool ValidPostHeaderName(const std::string& name)
{
return !name.empty() && name.find_first_not_of(
"!#$%&'*+-.^_`|~0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") == std::string::npos;
}
static bool ValidPostHeaderValue(const std::string& value)
{
for (size_t i = 0; i < value.size(); ++i)
{
unsigned char c = (unsigned char)value[i];
if ((c < 32 && c != '\t') || c == 127)
return false;
}
return true;
}
static bool ParsePostSize(const std::string& text, unsigned int base, size_t& value)
{
value = 0;
const size_t limit = std::string().max_size();
if (text.empty())
return false;
for (size_t i = 0; i < text.size(); ++i)
{
int digit = HexValue(text[i]);
if (digit < 0 || (unsigned int)digit >= base || value > (limit - digit) / base)
return false;
value = value * base + digit;
}
return true;
}
struct HttpPostReader
{
XboxTLSContext* ctx;