dfufile 0.3.0

DFU file processing
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
//! DfuSe extensions from STMicroelectronics.
//!
//! See document UM0391 Revision 1 for a detailed specification.

use std::io::{Read, Seek};

use crate::{SUFFIX_LENGTH, Suffix};

////////////////////////////////////////////////////////////////////////////////

/// Check if the file is a DfuSe file.
pub fn detect(file: &mut std::fs::File) -> Result<bool, Error> {
    file.rewind()?;
    let mut signature = [0; 5];
    file.read_exact(&mut signature)?;

    let Ok(suffix) = Suffix::from_file(file) else {
        return Err(Error::InvalidSuffix);
    };

    Ok(&signature == b"DfuSe" && suffix.bcdDFU == 0x011A)
}

////////////////////////////////////////////////////////////////////////////////

/// Reference to the file content.
#[derive(Debug)]
pub struct Content {
    /// The prefix header with metadata.
    pub prefix: Prefix,

    /// Vector of contained images.
    pub images: Vec<Image>,
}

impl Content {
    /// Creates a new instance.
    pub fn new(prefix: Prefix, images: Vec<Image>) -> Self {
        Self { prefix, images }
    }

    /// Creates a new instance with data read from file.
    pub fn from_file(file: &mut std::fs::File) -> Result<Self, Error> {
        let file_size = file.seek(std::io::SeekFrom::End(0))?;

        // File must be at least as large as the prefix + standard suffix
        if file_size < (PREFIX_LENGTH + SUFFIX_LENGTH) as u64 {
            return Err(Error::InsufficientFileSize);
        }

        let prefix = Prefix::from_file(file)?;
        let mut images = Vec::new();

        let mut file_pos = PREFIX_LENGTH as u64;

        for _ in 0..prefix.bTargets {
            let image = Image::from_file(file, &mut file_pos)?;
            images.push(image);
        }

        let content = Self::new(prefix, images);

        Ok(content)
    }

    /// Find an image with a specific alternate setting.
    pub fn find_image_by_alt(&self, alt_setting: u8) -> Option<&Image> {
        self.images
            .iter()
            .find(|&image| image.target_prefix.bAlternateSetting == alt_setting)
    }

    /// Find an image with a specific name.
    pub fn find_image_by_name<T: AsRef<str>>(&self, name: T) -> Option<&Image> {
        self.images
            .iter()
            .find(|&image| image.target_prefix.szTargetName == name.as_ref())
    }
}

////////////////////////////////////////////////////////////////////////////////

/// Length of the file prefix in bytes.
pub const PREFIX_LENGTH: usize = 11;

/// File prefix, see UM0391 section 2.1.
///
/// The DFU prefix placed as a header is the first part read by the
/// software application, used to retrieve the file context,
/// and enable valid DFU files to be recognized.
#[allow(non_snake_case)]
#[derive(Debug, Clone)]
pub struct Prefix {
    /// File identifier, must contain "DfuSe".
    pub szSignature: String,

    /// Format revision, usually 0x01.
    pub bVersion: u8,

    /// Total file length in bytes (including the suffix).
    pub DFUImageSize: u32,

    /// Number of images stored in the file.
    pub bTargets: u8,
}

impl Default for Prefix {
    /// Creates a new prefix with default values.
    fn default() -> Self {
        Self {
            szSignature: String::from("DfuSe"),
            bVersion: 1,
            DFUImageSize: 0,
            bTargets: 0,
        }
    }
}

impl Prefix {
    /// Creates a new prefix.
    pub fn new(signature: String, version: u8, image_size: u32, num_targets: u8) -> Self {
        Self {
            szSignature: signature,
            bVersion: version,
            DFUImageSize: image_size,
            bTargets: num_targets,
        }
    }

    /// Creates a new prefix from a buffer of u8 values.
    pub fn from_bytes(buffer: &[u8; PREFIX_LENGTH]) -> Self {
        Self::new(
            String::from_utf8_lossy(&buffer[0..5]).to_string(),
            u8::from_le(buffer[5]),
            u32::from_le_bytes([buffer[6], buffer[7], buffer[8], buffer[9]]),
            u8::from_le(buffer[10]),
        )
    }

    /// Creates a new prefix from reading a file.
    pub fn from_file(file: &mut std::fs::File) -> Result<Self, Error> {
        file.rewind()?;
        let mut buffer = [0; PREFIX_LENGTH];
        file.read_exact(&mut buffer)?;

        let data = Self::from_bytes(&buffer);

        if &data.szSignature != "DfuSe" {
            return Err(Error::InvalidPrefixSignature);
        }

        Ok(data)
    }
}

