loopdev/lib.rs
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
// Supress warnings generated by bindgen: https://github.com/rust-lang/rust-bindgen/issues/1651
#![allow(deref_nullptr)]
#![allow(unknown_lints)]
//! Setup and control loop devices.
//!
//! Provides rust interface with similar functionality to the Linux utility `losetup`.
//!
//! # Examples
//!
//! Default options:
//!
//! ```rust
//! use loopdev::LoopControl;
//! let lc = LoopControl::open().unwrap();
//! let ld = lc.next_free().unwrap();
//!
//! println!("{}", ld.path().unwrap().display());
//!
//! ld.attach_file("disk.img").unwrap();
//! // ...
//! ld.detach().unwrap();
//! ```
//!
//! Custom options:
//!
//! ```rust
//! # use loopdev::LoopControl;
//! # let lc = LoopControl::open().unwrap();
//! # let ld = lc.next_free().unwrap();
//! #
//! ld.with()
//! .part_scan(true)
//! .offset(512 * 1024 * 1024) // 512 MiB
//! .size_limit(1024 * 1024 * 1024) // 1GiB
//! .attach("disk.img").unwrap();
//! // ...
//! ld.detach().unwrap();
//! ```
extern crate libc;
#[cfg(feature = "direct_io")]
use bindings::LOOP_SET_DIRECT_IO;
use bindings::{
loop_info64, LOOP_CLR_FD, LOOP_CTL_GET_FREE, LOOP_SET_CAPACITY, LOOP_SET_FD, LOOP_SET_STATUS64,
LO_FLAGS_AUTOCLEAR, LO_FLAGS_READ_ONLY,
};
use libc::{c_int, ioctl};
use std::{
default::Default,
fs::{File, OpenOptions},
io,
os::unix::prelude::*,
path::{Path, PathBuf},
};
#[allow(non_camel_case_types)]
#[allow(dead_code)]
#[allow(non_snake_case)]
mod bindings {
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
}
#[cfg(all(not(target_os = "android"), not(target_env = "musl")))]
type IoctlRequest = libc::c_ulong;
#[cfg(any(target_os = "android", target_env = "musl"))]
type IoctlRequest = libc::c_int;
const LOOP_CONTROL: &str = "/dev/loop-control";
#[cfg(not(target_os = "android"))]
const LOOP_PREFIX: &str = "/dev/loop";
#[cfg(target_os = "android")]
const LOOP_PREFIX: &str = "/dev/block/loop";
/// Interface to the loop control device: `/dev/loop-control`.
#[derive(Debug)]
pub struct LoopControl {
dev_file: File,
}
impl LoopControl {
/// Opens the loop control device.
pub fn open() -> io::Result<Self> {
Ok(Self {
dev_file: OpenOptions::new()
.read(true)
.write(true)
.open(LOOP_CONTROL)?,
})
}
/// Finds and opens the next available loop device.
///
/// # Examples
///
/// ```rust
/// use loopdev::LoopControl;
/// let lc = LoopControl::open().unwrap();
/// let ld = lc.next_free().unwrap();
/// println!("{}", ld.path().unwrap().display());
/// ```
pub fn next_free(&self) -> io::Result<LoopDevice> {
let dev_num = ioctl_to_error(unsafe {
ioctl(
self.dev_file.as_raw_fd() as c_int,
LOOP_CTL_GET_FREE as IoctlRequest,
)
})?;
LoopDevice::open(&format!("{}{}", LOOP_PREFIX, dev_num))
}
}
impl AsRawFd for LoopControl {
fn as_raw_fd(&self) -> RawFd {
self.dev_file.as_raw_fd()
}
}
impl IntoRawFd for LoopControl {
fn into_raw_fd(self) -> RawFd {
self.dev_file.into_raw_fd()
}
}
/// Interface to a loop device ie `/dev/loop0`.
#[derive(Debug)]
pub struct LoopDevice {
device: File,
}
impl AsRawFd for LoopDevice {
fn as_raw_fd(&self) -> RawFd {
self.device.as_raw_fd()
}
}
impl IntoRawFd for LoopDevice {
fn into_raw_fd(self) -> RawFd {
self.device.into_raw_fd()
}
}
impl LoopDevice {
/// Opens a loop device.
pub fn open<P: AsRef<Path>>(dev: P) -> io::Result<Self> {
// TODO create dev if it does not exist and begins with LOOP_PREFIX
Ok(Self {
device: OpenOptions::new().read(true).write(true).open(dev)?,
})
}
/// Attach the loop device to a file with given options.
///
/// # Examples
///
/// Attach the device to a file.
///
/// ```rust
/// use loopdev::LoopDevice;
/// let mut ld = LoopDevice::open("/dev/loop3").unwrap();
/// ld.with().part_scan(true).attach("disk.img").unwrap();
/// # ld.detach().unwrap();
/// ```
pub fn with(&self) -> AttachOptions<'_> {
AttachOptions {
device: self,
info: Default::default(),
#[cfg(feature = "direct_io")]
direct_io: false,
}
}
/// Attach the loop device to a file that maps to the whole file.
///
/// # Examples
///
/// Attach the device to a file.
///
/// ```rust
/// use loopdev::LoopDevice;
/// let ld = LoopDevice::open("/dev/loop4").unwrap();
/// ld.attach_file("disk.img").unwrap();
/// # ld.detach().unwrap();
/// ```
pub fn attach_file<P: AsRef<Path>>(&self, backing_file: P) -> io::Result<()> {
let info = loop_info64 {
..Default::default()
};
Self::attach_with_loop_info(self, backing_file, info)
}
/// Attach the loop device to a file with loop_info64.
fn attach_with_loop_info(
&self, // TODO should be mut? - but changing it is a breaking change
backing_file: impl AsRef<Path>,
info: loop_info64,
) -> io::Result<()> {
let write_access = (info.lo_flags & LO_FLAGS_READ_ONLY) == 0;
let bf = OpenOptions::new()
.read(true)
.write(write_access)
.open(backing_file)?;
self.attach_fd_with_loop_info(bf, info)
}
/// Attach the loop device to a fd with loop_info.
fn attach_fd_with_loop_info(&self, bf: impl AsRawFd, info: loop_info64) -> io::Result<()> {
// Attach the file
ioctl_to_error(unsafe {
ioctl(
self.device.as_raw_fd() as c_int,
LOOP_SET_FD as IoctlRequest,
bf.as_raw_fd() as c_int,
)
})?;
let result = unsafe {
ioctl(
self.device.as_raw_fd() as c_int,
LOOP_SET_STATUS64 as IoctlRequest,
&info,
)
};
match ioctl_to_error(result) {
Err(err) => {
// Ignore the error to preserve the original error
let _ = self.detach();
Err(err)
}
Ok(_) => Ok(()),
}
}
/// Get the path of the loop device.
pub fn path(&self) -> Option<PathBuf> {
let mut p = PathBuf::from("/proc/self/fd");
p.push(self.device.as_raw_fd().to_string());
std::fs::read_link(&p).ok()
}
/// Get the device major number
pub fn major(&self) -> io::Result<u32> {
self.device
.metadata()
.map(|m| unsafe { libc::major(m.rdev()) as u32 })
}
/// Get the device major number
pub fn minor(&self) -> io::Result<u32> {
self.device
.metadata()
.map(|m| unsafe { libc::minor(m.rdev()) as u32 })
}
/// Detach a loop device from its backing file.
///
/// Note that the device won't fully detach until a short delay after the underling device file
/// gets closed. This happens when LoopDev goes out of scope so you should ensure the LoopDev
/// lives for a short a time as possible.
///
/// # Examples
///
/// ```rust
/// use loopdev::LoopDevice;
/// let ld = LoopDevice::open("/dev/loop5").unwrap();
/// # ld.attach_file("disk.img").unwrap();
/// ld.detach().unwrap();
/// ```
pub fn detach(&self) -> io::Result<()> {
ioctl_to_error(unsafe {
ioctl(
self.device.as_raw_fd() as c_int,
LOOP_CLR_FD as IoctlRequest,
0,
)
})?;
Ok(())
}
/// Resize a live loop device. If the size of the backing file changes this can be called to
/// inform the loop driver about the new size.
pub fn set_capacity(&self) -> io::Result<()> {
ioctl_to_error(unsafe {
ioctl(
self.device.as_raw_fd() as c_int,
LOOP_SET_CAPACITY as IoctlRequest,
0,
)
})?;
Ok(())
}
// Enable or disable direct I/O for the backing file.
#[cfg(feature = "direct_io")]
pub fn set_direct_io(&self, direct_io: bool) -> io::Result<()> {
ioctl_to_error(unsafe {
ioctl(
self.device.as_raw_fd() as c_int,
LOOP_SET_DIRECT_IO as IoctlRequest,
if direct_io { 1 } else { 0 },
)
})?;
Ok(())
}
}
/// Used to set options when attaching a device. Created with [LoopDevice::with()].
///
/// # Examples
///
/// Enable partition scanning on attach:
///
/// ```rust
/// use loopdev::LoopDevice;
/// let mut ld = LoopDevice::open("/dev/loop6").unwrap();
/// ld.with()
/// .part_scan(true)
/// .attach("disk.img")
/// .unwrap();
/// # ld.detach().unwrap();
/// ```
///
/// A 1MiB slice of the file located at 1KiB into the file.
///
/// ```rust
/// use loopdev::LoopDevice;
/// let mut ld = LoopDevice::open("/dev/loop7").unwrap();
/// ld.with()
/// .offset(1024*1024)
/// .size_limit(1024*1024*1024)
/// .attach("disk.img")
/// .unwrap();
/// # ld.detach().unwrap();
/// ```
pub struct AttachOptions<'d> {
device: &'d LoopDevice,
info: loop_info64,
#[cfg(feature = "direct_io")]
direct_io: bool,
}
impl AttachOptions<'_> {
/// Offset in bytes from the start of the backing file the data will start at.
pub fn offset(mut self, offset: u64) -> Self {
self.info.lo_offset = offset;
self
}
/// Maximum size of the data in bytes.
pub fn size_limit(mut self, size_limit: u64) -> Self {
self.info.lo_sizelimit = size_limit;
self
}
/// Set read only flag
pub fn read_only(mut self, read_only: bool) -> Self {
if read_only {
self.info.lo_flags |= LO_FLAGS_READ_ONLY;
} else {
self.info.lo_flags &= !LO_FLAGS_READ_ONLY;
}
self
}
/// Set autoclear flag
pub fn autoclear(mut self, read_only: bool) -> Self {
if read_only {
self.info.lo_flags |= LO_FLAGS_AUTOCLEAR;
} else {
self.info.lo_flags &= !LO_FLAGS_AUTOCLEAR;
}
self
}
// Enable or disable direct I/O for the backing file.
#[cfg(feature = "direct_io")]
pub fn set_direct_io(mut self, direct_io: bool) -> Self {
self.direct_io = direct_io;
self
}
/// Force the kernel to scan the partition table on a newly created loop device. Note that the
/// partition table parsing depends on sector sizes. The default is sector size is 512 bytes
pub fn part_scan(mut self, enable: bool) -> Self {
if enable {
self.info.lo_flags |= 1 << 4;
} else {
self.info.lo_flags &= u32::max_value() - (1 << 4);
}
self
}
/// Attach the loop device to a file with the set options.
pub fn attach(self, backing_file: impl AsRef<Path>) -> io::Result<()> {
self.device.attach_with_loop_info(backing_file, self.info)?;
#[cfg(feature = "direct_io")]
if self.direct_io {
self.device.set_direct_io(self.direct_io)?;
}
Ok(())
}
/// Attach the loop device to an fd
pub fn attach_fd(self, backing_file_fd: impl AsRawFd) -> io::Result<()> {
self.device
.attach_fd_with_loop_info(backing_file_fd, self.info)?;
#[cfg(feature = "direct_io")]
if self.direct_io {
self.device.set_direct_io(self.direct_io)?;
}
Ok(())
}
}
fn ioctl_to_error(ret: i32) -> io::Result<i32> {
if ret < 0 {
Err(io::Error::last_os_error())
} else {
Ok(ret)
}
}