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
// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

pub mod constants;

use {
    anyhow::{anyhow, ensure, Context as _, Error},
    fidl_fuchsia_hardware_block::BlockProxy,
    fidl_fuchsia_hardware_block_partition::PartitionProxy,
    fuchsia_zircon::{self as zx, HandleBased as _},
};

#[derive(Debug, PartialEq, Clone, Copy)]
pub enum DiskFormat {
    Unknown,
    Gpt,
    Mbr,
    Minfs,
    Fat,
    Blobfs,
    Fvm,
    Zxcrypt,
    BlockVerity,
    VbMeta,
    BootPart,
    Fxfs,
    F2fs,
    NandBroker,
}

impl DiskFormat {
    // These are copied verbatim from //src/storage/lib/fs_management/cpp/format.cc, and should be
    // kept in sync.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Unknown => "unknown!",
            Self::Gpt => "gpt",
            Self::Mbr => "mbr",
            Self::Minfs => "minfs",
            Self::Fat => "fat",
            Self::Blobfs => "blobfs",
            Self::Fvm => "fvm",
            Self::Zxcrypt => "zxcrypt",
            Self::BlockVerity => "block verity",
            Self::VbMeta => "vbmeta",
            Self::BootPart => "bootpart",
            Self::Fxfs => "fxfs",
            Self::F2fs => "f2fs",
            Self::NandBroker => "nand broker",
        }
    }
}

/// The inverse of DiskFormat::as_str().
impl From<&str> for DiskFormat {
    fn from(s: &str) -> Self {
        match s {
            "gpt" => Self::Gpt,
            "mbr" => Self::Mbr,
            "minfs" => Self::Minfs,
            "fat" => Self::Fat,
            "blobfs" => Self::Blobfs,
            "fvm" => Self::Fvm,
            "zxcrypt" => Self::Zxcrypt,
            "block verity" => Self::BlockVerity,
            "vbmeta" => Self::VbMeta,
            "bootpart" => Self::BootPart,
            "fxfs" => Self::Fxfs,
            "f2fs" => Self::F2fs,
            "nand broker" => Self::NandBroker,
            _ => Self::Unknown,
        }
    }
}

pub fn round_up(val: u64, divisor: u64) -> Option<u64> {
    // Checked version of ((val + (divisor - 1)) / divisor) * divisor
    ((val.checked_add(divisor.checked_sub(1)?)?).checked_div(divisor)?).checked_mul(divisor)
}

/// Wrap the functions that [`detect_disk_format`] needs to use from Block in a trait, so we can
/// substitute something else (e.g. a PartitionProxy).
pub trait DetectableDevice: Send + Sync {
    fn get_info(
        &self,
    ) -> fidl::client::QueryResponseFut<fidl_fuchsia_hardware_block::BlockGetInfoResult>;

    fn read_blocks(
        &self,
        vmo: fidl::Vmo,
        length: u64,
        dev_offset: u64,
        vmo_offset: u64,
    ) -> fidl::client::QueryResponseFut<fidl_fuchsia_hardware_block::BlockReadBlocksResult>;
}

impl DetectableDevice for BlockProxy {
    fn get_info(
        &self,
    ) -> fidl::client::QueryResponseFut<fidl_fuchsia_hardware_block::BlockGetInfoResult> {
        BlockProxy::get_info(self)
    }

    fn read_blocks(
        &self,
        vmo: fidl::Vmo,
        length: u64,
        dev_offset: u64,
        vmo_offset: u64,
    ) -> fidl::client::QueryResponseFut<fidl_fuchsia_hardware_block::BlockReadBlocksResult> {
        BlockProxy::read_blocks(self, vmo, length, dev_offset, vmo_offset)
    }
}

impl DetectableDevice for PartitionProxy {
    fn get_info(
        &self,
    ) -> fidl::client::QueryResponseFut<fidl_fuchsia_hardware_block::BlockGetInfoResult> {
        PartitionProxy::get_info(self)
    }

