1 /* -*- Mode: C; c-basic-offset:8 ; indent-tabs-mode:t -*- */
3 * Linux usbfs backend for libusb
4 * Copyright (C) 2007-2009 Daniel Drake <dsd@gentoo.org>
5 * Copyright (c) 2001 Johannes Erdfelt <johannes@erdfelt.com>
6 * Copyright (c) 2013 Nathan Hjelm <hjelmn@mac.com>
7 * Copyright (c) 2016 Chris Dickens <christopher.a.dickens@gmail.com>
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
34 #include <sys/types.h>
36 #ifdef HAVE_ASM_TYPES_H
37 #include <asm/types.h>
40 #include <sys/socket.h>
41 #include <linux/netlink.h>
44 #include "linux_usbfs.h"
46 #define NL_GROUP_KERNEL 1
49 #define SOCK_CLOEXEC 0
53 #define SOCK_NONBLOCK 0
56 static int linux_netlink_socket = -1;
57 static int netlink_control_pipe[2] = { -1, -1 };
58 static pthread_t libusb_linux_event_thread;
60 static void *linux_netlink_event_thread_main(void *arg);
62 static int set_fd_cloexec_nb(int fd, int socktype)
66 #if defined(FD_CLOEXEC)
67 /* Make sure the netlink socket file descriptor is marked as CLOEXEC */
68 if (!(socktype & SOCK_CLOEXEC)) {
69 flags = fcntl(fd, F_GETFD);
71 usbi_err(NULL, "failed to get netlink fd flags (%d)", errno);
75 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) {
76 usbi_err(NULL, "failed to set netlink fd flags (%d)", errno);
82 /* Make sure the netlink socket is non-blocking */
83 if (!(socktype & SOCK_NONBLOCK)) {
84 flags = fcntl(fd, F_GETFL);
86 usbi_err(NULL, "failed to get netlink fd status flags (%d)", errno);
90 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
91 usbi_err(NULL, "failed to set netlink fd status flags (%d)", errno);
99 int linux_netlink_start_event_monitor(void)
101 struct sockaddr_nl sa_nl = { .nl_family = AF_NETLINK, .nl_groups = NL_GROUP_KERNEL };
102 int socktype = SOCK_RAW | SOCK_NONBLOCK | SOCK_CLOEXEC;
106 linux_netlink_socket = socket(PF_NETLINK, socktype, NETLINK_KOBJECT_UEVENT);
107 if (linux_netlink_socket == -1 && errno == EINVAL) {
108 usbi_dbg("failed to create netlink socket of type %d, attempting SOCK_RAW", socktype);
110 linux_netlink_socket = socket(PF_NETLINK, socktype, NETLINK_KOBJECT_UEVENT);
113 if (linux_netlink_socket == -1) {
114 usbi_err(NULL, "failed to create netlink socket (%d)", errno);
118 ret = set_fd_cloexec_nb(linux_netlink_socket, socktype);
120 goto err_close_socket;
122 ret = bind(linux_netlink_socket, (struct sockaddr *)&sa_nl, sizeof(sa_nl));
124 usbi_err(NULL, "failed to bind netlink socket (%d)", errno);
125 goto err_close_socket;
128 ret = setsockopt(linux_netlink_socket, SOL_SOCKET, SO_PASSCRED, &opt, sizeof(opt));
130 usbi_err(NULL, "failed to set netlink socket SO_PASSCRED option (%d)", errno);
131 goto err_close_socket;
134 ret = usbi_pipe(netlink_control_pipe);
136 usbi_err(NULL, "failed to create netlink control pipe");
137 goto err_close_socket;
140 ret = pthread_create(&libusb_linux_event_thread, NULL, linux_netlink_event_thread_main, NULL);
142 usbi_err(NULL, "failed to create netlink event thread (%d)", ret);
146 return LIBUSB_SUCCESS;
149 close(netlink_control_pipe[0]);
150 close(netlink_control_pipe[1]);
151 netlink_control_pipe[0] = -1;
152 netlink_control_pipe[1] = -1;
154 close(linux_netlink_socket);
155 linux_netlink_socket = -1;
157 return LIBUSB_ERROR_OTHER;
160 int linux_netlink_stop_event_monitor(void)
165 assert(linux_netlink_socket != -1);
167 /* Write some dummy data to the control pipe and
168 * wait for the thread to exit */
169 r = write(netlink_control_pipe[1], &dummy, sizeof(dummy));
171 usbi_warn(NULL, "netlink control pipe signal failed");
173 pthread_join(libusb_linux_event_thread, NULL);
175 close(linux_netlink_socket);
176 linux_netlink_socket = -1;
178 /* close and reset control pipe */
179 close(netlink_control_pipe[0]);
180 close(netlink_control_pipe[1]);
181 netlink_control_pipe[0] = -1;
182 netlink_control_pipe[1] = -1;
184 return LIBUSB_SUCCESS;
187 static const char *netlink_message_parse(const char *buffer, size_t len, const char *key)
189 const char *end = buffer + len;
190 size_t keylen = strlen(key);
192 while (buffer < end && *buffer) {
193 if (strncmp(buffer, key, keylen) == 0 && buffer[keylen] == '=')
194 return buffer + keylen + 1;
195 buffer += strlen(buffer) + 1;
201 /* parse parts of netlink message common to both libudev and the kernel */
202 static int linux_netlink_parse(const char *buffer, size_t len, int *detached,
203 const char **sys_name, uint8_t *busnum, uint8_t *devaddr)
205 const char *tmp, *slash;
214 tmp = netlink_message_parse(buffer, len, "ACTION");
217 } else if (strcmp(tmp, "remove") == 0) {
219 } else if (strcmp(tmp, "add") != 0) {
220 usbi_dbg("unknown device action %s", tmp);
224 /* check that this is a usb message */
225 tmp = netlink_message_parse(buffer, len, "SUBSYSTEM");
226 if (!tmp || strcmp(tmp, "usb") != 0) {
227 /* not usb. ignore */
231 /* check that this is an actual usb device */
232 tmp = netlink_message_parse(buffer, len, "DEVTYPE");
233 if (!tmp || strcmp(tmp, "usb_device") != 0) {
234 /* not usb. ignore */
238 tmp = netlink_message_parse(buffer, len, "BUSNUM");
240 *busnum = (uint8_t)(strtoul(tmp, NULL, 10) & 0xff);
246 tmp = netlink_message_parse(buffer, len, "DEVNUM");
250 *devaddr = (uint8_t)(strtoul(tmp, NULL, 10) & 0xff);
256 /* no bus number. try "DEVICE" */
257 tmp = netlink_message_parse(buffer, len, "DEVICE");
259 /* not usb. ignore */
263 /* Parse a device path such as /dev/bus/usb/003/004 */
264 slash = strrchr(tmp, '/');
268 *busnum = (uint8_t)(strtoul(slash - 3, NULL, 10) & 0xff);
274 *devaddr = (uint8_t)(strtoul(slash + 1, NULL, 10) & 0xff);
283 tmp = netlink_message_parse(buffer, len, "DEVPATH");
287 slash = strrchr(tmp, '/');
289 *sys_name = slash + 1;
291 /* found a usb device */
295 static int linux_netlink_read_message(void)
297 char cred_buffer[CMSG_SPACE(sizeof(struct ucred))];
298 char msg_buffer[2048];
299 const char *sys_name = NULL;
300 uint8_t busnum, devaddr;
303 struct cmsghdr *cmsg;
305 struct sockaddr_nl sa_nl;
306 struct iovec iov = { .iov_base = msg_buffer, .iov_len = sizeof(msg_buffer) };
307 struct msghdr msg = {
308 .msg_iov = &iov, .msg_iovlen = 1,
309 .msg_control = cred_buffer, .msg_controllen = sizeof(cred_buffer),
310 .msg_name = &sa_nl, .msg_namelen = sizeof(sa_nl)
313 /* read netlink message */
314 len = recvmsg(linux_netlink_socket, &msg, 0);
316 if (errno != EAGAIN && errno != EINTR)
317 usbi_err(NULL, "error receiving message from netlink (%d)", errno);
321 if (len < 32 || (msg.msg_flags & MSG_TRUNC)) {
322 usbi_err(NULL, "invalid netlink message length");
326 if (sa_nl.nl_groups != NL_GROUP_KERNEL || sa_nl.nl_pid != 0) {
327 usbi_dbg("ignoring netlink message from unknown group/PID (%u/%u)",
328 (unsigned int)sa_nl.nl_groups, (unsigned int)sa_nl.nl_pid);
332 cmsg = CMSG_FIRSTHDR(&msg);
333 if (!cmsg || cmsg->cmsg_type != SCM_CREDENTIALS) {
334 usbi_dbg("ignoring netlink message with no sender credentials");
338 cred = (struct ucred *)CMSG_DATA(cmsg);
339 if (cred->uid != 0) {
340 usbi_dbg("ignoring netlink message with non-zero sender UID %u", (unsigned int)cred->uid);
344 r = linux_netlink_parse(msg_buffer, (size_t)len, &detached, &sys_name, &busnum, &devaddr);
348 usbi_dbg("netlink hotplug found device busnum: %hhu, devaddr: %hhu, sys_name: %s, removed: %s",
349 busnum, devaddr, sys_name, detached ? "yes" : "no");
351 /* signal device is available (or not) to all contexts */
353 linux_device_disconnected(busnum, devaddr);
355 linux_hotplug_enumerate(busnum, devaddr, sys_name);
360 static void *linux_netlink_event_thread_main(void *arg)
365 struct pollfd fds[] = {
366 { .fd = netlink_control_pipe[0],
368 { .fd = linux_netlink_socket,
374 usbi_dbg("netlink event thread entering");
376 while ((r = poll(fds, 2, -1)) >= 0 || errno == EINTR) {
378 /* temporary failure */
381 if (fds[0].revents & POLLIN) {
382 /* activity on control pipe, read the byte and exit */
383 nb = read(netlink_control_pipe[0], &dummy, sizeof(dummy));
385 usbi_warn(NULL, "netlink control pipe read failed");
388 if (fds[1].revents & POLLIN) {
389 usbi_mutex_static_lock(&linux_hotplug_lock);
390 linux_netlink_read_message();
391 usbi_mutex_static_unlock(&linux_hotplug_lock);
395 usbi_dbg("netlink event thread exiting");
400 void linux_netlink_hotplug_poll(void)
404 usbi_mutex_static_lock(&linux_hotplug_lock);
406 r = linux_netlink_read_message();
408 usbi_mutex_static_unlock(&linux_hotplug_lock);