////////////////////////////////////////////////////////////////////////////////

/// An image, see UM0391 section 2.3.1.
///
/// The DFU Image contains the effective data of the firmware,
/// starting by a Target prefix record followed by a number of Image elements
#[derive(Debug, Clone)]
pub struct Image {
    /// Target prefix record containing metadata.
    pub target_prefix: TargetPrefix,

    /// Vector of image elements containing the data.
    pub image_elements: Vec<ImageElement>,
}

impl Default for Image {
    /// Creates a new image with default values.
    fn default() -> Self {
        Self {
            target_prefix: TargetPrefix::default(),
            image_elements: Vec::new(),
        }
    }
}

impl Image {
    /// Creates a new image.
    pub fn new(target_prefix: TargetPrefix, image_elements: Vec<ImageElement>) -> Self {
        Self {
            target_prefix,
            image_elements,
        }
    }

    /// Creates a new image by reading a file.
    ///
    /// The `file_pos` argument must be set to the position inside the file as
    /// offset from the start and is updated according to the number of bytes read.
    pub fn from_file(file: &mut std::fs::File, file_pos: &mut u64) -> Result<Self, Error> {
        let target_prefix = TargetPrefix::from_file(file, file_pos)?;
        let mut image_elements = Vec::new();

        for _ in 0..target_prefix.dwNbElements {
            let image_element = ImageElement::from_file(file, file_pos)?;
            image_elements.push(image_element);
        }

        let image = Image::new(target_prefix, image_elements);

        Ok(image)
    }
}

////////////////////////////////////////////////////////////////////////////////

/// Length of the target prefix in bytes.
pub const TARGET_PREFIX_LENGTH: usize = 274;

/// Target prefix of an image, see UM0391 section 2.3.2.
///
/// The target prefix record is used to describe the associated image
#[allow(non_snake_case)]
#[derive(Debug, Clone)]
pub struct TargetPrefix {
    /// Target identifier, must contain "Target".
    pub szSignature: String,

    /// The device's alternate setting for which this image is intended.
    pub bAlternateSetting: u8,

    /// Boolean value (0 or 1) which indicates if the target is named or not.
    pub bTargetNamed: u8,

    /// Target name.
    pub szTargetName: String,

    /// Whole length of the associated image excluding this target prefix.
    pub dwTargetSize: u32,

    /// Number of elements in the associated image.
    pub dwNbElements: u32,
}

impl Default for TargetPrefix {
    /// Creates a new target prefix with default values.
    fn default() -> Self {
        Self {
            szSignature: String::from("Target"),
            bAlternateSetting: 0,
            bTargetNamed: 0,
            szTargetName: String::new(),
            dwTargetSize: 0,
            dwNbElements: 0,
        }
    }
}

impl TargetPrefix {
    /// Creates a new target prefix.
    pub fn new(
        signature: String,
        alt_setting: u8,
        named: u8,
        target_name: String,
        target_size: u32,
        num_elements: u32,
    ) -> Self {
        Self {
            szSignature: signature,
            bAlternateSetting: alt_setting,
            bTargetNamed: named,
            szTargetName: target_name,
            dwTargetSize: target_size,
            dwNbElements: num_elements,
        }
    }

    /// Creates a new target prefix from a buffer of u8 values.
    pub fn from_bytes(buffer: &[u8; TARGET_PREFIX_LENGTH]) -> Self {
        // The target name in the buffer is a null-terminated C string
        // but often the rest of the buffer contains garbage.
        // So we do some extra work here to detect the real length used.
        let target_name_full = String::from_utf8_lossy(&buffer[11..266]).to_string();
        let target_name_len = target_name_full.find('\x00');

        // If no null character is found, length is set to maximum of 255.
        let target_name_len = target_name_len.unwrap_or(255);

        Self::new(
            String::from_utf8_lossy(&buffer[0..6]).to_string(),
            u8::from_le(buffer[6]),
            u8::from_le(buffer[7]),
            String::from_utf8_lossy(&buffer[11..266])[0..target_name_len].to_string(),
            u32::from_le_bytes([buffer[266], buffer[267], buffer[268], buffer[269]]),
            u32::from_le_bytes([buffer[270], buffer[271], buffer[272], buffer[273]]),
        )
    }

