Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
1679 lines (1576 loc) · 78.7 KB
/
Copy pathmain.cpp
File metadata and controls
1679 lines (1576 loc) · 78.7 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
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <commctrl.h>
#include <shellapi.h>
#include <shobjidl.h>
#include "resource.h"
#include "build_config.h"
#include <curl/curl.h>
#include <algorithm>
#include <array>
#include <atomic>
#include <cctype>
#include <chrono>
#include <condition_variable>
#include <cwctype>
#include <cstdint>
#include <cstdio>
#include <ctime>
#include <cstring>
#include <filesystem>
#include <functional>
#include <deque>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits>
#include <memory>
#include <map>
#include <new>
#include <mutex>
#include <stdexcept>
#include <sstream>
#include <shared_mutex>
#include <string>
#include <thread>
#include <type_traits>
#include <vector>
namespace {
constexpr unsigned int kDefaultSegments = 16;
constexpr unsigned int kMaxSegments = 128;
constexpr size_t kDiskWriteBufferSize = 1024 * 1024;
constexpr uint32_t kLedgerBlockSize = 1024 * 1024;
constexpr uint64_t kMaximumLedgerBytes = 64ULL * 1024 * 1024;
constexpr uint32_t kLedgerVersion = 1;
constexpr size_t kLedgerMaxPathBytes = 65536;
constexpr size_t kLedgerMaxEtagBytes = 1024;
constexpr size_t kLedgerMaxLastModifiedBytes = 256;
// A larger libcurl receive buffer reduces callback overhead on fast links while
// keeping per-worker memory use bounded (about 64 MiB at 128 workers).
constexpr long kCurlReceiveBufferSize = 512L * 1024L;
std::atomic_bool gConsoleCancelled{false};
std::atomic_bool gDownloadPaused{false};
using StatusCallback = std::function<void(const std::wstring&)>;
struct CurlGlobal final {
CurlGlobal() : code(curl_global_init(CURL_GLOBAL_DEFAULT)) {}
~CurlGlobal() { if (code == CURLE_OK) curl_global_cleanup(); }
CURLcode code;
};
struct HeadInfo {
bool accepts_ranges = false;
std::string filename;
std::string etag;
std::string lastModified;
};
bool checkCurl(CURLcode result, const char* operation);
std::string trim(std::string value) {
const auto first = std::find_if_not(value.begin(), value.end(),
[](unsigned char c) { return std::isspace(c) != 0; });
const auto last = std::find_if_not(value.rbegin(), value.rend(),
[](unsigned char c) { return std::isspace(c) != 0; }).base();
if (first >= last) return {};
return std::string(first, last);
}
std::string lower(std::string value) {
std::transform(value.begin(), value.end(), value.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
return value;
}
std::wstring utf8ToWide(const std::string& value) {
if (value.empty()) return {};
const int size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, value.data(),
static_cast<int>(value.size()), nullptr, 0);
if (size <= 0) return std::wstring(value.begin(), value.end());
std::wstring result(static_cast<size_t>(size), L'\0');
MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, value.data(),
static_cast<int>(value.size()), result.data(), size);
return result;
}
std::string wideToUtf8(const std::wstring& value) {
if (value.empty()) return {};
const int size = WideCharToMultiByte(CP_UTF8, 0, value.data(),
static_cast<int>(value.size()), nullptr, 0, nullptr, nullptr);
if (size <= 0) return {};
std::string result(static_cast<size_t>(size), '\0');
WideCharToMultiByte(CP_UTF8, 0, value.data(), static_cast<int>(value.size()),
result.data(), size, nullptr, nullptr);
return result;
}
int hexValue(char c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
}
std::string percentDecode(const std::string& value) {
std::string decoded;
decoded.reserve(value.size());
for (size_t i = 0; i < value.size(); ++i) {
if (value[i] == '%' && i + 2 < value.size()) {
const int high = hexValue(value[i + 1]);
const int low = hexValue(value[i + 2]);
if (high >= 0 && low >= 0) {
decoded.push_back(static_cast<char>((high << 4) | low));
i += 2;
continue;
}
}
decoded.push_back(value[i]);
}
return decoded;
}
std::string safeFilename(std::string value) {
value = trim(value);
if (value.size() >= 2 && value.front() == '"' && value.back() == '"')
value = value.substr(1, value.size() - 2);
value = percentDecode(value);
const auto separator = value.find_last_of("/\\");
if (separator != std::string::npos) value = value.substr(separator + 1);
for (char& c : value) {
const unsigned char byte = static_cast<unsigned char>(c);
if (byte < 32 || c == '<' || c == '>' || c == ':' || c == '"' ||
c == '/' || c == '\\' || c == '|' || c == '?' || c == '*') c = '_';
}
while (!value.empty() && (value.back() == ' ' || value.back() == '.')) value.pop_back();
if (value.empty() || value == "." || value == "..") return "download";
const std::string stem = lower(value.substr(0, value.find('.')));
if (stem == "con" || stem == "prn" || stem == "aux" || stem == "nul" ||
(stem.size() == 4 && (stem.rfind("com", 0) == 0 || stem.rfind("lpt", 0) == 0) &&
stem[3] >= '1' && stem[3] <= '9')) value.insert(value.begin(), '_');
return value;
}
std::string filenameFromUrl(const std::string& url) {
const size_t end = url.find_first_of("?#");
const std::string withoutQuery = url.substr(0, end);
const size_t slash = withoutQuery.find_last_of('/');
return safeFilename(slash == std::string::npos ? withoutQuery : withoutQuery.substr(slash + 1));
}
std::string filenameFromDisposition(const std::string& value) {
const std::string folded = lower(value);
size_t key = folded.find("filename*=");
bool extended = key != std::string::npos;
size_t keyLength = extended ? 10 : 0;
if (!extended) {
key = folded.find("filename=");
keyLength = 9;
}
if (key == std::string::npos) return {};
size_t start = key + keyLength;
size_t end = value.find(';', start);
std::string filename = trim(value.substr(start, end == std::string::npos ? end : end - start));
if (extended) {
const size_t encoding = filename.find("''");
if (encoding != std::string::npos) filename.erase(0, encoding + 2);
}
return safeFilename(filename);
}
size_t headHeaderCallback(char* data, size_t size, size_t count, void* user) {
if (size != 0 && count > (std::numeric_limits<size_t>::max)() / size) return 0;
const size_t bytes = size * count;
auto* info = static_cast<HeadInfo*>(user);
const std::string line(data, bytes);
if (lower(line).rfind("http/", 0) == 0) {
info->accepts_ranges = false;
info->filename.clear();
info->etag.clear();
info->lastModified.clear();
}
const auto colon = line.find(':');
if (colon != std::string::npos) {
const std::string header = lower(trim(line.substr(0, colon)));
if (header == "accept-ranges") info->accepts_ranges = lower(trim(line.substr(colon + 1))) == "bytes";
else if (header == "content-disposition") info->filename = filenameFromDisposition(trim(line.substr(colon + 1)));
else if (header == "etag") info->etag = trim(line.substr(colon + 1));
else if (header == "last-modified") info->lastModified = trim(line.substr(colon + 1));
}
return bytes;
}
bool checkCurl(CURLcode result, const char* operation) {
if (result == CURLE_OK) return true;
std::cerr << operation << " failed: " << curl_easy_strerror(result) << '\n';
return false;
}
long preferredHttpVersion() {
const curl_version_info_data* runtime = curl_version_info(CURLVERSION_NOW);
if (runtime && (runtime->features & CURL_VERSION_HTTP3)) return CURL_HTTP_VERSION_3;
if (runtime && (runtime->features & CURL_VERSION_HTTP2)) return CURL_HTTP_VERSION_2TLS;
return CURL_HTTP_VERSION_1_1;
}
struct RangeTask {
uint64_t first = 0;
uint64_t last = 0;
unsigned int homeThread = 0;
};
struct CompletedRangeQueue {
std::mutex mutex;
std::deque<RangeTask> ranges;
void push(const RangeTask& range) {
std::lock_guard<std::mutex> lock(mutex);
ranges.push_back(range);
}
std::deque<RangeTask> takeAll() {
std::lock_guard<std::mutex> lock(mutex);
std::deque<RangeTask> result;
result.swap(ranges);
return result;
}
};
struct WorkerProgress {
std::atomic<uint64_t> bytes{0};
std::atomic<uint64_t> taskBytes{0};
std::atomic<uint64_t> taskSize{0};
std::atomic<unsigned int> homeThread{0};
std::atomic<int> state{0}; // 0 waiting, 1 downloading, 2 helping, 3 done
};
using ProgressCallback = std::function<void(uint64_t, uint64_t, unsigned int, unsigned int,
const std::vector<WorkerProgress>&)>;
// Lightweight local hill-climber: probe one extra connection, retain it only
// when observed throughput improves, and back off when disk writes queue up.
class AdaptiveController final {
public:
explicit AdaptiveController(unsigned int maximum)
: maximum_(std::max(1u, maximum)), limit_(std::min(4u, maximum_)),
lastSampleTime_(std::chrono::steady_clock::now()), nextProbe_(lastSampleTime_ + std::chrono::seconds(5)) {}
bool acquire(const std::atomic_bool& stop, const std::atomic_bool* cancel) {
std::unique_lock<std::mutex> lock(mutex_);
while (active_ >= limit_ && !stop.load() && !(cancel && cancel->load()))
changed_.wait_for(lock, std::chrono::milliseconds(100));
if (stop.load() || (cancel && cancel->load())) return false;
++active_;
return true;
}
void release() {
{ std::lock_guard<std::mutex> lock(mutex_); if (active_ > 0) --active_; }
changed_.notify_all();
}
unsigned int limit() const { return visibleLimit_.load(); }
void observe(uint64_t receivedBytes, unsigned int pendingWrites,
std::chrono::steady_clock::time_point now) {
if (now - lastSampleTime_ < std::chrono::seconds(5)) return;
const double seconds = std::chrono::duration<double>(now - lastSampleTime_).count();
const double rate = seconds > 0.0
? static_cast<double>(receivedBytes - lastSampleBytes_) / seconds : 0.0;
lastSampleBytes_ = receivedBytes;
lastSampleTime_ = now;
if (pendingWrites >= 48) {
setLimit(limit() > 1 ? limit() - 1 : 1);
trialPending_ = false;
nextProbe_ = now + std::chrono::seconds(10);
return;
}
if (trialPending_) {
// Keep a new connection only if it delivers a measurable gain.
if (rate < trialBaselineRate_ * 1.05) setLimit(trialPreviousLimit_);
trialPending_ = false;
nextProbe_ = now + std::chrono::seconds(8);
} else if (now >= nextProbe_ && limit() < maximum_ && rate > 0.0) {
trialBaselineRate_ = rate;
trialPreviousLimit_ = limit();
setLimit(trialPreviousLimit_ + 1);
trialPending_ = true;
nextProbe_ = now + std::chrono::seconds(5);
}
}
private:
const unsigned int maximum_;
mutable std::mutex mutex_;
std::condition_variable changed_;
unsigned int active_ = 0;
unsigned int limit_;
std::atomic<unsigned int> visibleLimit_{limit_};
uint64_t lastSampleBytes_ = 0;
std::chrono::steady_clock::time_point lastSampleTime_;
std::chrono::steady_clock::time_point nextProbe_;
double trialBaselineRate_ = 0.0;
unsigned int trialPreviousLimit_ = 0;
bool trialPending_ = false;
void setLimit(unsigned int value) {
{
std::lock_guard<std::mutex> lock(mutex_);
limit_ = std::clamp(value, 1u, maximum_);
visibleLimit_.store(limit_);
}
changed_.notify_all();
}
};
struct Segment {
const std::string* url = nullptr;
const std::wstring* path = nullptr;
const std::string* ifRangeValidator = nullptr;
uint64_t first = 0;
uint64_t last = 0;
uint64_t expected = 0;
std::atomic<uint64_t> written{0};
uint64_t contiguousWritten = 0;
uint64_t queued = 0;
uint64_t received = 0;
std::vector<char> writeBuffer;
std::atomic_bool write_failed{false};
std::atomic<unsigned int> pendingWrites{0};
std::mutex completionMutex;
std::condition_variable completionChanged;
std::map<uint64_t, uint64_t> completedRanges;
class AsyncDiskWriter* diskWriter = nullptr;
std::atomic_bool* cancel = nullptr;
std::atomic_bool* paused = nullptr;
std::atomic_bool* stop = nullptr;
std::atomic<uint64_t>* totalWritten = nullptr;
std::atomic<uint64_t>* totalReceived = nullptr;
WorkerProgress* progress = nullptr;
AdaptiveController* controller = nullptr;
long connectTimeoutSeconds = 90;
curl_off_t maxReceiveBytesPerSecond = 0;
};
struct BackgroundIoScope final {
BackgroundIoScope() : active(SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN) != FALSE) {}
~BackgroundIoScope() {
if (active) SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_END);
}
bool active;
};
// Each request owns its buffer until IOCP reports completion. At most 64 requests
// can be outstanding, so a slow disk applies backpressure instead of growing RAM.
class AsyncDiskWriter final {
struct WriteContext {
OVERLAPPED overlapped{};
Segment* segment = nullptr;
std::vector<char> data;
uint64_t offset = 0;
size_t completed = 0;
};
public:
explicit AsyncDiskWriter(const std::wstring& path, unsigned int workerCount) {
file_ = CreateFileW(path.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, nullptr);
if (file_ == INVALID_HANDLE_VALUE)
throw std::runtime_error("Could not open output file for asynchronous writes (Windows error " +
std::to_string(GetLastError()) + ").");
port_ = CreateIoCompletionPort(file_, nullptr, 0, 0);
if (!port_) {
const DWORD error = GetLastError(); CloseHandle(file_); file_ = INVALID_HANDLE_VALUE;
throw std::runtime_error("Could not create I/O completion port (Windows error " +
std::to_string(error) + ").");
}
const unsigned int count = std::max(1u, std::min(4u, workerCount));
try {
for (unsigned int i = 0; i < count; ++i) threads_.emplace_back(&AsyncDiskWriter::completionLoop, this);
} catch (...) {
for (size_t i = 0; i < threads_.size(); ++i) PostQueuedCompletionStatus(port_, 0, 0, nullptr);
for (auto& thread : threads_) if (thread.joinable()) thread.join();
CloseHandle(port_); CloseHandle(file_); port_ = nullptr; file_ = INVALID_HANDLE_VALUE;
throw;
}
}
~AsyncDiskWriter() {
close();
}
void close() {
if (closed_) return;
for (size_t i = 0; i < threads_.size(); ++i) PostQueuedCompletionStatus(port_, 0, 0, nullptr);
for (auto& thread : threads_) if (thread.joinable()) thread.join();
if (port_) CloseHandle(port_);
if (file_ != INVALID_HANDLE_VALUE) CloseHandle(file_);
port_ = nullptr;
file_ = INVALID_HANDLE_VALUE;
closed_ = true;
}
bool submit(Segment& segment) {
if (segment.writeBuffer.empty()) return true;
std::shared_lock<std::shared_mutex> submissionLock(submissionBarrier_);
{
std::unique_lock<std::mutex> lock(capacityMutex_);
capacityChanged_.wait(lock, [&] { return outstanding_ < kMaxOutstanding; });
++outstanding_;
}
auto* context = new (std::nothrow) WriteContext;
if (!context) { releaseCapacity(); segment.write_failed.store(true); return false; }
context->segment = &segment;
context->offset = segment.first + segment.queued;
const size_t submittedSize = segment.writeBuffer.size();
std::vector<char> replacementBuffer;
try { replacementBuffer.reserve(kDiskWriteBufferSize); }
catch (...) { delete context; releaseCapacity(); segment.write_failed.store(true); return false; }
context->data.swap(segment.writeBuffer);
segment.writeBuffer.swap(replacementBuffer);
segment.pendingWrites.fetch_add(1);
if (!issue(context)) return false;
segment.queued += submittedSize;
segment.writeBuffer.clear();
return true;
}
void wait(Segment& segment) {
std::unique_lock<std::mutex> lock(segment.completionMutex);
segment.completionChanged.wait(lock, [&] { return segment.pendingWrites.load() == 0; });
}
unsigned int outstanding() {
std::lock_guard<std::mutex> lock(capacityMutex_);
return outstanding_;
}
bool flushData() {
std::unique_lock<std::shared_mutex> barrier(submissionBarrier_);
{
std::unique_lock<std::mutex> lock(capacityMutex_);
capacityChanged_.wait(lock, [&] { return outstanding_ == 0; });
}
return file_ != INVALID_HANDLE_VALUE && FlushFileBuffers(file_) != FALSE;
}
private:
static constexpr unsigned int kMaxOutstanding = 64;
HANDLE file_ = INVALID_HANDLE_VALUE;
HANDLE port_ = nullptr;
std::vector<std::thread> threads_;
std::mutex capacityMutex_;
std::condition_variable capacityChanged_;
std::shared_mutex submissionBarrier_;
unsigned int outstanding_ = 0;
bool closed_ = false;
void releaseCapacity() {
{ std::lock_guard<std::mutex> lock(capacityMutex_); --outstanding_; }
capacityChanged_.notify_all();
}
bool issue(WriteContext* context) {
std::memset(&context->overlapped, 0, sizeof(context->overlapped));
const uint64_t offset = context->offset + context->completed;
context->overlapped.Offset = static_cast<DWORD>(offset & 0xffffffffu);
context->overlapped.OffsetHigh = static_cast<DWORD>(offset >> 32);
const DWORD length = static_cast<DWORD>(std::min<size_t>(context->data.size() - context->completed,
static_cast<size_t>((std::numeric_limits<DWORD>::max)())));
DWORD transferred = 0;
const BOOL ok = WriteFile(file_, context->data.data() + context->completed, length,
&transferred, &context->overlapped);
if (!ok && GetLastError() != ERROR_IO_PENDING) {
context->segment->write_failed.store(true);
finish(context, false, 0);
return false;
}
return true;
}
void completionLoop() {
for (;;) {
DWORD transferred = 0;
ULONG_PTR key = 0;
OVERLAPPED* overlapped = nullptr;
const BOOL ok = GetQueuedCompletionStatus(port_, &transferred, &key, &overlapped, INFINITE);
if (!overlapped) { if (key == 0) return; continue; }
auto* context = reinterpret_cast<WriteContext*>(overlapped);
if (!ok || transferred == 0) {
context->segment->write_failed.store(true);
finish(context, false, 0);
continue;
}
context->completed += transferred;
context->segment->written.fetch_add(transferred);
if (context->segment->totalWritten) context->segment->totalWritten->fetch_add(transferred);
if (context->segment->progress) {
context->segment->progress->bytes.fetch_add(transferred);
context->segment->progress->taskBytes.store(context->segment->written.load());
}
if (context->completed < context->data.size()) {
if (!issue(context)) continue;
} else finish(context, true, context->data.size());
}
}
void finish(WriteContext* context, bool success, size_t length) {
Segment& segment = *context->segment;
if (success) {
std::lock_guard<std::mutex> lock(segment.completionMutex);
segment.completedRanges.emplace(context->offset, length);
for (;;) {
auto it = segment.completedRanges.upper_bound(segment.first + segment.contiguousWritten);
if (it != segment.completedRanges.begin()) --it;
if (it == segment.completedRanges.end() || it->first > segment.first + segment.contiguousWritten ||
it->first + it->second <= segment.first + segment.contiguousWritten) break;
segment.contiguousWritten = it->first + it->second - segment.first;
segment.completedRanges.erase(it);
}
}
delete context;
segment.pendingWrites.fetch_sub(1);
segment.completionChanged.notify_all();
releaseCapacity();
}
};
bool flushSegmentBuffer(Segment& segment) {
if (segment.writeBuffer.empty()) return true;
return segment.diskWriter && segment.diskWriter->submit(segment);
}
int transferProgressCallback(void* user, curl_off_t, curl_off_t, curl_off_t, curl_off_t) {
const auto* segment = static_cast<const Segment*>(user);
return (segment->cancel && segment->cancel->load()) || (segment->stop && segment->stop->load()) ||
(segment->paused && segment->paused->load()) ? 1 : 0;
}
int headProgressCallback(void* user, curl_off_t, curl_off_t, curl_off_t, curl_off_t) {
const auto* cancel = static_cast<const std::atomic_bool*>(user);
return cancel && cancel->load() ? 1 : 0;
}
size_t fileWriteCallback(char* data, size_t size, size_t count, void* user) {
if (size != 0 && count > (std::numeric_limits<size_t>::max)() / size) return 0;
const size_t bytes = size * count;
auto* segment = static_cast<Segment*>(user);
if (segment->received > segment->expected || bytes > segment->expected - segment->received) {
segment->write_failed = true; // A server that ignored Range must not overwrite another segment.
return 0;
}
try {
segment->writeBuffer.insert(segment->writeBuffer.end(), data, data + bytes);
} catch (...) {
segment->write_failed = true;
return 0;
}
segment->received += bytes;
if (segment->totalReceived) segment->totalReceived->fetch_add(bytes);
if (segment->writeBuffer.size() >= kDiskWriteBufferSize && !flushSegmentBuffer(*segment)) return 0;
return bytes;
}
bool downloadRange(Segment& segment, CURL* curl, std::mutex& logMutex, bool terminalUi) {
constexpr unsigned int kMaxAttempts = 8;
CURLcode result = CURLE_OK;
long status = 0;
unsigned int attempt = 0;
while (attempt < kMaxAttempts) {
while (segment.paused && segment.paused->load()) {
if ((segment.cancel && segment.cancel->load()) || (segment.stop && segment.stop->load())) return false;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
if (segment.write_failed.load() || (segment.cancel && segment.cancel->load()) ||
(segment.stop && segment.stop->load())) return false;
++attempt;
// A retry resumes at the last contiguous committed byte, so the
// callback's range-overflow guard must use that same logical position.
segment.received = segment.contiguousWritten;
const uint64_t nextByte = segment.first + segment.contiguousWritten;
const std::string range = std::to_string(nextByte) + "-" + std::to_string(segment.last);
result = curl_easy_setopt(curl, CURLOPT_RANGE, range.c_str());
if (result != CURLE_OK) break;
result = curl_easy_perform(curl);
if (!flushSegmentBuffer(segment)) result = CURLE_WRITE_ERROR;
segment.diskWriter->wait(segment);
status = 0;
const CURLcode infoResult = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &status);
if (infoResult != CURLE_OK && result == CURLE_OK) result = infoResult;
if (status == 206 && segment.contiguousWritten == segment.expected) return true;
if (segment.paused && segment.paused->load()) {
while (segment.paused->load()) {
if ((segment.cancel && segment.cancel->load()) || (segment.stop && segment.stop->load())) return false;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
if ((segment.cancel && segment.cancel->load()) || (segment.stop && segment.stop->load())) return false;
--attempt; // A user pause is not a failed network attempt.
continue;
}
const bool cancelled = (segment.cancel && segment.cancel->load()) ||
(segment.stop && segment.stop->load());
const bool retryable = !cancelled && !segment.write_failed.load() && attempt < kMaxAttempts &&
(result != CURLE_OK || status == 429 || status >= 500);
if (!retryable) break;
if (!terminalUi) {
std::lock_guard<std::mutex> lock(logMutex);
std::cerr << "Range [" << segment.first << '-' << segment.last << "] retry "
<< attempt << '/' << (kMaxAttempts - 1) << " after "
<< segment.contiguousWritten << '/' << segment.expected << " bytes.\n";
}
for (unsigned int tick = 0; tick < (1u << (attempt - 1)) * 10; ++tick) {
if ((segment.cancel && segment.cancel->load()) || (segment.stop && segment.stop->load())) return false;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
if (!(segment.cancel && segment.cancel->load()) && !(segment.stop && segment.stop->load())) {
std::lock_guard<std::mutex> lock(logMutex);
std::cerr << "Range [" << segment.first << '-' << segment.last << "] failed: ";
if (segment.write_failed.load()) std::cerr << "disk write failed or range overflowed";
else if (result != CURLE_OK) std::cerr << curl_easy_strerror(result);
else if (status != 206) std::cerr << "server returned HTTP " << status << " instead of 206";
else std::cerr << "received " << segment.contiguousWritten << " of " << segment.expected << " bytes";
std::cerr << '\n';
}
return false;
}
void downloadSegment(unsigned int workerIndex, std::deque<RangeTask>& tasks,
std::mutex& queueMutex, Segment& segment, WorkerProgress& progress,
std::atomic<unsigned int>& finishedWorkers, std::atomic_bool& stop,
std::atomic_bool& failed, std::mutex& logMutex, bool terminalUi,
AsyncDiskWriter& diskWriter, CompletedRangeQueue& completedRanges) {
auto finish = [&]() { progress.state.store(3); finishedWorkers.fetch_add(1); };
segment.diskWriter = &diskWriter;
CURL* curl = curl_easy_init();
if (!curl) {
std::lock_guard<std::mutex> lock(logMutex);
std::cerr << "T" << workerIndex + 1 << " could not create a curl context.\n";
failed.store(true);
stop.store(true);
finish();
return;
}
try {
segment.writeBuffer.reserve(kDiskWriteBufferSize);
} catch (...) {
std::lock_guard<std::mutex> lock(logMutex);
std::cerr << "T" << workerIndex + 1 << " could not allocate its disk buffer.\n";
curl_easy_cleanup(curl);
failed.store(true);
stop.store(true);
finish();
return;
}
bool configured = true;
configured &= checkCurl(curl_easy_setopt(curl, CURLOPT_URL, segment.url->c_str()), "Setting URL");
if (std::filesystem::exists("curl-ca-bundle.crt"))
configured &= checkCurl(curl_easy_setopt(curl, CURLOPT_CAINFO, "curl-ca-bundle.crt"), "Setting bundled TLS certificate authorities");
configured &= checkCurl(curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fileWriteCallback), "Setting write callback");
configured &= checkCurl(curl_easy_setopt(curl, CURLOPT_WRITEDATA, &segment), "Setting write context");
configured &= checkCurl(curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L), "Enabling redirects");
configured &= checkCurl(curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, preferredHttpVersion()), "Selecting HTTP protocol");
configured &= checkCurl(curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, segment.connectTimeoutSeconds), "Setting connect timeout");
configured &= checkCurl(curl_easy_setopt(curl, CURLOPT_BUFFERSIZE, kCurlReceiveBufferSize), "Setting receive buffer size");
configured &= checkCurl(curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 64L), "Setting minimum transfer speed");
configured &= checkCurl(curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, 240L), "Setting low-speed timeout");
configured &= checkCurl(curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L), "Disabling curl signals");
configured &= checkCurl(curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L), "Enabling cancellation checks");
configured &= checkCurl(curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, transferProgressCallback), "Setting cancellation callback");
configured &= checkCurl(curl_easy_setopt(curl, CURLOPT_XFERINFODATA, &segment), "Setting cancellation context");
curl_slist* requestHeaders = nullptr;
if (segment.ifRangeValidator && !segment.ifRangeValidator->empty()) {
const std::string ifRange = "If-Range: " + *segment.ifRangeValidator;
requestHeaders = curl_slist_append(nullptr, ifRange.c_str());
if (!requestHeaders) {
std::cerr << "T" << workerIndex + 1 << " could not allocate the range validator header.\n";
configured = false;
} else {
configured &= checkCurl(curl_easy_setopt(curl, CURLOPT_HTTPHEADER, requestHeaders),
"Setting the If-Range validator");
}
}
if (!configured) { failed.store(true); stop.store(true); }
while (configured && !stop.load() && !(segment.cancel && segment.cancel->load())) {
progress.state.store(0);
if (!segment.controller || !segment.controller->acquire(stop, segment.cancel)) break;
RangeTask task;
{
std::lock_guard<std::mutex> lock(queueMutex);
if (tasks.empty()) {
segment.controller->release();
break;
}
task = tasks.front();
tasks.pop_front();
}
segment.first = task.first;
segment.last = task.last;
segment.expected = task.last - task.first + 1;
segment.written.store(0);
segment.contiguousWritten = 0;
segment.queued = 0;
segment.pendingWrites.store(0);
segment.completedRanges.clear();
segment.received = 0;
segment.writeBuffer.clear();
segment.write_failed.store(false);
progress.taskBytes.store(0);
progress.taskSize.store(segment.expected);
progress.homeThread.store(task.homeThread);
progress.state.store(task.homeThread == workerIndex ? 1 : 2);
if (segment.maxReceiveBytesPerSecond > 0) {
const uint64_t activeLimit = std::max(1u, segment.controller->limit());
const auto perConnectionLimit = static_cast<curl_off_t>(std::max<uint64_t>(
1, segment.maxReceiveBytesPerSecond / activeLimit));
if (!checkCurl(curl_easy_setopt(curl, CURLOPT_MAX_RECV_SPEED_LARGE, perConnectionLimit),
"Updating adaptive per-connection receive limit")) {
segment.controller->release();
failed.store(true);
stop.store(true);
break;
}
}
const bool taskSucceeded = downloadRange(segment, curl, logMutex, terminalUi);
segment.controller->release();
if (!taskSucceeded) {
if (!(segment.cancel && segment.cancel->load()) && !stop.load()) failed.store(true);
stop.store(true);
break;
}
completedRanges.push(task);
}
if (!segment.writeBuffer.empty() && !segment.write_failed.load()) flushSegmentBuffer(segment);
diskWriter.wait(segment);
if (requestHeaders) curl_slist_free_all(requestHeaders);
curl_easy_cleanup(curl);
finish();
}
bool getRemoteFileInfo(const std::string& url, uint64_t& length, std::string& filename,
std::string& etag, std::string& lastModified,
std::atomic_bool* cancel = nullptr, long connectTimeoutSeconds = 30) {
CURL* curl = curl_easy_init();
if (!curl) {
std::cerr << "Could not create curl context for HTTP HEAD request.\n";
return false;
}
HeadInfo headers;
bool configured = true;
configured &= checkCurl(curl_easy_setopt(curl, CURLOPT_URL, url.c_str()), "Setting HEAD URL");
if (std::filesystem::exists("curl-ca-bundle.crt"))
configured &= checkCurl(curl_easy_setopt(curl, CURLOPT_CAINFO, "curl-ca-bundle.crt"), "Setting bundled TLS certificate authorities");
configured &= checkCurl(curl_easy_setopt(curl, CURLOPT_NOBODY, 1L), "Configuring HTTP HEAD");
configured &= checkCurl(curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L), "Enabling redirects");
configured &= checkCurl(curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, preferredHttpVersion()), "Selecting HTTP protocol");
configured &= checkCurl(curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, headHeaderCallback), "Setting header callback");
configured &= checkCurl(curl_easy_setopt(curl, CURLOPT_HEADERDATA, &headers), "Setting header context");
configured &= checkCurl(curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, connectTimeoutSeconds), "Setting connect timeout");
configured &= checkCurl(curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L), "Enabling cancellation checks");
configured &= checkCurl(curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, headProgressCallback), "Setting cancellation callback");
configured &= checkCurl(curl_easy_setopt(curl, CURLOPT_XFERINFODATA, cancel), "Setting cancellation state");
CURLcode result = configured ? curl_easy_perform(curl) : CURLE_FAILED_INIT;
long status = 0;
curl_off_t contentLength = -1;
if (result == CURLE_OK) result = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &status);
if (result == CURLE_OK) result = curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &contentLength);
if (result != CURLE_OK) std::cerr << "HTTP HEAD request failed: " << curl_easy_strerror(result) << '\n';
else if (status < 200 || status >= 300) std::cerr << "HTTP HEAD returned status " << status << ".\n";
else if (contentLength <= 0) std::cerr << "Could not determine a positive Content-Length from HTTP HEAD.\n";
else if (!headers.accepts_ranges) std::cerr << "Server did not advertise Accept-Ranges: bytes.\n";
const bool ok = result == CURLE_OK && status >= 200 && status < 300 &&
contentLength > 0 && headers.accepts_ranges;
if (ok) {
length = static_cast<uint64_t>(contentLength);
filename = headers.filename.empty() ? filenameFromUrl(url) : headers.filename;
etag = headers.etag;
lastModified = headers.lastModified;
}
curl_easy_cleanup(curl);
return ok;
}
bool preallocateFile(const std::wstring& path, uint64_t size, bool resumeExisting = false) {
BackgroundIoScope backgroundIo;
HANDLE file = CreateFileW(path.c_str(), GENERIC_WRITE, FILE_SHARE_READ, nullptr,
resumeExisting ? OPEN_EXISTING : CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file == INVALID_HANDLE_VALUE) {
std::cerr << "Could not create output file (Windows error " << GetLastError() << ").\n";
return false;
}
bool ok = false;
if (resumeExisting) {
LARGE_INTEGER existing{};
ok = GetFileSizeEx(file, &existing) && existing.QuadPart == static_cast<LONGLONG>(size);
if (!ok) std::cerr << "Could not resume partial file because its size does not match the ledger.\n";
} else {
LARGE_INTEGER end{};
end.QuadPart = static_cast<LONGLONG>(size);
ok = SetFilePointerEx(file, end, nullptr, FILE_BEGIN) && SetEndOfFile(file);
if (ok) ok = FlushFileBuffers(file) != FALSE;
if (!ok) std::cerr << "Could not pre-allocate output file (Windows error " << GetLastError() << ").\n";
}
CloseHandle(file);
return ok;
}
struct DownloadLedger {
uint64_t fileSize = 0;
std::string destination;
std::string etag;
std::string lastModified;
std::vector<uint8_t> bitmap;
};
uint64_t ledgerBlockCount(uint64_t fileSize) {
return fileSize / kLedgerBlockSize + (fileSize % kLedgerBlockSize != 0);
}
uint64_t ledgerBitmapBytes(uint64_t blockCount) {
return blockCount / 8 + (blockCount % 8 != 0);
}
bool ledgerBit(const std::vector<uint8_t>& bitmap, uint64_t block) {
const uint64_t byte = block / 8;
return byte < bitmap.size() && (bitmap[static_cast<size_t>(byte)] & (uint8_t{1} << (block % 8))) != 0;
}
void setLedgerBit(std::vector<uint8_t>& bitmap, uint64_t block) {
bitmap[static_cast<size_t>(block / 8)] |= static_cast<uint8_t>(uint8_t{1} << (block % 8));
}
void appendLe16(std::vector<uint8_t>& bytes, uint16_t value) {
bytes.push_back(static_cast<uint8_t>(value));
bytes.push_back(static_cast<uint8_t>(value >> 8));
}
void appendLe32(std::vector<uint8_t>& bytes, uint32_t value) {
for (unsigned int i = 0; i < 4; ++i) bytes.push_back(static_cast<uint8_t>(value >> (i * 8)));
}
void appendLe64(std::vector<uint8_t>& bytes, uint64_t value) {
for (unsigned int i = 0; i < 8; ++i) bytes.push_back(static_cast<uint8_t>(value >> (i * 8)));
}
template <typename UInt>
bool readLe(const std::vector<uint8_t>& bytes, size_t& offset, UInt& value, size_t limit) {
static_assert(std::is_unsigned<UInt>::value, "readLe requires an unsigned integer");
if (offset > limit || sizeof(UInt) > limit - offset) return false;
value = 0;
for (size_t i = 0; i < sizeof(UInt); ++i)
value |= static_cast<UInt>(bytes[offset++]) << (i * 8);
return true;
}
uint32_t ledgerCrc32(const uint8_t* data, size_t size) {
uint32_t crc = 0xffffffffu;
for (size_t i = 0; i < size; ++i) {
crc ^= data[i];
for (unsigned int bit = 0; bit < 8; ++bit)
crc = (crc >> 1) ^ (0xedb88320u & (0u - (crc & 1u)));
}
return ~crc;
}
bool validLedgerText(const std::string& value, size_t maximum) {
return value.size() <= maximum && value.find('\0') == std::string::npos &&
value.find('\r') == std::string::npos && value.find('\n') == std::string::npos;
}
bool usableResumeValidator(const std::string& etag, const std::string& lastModified) {
const bool strongEtag = !etag.empty() && etag.rfind("W/", 0) != 0;
return (strongEtag && validLedgerText(etag, kLedgerMaxEtagBytes)) ||
(!lastModified.empty() && validLedgerText(lastModified, kLedgerMaxLastModifiedBytes));
}
bool ledgerMatches(const DownloadLedger& ledger, uint64_t fileSize, const std::string& destination,
const std::string& etag, const std::string& lastModified) {
if (ledger.fileSize != fileSize || ledger.destination != destination ||
!usableResumeValidator(etag, lastModified)) return false;
if (!ledger.etag.empty() && ledger.etag.rfind("W/", 0) != 0)
return ledger.etag == etag;
return !ledger.lastModified.empty() && ledger.lastModified == lastModified;
}
bool serializeLedger(const DownloadLedger& ledger, std::vector<uint8_t>& bytes) {
const uint64_t blockCount = ledgerBlockCount(ledger.fileSize);
const uint64_t expectedBitmapBytes = ledgerBitmapBytes(blockCount);
if (ledger.fileSize == 0 || ledger.bitmap.size() != expectedBitmapBytes ||
expectedBitmapBytes > kMaximumLedgerBytes ||
!validLedgerText(ledger.destination, kLedgerMaxPathBytes) || ledger.destination.empty() ||
!validLedgerText(ledger.etag, kLedgerMaxEtagBytes) ||
!validLedgerText(ledger.lastModified, kLedgerMaxLastModifiedBytes)) return false;
try {
bytes.clear();
bytes.reserve(static_cast<size_t>(44 + ledger.destination.size() + ledger.etag.size() +
ledger.lastModified.size() + expectedBitmapBytes + 4));
bytes.insert(bytes.end(), {'T', 'I', 'D', 'M'});
appendLe32(bytes, kLedgerVersion);
appendLe64(bytes, ledger.fileSize);
appendLe32(bytes, kLedgerBlockSize);
appendLe64(bytes, blockCount);
appendLe32(bytes, static_cast<uint32_t>(ledger.destination.size()));
appendLe16(bytes, static_cast<uint16_t>(ledger.etag.size()));
appendLe16(bytes, static_cast<uint16_t>(ledger.lastModified.size()));
appendLe64(bytes, expectedBitmapBytes);
bytes.insert(bytes.end(), ledger.destination.begin(), ledger.destination.end());
bytes.insert(bytes.end(), ledger.etag.begin(), ledger.etag.end());
bytes.insert(bytes.end(), ledger.lastModified.begin(), ledger.lastModified.end());
bytes.insert(bytes.end(), ledger.bitmap.begin(), ledger.bitmap.end());
appendLe32(bytes, ledgerCrc32(bytes.data(), bytes.size()));
return bytes.size() <= kMaximumLedgerBytes;
} catch (...) {
bytes.clear();
return false;
}
}
bool saveLedgerAtomic(const std::wstring& ledgerPath, const DownloadLedger& ledger) {
std::vector<uint8_t> bytes;
if (!serializeLedger(ledger, bytes)) return false;
const std::wstring tempPath = ledgerPath + L".tmp";
HANDLE file = CreateFileW(tempPath.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, nullptr);
if (file == INVALID_HANDLE_VALUE) return false;
size_t offset = 0;
bool ok = true;
while (offset < bytes.size()) {
const DWORD count = static_cast<DWORD>(std::min<size_t>(bytes.size() - offset,
static_cast<size_t>((std::numeric_limits<DWORD>::max)())));
DWORD written = 0;
if (!WriteFile(file, bytes.data() + offset, count, &written, nullptr) || written == 0) {
ok = false;
break;
}
offset += written;
}
if (ok) ok = FlushFileBuffers(file) != FALSE;
if (!CloseHandle(file)) ok = false;
if (ok) ok = MoveFileExW(tempPath.c_str(), ledgerPath.c_str(),
MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != FALSE;
if (!ok) DeleteFileW(tempPath.c_str());
return ok;
}
bool loadLedger(const std::wstring& ledgerPath, DownloadLedger& ledger) {
std::ifstream file(std::filesystem::path(ledgerPath), std::ios::binary | std::ios::ate);
if (!file) return false;
const std::streamoff end = file.tellg();
constexpr size_t kFixedLength = 44;
if (end < static_cast<std::streamoff>(kFixedLength + 4) ||
static_cast<uint64_t>(end) > kMaximumLedgerBytes) return false;
std::vector<uint8_t> bytes(static_cast<size_t>(end));
file.seekg(0, std::ios::beg);
if (!file.read(reinterpret_cast<char*>(bytes.data()), static_cast<std::streamsize>(bytes.size()))) return false;
if (std::memcmp(bytes.data(), "TIDM", 4) != 0) return false;
const size_t crcOffset = bytes.size() - 4;
size_t crcReadOffset = crcOffset;
uint32_t storedCrc = 0;
if (!readLe(bytes, crcReadOffset, storedCrc, bytes.size()) ||
storedCrc != ledgerCrc32(bytes.data(), crcOffset)) return false;
size_t offset = 4;
uint32_t version = 0, blockSize = 0, pathLength = 0;
uint64_t fileSize = 0, blockCount = 0, bitmapLength = 0;
uint16_t etagLength = 0, modifiedLength = 0;
if (!readLe(bytes, offset, version, crcOffset) || !readLe(bytes, offset, fileSize, crcOffset) ||
!readLe(bytes, offset, blockSize, crcOffset) || !readLe(bytes, offset, blockCount, crcOffset) ||
!readLe(bytes, offset, pathLength, crcOffset) || !readLe(bytes, offset, etagLength, crcOffset) ||
!readLe(bytes, offset, modifiedLength, crcOffset) || !readLe(bytes, offset, bitmapLength, crcOffset)) return false;
if (version != kLedgerVersion || fileSize == 0 || blockSize != kLedgerBlockSize ||
blockCount != ledgerBlockCount(fileSize) || bitmapLength != ledgerBitmapBytes(blockCount) ||
bitmapLength > kMaximumLedgerBytes || pathLength > kLedgerMaxPathBytes ||
etagLength > kLedgerMaxEtagBytes || modifiedLength > kLedgerMaxLastModifiedBytes) return false;
const uint64_t payloadLength = static_cast<uint64_t>(pathLength) + etagLength + modifiedLength + bitmapLength;
if (payloadLength != crcOffset - offset) return false;
DownloadLedger loaded;
loaded.fileSize = fileSize;
loaded.destination.assign(reinterpret_cast<const char*>(bytes.data() + offset), pathLength);
offset += pathLength;
loaded.etag.assign(reinterpret_cast<const char*>(bytes.data() + offset), etagLength);
offset += etagLength;
loaded.lastModified.assign(reinterpret_cast<const char*>(bytes.data() + offset), modifiedLength);