Debian Codegraph @

src/platform/linux_usbfs/hotplug.rs

raw symbols SCIP
1 use libc::{sockaddr, sockaddr_nl, socklen_t, AF_NETLINK, MSG_DONTWAIT};
2 use log::{debug, error, warn};
3 use rustix::{
4 fd::{AsFd, AsRawFd, OwnedFd},
5 net::{netlink, socket_with, AddressFamily, SocketFlags, SocketType},
6 };
7 use std::{
8 io::ErrorKind,
9 mem,
10 os::{raw::c_void, unix::prelude::BorrowedFd},
11 path::Path,
12 task::Poll,
13 };
14
15 use crate::{hotplug::HotplugEvent, Error};
16
17 use super::{enumeration::probe_device, events::Async, SysfsPath};
18
19 const UDEV_MAGIC: &[u8; 12] = b"libudev\0\xfe\xed\xca\xfe";
20 const UDEV_MULTICAST_GROUP: u32 = 1 << 1;
21
22 pub(crate) struct LinuxHotplugWatch {
23 fd: Async<OwnedFd>,
24 }
25
26 impl LinuxHotplugWatch {
27 pub(crate) fn new() -> Result<Self, Error> {
28 let fd = socket_with(
29 AddressFamily::NETLINK,
30 SocketType::RAW,
31 SocketFlags::CLOEXEC,
32 Some(netlink::KOBJECT_UEVENT),
33 )?;
34
35 unsafe {
36 // rustix doesn't support netlink yet (pending https://github.com/bytecodealliance/rustix/pull/1004)
37 // so use libc for now.
38 let mut addr: sockaddr_nl = mem::zeroed();
39 addr.nl_family = AF_NETLINK as u16;
40 addr.nl_groups = UDEV_MULTICAST_GROUP;
41 let r = libc::bind(
42 fd.as_raw_fd(),
43 &addr as *const sockaddr_nl as *const sockaddr,
44 mem::size_of_val(&addr) as socklen_t,
45 );
46 if r != 0 {
47 return Err(Error::last_os_error());
48 }
49 }
50
51 Ok(LinuxHotplugWatch {
52 fd: Async::new(fd)?,
53 })
54 }
55
56 pub(crate) fn poll_next(&mut self, cx: &mut std::task::Context<'_>) -> Poll<HotplugEvent> {
57 if let Some(event) = try_receive_event(self.fd.inner.as_fd()) {
58 return Poll::Ready(event);
59 }
60
61 if let Err(e) = self.fd.register(cx.waker()) {
62 log::error!("failed to register udev socket with epoll: {e}");
63 }
64
65 Poll::Pending
66 }
67 }
68
69 fn try_receive_event(fd: BorrowedFd) -> Option<HotplugEvent> {
70 let mut buf = [0; 8192];
71
72 let received = unsafe {
73 let mut addr: sockaddr_nl = mem::zeroed();
74 let mut addrlen: socklen_t = mem::size_of_val(&addr) as socklen_t;
75 let r = libc::recvfrom(
76 fd.as_raw_fd(),
77 buf.as_mut_ptr() as *mut c_void,
78 buf.len(),
79 MSG_DONTWAIT,
80 &mut addr as *mut sockaddr_nl as *mut sockaddr,
81 &mut addrlen,
82 );
83 if r >= 0 {
84 Ok((r as usize, addr.nl_groups))
85 } else {
86 Err(Error::last_os_error())
87 }
88 };
89
90 match received {
91 // udev messages will normally be sent to a multicast group, which only
92 // root can send to. Reject unicast messages that may be from anywhere.
93 Ok((size, groups)) if groups == UDEV_MULTICAST_GROUP => parse_packet(&buf[..size]),
94 Ok((_, src)) => {
95 warn!("udev netlink socket received message from {src:?}");
96 None
97 }
98 Err(e) if e.kind() == ErrorKind::WouldBlock => None,
99 Err(e) => {
100 error!("udev netlink socket recvfrom failed with {e}");
101 None
102 }
103 }
104 }
105
106 fn parse_packet(buf: &[u8]) -> Option<HotplugEvent> {
107 if buf.len() < 24 {
108 error!("packet too short: {buf:x?}");
109 return None;
110 }
111
112 if !buf.starts_with(UDEV_MAGIC) {
113 error!("packet does not start with expected header: {buf:x?}");
114 return None;
115 }
116
117 let properties_off = u32::from_ne_bytes(buf[16..20].try_into().unwrap()) as usize;
118 let properties_len = u32::from_ne_bytes(buf[20..24].try_into().unwrap()) as usize;
119 let Some(properties_buf) = buf.get(properties_off..properties_off + properties_len) else {
120 error!("properties offset={properties_off} length={properties_len} exceeds buffer length {len}", len = buf.len());
121 return None;
122 };
123
124 let mut is_add = None;
125 let mut busnum = None;
126 let mut devnum = None;
127 let mut devpath = None;
128
129 for (k, v) in parse_properties(properties_buf) {
130 debug!("uevent property {k} = {v}");
131 match k {
132 "SUBSYSTEM" if v != "usb" => return None,
133 "DEVTYPE" if v != "usb_device" => return None,
134 "ACTION" => {
135 is_add = Some(match v {
136 "add" => true,
137 "remove" => false,
138 _ => return None,
139 });
140 }
141 "BUSNUM" => {
142 busnum = v.parse::<u8>().ok();
143 }
144 "DEVNUM" => {
145 devnum = v.parse::<u8>().ok();
146 }
147 "DEVPATH" => {
148 devpath = Some(v);
149 }
150 _ => {}
151 }
152 }
153
154 let is_add = is_add?;
155 let busnum = busnum?;
156 let devnum = devnum?;
157 let devpath = devpath?;
158
159 if is_add {
160 let path = Path::new("/sys/").join(devpath.trim_start_matches('/'));
161 match probe_device(SysfsPath(path.clone())) {
162 Ok(d) => Some(HotplugEvent::Connected(d)),
163 Err(e) => {
164 error!("Failed to probe device {path:?}: {e}");
165 None
166 }
167 }
168 } else {
169 Some(HotplugEvent::Disconnected(crate::DeviceId(
170 super::DeviceId {
171 bus: busnum,
172 addr: devnum,
173 },
174 )))
175 }
176 }
177
178 /// Split nul-separated key=value pairs
179 fn parse_properties(buf: &[u8]) -> impl Iterator<Item = (&str, &str)> + '_ {
180 buf.split(|b| b == &0)
181 .filter_map(|entry| std::str::from_utf8(entry).ok()?.split_once('='))
182 }