    fn read_blocks(
        &self,
        vmo: fidl::Vmo,
        length: u64,
        dev_offset: u64,
        vmo_offset: u64,
    ) -> fidl::client::QueryResponseFut<fidl_fuchsia_hardware_block::BlockReadBlocksResult> {
        PartitionProxy::read_blocks(self, vmo, length, dev_offset, vmo_offset)
    }
}

pub async fn detect_disk_format(block_proxy: &dyn DetectableDevice) -> DiskFormat {
    match detect_disk_format_res(block_proxy).await {
        Ok(format) => format,
        Err(e) => {
            tracing::error!("detect_disk_format failed: {:?}", e);
            return DiskFormat::Unknown;
        }
    }
}

async fn detect_disk_format_res(block_proxy: &dyn DetectableDevice) -> Result<DiskFormat, Error> {
    let block_info = block_proxy
        .get_info()
        .await
        .context("transport error on get_info call")?
        .map_err(zx::Status::from_raw)
        .context("get_info call failed")?;
    ensure!(block_info.block_size > 0, "block size expected to be non-zero");

    let double_block_size = (block_info.block_size)
        .checked_mul(2)
        .ok_or_else(|| anyhow!("overflow calculating double block size"))?;

    let header_size = if constants::HEADER_SIZE > double_block_size {
        constants::HEADER_SIZE
    } else {
        double_block_size
    };

    let device_size = (block_info.block_size as u64)
        .checked_mul(block_info.block_count)
        .ok_or_else(|| anyhow!("overflow calculating device size"))?;

    if header_size as u64 > device_size {
        // The header we want to read is bigger than the actual device. This isn't necessarily an
        // error, but it does mean we can't inspect the content.
        return Ok(DiskFormat::Unknown);
    }

    let buffer_size = round_up(header_size as u64, block_info.block_size as u64)
        .ok_or_else(|| anyhow!("overflow rounding header size up"))?;
    let vmo = zx::Vmo::create(buffer_size).context("failed to create vmo")?;
    let () = block_proxy
        .read_blocks(
            vmo.duplicate_handle(zx::Rights::SAME_RIGHTS)
                .context("vmo duplicate handle call failed")?,
            buffer_size,
            0,
            0,
        )
        .await
        .context("transport error on read_blocks protocol")?
        .map_err(zx::Status::from_raw)
        .context("read_blocks returned an error status")?;

    let mut data = vec![0; buffer_size as usize];
    vmo.read(&mut data, 0).context("vmo read failed")?;

    if data.starts_with(&constants::FVM_MAGIC) {
        return Ok(DiskFormat::Fvm);
    }

    if data.starts_with(&constants::ZXCRYPT_MAGIC) {
        return Ok(DiskFormat::Zxcrypt);
    }

    if data.starts_with(&constants::BLOCK_VERITY_MAGIC) {
        return Ok(DiskFormat::BlockVerity);
    }

    if &data[block_info.block_size as usize..block_info.block_size as usize + 16]
        == &constants::GPT_MAGIC
    {
        return Ok(DiskFormat::Gpt);
    }

    if data.starts_with(&constants::MINFS_MAGIC) {
        return Ok(DiskFormat::Minfs);
    }

    if data.starts_with(&constants::BLOBFS_MAGIC) {
        return Ok(DiskFormat::Blobfs);
    }

    if data.starts_with(&constants::VB_META_MAGIC) {
        return Ok(DiskFormat::VbMeta);
    }

    if &data[1024..1024 + constants::F2FS_MAGIC.len()] == &constants::F2FS_MAGIC {
        return Ok(DiskFormat::F2fs);
    }

    if data.starts_with(&constants::FXFS_MAGIC) {
        return Ok(DiskFormat::Fxfs);
    }

    // Check for Mbr and Fat last.  Since they only have two bytes of magic, it's fairly easy to
    // randomly encounter this combination (this has happened multiple times in unit tests).
    if data[510] == 0x55 && data[511] == 0xAA {
        if data[38] == 0x29 || data[66] == 0x29 {
            // 0x55AA are always placed at offset 510 and 511 for FAT filesystems.
            // 0x29 is the Boot Signature, but it is placed at either offset 38 or
            // 66 (depending on FAT type).
            return Ok(DiskFormat::Fat);
        }
        return Ok(DiskFormat::Mbr);
    }

    return Ok(DiskFormat::Unknown);
}

