erofs-rs 0.2.1

A pure Rust library for reading EROFS (Enhanced Read-Only File System) images
Documentation
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
#[cfg(feature = "std")]
use std::{
    fs::Permissions,
    os::unix::fs::PermissionsExt,
    time::{Duration, SystemTime},
};

use binrw::BinRead;
use rustix::fs::FileType;

use crate::Error;

pub const MAGIC_NUMBER: u32 = 0xe0f5e1e2;
pub const SUPER_BLOCK_OFFSET: usize = 1024;

pub const LAYOUT_CHUNK_FORMAT_BITS: u16 = 0x001F;
pub const LAYOUT_CHUNK_FORMAT_INDEXES: u16 = 0x0020;

pub const SB_EXTSLOT_SIZE: usize = 16;

#[repr(C)]
#[derive(Debug, Clone, Copy, BinRead)]
#[br(little)]
pub struct SuperBlock {
    pub magic: u32,
    pub checksum: u32,
    pub feature_compat: u32,
    pub blk_size_bits: u8,
    pub ext_slots: u8,
    pub root_nid: u16,
    pub inos: u64,
    pub build_time: u64,
    pub build_time_ns: u32,
    pub blocks: u32,
    pub meta_blk_addr: u32,
    pub xattr_blk_addr: u32,
    pub uuid: [u8; 16],
    pub volume_name: [u8; 16],
    pub feature_incompat: u32,
    pub compr_algs: u16,
    pub extra_devices: u16,
    pub devt_slot_off: u16,
    pub dir_blk_bits: u8,
    pub xattr_prefix_count: u8,
    pub xattr_prefix_start: u32,
    pub packed_nid: u64,
    pub xattr_filter_res: u8,
    pub reserved: [u8; 23],
}

impl SuperBlock {
    #[inline]
    pub const fn size() -> usize {
        size_of::<Self>()
    }
}

#[derive(Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum Layout {
    FlatPlain = 0,
    CompressedFull = 1,
    FlatInline = 2,
    CompressedCompact = 3,
    ChunkBased = 4,
}

impl TryFrom<u8> for Layout {
    type Error = Error;
    fn try_from(x: u8) -> Result<Self, Error> {
        use Layout::*;
        match x {
            0 => Ok(FlatPlain),
            1 => Ok(CompressedFull),
            2 => Ok(FlatInline),
            3 => Ok(CompressedCompact),
            4 => Ok(ChunkBased),
            x => Err(Error::InvalidLayout(x)),
        }
    }
}

bitflags::bitflags! {
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub struct FileMode: u16 {
        const READ = 0o400;
        const WRITE = 0o200;
        const EXEC = 0o100;
        const READ_GROUP = 0o040;
        const WRITE_GROUP = 0o020;
        const EXEC_GROUP = 0o010;
        const READ_OTHER = 0o004;
        const WRITE_OTHER = 0o002;
        const EXEC_OTHER = 0o001;
        const DIR = 0o040000;
        const CHAR_DEVICE = 0o020000;
        const BLOCK_DEVICE = 0o060000;
        const NAMED_PIPE = 0o010000;
        const SOCKET = 0o140000;
        const SYMLINK = 0o120000;
        const IRREGULAR = 0o100000;
        const SETUID = 0o004000;
        const SETGID = 0o002000;
        const STICKY = 0o001000;
    }
}

impl FileMode {
    pub fn is_dir(&self) -> bool {
        self.contains(Self::DIR)
    }

    pub fn is_file(&self) -> bool {
        !self.intersects(
            Self::DIR
                | Self::CHAR_DEVICE
                | Self::BLOCK_DEVICE
                | Self::NAMED_PIPE
                | Self::SOCKET
                | Self::SYMLINK
                | Self::IRREGULAR,
        )
    }
}

#[derive(Debug, Clone, Copy)]
pub enum Inode {
    Compact((u64, InodeCompact)),
    Extended((u64, InodeExtended)),
}

impl Inode {
    pub fn is_compact_format(layout: u16) -> bool {
        (layout & 0x01) == 0
    }

    pub fn id(&self) -> u64 {
        match self {
            Self::Compact((nid, _)) => *nid,
            Self::Extended((nid, _)) => *nid,
        }
    }

