blob: 7ac72c8bb3161ce7eac17f28a790c7ac3153299c [file] [log] [blame]
Jiyong Park86c9b082021-06-04 19:03:48 +09001/*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17// `dm` module implements part of the `device-mapper` ioctl interfaces. It currently supports
18// creation and deletion of the mapper device. It doesn't support other operations like querying
19// the status of the mapper device. And there's no plan to extend the support unless it is
20// required.
21//
22// Why in-house development? [`devicemapper`](https://crates.io/crates/devicemapper) is a public
23// Rust implementation of the device mapper APIs. However, it doesn't provide any abstraction for
24// the target-specific tables. User has to manually craft the table. Ironically, the library
25// provides a lot of APIs for the features that are not required for `apkdmverity` such as listing
26// the device mapper block devices that are currently listed in the kernel. Size is an important
27// criteria for Microdroid.
28
29use crate::util::*;
30
31use anyhow::Result;
32use std::fs::{File, OpenOptions};
33use std::io::Write;
34use std::mem::size_of;
35use std::os::unix::io::AsRawFd;
36use std::path::{Path, PathBuf};
Jiyong Park86c9b082021-06-04 19:03:48 +090037
38mod sys;
39mod verity;
40use sys::*;
41pub use verity::*;
42
43nix::ioctl_readwrite!(_dm_dev_create, DM_IOCTL, Cmd::DM_DEV_CREATE, DmIoctl);
Jiyong Park86c9b082021-06-04 19:03:48 +090044nix::ioctl_readwrite!(_dm_dev_suspend, DM_IOCTL, Cmd::DM_DEV_SUSPEND, DmIoctl);
45nix::ioctl_readwrite!(_dm_table_load, DM_IOCTL, Cmd::DM_TABLE_LOAD, DmIoctl);
Jiyong Park99a35b82021-06-07 10:13:44 +090046#[cfg(test)]
47nix::ioctl_readwrite!(_dm_dev_remove, DM_IOCTL, Cmd::DM_DEV_REMOVE, DmIoctl);
Jiyong Park86c9b082021-06-04 19:03:48 +090048
49fn dm_dev_create(dm: &DeviceMapper, ioctl: *mut DmIoctl) -> Result<i32> {
50 // SAFETY: `ioctl` is copied into the kernel. It modifies the state in the kernel, not the
51 // state of this process in any way.
52 Ok(unsafe { _dm_dev_create(dm.0.as_raw_fd(), ioctl) }?)
53}
54
Jiyong Park86c9b082021-06-04 19:03:48 +090055fn dm_dev_suspend(dm: &DeviceMapper, ioctl: *mut DmIoctl) -> Result<i32> {
56 // SAFETY: `ioctl` is copied into the kernel. It modifies the state in the kernel, not the
57 // state of this process in any way.
58 Ok(unsafe { _dm_dev_suspend(dm.0.as_raw_fd(), ioctl) }?)
59}
60
61fn dm_table_load(dm: &DeviceMapper, ioctl: *mut DmIoctl) -> Result<i32> {
62 // SAFETY: `ioctl` is copied into the kernel. It modifies the state in the kernel, not the
63 // state of this process in any way.
64 Ok(unsafe { _dm_table_load(dm.0.as_raw_fd(), ioctl) }?)
65}
66
Jiyong Park99a35b82021-06-07 10:13:44 +090067#[cfg(test)]
68fn dm_dev_remove(dm: &DeviceMapper, ioctl: *mut DmIoctl) -> Result<i32> {
69 // SAFETY: `ioctl` is copied into the kernel. It modifies the state in the kernel, not the
70 // state of this process in any way.
71 Ok(unsafe { _dm_dev_remove(dm.0.as_raw_fd(), ioctl) }?)
72}
73
Jiyong Park86c9b082021-06-04 19:03:48 +090074// `DmTargetSpec` is the header of the data structure for a device-mapper target. When doing the
75// ioctl, one of more `DmTargetSpec` (and its body) are appened to the `DmIoctl` struct.
76#[repr(C)]
77struct DmTargetSpec {
78 sector_start: u64,
79 length: u64, // number of 512 sectors
80 status: i32,
81 next: u32,
82 target_type: [u8; DM_MAX_TYPE_NAME],
83}
84
85impl DmTargetSpec {
86 fn new(target_type: &str) -> Result<Self> {
87 // SAFETY: zero initialized C struct is safe
88 let mut spec = unsafe { std::mem::MaybeUninit::<Self>::zeroed().assume_init() };
89 spec.target_type.as_mut().write_all(target_type.as_bytes())?;
90 Ok(spec)
91 }
92
93 fn as_u8_slice(&self) -> &[u8; size_of::<Self>()] {
94 // SAFETY: lifetime of the output reference isn't changed.
Jiyong Park99a35b82021-06-07 10:13:44 +090095 unsafe { &*(&self as *const &Self as *const [u8; size_of::<Self>()]) }
Jiyong Park86c9b082021-06-04 19:03:48 +090096 }
97}
98
99impl DmIoctl {
100 fn new(name: &str) -> Result<DmIoctl> {
101 // SAFETY: zero initialized C struct is safe
102 let mut data = unsafe { std::mem::MaybeUninit::<Self>::zeroed().assume_init() };
103 data.version[0] = DM_VERSION_MAJOR;
104 data.version[1] = DM_VERSION_MINOR;
105 data.version[2] = DM_VERSION_PATCHLEVEL;
106 data.data_size = size_of::<Self>() as u32;
107 data.data_start = 0;
108 data.name.as_mut().write_all(name.as_bytes())?;
109 Ok(data)
110 }
111
112 fn set_uuid(&mut self, uuid: &str) -> Result<()> {
113 let mut dst = self.uuid.as_mut();
114 dst.fill(0);
115 dst.write_all(uuid.as_bytes())?;
116 Ok(())
117 }
118
119 fn as_u8_slice(&self) -> &[u8; size_of::<Self>()] {
120 // SAFETY: lifetime of the output reference isn't changed.
Jiyong Park99a35b82021-06-07 10:13:44 +0900121 unsafe { &*(&self as *const &Self as *const [u8; size_of::<Self>()]) }
Jiyong Park86c9b082021-06-04 19:03:48 +0900122 }
123}
124
125/// `DeviceMapper` is the entry point for the device mapper framework. It essentially is a file
126/// handle to "/dev/mapper/control".
127pub struct DeviceMapper(File);
128
Jiyong Park5f0ebea2021-06-07 12:53:35 +0900129#[cfg(not(target_os = "android"))]
130const MAPPER_CONTROL: &str = "/dev/mapper/control";
131#[cfg(not(target_os = "android"))]
132const MAPPER_DEV_ROOT: &str = "/dev/mapper";
133
134#[cfg(target_os = "android")]
135const MAPPER_CONTROL: &str = "/dev/device-mapper";
136#[cfg(target_os = "android")]
137const MAPPER_DEV_ROOT: &str = "/dev/block/mapper";
138
Jiyong Park86c9b082021-06-04 19:03:48 +0900139impl DeviceMapper {
140 /// Constructs a new `DeviceMapper` entrypoint. This is essentially the same as opening
141 /// "/dev/mapper/control".
142 pub fn new() -> Result<DeviceMapper> {
Jiyong Park5f0ebea2021-06-07 12:53:35 +0900143 let f = OpenOptions::new().read(true).write(true).open(MAPPER_CONTROL)?;
Jiyong Park86c9b082021-06-04 19:03:48 +0900144 Ok(DeviceMapper(f))
145 }
146
147 /// Creates a device mapper device and configure it according to the `target` specification.
148 /// The path to the generated device is "/dev/mapper/<name>".
149 pub fn create_device(&self, name: &str, target: &DmVerityTarget) -> Result<PathBuf> {
150 // Step 1: create an empty device
151 let mut data = DmIoctl::new(&name)?;
Jiyong Parkf02061f2021-06-07 09:44:44 +0900152 data.set_uuid(&uuid()?)?;
Jiyong Park86c9b082021-06-04 19:03:48 +0900153 dm_dev_create(&self, &mut data)?;
154
155 // Step 2: load table onto the device
156 let payload_size = size_of::<DmIoctl>() + target.as_u8_slice().len();
157
158 let mut data = DmIoctl::new(&name)?;
159 data.data_size = payload_size as u32;
160 data.data_start = size_of::<DmIoctl>() as u32;
161 data.target_count = 1;
162 data.flags |= Flag::DM_READONLY_FLAG;
163
164 let mut payload = Vec::with_capacity(payload_size);
Jiyong Park99a35b82021-06-07 10:13:44 +0900165 payload.extend_from_slice(data.as_u8_slice());
166 payload.extend_from_slice(target.as_u8_slice());
Jiyong Park86c9b082021-06-04 19:03:48 +0900167 dm_table_load(&self, payload.as_mut_ptr() as *mut DmIoctl)?;
168
169 // Step 3: activate the device (note: the term 'suspend' might be misleading, but it
170 // actually activates the table. See include/uapi/linux/dm-ioctl.h
171 let mut data = DmIoctl::new(&name)?;
172 dm_dev_suspend(&self, &mut data)?;
173
174 // Step 4: wait unti the device is created and return the device path
Jiyong Park5f0ebea2021-06-07 12:53:35 +0900175 let path = Path::new(MAPPER_DEV_ROOT).join(&name);
Jiyong Park86c9b082021-06-04 19:03:48 +0900176 wait_for_path(&path)?;
177 Ok(path)
178 }
179
180 /// Removes a mapper device
Jiyong Park99a35b82021-06-07 10:13:44 +0900181 #[cfg(test)]
Jiyong Park86c9b082021-06-04 19:03:48 +0900182 pub fn delete_device_deferred(&self, name: &str) -> Result<()> {
183 let mut data = DmIoctl::new(&name)?;
184 data.flags |= Flag::DM_DEFERRED_REMOVE;
185 dm_dev_remove(&self, &mut data)?;
186 Ok(())
187 }
188}
189
190/// Used to derive a UUID that uniquely identifies a device mapper device when creating it.
Jiyong Parkf02061f2021-06-07 09:44:44 +0900191fn uuid() -> Result<String> {
192 use std::time::{SystemTime, UNIX_EPOCH};
193 use uuid::v1::{Context, Timestamp};
194 use uuid::Uuid;
195
196 let context = Context::new(0);
197 let now = SystemTime::now().duration_since(UNIX_EPOCH)?;
198 let ts = Timestamp::from_unix(&context, now.as_secs(), now.subsec_nanos());
199 let uuid = Uuid::new_v1(ts, "apkver".as_bytes())?;
200 Ok(String::from(uuid.to_hyphenated().encode_lower(&mut Uuid::encode_buffer())))
Jiyong Park86c9b082021-06-04 19:03:48 +0900201}