backhand 0.25.1

Library for the reading, creating, and modification of SquashFS file systems
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
458
459
460
461
//! Types of image formats

use core::fmt;
use std::sync::Arc;

use crate::traits::CompressionAction;
#[cfg(feature = "v3")]
use crate::v3::compressor::DefaultCompressor as V3DefaultCompressor;
#[cfg(feature = "v3_lzma")]
use crate::v3_lzma::compressor::LzmaAdaptiveCompressor as V3LzmaCompressor;
#[cfg(feature = "v3_lzma")]
use crate::v3_lzma::standard_compressor::LzmaStandardCompressor as V3LzmaStandardCompressor;
use crate::v4::compressor::DefaultCompressor as V4DefaultCompressor;

// Static instances of compressors
#[cfg(feature = "v3_lzma")]
static V3_LZMA_STANDARD_COMPRESSOR: V3LzmaStandardCompressor = V3LzmaStandardCompressor;

/// Kind Magic - First 4 bytes of image
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Magic {
    /// Little Endian `b"hsqs"`
    Little,
    /// Big Endian `b"sqsh"`
    Big,
}

impl Magic {
    fn magic(self) -> [u8; 4] {
        match self {
            Self::Little => *b"hsqs",
            Self::Big => *b"sqsh",
        }
    }
}

/// Kind Endian
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Endian {
    Little,
    Big,
}