    pub fn layout(&self) -> Result<Layout, Error> {
        let format_layout = match self {
            Self::Compact((_, n)) => n.format,
            Self::Extended((_, n)) => n.format,
        };

        let layout = ((format_layout & 0x0E) >> 1) as u8;
        layout.try_into()
    }

    pub fn size(&self) -> usize {
        match self {
            Self::Compact(_) => size_of::<InodeCompact>(),
            Self::Extended(_) => size_of::<InodeExtended>(),
        }
    }

    #[inline]
    pub fn data_size(&self) -> usize {
        match self {
            Self::Compact((_, n)) => n.size as usize,
            Self::Extended((_, n)) => n.size as usize,
        }
    }

    pub fn raw_block_addr(&self) -> u32 {
        match self {
            Self::Compact((_, n)) => n.inode_data,
            Self::Extended((_, n)) => n.inode_data,
        }
    }

    pub fn xattr_size(&self) -> usize {
        let count = match self {
            Self::Compact((_, n)) => n.xattr_count,
            Self::Extended((_, n)) => n.xattr_count,
        };
        if count == 0 {
            0
        } else {
            (count - 1) as usize * size_of::<XattrEntry>() + size_of::<XattrHeader>()
        }
    }

    pub fn file_type(&self) -> FileType {
        match self {
            Self::Compact((_, n)) => FileType::from_raw_mode(n.mode as _),
            Self::Extended((_, n)) => FileType::from_raw_mode(n.mode as _),
        }
    }

    pub fn is_dir(&self) -> bool {
        self.file_type().is_dir()
    }

    pub fn is_file(&self) -> bool {
        self.file_type().is_file()
    }

    pub fn is_symlink(&self) -> bool {
        self.file_type().is_symlink()
    }

    #[cfg(feature = "std")]
    pub fn permissions(&self) -> Permissions {
        match self {
            Self::Compact((_, n)) => Permissions::from_mode(n.mode.into()),
            Self::Extended((_, n)) => Permissions::from_mode(n.mode.into()),
        }
    }

    #[cfg(not(feature = "std"))]
    pub fn permissions(&self) -> u16 {
        match self {
            Self::Compact((_, n)) => n.mode,
            Self::Extended((_, n)) => n.mode,
        }
    }

    #[cfg(feature = "std")]
    pub fn modified(&self) -> Option<SystemTime> {
        match self {
            Self::Compact((_, _)) => None,
            Self::Extended((_, n)) => {
                let secs = n.mtime;
                let nanos = n.mtime_ns;
                Some(
                    SystemTime::UNIX_EPOCH
                        + Duration::from_secs(secs)
                        + Duration::from_nanos(nanos as u64),
                )
            }
        }
    }

    #[cfg(not(feature = "std"))]
    pub fn modified(&self) -> Option<(u64, u32)> {
        match self {
            Self::Compact((_, _)) => None,
            Self::Extended((_, n)) => {
                let secs = n.mtime;
                let nanos = n.mtime_ns;
                Some((secs, nanos))
            }
        }
    }

    pub fn gid(&self) -> u32 {
        match self {
            Self::Compact((_, n)) => n.gid as u32,
            Self::Extended((_, n)) => n.gid,
        }
    }

    pub fn uid(&self) -> u32 {
        match self {
            Self::Compact((_, n)) => n.uid as u32,
            Self::Extended((_, n)) => n.uid,
        }
    }
}

#[repr(C)]
#[derive(Debug, Clone, Copy, BinRead)]
#[br(little)]
pub struct InodeCompact {
    pub format: u16,
    pub xattr_count: u16,
    pub mode: u16,
    pub nlink: u16,
    pub size: u32,
    pub reserved: u32,
    pub inode_data: u32,
    pub inode: u32,
    pub uid: u16,
    pub gid: u16,
    pub reserved2: u32,
}

impl InodeCompact {
    #[inline]
    pub const fn size() -> usize {
        size_of::<Self>()
    }
}

#[repr(C)]
#[derive(Debug, Clone, Copy, BinRead)]
#[br(little)]
pub struct InodeExtended {
    pub format: u16,
    pub xattr_count: u16,
    pub mode: u16,
    pub reserved: u16,
    pub size: u64,
    pub inode_data: u32,
    pub inode: u32,
    pub uid: u32,
    pub gid: u32,
    pub mtime: u64,
    pub mtime_ns: u32,
    pub nlink: u32,
    pub reserved2: [u8; 16],
}

