rustix/ioctl/
mod.rs

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
17use crate::backend::c;
18use crate::fd::{AsFd, BorrowedFd};
19use crate::io::Result;
20
21#[cfg(any(linux_kernel, bsd))]
22use core::mem;
23
24pub use patterns::*;
25
26mod patterns;
27
28#[cfg(linux_kernel)]
29mod linux;
30
31#[cfg(bsd)]
32mod bsd;
33
34#[cfg(linux_kernel)]
35use linux as platform;
36
37#[cfg(bsd)]
38use 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, it is
62/// still unsafe to call this code with arbitrary device drivers, as it is up
63/// to the device driver to implement the `ioctl` call correctly. It is on the
64/// onus of the protocol between the user and the driver to ensure that the
65/// `ioctl` call is safe to make.
66///
67/// # References
68///  - [Linux]
69///  - [Winsock]
70///  - [FreeBSD]
71///  - [NetBSD]
72///  - [OpenBSD]
73///  - [Apple]
74///  - [Solaris]
75///  - [illumos]
76///
77/// [Linux]: https://man7.org/linux/man-pages/man2/ioctl.2.html
78/// [Winsock]: https://learn.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-ioctlsocket
79/// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=ioctl&sektion=2
80/// [NetBSD]: https://man.netbsd.org/ioctl.2
81/// [OpenBSD]: https://man.openbsd.org/ioctl.2
82/// [Apple]: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/ioctl.2.html
83/// [Solaris]: https://docs.oracle.com/cd/E23824_01/html/821-1463/ioctl-2.html
84/// [illumos]: https://illumos.org/man/2/ioctl
85#[inline]
86pub unsafe fn ioctl<F: AsFd, I: Ioctl>(fd: F, mut ioctl: I) -> Result<I::Output> {
87    let fd = fd.as_fd();
88    let request = I::OPCODE.raw();
89    let arg = ioctl.as_ptr();
90
91    // SAFETY: The variant of `Ioctl` asserts that this is a valid IOCTL call
92    // to make.
93    let output = if I::IS_MUTATING {
94        _ioctl(fd, request, arg)?
95    } else {
96        _ioctl_readonly(fd, request, arg)?
97    };
98
99    // SAFETY: The variant of `Ioctl` asserts that this is a valid pointer to
100    // the output data.
101    I::output_from_ptr(output, arg)
102}
103
104unsafe fn _ioctl(
105    fd: BorrowedFd<'_>,
106    request: RawOpcode,
107    arg: *mut c::c_void,
108) -> Result<IoctlOutput> {
109    crate::backend::io::syscalls::ioctl(fd, request, arg)
110}
111
112unsafe fn _ioctl_readonly(
113    fd: BorrowedFd<'_>,
114    request: RawOpcode,
115    arg: *mut c::c_void,
116) -> Result<IoctlOutput> {
117    crate::backend::io::syscalls::ioctl_readonly(fd, request, arg)
118}
119
120/// A trait defining the properties of an `ioctl` command.
121///
122/// Objects implementing this trait can be passed to [`ioctl`] to make an
123/// `ioctl` call. The contents of the object represent the inputs to the
124/// `ioctl` call. The inputs must be convertible to a pointer through the
125/// `as_ptr` method. In most cases, this involves either casting a number to a
126/// pointer, or creating a pointer to the actual data. The latter case is
127/// necessary for `ioctl` calls that modify userspace data.
128///
129/// # Safety
130///
131/// This trait is unsafe to implement because it is impossible to guarantee
132/// that the `ioctl` call is safe. The `ioctl` call may be proprietary, or it
133/// may be unsafe to call in certain circumstances.
134///
135/// By implementing this trait, you guarantee that:
136///
137/// - The `ioctl` call expects the input provided by `as_ptr` and produces the
138///   output as indicated by `output`.
139/// - That `output_from_ptr` can safely take the pointer from `as_ptr` and cast
140///   it to the correct type, *only* after the `ioctl` call.
141/// - That `OPCODE` uniquely identifies the `ioctl` call.
142/// - That, for whatever platforms you are targeting, the `ioctl` call is safe
143///   to make.
144/// - If `IS_MUTATING` is false, that no userspace data will be modified by the
145///   `ioctl` call.
146pub unsafe trait Ioctl {
147    /// The type of the output data.
148    ///
149    /// Given a pointer, one should be able to construct an instance of this
150    /// type.
151    type Output;
152
153    /// The opcode used by this `ioctl` command.
154    ///
155    /// There are different types of opcode depending on the operation. See
156    /// documentation for the [`Opcode`] struct for more information.
157    const OPCODE: Opcode;
158
159    /// Does the `ioctl` mutate any data in the userspace?
160    ///
161    /// If the `ioctl` call does not mutate any data in the userspace, then
162    /// making this `false` enables optimizations that can make the call
163    /// faster. When in doubt, set this to `true`.
164    ///
165    /// # Safety
166    ///
167    /// This should only be set to `false` if the `ioctl` call does not mutate
168    /// any data in the userspace. Undefined behavior may occur if this is set
169    /// to `false` when it should be `true`.
170    const IS_MUTATING: bool;
171
172    /// Get a pointer to the data to be passed to the `ioctl` command.
173    ///
174    /// See trait-level documentation for more information.
175    fn as_ptr(&mut self) -> *mut c::c_void;
176
177    /// Cast the output data to the correct type.
178    ///
179    /// # Safety
180    ///
181    /// The `extract_output` value must be the resulting value after a
182    /// successful `ioctl` call, and `out` is the direct return value of an
183    /// `ioctl` call that did not fail. In this case `extract_output` is the
184    /// pointer that was passed to the `ioctl` call.
185    unsafe fn output_from_ptr(
186        out: IoctlOutput,
187        extract_output: *mut c::c_void,
188    ) -> Result<Self::Output>;
189}
190
191/// The opcode used by an `Ioctl`.
192#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
193pub struct Opcode {
194    /// The raw opcode.
195    raw: RawOpcode,
196}
197
198impl Opcode {
199    /// Create a new old `Opcode` from a raw opcode.
200    ///
201    /// Rather than being a composition of several attributes, old opcodes are
202    /// just numbers. In general most drivers follow stricter conventions, but
203    /// older drivers may still use this strategy.
204    #[inline]
205    pub const fn old(raw: RawOpcode) -> Self {
206        Self { raw }
207    }
208
209    /// Create a new opcode from a direction, group, number, and size.
210    ///
211    /// This corresponds to the C macro `_IOC(direction, group, number, size)`
212    #[cfg(any(linux_kernel, bsd))]
213    #[inline]
214    pub const fn from_components(
215        direction: Direction,
216        group: u8,
217        number: u8,
218        data_size: usize,
219    ) -> Self {
220        assert!(
221            data_size <= RawOpcode::MAX as usize,
222            "data size is too large"
223        );
224
225        Self::old(platform::compose_opcode(
226            direction,
227            group as RawOpcode,
228            number as RawOpcode,
229            data_size as RawOpcode,
230        ))
231    }
232
233    /// Create a new non-mutating opcode from a group, a number, and the type
234    /// of data.
235    ///
236    /// This corresponds to the C macro `_IO(group, number)` when `T` is zero
237    /// sized.
238    #[cfg(any(linux_kernel, bsd))]
239    #[inline]
240    pub const fn none<T>(group: u8, number: u8) -> Self {
241        Self::from_components(Direction::None, group, number, mem::size_of::<T>())
242    }
243
244    /// Create a new reading opcode from a group, a number and the type of
245    /// data.
246    ///
247    /// This corresponds to the C macro `_IOR(group, number, T)`.
248    #[cfg(any(linux_kernel, bsd))]
249    #[inline]
250    pub const fn read<T>(group: u8, number: u8) -> Self {
251        Self::from_components(Direction::Read, group, number, mem::size_of::<T>())
252    }
253
254    /// Create a new writing opcode from a group, a number and the type of
255    /// data.
256    ///
257    /// This corresponds to the C macro `_IOW(group, number, T)`.
258    #[cfg(any(linux_kernel, bsd))]
259    #[inline]
260    pub const fn write<T>(group: u8, number: u8) -> Self {
261        Self::from_components(Direction::Write, group, number, mem::size_of::<T>())
262    }
263
264    /// Create a new reading and writing opcode from a group, a number and the
265    /// type of data.
266    ///
267    /// This corresponds to the C macro `_IOWR(group, number, T)`.
268    #[cfg(any(linux_kernel, bsd))]
269    #[inline]
270    pub const fn read_write<T>(group: u8, number: u8) -> Self {
271        Self::from_components(Direction::ReadWrite, group, number, mem::size_of::<T>())
272    }
273
274    /// Get the raw opcode.
275    #[inline]
276    pub fn raw(self) -> RawOpcode {
277        self.raw
278    }
279}
280
281/// The direction that an `ioctl` is going.
282///
283/// Note that this is relative to userspace. `Read` means reading data from the
284/// kernel, and write means the kernel writing data to userspace.
285#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
286pub enum Direction {
287    /// None of the above.
288    None,
289
290    /// Read data from the kernel.
291    Read,
292
293    /// Write data to the kernel.
294    Write,
295
296    /// Read and write data to the kernel.
297    ReadWrite,
298}
299
300/// The type used by the `ioctl` to signify the output.
301pub type IoctlOutput = c::c_int;
302
303/// The type used by the `ioctl` to signify the command.
304pub type RawOpcode = _RawOpcode;
305
306// Under raw Linux, this is an `unsigned int`.
307#[cfg(linux_raw)]
308type _RawOpcode = c::c_uint;
309
310// On libc Linux with GNU libc or uclibc, this is an `unsigned long`.
311#[cfg(all(
312    not(linux_raw),
313    target_os = "linux",
314    any(target_env = "gnu", target_env = "uclibc")
315))]
316type _RawOpcode = c::c_ulong;
317
318// Musl uses `c_int`.
319#[cfg(all(
320    not(linux_raw),
321    target_os = "linux",
322    not(target_env = "gnu"),
323    not(target_env = "uclibc")
324))]
325type _RawOpcode = c::c_int;
326
327// Android uses `c_int`.
328#[cfg(all(not(linux_raw), target_os = "android"))]
329type _RawOpcode = c::c_int;
330
331// BSD, Haiku, Hurd, Redox, and Vita use `unsigned long`.
332#[cfg(any(
333    bsd,
334    target_os = "redox",
335    target_os = "haiku",
336    target_os = "horizon",
337    target_os = "hurd",
338    target_os = "vita"
339))]
340type _RawOpcode = c::c_ulong;
341
342// AIX, Emscripten, Fuchsia, Solaris, and WASI use a `int`.
343#[cfg(any(
344    solarish,
345    target_os = "aix",
346    target_os = "fuchsia",
347    target_os = "emscripten",
348    target_os = "wasi",
349    target_os = "nto"
350))]
351type _RawOpcode = c::c_int;
352
353// ESP-IDF uses a `c_uint`.
354#[cfg(target_os = "espidf")]
355type _RawOpcode = c::c_uint;
356
357// Windows has `ioctlsocket`, which uses `i32`.
358#[cfg(windows)]
359type _RawOpcode = i32;