#[cfg(test)]
mod tests {
    use {
        super::{constants, detect_disk_format_res, DiskFormat},
        anyhow::Error,
        fidl::endpoints::create_proxy_and_stream,
        fidl_fuchsia_hardware_block::{BlockInfo, BlockMarker, BlockRequest, Flag},
        futures::{pin_mut, select, FutureExt, TryStreamExt},
    };

    async fn get_detected_disk_format(
        content: &[u8],
        block_count: u64,
        block_size: u64,
    ) -> Result<DiskFormat, Error> {
        let (proxy, mut stream) = create_proxy_and_stream::<BlockMarker>().unwrap();

        let mock_device = async {
            while let Some(request) = stream.try_next().await.unwrap() {
                match request {
                    BlockRequest::GetInfo { responder } => {
                        responder
                            .send(Ok(&BlockInfo {
                                block_count: block_count,
                                block_size: block_size as u32,
                                max_transfer_size: 1024 * 1024,
                                flags: Flag::empty(),
                            }))
                            .unwrap();
                    }
                    BlockRequest::ReadBlocks { vmo, length, dev_offset, vmo_offset, responder } => {
                        assert_eq!(dev_offset, 0);
                        assert_eq!(length, content.len() as u64);
                        vmo.write(content, vmo_offset).unwrap();
                        responder.send(Ok(())).unwrap();
                    }
                    _ => unreachable!(),
                }
            }
        }
        .fuse();

        pin_mut!(mock_device);

        select! {
          _ = mock_device => unreachable!(),
          format = detect_disk_format_res(&proxy).fuse() => format,
        }
    }

    /// Confirm that we map to/from string consistently.
    #[test]
    fn to_from_str_test() {
        for fmt in vec![
            DiskFormat::Unknown,
            DiskFormat::Gpt,
            DiskFormat::Mbr,
            DiskFormat::Minfs,
            DiskFormat::Fat,
            DiskFormat::Blobfs,
            DiskFormat::Fvm,
            DiskFormat::Zxcrypt,
            DiskFormat::BlockVerity,
            DiskFormat::VbMeta,
            DiskFormat::BootPart,
            DiskFormat::Fxfs,
            DiskFormat::F2fs,
            DiskFormat::NandBroker,
        ] {
            assert_eq!(fmt, fmt.as_str().into());
        }
    }

    #[fuchsia::test]
    async fn detect_disk_format_too_small() {
        assert_eq!(
            get_detected_disk_format(&Vec::new(), 1, 512).await.unwrap(),
            DiskFormat::Unknown
        );
    }

    #[fuchsia::test]
    async fn detect_format_fvm() {
        let mut data = vec![0; 4096];
        data[..constants::FVM_MAGIC.len()].copy_from_slice(&constants::FVM_MAGIC);
        assert_eq!(get_detected_disk_format(&data, 1000, 512).await.unwrap(), DiskFormat::Fvm);
    }

    #[fuchsia::test]
    async fn detect_format_zxcrypt() {
        let mut data = vec![0; 4096];
        data[0..constants::ZXCRYPT_MAGIC.len()].copy_from_slice(&constants::ZXCRYPT_MAGIC);
        assert_eq!(get_detected_disk_format(&data, 1000, 512).await.unwrap(), DiskFormat::Zxcrypt);
    }

    #[fuchsia::test]
    async fn detect_format_block_verity() {
        let mut data = vec![0; 4096];
        data[0..constants::BLOCK_VERITY_MAGIC.len()]
            .copy_from_slice(&constants::BLOCK_VERITY_MAGIC);
        assert_eq!(
            get_detected_disk_format(&data, 1000, 512).await.unwrap(),
            DiskFormat::BlockVerity
        );
    }

