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