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
25 #include "linux_usbfs.h"
34 #ifdef HAVE_ASM_TYPES_H
35 #include <asm/types.h>
37 #include <linux/netlink.h>
38 #include <sys/socket.h>
40 #define NL_GROUP_KERNEL 1
43 #define SOCK_CLOEXEC 0
47 #define SOCK_NONBLOCK 0
50 static int linux_netlink_socket = -1;
51 static int netlink_control_pipe[2] = { -1, -1 };
52 static pthread_t libusb_linux_event_thread;
54 static void *linux_netlink_event_thread_main(void *arg);
56 static int set_fd_cloexec_nb(int fd, int socktype)
60 #if defined(FD_CLOEXEC)
61 /* Make sure the netlink socket file descriptor is marked as CLOEXEC */
62 if (!(socktype & SOCK_CLOEXEC)) {
63 flags = fcntl(fd, F_GETFD);
65 usbi_err(NULL, "failed to get netlink fd flags, errno=%d", errno);
69 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) {
70 usbi_err(NULL, "failed to set netlink fd flags, errno=%d", errno);
76 /* Make sure the netlink socket is non-blocking */
77 if (!(socktype & SOCK_NONBLOCK)) {
78 flags = fcntl(fd, F_GETFL);
80 usbi_err(NULL, "failed to get netlink fd status flags, errno=%d", errno);
84 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
85 usbi_err(NULL, "failed to set netlink fd status flags, errno=%d", errno);
93 int linux_netlink_start_event_monitor(void)
95 struct sockaddr_nl sa_nl = { .nl_family = AF_NETLINK, .nl_groups = NL_GROUP_KERNEL };
96 int socktype = SOCK_RAW | SOCK_NONBLOCK | SOCK_CLOEXEC;
100 linux_netlink_socket = socket(PF_NETLINK, socktype, NETLINK_KOBJECT_UEVENT);
101 if (linux_netlink_socket == -1 && errno == EINVAL) {
102 usbi_dbg("failed to create netlink socket of type %d, attempting SOCK_RAW", socktype);
104 linux_netlink_socket = socket(PF_NETLINK, socktype, NETLINK_KOBJECT_UEVENT);
107 if (linux_netlink_socket == -1) {
108 usbi_err(NULL, "failed to create netlink socket, errno=%d", errno);
112 ret = set_fd_cloexec_nb(linux_netlink_socket, socktype);
114 goto err_close_socket;
116 ret = bind(linux_netlink_socket, (struct sockaddr *)&sa_nl, sizeof(sa_nl));
118 usbi_err(NULL, "failed to bind netlink socket, errno=%d", errno);
119 goto err_close_socket;
122 ret = setsockopt(linux_netlink_socket, SOL_SOCKET, SO_PASSCRED, &opt, sizeof(opt));
124 usbi_err(NULL, "failed to set netlink socket SO_PASSCRED option, errno=%d", errno);
125 goto err_close_socket;
128 ret = usbi_pipe(netlink_control_pipe);
130 usbi_err(NULL, "failed to create netlink control pipe");
131 goto err_close_socket;
134 ret = pthread_create(&libusb_linux_event_thread, NULL, linux_netlink_event_thread_main, NULL);
136 usbi_err(NULL, "failed to create netlink event thread (%d)", ret);
140 return LIBUSB_SUCCESS;
143 close(netlink_control_pipe[0]);
144 close(netlink_control_pipe[1]);
145 netlink_control_pipe[0] = -1;
146 netlink_control_pipe[1] = -1;
148 close(linux_netlink_socket);
149 linux_netlink_socket = -1;
151 return LIBUSB_ERROR_OTHER;
154 int linux_netlink_stop_event_monitor(void)
159 assert(linux_netlink_socket != -1);
161 /* Write some dummy data to the control pipe and
162 * wait for the thread to exit */
163 r = write(netlink_control_pipe[1], &dummy, sizeof(dummy));
165 usbi_warn(NULL, "netlink control pipe signal failed");
167 pthread_join(libusb_linux_event_thread, NULL);
169 close(linux_netlink_socket);
170 linux_netlink_socket = -1;
172 /* close and reset control pipe */
173 close(netlink_control_pipe[0]);
174 close(netlink_control_pipe[1]);
175 netlink_control_pipe[0] = -1;
176 netlink_control_pipe[1] = -1;
178 return LIBUSB_SUCCESS;
181 static const char *netlink_message_parse(const char *buffer, size_t len, const char *key)
183 const char *end = buffer + len;
184 size_t keylen = strlen(key);
186 while (buffer < end && *buffer) {
187 if (strncmp(buffer, key, keylen) == 0 && buffer[keylen] == '=')
188 return buffer + keylen + 1;
189 buffer += strlen(buffer) + 1;
195 /* parse parts of netlink message common to both libudev and the kernel */
196 static int linux_netlink_parse(const char *buffer, size_t len, int *detached,
197 const char **sys_name, uint8_t *busnum, uint8_t *devaddr)
199 const char *tmp, *slash;
208 tmp = netlink_message_parse(buffer, len, "ACTION");
211 } else if (strcmp(tmp, "remove") == 0) {
213 } else if (strcmp(tmp, "add") != 0) {
214 usbi_dbg("unknown device action %s", tmp);
218 /* check that this is a usb message */
219 tmp = netlink_message_parse(buffer, len, "SUBSYSTEM");
220 if (!tmp || strcmp(tmp, "usb") != 0) {
221 /* not usb. ignore */
225 /* check that this is an actual usb device */
226 tmp = netlink_message_parse(buffer, len, "DEVTYPE");
227 if (!tmp || strcmp(tmp, "usb_device") != 0) {
228 /* not usb. ignore */
232 tmp = netlink_message_parse(buffer, len, "BUSNUM");
234 *busnum = (uint8_t)(strtoul(tmp, NULL, 10) & 0xff);
240 tmp = netlink_message_parse(buffer, len, "DEVNUM");
244 *devaddr = (uint8_t)(strtoul(tmp, NULL, 10) & 0xff);
250 /* no bus number. try "DEVICE" */
251 tmp = netlink_message_parse(buffer, len, "DEVICE");
253 /* not usb. ignore */
257 /* Parse a device path such as /dev/bus/usb/003/004 */
258 slash = strrchr(tmp, '/');
262 *busnum = (uint8_t)(strtoul(slash - 3, NULL, 10) & 0xff);
268 *devaddr = (uint8_t)(strtoul(slash + 1, NULL, 10) & 0xff);
277 tmp = netlink_message_parse(buffer, len, "DEVPATH");
281 slash = strrchr(tmp, '/');
283 *sys_name = slash + 1;
285 /* found a usb device */
289 static int linux_netlink_read_message(void)
291 char cred_buffer[CMSG_SPACE(sizeof(struct ucred))];
292 char msg_buffer[2048];
293 const char *sys_name = NULL;
294 uint8_t busnum, devaddr;
297 struct cmsghdr *cmsg;
299 struct sockaddr_nl sa_nl;
300 struct iovec iov = { .iov_base = msg_buffer, .iov_len = sizeof(msg_buffer) };
301 struct msghdr msg = {
302 .msg_iov = &iov, .msg_iovlen = 1,
303 .msg_control = cred_buffer, .msg_controllen = sizeof(cred_buffer),
304 .msg_name = &sa_nl, .msg_namelen = sizeof(sa_nl)
307 /* read netlink message */
308 len = recvmsg(linux_netlink_socket, &msg, 0);
310 if (errno != EAGAIN && errno != EINTR)
311 usbi_err(NULL, "error receiving message from netlink, errno=%d", errno);
315 if (len < 32 || (msg.msg_flags & MSG_TRUNC)) {
316 usbi_err(NULL, "invalid netlink message length");
320 if (sa_nl.nl_groups != NL_GROUP_KERNEL || sa_nl.nl_pid != 0) {
321 usbi_dbg("ignoring netlink message from unknown group/PID (%u/%u)",
322 (unsigned int)sa_nl.nl_groups, (unsigned int)sa_nl.nl_pid);
326 cmsg = CMSG_FIRSTHDR(&msg);
327 if (!cmsg || cmsg->cmsg_type != SCM_CREDENTIALS) {
328 usbi_dbg("ignoring netlink message with no sender credentials");
332 cred = (struct ucred *)CMSG_DATA(cmsg);
333 if (cred->uid != 0) {
334 usbi_dbg("ignoring netlink message with non-zero sender UID %u", (unsigned int)cred->uid);
338 r = linux_netlink_parse(msg_buffer, (size_t)len, &detached, &sys_name, &busnum, &devaddr);
342 usbi_dbg("netlink hotplug found device busnum: %hhu, devaddr: %hhu, sys_name: %s, removed: %s",
343 busnum, devaddr, sys_name, detached ? "yes" : "no");
345 /* signal device is available (or not) to all contexts */
347 linux_device_disconnected(busnum, devaddr);
349 linux_hotplug_enumerate(busnum, devaddr, sys_name);
354 static void *linux_netlink_event_thread_main(void *arg)
359 struct pollfd fds[] = {
360 { .fd = netlink_control_pipe[0],
362 { .fd = linux_netlink_socket,
368 usbi_dbg("netlink event thread entering");
370 while ((r = poll(fds, 2, -1)) >= 0 || errno == EINTR) {
372 /* temporary failure */
375 if (fds[0].revents & POLLIN) {
376 /* activity on control pipe, read the byte and exit */
377 nb = read(netlink_control_pipe[0], &dummy, sizeof(dummy));
379 usbi_warn(NULL, "netlink control pipe read failed");
382 if (fds[1].revents & POLLIN) {
383 usbi_mutex_static_lock(&linux_hotplug_lock);
384 linux_netlink_read_message();
385 usbi_mutex_static_unlock(&linux_hotplug_lock);
389 usbi_dbg("netlink event thread exiting");
394 void linux_netlink_hotplug_poll(void)
398 usbi_mutex_static_lock(&linux_hotplug_lock);
400 r = linux_netlink_read_message();
402 usbi_mutex_static_unlock(&linux_hotplug_lock);