blob: 2b44876cf206b698f7874b2d5a97f087ab73bfa7 [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
Jiyong Park0553ff22021-07-15 12:25:36 +090031use anyhow::{Context, Result};
Jiyong Park3c327d22021-06-08 20:51:54 +090032use data_model::DataInit;
Jiyong Park86c9b082021-06-04 19:03:48 +090033use std::fs::{File, OpenOptions};
34use std::io::Write;
35use std::mem::size_of;
36use std::os::unix::io::AsRawFd;
37use std::path::{Path, PathBuf};
Jiyong Park86c9b082021-06-04 19:03:48 +090038
39mod sys;
40mod verity;
41use sys::*;
42pub use verity::*;
43
44nix::ioctl_readwrite!(_dm_dev_create, DM_IOCTL, Cmd::DM_DEV_CREATE, DmIoctl);
Jiyong Park86c9b082021-06-04 19:03:48 +090045nix::ioctl_readwrite!(_dm_dev_suspend, DM_IOCTL, Cmd::DM_DEV_SUSPEND, DmIoctl);
46nix::ioctl_readwrite!(_dm_table_load, DM_IOCTL, Cmd::DM_TABLE_LOAD, DmIoctl);
Jiyong Park99a35b82021-06-07 10:13:44 +090047#[cfg(test)]
48nix::ioctl_readwrite!(_dm_dev_remove, DM_IOCTL, Cmd::DM_DEV_REMOVE, DmIoctl);
Jiyong Park86c9b082021-06-04 19:03:48 +090049
50fn dm_dev_create(dm: &DeviceMapper, ioctl: *mut DmIoctl) -> Result<i32> {
51 // SAFETY: `ioctl` is copied into the kernel. It modifies the state in the kernel, not the
52 // state of this process in any way.
53 Ok(unsafe { _dm_dev_create(dm.0.as_raw_fd(), ioctl) }?)
54}
55
Jiyong Park86c9b082021-06-04 19:03:48 +090056fn dm_dev_suspend(dm: &DeviceMapper, ioctl: *mut DmIoctl) -> Result<i32> {
57 // SAFETY: `ioctl` is copied into the kernel. It modifies the state in the kernel, not the
58 // state of this process in any way.
59 Ok(unsafe { _dm_dev_suspend(dm.0.as_raw_fd(), ioctl) }?)
60}
61
62fn dm_table_load(dm: &DeviceMapper, ioctl: *mut DmIoctl) -> Result<i32> {
63 // SAFETY: `ioctl` is copied into the kernel. It modifies the state in the kernel, not the
64 // state of this process in any way.
65 Ok(unsafe { _dm_table_load(dm.0.as_raw_fd(), ioctl) }?)
66}
67
Jiyong Park99a35b82021-06-07 10:13:44 +090068#[cfg(test)]
69fn dm_dev_remove(dm: &DeviceMapper, ioctl: *mut DmIoctl) -> Result<i32> {
70 // SAFETY: `ioctl` is copied into the kernel. It modifies the state in the kernel, not the
71 // state of this process in any way.
72 Ok(unsafe { _dm_dev_remove(dm.0.as_raw_fd(), ioctl) }?)
73}
74
Jiyong Park86c9b082021-06-04 19:03:48 +090075// `DmTargetSpec` is the header of the data structure for a device-mapper target. When doing the
76// ioctl, one of more `DmTargetSpec` (and its body) are appened to the `DmIoctl` struct.
77#[repr(C)]
Jiyong Park3c327d22021-06-08 20:51:54 +090078#[derive(Copy, Clone)]
Jiyong Park86c9b082021-06-04 19:03:48 +090079struct DmTargetSpec {
80 sector_start: u64,
81 length: u64, // number of 512 sectors
82 status: i32,
83 next: u32,
84 target_type: [u8; DM_MAX_TYPE_NAME],
85}
86
Jiyong Park3c327d22021-06-08 20:51:54 +090087// SAFETY: C struct is safe to be initialized from raw data
88unsafe impl DataInit for DmTargetSpec {}
89
Jiyong Park86c9b082021-06-04 19:03:48 +090090impl DmTargetSpec {
91 fn new(target_type: &str) -> Result<Self> {
Jiyong Park3c327d22021-06-08 20:51:54 +090092 // safe because the size of the array is the same as the size of the struct
93 let mut spec: Self = *DataInit::from_mut_slice(&mut [0; size_of::<Self>()]).unwrap();
Jiyong Park86c9b082021-06-04 19:03:48 +090094 spec.target_type.as_mut().write_all(target_type.as_bytes())?;
95 Ok(spec)
96 }
Jiyong Park86c9b082021-06-04 19:03:48 +090097}
98
99impl DmIoctl {
100 fn new(name: &str) -> Result<DmIoctl> {
Jiyong Park3c327d22021-06-08 20:51:54 +0900101 // safe because the size of the array is the same as the size of the struct
102 let mut data: Self = *DataInit::from_mut_slice(&mut [0; size_of::<Self>()]).unwrap();
Jiyong Park86c9b082021-06-04 19:03:48 +0900103 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 }
Jiyong Park86c9b082021-06-04 19:03:48 +0900118}
119
120/// `DeviceMapper` is the entry point for the device mapper framework. It essentially is a file
121/// handle to "/dev/mapper/control".
122pub struct DeviceMapper(File);
123
Jiyong Park5f0ebea2021-06-07 12:53:35 +0900124#[cfg(not(target_os = "android"))]
125const MAPPER_CONTROL: &str = "/dev/mapper/control";
126#[cfg(not(target_os = "android"))]
127const MAPPER_DEV_ROOT: &str = "/dev/mapper";
128
129#[cfg(target_os = "android")]
130const MAPPER_CONTROL: &str = "/dev/device-mapper";
131#[cfg(target_os = "android")]
132const MAPPER_DEV_ROOT: &str = "/dev/block/mapper";
133
Jiyong Park86c9b082021-06-04 19:03:48 +0900134impl DeviceMapper {
135 /// Constructs a new `DeviceMapper` entrypoint. This is essentially the same as opening
136 /// "/dev/mapper/control".
137 pub fn new() -> Result<DeviceMapper> {
Jiyong Park0553ff22021-07-15 12:25:36 +0900138 let f = OpenOptions::new()
139 .read(true)
140 .write(true)
141 .open(MAPPER_CONTROL)
142 .context(format!("failed to open {}", MAPPER_CONTROL))?;
Jiyong Park86c9b082021-06-04 19:03:48 +0900143 Ok(DeviceMapper(f))
144 }
145
146 /// Creates a device mapper device and configure it according to the `target` specification.
147 /// The path to the generated device is "/dev/mapper/<name>".
148 pub fn create_device(&self, name: &str, target: &DmVerityTarget) -> Result<PathBuf> {
149 // Step 1: create an empty device
150 let mut data = DmIoctl::new(&name)?;
Jiyong Parkf02061f2021-06-07 09:44:44 +0900151 data.set_uuid(&uuid()?)?;
Jiyong Park0553ff22021-07-15 12:25:36 +0900152 dm_dev_create(&self, &mut data)
153 .context(format!("failed to create an empty device with name {}", &name))?;
Jiyong Park86c9b082021-06-04 19:03:48 +0900154
155 // Step 2: load table onto the device
Jiyong Park3c327d22021-06-08 20:51:54 +0900156 let payload_size = size_of::<DmIoctl>() + target.as_slice().len();
Jiyong Park86c9b082021-06-04 19:03:48 +0900157
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 Park3c327d22021-06-08 20:51:54 +0900165 payload.extend_from_slice(data.as_slice());
166 payload.extend_from_slice(target.as_slice());
Jiyong Park0553ff22021-07-15 12:25:36 +0900167 dm_table_load(&self, payload.as_mut_ptr() as *mut DmIoctl)
168 .context("failed to load table")?;
Jiyong Park86c9b082021-06-04 19:03:48 +0900169
170 // Step 3: activate the device (note: the term 'suspend' might be misleading, but it
171 // actually activates the table. See include/uapi/linux/dm-ioctl.h
172 let mut data = DmIoctl::new(&name)?;
Jiyong Park0553ff22021-07-15 12:25:36 +0900173 dm_dev_suspend(&self, &mut data).context("failed to activate")?;
Jiyong Park86c9b082021-06-04 19:03:48 +0900174
175 // Step 4: wait unti the device is created and return the device path
Jiyong Park5f0ebea2021-06-07 12:53:35 +0900176 let path = Path::new(MAPPER_DEV_ROOT).join(&name);
Jiyong Park86c9b082021-06-04 19:03:48 +0900177 wait_for_path(&path)?;
178 Ok(path)
179 }
180
181 /// Removes a mapper device
Jiyong Park99a35b82021-06-07 10:13:44 +0900182 #[cfg(test)]
Jiyong Park86c9b082021-06-04 19:03:48 +0900183 pub fn delete_device_deferred(&self, name: &str) -> Result<()> {
184 let mut data = DmIoctl::new(&name)?;
185 data.flags |= Flag::DM_DEFERRED_REMOVE;
Jiyong Park0553ff22021-07-15 12:25:36 +0900186 dm_dev_remove(&self, &mut data)
187 .context(format!("failed to remove device with name {}", &name))?;
Jiyong Park86c9b082021-06-04 19:03:48 +0900188 Ok(())
189 }
190}
191
192/// Used to derive a UUID that uniquely identifies a device mapper device when creating it.
Jiyong Parkf02061f2021-06-07 09:44:44 +0900193fn uuid() -> Result<String> {
194 use std::time::{SystemTime, UNIX_EPOCH};
195 use uuid::v1::{Context, Timestamp};
196 use uuid::Uuid;
197
198 let context = Context::new(0);
199 let now = SystemTime::now().duration_since(UNIX_EPOCH)?;
200 let ts = Timestamp::from_unix(&context, now.as_secs(), now.subsec_nanos());
201 let uuid = Uuid::new_v1(ts, "apkver".as_bytes())?;
202 Ok(String::from(uuid.to_hyphenated().encode_lower(&mut Uuid::encode_buffer())))
Jiyong Park86c9b082021-06-04 19:03:48 +0900203}