Home | History | Annotate | Download | only in input
      1 /*
      2  *
      3  *  BlueZ - Bluetooth protocol stack for Linux
      4  *
      5  *  Copyright (C) 2004-2010  Marcel Holtmann <marcel (at) 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 "log.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 
    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 
    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 
    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 
    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 
    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 
    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 
    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 
    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 
    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 	DBG("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 
    323 static inline DBusMessage *not_supported(DBusMessage *msg)
    324 {
    325 	return g_dbus_create_error(msg, ERROR_INTERFACE ".Failed",
    326 							"Not supported");
    327 }
    328 
    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 
    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 
    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 
    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 
    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 
    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 
    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 
    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 
    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 
    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 
    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 
    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 
    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 	free(req->rd_data);
    600 
    601 	g_free(req);
    602 }
    603 
    604 static int hidp_add_connection(const struct input_device *idev,
    605 				const struct input_conn *iconn)
    606 {
    607 	struct hidp_connadd_req *req;
    608 	struct fake_hid *fake_hid;
    609 	struct fake_input *fake;
    610 	sdp_record_t *rec;
    611 	char src_addr[18], dst_addr[18];
    612 	int err;
    613 
    614 	req = g_new0(struct hidp_connadd_req, 1);
    615 	req->ctrl_sock = g_io_channel_unix_get_fd(iconn->ctrl_io);
    616 	req->intr_sock = g_io_channel_unix_get_fd(iconn->intr_io);
    617 	req->flags     = 0;
    618 	req->idle_to   = iconn->timeout;
    619 
    620 	ba2str(&idev->src, src_addr);
    621 	ba2str(&idev->dst, dst_addr);
    622 
    623 	rec = fetch_record(src_addr, dst_addr, idev->handle);
    624 	if (!rec) {
    625 		error("Rejected connection from unknown device %s", dst_addr);
    626 		err = -EPERM;
    627 		goto cleanup;
    628 	}
    629 
    630 	extract_hid_record(rec, req);
    631 	sdp_record_free(rec);
    632 
    633 	read_device_id(src_addr, dst_addr, NULL,
    634 				&req->vendor, &req->product, &req->version);
    635 
    636 	fake_hid = get_fake_hid(req->vendor, req->product);
    637 	if (fake_hid) {
    638 		fake = g_new0(struct fake_input, 1);
    639 		fake->connect = fake_hid_connect;
    640 		fake->disconnect = fake_hid_disconnect;
    641 		fake->priv = fake_hid;
    642 		err = fake_hid_connadd(fake, iconn->intr_io, fake_hid);
    643 		goto cleanup;
    644 	}
    645 
    646 	if (idev->name)
    647 		strncpy(req->name, idev->name, sizeof(req->name) - 1);
    648 
    649 	/* Encryption is mandatory for keyboards */
    650 	if (req->subclass & 0x40) {
    651 		err = bt_acl_encrypt(&idev->src, &idev->dst, encrypt_completed, req);
    652 		if (err == 0) {
    653 			/* Waiting async encryption */
    654 			return 0;
    655 		} else if (err != -EALREADY) {
    656 			error("bt_acl_encrypt(): %s(%d)", strerror(-err), -err);
    657 			goto cleanup;
    658 		}
    659 	}
    660 
    661 	err = ioctl_connadd(req);
    662 
    663 cleanup:
    664 	free(req->rd_data);
    665 	g_free(req);
    666 
    667 	return err;
    668 }
    669 
    670 static int is_connected(struct input_conn *iconn)
    671 {
    672 	struct input_device *idev = iconn->idev;
    673 	struct fake_input *fake = iconn->fake;
    674 	struct hidp_conninfo ci;
    675 	int ctl;
    676 
    677 	/* Fake input */
    678 	if (fake)
    679 		return fake->flags & FI_FLAG_CONNECTED;
    680 
    681 	/* Standard HID */
    682 	ctl = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HIDP);
    683 	if (ctl < 0)
    684 		return 0;
    685 
    686 	memset(&ci, 0, sizeof(ci));
    687 	bacpy(&ci.bdaddr, &idev->dst);
    688 	if (ioctl(ctl, HIDPGETCONNINFO, &ci) < 0) {
    689 		close(ctl);
    690 		return 0;
    691 	}
    692 
    693 	close(ctl);
    694 
    695 	if (ci.state != BT_CONNECTED)
    696 		return 0;
    697 	else
    698 		return 1;
    699 }
    700 
    701 static int connection_disconnect(struct input_conn *iconn, uint32_t flags)
    702 {
    703 	struct input_device *idev = iconn->idev;
    704 	struct fake_input *fake = iconn->fake;
    705 	struct hidp_conndel_req req;
    706 	struct hidp_conninfo ci;
    707 	int ctl, err;
    708 
    709 	/* Fake input disconnect */
    710 	if (fake) {
    711 		err = fake->disconnect(iconn);
    712 		if (err == 0)
    713 			fake->flags &= ~FI_FLAG_CONNECTED;
    714 		return err;
    715 	}
    716 
    717 	/* Standard HID disconnect */
    718 	if (iconn->intr_io)
    719 		g_io_channel_shutdown(iconn->intr_io, TRUE, NULL);
    720 	if (iconn->ctrl_io)
    721 		g_io_channel_shutdown(iconn->ctrl_io, TRUE, NULL);
    722 
    723 	ctl = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HIDP);
    724 	if (ctl < 0) {
    725 		error("Can't open HIDP control socket");
    726 		return -errno;
    727 	}
    728 
    729 	memset(&ci, 0, sizeof(ci));
    730 	bacpy(&ci.bdaddr, &idev->dst);
    731 	if ((ioctl(ctl, HIDPGETCONNINFO, &ci) < 0) ||
    732 				(ci.state != BT_CONNECTED)) {
    733 		errno = ENOTCONN;
    734 		goto fail;
    735 	}
    736 
    737 	memset(&req, 0, sizeof(req));
    738 	bacpy(&req.bdaddr, &idev->dst);
    739 	req.flags = flags;
    740 	if (ioctl(ctl, HIDPCONNDEL, &req) < 0) {
    741 		error("Can't delete the HID device: %s(%d)",
    742 				strerror(errno), errno);
    743 		goto fail;
    744 	}
    745 
    746 	close(ctl);
    747 
    748 	return 0;
    749 
    750 fail:
    751 	err = errno;
    752 	close(ctl);
    753 	errno = err;
    754 
    755 	return -err;
    756 }
    757 
    758 static int disconnect(struct input_device *idev, uint32_t flags)
    759 {
    760 	struct input_conn *iconn = NULL;
    761 	GSList *l;
    762 
    763 	for (l = idev->connections; l; l = l->next) {
    764 		iconn = l->data;
    765 
    766 		if (is_connected(iconn))
    767 			break;
    768 	}
    769 
    770 	if (!iconn)
    771 		return ENOTCONN;
    772 
    773 	return connection_disconnect(iconn, flags);
    774 }
    775 
    776 static void disconnect_cb(struct btd_device *device, gboolean removal,
    777 				void *user_data)
    778 {
    779 	struct input_device *idev = user_data;
    780 	int flags;
    781 
    782 	info("Input: disconnect %s", idev->path);
    783 
    784 	flags = removal ? (1 << HIDP_VIRTUAL_CABLE_UNPLUG) : 0;
    785 
    786 	disconnect(idev, flags);
    787 }
    788 
    789 static int input_device_connected(struct input_device *idev,
    790 						struct input_conn *iconn)
    791 {
    792 	dbus_bool_t connected;
    793 	int err;
    794 
    795 	if (iconn->intr_io == NULL || iconn->ctrl_io == NULL)
    796 		return -ENOTCONN;
    797 
    798 	err = hidp_add_connection(idev, iconn);
    799 	if (err < 0)
    800 		return err;
    801 
    802 	iconn->intr_watch = g_io_add_watch(iconn->intr_io,
    803 					G_IO_HUP | G_IO_ERR | G_IO_NVAL,
    804 					intr_watch_cb, iconn);
    805 	iconn->ctrl_watch = g_io_add_watch(iconn->ctrl_io,
    806 					G_IO_HUP | G_IO_ERR | G_IO_NVAL,
    807 					ctrl_watch_cb, iconn);
    808 
    809 	connected = TRUE;
    810 	emit_property_changed(idev->conn, idev->path, INPUT_DEVICE_INTERFACE,
    811 				"Connected", DBUS_TYPE_BOOLEAN, &connected);
    812 
    813 	idev->dc_id = device_add_disconnect_watch(idev->device, disconnect_cb,
    814 							idev, NULL);
    815 
    816 	return 0;
    817 }
    818 
    819 static void interrupt_connect_cb(GIOChannel *chan, GError *conn_err,
    820 							gpointer user_data)
    821 {
    822 	struct input_conn *iconn = user_data;
    823 	struct input_device *idev = iconn->idev;
    824 	DBusMessage *reply;
    825 	int err;
    826 	const char *err_msg;
    827 
    828 	if (conn_err) {
    829 		err_msg = conn_err->message;
    830 		g_io_channel_unref(iconn->intr_io);
    831 		iconn->intr_io = NULL;
    832 		goto failed;
    833 	}
    834 
    835 	err = input_device_connected(idev, iconn);
    836 	if (err < 0) {
    837 		err_msg = strerror(-err);
    838 		goto failed;
    839 	}
    840 
    841 	/* Replying to the requestor */
    842 	g_dbus_send_reply(idev->conn, iconn->pending_connect, DBUS_TYPE_INVALID);
    843 
    844 	dbus_message_unref(iconn->pending_connect);
    845 	iconn->pending_connect = NULL;
    846 
    847 	return;
    848 
    849 failed:
    850 	error("%s", err_msg);
    851 	reply = connection_attempt_failed(iconn->pending_connect, err_msg);
    852 	g_dbus_send_message(idev->conn, reply);
    853 
    854 	if (iconn->ctrl_io)
    855 		g_io_channel_shutdown(iconn->ctrl_io, FALSE, NULL);
    856 
    857 	if (iconn->intr_io) {
    858 		if (!conn_err)
    859 			g_io_channel_shutdown(iconn->intr_io, FALSE, NULL);
    860 		g_io_channel_unref(iconn->intr_io);
    861 		iconn->intr_io = NULL;
    862 	}
    863 }
    864 
    865 static void control_connect_cb(GIOChannel *chan, GError *conn_err,
    866 							gpointer user_data)
    867 {
    868 	struct input_conn *iconn = user_data;
    869 	struct input_device *idev = iconn->idev;
    870 	DBusMessage *reply;
    871 	GIOChannel *io;
    872 	GError *err = NULL;
    873 
    874 	if (conn_err) {
    875 		error("%s", conn_err->message);
    876 		reply = connection_attempt_failed(iconn->pending_connect,
    877 							conn_err->message);
    878 		goto failed;
    879 	}
    880 
    881 	/* Connect to the HID interrupt channel */
    882 	io = bt_io_connect(BT_IO_L2CAP, interrupt_connect_cb, iconn,
    883 				NULL, &err,
    884 				BT_IO_OPT_SOURCE_BDADDR, &idev->src,
    885 				BT_IO_OPT_DEST_BDADDR, &idev->dst,
    886 				BT_IO_OPT_PSM, L2CAP_PSM_HIDP_INTR,
    887 				BT_IO_OPT_SEC_LEVEL, BT_IO_SEC_LOW,
    888 				BT_IO_OPT_INVALID);
    889 	if (!io) {
    890 		error("%s", err->message);
    891 		reply = connection_attempt_failed(iconn->pending_connect,
    892 							err->message);
    893 		g_error_free(err);
    894 		g_io_channel_shutdown(chan, TRUE, NULL);
    895 		goto failed;
    896 	}
    897 
    898 	iconn->intr_io = io;
    899 
    900 	return;
    901 
    902 failed:
    903 	g_dbus_send_message(idev->conn, reply);
    904 	dbus_message_unref(iconn->pending_connect);
    905 	iconn->pending_connect = NULL;
    906 }
    907 
    908 static int fake_disconnect(struct input_conn *iconn)
    909 {
    910 	struct fake_input *fake = iconn->fake;
    911 
    912 	if (!fake->io)
    913 		return -ENOTCONN;
    914 
    915 	g_io_channel_shutdown(fake->io, TRUE, NULL);
    916 	g_io_channel_unref(fake->io);
    917 	fake->io = NULL;
    918 
    919 	if (fake->uinput >= 0) {
    920 		ioctl(fake->uinput, UI_DEV_DESTROY);
    921 		close(fake->uinput);
    922 		fake->uinput = -1;
    923 	}
    924 
    925 	return 0;
    926 }
    927 
    928 /*
    929  * Input Device methods
    930  */
    931 static DBusMessage *input_device_connect(DBusConnection *conn,
    932 					DBusMessage *msg, void *data)
    933 {
    934 	struct input_device *idev = data;
    935 	struct input_conn *iconn;
    936 	struct fake_input *fake;
    937 	DBusMessage *reply;
    938 	GError *err = NULL;
    939 
    940 	iconn = find_connection(idev->connections, "HID");
    941 	if (!iconn)
    942 		return not_supported(msg);
    943 
    944 	if (iconn->pending_connect)
    945 		return in_progress(msg);
    946 
    947 	if (is_connected(iconn))
    948 		return already_connected(msg);
    949 
    950 	iconn->pending_connect = dbus_message_ref(msg);
    951 	fake = iconn->fake;
    952 
    953 	if (fake) {
    954 		/* Fake input device */
    955 		if (fake->connect(iconn, &err))
    956 			fake->flags |= FI_FLAG_CONNECTED;
    957 	} else {
    958 		/* HID devices */
    959 		GIOChannel *io;
    960 
    961 		io = bt_io_connect(BT_IO_L2CAP, control_connect_cb, iconn,
    962 					NULL, &err,
    963 					BT_IO_OPT_SOURCE_BDADDR, &idev->src,
    964 					BT_IO_OPT_DEST_BDADDR, &idev->dst,
    965 					BT_IO_OPT_PSM, L2CAP_PSM_HIDP_CTRL,
    966 					BT_IO_OPT_SEC_LEVEL, BT_IO_SEC_LOW,
    967 					BT_IO_OPT_INVALID);
    968 		iconn->ctrl_io = io;
    969 	}
    970 
    971 	if (err == NULL)
    972 		return NULL;
    973 
    974 	error("%s", err->message);
    975 	dbus_message_unref(iconn->pending_connect);
    976 	iconn->pending_connect = NULL;
    977 	reply = connection_attempt_failed(msg, err->message);
    978 	g_error_free(err);
    979 	return reply;
    980 }
    981 
    982 static DBusMessage *create_errno_message(DBusMessage *msg, int err)
    983 {
    984 	return g_dbus_create_error(msg, ERROR_INTERFACE ".Failed",
    985 							strerror(err));
    986 }
    987 
    988 static DBusMessage *input_device_disconnect(DBusConnection *conn,
    989 						DBusMessage *msg, void *data)
    990 {
    991 	struct input_device *idev = data;
    992 	int err;
    993 
    994 	err = disconnect(idev, 0);
    995 	if (err < 0)
    996 		return create_errno_message(msg, -err);
    997 
    998 	return g_dbus_create_reply(msg, DBUS_TYPE_INVALID);
    999 }
   1000 
   1001 static void device_unregister(void *data)
   1002 {
   1003 	struct input_device *idev = data;
   1004 
   1005 	DBG("Unregistered interface %s on path %s", INPUT_DEVICE_INTERFACE,
   1006 								idev->path);
   1007 
   1008 	devices = g_slist_remove(devices, idev);
   1009 	input_device_free(idev);
   1010 }
   1011 
   1012 static gint connected_cmp(gpointer a, gpointer b)
   1013 {
   1014 	struct input_conn *iconn = a;
   1015 
   1016 	return !is_connected(iconn);
   1017 }
   1018 
   1019 static DBusMessage *input_device_get_properties(DBusConnection *conn,
   1020 					DBusMessage *msg, void *data)
   1021 {
   1022 	struct input_device *idev = data;
   1023 	DBusMessage *reply;
   1024 	DBusMessageIter iter;
   1025 	DBusMessageIter dict;
   1026 	dbus_bool_t connected;
   1027 
   1028 	reply = dbus_message_new_method_return(msg);
   1029 	if (!reply)
   1030 		return NULL;
   1031 
   1032 	dbus_message_iter_init_append(reply, &iter);
   1033 
   1034 	dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
   1035 			DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
   1036 			DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING
   1037 			DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &dict);
   1038 
   1039 	/* Connected */
   1040 	connected = !!g_slist_find_custom(idev->connections, NULL,
   1041 					(GCompareFunc) connected_cmp);
   1042 	dict_append_entry(&dict, "Connected", DBUS_TYPE_BOOLEAN, &connected);
   1043 
   1044 	dbus_message_iter_close_container(&iter, &dict);
   1045 
   1046 	return reply;
   1047 }
   1048 
   1049 static GDBusMethodTable device_methods[] = {
   1050 	{ "Connect",		"",	"",	input_device_connect,
   1051 						G_DBUS_METHOD_FLAG_ASYNC },
   1052 	{ "Disconnect",		"",	"",	input_device_disconnect	},
   1053 	{ "GetProperties",	"",	"a{sv}",input_device_get_properties },
   1054 	{ }
   1055 };
   1056 
   1057 static GDBusSignalTable device_signals[] = {
   1058 	{ "PropertyChanged",	"sv"	},
   1059 	{ }
   1060 };
   1061 
   1062 static struct input_device *input_device_new(DBusConnection *conn,
   1063 					struct btd_device *device, const char *path,
   1064 					const bdaddr_t *src, const bdaddr_t *dst,
   1065 					const uint32_t handle)
   1066 {
   1067 	struct input_device *idev;
   1068 	char name[249], src_addr[18], dst_addr[18];
   1069 
   1070 	idev = g_new0(struct input_device, 1);
   1071 	bacpy(&idev->src, src);
   1072 	bacpy(&idev->dst, dst);
   1073 	idev->device = btd_device_ref(device);
   1074 	idev->path = g_strdup(path);
   1075 	idev->conn = dbus_connection_ref(conn);
   1076 	idev->handle = handle;
   1077 
   1078 	ba2str(src, src_addr);
   1079 	ba2str(dst, dst_addr);
   1080 	if (read_device_name(src_addr, dst_addr, name) == 0)
   1081 		idev->name = g_strdup(name);
   1082 
   1083 	if (g_dbus_register_interface(conn, idev->path, INPUT_DEVICE_INTERFACE,
   1084 					device_methods, device_signals, NULL,
   1085 					idev, device_unregister) == FALSE) {
   1086 		error("Failed to register interface %s on path %s",
   1087 			INPUT_DEVICE_INTERFACE, path);
   1088 		input_device_free(idev);
   1089 		return NULL;
   1090 	}
   1091 
   1092 	DBG("Registered interface %s on path %s",
   1093 			INPUT_DEVICE_INTERFACE, idev->path);
   1094 
   1095 	return idev;
   1096 }
   1097 
   1098 static struct input_conn *input_conn_new(struct input_device *idev,
   1099 					const char *uuid, const char *alias,
   1100 					int timeout)
   1101 {
   1102 	struct input_conn *iconn;
   1103 
   1104 	iconn = g_new0(struct input_conn, 1);
   1105 	iconn->timeout = timeout;
   1106 	iconn->uuid = g_strdup(uuid);
   1107 	iconn->alias = g_strdup(alias);
   1108 	iconn->idev = idev;
   1109 
   1110 	return iconn;
   1111 }
   1112 
   1113 int input_device_register(DBusConnection *conn, struct btd_device *device,
   1114 			const char *path, const bdaddr_t *src,
   1115 			const bdaddr_t *dst, const char *uuid,
   1116 			uint32_t handle, int timeout)
   1117 {
   1118 	struct input_device *idev;
   1119 	struct input_conn *iconn;
   1120 
   1121 	idev = find_device_by_path(devices, path);
   1122 	if (!idev) {
   1123 		idev = input_device_new(conn, device, path, src, dst, handle);
   1124 		if (!idev)
   1125 			return -EINVAL;
   1126 		devices = g_slist_append(devices, idev);
   1127 	}
   1128 
   1129 	iconn = input_conn_new(idev, uuid, "hid", timeout);
   1130 	if (!iconn)
   1131 		return -EINVAL;
   1132 
   1133 	idev->connections = g_slist_append(idev->connections, iconn);
   1134 
   1135 	return 0;
   1136 }
   1137 
   1138 int fake_input_register(DBusConnection *conn, struct btd_device *device,
   1139 			const char *path, bdaddr_t *src, bdaddr_t *dst,
   1140 			const char *uuid, uint8_t channel)
   1141 {
   1142 	struct input_device *idev;
   1143 	struct input_conn *iconn;
   1144 
   1145 	idev = find_device_by_path(devices, path);
   1146 	if (!idev) {
   1147 		idev = input_device_new(conn, device, path, src, dst, 0);
   1148 		if (!idev)
   1149 			return -EINVAL;
   1150 		devices = g_slist_append(devices, idev);
   1151 	}
   1152 
   1153 	iconn = input_conn_new(idev, uuid, "hsp", 0);
   1154 	if (!iconn)
   1155 		return -EINVAL;
   1156 
   1157 	iconn->fake = g_new0(struct fake_input, 1);
   1158 	iconn->fake->ch = channel;
   1159 	iconn->fake->connect = rfcomm_connect;
   1160 	iconn->fake->disconnect = fake_disconnect;
   1161 
   1162 	idev->connections = g_slist_append(idev->connections, iconn);
   1163 
   1164 	return 0;
   1165 }
   1166 
   1167 static struct input_device *find_device(const bdaddr_t *src,
   1168 					const bdaddr_t *dst)
   1169 {
   1170 	GSList *list;
   1171 
   1172 	for (list = devices; list != NULL; list = list->next) {
   1173 		struct input_device *idev = list->data;
   1174 
   1175 		if (!bacmp(&idev->src, src) && !bacmp(&idev->dst, dst))
   1176 			return idev;
   1177 	}
   1178 
   1179 	return NULL;
   1180 }
   1181 
   1182 int input_device_unregister(const char *path, const char *uuid)
   1183 {
   1184 	struct input_device *idev;
   1185 	struct input_conn *iconn;
   1186 
   1187 	idev = find_device_by_path(devices, path);
   1188 	if (idev == NULL)
   1189 		return -EINVAL;
   1190 
   1191 	iconn = find_connection(idev->connections, uuid);
   1192 	if (iconn == NULL)
   1193 		return -EINVAL;
   1194 
   1195 	if (iconn->pending_connect) {
   1196 		/* Pending connection running */
   1197 		return -EBUSY;
   1198 	}
   1199 
   1200 	idev->connections = g_slist_remove(idev->connections, iconn);
   1201 	input_conn_free(iconn);
   1202 	if (idev->connections)
   1203 		return 0;
   1204 
   1205 	g_dbus_unregister_interface(idev->conn, path, INPUT_DEVICE_INTERFACE);
   1206 
   1207 	return 0;
   1208 }
   1209 
   1210 static int input_device_connadd(struct input_device *idev,
   1211 				struct input_conn *iconn)
   1212 {
   1213 	int err;
   1214 
   1215 	err = input_device_connected(idev, iconn);
   1216 	if (err < 0)
   1217 		goto error;
   1218 
   1219 	return 0;
   1220 
   1221 error:
   1222 	if (iconn->ctrl_io) {
   1223 		g_io_channel_shutdown(iconn->ctrl_io, FALSE, NULL);
   1224 		g_io_channel_unref(iconn->ctrl_io);
   1225 		iconn->ctrl_io = NULL;
   1226 	}
   1227 	if (iconn->intr_io) {
   1228 		g_io_channel_shutdown(iconn->intr_io, FALSE, NULL);
   1229 		g_io_channel_unref(iconn->intr_io);
   1230 		iconn->intr_io = NULL;
   1231 	}
   1232 
   1233 	return err;
   1234 }
   1235 
   1236 int input_device_set_channel(const bdaddr_t *src, const bdaddr_t *dst, int psm,
   1237 								GIOChannel *io)
   1238 {
   1239 	struct input_device *idev = find_device(src, dst);
   1240 	struct input_conn *iconn;
   1241 
   1242 	if (!idev)
   1243 		return -ENOENT;
   1244 
   1245 	iconn = find_connection(idev->connections, "hid");
   1246 	if (!iconn)
   1247 		return -ENOENT;
   1248 
   1249 	switch (psm) {
   1250 	case L2CAP_PSM_HIDP_CTRL:
   1251 		if (iconn->ctrl_io)
   1252 			return -EALREADY;
   1253 		iconn->ctrl_io = g_io_channel_ref(io);
   1254 		break;
   1255 	case L2CAP_PSM_HIDP_INTR:
   1256 		if (iconn->intr_io)
   1257 			return -EALREADY;
   1258 		iconn->intr_io = g_io_channel_ref(io);
   1259 		break;
   1260 	}
   1261 
   1262 	if (iconn->intr_io && iconn->ctrl_io)
   1263 		input_device_connadd(idev, iconn);
   1264 
   1265 	return 0;
   1266 }
   1267 
   1268 int input_device_close_channels(const bdaddr_t *src, const bdaddr_t *dst)
   1269 {
   1270 	struct input_device *idev = find_device(src, dst);
   1271 	struct input_conn *iconn;
   1272 
   1273 	if (!idev)
   1274 		return -ENOENT;
   1275 
   1276 	iconn = find_connection(idev->connections, "hid");
   1277 	if (!iconn)
   1278 		return -ENOENT;
   1279 
   1280 	if (iconn->intr_io)
   1281 		g_io_channel_shutdown(iconn->intr_io, TRUE, NULL);
   1282 
   1283 	if (iconn->ctrl_io)
   1284 		g_io_channel_shutdown(iconn->ctrl_io, TRUE, NULL);
   1285 
   1286 	return 0;
   1287 }
   1288