linux: ensure the netlink socket is correctly opened with older Linux kernels
[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  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #include "config.h"
24 #include "libusb.h"
25 #include "libusbi.h"
26 #include "linux_usbfs.h"
27
28 #include <ctype.h>
29 #include <dirent.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <poll.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <sys/types.h>
37
38 #ifdef HAVE_ASM_TYPES_H
39 #include <asm/types.h>
40 #endif
41
42 #ifdef HAVE_SYS_SOCKET_H
43 #include <sys/socket.h>
44 #endif
45
46 #include <arpa/inet.h>
47
48 #ifdef HAVE_LINUX_NETLINK_H
49 #include <linux/netlink.h>
50 #endif
51
52 #ifdef HAVE_LINUX_FILTER_H
53 #include <linux/filter.h>
54 #endif
55
56 #define KERNEL 1
57
58 static int linux_netlink_socket = -1;
59 static int netlink_control_pipe[2] = { -1, -1 };
60 static pthread_t libusb_linux_event_thread;
61
62 static void *linux_netlink_event_thread_main(void *arg);
63
64 struct sockaddr_nl snl = { .nl_family=AF_NETLINK, .nl_groups=KERNEL };
65
66 static int set_fd_cloexec_nb (int fd)
67 {
68         int flags;
69
70 #if defined(FD_CLOEXEC)
71         fcntl (linux_netlink_socket, F_GETFD, &flags);
72
73         if (!(flags & FD_CLOEXEC)) {
74                 fcntl (linux_netlink_socket, F_SETFD, flags | FD_CLOEXEC);
75         }
76 #endif
77
78         fcntl (linux_netlink_socket, F_GETFL, &flags);
79         if (!(flags & O_NONBLOCK)) {
80                 fcntl (linux_netlink_socket, F_SETFL, flags | O_NONBLOCK);
81         }
82
83         return 0;
84 }
85
86 int linux_netlink_start_event_monitor(void)
87 {
88         int socktype = SOCK_RAW;
89         int ret;
90
91         snl.nl_groups = KERNEL;
92
93 #if defined(SOCK_CLOEXEC)
94         socktype |= SOCK_CLOEXEC;
95 #endif
96 #if defined(SOCK_NONBLOCK)
97         socktype |= SOCK_NONBLOCK;
98 #endif
99
100         linux_netlink_socket = socket(PF_NETLINK, socktype, NETLINK_KOBJECT_UEVENT);
101         if (-1 == linux_netlink_socket && EINVAL == errno) {
102                 linux_netlink_socket = socket(PF_NETLINK, SOCK_RAW, NETLINK_KOBJECT_UEVENT);
103         }
104
105         if (-1 == linux_netlink_socket) {
106                 return LIBUSB_ERROR_OTHER;
107         }
108
109         ret = set_fd_cloexec_nb (linux_netlink_socket);
110         if (0 != ret) {
111                 close (linux_netlink_socket);
112                 linux_netlink_socket = -1;
113                 return LIBUSB_ERROR_OTHER;
114         }
115
116         ret = bind(linux_netlink_socket, (struct sockaddr *) &snl, sizeof(snl));
117         if (0 != ret) {
118                 close(linux_netlink_socket);
119                 return LIBUSB_ERROR_OTHER;
120         }
121
122         /* TODO -- add authentication */
123         /* setsockopt(linux_netlink_socket, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)); */
124
125         ret = usbi_pipe(netlink_control_pipe);
126         if (ret) {
127                 usbi_err(NULL, "could not create netlink control pipe");
128                 close(linux_netlink_socket);
129                 return LIBUSB_ERROR_OTHER;
130         }
131
132         ret = pthread_create(&libusb_linux_event_thread, NULL, linux_netlink_event_thread_main, NULL);
133         if (0 != ret) {
134                 close(netlink_control_pipe[0]);
135                 close(netlink_control_pipe[1]);
136                 close(linux_netlink_socket);
137                 return LIBUSB_ERROR_OTHER;
138         }
139
140         return LIBUSB_SUCCESS;
141 }
142
143 int linux_netlink_stop_event_monitor(void)
144 {
145         int r;
146         char dummy = 1;
147
148         if (-1 == linux_netlink_socket) {
149                 /* already closed. nothing to do */
150                 return LIBUSB_SUCCESS;
151         }
152
153         /* Write some dummy data to the control pipe and
154          * wait for the thread to exit */
155         r = usbi_write(netlink_control_pipe[1], &dummy, sizeof(dummy));
156         if (r <= 0) {
157                 usbi_warn(NULL, "netlink control pipe signal failed");
158         }
159         pthread_join(libusb_linux_event_thread, NULL);
160
161         close(linux_netlink_socket);
162         linux_netlink_socket = -1;
163
164         /* close and reset control pipe */
165         close(netlink_control_pipe[0]);
166         close(netlink_control_pipe[1]);
167         netlink_control_pipe[0] = -1;
168         netlink_control_pipe[1] = -1;
169
170         return LIBUSB_SUCCESS;
171 }
172
173 static const char *netlink_message_parse (const char *buffer, size_t len, const char *key)
174 {
175         size_t keylen = strlen(key);
176         size_t offset;
177
178         for (offset = 0 ; offset < len && '\0' != buffer[offset] ; offset += strlen(buffer + offset) + 1) {
179                 if (0 == strncmp(buffer + offset, key, keylen) &&
180                     '=' == buffer[offset + keylen]) {
181                         return buffer + offset + keylen + 1;
182                 }
183         }
184
185         return NULL;
186 }
187
188 /* parse parts of netlink message common to both libudev and the kernel */
189 static int linux_netlink_parse(char *buffer, size_t len, int *detached, const char **sys_name,
190                                uint8_t *busnum, uint8_t *devaddr) {
191         const char *tmp;
192         int i;
193
194         errno = 0;
195
196         *sys_name = NULL;
197         *detached = 0;
198         *busnum   = 0;
199         *devaddr  = 0;
200
201         tmp = netlink_message_parse((const char *) buffer, len, "ACTION");
202         if (tmp == NULL)
203                 return -1;
204         if (0 == strcmp(tmp, "remove")) {
205                 *detached = 1;
206         } else if (0 != strcmp(tmp, "add")) {
207                 usbi_dbg("unknown device action %s", tmp);
208                 return -1;
209         }
210
211         /* check that this is a usb message */
212         tmp = netlink_message_parse(buffer, len, "SUBSYSTEM");
213         if (NULL == tmp || 0 != strcmp(tmp, "usb")) {
214                 /* not usb. ignore */
215                 return -1;
216         }
217
218         tmp = netlink_message_parse(buffer, len, "BUSNUM");
219         if (NULL == tmp) {
220                 /* no bus number (likely a usb interface). ignore*/
221                 return -1;
222         }
223
224         *busnum = (uint8_t)(strtoul(tmp, NULL, 10) & 0xff);
225         if (errno) {
226                 errno = 0;
227                 return -1;
228         }
229
230         tmp = netlink_message_parse(buffer, len, "DEVNUM");
231         if (NULL == tmp) {
232                 return -1;
233         }
234
235         *devaddr = (uint8_t)(strtoul(tmp, NULL, 10) & 0xff);
236         if (errno) {
237                 errno = 0;
238                 return -1;
239         }
240
241         tmp = netlink_message_parse(buffer, len, "DEVPATH");
242         if (NULL == tmp) {
243                 return -1;
244         }
245
246         for (i = strlen(tmp) - 1 ; i ; --i) {
247                 if ('/' ==tmp[i]) {
248                         *sys_name = tmp + i + 1;
249                         break;
250                 }
251         }
252
253         /* found a usb device */
254         return 0;
255 }
256
257 static int linux_netlink_read_message(void)
258 {
259         unsigned char buffer[1024];
260         struct iovec iov = {.iov_base = buffer, .iov_len = sizeof(buffer)};
261         struct msghdr meh = { .msg_iov=&iov, .msg_iovlen=1,
262                              .msg_name=&snl, .msg_namelen=sizeof(snl) };
263         const char *sys_name = NULL;
264         uint8_t busnum, devaddr;
265         int detached, r;
266         size_t len;
267
268         /* read netlink message */
269         memset(buffer, 0, sizeof(buffer));
270         len = recvmsg(linux_netlink_socket, &meh, 0);
271         if (len < 32) {
272                 if (errno != EAGAIN)
273                         usbi_dbg("error recieving message from netlink");
274                 return -1;
275         }
276
277         /* TODO -- authenticate this message is from the kernel or udevd */
278
279         r = linux_netlink_parse(buffer, len, &detached, &sys_name,
280                                 &busnum, &devaddr);
281         if (r)
282                 return r;
283
284         usbi_dbg("netlink hotplug found device busnum: %hhu, devaddr: %hhu, sys_name: %s, removed: %s",
285                  busnum, devaddr, sys_name, detached ? "yes" : "no");
286
287         /* signal device is available (or not) to all contexts */
288         if (detached)
289                 linux_hotplug_disconnected(busnum, devaddr, sys_name);
290         else
291                 linux_hotplug_enumerate(busnum, devaddr, sys_name);
292
293         return 0;
294 }
295
296 static void *linux_netlink_event_thread_main(void *arg)
297 {
298         char dummy;
299         int r;
300         struct pollfd fds[] = {
301                 { .fd = netlink_control_pipe[0],
302                   .events = POLLIN },
303                 { .fd = linux_netlink_socket,
304                   .events = POLLIN },
305         };
306
307         /* silence compiler warning */
308         (void) arg;
309
310         while (poll(fds, 2, -1) >= 0) {
311                 if (fds[0].revents & POLLIN) {
312                         /* activity on control pipe, read the byte and exit */
313                         r = usbi_read(netlink_control_pipe[0], &dummy, sizeof(dummy));
314                         if (r <= 0) {
315                                 usbi_warn(NULL, "netlink control pipe read failed");
316                         }
317                         break;
318                 }
319                 if (fds[1].revents & POLLIN) {
320                         usbi_mutex_static_lock(&linux_hotplug_lock);
321                         linux_netlink_read_message();
322                         usbi_mutex_static_unlock(&linux_hotplug_lock);
323                 }
324         }
325
326         return NULL;
327 }
328
329 void linux_netlink_hotplug_poll(void)
330 {
331         int r;
332
333         usbi_mutex_static_lock(&linux_hotplug_lock);
334         do {
335                 r = linux_netlink_read_message();
336         } while (r == 0);
337         usbi_mutex_static_unlock(&linux_hotplug_lock);
338 }