Misc: Trim and consolidate header file usage
[platform/upstream/libusb.git] / libusb / os / linux_netlink.c
1 /* -*- Mode: C; c-basic-offset:8 ; indent-tabs-mode:t -*- */
2 /*
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>
8  *
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.
13  *
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.
18  *
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
22  */
23
24 #include "libusbi.h"
25 #include "linux_usbfs.h"
26
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <poll.h>
30 #include <pthread.h>
31 #include <string.h>
32 #include <unistd.h>
33
34 #ifdef HAVE_ASM_TYPES_H
35 #include <asm/types.h>
36 #endif
37 #include <linux/netlink.h>
38 #include <sys/socket.h>
39
40 #define NL_GROUP_KERNEL 1
41
42 #ifndef SOCK_CLOEXEC
43 #define SOCK_CLOEXEC    0
44 #endif
45
46 #ifndef SOCK_NONBLOCK
47 #define SOCK_NONBLOCK   0
48 #endif
49
50 static int linux_netlink_socket = -1;
51 static int netlink_control_pipe[2] = { -1, -1 };
52 static pthread_t libusb_linux_event_thread;
53
54 static void *linux_netlink_event_thread_main(void *arg);
55
56 static int set_fd_cloexec_nb(int fd, int socktype)
57 {
58         int flags;
59
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);
64                 if (flags == -1) {
65                         usbi_err(NULL, "failed to get netlink fd flags, errno=%d", errno);
66                         return -1;
67                 }
68
69                 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) {
70                         usbi_err(NULL, "failed to set netlink fd flags, errno=%d", errno);
71                         return -1;
72                 }
73         }
74 #endif
75
76         /* Make sure the netlink socket is non-blocking */
77         if (!(socktype & SOCK_NONBLOCK)) {
78                 flags = fcntl(fd, F_GETFL);
79                 if (flags == -1) {
80                         usbi_err(NULL, "failed to get netlink fd status flags, errno=%d", errno);
81                         return -1;
82                 }
83
84                 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
85                         usbi_err(NULL, "failed to set netlink fd status flags, errno=%d", errno);
86                         return -1;
87                 }
88         }
89
90         return 0;
91 }
92
93 int linux_netlink_start_event_monitor(void)
94 {
95         struct sockaddr_nl sa_nl = { .nl_family = AF_NETLINK, .nl_groups = NL_GROUP_KERNEL };
96         int socktype = SOCK_RAW | SOCK_NONBLOCK | SOCK_CLOEXEC;
97         int opt = 1;
98         int ret;
99
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);
103                 socktype = SOCK_RAW;
104                 linux_netlink_socket = socket(PF_NETLINK, socktype, NETLINK_KOBJECT_UEVENT);
105         }
106
107         if (linux_netlink_socket == -1) {
108                 usbi_err(NULL, "failed to create netlink socket, errno=%d", errno);
109                 goto err;
110         }
111
112         ret = set_fd_cloexec_nb(linux_netlink_socket, socktype);
113         if (ret == -1)
114                 goto err_close_socket;
115
116         ret = bind(linux_netlink_socket, (struct sockaddr *)&sa_nl, sizeof(sa_nl));
117         if (ret == -1) {
118                 usbi_err(NULL, "failed to bind netlink socket, errno=%d", errno);
119                 goto err_close_socket;
120         }
121
122         ret = setsockopt(linux_netlink_socket, SOL_SOCKET, SO_PASSCRED, &opt, sizeof(opt));
123         if (ret == -1) {
124                 usbi_err(NULL, "failed to set netlink socket SO_PASSCRED option, errno=%d", errno);
125                 goto err_close_socket;
126         }
127
128         ret = usbi_pipe(netlink_control_pipe);
129         if (ret) {
130                 usbi_err(NULL, "failed to create netlink control pipe");
131                 goto err_close_socket;
132         }
133
134         ret = pthread_create(&libusb_linux_event_thread, NULL, linux_netlink_event_thread_main, NULL);
135         if (ret != 0) {
136                 usbi_err(NULL, "failed to create netlink event thread (%d)", ret);
137                 goto err_close_pipe;
138         }
139
140         return LIBUSB_SUCCESS;
141
142 err_close_pipe:
143         close(netlink_control_pipe[0]);
144         close(netlink_control_pipe[1]);
145         netlink_control_pipe[0] = -1;
146         netlink_control_pipe[1] = -1;
147 err_close_socket:
148         close(linux_netlink_socket);
149         linux_netlink_socket = -1;
150 err:
151         return LIBUSB_ERROR_OTHER;
152 }
153
154 int linux_netlink_stop_event_monitor(void)
155 {
156         char dummy = 1;
157         ssize_t r;
158
159         assert(linux_netlink_socket != -1);
160
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));
164         if (r <= 0)
165                 usbi_warn(NULL, "netlink control pipe signal failed");
166
167         pthread_join(libusb_linux_event_thread, NULL);
168
169         close(linux_netlink_socket);
170         linux_netlink_socket = -1;
171
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;
177
178         return LIBUSB_SUCCESS;
179 }
180
181 static const char *netlink_message_parse(const char *buffer, size_t len, const char *key)
182 {
183         const char *end = buffer + len;
184         size_t keylen = strlen(key);
185
186         while (buffer < end && *buffer) {
187                 if (strncmp(buffer, key, keylen) == 0 && buffer[keylen] == '=')
188                         return buffer + keylen + 1;
189                 buffer += strlen(buffer) + 1;
190         }
191
192         return NULL;
193 }
194
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)
198 {
199         const char *tmp, *slash;
200
201         errno = 0;
202
203         *sys_name = NULL;
204         *detached = 0;
205         *busnum   = 0;
206         *devaddr  = 0;
207
208         tmp = netlink_message_parse(buffer, len, "ACTION");
209         if (!tmp) {
210                 return -1;
211         } else if (strcmp(tmp, "remove") == 0) {
212                 *detached = 1;
213         } else if (strcmp(tmp, "add") != 0) {
214                 usbi_dbg("unknown device action %s", tmp);
215                 return -1;
216         }
217
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 */
222                 return -1;
223         }
224
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 */
229                 return -1;
230         }
231
232         tmp = netlink_message_parse(buffer, len, "BUSNUM");
233         if (tmp) {
234                 *busnum = (uint8_t)(strtoul(tmp, NULL, 10) & 0xff);
235                 if (errno) {
236                         errno = 0;
237                         return -1;
238                 }
239
240                 tmp = netlink_message_parse(buffer, len, "DEVNUM");
241                 if (NULL == tmp)
242                         return -1;
243
244                 *devaddr = (uint8_t)(strtoul(tmp, NULL, 10) & 0xff);
245                 if (errno) {
246                         errno = 0;
247                         return -1;
248                 }
249         } else {
250                 /* no bus number. try "DEVICE" */
251                 tmp = netlink_message_parse(buffer, len, "DEVICE");
252                 if (!tmp) {
253                         /* not usb. ignore */
254                         return -1;
255                 }
256
257                 /* Parse a device path such as /dev/bus/usb/003/004 */
258                 slash = strrchr(tmp, '/');
259                 if (!slash)
260                         return -1;
261
262                 *busnum = (uint8_t)(strtoul(slash - 3, NULL, 10) & 0xff);
263                 if (errno) {
264                         errno = 0;
265                         return -1;
266                 }
267
268                 *devaddr = (uint8_t)(strtoul(slash + 1, NULL, 10) & 0xff);
269                 if (errno) {
270                         errno = 0;
271                         return -1;
272                 }
273
274                 return 0;
275         }
276
277         tmp = netlink_message_parse(buffer, len, "DEVPATH");
278         if (!tmp)
279                 return -1;
280
281         slash = strrchr(tmp, '/');
282         if (slash)
283                 *sys_name = slash + 1;
284
285         /* found a usb device */
286         return 0;
287 }
288
289 static int linux_netlink_read_message(void)
290 {
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;
295         int detached, r;
296         ssize_t len;
297         struct cmsghdr *cmsg;
298         struct ucred *cred;
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)
305         };
306
307         /* read netlink message */
308         len = recvmsg(linux_netlink_socket, &msg, 0);
309         if (len == -1) {
310                 if (errno != EAGAIN && errno != EINTR)
311                         usbi_err(NULL, "error receiving message from netlink, errno=%d", errno);
312                 return -1;
313         }
314
315         if (len < 32 || (msg.msg_flags & MSG_TRUNC)) {
316                 usbi_err(NULL, "invalid netlink message length");
317                 return -1;
318         }
319
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);
323                 return -1;
324         }
325
326         cmsg = CMSG_FIRSTHDR(&msg);
327         if (!cmsg || cmsg->cmsg_type != SCM_CREDENTIALS) {
328                 usbi_dbg("ignoring netlink message with no sender credentials");
329                 return -1;
330         }
331
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);
335                 return -1;
336         }
337
338         r = linux_netlink_parse(msg_buffer, (size_t)len, &detached, &sys_name, &busnum, &devaddr);
339         if (r)
340                 return r;
341
342         usbi_dbg("netlink hotplug found device busnum: %hhu, devaddr: %hhu, sys_name: %s, removed: %s",
343                  busnum, devaddr, sys_name, detached ? "yes" : "no");
344
345         /* signal device is available (or not) to all contexts */
346         if (detached)
347                 linux_device_disconnected(busnum, devaddr);
348         else
349                 linux_hotplug_enumerate(busnum, devaddr, sys_name);
350
351         return 0;
352 }
353
354 static void *linux_netlink_event_thread_main(void *arg)
355 {
356         char dummy;
357         int r;
358         ssize_t nb;
359         struct pollfd fds[] = {
360                 { .fd = netlink_control_pipe[0],
361                   .events = POLLIN },
362                 { .fd = linux_netlink_socket,
363                   .events = POLLIN },
364         };
365
366         UNUSED(arg);
367
368         usbi_dbg("netlink event thread entering");
369
370         while ((r = poll(fds, 2, -1)) >= 0 || errno == EINTR) {
371                 if (r < 0) {
372                         /* temporary failure */
373                         continue;
374                 }
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));
378                         if (nb <= 0)
379                                 usbi_warn(NULL, "netlink control pipe read failed");
380                         break;
381                 }
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);
386                 }
387         }
388
389         usbi_dbg("netlink event thread exiting");
390
391         return NULL;
392 }
393
394 void linux_netlink_hotplug_poll(void)
395 {
396         int r;
397
398         usbi_mutex_static_lock(&linux_hotplug_lock);
399         do {
400                 r = linux_netlink_read_message();
401         } while (r == 0);
402         usbi_mutex_static_unlock(&linux_hotplug_lock);
403 }