    /// Creates a new target prefix by reading a file.
    ///
    /// The `file_pos` argument must be set to the position inside the file as
    /// offset from the start and is updated according to the number of bytes read.
    pub fn from_file(file: &mut std::fs::File, file_pos: &mut u64) -> Result<Self, Error> {
        file.seek(std::io::SeekFrom::Start(*file_pos))?;
        let mut buffer = [0; TARGET_PREFIX_LENGTH];
        file.read_exact(&mut buffer)?;

        *file_pos += TARGET_PREFIX_LENGTH as u64;

        let data = Self::from_bytes(&buffer);

        if &data.szSignature != "Target" {
            return Err(Error::InvalidTargetPrefixSignature);
        }

        Ok(data)
    }
}

////////////////////////////////////////////////////////////////////////////////

/// Length of the image element without data in bytes.
pub const IMAGE_ELEMENT_LENGTH: usize = 8;

/// An image element, see UM0391 section 2.3.3.
///
/// The image element provides a data record containing the effective
/// firmware data preceded by the data address and data size.
#[allow(non_snake_case)]
#[derive(Debug, Clone)]
pub struct ImageElement {
    /// Starting address of the data.
    pub dwElementAddress: u32,

    /// Size of the contained data.
    pub dwElementSize: u32,

    /// File position of data as offset from the start.
    pub data_position: u64,
}

impl Default for ImageElement {
    /// Creates a new image element with default values.
    fn default() -> Self {
        Self {
            dwElementAddress: 0,
            dwElementSize: 0,
            data_position: 0,
        }
    }
}

impl ImageElement {
    /// Creates a new image element.
    pub fn new(element_address: u32, element_size: u32, data_position: u64) -> Self {
        Self {
            dwElementAddress: element_address,
            dwElementSize: element_size,
            data_position,
        }
    }

    /// Creates a new image element from a buffer of u8 values and data position.
    pub fn from_bytes(buffer: &[u8; IMAGE_ELEMENT_LENGTH], data_position: u64) -> Self {
        Self::new(
            u32::from_le_bytes([buffer[0], buffer[1], buffer[2], buffer[3]]),
            u32::from_le_bytes([buffer[4], buffer[5], buffer[6], buffer[7]]),
            data_position,
        )
    }

    /// Creates a new image element by reading a file.
    ///
    /// The `file_pos` argument must be set to the position inside the file as
    /// offset from the start and is updated according to the number of bytes read.
    pub fn from_file(file: &mut std::fs::File, file_pos: &mut u64) -> Result<Self, Error> {
        file.seek(std::io::SeekFrom::Start(*file_pos))?;
        let mut buffer = [0; IMAGE_ELEMENT_LENGTH];
        file.read_exact(&mut buffer)?;

        *file_pos += IMAGE_ELEMENT_LENGTH as u64;

        let data = Self::from_bytes(&buffer, *file_pos);

        *file_pos += data.dwElementSize as u64;

        Ok(data)
    }

    /// Read data from file into a buffer.
    ///
    /// The `position` argument is relative to the start of the element
    /// The function tries to fill the buffer completely and returns the
    /// number of valid bytes in the buffer. This may be less than the buffer
    /// size in case of EOF or reaching the element borders.
    pub fn read_at(
        &self,
        file: &mut std::fs::File,
        position: u32,
        buffer: &mut [u8],
    ) -> Result<usize, Error> {
        let file_pos = self.data_position + (position as u64);
        file.seek(std::io::SeekFrom::Start(file_pos))?;
        let read_size = file.read(buffer)?;

        let read_size = std::cmp::min(read_size, (self.dwElementSize - position) as usize);

        Ok(read_size)
    }
}

////////////////////////////////////////////////////////////////////////////////

/// Parsing errors.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// File prefix signature is not "DfuSe".
    #[error("Invalid file prefix signature.")]
    InvalidPrefixSignature,

    /// File suffix invalid or can't be read.
    #[error("Invalid file suffix.")]
    InvalidSuffix,

    /// Target prefix signature is not "Target".
    #[error("Invalid target prefix signature.")]
    InvalidTargetPrefixSignature,

    /// File is too small (smaller than prefix + suffix size).
    #[error("File size is to small to contain prefix and suffix")]
    InsufficientFileSize,

    /// I/O error.
    #[error(transparent)]
    Io(#[from] std::io::Error),
}