• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *
3  *  BlueZ - Bluetooth protocol stack for Linux
4  *
5  *  Copyright (C) 2004-2009  Marcel Holtmann <marcel@holtmann.org>
6  *
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program 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
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21  *
22  */
23 
24 #ifdef HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27 
28 #include <stdlib.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <unistd.h>
32 #include <sys/stat.h>
33 #include <sys/ioctl.h>
34 #include <sys/socket.h>
35 
36 #include <bluetooth/bluetooth.h>
37 #include <bluetooth/hci.h>
38 #include <bluetooth/hci_lib.h>
39 #include <bluetooth/hidp.h>
40 #include <bluetooth/l2cap.h>
41 #include <bluetooth/rfcomm.h>
42 #include <bluetooth/sdp.h>
43 #include <bluetooth/sdp_lib.h>
44 
45 #include <glib.h>
46 #include <dbus/dbus.h>
47 #include <gdbus.h>
48 
49 #include "logging.h"
50 #include "textfile.h"
51 #include "uinput.h"
52 
53 #include "../src/storage.h"
54 #include "../src/manager.h"
55 #include "../src/dbus-common.h"
56 #include "adapter.h"
57 #include "../src/device.h"
58 
59 #include "device.h"
60 #include "error.h"
61 #include "fakehid.h"
62 #include "glib-helper.h"
63 #include "btio.h"
64 
65 #define INPUT_DEVICE_INTERFACE "org.bluez.Input"
66 
67 #define BUF_SIZE		16
68 
69 #define UPDOWN_ENABLED		1
70 
71 #define FI_FLAG_CONNECTED	1
72 
73 struct input_conn {
74 	struct fake_input	*fake;
75 	DBusMessage		*pending_connect;
76 	char			*uuid;
77 	char			*alias;
78 	GIOChannel		*ctrl_io;
79 	GIOChannel		*intr_io;
80 	guint			ctrl_watch;
81 	guint			intr_watch;
82 	int			timeout;
83 	struct input_device	*idev;
84 };
85 
86 struct input_device {
87 	DBusConnection		*conn;
88 	char			*path;
89 	bdaddr_t		src;
90 	bdaddr_t		dst;
91 	uint32_t		handle;
92 	guint			dc_id;
93 	char			*name;
94 	struct btd_device	*device;
95 	GSList			*connections;
96 };
97 
98 GSList *devices = NULL;
99 
find_device_by_path(GSList * list,const char * path)100 static struct input_device *find_device_by_path(GSList *list, const char *path)
101 {
102 	GSList *l;
103 
104 	for (l = list; l; l = l->next) {
105 		struct input_device *idev = l->data;
106 
107 		if (!strcmp(idev->path, path))
108 			return idev;
109 	}
110 
111 	return NULL;
112 }
113 
find_connection(GSList * list,const char * pattern)114 static struct input_conn *find_connection(GSList *list, const char *pattern)
115 {
116 	GSList *l;
117 
118 	for (l = list; l; l = l->next) {
119 		struct input_conn *iconn = l->data;
120 
121 		if (!strcasecmp(iconn->uuid, pattern))
122 			return iconn;
123 
124 		if (!strcasecmp(iconn->alias, pattern))
125 			return iconn;
126 	}
127 
128 	return NULL;
129 }
130 
input_conn_free(struct input_conn * iconn)131 static void input_conn_free(struct input_conn *iconn)
132 {
133 	if (iconn->pending_connect)
134 		dbus_message_unref(iconn->pending_connect);
135 
136 	if (iconn->ctrl_watch)
137 		g_source_remove(iconn->ctrl_watch);
138 
139 	if (iconn->intr_watch)
140 		g_source_remove(iconn->intr_watch);
141 
142 	if (iconn->intr_io)
143 		g_io_channel_unref(iconn->intr_io);
144 
145 	if (iconn->ctrl_io)
146 		g_io_channel_unref(iconn->ctrl_io);
147 
148 	g_free(iconn->uuid);
149 	g_free(iconn->alias);
150 	g_free(iconn->fake);
151 	g_free(iconn);
152 }
153 
input_device_free(struct input_device * idev)154 static void input_device_free(struct input_device *idev)
155 {
156 	if (idev->dc_id)
157 		device_remove_disconnect_watch(idev->device, idev->dc_id);
158 
159 	dbus_connection_unref(idev->conn);
160 	btd_device_unref(idev->device);
161 	g_free(idev->name);
162 	g_free(idev->path);
163 	g_free(idev);
164 }
165 
uinput_create(char * name)166 static int uinput_create(char *name)
167 {
168 	struct uinput_dev dev;
169 	int fd, err;
170 
171 	fd = open("/dev/uinput", O_RDWR);
172 	if (fd < 0) {
173 		fd = open("/dev/input/uinput", O_RDWR);
174 		if (fd < 0) {
175 			fd = open("/dev/misc/uinput", O_RDWR);
176 			if (fd < 0) {
177 				err = errno;
178 				error("Can't open input device: %s (%d)",
179 							strerror(err), err);
180 				return -err;
181 			}
182 		}
183 	}
184 
185 	memset(&dev, 0, sizeof(dev));
186 	if (name)
187 		strncpy(dev.name, name, UINPUT_MAX_NAME_SIZE - 1);
188 
189 	dev.id.bustype = BUS_BLUETOOTH;
190 	dev.id.vendor  = 0x0000;
191 	dev.id.product = 0x0000;
192 	dev.id.version = 0x0000;
193 
194 	if (write(fd, &dev, sizeof(dev)) < 0) {
195 		err = errno;
196 		error("Can't write device information: %s (%d)",
197 						strerror(err), err);
198 		close(fd);
199 		errno = err;
200 		return -err;
201 	}
202 
203 	ioctl(fd, UI_SET_EVBIT, EV_KEY);
204 	ioctl(fd, UI_SET_EVBIT, EV_REL);
205 	ioctl(fd, UI_SET_EVBIT, EV_REP);
206 
207 	ioctl(fd, UI_SET_KEYBIT, KEY_UP);
208 	ioctl(fd, UI_SET_KEYBIT, KEY_PAGEUP);
209 	ioctl(fd, UI_SET_KEYBIT, KEY_DOWN);
210 	ioctl(fd, UI_SET_KEYBIT, KEY_PAGEDOWN);
211 
212 	if (ioctl(fd, UI_DEV_CREATE, NULL) < 0) {
213 		err = errno;
214 		error("Can't create uinput device: %s (%d)",
215 						strerror(err), err);
216 		close(fd);
217 		errno = err;
218 		return -err;
219 	}
220 
221 	return fd;
222 }
223 
decode_key(const char * str)224 static int decode_key(const char *str)
225 {
226 	static int mode = UPDOWN_ENABLED, gain = 0;
227 
228 	uint16_t key;
229 	int new_gain;
230 
231 	/* Switch from key up/down to page up/down */
232 	if (strncmp("AT+CKPD=200", str, 11) == 0) {
233 		mode = ~mode;
234 		return KEY_RESERVED;
235 	}
236 
237 	if (strncmp("AT+VG", str, 5))
238 		return KEY_RESERVED;
239 
240 	/* Gain key pressed */
241 	if (strlen(str) != 10)
242 		return KEY_RESERVED;
243 
244 	new_gain = strtol(&str[7], NULL, 10);
245 	if (new_gain <= gain)
246 		key = (mode == UPDOWN_ENABLED ? KEY_UP : KEY_PAGEUP);
247 	else
248 		key = (mode == UPDOWN_ENABLED ? KEY_DOWN : KEY_PAGEDOWN);
249 
250 	gain = new_gain;
251 
252 	return key;
253 }
254 
send_event(int fd,uint16_t type,uint16_t code,int32_t value)255 static void send_event(int fd, uint16_t type, uint16_t code, int32_t value)
256 {
257 	struct uinput_event event;
258 	int err;
259 
260 	memset(&event, 0, sizeof(event));
261 	event.type	= type;
262 	event.code	= code;
263 	event.value	= value;
264 
265 	err = write(fd, &event, sizeof(event));
266 }
267 
send_key(int fd,uint16_t key)268 static void send_key(int fd, uint16_t key)
269 {
270 	/* Key press */
271 	send_event(fd, EV_KEY, key, 1);
272 	send_event(fd, EV_SYN, SYN_REPORT, 0);
273 	/* Key release */
274 	send_event(fd, EV_KEY, key, 0);
275 	send_event(fd, EV_SYN, SYN_REPORT, 0);
276 }
277 
rfcomm_io_cb(GIOChannel * chan,GIOCondition cond,gpointer data)278 static gboolean rfcomm_io_cb(GIOChannel *chan, GIOCondition cond, gpointer data)
279 {
280 	struct fake_input *fake = data;
281 	const char *ok = "\r\nOK\r\n";
282 	char buf[BUF_SIZE];
283 	gsize bread = 0, bwritten;
284 	uint16_t key;
285 
286 	if (cond & G_IO_NVAL)
287 		return FALSE;
288 
289 	if (cond & (G_IO_HUP | G_IO_ERR)) {
290 		error("Hangup or error on rfcomm server socket");
291 		goto failed;
292 	}
293 
294 	memset(buf, 0, BUF_SIZE);
295 	if (g_io_channel_read(chan, buf, sizeof(buf) - 1,
296 				&bread) != G_IO_ERROR_NONE) {
297 		error("IO Channel read error");
298 		goto failed;
299 	}
300 
301 	debug("Received: %s", buf);
302 
303 	if (g_io_channel_write(chan, ok, 6, &bwritten) != G_IO_ERROR_NONE) {
304 		error("IO Channel write error");
305 		goto failed;
306 	}
307 
308 	key = decode_key(buf);
309 	if (key != KEY_RESERVED)
310 		send_key(fake->uinput, key);
311 
312 	return TRUE;
313 
314 failed:
315 	ioctl(fake->uinput, UI_DEV_DESTROY);
316 	close(fake->uinput);
317 	fake->uinput = -1;
318 	g_io_channel_unref(fake->io);
319 
320 	return FALSE;
321 }
322 
not_supported(DBusMessage * msg)323 static inline DBusMessage *not_supported(DBusMessage *msg)
324 {
325 	return g_dbus_create_error(msg, ERROR_INTERFACE ".Failed",
326 							"Not supported");
327 }
328 
in_progress(DBusMessage * msg)329 static inline DBusMessage *in_progress(DBusMessage *msg)
330 {
331 	return g_dbus_create_error(msg, ERROR_INTERFACE ".InProgress",
332 				"Device connection already in progress");
333 }
334 
already_connected(DBusMessage * msg)335 static inline DBusMessage *already_connected(DBusMessage *msg)
336 {
337 	return g_dbus_create_error(msg, ERROR_INTERFACE ".AlreadyConnected",
338 					"Already connected to a device");
339 }
340 
connection_attempt_failed(DBusMessage * msg,const char * err)341 static inline DBusMessage *connection_attempt_failed(DBusMessage *msg,
342 							const char *err)
343 {
344 	return g_dbus_create_error(msg,
345 				ERROR_INTERFACE ".ConnectionAttemptFailed",
346 				err ? err : "Connection attempt failed");
347 }
348 
rfcomm_connect_cb(GIOChannel * chan,GError * err,gpointer user_data)349 static void rfcomm_connect_cb(GIOChannel *chan, GError *err, gpointer user_data)
350 {
351 	struct input_conn *iconn = user_data;
352 	struct input_device *idev = iconn->idev;
353 	struct fake_input *fake = iconn->fake;
354 	DBusMessage *reply;
355 
356 	if (err) {
357 		reply = connection_attempt_failed(iconn->pending_connect,
358 								err->message);
359 		goto failed;
360 	}
361 
362 	fake->rfcomm = g_io_channel_unix_get_fd(chan);
363 
364 	/*
365 	 * FIXME: Some headsets required a sco connection
366 	 * first to report volume gain key events
367 	 */
368 	fake->uinput = uinput_create(idev->name);
369 	if (fake->uinput < 0) {
370 		g_io_channel_shutdown(chan, TRUE, NULL);
371 		reply = connection_attempt_failed(iconn->pending_connect,
372 							strerror(errno));
373 		goto failed;
374 	}
375 
376 	fake->io = g_io_channel_unix_new(fake->rfcomm);
377 	g_io_channel_set_close_on_unref(fake->io, TRUE);
378 	g_io_add_watch(fake->io, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
379 						(GIOFunc) rfcomm_io_cb, fake);
380 
381 	/* Replying to the requestor */
382 	reply = dbus_message_new_method_return(iconn->pending_connect);
383 	g_dbus_send_message(idev->conn, reply);
384 
385 	dbus_message_unref(iconn->pending_connect);
386 	iconn->pending_connect = NULL;
387 
388 	return;
389 
390 failed:
391 	g_dbus_send_message(idev->conn, reply);
392 	dbus_message_unref(iconn->pending_connect);
393 	iconn->pending_connect = NULL;
394 }
395 
rfcomm_connect(struct input_conn * iconn,GError ** err)396 static gboolean rfcomm_connect(struct input_conn *iconn, GError **err)
397 {
398 	struct input_device *idev = iconn->idev;
399 	GIOChannel *io;
400 
401 	io = bt_io_connect(BT_IO_RFCOMM, rfcomm_connect_cb, iconn,
402 				NULL, err,
403 				BT_IO_OPT_SOURCE_BDADDR, &idev->src,
404 				BT_IO_OPT_DEST_BDADDR, &idev->dst,
405 				BT_IO_OPT_INVALID);
406 	if (!io)
407 		return FALSE;
408 
409 	g_io_channel_unref(io);
410 
411 	return TRUE;
412 }
413 
intr_watch_cb(GIOChannel * chan,GIOCondition cond,gpointer data)414 static gboolean intr_watch_cb(GIOChannel *chan, GIOCondition cond, gpointer data)
415 {
416 	struct input_conn *iconn = data;
417 	struct input_device *idev = iconn->idev;
418 	gboolean connected = FALSE;
419 
420 	/* Checking for ctrl_watch avoids a double g_io_channel_shutdown since
421 	 * it's likely that ctrl_watch_cb has been queued for dispatching in
422 	 * this mainloop iteration */
423 	if ((cond & (G_IO_HUP | G_IO_ERR)) && iconn->ctrl_watch)
424 		g_io_channel_shutdown(chan, TRUE, NULL);
425 
426 	emit_property_changed(idev->conn, idev->path, INPUT_DEVICE_INTERFACE,
427 				"Connected", DBUS_TYPE_BOOLEAN, &connected);
428 
429 	device_remove_disconnect_watch(idev->device, idev->dc_id);
430 	idev->dc_id = 0;
431 
432 	iconn->intr_watch = 0;
433 
434 	g_io_channel_unref(iconn->intr_io);
435 	iconn->intr_io = NULL;
436 
437 	/* Close control channel */
438 	if (iconn->ctrl_io && !(cond & G_IO_NVAL))
439 		g_io_channel_shutdown(iconn->ctrl_io, TRUE, NULL);
440 
441 	return FALSE;
442 }
443 
ctrl_watch_cb(GIOChannel * chan,GIOCondition cond,gpointer data)444 static gboolean ctrl_watch_cb(GIOChannel *chan, GIOCondition cond, gpointer data)
445 {
446 	struct input_conn *iconn = data;
447 
448 	/* Checking for intr_watch avoids a double g_io_channel_shutdown since
449 	 * it's likely that intr_watch_cb has been queued for dispatching in
450 	 * this mainloop iteration */
451 	if ((cond & (G_IO_HUP | G_IO_ERR)) && iconn->intr_watch)
452 		g_io_channel_shutdown(chan, TRUE, NULL);
453 
454 	iconn->ctrl_watch = 0;
455 
456 	g_io_channel_unref(iconn->ctrl_io);
457 	iconn->ctrl_io = NULL;
458 
459 	/* Close interrupt channel */
460 	if (iconn->intr_io && !(cond & G_IO_NVAL))
461 		g_io_channel_shutdown(iconn->intr_io, TRUE, NULL);
462 
463 	return FALSE;
464 }
465 
fake_hid_connect(struct input_conn * iconn,GError ** err)466 static gboolean fake_hid_connect(struct input_conn *iconn, GError **err)
467 {
468 	struct fake_hid *fhid = iconn->fake->priv;
469 
470 	return fhid->connect(iconn->fake, err);
471 }
472 
fake_hid_disconnect(struct input_conn * iconn)473 static int fake_hid_disconnect(struct input_conn *iconn)
474 {
475 	struct fake_hid *fhid = iconn->fake->priv;
476 
477 	return fhid->disconnect(iconn->fake);
478 }
479 
epox_endian_quirk(unsigned char * data,int size)480 static void epox_endian_quirk(unsigned char *data, int size)
481 {
482 	/* USAGE_PAGE (Keyboard)	05 07
483 	 * USAGE_MINIMUM (0)		19 00
484 	 * USAGE_MAXIMUM (65280)	2A 00 FF   <= must be FF 00
485 	 * LOGICAL_MINIMUM (0)		15 00
486 	 * LOGICAL_MAXIMUM (65280)	26 00 FF   <= must be FF 00
487 	 */
488 	unsigned char pattern[] = { 0x05, 0x07, 0x19, 0x00, 0x2a, 0x00, 0xff,
489 						0x15, 0x00, 0x26, 0x00, 0xff };
490 	unsigned int i;
491 
492 	if (!data)
493 		return;
494 
495 	for (i = 0; i < size - sizeof(pattern); i++) {
496 		if (!memcmp(data + i, pattern, sizeof(pattern))) {
497 			data[i + 5] = 0xff;
498 			data[i + 6] = 0x00;
499 			data[i + 10] = 0xff;
500 			data[i + 11] = 0x00;
501 		}
502 	}
503 }
504 
extract_hid_record(sdp_record_t * rec,struct hidp_connadd_req * req)505 static void extract_hid_record(sdp_record_t *rec, struct hidp_connadd_req *req)
506 {
507 	sdp_data_t *pdlist, *pdlist2;
508 	uint8_t attr_val;
509 
510 	pdlist = sdp_data_get(rec, 0x0101);
511 	pdlist2 = sdp_data_get(rec, 0x0102);
512 	if (pdlist) {
513 		if (pdlist2) {
514 			if (strncmp(pdlist->val.str, pdlist2->val.str, 5)) {
515 				strncpy(req->name, pdlist2->val.str, 127);
516 				strcat(req->name, " ");
517 			}
518 			strncat(req->name, pdlist->val.str, 127 - strlen(req->name));
519 		} else
520 			strncpy(req->name, pdlist->val.str, 127);
521 	} else {
522 		pdlist2 = sdp_data_get(rec, 0x0100);
523 		if (pdlist2)
524 			strncpy(req->name, pdlist2->val.str, 127);
525 	}
526 
527 	pdlist = sdp_data_get(rec, SDP_ATTR_HID_PARSER_VERSION);
528 	req->parser = pdlist ? pdlist->val.uint16 : 0x0100;
529 
530 	pdlist = sdp_data_get(rec, SDP_ATTR_HID_DEVICE_SUBCLASS);
531 	req->subclass = pdlist ? pdlist->val.uint8 : 0;
532 
533 	pdlist = sdp_data_get(rec, SDP_ATTR_HID_COUNTRY_CODE);
534 	req->country = pdlist ? pdlist->val.uint8 : 0;
535 
536 	pdlist = sdp_data_get(rec, SDP_ATTR_HID_VIRTUAL_CABLE);
537 	attr_val = pdlist ? pdlist->val.uint8 : 0;
538 	if (attr_val)
539 		req->flags |= (1 << HIDP_VIRTUAL_CABLE_UNPLUG);
540 
541 	pdlist = sdp_data_get(rec, SDP_ATTR_HID_BOOT_DEVICE);
542 	attr_val = pdlist ? pdlist->val.uint8 : 0;
543 	if (attr_val)
544 		req->flags |= (1 << HIDP_BOOT_PROTOCOL_MODE);
545 
546 	pdlist = sdp_data_get(rec, SDP_ATTR_HID_DESCRIPTOR_LIST);
547 	if (pdlist) {
548 		pdlist = pdlist->val.dataseq;
549 		pdlist = pdlist->val.dataseq;
550 		pdlist = pdlist->next;
551 
552 		req->rd_data = g_try_malloc0(pdlist->unitSize);
553 		if (req->rd_data) {
554 			memcpy(req->rd_data, (unsigned char *) pdlist->val.str,
555 								pdlist->unitSize);
556 			req->rd_size = pdlist->unitSize;
557 			epox_endian_quirk(req->rd_data, req->rd_size);
558 		}
559 	}
560 }
561 
ioctl_connadd(struct hidp_connadd_req * req)562 static int ioctl_connadd(struct hidp_connadd_req *req)
563 {
564 	int ctl, err = 0;
565 
566 	ctl = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HIDP);
567 	if (ctl < 0)
568 		return -errno;
569 
570 	if (ioctl(ctl, HIDPCONNADD, req) < 0)
571 		err = errno;
572 
573 	close(ctl);
574 
575 	return -err;
576 }
577 
encrypt_completed(uint8_t status,gpointer user_data)578 static void encrypt_completed(uint8_t status, gpointer user_data)
579 {
580 	struct hidp_connadd_req *req = user_data;
581 	int err;
582 
583 	if (status) {
584 		error("Encryption failed: %s(0x%x)",
585 				strerror(bt_error(status)), status);
586 		goto failed;
587 	}
588 
589 	err = ioctl_connadd(req);
590 	if (err == 0)
591 		goto cleanup;
592 
593 	error("ioctl_connadd(): %s(%d)", strerror(-err), -err);
594 failed:
595 	close(req->intr_sock);
596 	close(req->ctrl_sock);
597 
598 cleanup:
599 	if (req->rd_data)
600 		free(req->rd_data);
601 
602 	g_free(req);
603 }
604 
hidp_add_connection(const struct input_device * idev,const struct input_conn * iconn)605 static int hidp_add_connection(const struct input_device *idev,
606 				const struct input_conn *iconn)
607 {
608 	struct hidp_connadd_req *req;
609 	struct fake_hid *fake_hid;
610 	struct fake_input *fake;
611 	sdp_record_t *rec;
612 	char src_addr[18], dst_addr[18];
613 	int err;
614 
615 	req = g_new0(struct hidp_connadd_req, 1);
616 	req->ctrl_sock = g_io_channel_unix_get_fd(iconn->ctrl_io);
617 	req->intr_sock = g_io_channel_unix_get_fd(iconn->intr_io);
618 	req->flags     = 0;
619 	req->idle_to   = iconn->timeout;
620 
621 	ba2str(&idev->src, src_addr);
622 	ba2str(&idev->dst, dst_addr);
623 
624 	rec = fetch_record(src_addr, dst_addr, idev->handle);
625 	if (!rec) {
626 		error("Rejected connection from unknown device %s", dst_addr);
627 		err = -EPERM;
628 		goto cleanup;
629 	}
630 
631 	extract_hid_record(rec, req);
632 	sdp_record_free(rec);
633 
634 	read_device_id(src_addr, dst_addr, NULL,
635 				&req->vendor, &req->product, &req->version);
636 
637 	fake_hid = get_fake_hid(req->vendor, req->product);
638 	if (fake_hid) {
639 		fake = g_new0(struct fake_input, 1);
640 		fake->connect = fake_hid_connect;
641 		fake->disconnect = fake_hid_disconnect;
642 		fake->priv = fake_hid;
643 		err = fake_hid_connadd(fake, iconn->intr_io, fake_hid);
644 		goto cleanup;
645 	}
646 
647 	if (idev->name)
648 		strncpy(req->name, idev->name, sizeof(req->name) - 1);
649 
650 	/* Encryption is mandatory for keyboards */
651 	if (req->subclass & 0x40) {
652 		err = bt_acl_encrypt(&idev->src, &idev->dst, encrypt_completed, req);
653 		if (err == 0) {
654 			/* Waiting async encryption */
655 			return 0;
656 		} else if (err != -EALREADY) {
657 			error("bt_acl_encrypt(): %s(%d)", strerror(-err), -err);
658 			goto cleanup;
659 		}
660 	}
661 
662 	if (req->vendor == 0x054c && req->product == 0x0268) {
663 		unsigned char buf[] = { 0x53, 0xf4,  0x42, 0x03, 0x00, 0x00 };
664 		int sk = g_io_channel_unix_get_fd(iconn->ctrl_io);
665 		err = write(sk, buf, sizeof(buf));
666 	}
667 
668 	err = ioctl_connadd(req);
669 
670 cleanup:
671 	if (req->rd_data)
672 		free(req->rd_data);
673 	g_free(req);
674 
675 	return err;
676 }
677 
is_connected(struct input_conn * iconn)678 static int is_connected(struct input_conn *iconn)
679 {
680 	struct input_device *idev = iconn->idev;
681 	struct fake_input *fake = iconn->fake;
682 	struct hidp_conninfo ci;
683 	int ctl;
684 
685 	/* Fake input */
686 	if (fake)
687 		return fake->flags & FI_FLAG_CONNECTED;
688 
689 	/* Standard HID */
690 	ctl = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HIDP);
691 	if (ctl < 0)
692 		return 0;
693 
694 	memset(&ci, 0, sizeof(ci));
695 	bacpy(&ci.bdaddr, &idev->dst);
696 	if (ioctl(ctl, HIDPGETCONNINFO, &ci) < 0) {
697 		close(ctl);
698 		return 0;
699 	}
700 
701 	close(ctl);
702 
703 	if (ci.state != BT_CONNECTED)
704 		return 0;
705 	else
706 		return 1;
707 }
708 
connection_disconnect(struct input_conn * iconn,uint32_t flags)709 static int connection_disconnect(struct input_conn *iconn, uint32_t flags)
710 {
711 	struct input_device *idev = iconn->idev;
712 	struct fake_input *fake = iconn->fake;
713 	struct hidp_conndel_req req;
714 	struct hidp_conninfo ci;
715 	int ctl, err;
716 
717 	/* Fake input disconnect */
718 	if (fake) {
719 		err = fake->disconnect(iconn);
720 		if (err == 0)
721 			fake->flags &= ~FI_FLAG_CONNECTED;
722 		return err;
723 	}
724 
725 	/* Standard HID disconnect */
726 	if (iconn->intr_io)
727 		g_io_channel_shutdown(iconn->intr_io, TRUE, NULL);
728 	if (iconn->ctrl_io)
729 		g_io_channel_shutdown(iconn->ctrl_io, TRUE, NULL);
730 
731 	ctl = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HIDP);
732 	if (ctl < 0) {
733 		error("Can't open HIDP control socket");
734 		return -errno;
735 	}
736 
737 	memset(&ci, 0, sizeof(ci));
738 	bacpy(&ci.bdaddr, &idev->dst);
739 	if ((ioctl(ctl, HIDPGETCONNINFO, &ci) < 0) ||
740 				(ci.state != BT_CONNECTED)) {
741 		errno = ENOTCONN;
742 		goto fail;
743 	}
744 
745 	memset(&req, 0, sizeof(req));
746 	bacpy(&req.bdaddr, &idev->dst);
747 	req.flags = flags;
748 	if (ioctl(ctl, HIDPCONNDEL, &req) < 0) {
749 		error("Can't delete the HID device: %s(%d)",
750 				strerror(errno), errno);
751 		goto fail;
752 	}
753 
754 	close(ctl);
755 
756 	return 0;
757 
758 fail:
759 	err = errno;
760 	close(ctl);
761 	errno = err;
762 
763 	return -err;
764 }
765 
disconnect(struct input_device * idev,uint32_t flags)766 static int disconnect(struct input_device *idev, uint32_t flags)
767 {
768 	struct input_conn *iconn = NULL;
769 	GSList *l;
770 
771 	for (l = idev->connections; l; l = l->next) {
772 		iconn = l->data;
773 
774 		if (is_connected(iconn))
775 			break;
776 	}
777 
778 	if (!iconn)
779 		return ENOTCONN;
780 
781 	return connection_disconnect(iconn, flags);
782 }
783 
disconnect_cb(struct btd_device * device,gboolean removal,void * user_data)784 static void disconnect_cb(struct btd_device *device, gboolean removal,
785 				void *user_data)
786 {
787 	struct input_device *idev = user_data;
788 	int flags;
789 
790 	info("Input: disconnect %s", idev->path);
791 
792 	flags = removal ? (1 << HIDP_VIRTUAL_CABLE_UNPLUG) : 0;
793 
794 	disconnect(idev, flags);
795 }
796 
input_device_connected(struct input_device * idev,struct input_conn * iconn)797 static int input_device_connected(struct input_device *idev,
798 						struct input_conn *iconn)
799 {
800 	dbus_bool_t connected;
801 	int err;
802 
803 	if (iconn->intr_io == NULL || iconn->ctrl_io == NULL)
804 		return -ENOTCONN;
805 
806 	err = hidp_add_connection(idev, iconn);
807 	if (err < 0)
808 		return err;
809 
810 	iconn->intr_watch = g_io_add_watch(iconn->intr_io,
811 					G_IO_HUP | G_IO_ERR | G_IO_NVAL,
812 					intr_watch_cb, iconn);
813 	iconn->ctrl_watch = g_io_add_watch(iconn->ctrl_io,
814 					G_IO_HUP | G_IO_ERR | G_IO_NVAL,
815 					ctrl_watch_cb, iconn);
816 
817 	connected = TRUE;
818 	emit_property_changed(idev->conn, idev->path, INPUT_DEVICE_INTERFACE,
819 				"Connected", DBUS_TYPE_BOOLEAN, &connected);
820 
821 	idev->dc_id = device_add_disconnect_watch(idev->device, disconnect_cb,
822 							idev, NULL);
823 
824 	return 0;
825 }
826 
interrupt_connect_cb(GIOChannel * chan,GError * conn_err,gpointer user_data)827 static void interrupt_connect_cb(GIOChannel *chan, GError *conn_err,
828 							gpointer user_data)
829 {
830 	struct input_conn *iconn = user_data;
831 	struct input_device *idev = iconn->idev;
832 	DBusMessage *reply;
833 	int err;
834 	const char *err_msg;
835 
836 	if (conn_err) {
837 		err_msg = conn_err->message;
838 		g_io_channel_unref(iconn->intr_io);
839 		iconn->intr_io = NULL;
840 		goto failed;
841 	}
842 
843 	err = input_device_connected(idev, iconn);
844 	if (err < 0) {
845 		err_msg = strerror(-err);
846 		goto failed;
847 	}
848 
849 	/* Replying to the requestor */
850 	g_dbus_send_reply(idev->conn, iconn->pending_connect, DBUS_TYPE_INVALID);
851 
852 	dbus_message_unref(iconn->pending_connect);
853 	iconn->pending_connect = NULL;
854 
855 	return;
856 
857 failed:
858 	error("%s", err_msg);
859 	reply = connection_attempt_failed(iconn->pending_connect, err_msg);
860 	g_dbus_send_message(idev->conn, reply);
861 
862 	if (iconn->ctrl_io)
863 		g_io_channel_shutdown(iconn->ctrl_io, FALSE, NULL);
864 
865 	if (iconn->intr_io) {
866 		if (!conn_err)
867 			g_io_channel_shutdown(iconn->intr_io, FALSE, NULL);
868 		g_io_channel_unref(iconn->intr_io);
869 		iconn->intr_io = NULL;
870 	}
871 }
872 
control_connect_cb(GIOChannel * chan,GError * conn_err,gpointer user_data)873 static void control_connect_cb(GIOChannel *chan, GError *conn_err,
874 							gpointer user_data)
875 {
876 	struct input_conn *iconn = user_data;
877 	struct input_device *idev = iconn->idev;
878 	DBusMessage *reply;
879 	GIOChannel *io;
880 	GError *err = NULL;
881 
882 	if (conn_err) {
883 		error("%s", conn_err->message);
884 		reply = connection_attempt_failed(iconn->pending_connect,
885 							conn_err->message);
886 		goto failed;
887 	}
888 
889 	/* Connect to the HID interrupt channel */
890 	io = bt_io_connect(BT_IO_L2CAP, interrupt_connect_cb, iconn,
891 				NULL, &err,
892 				BT_IO_OPT_SOURCE_BDADDR, &idev->src,
893 				BT_IO_OPT_DEST_BDADDR, &idev->dst,
894 				BT_IO_OPT_PSM, L2CAP_PSM_HIDP_INTR,
895 				BT_IO_OPT_INVALID);
896 	if (!io) {
897 		error("%s", err->message);
898 		reply = connection_attempt_failed(iconn->pending_connect,
899 							err->message);
900 		g_error_free(err);
901 		g_io_channel_shutdown(chan, TRUE, NULL);
902 		goto failed;
903 	}
904 
905 	iconn->intr_io = io;
906 
907 	return;
908 
909 failed:
910 	g_dbus_send_message(idev->conn, reply);
911 	dbus_message_unref(iconn->pending_connect);
912 	iconn->pending_connect = NULL;
913 }
914 
fake_disconnect(struct input_conn * iconn)915 static int fake_disconnect(struct input_conn *iconn)
916 {
917 	struct fake_input *fake = iconn->fake;
918 
919 	if (!fake->io)
920 		return -ENOTCONN;
921 
922 	g_io_channel_shutdown(fake->io, TRUE, NULL);
923 	g_io_channel_unref(fake->io);
924 	fake->io = NULL;
925 
926 	if (fake->uinput >= 0) {
927 		ioctl(fake->uinput, UI_DEV_DESTROY);
928 		close(fake->uinput);
929 		fake->uinput = -1;
930 	}
931 
932 	return 0;
933 }
934 
935 /*
936  * Input Device methods
937  */
input_device_connect(DBusConnection * conn,DBusMessage * msg,void * data)938 static DBusMessage *input_device_connect(DBusConnection *conn,
939 					DBusMessage *msg, void *data)
940 {
941 	struct input_device *idev = data;
942 	struct input_conn *iconn;
943 	struct fake_input *fake;
944 	DBusMessage *reply;
945 	GError *err = NULL;
946 
947 	iconn = find_connection(idev->connections, "HID");
948 	if (!iconn)
949 		return not_supported(msg);
950 
951 	if (iconn->pending_connect)
952 		return in_progress(msg);
953 
954 	if (is_connected(iconn))
955 		return already_connected(msg);
956 
957 	iconn->pending_connect = dbus_message_ref(msg);
958 	fake = iconn->fake;
959 
960 	if (fake) {
961 		/* Fake input device */
962 		if (fake->connect(iconn, &err))
963 			fake->flags |= FI_FLAG_CONNECTED;
964 	} else {
965 		/* HID devices */
966 		GIOChannel *io;
967 
968 		io = bt_io_connect(BT_IO_L2CAP, control_connect_cb, iconn,
969 					NULL, &err,
970 					BT_IO_OPT_SOURCE_BDADDR, &idev->src,
971 					BT_IO_OPT_DEST_BDADDR, &idev->dst,
972 					BT_IO_OPT_PSM, L2CAP_PSM_HIDP_CTRL,
973 					BT_IO_OPT_INVALID);
974 		iconn->ctrl_io = io;
975 	}
976 
977 	if (err == NULL)
978 		return NULL;
979 
980 	error("%s", err->message);
981 	dbus_message_unref(iconn->pending_connect);
982 	iconn->pending_connect = NULL;
983 	reply = connection_attempt_failed(msg, err->message);
984 	g_error_free(err);
985 	return reply;
986 }
987 
create_errno_message(DBusMessage * msg,int err)988 static DBusMessage *create_errno_message(DBusMessage *msg, int err)
989 {
990 	return g_dbus_create_error(msg, ERROR_INTERFACE ".Failed",
991 							strerror(err));
992 }
993 
input_device_disconnect(DBusConnection * conn,DBusMessage * msg,void * data)994 static DBusMessage *input_device_disconnect(DBusConnection *conn,
995 						DBusMessage *msg, void *data)
996 {
997 	struct input_device *idev = data;
998 	int err;
999 
1000 	err = disconnect(idev, 0);
1001 	if (err < 0)
1002 		return create_errno_message(msg, -err);
1003 
1004 	return g_dbus_create_reply(msg, DBUS_TYPE_INVALID);
1005 }
1006 
device_unregister(void * data)1007 static void device_unregister(void *data)
1008 {
1009 	struct input_device *idev = data;
1010 
1011 	debug("Unregistered interface %s on path %s", INPUT_DEVICE_INTERFACE,
1012 								idev->path);
1013 
1014 	devices = g_slist_remove(devices, idev);
1015 	input_device_free(idev);
1016 }
1017 
connected_cmp(gpointer a,gpointer b)1018 static gint connected_cmp(gpointer a, gpointer b)
1019 {
1020 	struct input_conn *iconn = a;
1021 
1022 	return !is_connected(iconn);
1023 }
1024 
input_device_get_properties(DBusConnection * conn,DBusMessage * msg,void * data)1025 static DBusMessage *input_device_get_properties(DBusConnection *conn,
1026 					DBusMessage *msg, void *data)
1027 {
1028 	struct input_device *idev = data;
1029 	DBusMessage *reply;
1030 	DBusMessageIter iter;
1031 	DBusMessageIter dict;
1032 	dbus_bool_t connected;
1033 
1034 	reply = dbus_message_new_method_return(msg);
1035 	if (!reply)
1036 		return NULL;
1037 
1038 	dbus_message_iter_init_append(reply, &iter);
1039 
1040 	dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
1041 			DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
1042 			DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING
1043 			DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &dict);
1044 
1045 	/* Connected */
1046 	connected = !!g_slist_find_custom(idev->connections, NULL,
1047 					(GCompareFunc) connected_cmp);
1048 	dict_append_entry(&dict, "Connected", DBUS_TYPE_BOOLEAN, &connected);
1049 
1050 	dbus_message_iter_close_container(&iter, &dict);
1051 
1052 	return reply;
1053 }
1054 
1055 static GDBusMethodTable device_methods[] = {
1056 	{ "Connect",		"",	"",	input_device_connect,
1057 						G_DBUS_METHOD_FLAG_ASYNC },
1058 	{ "Disconnect",		"",	"",	input_device_disconnect	},
1059 	{ "GetProperties",	"",	"a{sv}",input_device_get_properties },
1060 	{ }
1061 };
1062 
1063 static GDBusSignalTable device_signals[] = {
1064 	{ "PropertyChanged",	"sv"	},
1065 	{ }
1066 };
1067 
input_device_new(DBusConnection * conn,struct btd_device * device,const char * path,const bdaddr_t * src,const bdaddr_t * dst,const uint32_t handle)1068 static struct input_device *input_device_new(DBusConnection *conn,
1069 					struct btd_device *device, const char *path,
1070 					const bdaddr_t *src, const bdaddr_t *dst,
1071 					const uint32_t handle)
1072 {
1073 	struct input_device *idev;
1074 	char name[249], src_addr[18], dst_addr[18];
1075 
1076 	idev = g_new0(struct input_device, 1);
1077 	bacpy(&idev->src, src);
1078 	bacpy(&idev->dst, dst);
1079 	idev->device = btd_device_ref(device);
1080 	idev->path = g_strdup(path);
1081 	idev->conn = dbus_connection_ref(conn);
1082 	idev->handle = handle;
1083 
1084 	ba2str(src, src_addr);
1085 	ba2str(dst, dst_addr);
1086 	if (read_device_name(src_addr, dst_addr, name) == 0)
1087 		idev->name = g_strdup(name);
1088 
1089 	if (g_dbus_register_interface(conn, idev->path, INPUT_DEVICE_INTERFACE,
1090 					device_methods, device_signals, NULL,
1091 					idev, device_unregister) == FALSE) {
1092 		error("Failed to register interface %s on path %s",
1093 			INPUT_DEVICE_INTERFACE, path);
1094 		input_device_free(idev);
1095 		return NULL;
1096 	}
1097 
1098 	debug("Registered interface %s on path %s",
1099 			INPUT_DEVICE_INTERFACE, idev->path);
1100 
1101 	return idev;
1102 }
1103 
input_conn_new(struct input_device * idev,const char * uuid,const char * alias,int timeout)1104 static struct input_conn *input_conn_new(struct input_device *idev,
1105 					const char *uuid, const char *alias,
1106 					int timeout)
1107 {
1108 	struct input_conn *iconn;
1109 
1110 	iconn = g_new0(struct input_conn, 1);
1111 	iconn->timeout = timeout;
1112 	iconn->uuid = g_strdup(uuid);
1113 	iconn->alias = g_strdup(alias);
1114 	iconn->idev = idev;
1115 
1116 	return iconn;
1117 }
1118 
input_device_register(DBusConnection * conn,struct btd_device * device,const char * path,const bdaddr_t * src,const bdaddr_t * dst,const char * uuid,uint32_t handle,int timeout)1119 int input_device_register(DBusConnection *conn, struct btd_device *device,
1120 			const char *path, const bdaddr_t *src,
1121 			const bdaddr_t *dst, const char *uuid,
1122 			uint32_t handle, int timeout)
1123 {
1124 	struct input_device *idev;
1125 	struct input_conn *iconn;
1126 
1127 	idev = find_device_by_path(devices, path);
1128 	if (!idev) {
1129 		idev = input_device_new(conn, device, path, src, dst, handle);
1130 		if (!idev)
1131 			return -EINVAL;
1132 		devices = g_slist_append(devices, idev);
1133 	}
1134 
1135 	iconn = input_conn_new(idev, uuid, "hid", timeout);
1136 	if (!iconn)
1137 		return -EINVAL;
1138 
1139 	idev->connections = g_slist_append(idev->connections, iconn);
1140 
1141 	return 0;
1142 }
1143 
fake_input_register(DBusConnection * conn,struct btd_device * device,const char * path,bdaddr_t * src,bdaddr_t * dst,const char * uuid,uint8_t channel)1144 int fake_input_register(DBusConnection *conn, struct btd_device *device,
1145 			const char *path, bdaddr_t *src, bdaddr_t *dst,
1146 			const char *uuid, uint8_t channel)
1147 {
1148 	struct input_device *idev;
1149 	struct input_conn *iconn;
1150 
1151 	idev = find_device_by_path(devices, path);
1152 	if (!idev) {
1153 		idev = input_device_new(conn, device, path, src, dst, 0);
1154 		if (!idev)
1155 			return -EINVAL;
1156 		devices = g_slist_append(devices, idev);
1157 	}
1158 
1159 	iconn = input_conn_new(idev, uuid, "hsp", 0);
1160 	if (!iconn)
1161 		return -EINVAL;
1162 
1163 	iconn->fake = g_new0(struct fake_input, 1);
1164 	iconn->fake->ch = channel;
1165 	iconn->fake->connect = rfcomm_connect;
1166 	iconn->fake->disconnect = fake_disconnect;
1167 
1168 	idev->connections = g_slist_append(idev->connections, iconn);
1169 
1170 	return 0;
1171 }
1172 
find_device(const bdaddr_t * src,const bdaddr_t * dst)1173 static struct input_device *find_device(const bdaddr_t *src,
1174 					const bdaddr_t *dst)
1175 {
1176 	GSList *list;
1177 
1178 	for (list = devices; list != NULL; list = list->next) {
1179 		struct input_device *idev = list->data;
1180 
1181 		if (!bacmp(&idev->src, src) && !bacmp(&idev->dst, dst))
1182 			return idev;
1183 	}
1184 
1185 	return NULL;
1186 }
1187 
input_device_unregister(const char * path,const char * uuid)1188 int input_device_unregister(const char *path, const char *uuid)
1189 {
1190 	struct input_device *idev;
1191 	struct input_conn *iconn;
1192 
1193 	idev = find_device_by_path(devices, path);
1194 	if (idev == NULL)
1195 		return -EINVAL;
1196 
1197 	iconn = find_connection(idev->connections, uuid);
1198 	if (iconn == NULL)
1199 		return -EINVAL;
1200 
1201 	if (iconn->pending_connect) {
1202 		/* Pending connection running */
1203 		return -EBUSY;
1204 	}
1205 
1206 	idev->connections = g_slist_remove(idev->connections, iconn);
1207 	input_conn_free(iconn);
1208 	if (idev->connections)
1209 		return 0;
1210 
1211 	g_dbus_unregister_interface(idev->conn, path, INPUT_DEVICE_INTERFACE);
1212 
1213 	return 0;
1214 }
1215 
input_device_connadd(struct input_device * idev,struct input_conn * iconn)1216 static int input_device_connadd(struct input_device *idev,
1217 				struct input_conn *iconn)
1218 {
1219 	int err;
1220 
1221 	err = input_device_connected(idev, iconn);
1222 	if (err < 0)
1223 		goto error;
1224 
1225 	return 0;
1226 
1227 error:
1228 	if (iconn->ctrl_io) {
1229 		g_io_channel_shutdown(iconn->ctrl_io, FALSE, NULL);
1230 		g_io_channel_unref(iconn->ctrl_io);
1231 		iconn->ctrl_io = NULL;
1232 	}
1233 	if (iconn->intr_io) {
1234 		g_io_channel_shutdown(iconn->intr_io, FALSE, NULL);
1235 		g_io_channel_unref(iconn->intr_io);
1236 		iconn->intr_io = NULL;
1237 	}
1238 
1239 	return err;
1240 }
1241 
input_device_set_channel(const bdaddr_t * src,const bdaddr_t * dst,int psm,GIOChannel * io)1242 int input_device_set_channel(const bdaddr_t *src, const bdaddr_t *dst, int psm,
1243 								GIOChannel *io)
1244 {
1245 	struct input_device *idev = find_device(src, dst);
1246 	struct input_conn *iconn;
1247 
1248 	if (!idev)
1249 		return -ENOENT;
1250 
1251 	iconn = find_connection(idev->connections, "hid");
1252 	if (!iconn)
1253 		return -ENOENT;
1254 
1255 	switch (psm) {
1256 	case L2CAP_PSM_HIDP_CTRL:
1257 		if (iconn->ctrl_io)
1258 			return -EALREADY;
1259 		iconn->ctrl_io = g_io_channel_ref(io);
1260 		break;
1261 	case L2CAP_PSM_HIDP_INTR:
1262 		if (iconn->intr_io)
1263 			return -EALREADY;
1264 		iconn->intr_io = g_io_channel_ref(io);
1265 		break;
1266 	}
1267 
1268 	if (iconn->intr_io && iconn->ctrl_io)
1269 		input_device_connadd(idev, iconn);
1270 
1271 	return 0;
1272 }
1273 
input_device_close_channels(const bdaddr_t * src,const bdaddr_t * dst)1274 int input_device_close_channels(const bdaddr_t *src, const bdaddr_t *dst)
1275 {
1276 	struct input_device *idev = find_device(src, dst);
1277 	struct input_conn *iconn;
1278 
1279 	if (!idev)
1280 		return -ENOENT;
1281 
1282 	iconn = find_connection(idev->connections, "hid");
1283 	if (!iconn)
1284 		return -ENOENT;
1285 
1286 	if (iconn->intr_io)
1287 		g_io_channel_shutdown(iconn->intr_io, TRUE, NULL);
1288 
1289 	if (iconn->ctrl_io)
1290 		g_io_channel_shutdown(iconn->ctrl_io, TRUE, NULL);
1291 
1292 	return 0;
1293 }
1294