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