| 1 | //! Unsafe `ioctl` API. |
| 2 | //! |
| 3 | //! Unix systems expose a number of `ioctl`'s. `ioctl`s have been adopted as a |
| 4 | //! general purpose system call for making calls into the kernel. In addition |
| 5 | //! to the wide variety of system calls that are included by default in the |
| 6 | //! kernel, many drivers expose their own `ioctl`'s for controlling their |
| 7 | //! behavior, some of which are proprietary. Therefore it is impossible to make |
| 8 | //! a safe interface for every `ioctl` call, as they all have wildly varying |
| 9 | //! semantics. |
| 10 | //! |
| 11 | //! This module provides an unsafe interface to write your own `ioctl` API. To |
| 12 | //! start, create a type that implements [`Ioctl`]. Then, pass it to [`ioctl`] |
| 13 | //! to make the `ioctl` call. |
| 14 | |
| 15 | #![allow (unsafe_code)] |
| 16 | |
| 17 | use crate::fd::{AsFd, BorrowedFd}; |
| 18 | use crate::ffi as c; |
| 19 | use crate::io::Result; |
| 20 | |
| 21 | #[cfg (any(linux_kernel, bsd))] |
| 22 | use core::mem; |
| 23 | |
| 24 | pub use patterns::*; |
| 25 | |
| 26 | mod patterns; |
| 27 | |
| 28 | #[cfg (linux_kernel)] |
| 29 | mod linux; |
| 30 | |
| 31 | #[cfg (bsd)] |
| 32 | mod bsd; |
| 33 | |
| 34 | #[cfg (linux_kernel)] |
| 35 | use linux as platform; |
| 36 | |
| 37 | #[cfg (bsd)] |
| 38 | use bsd as platform; |
| 39 | |
| 40 | /// Perform an `ioctl` call. |
| 41 | /// |
| 42 | /// `ioctl` was originally intended to act as a way of modifying the behavior |
| 43 | /// of files, but has since been adopted as a general purpose system call for |
| 44 | /// making calls into the kernel. In addition to the default calls exposed by |
| 45 | /// generic file descriptors, many drivers expose their own `ioctl` calls for |
| 46 | /// controlling their behavior, some of which are proprietary. |
| 47 | /// |
| 48 | /// This crate exposes many other `ioctl` interfaces with safe and idiomatic |
| 49 | /// wrappers, like [`ioctl_fionbio`] and [`ioctl_fionread`]. It is recommended |
| 50 | /// to use those instead of this function, as they are safer and more |
| 51 | /// idiomatic. For other cases, implement the [`Ioctl`] API and pass it to this |
| 52 | /// function. |
| 53 | /// |
| 54 | /// See documentation for [`Ioctl`] for more information. |
| 55 | /// |
| 56 | /// [`ioctl_fionbio`]: crate::io::ioctl_fionbio |
| 57 | /// [`ioctl_fionread`]: crate::io::ioctl_fionread |
| 58 | /// |
| 59 | /// # Safety |
| 60 | /// |
| 61 | /// While [`Ioctl`] takes much of the unsafety out of `ioctl` calls, callers |
| 62 | /// must still ensure that the opcode value, operand type, and data access |
| 63 | /// correctly reflect what's in the device driver servicing the call. `ioctl` |
| 64 | /// calls form a protocol between the userspace `ioctl` callers and the device |
| 65 | /// drivers in the kernel, and safety depends on both sides agreeing and |
| 66 | /// upholding the expectations of the other. |
| 67 | /// |
| 68 | /// And, `ioctl` calls can read and write arbitrary memory and have arbitrary |
| 69 | /// side effects. Callers must ensure that any memory accesses and side effects |
| 70 | /// are compatible with Rust language invariants. |
| 71 | /// |
| 72 | /// # References |
| 73 | /// - [Linux] |
| 74 | /// - [Winsock] |
| 75 | /// - [FreeBSD] |
| 76 | /// - [NetBSD] |
| 77 | /// - [OpenBSD] |
| 78 | /// - [Apple] |
| 79 | /// - [Solaris] |
| 80 | /// - [illumos] |
| 81 | /// |
| 82 | /// [Linux]: https://man7.org/linux/man-pages/man2/ioctl.2.html |
| 83 | /// [Winsock]: https://learn.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-ioctlsocket |
| 84 | /// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=ioctl&sektion=2 |
| 85 | /// [NetBSD]: https://man.netbsd.org/ioctl.2 |
| 86 | /// [OpenBSD]: https://man.openbsd.org/ioctl.2 |
| 87 | /// [Apple]: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/ioctl.2.html |
| 88 | /// [Solaris]: https://docs.oracle.com/cd/E23824_01/html/821-1463/ioctl-2.html |
| 89 | /// [illumos]: https://illumos.org/man/2/ioctl |
| 90 | #[inline ] |
| 91 | pub unsafe fn ioctl<F: AsFd, I: Ioctl>(fd: F, mut ioctl: I) -> Result<I::Output> { |
| 92 | let fd: BorrowedFd<'_> = fd.as_fd(); |
| 93 | let request = ioctl.opcode(); |
| 94 | let arg: *mut c_void = ioctl.as_ptr(); |
| 95 | |
| 96 | // SAFETY: The variant of `Ioctl` asserts that this is a valid IOCTL call |
| 97 | // to make. |
| 98 | let output: as Try>::Output = if I::IS_MUTATING { |
| 99 | _ioctl(fd, request, arg)? |
| 100 | } else { |
| 101 | _ioctl_readonly(fd, request, arg)? |
| 102 | }; |
| 103 | |
| 104 | // SAFETY: The variant of `Ioctl` asserts that this is a valid pointer to |
| 105 | // the output data. |
| 106 | I::output_from_ptr(out:output, extract_output:arg) |
| 107 | } |
| 108 | |
| 109 | unsafe fn _ioctl(fd: BorrowedFd<'_>, request: Opcode, arg: *mut c::c_void) -> Result<IoctlOutput> { |
| 110 | crate::backend::io::syscalls::ioctl(fd, request, arg) |
| 111 | } |
| 112 | |
| 113 | unsafe fn _ioctl_readonly( |
| 114 | fd: BorrowedFd<'_>, |
| 115 | request: Opcode, |
| 116 | arg: *mut c::c_void, |
| 117 | ) -> Result<IoctlOutput> { |
| 118 | crate::backend::io::syscalls::ioctl_readonly(fd, request, arg) |
| 119 | } |
| 120 | |
| 121 | /// A trait defining the properties of an `ioctl` command. |
| 122 | /// |
| 123 | /// Objects implementing this trait can be passed to [`ioctl`] to make an |
| 124 | /// `ioctl` call. The contents of the object represent the inputs to the |
| 125 | /// `ioctl` call. The inputs must be convertible to a pointer through the |
| 126 | /// `as_ptr` method. In most cases, this involves either casting a number to a |
| 127 | /// pointer, or creating a pointer to the actual data. The latter case is |
| 128 | /// necessary for `ioctl` calls that modify userspace data. |
| 129 | /// |
| 130 | /// # Safety |
| 131 | /// |
| 132 | /// This trait is unsafe to implement because it is impossible to guarantee |
| 133 | /// that the `ioctl` call is safe. The `ioctl` call may be proprietary, or it |
| 134 | /// may be unsafe to call in certain circumstances. |
| 135 | /// |
| 136 | /// By implementing this trait, you guarantee that: |
| 137 | /// |
| 138 | /// - The `ioctl` call expects the input provided by `as_ptr` and produces the |
| 139 | /// output as indicated by `output`. |
| 140 | /// - That `output_from_ptr` can safely take the pointer from `as_ptr` and |
| 141 | /// cast it to the correct type, *only* after the `ioctl` call. |
| 142 | /// - That the return value of `opcode` uniquely identifies the `ioctl` call. |
| 143 | /// - That, for whatever platforms you are targeting, the `ioctl` call is safe |
| 144 | /// to make. |
| 145 | /// - If `IS_MUTATING` is false, that no userspace data will be modified by |
| 146 | /// the `ioctl` call. |
| 147 | pub unsafe trait Ioctl { |
| 148 | /// The type of the output data. |
| 149 | /// |
| 150 | /// Given a pointer, one should be able to construct an instance of this |
| 151 | /// type. |
| 152 | type Output; |
| 153 | |
| 154 | /// Does the `ioctl` mutate any data in the userspace? |
| 155 | /// |
| 156 | /// If the `ioctl` call does not mutate any data in the userspace, then |
| 157 | /// making this `false` enables optimizations that can make the call |
| 158 | /// faster. When in doubt, set this to `true`. |
| 159 | /// |
| 160 | /// # Safety |
| 161 | /// |
| 162 | /// This should only be set to `false` if the `ioctl` call does not mutate |
| 163 | /// any data in the userspace. Undefined behavior may occur if this is set |
| 164 | /// to `false` when it should be `true`. |
| 165 | const IS_MUTATING: bool; |
| 166 | |
| 167 | /// Get the opcode used by this `ioctl` command. |
| 168 | /// |
| 169 | /// There are different types of opcode depending on the operation. See |
| 170 | /// documentation for [`opcode`] for more information. |
| 171 | fn opcode(&self) -> Opcode; |
| 172 | |
| 173 | /// Get a pointer to the data to be passed to the `ioctl` command. |
| 174 | /// |
| 175 | /// See trait-level documentation for more information. |
| 176 | fn as_ptr(&mut self) -> *mut c::c_void; |
| 177 | |
| 178 | /// Cast the output data to the correct type. |
| 179 | /// |
| 180 | /// # Safety |
| 181 | /// |
| 182 | /// The `extract_output` value must be the resulting value after a |
| 183 | /// successful `ioctl` call, and `out` is the direct return value of an |
| 184 | /// `ioctl` call that did not fail. In this case `extract_output` is the |
| 185 | /// pointer that was passed to the `ioctl` call. |
| 186 | unsafe fn output_from_ptr( |
| 187 | out: IoctlOutput, |
| 188 | extract_output: *mut c::c_void, |
| 189 | ) -> Result<Self::Output>; |
| 190 | } |
| 191 | |
| 192 | /// Const functions for computing opcode values. |
| 193 | /// |
| 194 | /// Linux's headers define macros such as `_IO`, `_IOR`, `_IOW`, and `_IOWR` |
| 195 | /// for defining ioctl values in a structured way that encode whether they |
| 196 | /// are reading and/or writing, and other information about the ioctl. The |
| 197 | /// functions in this module correspond to those macros. |
| 198 | /// |
| 199 | /// If you're writing a driver and defining your own ioctl numbers, it's |
| 200 | /// recommended to use these functions to compute them. |
| 201 | #[cfg (any(linux_kernel, bsd))] |
| 202 | pub mod opcode { |
| 203 | use super::*; |
| 204 | |
| 205 | /// Create a new opcode from a direction, group, number, and size. |
| 206 | /// |
| 207 | /// This corresponds to the C macro `_IOC(direction, group, number, size)` |
| 208 | #[doc (alias = "_IOC" )] |
| 209 | #[inline ] |
| 210 | pub const fn from_components( |
| 211 | direction: Direction, |
| 212 | group: u8, |
| 213 | number: u8, |
| 214 | data_size: usize, |
| 215 | ) -> Opcode { |
| 216 | assert!(data_size <= Opcode::MAX as usize, "data size is too large" ); |
| 217 | |
| 218 | platform::compose_opcode( |
| 219 | direction, |
| 220 | group as Opcode, |
| 221 | number as Opcode, |
| 222 | data_size as Opcode, |
| 223 | ) |
| 224 | } |
| 225 | |
| 226 | /// Create a new opcode from a group, a number, that uses no data. |
| 227 | /// |
| 228 | /// This corresponds to the C macro `_IO(group, number)`. |
| 229 | #[doc (alias = "_IO" )] |
| 230 | #[inline ] |
| 231 | pub const fn none(group: u8, number: u8) -> Opcode { |
| 232 | from_components(Direction::None, group, number, 0) |
| 233 | } |
| 234 | |
| 235 | /// Create a new reading opcode from a group, a number and the type of |
| 236 | /// data. |
| 237 | /// |
| 238 | /// This corresponds to the C macro `_IOR(group, number, T)`. |
| 239 | #[doc (alias = "_IOR" )] |
| 240 | #[inline ] |
| 241 | pub const fn read<T>(group: u8, number: u8) -> Opcode { |
| 242 | from_components(Direction::Read, group, number, mem::size_of::<T>()) |
| 243 | } |
| 244 | |
| 245 | /// Create a new writing opcode from a group, a number and the type of |
| 246 | /// data. |
| 247 | /// |
| 248 | /// This corresponds to the C macro `_IOW(group, number, T)`. |
| 249 | #[doc (alias = "_IOW" )] |
| 250 | #[inline ] |
| 251 | pub const fn write<T>(group: u8, number: u8) -> Opcode { |
| 252 | from_components(Direction::Write, group, number, mem::size_of::<T>()) |
| 253 | } |
| 254 | |
| 255 | /// Create a new reading and writing opcode from a group, a number and the |
| 256 | /// type of data. |
| 257 | /// |
| 258 | /// This corresponds to the C macro `_IOWR(group, number, T)`. |
| 259 | #[doc (alias = "_IOWR" )] |
| 260 | #[inline ] |
| 261 | pub const fn read_write<T>(group: u8, number: u8) -> Opcode { |
| 262 | from_components(Direction::ReadWrite, group, number, mem::size_of::<T>()) |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | /// The direction that an `ioctl` is going. |
| 267 | /// |
| 268 | /// The direction is relative to userspace: `Read` means reading data from the |
| 269 | /// kernel, and `Write` means the kernel writing data to userspace. |
| 270 | #[derive (Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] |
| 271 | pub enum Direction { |
| 272 | /// None of the above. |
| 273 | None, |
| 274 | |
| 275 | /// Read data from the kernel. |
| 276 | Read, |
| 277 | |
| 278 | /// Write data to the kernel. |
| 279 | Write, |
| 280 | |
| 281 | /// Read and write data to the kernel. |
| 282 | ReadWrite, |
| 283 | } |
| 284 | |
| 285 | /// The type used by the `ioctl` to signify the output. |
| 286 | pub type IoctlOutput = c::c_int; |
| 287 | |
| 288 | /// The type used by the `ioctl` to signify the command. |
| 289 | pub type Opcode = _Opcode; |
| 290 | |
| 291 | // Under raw Linux, this is an `unsigned int`. |
| 292 | #[cfg (linux_raw)] |
| 293 | type _Opcode = c::c_uint; |
| 294 | |
| 295 | // On libc Linux with GNU libc or uclibc, this is an `unsigned long`. |
| 296 | #[cfg (all( |
| 297 | not(linux_raw), |
| 298 | target_os = "linux" , |
| 299 | any(target_env = "gnu" , target_env = "uclibc" ) |
| 300 | ))] |
| 301 | type _Opcode = c::c_ulong; |
| 302 | |
| 303 | // Musl uses `c_int`. |
| 304 | #[cfg (all( |
| 305 | not(linux_raw), |
| 306 | target_os = "linux" , |
| 307 | not(target_env = "gnu" ), |
| 308 | not(target_env = "uclibc" ) |
| 309 | ))] |
| 310 | type _Opcode = c::c_int; |
| 311 | |
| 312 | // Android uses `c_int`. |
| 313 | #[cfg (all(not(linux_raw), target_os = "android" ))] |
| 314 | type _Opcode = c::c_int; |
| 315 | |
| 316 | // BSD, Haiku, Hurd, Redox, and Vita use `unsigned long`. |
| 317 | #[cfg (any( |
| 318 | bsd, |
| 319 | target_os = "redox" , |
| 320 | target_os = "haiku" , |
| 321 | target_os = "horizon" , |
| 322 | target_os = "hurd" , |
| 323 | target_os = "vita" |
| 324 | ))] |
| 325 | type _Opcode = c::c_ulong; |
| 326 | |
| 327 | // AIX, Emscripten, Fuchsia, Solaris, and WASI use a `int`. |
| 328 | #[cfg (any( |
| 329 | solarish, |
| 330 | target_os = "aix" , |
| 331 | target_os = "cygwin" , |
| 332 | target_os = "fuchsia" , |
| 333 | target_os = "emscripten" , |
| 334 | target_os = "nto" , |
| 335 | target_os = "wasi" , |
| 336 | ))] |
| 337 | type _Opcode = c::c_int; |
| 338 | |
| 339 | // ESP-IDF uses a `c_uint`. |
| 340 | #[cfg (target_os = "espidf" )] |
| 341 | type _Opcode = c::c_uint; |
| 342 | |
| 343 | // Windows has `ioctlsocket`, which uses `i32`. |
| 344 | #[cfg (windows)] |
| 345 | type _Opcode = i32; |
| 346 | |
| 347 | #[cfg (linux_kernel)] |
| 348 | #[cfg (not(any(target_arch = "sparc" , target_arch = "sparc64" )))] |
| 349 | #[cfg (test)] |
| 350 | mod tests { |
| 351 | use super::*; |
| 352 | |
| 353 | #[test ] |
| 354 | fn test_opcode_funcs() { |
| 355 | // `TUNGETDEVNETNS` is defined as `_IO('T', 227)`. |
| 356 | assert_eq!( |
| 357 | linux_raw_sys::ioctl::TUNGETDEVNETNS as Opcode, |
| 358 | opcode::none(b'T' , 227) |
| 359 | ); |
| 360 | // `FS_IOC_GETVERSION` is defined as `_IOR('v', 1, long)`. |
| 361 | assert_eq!( |
| 362 | linux_raw_sys::ioctl::FS_IOC_GETVERSION as Opcode, |
| 363 | opcode::read::<c::c_long>(b'v' , 1) |
| 364 | ); |
| 365 | // `TUNSETNOCSUM` is defined as `_IOW('T', 200, int)`. |
| 366 | assert_eq!( |
| 367 | linux_raw_sys::ioctl::TUNSETNOCSUM as Opcode, |
| 368 | opcode::write::<c::c_int>(b'T' , 200) |
| 369 | ); |
| 370 | // `FIFREEZE` is defined as `_IOWR('X', 119, int)`. |
| 371 | assert_eq!( |
| 372 | linux_raw_sys::ioctl::FIFREEZE as Opcode, |
| 373 | opcode::read_write::<c::c_int>(b'X' , 119) |
| 374 | ); |
| 375 | } |
| 376 | } |
| 377 | |