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 if data_size > RawOpcode::MAX as usize {
221 panic!("data size is too large");
222 }
223
224 Self::old(platform::compose_opcode(
225 direction,
226 group as RawOpcode,
227 number as RawOpcode,
228 data_size as RawOpcode,
229 ))
230 }
231
232 /// Create a new non-mutating opcode from a group, a number, and the type
233 /// of data.
234 ///
235 /// This corresponds to the C macro `_IO(group, number)` when `T` is zero
236 /// sized.
237 #[cfg(any(linux_kernel, bsd))]
238 #[inline]
239 pub const fn none<T>(group: u8, number: u8) -> Self {
240 Self::from_components(Direction::None, group, number, mem::size_of::<T>())
241 }
242
243 /// Create a new reading opcode from a group, a number and the type of
244 /// data.
245 ///
246 /// This corresponds to the C macro `_IOR(group, number, T)`.
247 #[cfg(any(linux_kernel, bsd))]
248 #[inline]
249 pub const fn read<T>(group: u8, number: u8) -> Self {
250 Self::from_components(Direction::Read, group, number, mem::size_of::<T>())
251 }
252
253 /// Create a new writing opcode from a group, a number and the type of
254 /// data.
255 ///
256 /// This corresponds to the C macro `_IOW(group, number, T)`.
257 #[cfg(any(linux_kernel, bsd))]
258 #[inline]
259 pub const fn write<T>(group: u8, number: u8) -> Self {
260 Self::from_components(Direction::Write, group, number, mem::size_of::<T>())
261 }
262
263 /// Create a new reading and writing opcode from a group, a number and the
264 /// type of data.
265 ///
266 /// This corresponds to the C macro `_IOWR(group, number, T)`.
267 #[cfg(any(linux_kernel, bsd))]
268 #[inline]
269 pub const fn read_write<T>(group: u8, number: u8) -> Self {
270 Self::from_components(Direction::ReadWrite, group, number, mem::size_of::<T>())
271 }
272
273 /// Get the raw opcode.
274 #[inline]
275 pub fn raw(self) -> RawOpcode {
276 self.raw
277 }
278}
279
280/// The direction that an `ioctl` is going.
281///
282/// Note that this is relative to userspace. `Read` means reading data from the
283/// kernel, and write means the kernel writing data to userspace.
284#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
285pub enum Direction {
286 /// None of the above.
287 None,
288
289 /// Read data from the kernel.
290 Read,
291
292 /// Write data to the kernel.
293 Write,
294
295 /// Read and write data to the kernel.
296 ReadWrite,
297}
298
299/// The type used by the `ioctl` to signify the output.
300pub type IoctlOutput = c::c_int;
301
302/// The type used by the `ioctl` to signify the command.
303pub type RawOpcode = _RawOpcode;
304
305// Under raw Linux, this is an `unsigned int`.
306#[cfg(linux_raw)]
307type _RawOpcode = c::c_uint;
308
309// On libc Linux with GNU libc or uclibc, this is an `unsigned long`.
310#[cfg(all(
311 not(linux_raw),
312 target_os = "linux",
313 any(target_env = "gnu", target_env = "uclibc")
314))]
315type _RawOpcode = c::c_ulong;
316
317// Musl uses `c_int`.
318#[cfg(all(
319 not(linux_raw),
320 target_os = "linux",
321 not(target_env = "gnu"),
322 not(target_env = "uclibc")
323))]
324type _RawOpcode = c::c_int;
325
326// Android uses `c_int`.
327#[cfg(all(not(linux_raw), target_os = "android"))]
328type _RawOpcode = c::c_int;
329
330// BSD, Haiku, Hurd, Redox, and Vita use `unsigned long`.
331#[cfg(any(
332 bsd,
333 target_os = "redox",
334 target_os = "haiku",
335 target_os = "hurd",
336 target_os = "vita"
337))]
338type _RawOpcode = c::c_ulong;
339
340// AIX, Emscripten, Fuchsia, Solaris, and WASI use a `int`.
341#[cfg(any(
342 solarish,
343 target_os = "aix",
344 target_os = "fuchsia",
345 target_os = "emscripten",
346 target_os = "wasi",
347 target_os = "nto"
348))]
349type _RawOpcode = c::c_int;
350
351// ESP-IDF uses a `c_uint`.
352#[cfg(target_os = "espidf")]
353type _RawOpcode = c::c_uint;
354
355// Windows has `ioctlsocket`, which uses `i32`.
356#[cfg(windows)]
357type _RawOpcode = i32;
358