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
|
// Copyright Epic Games, Inc. All Rights Reserved.
#include <zenhttp/packageformat.h>
#include <zencore/compactbinarybuilder.h>
#include <zencore/compactbinarypackage.h>
#include <zencore/compactbinaryutil.h>
#include <zencore/compositebuffer.h>
#include <zencore/filesystem.h>
#include <zencore/fmtutils.h>
#include <zencore/iobuffer.h>
#include <zencore/iohash.h>
#include <zencore/logging.h>
#include <zencore/scopeguard.h>
#include <zencore/stream.h>
#include <zencore/testing.h>
#include <zencore/testutils.h>
#include <zencore/trace.h>
#include <span>
#include <vector>
#include <EASTL/fixed_vector.h>
#if ZEN_PLATFORM_WINDOWS
# include <zencore/windows.h>
#endif
ZEN_THIRD_PARTY_INCLUDES_START
#include <tsl/robin_map.h>
ZEN_THIRD_PARTY_INCLUDES_END
namespace zen {
const std::string_view HandlePrefix(":?#:");
typedef eastl::fixed_vector<IoBuffer, 16> IoBufferVec_t;
IoBufferVec_t FormatPackageMessageInternal(const CbPackage& Data, FormatFlags Flags, void* TargetProcessHandle);
std::vector<IoBuffer>
FormatPackageMessage(const CbPackage& Data, void* TargetProcessHandle)
{
return FormatPackageMessage(Data, FormatFlags::kDefault, TargetProcessHandle);
}
CompositeBuffer
FormatPackageMessageBuffer(const CbPackage& Data, void* TargetProcessHandle)
{
return FormatPackageMessageBuffer(Data, FormatFlags::kDefault, TargetProcessHandle);
}
std::vector<IoBuffer>
FormatPackageMessage(const CbPackage& Data, FormatFlags Flags, void* TargetProcessHandle)
{
auto Vec = FormatPackageMessageInternal(Data, Flags, TargetProcessHandle);
return std::vector<IoBuffer>(begin(Vec), end(Vec));
}
CompositeBuffer
FormatPackageMessageBuffer(const CbPackage& Data, FormatFlags Flags, void* TargetProcessHandle)
{
auto Vec = FormatPackageMessageInternal(Data, Flags, TargetProcessHandle);
return CompositeBuffer(std::span{begin(Vec), end(Vec)});
}
static void
MarshalLocal(CbAttachmentEntry*& AttachmentInfo,
const std::string& Path8,
CbAttachmentReferenceHeader& LocalRef,
const IoHash& AttachmentHash,
bool IsCompressed,
IoBufferVec_t& ResponseBuffers)
{
IoBuffer RefBuffer(sizeof(CbAttachmentReferenceHeader) + Path8.size());
CbAttachmentReferenceHeader* RefHdr = RefBuffer.MutableData<CbAttachmentReferenceHeader>();
*RefHdr++ = LocalRef;
memcpy(RefHdr, Path8.data(), Path8.size());
*AttachmentInfo++ = {.PayloadSize = RefBuffer.GetSize(),
.Flags = (IsCompressed ? uint32_t(CbAttachmentEntry::kIsCompressed) : 0u) | CbAttachmentEntry::kIsLocalRef,
.AttachmentHash = AttachmentHash};
ResponseBuffers.emplace_back(std::move(RefBuffer));
};
static bool
IsLocalRef(tsl::robin_map<void*, std::string>& FileNameMap,
std::vector<void*>& DuplicatedHandles,
const CompositeBuffer& AttachmentBinary,
bool DenyPartialLocalReferences,
void* TargetProcessHandle,
CbAttachmentReferenceHeader& LocalRef,
std::string& Path8)
{
const SharedBuffer& Segment = AttachmentBinary.GetSegments().front();
IoBufferFileReference Ref;
const IoBuffer& SegmentBuffer = Segment.AsIoBuffer();
if (!SegmentBuffer.GetFileReference(Ref))
{
return false;
}
if (DenyPartialLocalReferences && !SegmentBuffer.IsWholeFile())
{
return false;
}
if (auto It = FileNameMap.find(Ref.FileHandle); It != FileNameMap.end())
{
Path8 = It->second;
}
else
{
bool UseFilePath = true;
#if ZEN_PLATFORM_WINDOWS
if (TargetProcessHandle != nullptr)
{
HANDLE TargetHandle = INVALID_HANDLE_VALUE;
BOOL OK = ::DuplicateHandle(GetCurrentProcess(),
Ref.FileHandle,
(HANDLE)TargetProcessHandle,
&TargetHandle,
FILE_GENERIC_READ,
FALSE,
0);
if (OK)
{
DuplicatedHandles.push_back((void*)TargetHandle);
Path8 = fmt::format("{}{}", HandlePrefix, reinterpret_cast<uint64_t>(TargetHandle));
UseFilePath = false;
}
}
#else // ZEN_PLATFORM_WINDOWS
ZEN_UNUSED(TargetProcessHandle);
ZEN_UNUSED(DuplicatedHandles);
// Not supported on Linux/Mac. Could potentially use pidfd_getfd() but that requires a fairly new Linux kernel/includes and to
// deal with access rights etc.
#endif // ZEN_PLATFORM_WINDOWS
if (UseFilePath)
{
ExtendablePathBuilder<256> LocalRefFile;
std::error_code Ec;
std::filesystem::path FilePath = PathFromHandle(Ref.FileHandle, Ec);
if (Ec)
{
ZEN_WARN("Failed to get path for file handle {} in IsLocalRef check, reason '{}'", Ref.FileHandle, Ec.message());
return false;
}
LocalRefFile.Append(std::filesystem::absolute(FilePath));
Path8 = LocalRefFile.ToUtf8();
}
FileNameMap.insert_or_assign(Ref.FileHandle, Path8);
}
LocalRef.AbsolutePathLength = gsl::narrow<uint16_t>(Path8.size());
LocalRef.PayloadByteOffset = Ref.FileChunkOffset;
LocalRef.PayloadByteSize = Ref.FileChunkSize;
return true;
};
IoBufferVec_t
FormatPackageMessageInternal(const CbPackage& Data, FormatFlags Flags, void* TargetProcessHandle)
{
ZEN_TRACE_CPU("FormatPackageMessage");
std::vector<void*> DuplicatedHandles;
#if ZEN_PLATFORM_WINDOWS
auto _ = MakeGuard([&DuplicatedHandles, &TargetProcessHandle]() {
if (TargetProcessHandle == nullptr)
{
return;
}
for (void* DuplicatedHandle : DuplicatedHandles)
{
HANDLE ClosingHandle;
if (::DuplicateHandle((HANDLE)TargetProcessHandle,
(HANDLE)DuplicatedHandle,
GetCurrentProcess(),
&ClosingHandle,
0,
FALSE,
DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS) == TRUE)
{
::CloseHandle(ClosingHandle);
}
}
});
#endif // ZEN_PLATFORM_WINDOWS
const std::span<const CbAttachment>& Attachments = Data.GetAttachments();
IoBufferVec_t ResponseBuffers;
ResponseBuffers.reserve(2 + Attachments.size()); // TODO: may want to use an additional fudge factor here to avoid growing since each
// attachment is likely to consist of several buffers
IoBuffer AttachmentMetadataBuffer = IoBuffer{sizeof(CbPackageHeader) + sizeof(CbAttachmentEntry) * (Attachments.size() + /* root */ 1)};
MutableMemoryView HeaderView = AttachmentMetadataBuffer.GetMutableView();
// Fixed size header
CbPackageHeader* Hdr = (CbPackageHeader*)HeaderView.GetData();
*Hdr = {.HeaderMagic = kCbPkgMagic, .AttachmentCount = gsl::narrow<uint32_t>(Attachments.size())};
HeaderView.MidInline(sizeof(CbPackageHeader));
// Attachment metadata array
CbAttachmentEntry* AttachmentInfo = reinterpret_cast<CbAttachmentEntry*>(HeaderView.GetData());
ResponseBuffers.emplace_back(std::move(AttachmentMetadataBuffer)); // Attachment metadata
// Root object
IoBuffer RootIoBuffer = Data.GetObject().GetBuffer().AsIoBuffer();
ZEN_ASSERT(RootIoBuffer.GetSize() > 0);
*AttachmentInfo++ = {.PayloadSize = RootIoBuffer.Size(), .Flags = CbAttachmentEntry::kIsObject, .AttachmentHash = Data.GetObjectHash()};
ResponseBuffers.emplace_back(std::move(RootIoBuffer)); // Root object
// Attachment payloads
tsl::robin_map<void*, std::string> FileNameMap;
for (const CbAttachment& Attachment : Attachments)
{
if (Attachment.IsNull())
{
ZEN_NOT_IMPLEMENTED("Null attachments are not supported");
}
else if (const CompressedBuffer& AttachmentBuffer = Attachment.AsCompressedBinary())
{
const CompositeBuffer& Compressed = AttachmentBuffer.GetCompressed();
IoHash AttachmentHash = Attachment.GetHash();
// If the data is either not backed by a file, or there are multiple
// fragments then we cannot marshal it by local reference. We might
// want/need to extend this in the future to allow multiple chunk
// segments to be marshaled at once
bool MarshalByLocalRef = EnumHasAllFlags(Flags, FormatFlags::kAllowLocalReferences) && (Compressed.GetSegments().size() == 1);
bool DenyPartialLocalReferences = EnumHasAllFlags(Flags, FormatFlags::kDenyPartialLocalReferences);
CbAttachmentReferenceHeader LocalRef;
std::string Path8;
if (MarshalByLocalRef)
{
MarshalByLocalRef = IsLocalRef(FileNameMap,
DuplicatedHandles,
Compressed,
DenyPartialLocalReferences,
TargetProcessHandle,
LocalRef,
Path8);
}
if (MarshalByLocalRef)
{
const bool IsCompressed = true;
bool IsHandle = false;
#if ZEN_PLATFORM_WINDOWS
IsHandle = Path8.starts_with(HandlePrefix);
#endif
MarshalLocal(AttachmentInfo, Path8, LocalRef, AttachmentHash, IsCompressed, ResponseBuffers);
ZEN_DEBUG("Marshalled '{}' as file {} of {} bytes", Path8, IsHandle ? "handle" : "path", Compressed.GetSize());
}
else
{
*AttachmentInfo++ = {.PayloadSize = AttachmentBuffer.GetCompressedSize(),
.Flags = CbAttachmentEntry::kIsCompressed,
.AttachmentHash = AttachmentHash};
std::span<const SharedBuffer> Segments = Compressed.GetSegments();
ResponseBuffers.reserve(ResponseBuffers.size() + Segments.size() - 1);
for (const SharedBuffer& Segment : Segments)
{
ZEN_ASSERT(Segment.GetSize() > 0);
ResponseBuffers.emplace_back(Segment.AsIoBuffer());
}
}
}
else if (CbObject AttachmentObject = Attachment.AsObject())
{
IoBuffer ObjIoBuffer = AttachmentObject.GetBuffer().AsIoBuffer();
ZEN_ASSERT(ObjIoBuffer.GetSize() > 0);
*AttachmentInfo++ = {.PayloadSize = ObjIoBuffer.Size(),
.Flags = CbAttachmentEntry::kIsObject,
.AttachmentHash = Attachment.GetHash()};
ResponseBuffers.emplace_back(std::move(ObjIoBuffer));
}
else if (const CompositeBuffer& AttachmentBinary = Attachment.AsCompositeBinary())
{
IoHash AttachmentHash = Attachment.GetHash();
bool MarshalByLocalRef =
EnumHasAllFlags(Flags, FormatFlags::kAllowLocalReferences) && (AttachmentBinary.GetSegments().size() == 1);
bool DenyPartialLocalReferences = EnumHasAllFlags(Flags, FormatFlags::kDenyPartialLocalReferences);
CbAttachmentReferenceHeader LocalRef;
std::string Path8;
if (MarshalByLocalRef)
{
MarshalByLocalRef = IsLocalRef(FileNameMap,
DuplicatedHandles,
AttachmentBinary,
DenyPartialLocalReferences,
TargetProcessHandle,
LocalRef,
Path8);
}
if (MarshalByLocalRef)
{
const bool IsCompressed = false;
bool IsHandle = false;
#if ZEN_PLATFORM_WINDOWS
IsHandle = Path8.starts_with(HandlePrefix);
#endif
MarshalLocal(AttachmentInfo, Path8, LocalRef, AttachmentHash, IsCompressed, ResponseBuffers);
ZEN_DEBUG("Marshalled '{}' as file {} of {} bytes", Path8, IsHandle ? "handle" : "path", AttachmentBinary.GetSize());
}
else
{
*AttachmentInfo++ = {.PayloadSize = AttachmentBinary.GetSize(), .Flags = 0, .AttachmentHash = Attachment.GetHash()};
std::span<const SharedBuffer> Segments = AttachmentBinary.GetSegments();
ResponseBuffers.reserve(ResponseBuffers.size() + Segments.size() - 1);
for (const SharedBuffer& Segment : Segments)
{
ZEN_ASSERT(Segment.GetSize() > 0);
ResponseBuffers.emplace_back(Segment.AsIoBuffer());
}
}
}
else
{
ZEN_NOT_IMPLEMENTED("Unknown attachment kind");
}
}
FileNameMap.clear();
#if ZEN_PLATFORM_WINDOWS
DuplicatedHandles.clear();
#endif // ZEN_PLATFORM_WINDOWS
return ResponseBuffers;
}
bool
IsPackageMessage(IoBuffer Payload)
{
if (Payload.GetSize() < sizeof(CbPackageHeader))
{
return false;
}
BinaryReader Reader(Payload);
const CbPackageHeader* Hdr = reinterpret_cast<const CbPackageHeader*>(Reader.GetView(sizeof(CbPackageHeader)).GetData());
if (Hdr->HeaderMagic != kCbPkgMagic)
{
return false;
}
return true;
}
CbPackage
ParsePackageMessage(IoBuffer Payload, std::function<IoBuffer(const IoHash&, uint64_t)> CreateBuffer)
{
ZEN_TRACE_CPU("ParsePackageMessage");
if (Payload.GetSize() < sizeof(CbPackageHeader))
{
throw std::invalid_argument(fmt::format("invalid CbPackage, missing complete header (size {})", Payload.GetSize()));
}
BinaryReader Reader(Payload);
const CbPackageHeader* Hdr = reinterpret_cast<const CbPackageHeader*>(Reader.GetView(sizeof(CbPackageHeader)).GetData());
if (Hdr->HeaderMagic != kCbPkgMagic)
{
throw std::invalid_argument(
fmt::format("invalid CbPackage header magic, expected {0:x}, got {1:x}", static_cast<uint32_t>(kCbPkgMagic), Hdr->HeaderMagic));
}
Reader.Skip(sizeof(CbPackageHeader));
const uint32_t ChunkCount = Hdr->AttachmentCount + 1;
if (Reader.Remaining() < sizeof(CbAttachmentEntry) * ChunkCount)
{
throw std::invalid_argument(fmt::format("invalid CbPackage, missing attachment entry data (need {} bytes, have {} bytes)",
sizeof(CbAttachmentEntry) * ChunkCount,
Reader.Remaining()));
}
const CbAttachmentEntry* AttachmentEntries =
reinterpret_cast<const CbAttachmentEntry*>(Reader.GetView(sizeof(CbAttachmentEntry) * ChunkCount).GetData());
Reader.Skip(sizeof(CbAttachmentEntry) * ChunkCount);
CbPackage Package;
std::vector<CbAttachment> Attachments;
Attachments.reserve(ChunkCount); // Guessing here...
tsl::robin_map<std::string, IoBuffer> PartialFileBuffers;
std::vector<std::pair<uint32_t, std::string>> MalformedAttachments;
for (uint32_t i = 0; i < ChunkCount; ++i)
{
const CbAttachmentEntry& Entry = AttachmentEntries[i];
const uint64_t AttachmentSize = Entry.PayloadSize;
if (Reader.Remaining() < AttachmentSize)
{
throw std::invalid_argument(fmt::format("invalid CbPackage, missing attachment data (need {} bytes, have {} bytes)",
AttachmentSize,
Reader.Remaining()));
}
const IoBuffer AttachmentBuffer(Payload, Reader.CurrentOffset(), AttachmentSize);
Reader.Skip(AttachmentSize);
if (Entry.Flags & CbAttachmentEntry::kIsLocalRef)
{
// Marshal local reference - a "pointer" to the chunk backing file
ZEN_ASSERT(AttachmentBuffer.Size() >= sizeof(CbAttachmentReferenceHeader));
const CbAttachmentReferenceHeader* AttachRefHdr = AttachmentBuffer.Data<CbAttachmentReferenceHeader>();
const char* PathPointer = reinterpret_cast<const char*>(AttachRefHdr + 1);
ZEN_ASSERT(AttachmentBuffer.Size() >= (sizeof(CbAttachmentReferenceHeader) + AttachRefHdr->AbsolutePathLength));
std::string_view PathView(PathPointer, AttachRefHdr->AbsolutePathLength);
IoBuffer FullFileBuffer;
std::filesystem::path Path(Utf8ToWide(PathView));
if (auto It = PartialFileBuffers.find(Path.string()); It != PartialFileBuffers.end())
{
FullFileBuffer = It->second;
}
else
{
if (PathView.starts_with(HandlePrefix))
{
#if ZEN_PLATFORM_WINDOWS
std::string_view HandleString(PathView.substr(HandlePrefix.length()));
std::optional<uint64_t> HandleNumber(ParseInt<uint64_t>(HandleString));
if (HandleNumber.has_value())
{
HANDLE FileHandle = HANDLE(HandleNumber.value());
ULARGE_INTEGER liFileSize;
liFileSize.LowPart = ::GetFileSize(FileHandle, &liFileSize.HighPart);
if (liFileSize.LowPart != INVALID_FILE_SIZE)
{
FullFileBuffer =
IoBuffer(IoBuffer::File, (void*)FileHandle, 0, uint64_t(liFileSize.QuadPart), /*IsWholeFile*/ true);
PartialFileBuffers.insert_or_assign(Path.string(), FullFileBuffer);
}
}
#else // ZEN_PLATFORM_WINDOWS
// Not supported on Linux/Mac. Could potentially use pidfd_getfd() but that requires a fairly new Linux kernel/includes
// and to deal with acceess rights etc.
ZEN_ASSERT(false);
#endif // ZEN_PLATFORM_WINDOWS
}
else
{
FullFileBuffer = PartialFileBuffers.insert_or_assign(Path.string(), IoBufferBuilder::MakeFromFile(Path)).first->second;
}
}
if (FullFileBuffer)
{
IoBuffer ChunkReference = AttachRefHdr->PayloadByteOffset == 0 && AttachRefHdr->PayloadByteSize == FullFileBuffer.GetSize()
? FullFileBuffer
: IoBuffer(FullFileBuffer, AttachRefHdr->PayloadByteOffset, AttachRefHdr->PayloadByteSize);
CompressedBuffer CompBuf(CompressedBuffer::FromCompressedNoValidate(std::move(ChunkReference)));
if (CompBuf)
{
Attachments.emplace_back(CbAttachment(std::move(CompBuf), Entry.AttachmentHash));
}
else
{
MalformedAttachments.push_back(std::make_pair(i,
fmt::format("Invalid format in '{}' (offset {}, size {}) for {}",
Path,
AttachRefHdr->PayloadByteOffset,
AttachRefHdr->PayloadByteSize,
Entry.AttachmentHash)));
}
}
else
{
MalformedAttachments.push_back(std::make_pair(i,
fmt::format("Unable to resolve chunk at '{}' (offset {}, size {}) for {}",
Path,
AttachRefHdr->PayloadByteOffset,
AttachRefHdr->PayloadByteSize,
Entry.AttachmentHash)));
}
}
else if (Entry.Flags & CbAttachmentEntry::kIsCompressed)
{
if (Entry.Flags & CbAttachmentEntry::kIsObject)
{
CbObject AttachmentObject;
CompressedBuffer CompBuf(CompressedBuffer::FromCompressedNoValidate(IoBuffer(AttachmentBuffer)));
if (!CompBuf)
{
// First payload is always a compact binary object
MalformedAttachments.push_back(
std::make_pair(i,
fmt::format("Invalid format, expected compressed buffer for CbObject (size {}) for {}",
AttachmentBuffer.GetSize(),
Entry.AttachmentHash)));
}
else
{
CbValidateError ValidationError = CbValidateError::None;
AttachmentObject = ValidateAndReadCompactBinaryObject(std::move(CompBuf), ValidationError);
if (ValidationError != CbValidateError::None)
{
MalformedAttachments.push_back(std::make_pair(
i,
fmt::format("Invalid format, CbObject for {}. Reason '{}'", Entry.AttachmentHash, ToString(ValidationError))));
}
}
if (i == 0)
{
// First payload is always a compact binary object
Package.SetObject(AttachmentObject);
}
else
{
Attachments.emplace_back(CbAttachment(AttachmentObject, Entry.AttachmentHash));
}
}
else
{
CompressedBuffer CompBuf(CompressedBuffer::FromCompressedNoValidate(IoBuffer(AttachmentBuffer)));
if (CompBuf)
{
Attachments.emplace_back(CbAttachment(std::move(CompBuf), Entry.AttachmentHash));
}
else
{
MalformedAttachments.push_back(
std::make_pair(i,
fmt::format("Invalid format, expected compressed buffer for attachment (size {}) for {}",
AttachmentBuffer.GetSize(),
Entry.AttachmentHash)));
}
}
}
else /* not compressed */
{
if (Entry.Flags & CbAttachmentEntry::kIsObject)
{
CbValidateError ValidationError = CbValidateError::None;
CbObject AttachmentObject = ValidateAndReadCompactBinaryObject(std::move(AttachmentBuffer), ValidationError);
if (ValidationError != CbValidateError::None)
{
MalformedAttachments.push_back(std::make_pair(
i,
fmt::format("Invalid format, CbObject for {}. Reason '{}'", Entry.AttachmentHash, ToString(ValidationError))));
}
if (i == 0)
{
Package.SetObject(AttachmentObject);
}
else
{
Attachments.emplace_back(CbAttachment(AttachmentObject, Entry.AttachmentHash));
}
}
else if (AttachmentSize > 0)
{
// Make a copy of the buffer so the attachments don't reference the entire payload
IoBuffer AttachmentBufferCopy = CreateBuffer(Entry.AttachmentHash, AttachmentSize);
ZEN_ASSERT(AttachmentBufferCopy);
ZEN_ASSERT(AttachmentBufferCopy.Size() == AttachmentSize);
AttachmentBufferCopy.GetMutableView().CopyFrom(AttachmentBuffer.GetView());
Attachments.emplace_back(CbAttachment(SharedBuffer{AttachmentBufferCopy}, Entry.AttachmentHash));
}
else
{
MalformedAttachments.push_back(
std::make_pair(i, fmt::format("Invalid format, attachment of size zero detected for {}", Entry.AttachmentHash)));
}
}
}
PartialFileBuffers.clear();
Package.AddAttachments(Attachments);
using namespace std::literals;
if (!MalformedAttachments.empty())
{
ExtendableStringBuilder<1024> SB;
SB << (uint64_t)MalformedAttachments.size() << " malformed attachments in package message:\n";
for (const auto& It : MalformedAttachments)
{
SB << " #"sv << It.first << ": " << It.second << "\n";
}
ZEN_WARN("{}", SB.ToView());
throw std::invalid_argument(SB.ToString());
}
return Package;
}
bool
ParsePackageMessageWithLegacyFallback(const IoBuffer& Response, CbPackage& OutPackage)
{
if (IsPackageMessage(Response))
{
OutPackage = ParsePackageMessage(Response);
return true;
}
return OutPackage.TryLoad(Response);
}
CbPackageReader::CbPackageReader() : m_CreateBuffer([](const IoHash&, uint64_t Size) -> IoBuffer { return IoBuffer{Size}; })
{
}
CbPackageReader::~CbPackageReader()
{
}
void
CbPackageReader::SetPayloadBufferCreator(std::function<IoBuffer(const IoHash& Cid, uint64_t Size)> CreateBuffer)
{
m_CreateBuffer = CreateBuffer;
}
uint64_t
CbPackageReader::ProcessPackageHeaderData(const void* Data, uint64_t DataBytes)
{
ZEN_ASSERT(m_CurrentState != State::kReadingBuffers);
switch (m_CurrentState)
{
case State::kInitialState:
ZEN_ASSERT(Data == nullptr);
m_CurrentState = State::kReadingHeader;
return sizeof m_PackageHeader;
case State::kReadingHeader:
ZEN_ASSERT(DataBytes == sizeof m_PackageHeader);
memcpy(&m_PackageHeader, Data, sizeof m_PackageHeader);
ZEN_ASSERT(m_PackageHeader.HeaderMagic == kCbPkgMagic);
m_CurrentState = State::kReadingAttachmentEntries;
m_AttachmentEntries.resize(m_PackageHeader.AttachmentCount + 1);
return (m_PackageHeader.AttachmentCount + 1) * sizeof(CbAttachmentEntry);
case State::kReadingAttachmentEntries:
ZEN_ASSERT(DataBytes == ((m_PackageHeader.AttachmentCount + 1) * sizeof(CbAttachmentEntry)));
memcpy(m_AttachmentEntries.data(), Data, DataBytes);
for (CbAttachmentEntry& Entry : m_AttachmentEntries)
{
// This preallocates memory for payloads but note that for the local references
// the caller will need to handle the payload differently (i.e it's a
// CbAttachmentReferenceHeader not the actual payload)
m_PayloadBuffers.emplace_back(IoBuffer{Entry.PayloadSize});
}
m_CurrentState = State::kReadingBuffers;
return 0;
default:
ZEN_ASSERT(false);
return 0;
}
}
IoBuffer
CbPackageReader::MarshalLocalChunkReference(IoBuffer AttachmentBuffer)
{
// Marshal local reference - a "pointer" to the chunk backing file
ZEN_ASSERT(AttachmentBuffer.Size() >= sizeof(CbAttachmentReferenceHeader));
const CbAttachmentReferenceHeader* AttachRefHdr = AttachmentBuffer.Data<CbAttachmentReferenceHeader>();
const char8_t* PathPointer = reinterpret_cast<const char8_t*>(AttachRefHdr + 1);
ZEN_ASSERT(AttachmentBuffer.Size() >= (sizeof(CbAttachmentReferenceHeader) + AttachRefHdr->AbsolutePathLength));
std::u8string_view PathView{PathPointer, AttachRefHdr->AbsolutePathLength};
std::filesystem::path Path{PathView};
IoBuffer ChunkReference = IoBufferBuilder::MakeFromFile(Path, AttachRefHdr->PayloadByteOffset, AttachRefHdr->PayloadByteSize);
if (!ChunkReference)
{
// Unable to open chunk reference
throw std::runtime_error(fmt::format("unable to resolve local reference to '{}' (offset {}, size {})",
PathToUtf8(Path),
AttachRefHdr->PayloadByteOffset,
AttachRefHdr->PayloadByteSize));
}
return ChunkReference;
};
void
CbPackageReader::Finalize()
{
if (m_AttachmentEntries.empty())
{
return;
}
m_Attachments.reserve(m_AttachmentEntries.size() - 1);
int CurrentAttachmentIndex = 0;
for (CbAttachmentEntry& Entry : m_AttachmentEntries)
{
IoBuffer AttachmentBuffer = m_PayloadBuffers[CurrentAttachmentIndex];
if (CurrentAttachmentIndex == 0)
{
// Root object
if (Entry.Flags & CbAttachmentEntry::kIsObject)
{
if (Entry.Flags & CbAttachmentEntry::kIsLocalRef)
{
CbValidateError ValidateError = CbValidateError::None;
m_RootObject = ValidateAndReadCompactBinaryObject(MarshalLocalChunkReference(AttachmentBuffer), ValidateError);
if (ValidateError != CbValidateError::None)
{
throw std::runtime_error(fmt::format("Root object format is invalid, reason: '{}'", ToString(ValidateError)));
}
}
else if (Entry.Flags & CbAttachmentEntry::kIsCompressed)
{
IoHash RawHash;
uint64_t RawSize;
CompressedBuffer Compressed = CompressedBuffer::FromCompressed(SharedBuffer(AttachmentBuffer), RawHash, RawSize);
if (RawHash == Entry.AttachmentHash)
{
CbValidateError ValidateError = CbValidateError::None;
m_RootObject = ValidateAndReadCompactBinaryObject(std::move(Compressed), ValidateError);
if (ValidateError != CbValidateError::None)
{
throw std::runtime_error(fmt::format("Root object format is invalid, reason: '{}'", ToString(ValidateError)));
}
}
}
else
{
CbValidateError ValidateError = CbValidateError::None;
m_RootObject = ValidateAndReadCompactBinaryObject(std::move(AttachmentBuffer), ValidateError);
if (ValidateError != CbValidateError::None)
{
throw std::runtime_error(fmt::format("Root object format is invalid, reason: '{}'", ToString(ValidateError)));
}
}
}
else
{
throw std::runtime_error("missing or invalid root object");
}
}
else if (Entry.Flags & CbAttachmentEntry::kIsLocalRef)
{
IoBuffer ChunkReference = MarshalLocalChunkReference(AttachmentBuffer);
if (Entry.Flags & CbAttachmentEntry::kIsCompressed)
{
IoHash RawHash;
uint64_t RawSize;
CompressedBuffer Compressed = CompressedBuffer::FromCompressed(SharedBuffer(ChunkReference), RawHash, RawSize);
if (RawHash == Entry.AttachmentHash)
{
m_Attachments.emplace_back(CbAttachment(Compressed, Entry.AttachmentHash));
}
}
else
{
CompressedBuffer Compressed =
CompressedBuffer::Compress(SharedBuffer(ChunkReference), OodleCompressor::NotSet, OodleCompressionLevel::None);
m_Attachments.emplace_back(CbAttachment(std::move(Compressed), Compressed.DecodeRawHash()));
}
}
++CurrentAttachmentIndex;
}
}
/**
______________________ _____________________________
\__ ___/\_ _____// _____/\__ ___/ _____/
| | | __)_ \_____ \ | | \_____ \
| | | \/ \ | | / \
|____| /_______ /_______ / |____| /_______ /
\/ \/ \/
*/
#if ZEN_WITH_TESTS
TEST_CASE("CbPackage.Serialization")
{
// Make a test package
CbAttachment Attach1{SharedBuffer::MakeView(MakeMemoryView("abcd"))};
CbAttachment Attach2{SharedBuffer::MakeView(MakeMemoryView("efgh"))};
CbObjectWriter Cbo;
Cbo.AddAttachment("abcd", Attach1);
Cbo.AddAttachment("efgh", Attach2);
CbPackage Pkg;
Pkg.AddAttachment(Attach1);
Pkg.AddAttachment(Attach2);
Pkg.SetObject(Cbo.Save());
SharedBuffer Buffer = FormatPackageMessageBuffer(Pkg).Flatten();
const uint8_t* CursorPtr = reinterpret_cast<const uint8_t*>(Buffer.GetData());
uint64_t RemainingBytes = Buffer.GetSize();
auto ConsumeBytes = [&](uint64_t ByteCount) {
ZEN_ASSERT(ByteCount <= RemainingBytes);
void* ReturnPtr = (void*)CursorPtr;
CursorPtr += ByteCount;
RemainingBytes -= ByteCount;
return ReturnPtr;
};
auto CopyBytes = [&](void* TargetBuffer, uint64_t ByteCount) {
ZEN_ASSERT(ByteCount <= RemainingBytes);
memcpy(TargetBuffer, CursorPtr, ByteCount);
CursorPtr += ByteCount;
RemainingBytes -= ByteCount;
};
CbPackageReader Reader;
uint64_t InitialRead = Reader.ProcessPackageHeaderData(nullptr, 0);
uint64_t NextBytes = Reader.ProcessPackageHeaderData(ConsumeBytes(InitialRead), InitialRead);
NextBytes = Reader.ProcessPackageHeaderData(ConsumeBytes(NextBytes), NextBytes);
auto Buffers = Reader.GetPayloadBuffers();
for (auto& PayloadBuffer : Buffers)
{
CopyBytes(PayloadBuffer.MutableData(), PayloadBuffer.GetSize());
}
Reader.Finalize();
}
TEST_CASE("CbPackage.EmptyObject")
{
CbPackage Pkg;
Pkg.SetObject({});
std::vector<IoBuffer> Result = FormatPackageMessage(Pkg, nullptr);
}
TEST_CASE("CbPackage.LocalRef")
{
ScopedTemporaryDirectory TempDir;
auto Path1 = TempDir.Path() / "abcd";
auto Path2 = TempDir.Path() / "efgh";
{
IoBuffer Buffer1 = IoBufferBuilder::MakeCloneFromMemory(MakeMemoryView("abcd"));
IoBuffer Buffer2 = IoBufferBuilder::MakeCloneFromMemory(MakeMemoryView("efgh"));
WriteFile(Path1, Buffer1);
WriteFile(Path2, Buffer2);
}
// Make a test package
IoBuffer FileBuffer1 = IoBufferBuilder::MakeFromFile(Path1);
IoBuffer FileBuffer2 = IoBufferBuilder::MakeFromFile(Path2);
CbAttachment Attach1{SharedBuffer(FileBuffer1)};
CbAttachment Attach2{SharedBuffer(FileBuffer2)};
CbObjectWriter Cbo;
Cbo.AddAttachment("abcd", Attach1);
Cbo.AddAttachment("efgh", Attach2);
CbPackage Pkg;
Pkg.AddAttachment(Attach1);
Pkg.AddAttachment(Attach2);
Pkg.SetObject(Cbo.Save());
SharedBuffer Buffer = FormatPackageMessageBuffer(Pkg, FormatFlags::kAllowLocalReferences).Flatten();
const uint8_t* CursorPtr = reinterpret_cast<const uint8_t*>(Buffer.GetData());
uint64_t RemainingBytes = Buffer.GetSize();
auto ConsumeBytes = [&](uint64_t ByteCount) {
ZEN_ASSERT(ByteCount <= RemainingBytes);
void* ReturnPtr = (void*)CursorPtr;
CursorPtr += ByteCount;
RemainingBytes -= ByteCount;
return ReturnPtr;
};
auto CopyBytes = [&](void* TargetBuffer, uint64_t ByteCount) {
ZEN_ASSERT(ByteCount <= RemainingBytes);
memcpy(TargetBuffer, CursorPtr, ByteCount);
CursorPtr += ByteCount;
RemainingBytes -= ByteCount;
};
CbPackageReader Reader;
uint64_t InitialRead = Reader.ProcessPackageHeaderData(nullptr, 0);
uint64_t NextBytes = Reader.ProcessPackageHeaderData(ConsumeBytes(InitialRead), InitialRead);
NextBytes = Reader.ProcessPackageHeaderData(ConsumeBytes(NextBytes), NextBytes);
auto Buffers = Reader.GetPayloadBuffers();
for (auto& PayloadBuffer : Buffers)
{
CopyBytes(PayloadBuffer.MutableData(), PayloadBuffer.GetSize());
}
Reader.Finalize();
}
void
forcelink_packageformat()
{
}
#endif
} // namespace zen
|