/// Version-specific compressor types
#[derive(Clone)]
pub enum VersionedCompressor {
    #[cfg(feature = "v3")]
    V3(&'static V3DefaultCompressor),
    #[cfg(feature = "v3_lzma")]
    V3Lzma(&'static V3LzmaCompressor),
    #[cfg(feature = "v3_lzma")]
    V3LzmaStandard(&'static V3LzmaStandardCompressor),
    V4(&'static V4DefaultCompressor),
    /// Custom v4 compressor
    CustomV4(
        &'static (
                     dyn crate::traits::CompressionAction<
            Error = crate::BackhandError,
            Compressor = crate::v4::compressor::Compressor,
            FilesystemCompressor = crate::v4::filesystem::writer::FilesystemCompressor,
            SuperBlock = crate::v4::squashfs::SuperBlock,
        > + Send
                         + Sync
                 ),
    ),
}

impl VersionedCompressor {
    /// Decompress data using the version-specific compressor
    pub fn decompress(
        &self,
        bytes: &[u8],
        out: &mut Vec<u8>,
        compressor: Option<crate::traits::types::Compressor>,
    ) -> Result<(), crate::BackhandError> {
        match self {
            #[cfg(feature = "v3")]
            VersionedCompressor::V3(comp) => comp.decompress(bytes, out, None),
            #[cfg(feature = "v3_lzma")]
            VersionedCompressor::V3Lzma(comp) => comp.decompress(bytes, out, None),
            #[cfg(feature = "v3_lzma")]
            VersionedCompressor::V3LzmaStandard(comp) => comp.decompress(bytes, out, None),
            VersionedCompressor::V4(comp) => {
                let v4_compressor =
                    compressor.ok_or(crate::BackhandError::MissingCompressor)?.into();
                comp.decompress(bytes, out, v4_compressor)
            }
            VersionedCompressor::CustomV4(comp) => {
                let v4_compressor =
                    compressor.ok_or(crate::BackhandError::MissingCompressor)?.into();
                comp.decompress(bytes, out, v4_compressor)
            }
        }
    }
}

#[derive(Clone)]
pub struct InnerKind {
    /// Magic at the beginning of the image
    pub(crate) magic: [u8; 4],
    /// Endian used for all data types
    pub(crate) type_endian: deku::ctx::Endian,
    /// Endian used for Metadata Lengths
    pub(crate) data_endian: deku::ctx::Endian,
    /// Major version
    pub(crate) version_major: u16,
    /// Minor version
    pub(crate) version_minor: u16,
    /// Version-specific compression impl
    pub(crate) compressor: VersionedCompressor,
    /// v3 needs the bit-order for reading with little endian
    /// v4 does not need this field
    #[allow(dead_code)]
    pub(crate) bit_order: Option<deku::ctx::Order>,
}

/// Version of SquashFS, also supporting custom changes to SquashFS seen in 3rd-party firmware
///
/// See [Kind Constants](`crate::kind#constants`) for a list of custom Kinds
#[derive(Clone)]
pub struct Kind {
    /// "Easier for the eyes" type for the real Kind
    pub(crate) inner: Arc<InnerKind>,
}

impl fmt::Debug for Kind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FilesystemWriter")
            .field("magic", &self.inner.magic)
            .field("type_endian", &self.inner.type_endian)
            .field("data_endian", &self.inner.data_endian)
            .field("version_major", &self.inner.version_major)
            .field("version_minor", &self.inner.version_minor)
            .finish()
    }
}

impl Kind {
    /// Create a new Kind with a custom v4 compressor (defaults to LE_V4_0)
    ///
    /// # Example
    /// ```rust,ignore
    /// # use backhand::{kind::Kind, compression::CompressionAction};
    /// struct MyCompressor;
    /// impl CompressionAction for MyCompressor {
    ///     // ... implementation
    /// }
    /// static MY_COMPRESSOR: MyCompressor = MyCompressor;
    /// let kind = Kind::new_v4(&MY_COMPRESSOR);
    /// ```
    pub fn new_v4<C>(compression: &'static C) -> Self
    where
        C: crate::traits::CompressionAction<
                Error = crate::BackhandError,
                Compressor = crate::v4::compressor::Compressor,
                FilesystemCompressor = crate::v4::filesystem::writer::FilesystemCompressor,
                SuperBlock = crate::v4::squashfs::SuperBlock,
            > + Send
            + Sync,
    {
        Kind {
            inner: Arc::new(InnerKind {
                magic: LE_V4_0.magic,
                type_endian: LE_V4_0.type_endian,
                data_endian: LE_V4_0.data_endian,
                version_major: LE_V4_0.version_major,
                version_minor: LE_V4_0.version_minor,
                compressor: VersionedCompressor::CustomV4(compression),
                bit_order: LE_V4_0.bit_order,
            }),
        }
    }

    /// Create a Kind from a const with a custom v4 compressor
    ///
    /// # Example
    /// ```rust,ignore
    /// # use backhand::{kind::{self, Kind}, compression::CompressionAction};
    /// struct MyCompressor;
    /// impl CompressionAction for MyCompressor {
    ///     // ... implementation
    /// }
    /// static MY_COMPRESSOR: MyCompressor = MyCompressor;
    /// let kind = Kind::new_v4_with_const(&MY_COMPRESSOR, kind::BE_V4_0);
    /// ```
    pub fn new_v4_with_const<C>(compression: &'static C, inner: InnerKind) -> Self
    where
        C: crate::traits::CompressionAction<
                Error = crate::BackhandError,
                Compressor = crate::v4::compressor::Compressor,
                FilesystemCompressor = crate::v4::filesystem::writer::FilesystemCompressor,
                SuperBlock = crate::v4::squashfs::SuperBlock,
            > + Send
            + Sync,
    {
        Kind {
            inner: Arc::new(InnerKind {
                magic: inner.magic,
                type_endian: inner.type_endian,
                data_endian: inner.data_endian,
                version_major: inner.version_major,
                version_minor: inner.version_minor,
                compressor: VersionedCompressor::CustomV4(compression),
                bit_order: inner.bit_order,
            }),
        }
    }

    /// From a string, return a kind
    ///
    /// # Example
    /// Get a default [`Kind`]
    /// ```rust
    /// # use backhand::{kind, kind::Kind};
    /// let kind = Kind::from_target("le_v4_0").unwrap();
    /// ```
    pub fn from_target(s: &str) -> Result<Kind, String> {
        let kind = match s {
            "be_v4_0" => BE_V4_0,
            "le_v4_0" => LE_V4_0,
            "avm_be_v4_0" => AVM_BE_V4_0,
            #[cfg(feature = "v3")]
            "be_v3_0" => BE_V3_0,
            #[cfg(feature = "v3")]
            "le_v3_0" => LE_V3_0,
            #[cfg(feature = "v3_lzma")]
            "le_v3_0_lzma" => LE_V3_0_LZMA,
            #[cfg(feature = "v3_lzma")]
            "be_v3_0_lzma" => BE_V3_0_LZMA,
            #[cfg(feature = "v3_lzma")]
            "netgear_be_v3_0_lzma" => NETGEAR_BE_V3_0_LZMA,
            #[cfg(feature = "v3_lzma")]
            "netgear_be_v3_0_lzma_standard" => NETGEAR_BE_V3_0_LZMA_STANDARD,
            #[cfg(feature = "v3_lzma")]
            "le_v3_1_lzma_swap" => LE_V3_1_LZMA_SWAP,
            #[cfg(feature = "v3_lzma")]
            "be_v3_1_lzma_swap" => BE_V3_1_LZMA_SWAP,
            _ => return Err("not a valid kind".to_string()),
        };

        Ok(Kind { inner: Arc::new(kind) })
    }

    /// From a known Squashfs image Kind, return a [`Kind`]
    ///
    /// # Example
    /// Get a default [`Kind`]
    ///
    /// ```rust
    /// # use backhand::{kind, kind::Kind};
    /// let kind = Kind::from_const(kind::LE_V4_0).unwrap();
    /// ```
    pub fn from_const(inner: InnerKind) -> Result<Kind, String> {
        Ok(Kind { inner: Arc::new(inner) })
    }

    // TODO: example
    pub fn from_kind(kind: &Kind) -> Kind {
        Self { inner: kind.inner.clone() }
    }

    /// Set magic type at the beginning of the image
    // TODO: example
    pub fn with_magic(self, magic: Magic) -> Self {
        let mut inner = (*self.inner).clone();
        inner.magic = magic.magic();
        Self { inner: Arc::new(inner) }
    }

    pub fn magic(&self) -> [u8; 4] {
        self.inner.magic
    }

    /// Get major version
    pub fn version_major(&self) -> u16 {
        self.inner.version_major
    }

    /// Get minor version
    pub fn version_minor(&self) -> u16 {
        self.inner.version_minor
    }

    /// Set endian used for data types
    // TODO: example
    pub fn with_type_endian(self, endian: Endian) -> Self {
        let mut inner = (*self.inner).clone();
        inner.type_endian = match endian {
            Endian::Little => deku::ctx::Endian::Little,
            Endian::Big => deku::ctx::Endian::Big,
        };
        Self { inner: Arc::new(inner) }
    }

    /// Set endian used for Metadata lengths
    // TODO: example
    pub fn with_data_endian(self, endian: Endian) -> Self {
        let mut inner = (*self.inner).clone();
        inner.data_endian = match endian {
            Endian::Little => deku::ctx::Endian::Little,
            Endian::Big => deku::ctx::Endian::Big,
        };
        Self { inner: Arc::new(inner) }
    }

    /// Set both type and data endian
    // TODO: example
    pub fn with_all_endian(self, endian: Endian) -> Self {
        let mut inner = (*self.inner).clone();
        match endian {
            Endian::Little => {
                inner.type_endian = deku::ctx::Endian::Little;
                inner.data_endian = deku::ctx::Endian::Little;
            }
            Endian::Big => {
                inner.type_endian = deku::ctx::Endian::Big;
                inner.data_endian = deku::ctx::Endian::Big;
            }
        }
        Self { inner: Arc::new(inner) }
    }

    /// Set major and minor version
    // TODO: example
    pub fn with_version(self, major: u16, minor: u16) -> Self {
        let mut inner = (*self.inner).clone();
        inner.version_major = major;
        inner.version_minor = minor;
        Self { inner: Arc::new(inner) }
    }
}

/// Default `Kind` for linux kernel and squashfs-tools/mksquashfs. Little-Endian v4.0
pub const LE_V4_0: InnerKind = InnerKind {
    magic: *b"hsqs",
    type_endian: deku::ctx::Endian::Little,
    data_endian: deku::ctx::Endian::Little,
    version_major: 4,
    version_minor: 0,
    compressor: VersionedCompressor::V4(&V4DefaultCompressor),
    bit_order: None,
};

/// Big-Endian Superblock v4.0
pub const BE_V4_0: InnerKind = InnerKind {
    magic: *b"sqsh",
    type_endian: deku::ctx::Endian::Big,
    data_endian: deku::ctx::Endian::Big,
    version_major: 4,
    version_minor: 0,
    compressor: VersionedCompressor::V4(&V4DefaultCompressor),
    bit_order: None,
};

/// AVM Fritz!OS firmware support. Tested with: <https://github.com/dnicolodi/squashfs-avm-tools>
pub const AVM_BE_V4_0: InnerKind = InnerKind {
    magic: *b"sqsh",
    type_endian: deku::ctx::Endian::Big,
    data_endian: deku::ctx::Endian::Little,
    version_major: 4,
    version_minor: 0,
    compressor: VersionedCompressor::V4(&V4DefaultCompressor),
    bit_order: None,
};

/// Default `Kind` for SquashFS v3.0 Little-Endian
#[cfg(feature = "v3")]
pub const LE_V3_0: InnerKind = InnerKind {
    magic: *b"hsqs",
    type_endian: deku::ctx::Endian::Little,
    data_endian: deku::ctx::Endian::Little,
    version_major: 3,
    version_minor: 0,
    compressor: VersionedCompressor::V3(&V3DefaultCompressor),
    bit_order: Some(deku::ctx::Order::Lsb0),
};

/// Big-Endian SquashFS v3.0
#[cfg(feature = "v3")]
pub const BE_V3_0: InnerKind = InnerKind {
    magic: *b"sqsh",
    type_endian: deku::ctx::Endian::Big,
    data_endian: deku::ctx::Endian::Big,
    version_major: 3,
    version_minor: 0,
    compressor: VersionedCompressor::V3(&V3DefaultCompressor),
    bit_order: Some(deku::ctx::Order::Msb0),
};

/// Little-Endian SquashFS v3.0 with LZMA compression
#[cfg(feature = "v3_lzma")]
pub const LE_V3_0_LZMA: InnerKind = InnerKind {
    magic: *b"hsqs",
    type_endian: deku::ctx::Endian::Little,
    data_endian: deku::ctx::Endian::Little,
    version_major: 3,
    version_minor: 0,
    compressor: VersionedCompressor::V3Lzma(&V3LzmaCompressor),
    bit_order: Some(deku::ctx::Order::Lsb0),
};

/// Big-Endian SquashFS v3.0 with LZMA compression
#[cfg(feature = "v3_lzma")]
pub const BE_V3_0_LZMA: InnerKind = InnerKind {
    magic: *b"sqsh",
    type_endian: deku::ctx::Endian::Big,
    data_endian: deku::ctx::Endian::Big,
    version_major: 3,
    version_minor: 0,
    compressor: VersionedCompressor::V3Lzma(&V3LzmaCompressor),
    bit_order: Some(deku::ctx::Order::Msb0),
};

/// Big-Endian SquashFS v3.0 with LZMA compression for Netgear
#[cfg(feature = "v3_lzma")]
pub const NETGEAR_BE_V3_0_LZMA: InnerKind = InnerKind {
    magic: *b"qshs",
    type_endian: deku::ctx::Endian::Big,
    data_endian: deku::ctx::Endian::Big,
    version_major: 3,
    version_minor: 0,
    compressor: VersionedCompressor::V3Lzma(&V3LzmaCompressor),
    bit_order: Some(deku::ctx::Order::Msb0),
};

/// Big-Endian SquashFS v3.0 with LZMA standard compression for Netgear
#[cfg(feature = "v3_lzma")]
pub const NETGEAR_BE_V3_0_LZMA_STANDARD: InnerKind = InnerKind {
    magic: *b"qshs",
    type_endian: deku::ctx::Endian::Big,
    data_endian: deku::ctx::Endian::Big,
    version_major: 3,
    version_minor: 0,
    compressor: VersionedCompressor::V3LzmaStandard(&V3_LZMA_STANDARD_COMPRESSOR),
    bit_order: Some(deku::ctx::Order::Msb0),
};

/// Little-Endian SquashFS v3.1 with LZMA compression and swapped magic (Thomson/Technicolor/NETGEAR)
#[cfg(feature = "v3_lzma")]
pub const LE_V3_1_LZMA_SWAP: InnerKind = InnerKind {
    magic: *b"shsq",
    type_endian: deku::ctx::Endian::Little,
    data_endian: deku::ctx::Endian::Little,
    version_major: 3,
    version_minor: 1,
    compressor: VersionedCompressor::V3Lzma(&V3LzmaCompressor),
    bit_order: Some(deku::ctx::Order::Lsb0),
};

/// Big-Endian SquashFS v3.1 with LZMA compression and swapped magic (Thomson/Technicolor/NETGEAR)
#[cfg(feature = "v3_lzma")]
pub const BE_V3_1_LZMA_SWAP: InnerKind = InnerKind {
    magic: *b"shsq",
    type_endian: deku::ctx::Endian::Big,
    data_endian: deku::ctx::Endian::Big,
    version_major: 3,
    version_minor: 1,
    compressor: VersionedCompressor::V3Lzma(&V3LzmaCompressor),
    bit_order: Some(deku::ctx::Order::Msb0),
};