impl InodeExtended {
    #[inline]
    pub const fn size() -> usize {
        size_of::<Self>()
    }
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum DirentFileType {
    Unknown = 0,
    RegularFile = 1,
    Directory = 2,
    CharacterDevice = 3,
    BlockDevice = 4,
    Fifo = 5,
    Socket = 6,
    Symlink = 7,
}

impl DirentFileType {
    pub fn is_dir(&self) -> bool {
        matches!(self, Self::Directory)
    }

    pub fn is_file(&self) -> bool {
        matches!(self, Self::RegularFile)
    }

    pub fn is_symlink(&self) -> bool {
        matches!(self, Self::Symlink)
    }
}

impl TryFrom<u8> for DirentFileType {
    type Error = Error;
    fn try_from(x: u8) -> Result<Self, Error> {
        use DirentFileType::*;
        match x {
            0 => Ok(Unknown),
            1 => Ok(RegularFile),
            2 => Ok(Directory),
            3 => Ok(CharacterDevice),
            4 => Ok(BlockDevice),
            5 => Ok(Fifo),
            6 => Ok(Socket),
            7 => Ok(Symlink),
            _ => Err(Error::InvalidDirentFileType(x)),
        }
    }
}

#[repr(C, packed)]
#[derive(Debug, Clone, Copy, Default, BinRead)]
#[br(little)]
pub struct Dirent {
    pub nid: u64,
    pub name_off: u16,
    pub file_type: u8,
    pub reserved: u8,
}

impl Dirent {
    #[inline]
    pub const fn size() -> usize {
        size_of::<Self>()
    }
}

pub struct ChunkBasedFormat(u16);

impl ChunkBasedFormat {
    pub fn new(format: u32) -> Self {
        Self(format as u16)
    }

    pub fn is_valid(&self) -> bool {
        let allowed_bits = LAYOUT_CHUNK_FORMAT_BITS | LAYOUT_CHUNK_FORMAT_INDEXES;
        (self.0 & !allowed_bits) == 0
    }

    pub fn is_indexes(&self) -> bool {
        (self.0 & LAYOUT_CHUNK_FORMAT_INDEXES) != 0
    }

    pub fn chunk_size_bits(&self) -> u8 {
        (self.0 & LAYOUT_CHUNK_FORMAT_BITS) as u8
    }
}

#[repr(C)]
#[derive(Debug, Clone, Copy, BinRead)]
#[br(little)]
pub struct XattrHeader {
    pub name_filter: u32,
    pub shared_count: u8,
    pub reserved: [u8; 7],
}

#[repr(C)]
#[derive(Debug, Clone, Copy, BinRead)]
#[br(little)]
pub struct XattrEntry {
    pub name_len: u8,
    pub name_index: u8,
    pub value_len: u16,
}

#[repr(C, packed)]
#[derive(Debug, Clone, Copy, BinRead)]
#[br(little)]
pub struct XattrLongPrefixItem {
    pub prefix_addr: u32,
    pub prefix_len: u8,
}

#[repr(C, packed)]
#[derive(Debug, Clone, Copy, BinRead)]
#[br(little)]
pub struct XattrLongPrefix {
    pub base_index: u8,
}

#[repr(C)]
#[derive(Debug, Clone, Copy, BinRead)]
#[br(little)]
pub struct MapHeader {
    pub _reserved: u16,
    pub data_size: u16,
    pub advise: u16,
    // algorithm type (bit 0-3: HEAD1; bit 4-7: HEAD2)
    pub algorithmtype: u8,
    /*
     * bit 0-3 : logical cluster bits - blkszbits
     * bit 4-6 : reserved
     * bit 7   : pack the whole file into packed inode
     */
    pub clusterbits: u8,
}

impl MapHeader {
    #[inline]
    pub const fn size() -> usize {
        size_of::<Self>()
    }

    pub fn fragmentoff(&self) -> u32 {
        u32::from_le((self._reserved as u32) << 16 | u32::from(self.data_size))
    }
}