/
lib.rs
2193 lines (1972 loc) · 80.5 KB
/
lib.rs
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
use std::collections::HashMap;
use std::convert::TryFrom;
use std::io;
use std::io::{Read, Seek, SeekFrom, Write};
#[macro_use]
extern crate bitflags;
use bincode::Options;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use layers::traits::InnerReaderTrait;
use serde::{Deserialize, Serialize};
pub mod layers;
use crate::layers::compress::{
CompressionLayerFailSafeReader, CompressionLayerReader, CompressionLayerWriter,
};
use crate::layers::encrypt::{
EncryptionLayerFailSafeReader, EncryptionLayerReader, EncryptionLayerWriter,
};
use crate::layers::position::PositionLayerWriter;
use crate::layers::raw::{RawLayerFailSafeReader, RawLayerReader, RawLayerWriter};
use crate::layers::traits::{
InnerWriterTrait, InnerWriterType, LayerFailSafeReader, LayerReader, LayerWriter,
};
pub mod errors;
use crate::errors::{Error, FailSafeReadError};
pub mod config;
use crate::config::{ArchivePersistentConfig, ArchiveReaderConfig, ArchiveWriterConfig};
#[doc(hidden)]
pub mod crypto;
use crate::crypto::hash::{HashWrapperReader, Sha256Hash};
use sha2::{Digest, Sha256};
use x25519_dalek::PublicKey;
pub mod helpers;
// -------- Constants --------
const MLA_MAGIC: &[u8; 3] = b"MLA";
const MLA_FORMAT_VERSION: u32 = 1;
/// Maximum number of UTF-8 characters supported in each file's "name" (which is free
/// to be used as a filename, an absolute path, or... ?). 32KiB was chosen because it
/// supports any path a Windows NT, Linux, FreeBSD, OpenBSD, or NetBSD kernel supports.
const FILENAME_MAX_SIZE: u64 = 65536;
/// Maximum allowed object size (in bytes) to deserialize in-memory, to avoid DoS on
/// malformed files
pub(crate) const BINCODE_MAX_DESERIALIZE: u64 = 512 * 1024 * 1024;
bitflags! {
/// Available layers. Order is relevant:
/// ```ascii-art
/// [File to blocks decomposition]
/// [Compression (COMPRESS)]
/// [Encryption (ENCRYPT)]
/// [Raw File I/O]
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Layers: u8 {
const ENCRYPT = 0b0000_0001;
const COMPRESS = 0b0000_0010;
/// Recommended layering
const DEFAULT = Self::ENCRYPT.bits() | Self::COMPRESS.bits();
/// No additional layer (ie, for debugging purpose)
const DEBUG = 0;
const EMPTY = 0;
}
}
impl std::default::Default for Layers {
fn default() -> Self {
Layers::DEFAULT
}
}
pub type ArchiveFileID = u64;
// -------- MLA Format Header --------
pub struct ArchiveHeader {
pub format_version: u32,
pub config: ArchivePersistentConfig,
}
impl ArchiveHeader {
pub fn from<T: Read>(src: &mut T) -> Result<Self, Error> {
let mut buf = vec![00u8; MLA_MAGIC.len()];
src.read_exact(buf.as_mut_slice())?;
if buf != MLA_MAGIC {
return Err(Error::WrongMagic);
}
let format_version = src.read_u32::<LittleEndian>()?;
if format_version != MLA_FORMAT_VERSION {
return Err(Error::UnsupportedVersion);
}
let config: ArchivePersistentConfig = match bincode::options()
.with_limit(BINCODE_MAX_DESERIALIZE)
.with_fixint_encoding()
.deserialize_from(src)
{
Ok(config) => config,
_ => {
return Err(Error::DeserializationError);
}
};
Ok(ArchiveHeader {
format_version,
config,
})
}
fn dump<T: Write>(&self, dest: &mut T) -> Result<(), Error> {
dest.write_all(MLA_MAGIC)?;
dest.write_u32::<LittleEndian>(self.format_version)?;
if bincode::options()
.with_limit(BINCODE_MAX_DESERIALIZE)
.with_fixint_encoding()
.serialize_into(dest, &self.config)
.is_err()
{
return Err(Error::SerializationError);
}
Ok(())
}
}
// -------- MLA Format Footer --------
pub struct ArchiveFooter {
/// Filename -> Corresponding FileInfo
pub files_info: HashMap<String, FileInfo>,
}
impl ArchiveFooter {
/// Footer:
/// ```ascii-art
/// [files_info][files_info length]
/// ```
/// Performs zero-copy serialization of a footer
fn serialize_into<W: Write>(
mut dest: W,
files_info: &HashMap<String, ArchiveFileID>,
ids_info: &HashMap<ArchiveFileID, FileInfo>,
) -> Result<(), Error> {
let mut serialization_len = 0;
// Combine `files_info` and `ids_info` to ArchiveFooter.files_info,
// avoiding copies (only references)
let mut tmp: HashMap<&String, &FileInfo> = HashMap::new();
for (k, i) in files_info {
let v = ids_info.get(i).ok_or_else(|| {
Error::WrongWriterState(
"[ArchiveFooter seriliaze] Unable to find the ID".to_string(),
)
})?;
tmp.insert(k, v);
}
if bincode::options()
.with_limit(BINCODE_MAX_DESERIALIZE)
.with_fixint_encoding()
.serialize_into(&mut dest, &tmp)
.is_err()
{
return Err(Error::SerializationError);
};
serialization_len += match bincode::serialized_size(&tmp) {
Ok(size) => size,
Err(_) => {
return Err(Error::SerializationError);
}
};
// footer length
dest.write_u32::<LittleEndian>(serialization_len as u32)?;
Ok(())
}
/// Parses and instantiates a footer from serialized data
pub fn deserialize_from<R: Read + Seek>(mut src: R) -> Result<ArchiveFooter, Error> {
// Read the footer length
let pos = src.seek(SeekFrom::End(-4))?;
let len = src.read_u32::<LittleEndian>()? as u64;
// Prepare for deserialization
src.seek(SeekFrom::Start(pos - len))?;
// Read files_info
let files_info: HashMap<String, FileInfo> = match bincode::options()
.with_limit(BINCODE_MAX_DESERIALIZE)
.with_fixint_encoding()
.deserialize_from(&mut src.take(len))
{
Ok(finfo) => finfo,
_ => {
return Err(Error::DeserializationError);
}
};
Ok(ArchiveFooter { files_info })
}
}
// -------- Writer --------
/// Tags used in each ArchiveFileBlock to indicate the type of block that follows
#[derive(Debug)]
#[repr(u8)]
enum ArchiveFileBlockType {
FileStart = 0x00,
FileContent = 0x01,
EndOfArchiveData = 0xFE,
EndOfFile = 0xFF,
}
impl TryFrom<u8> for ArchiveFileBlockType {
type Error = Error;
fn try_from(value: u8) -> Result<Self, Self::Error> {
if value == ArchiveFileBlockType::FileStart as u8 {
Ok(ArchiveFileBlockType::FileStart)
} else if value == ArchiveFileBlockType::FileContent as u8 {
Ok(ArchiveFileBlockType::FileContent)
} else if value == ArchiveFileBlockType::EndOfFile as u8 {
Ok(ArchiveFileBlockType::EndOfFile)
} else if value == ArchiveFileBlockType::EndOfArchiveData as u8 {
Ok(ArchiveFileBlockType::EndOfArchiveData)
} else {
Err(Error::WrongBlockSubFileType)
}
}
}
#[derive(Debug)]
pub enum ArchiveFileBlock<T: Read> {
/// Usually, a file is made of:
/// [FileStart][FileContent]...[FileContent][EndOfFile]
/// The `id` is used to keep track internally of which file a `ArchiveFileBlock` belongs to
///
/// Start of a file
FileStart { filename: String, id: ArchiveFileID },
/// File content.
/// (length, data) is used instead of a Vec to avoid having the whole data
/// in memory. On parsing, the data can be set to None. It indicates to the
/// caller that the data is just next to it
/// TODO: use the same trick than ArchiveReader to avoid the Option
FileContent {
length: u64,
data: Option<T>,
id: ArchiveFileID,
},
/// End of file (last block) - contains the SHA256 of the whole file
EndOfFile { id: ArchiveFileID, hash: Sha256Hash },
/// End of archive data (no more files after that)
EndOfArchiveData,
}
impl<T> ArchiveFileBlock<T>
where
T: Read,
{
fn dump<U: Write>(&mut self, dest: &mut U) -> Result<(), Error> {
match self {
ArchiveFileBlock::FileStart { filename, id } => {
dest.write_u8(ArchiveFileBlockType::FileStart as u8)?;
dest.write_u64::<LittleEndian>(*id)?;
let bytes = filename.as_bytes();
let length = bytes.len() as u64;
if length > FILENAME_MAX_SIZE {
return Err(Error::FilenameTooLong);
}
dest.write_u64::<LittleEndian>(length)?;
dest.write_all(bytes)?;
Ok(())
}
ArchiveFileBlock::FileContent { length, data, id } => {
dest.write_u8(ArchiveFileBlockType::FileContent as u8)?;
dest.write_u64::<LittleEndian>(*id)?;
dest.write_u64::<LittleEndian>(*length)?;
match data {
None => {
return Err(Error::AssertionError(String::from(
"Data missing in file content",
)));
}
Some(content) => {
// TODO check length
io::copy(&mut content.take(*length), dest)?;
}
}
Ok(())
}
ArchiveFileBlock::EndOfFile { id, hash } => {
dest.write_u8(ArchiveFileBlockType::EndOfFile as u8)?;
dest.write_u64::<LittleEndian>(*id)?;
dest.write_all(hash)?;
Ok(())
}
ArchiveFileBlock::EndOfArchiveData => {
dest.write_u8(ArchiveFileBlockType::EndOfArchiveData as u8)?;
Ok(())
}
}
}
fn from(src: &mut T) -> Result<Self, Error> {
let byte = src.read_u8()?;
match ArchiveFileBlockType::try_from(byte)? {
ArchiveFileBlockType::FileStart => {
let id = src.read_u64::<LittleEndian>()?;
let length = src.read_u64::<LittleEndian>()?;
if length > FILENAME_MAX_SIZE {
return Err(Error::FilenameTooLong);
}
let mut filename = vec![0u8; length as usize];
src.read_exact(&mut filename)?;
Ok(ArchiveFileBlock::FileStart {
id,
filename: String::from_utf8(filename)?,
})
}
ArchiveFileBlockType::FileContent => {
let id = src.read_u64::<LittleEndian>()?;
let length = src.read_u64::<LittleEndian>()?;
// /!\ WARNING: to avoid loading this entire subfileblock's contents
// in-memory, the `data` reader is None; the `src` now starts at the
// beginning of the data
Ok(ArchiveFileBlock::FileContent {
length,
data: None,
id,
})
}
ArchiveFileBlockType::EndOfFile => {
let id = src.read_u64::<LittleEndian>()?;
let mut hash = Sha256Hash::default();
src.read_exact(&mut hash)?;
Ok(ArchiveFileBlock::EndOfFile { id, hash })
}
ArchiveFileBlockType::EndOfArchiveData => Ok(ArchiveFileBlock::EndOfArchiveData),
}
}
}
#[derive(Debug, Clone)]
pub enum ArchiveWriterState {
/// Initialized, with files opened
OpenedFiles {
ids: Vec<ArchiveFileID>,
hashes: HashMap<ArchiveFileID, Sha256>,
},
/// File finalized, no more change allowed
Finalized,
}
impl ArchiveWriterState {
/// Wrap a `impl Read` with hash updating, corresponding to the file identified by `id`
fn wrap_with_hash<R: Read>(
&mut self,
id: ArchiveFileID,
src: R,
) -> Result<HashWrapperReader<R>, Error> {
let hash = match self {
ArchiveWriterState::OpenedFiles { hashes, .. } => match hashes.get_mut(&id) {
Some(hash) => hash,
None => {
return Err(Error::WrongWriterState(
"[wrap_with_hash] Unable to find the ID".to_string(),
))
}
},
_ => {
return Err(Error::WrongWriterState(
"[wrap_with_hash] Wrong state".to_string(),
))
}
};
Ok(HashWrapperReader::new(src, hash))
}
}
/// Used to check whether the current state is the one expected
/// ```text
/// check_state!(self.state, ArchiveWriterState::XXX)
/// ```
macro_rules! check_state {
( $x:expr, $y:ident ) => {{
match $x {
ArchiveWriterState::$y { .. } => (),
_ => {
return Err(Error::WrongArchiveWriterState {
current_state: format!("{:?}", $x).to_string(),
expected_state: format! {"{}", "ArchiveWriterState::$y"}.to_string(),
});
}
}
}};
}
/// Used to check whether the current state is `OpenedFiles`, with the expected file opened
/// ```text
/// check_state_file_opened!(self.state, file_id)
/// ```
macro_rules! check_state_file_opened {
( $x:expr, $y:expr ) => {{
match $x {
ArchiveWriterState::OpenedFiles { ids, hashes } => {
if !ids.contains($y) || !hashes.contains_key($y) {
return Err(Error::WrongArchiveWriterState {
current_state: format!("{:?}", $x).to_string(),
expected_state: "ArchiveWriterState with id $y".to_string(),
});
}
}
_ => {
return Err(Error::WrongArchiveWriterState {
current_state: format!("{:?}", $x).to_string(),
expected_state: "ArchiveWriterState with id $y".to_string(),
});
}
}
}};
}
pub struct ArchiveWriter<'a, W: 'a + InnerWriterTrait> {
/// MLA Archive format writer
///
/// Configuration
// config is not used for now after archive creation,
// but it could in the future
#[allow(dead_code)]
config: ArchiveWriterConfig,
///
/// Internals part:
///
/// Destination: use a Box to be able to dynamically changes layers
dest: Box<PositionLayerWriter<'a, W>>,
/// Internal state
state: ArchiveWriterState,
/// Filename -> Corresponding ArchiveFileID
///
/// This is done to keep a quick check for filename existence
files_info: HashMap<String, ArchiveFileID>,
/// ID -> Corresponding FileInfo
///
/// File chunks identify their relative file using the `ArchiveFileID`.
/// `files_info` and `ids_info` could have been merged into a single HashMap
/// String -> FileInfo, at the cost of an additional HashMap ArchiveFileID ->
/// String, thus increasing memory footprint.
/// These hashmaps are actually merged at the last moment, on footer
/// serialization
ids_info: HashMap<ArchiveFileID, FileInfo>,
/// Next file id to use
next_id: ArchiveFileID,
/// Current file being written (for continuous block detection)
current_id: ArchiveFileID,
}
// This is an unstable feature for now (`Vec.remove_item`), use a function
// instead to keep stable compatibility
pub fn vec_remove_item<T: std::cmp::PartialEq>(vec: &mut Vec<T>, item: &T) -> Option<T> {
let pos = match vec.iter().position(|x| *x == *item) {
Some(x) => x,
None => return None,
};
Some(vec.remove(pos))
}
impl<'a, W: InnerWriterTrait> ArchiveWriter<'a, W> {
pub fn from_config(dest: W, config: ArchiveWriterConfig) -> Result<Self, Error> {
// Ensure config is correct
config.check()?;
// Write archive header
let mut dest: InnerWriterType<W> = Box::new(RawLayerWriter::new(dest));
ArchiveHeader {
format_version: MLA_FORMAT_VERSION,
config: config.to_persistent()?,
// TODO public_key hashes for easier decryption
}
.dump(&mut dest)?;
// Enable layers depending on user option
if config.is_layers_enabled(Layers::ENCRYPT) {
dest = Box::new(EncryptionLayerWriter::new(dest, &config.encrypt)?);
}
if config.is_layers_enabled(Layers::COMPRESS) {
dest = Box::new(CompressionLayerWriter::new(dest, &config.compress));
}
// Upper layer must be a PositionLayer
let mut final_dest = Box::new(PositionLayerWriter::new(dest));
final_dest.reset_position();
// Build initial archive
Ok(ArchiveWriter {
config,
dest: final_dest,
state: ArchiveWriterState::OpenedFiles {
ids: Vec::new(),
hashes: HashMap::new(),
},
files_info: HashMap::new(),
ids_info: HashMap::new(),
next_id: 0,
current_id: 0,
})
}
pub fn new(dest: W, public_keys: &[PublicKey]) -> Result<Self, Error> {
let mut config = ArchiveWriterConfig::default();
config.add_public_keys(public_keys);
Self::from_config(dest, config)
}
pub fn finalize(&mut self) -> Result<(), Error> {
// Check final state (empty ids, empty hashes)
check_state!(self.state, OpenedFiles);
match &mut self.state {
ArchiveWriterState::OpenedFiles { ids, hashes } => {
if !ids.is_empty() || !hashes.is_empty() {
return Err(Error::WrongWriterState(
"[Finalize] At least one file is still open".to_string(),
));
}
}
_ => {
// Never happens, due to `check_state!`
return Err(Error::WrongWriterState(
"[Finalize] State have changes inside finalize".to_string(),
));
}
}
self.state = ArchiveWriterState::Finalized;
// Mark the end of the data
// Use std::io::Empty as a readable placeholder type
ArchiveFileBlock::EndOfArchiveData::<std::io::Empty> {}.dump(&mut self.dest)?;
ArchiveFooter::serialize_into(&mut self.dest, &self.files_info, &self.ids_info)?;
// Recursive call
self.dest.finalize()?;
Ok(())
}
/// Add the current offset to the corresponding list if the file id is not
/// the current one, ie. if blocks are not continuous
fn mark_continuous_block(&mut self, id: ArchiveFileID) -> Result<(), Error> {
if id != self.current_id {
let offset = self.dest.position();
match self.ids_info.get_mut(&id) {
Some(file_info) => file_info.offsets.push(offset),
None => {
return Err(Error::WrongWriterState(
"[mark_continuous_block] Unable to find the ID".to_string(),
))
}
};
self.current_id = id;
}
Ok(())
}
/// Set the EoF offset to the current offset for the corresponding file id
fn mark_eof(&mut self, id: ArchiveFileID) -> Result<(), Error> {
let offset = self.dest.position();
match self.ids_info.get_mut(&id) {
Some(file_info) => file_info.eof_offset = offset,
None => {
return Err(Error::WrongWriterState(
"[mark_eof] Unable to find the ID".to_string(),
))
}
}
Ok(())
}
/// Add the current block size to the total size of the corresponding file id
fn extend_file_size(&mut self, id: ArchiveFileID, block_size: u64) -> Result<(), Error> {
match self.ids_info.get_mut(&id) {
Some(file_info) => file_info.size += block_size,
None => {
return Err(Error::WrongWriterState(
"[extend_file_size] Unable to find the ID".to_string(),
))
}
}
Ok(())
}
pub fn start_file(&mut self, filename: &str) -> Result<ArchiveFileID, Error> {
check_state!(self.state, OpenedFiles);
if self.files_info.contains_key(filename) {
return Err(Error::DuplicateFilename);
}
// Create ID for this file
let id = self.next_id;
self.next_id += 1;
self.current_id = id;
self.files_info.insert(filename.to_string(), id);
// Save the current position
self.ids_info.insert(
id,
FileInfo {
offsets: vec![self.dest.position()],
size: 0,
eof_offset: 0,
},
);
// Use std::io::Empty as a readable placeholder type
ArchiveFileBlock::FileStart::<std::io::Empty> {
filename: filename.to_string(),
id,
}
.dump(&mut self.dest)?;
match &mut self.state {
ArchiveWriterState::OpenedFiles { ids, hashes } => {
ids.push(id);
hashes.insert(id, Sha256::default());
}
_ => {
// Never happens, due to `check_state!`
return Err(Error::WrongWriterState(
"[StartFile] State have changes inside start_file".to_string(),
));
}
}
Ok(id)
}
pub fn append_file_content<U: Read>(
&mut self,
id: ArchiveFileID,
size: u64,
src: U,
) -> Result<(), Error> {
check_state_file_opened!(&self.state, &id);
if size == 0 {
// Avoid creating 0-sized block
return Ok(());
}
self.mark_continuous_block(id)?;
self.extend_file_size(id, size)?;
let src = self.state.wrap_with_hash(id, src)?;
ArchiveFileBlock::FileContent {
id,
length: size,
data: Some(src),
}
.dump(&mut self.dest)
}
pub fn end_file(&mut self, id: ArchiveFileID) -> Result<(), Error> {
check_state_file_opened!(&self.state, &id);
let hash = match &mut self.state {
ArchiveWriterState::OpenedFiles { ids, hashes } => {
let hash = hashes.remove(&id).ok_or_else(|| {
Error::WrongWriterState("[EndFile] Unable to retrieve the hash".to_string())
})?;
vec_remove_item(ids, &id);
hash.finalize().into()
}
_ => {
// Never happens, due to `check_state_file_opened!`
return Err(Error::WrongWriterState(
"[EndFile] State have changes inside end_file".to_string(),
));
}
};
self.mark_continuous_block(id)?;
self.mark_eof(id)?;
// Use std::io::Empty as a readable placeholder type
ArchiveFileBlock::EndOfFile::<std::io::Empty> { id, hash }.dump(&mut self.dest)?;
Ok(())
}
pub fn add_file<U: Read>(&mut self, filename: &str, size: u64, src: U) -> Result<(), Error> {
let id = self.start_file(filename)?;
self.append_file_content(id, size, src)?;
self.end_file(id)
}
/// Unwraps the inner writer
pub fn into_raw(self) -> W {
self.dest.into_raw()
}
pub fn flush(&mut self) -> io::Result<()> {
self.dest.flush()
}
}
// -------- Reader --------
#[derive(Debug)]
pub struct ArchiveFile<T: Read> {
/// File inside a MLA Archive
pub filename: String,
pub data: T,
pub size: u64,
}
#[derive(PartialEq, Debug)]
enum BlocksToFileReaderState {
// Remaining size
InFile(usize),
Ready,
Finish,
}
#[derive(Debug)]
pub struct BlocksToFileReader<'a, R: Read + Seek> {
/// This structure wraps the internals to get back a file's content
src: &'a mut R,
state: BlocksToFileReaderState,
/// id of the File being read
id: ArchiveFileID,
/// position in `offsets` of the last offset used
current_offset: usize,
/// List of offsets of continuous blocks corresponding to where the file can be read
offsets: &'a [u64],
}
impl<'a, R: Read + Seek> BlocksToFileReader<'a, R> {
fn new(src: &'a mut R, offsets: &'a [u64]) -> Result<BlocksToFileReader<'a, R>, Error> {
// Set the inner layer at the start of the file
src.seek(SeekFrom::Start(offsets[0]))?;
// Read file information header
let id = match ArchiveFileBlock::from(src)? {
ArchiveFileBlock::FileStart { id, .. } => id,
_ => {
return Err(Error::WrongReaderState(
"[BlocksToFileReader] A file must start with a FileStart".to_string(),
));
}
};
Ok(BlocksToFileReader {
src,
state: BlocksToFileReaderState::Ready,
id,
current_offset: 0,
offsets,
})
}
/// Move `self.src` to the next continuous block
fn move_to_next_block(&mut self) -> Result<(), Error> {
self.current_offset += 1;
if self.current_offset >= self.offsets.len() {
return Err(Error::WrongReaderState(
"[BlocksToFileReader] No more continuous blocks".to_string(),
));
}
self.src
.seek(SeekFrom::Start(self.offsets[self.current_offset]))?;
Ok(())
}
}
impl<'a, T: Read + Seek> Read for BlocksToFileReader<'a, T> {
fn read(&mut self, into: &mut [u8]) -> io::Result<usize> {
let (remaining, count) = match self.state {
BlocksToFileReaderState::Ready => {
// Start a new block FileContent
match ArchiveFileBlock::from(&mut self.src)? {
ArchiveFileBlock::FileContent { length, id, .. } => {
if id != self.id {
self.move_to_next_block()?;
return self.read(into);
}
let count = self.src.by_ref().take(length).read(into)?;
let length_usize = length as usize;
(length_usize - count, count)
}
ArchiveFileBlock::EndOfFile { id, .. } => {
if id != self.id {
self.move_to_next_block()?;
return self.read(into);
}
self.state = BlocksToFileReaderState::Finish;
return Ok(0);
}
ArchiveFileBlock::FileStart { id, .. } => {
if id != self.id {
self.move_to_next_block()?;
return self.read(into);
}
return Err(Error::WrongReaderState(
"[BlocksToFileReader] Start with a wrong block type".to_string(),
)
.into());
}
ArchiveFileBlock::EndOfArchiveData => {
return Err(Error::WrongReaderState(
"[BlocksToFileReader] Try to read the end of the archive".to_string(),
)
.into());
}
}
}
BlocksToFileReaderState::InFile(remaining) => {
let count = self.src.by_ref().take(remaining as u64).read(into)?;
(remaining - count, count)
}
BlocksToFileReaderState::Finish => {
return Ok(0);
}
};
if remaining > 0 {
self.state = BlocksToFileReaderState::InFile(remaining);
} else {
// remaining is 0 (> never happens thanks to take)
self.state = BlocksToFileReaderState::Ready;
}
Ok(count)
}
}
#[derive(Serialize, Deserialize)]
#[cfg_attr(test, derive(PartialEq, Eq, Debug))]
pub struct FileInfo {
/// File information to save in the footer
///
/// Offsets of continuous chunks of `ArchiveFileBlock`
offsets: Vec<u64>,
/// Size of the file, in bytes
pub size: u64,
/// Offset of the ArchiveFileBlock::EndOfFile
///
/// This offset is used to retrieve information from the EoF tag, such as
/// the file hash
eof_offset: u64,
}
pub struct ArchiveReader<'a, R: 'a + InnerReaderTrait> {
/// MLA Archive format Reader
/// User's reading configuration
pub config: ArchiveReaderConfig,
/// Source
src: Box<dyn 'a + LayerReader<'a, R>>,
/// Metadata (from footer if any)
metadata: Option<ArchiveFooter>,
}
impl<'b, R: 'b + InnerReaderTrait> ArchiveReader<'b, R> {
pub fn from_config(mut src: R, mut config: ArchiveReaderConfig) -> Result<Self, Error> {
// Make sure we read the archive header from the start
src.rewind()?;
let header = ArchiveHeader::from(&mut src)?;
config.load_persistent(header.config)?;
// Pin the current position (after header) as the new 0
let mut raw_src = Box::new(RawLayerReader::new(src));
raw_src.reset_position()?;
// Enable layers depending on user option. Order is relevant
let mut src: Box<dyn 'b + LayerReader<'b, R>> = raw_src;
if config.layers_enabled.contains(Layers::ENCRYPT) {
src = Box::new(EncryptionLayerReader::new(src, &config.encrypt)?);
}
if config.layers_enabled.contains(Layers::COMPRESS) {
src = Box::new(CompressionLayerReader::new(src)?);
}
src.initialize()?;
// Read the footer
let metadata = Some(ArchiveFooter::deserialize_from(&mut src)?);
// Reset the position for further uses
src.rewind()?;
Ok(ArchiveReader {
config,
src,
metadata,
})
}
pub fn new(src: R) -> Result<Self, Error> {
Self::from_config(src, ArchiveReaderConfig::new())
}
/// Return an iterator on filenames present in the archive
///
/// Order is not relevant, and may change
pub fn list_files(&self) -> Result<impl Iterator<Item = &String>, Error> {
if let Some(ArchiveFooter { files_info, .. }) = &self.metadata {
Ok(files_info.keys())
} else {
Err(Error::MissingMetadata)
}
}
pub fn get_hash(&mut self, filename: &str) -> Result<Option<Sha256Hash>, Error> {
if let Some(ArchiveFooter { files_info }) = &self.metadata {
// Get file relative information
let file_info = match files_info.get(filename) {
None => return Ok(None),
Some(finfo) => finfo,
};
// Set the inner layer at the start of the EoF tag
self.src.seek(SeekFrom::Start(file_info.eof_offset))?;
// Return the file hash
match ArchiveFileBlock::from(&mut self.src)? {
ArchiveFileBlock::EndOfFile { hash, .. } => Ok(Some(hash)),
_ => Err(Error::WrongReaderState(
"[ArchiveReader] eof_offset must point to a EoF".to_string(),
)),
}
} else {
Err(Error::MissingMetadata)
}
}
#[allow(clippy::type_complexity)]
pub fn get_file<'a>(
&'a mut self,
filename: String,
) -> Result<Option<ArchiveFile<BlocksToFileReader<Box<dyn 'b + LayerReader<'b, R>>>>>, Error>
{
if let Some(ArchiveFooter { files_info }) = &self.metadata {
// Get file relative information
let file_info = match files_info.get(&filename) {
None => return Ok(None),
Some(finfo) => finfo,
};
if file_info.offsets.is_empty() {
return Err(Error::WrongReaderState(
"[ArchiveReader] A file must have at least one offset".to_string(),
));
}
// Instantiate the file representation
let reader = BlocksToFileReader::new(&mut self.src, &file_info.offsets)?;
Ok(Some(ArchiveFile {
filename,
data: reader,
size: file_info.size,
}))
} else {
Err(Error::MissingMetadata)
}
}
}
// This code is very similar with MLAArchiveReader
pub struct ArchiveFailSafeReader<'a, R: 'a + Read> {
/// MLA Archive format Reader (fail-safe)
/// User's reading configuration
// config is not used for now after reader creation,
// but it could in the future
#[allow(dead_code)]
config: ArchiveReaderConfig,
/// Source
src: Box<dyn 'a + LayerFailSafeReader<'a, R>>,
}
// Size of the repaired file blocks
const CACHE_SIZE: usize = 8 * 1024 * 1024; // 8MB
/// Used to update the error state only if it was NoError
/// ```text
/// update_error!(error_var, FailSafeReadError::...)
/// ```
macro_rules! update_error {
( $x:ident = $y:expr ) => {
#[allow(clippy::single_match)]
match $x {
FailSafeReadError::NoError => {
$x = $y;
}
_ => {}
}
};
}
impl<'b, R: 'b + Read> ArchiveFailSafeReader<'b, R> {
pub fn from_config(mut src: R, mut config: ArchiveReaderConfig) -> Result<Self, Error> {
let header = ArchiveHeader::from(&mut src)?;
config.load_persistent(header.config)?;