Fix issue 1) not recognizes some usb device, 2) reconnect when ffmpeg encoder error
[rtmpclient.git] / app / src / main / jni / libusb / libusb / os / android_netlink.c
1 /* -*- Mode: C; c-basic-offset:8 ; indent-tabs-mode:t -*- */
2 /*
3  * non-rooted Android 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 #define LOG_TAG "libusb/netlink"
24 #if 0   // デバッグ情報を出さない時1
25         #ifndef LOG_NDEBUG
26                 #define LOG_NDEBUG              // LOGV/LOGD/MARKを出力しない時
27                 #endif
28         #undef USE_LOGALL                       // 指定したLOGxだけを出力
29 #else
30         #define USE_LOGALL
31         #undef LOG_NDEBUG
32         #undef NDEBUG
33         #define GET_RAW_DESCRIPTOR
34 #endif
35
36 #include "config.h"
37 #include "libusb.h"
38 #include "libusbi.h"
39 #include "android_usbfs.h"
40
41 #include <ctype.h>
42 #include <dirent.h>
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <poll.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <sys/types.h>
50
51 #ifdef HAVE_ASM_TYPES_H
52 #include <asm/types.h>
53 #endif
54
55 #ifdef HAVE_SYS_SOCKET_H
56 #include <sys/socket.h>
57 #endif
58
59 #include <arpa/inet.h>
60
61 #ifdef HAVE_LINUX_NETLINK_H
62 #include <linux/netlink.h>
63 #endif
64
65 #ifdef HAVE_LINUX_FILTER_H
66 #include <linux/filter.h>
67 #endif
68
69 #define KERNEL 1
70
71 static int android_netlink_socket = -1;
72 static int netlink_control_pipe[2] = { -1, -1 };
73 static pthread_t libusb_android_event_thread;
74
75 static void *android_netlink_event_thread_main(void *arg);
76
77 struct sockaddr_nl snl = { .nl_family=AF_NETLINK, .nl_groups=KERNEL };
78
79 static int set_fd_cloexec_nb (int fd)
80 {
81         int flags;
82
83 #if defined(FD_CLOEXEC)
84         flags = fcntl (android_netlink_socket, F_GETFD);
85         if (0 > flags) {
86                 return -1;
87         }
88
89         if (!(flags & FD_CLOEXEC)) {
90                 fcntl (android_netlink_socket, F_SETFD, flags | FD_CLOEXEC);
91         }
92 #endif
93
94         flags = fcntl (android_netlink_socket, F_GETFL);
95         if (0 > flags) {
96                 return -1;
97         }
98
99         if (!(flags & O_NONBLOCK)) {
100                 fcntl (android_netlink_socket, F_SETFL, flags | O_NONBLOCK);
101         }
102
103         return 0;
104 }
105
106 int android_netlink_start_event_monitor(void)
107 {
108         ENTER();
109         int socktype = SOCK_RAW;
110         int ret;
111
112         snl.nl_groups = KERNEL;
113
114 #if defined(SOCK_CLOEXEC)
115         socktype |= SOCK_CLOEXEC;
116 #endif
117 #if defined(SOCK_NONBLOCK)
118         socktype |= SOCK_NONBLOCK;
119 #endif
120
121         android_netlink_socket = socket(PF_NETLINK, socktype, NETLINK_KOBJECT_UEVENT);
122         if (-1 == android_netlink_socket && EINVAL == errno) {
123                 android_netlink_socket = socket(PF_NETLINK, SOCK_RAW, NETLINK_KOBJECT_UEVENT);
124         }
125
126         if (-1 == android_netlink_socket) {
127                 LOGE("failed to create android_netlink_socket:errno=%d", errno);        // 13:Permission deniedが返ってくる
128                 RETURN(LIBUSB_ERROR_OTHER, int);
129         }
130
131         ret = set_fd_cloexec_nb (android_netlink_socket);
132         if (0 != ret) {
133                 close (android_netlink_socket);
134                 android_netlink_socket = -1;
135                 RETURN(LIBUSB_ERROR_OTHER, int);
136         }
137
138         ret = bind(android_netlink_socket, (struct sockaddr *) &snl, sizeof(snl));
139         if (0 != ret) {
140                 close(android_netlink_socket);
141                 RETURN(LIBUSB_ERROR_OTHER, int);
142         }
143
144         /* TODO -- add authentication */
145         /* setsockopt(android_netlink_socket, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)); */
146
147         ret = usbi_pipe(netlink_control_pipe);
148         if (ret) {
149                 LOGE("could not create netlink control pipe");
150                 usbi_err(NULL, "could not create netlink control pipe");
151                 close(android_netlink_socket);
152                 RETURN(LIBUSB_ERROR_OTHER, int);
153         }
154
155         ret = pthread_create(&libusb_android_event_thread, NULL, android_netlink_event_thread_main, NULL);
156         if (0 != ret) {
157                 close(netlink_control_pipe[0]);
158         close(netlink_control_pipe[1]);
159         close(android_netlink_socket);
160                 RETURN(LIBUSB_ERROR_OTHER, int);
161         }
162
163         RETURN(LIBUSB_SUCCESS, int);
164 }
165
166 int android_netlink_stop_event_monitor(void)
167 {
168         int r;
169         char dummy = 1;
170
171         if (-1 == android_netlink_socket) {
172                 /* already closed. nothing to do */
173                 return LIBUSB_SUCCESS;
174         }
175
176         /* Write some dummy data to the control pipe and
177          * wait for the thread to exit */
178         r = usbi_write(netlink_control_pipe[1], &dummy, sizeof(dummy));
179         if (r <= 0) {
180                 usbi_warn(NULL, "netlink control pipe signal failed");
181         }
182         pthread_join(libusb_android_event_thread, NULL);
183
184         close(android_netlink_socket);
185         android_netlink_socket = -1;
186
187         /* close and reset control pipe */
188         close(netlink_control_pipe[0]);
189         close(netlink_control_pipe[1]);
190         netlink_control_pipe[0] = -1;
191         netlink_control_pipe[1] = -1;
192
193         return LIBUSB_SUCCESS;
194 }
195
196 static const char *netlink_message_parse (const char *buffer, size_t len, const char *key)
197 {
198         size_t keylen = strlen(key);
199         size_t offset;
200
201         for (offset = 0 ; offset < len && '\0' != buffer[offset] ; offset += strlen(buffer + offset) + 1) {
202                 if (0 == strncmp(buffer + offset, key, keylen) &&
203                     '=' == buffer[offset + keylen]) {
204                         return buffer + offset + keylen + 1;
205                 }
206         }
207
208         return NULL;
209 }
210
211 /* parse parts of netlink message common to both libudev and the kernel */
212 static int android_netlink_parse(char *buffer, size_t len, int *detached, const char **sys_name,
213                                uint8_t *busnum, uint8_t *devaddr) {
214         const char *tmp;
215         int i;
216
217         errno = 0;
218
219         *sys_name = NULL;
220         *detached = 0;
221         *busnum   = 0;
222         *devaddr  = 0;
223
224         tmp = netlink_message_parse((const char *) buffer, len, "ACTION");
225         if (tmp == NULL)
226                 return -1;
227         if (0 == strcmp(tmp, "remove")) {
228                 *detached = 1;
229         } else if (0 == strcmp(tmp, "add")) {
230                 // pass through
231         } else if (0 != strcmp(tmp, "change")) {
232                 usbi_dbg("unknown device action [%s]", tmp);
233                 return -1;
234         }
235
236         /* check that this is a usb message */
237         tmp = netlink_message_parse(buffer, len, "SUBSYSTEM");
238         if (NULL == tmp || 0 != strcmp(tmp, "usb")) {
239                 /* not usb. ignore */
240                 return -1;
241         }
242
243         tmp = netlink_message_parse(buffer, len, "BUSNUM");
244         if (NULL == tmp) {
245                 /* no bus number. try "DEVICE" */
246                 tmp = netlink_message_parse(buffer, len, "DEVICE");
247                 if (NULL == tmp) {
248                         /* not usb. ignore */
249                         return -1;
250                 }
251                 
252                 /* Parse a device path such as /dev/bus/usb/003/004 */
253                 char *pLastSlash = (char*)strrchr(tmp,'/');
254                 if(NULL == pLastSlash) {
255                         return -1;
256                 }
257
258                 *devaddr = strtoul(pLastSlash + 1, NULL, 10);
259                 if (errno) {
260                         errno = 0;
261                         return -1;
262                 }
263                 
264                 *busnum = strtoul(pLastSlash - 3, NULL, 10);
265                 if (errno) {
266                         errno = 0;
267                         return -1;
268                 }
269                 
270                 return 0;
271         }
272
273         *busnum = (uint8_t)(strtoul(tmp, NULL, 10) & 0xff);
274         if (errno) {
275                 errno = 0;
276                 return -1;
277         }
278
279         tmp = netlink_message_parse(buffer, len, "DEVNUM");
280         if (NULL == tmp) {
281                 return -1;
282         }
283
284         *devaddr = (uint8_t)(strtoul(tmp, NULL, 10) & 0xff);
285         if (errno) {
286                 errno = 0;
287                 return -1;
288         }
289
290         tmp = netlink_message_parse(buffer, len, "DEVPATH");
291         if (NULL == tmp) {
292                 return -1;
293         }
294
295         for (i = strlen(tmp) - 1 ; i ; --i) {
296                 if ('/' ==tmp[i]) {
297                         *sys_name = tmp + i + 1;
298                         break;
299                 }
300         }
301
302         /* found a usb device */
303         return 0;
304 }
305
306 static int android_netlink_read_message(void)
307 {
308         char buffer[1024];      // XXX changed from unsigned char to char because the first argument of android_netlink_parse is char *
309         struct iovec iov = {.iov_base = buffer, .iov_len = sizeof(buffer)};
310         struct msghdr meh = { .msg_iov=&iov, .msg_iovlen=1,
311                              .msg_name=&snl, .msg_namelen=sizeof(snl) };
312         const char *sys_name = NULL;
313         uint8_t busnum, devaddr;
314         int detached, r;
315         size_t len;
316
317         /* read netlink message */
318         memset(buffer, 0, sizeof(buffer));
319         len = recvmsg(android_netlink_socket, &meh, 0);
320         if (len < 32) {
321                 if (errno != EAGAIN)
322                         usbi_dbg("error recieving message from netlink");
323                 return -1;
324         }
325
326         /* TODO -- authenticate this message is from the kernel or udevd */
327
328         r = android_netlink_parse(buffer, len, &detached, &sys_name, &busnum, &devaddr);
329         if (r)
330                 return r;
331
332         usbi_dbg("netlink hotplug found device busnum: %hhu, devaddr: %hhu, sys_name: %s, removed: %s",
333                  busnum, devaddr, sys_name, detached ? "yes" : "no");
334
335         /* signal device is available (or not) to all contexts */
336         if (detached)
337                 android_device_disconnected(busnum, devaddr, sys_name);
338         else
339                 android_hotplug_enumerate(busnum, devaddr, sys_name);
340
341         return 0;
342 }
343
344 static void *android_netlink_event_thread_main(void *arg)
345 {
346         char dummy;
347         int r;
348         struct pollfd fds[] = {
349                 { .fd = netlink_control_pipe[0],
350                   .events = POLLIN },
351                 { .fd = android_netlink_socket,
352                   .events = POLLIN },
353         };
354
355         /* silence compiler warning */
356         (void) arg;
357
358         while (poll(fds, 2, -1) >= 0) {
359                 if (fds[0].revents & POLLIN) {
360                         /* activity on control pipe, read the byte and exit */
361                         r = usbi_read(netlink_control_pipe[0], &dummy, sizeof(dummy));
362                         if (r <= 0) {
363                                 usbi_warn(NULL, "netlink control pipe read failed");
364                         }
365                         break;
366                 }
367                 if (fds[1].revents & POLLIN) {
368                         usbi_mutex_static_lock(&android_hotplug_lock);
369                         android_netlink_read_message();
370                         usbi_mutex_static_unlock(&android_hotplug_lock);
371                 }
372         }
373
374         return NULL;
375 }
376
377 void android_netlink_hotplug_poll(void)
378 {
379         int r;
380
381         usbi_mutex_static_lock(&android_hotplug_lock);
382         do {
383                 r = android_netlink_read_message();
384         } while (r == 0);
385         usbi_mutex_static_unlock(&android_hotplug_lock);
386 }