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///
69/// - [Linux]
70/// - [WinSock2]
71/// - [FreeBSD]
72/// - [NetBSD]
73/// - [OpenBSD]
74/// - [Apple]
75/// - [Solaris]
76/// - [illumos]
77///
78/// [Linux]: https://man7.org/linux/man-pages/man2/ioctl.2.html
79/// [Winsock2]: https://learn.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-ioctlsocket
80/// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=ioctl&sektion=2
81/// [NetBSD]: https://man.netbsd.org/ioctl.2
82/// [OpenBSD]: https://man.openbsd.org/ioctl.2
83/// [Apple]: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/ioctl.2.html
84/// [Solaris]: https://docs.oracle.com/cd/E23824_01/html/821-1463/ioctl-2.html
85/// [illumos]: https://illumos.org/man/2/ioctl
86#[inline]
87pub unsafe fn ioctl<F: AsFd, I: Ioctl>(fd: F, mut ioctl: I) -> Result<I::Output> {
88 let fd = fd.as_fd();
89 let request = I::OPCODE.raw();
90 let arg = ioctl.as_ptr();
91
92 // SAFETY: The variant of `Ioctl` asserts that this is a valid IOCTL call
93 // to make.
94 let output = if I::IS_MUTATING {
95 _ioctl(fd, request, arg)?
96 } else {
97 _ioctl_readonly(fd, request, arg)?
98 };
99
100 // SAFETY: The variant of `Ioctl` asserts that this is a valid pointer to
101 // the output data.
102 I::output_from_ptr(output, arg)
103}
104
105unsafe fn _ioctl(
106 fd: BorrowedFd<'_>,
107 request: RawOpcode,
108 arg: *mut c::c_void,
109) -> Result<IoctlOutput> {
110 crate::backend::io::syscalls::ioctl(fd, request, arg)
111}
112
113unsafe fn _ioctl_readonly(
114 fd: BorrowedFd<'_>,
115 request: RawOpcode,
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 cast
141/// it to the correct type, *only* after the `ioctl` call.
142/// - That `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 the
146/// `ioctl` call.
147pub 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 /// The opcode used by this `ioctl` command.
155 ///
156 /// There are different types of opcode depending on the operation. See
157 /// documentation for the [`Opcode`] struct for more information.
158 const OPCODE: Opcode;
159
160 /// Does the `ioctl` mutate any data in the userspace?
161 ///
162 /// If the `ioctl` call does not mutate any data in the userspace, then
163 /// making this `false` enables optimizations that can make the call
164 /// faster. When in doubt, set this to `true`.
165 ///
166 /// # Safety
167 ///
168 /// This should only be set to `false` if the `ioctl` call does not mutate
169 /// any data in the userspace. Undefined behavior may occur if this is set
170 /// to `false` when it should be `true`.
171 const IS_MUTATING: bool;
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/// The opcode used by an `Ioctl`.
193#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
194pub struct Opcode {
195 /// The raw opcode.
196 raw: RawOpcode,
197}
198
199impl Opcode {
200 /// Create a new old `Opcode` from a raw opcode.
201 ///
202 /// Rather than being a composition of several attributes, old opcodes are
203 /// just numbers. In general most drivers follow stricter conventions, but
204 /// older drivers may still use this strategy.
205 #[inline]
206 pub const fn old(raw: RawOpcode) -> Self {
207 Self { raw }
208 }
209
210 /// Create a new opcode from a direction, group, number, and size.
211 ///
212 /// This corresponds to the C macro `_IOC(direction, group, number, size)`
213 #[cfg(any(linux_kernel, bsd))]
214 #[inline]
215 pub const fn from_components(
216 direction: Direction,
217 group: u8,
218 number: u8,
219 data_size: usize,
220 ) -> Self {
221 if data_size > RawOpcode::MAX as usize {
222 panic!("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 = "hurd",
337 target_os = "vita"
338))]
339type _RawOpcode = c::c_ulong;
340
341// AIX, Emscripten, Fuchsia, Solaris, and WASI use a `int`.
342#[cfg(any(
343 solarish,
344 target_os = "aix",
345 target_os = "fuchsia",
346 target_os = "emscripten",
347 target_os = "wasi",
348 target_os = "nto"
349))]
350type _RawOpcode = c::c_int;
351
352// ESP-IDF uses a `c_uint`.
353#[cfg(target_os = "espidf")]
354type _RawOpcode = c::c_uint;
355
356// Windows has `ioctlsocket`, which uses `i32`.
357#[cfg(windows)]
358type _RawOpcode = i32;