    #[fuchsia::test]
    async fn detect_format_gpt() {
        let mut data = vec![0; 4096];
        data[512..512 + 16].copy_from_slice(&constants::GPT_MAGIC);
        assert_eq!(get_detected_disk_format(&data, 1000, 512).await.unwrap(), DiskFormat::Gpt);
    }

    #[fuchsia::test]
    async fn detect_format_minfs() {
        let mut data = vec![0; 4096];
        data[0..constants::MINFS_MAGIC.len()].copy_from_slice(&constants::MINFS_MAGIC);
        assert_eq!(get_detected_disk_format(&data, 1000, 512).await.unwrap(), DiskFormat::Minfs);
    }

    #[fuchsia::test]
    async fn detect_format_minfs_large_block_device() {
        let mut data = vec![0; 32768];
        data[0..constants::MINFS_MAGIC.len()].copy_from_slice(&constants::MINFS_MAGIC);
        assert_eq!(
            get_detected_disk_format(&data, 1250000, 16384).await.unwrap(),
            DiskFormat::Minfs
        );
    }

    #[fuchsia::test]
    async fn detect_format_blobfs() {
        let mut data = vec![0; 4096];
        data[0..constants::BLOBFS_MAGIC.len()].copy_from_slice(&constants::BLOBFS_MAGIC);
        assert_eq!(get_detected_disk_format(&data, 1000, 512).await.unwrap(), DiskFormat::Blobfs);
    }

    #[fuchsia::test]
    async fn detect_format_vb_meta() {
        let mut data = vec![0; 4096];
        data[0..constants::VB_META_MAGIC.len()].copy_from_slice(&constants::VB_META_MAGIC);
        assert_eq!(get_detected_disk_format(&data, 1000, 512).await.unwrap(), DiskFormat::VbMeta);
    }

    #[fuchsia::test]
    async fn detect_format_mbr() {
        let mut data = vec![0; 4096];
        data[510] = 0x55 as u8;
        data[511] = 0xAA as u8;
        data[38] = 0x30 as u8;
        data[66] = 0x30 as u8;
        assert_eq!(get_detected_disk_format(&data, 1000, 512).await.unwrap(), DiskFormat::Mbr);
    }

    #[fuchsia::test]
    async fn detect_format_fat_1() {
        let mut data = vec![0; 4096];
        data[510] = 0x55 as u8;
        data[511] = 0xAA as u8;
        data[38] = 0x29 as u8;
        data[66] = 0x30 as u8;
        assert_eq!(get_detected_disk_format(&data, 1000, 512).await.unwrap(), DiskFormat::Fat);
    }

    #[fuchsia::test]
    async fn detect_format_fat_2() {
        let mut data = vec![0; 4096];
        data[510] = 0x55 as u8;
        data[511] = 0xAA as u8;
        data[38] = 0x30 as u8;
        data[66] = 0x29 as u8;
        assert_eq!(get_detected_disk_format(&data, 1000, 512).await.unwrap(), DiskFormat::Fat);
    }

    #[fuchsia::test]
    async fn detect_format_f2fs() {
        let mut data = vec![0; 4096];
        data[1024..1024 + constants::F2FS_MAGIC.len()].copy_from_slice(&constants::F2FS_MAGIC);
        assert_eq!(get_detected_disk_format(&data, 1000, 512).await.unwrap(), DiskFormat::F2fs);
    }

    #[fuchsia::test]
    async fn detect_format_fxfs() {
        let mut data = vec![0; 4096];
        data[0..constants::FXFS_MAGIC.len()].copy_from_slice(&constants::FXFS_MAGIC);
        assert_eq!(get_detected_disk_format(&data, 1000, 512).await.unwrap(), DiskFormat::Fxfs);
    }

    #[fuchsia::test]
    async fn detect_format_unknown() {
        assert_eq!(
            get_detected_disk_format(&vec![0; 4096], 1000, 512).await.unwrap(),
            DiskFormat::Unknown
        );
    }
}