3 * BlueZ - Bluetooth protocol stack for Linux
5 * Copyright (C) 2004-2010 Marcel Holtmann <marcel@holtmann.org>
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.
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.
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
33 #include <sys/ioctl.h>
35 #include <bluetooth/bluetooth.h>
36 #include <bluetooth/hidp.h>
37 #include <bluetooth/sdp.h>
38 #include <bluetooth/sdp_lib.h>
40 #include <gdbus/gdbus.h>
44 #include "btio/btio.h"
46 #include "src/adapter.h"
47 #include "src/device.h"
48 #include "src/profile.h"
49 #include "src/service.h"
50 #include "src/storage.h"
51 #include "src/dbus-common.h"
52 #include "src/error.h"
53 #include "src/sdp-client.h"
57 #define INPUT_INTERFACE "org.bluez.Input1"
59 enum reconnect_mode_t {
67 struct btd_service *service;
68 struct btd_device *device;
78 struct hidp_connadd_req *req;
81 enum reconnect_mode_t reconnect_mode;
82 guint reconnect_timer;
83 uint32_t reconnect_attempt;
86 static int idle_timeout = 0;
88 void input_set_idle_timeout(int timeout)
90 idle_timeout = timeout;
93 static void input_device_enter_reconnect_mode(struct input_device *idev);
95 static void input_device_free(struct input_device *idev)
98 device_remove_disconnect_watch(idev->device, idev->dc_id);
100 btd_service_unref(idev->service);
101 btd_device_unref(idev->device);
104 if (idev->ctrl_watch > 0)
105 g_source_remove(idev->ctrl_watch);
107 if (idev->intr_watch > 0)
108 g_source_remove(idev->intr_watch);
110 if (idev->sec_watch > 0)
111 g_source_remove(idev->sec_watch);
114 g_io_channel_unref(idev->intr_io);
117 g_io_channel_unref(idev->ctrl_io);
120 g_free(idev->req->rd_data);
124 if (idev->reconnect_timer > 0)
125 g_source_remove(idev->reconnect_timer);
130 static gboolean intr_watch_cb(GIOChannel *chan, GIOCondition cond, gpointer data)
132 struct input_device *idev = data;
135 ba2str(&idev->dst, address);
137 DBG("Device %s disconnected", address);
139 /* Checking for ctrl_watch avoids a double g_io_channel_shutdown since
140 * it's likely that ctrl_watch_cb has been queued for dispatching in
141 * this mainloop iteration */
142 if ((cond & (G_IO_HUP | G_IO_ERR)) && idev->ctrl_watch)
143 g_io_channel_shutdown(chan, TRUE, NULL);
145 device_remove_disconnect_watch(idev->device, idev->dc_id);
148 idev->intr_watch = 0;
151 g_io_channel_unref(idev->intr_io);
152 idev->intr_io = NULL;
155 /* Close control channel */
156 if (idev->ctrl_io && !(cond & G_IO_NVAL))
157 g_io_channel_shutdown(idev->ctrl_io, TRUE, NULL);
159 btd_service_disconnecting_complete(idev->service, 0);
161 /* Enter the auto-reconnect mode if needed */
162 input_device_enter_reconnect_mode(idev);
167 static gboolean ctrl_watch_cb(GIOChannel *chan, GIOCondition cond, gpointer data)
169 struct input_device *idev = data;
172 ba2str(&idev->dst, address);
174 DBG("Device %s disconnected", address);
176 /* Checking for intr_watch avoids a double g_io_channel_shutdown since
177 * it's likely that intr_watch_cb has been queued for dispatching in
178 * this mainloop iteration */
179 if ((cond & (G_IO_HUP | G_IO_ERR)) && idev->intr_watch)
180 g_io_channel_shutdown(chan, TRUE, NULL);
182 idev->ctrl_watch = 0;
185 g_io_channel_unref(idev->ctrl_io);
186 idev->ctrl_io = NULL;
189 /* Close interrupt channel */
190 if (idev->intr_io && !(cond & G_IO_NVAL))
191 g_io_channel_shutdown(idev->intr_io, TRUE, NULL);
196 static void epox_endian_quirk(unsigned char *data, int size)
198 /* USAGE_PAGE (Keyboard) 05 07
199 * USAGE_MINIMUM (0) 19 00
200 * USAGE_MAXIMUM (65280) 2A 00 FF <= must be FF 00
201 * LOGICAL_MINIMUM (0) 15 00
202 * LOGICAL_MAXIMUM (65280) 26 00 FF <= must be FF 00
204 unsigned char pattern[] = { 0x05, 0x07, 0x19, 0x00, 0x2a, 0x00, 0xff,
205 0x15, 0x00, 0x26, 0x00, 0xff };
211 for (i = 0; i < size - sizeof(pattern); i++) {
212 if (!memcmp(data + i, pattern, sizeof(pattern))) {
221 static int create_hid_dev_name(sdp_record_t *rec, struct hidp_connadd_req *req)
223 char sdesc[sizeof(req->name)];
225 if (sdp_get_service_desc(rec, sdesc, sizeof(sdesc)) == 0) {
226 char pname[sizeof(req->name)];
228 if (sdp_get_provider_name(rec, pname, sizeof(pname)) == 0 &&
229 strncmp(sdesc, pname, 5) != 0)
230 snprintf(req->name, sizeof(req->name), "%s %s", pname,
233 snprintf(req->name, sizeof(req->name), "%s", sdesc);
235 return sdp_get_service_name(rec, req->name, sizeof(req->name));
241 /* See HID profile specification v1.0, "7.11.6 HIDDescriptorList" for details
242 * on the attribute format. */
243 static int extract_hid_desc_data(sdp_record_t *rec,
244 struct hidp_connadd_req *req)
248 d = sdp_data_get(rec, SDP_ATTR_HID_DESCRIPTOR_LIST);
252 if (!SDP_IS_SEQ(d->dtd))
255 /* First HIDDescriptor */
257 if (!SDP_IS_SEQ(d->dtd))
260 /* ClassDescriptorType */
262 if (d->dtd != SDP_UINT8)
265 /* ClassDescriptorData */
267 if (!d || !SDP_IS_TEXT_STR(d->dtd))
270 req->rd_data = g_try_malloc0(d->unitSize);
272 memcpy(req->rd_data, d->val.str, d->unitSize);
273 req->rd_size = d->unitSize;
274 epox_endian_quirk(req->rd_data, req->rd_size);
280 error("Missing or invalid HIDDescriptorList SDP attribute");
284 static int extract_hid_record(sdp_record_t *rec, struct hidp_connadd_req *req)
290 err = create_hid_dev_name(rec, req);
292 DBG("No valid Service Name or Service Description found");
294 pdlist = sdp_data_get(rec, SDP_ATTR_HID_PARSER_VERSION);
295 req->parser = pdlist ? pdlist->val.uint16 : 0x0100;
297 pdlist = sdp_data_get(rec, SDP_ATTR_HID_DEVICE_SUBCLASS);
298 req->subclass = pdlist ? pdlist->val.uint8 : 0;
300 pdlist = sdp_data_get(rec, SDP_ATTR_HID_COUNTRY_CODE);
301 req->country = pdlist ? pdlist->val.uint8 : 0;
303 pdlist = sdp_data_get(rec, SDP_ATTR_HID_VIRTUAL_CABLE);
304 attr_val = pdlist ? pdlist->val.uint8 : 0;
306 req->flags |= (1 << HIDP_VIRTUAL_CABLE_UNPLUG);
308 pdlist = sdp_data_get(rec, SDP_ATTR_HID_BOOT_DEVICE);
309 attr_val = pdlist ? pdlist->val.uint8 : 0;
311 req->flags |= (1 << HIDP_BOOT_PROTOCOL_MODE);
313 err = extract_hid_desc_data(rec, req);
320 static int ioctl_connadd(struct hidp_connadd_req *req)
324 ctl = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HIDP);
328 if (ioctl(ctl, HIDPCONNADD, req) < 0)
336 static gboolean encrypt_notify(GIOChannel *io, GIOCondition condition,
339 struct input_device *idev = data;
344 err = ioctl_connadd(idev->req);
346 error("ioctl_connadd(): %s (%d)", strerror(-err), -err);
349 g_io_channel_shutdown(idev->ctrl_io, FALSE, NULL);
350 g_io_channel_unref(idev->ctrl_io);
351 idev->ctrl_io = NULL;
355 g_io_channel_shutdown(idev->intr_io, FALSE, NULL);
356 g_io_channel_unref(idev->intr_io);
357 idev->intr_io = NULL;
363 g_free(idev->req->rd_data);
370 static int hidp_add_connection(struct input_device *idev)
372 struct hidp_connadd_req *req;
374 char src_addr[18], dst_addr[18];
375 char filename[PATH_MAX + 1];
377 char handle[11], *str;
381 req = g_new0(struct hidp_connadd_req, 1);
382 req->ctrl_sock = g_io_channel_unix_get_fd(idev->ctrl_io);
383 req->intr_sock = g_io_channel_unix_get_fd(idev->intr_io);
385 req->idle_to = idle_timeout;
387 ba2str(&idev->src, src_addr);
388 ba2str(&idev->dst, dst_addr);
390 snprintf(filename, PATH_MAX, STORAGEDIR "/%s/cache/%s", src_addr,
392 filename[PATH_MAX] = '\0';
393 sprintf(handle, "0x%8.8X", idev->handle);
395 key_file = g_key_file_new();
396 g_key_file_load_from_file(key_file, filename, 0, NULL);
397 str = g_key_file_get_string(key_file, "ServiceRecords", handle, NULL);
398 g_key_file_free(key_file);
401 error("Rejected connection from unknown device %s", dst_addr);
406 rec = record_from_string(str);
409 err = extract_hid_record(rec, req);
410 sdp_record_free(rec);
412 error("Could not parse HID SDP record: %s (%d)", strerror(-err),
417 req->vendor = btd_device_get_vendor(idev->device);
418 req->product = btd_device_get_product(idev->device);
419 req->version = btd_device_get_version(idev->device);
421 if (device_name_known(idev->device))
422 device_get_name(idev->device, req->name, sizeof(req->name));
424 /* Encryption is mandatory for keyboards */
425 if (req->subclass & 0x40) {
426 if (!bt_io_set(idev->intr_io, &gerr,
427 BT_IO_OPT_SEC_LEVEL, BT_IO_SEC_MEDIUM,
428 BT_IO_OPT_INVALID)) {
429 error("btio: %s", gerr->message);
436 idev->sec_watch = g_io_add_watch(idev->intr_io, G_IO_OUT,
437 encrypt_notify, idev);
442 err = ioctl_connadd(req);
445 g_free(req->rd_data);
451 static int is_connected(struct input_device *idev)
453 struct hidp_conninfo ci;
457 ctl = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HIDP);
461 memset(&ci, 0, sizeof(ci));
462 bacpy(&ci.bdaddr, &idev->dst);
463 if (ioctl(ctl, HIDPGETCONNINFO, &ci) < 0) {
470 if (ci.state != BT_CONNECTED)
476 static int connection_disconnect(struct input_device *idev, uint32_t flags)
478 struct hidp_conndel_req req;
479 struct hidp_conninfo ci;
482 if (!is_connected(idev))
485 /* Standard HID disconnect */
487 g_io_channel_shutdown(idev->intr_io, TRUE, NULL);
489 g_io_channel_shutdown(idev->ctrl_io, TRUE, NULL);
491 ctl = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HIDP);
493 error("Can't open HIDP control socket");
497 memset(&ci, 0, sizeof(ci));
498 bacpy(&ci.bdaddr, &idev->dst);
499 if ((ioctl(ctl, HIDPGETCONNINFO, &ci) < 0) ||
500 (ci.state != BT_CONNECTED)) {
505 memset(&req, 0, sizeof(req));
506 bacpy(&req.bdaddr, &idev->dst);
508 if (ioctl(ctl, HIDPCONNDEL, &req) < 0) {
510 error("Can't delete the HID device: %s(%d)",
511 strerror(-err), -err);
521 static void disconnect_cb(struct btd_device *device, gboolean removal,
524 struct input_device *idev = user_data;
527 info("Input: disconnect %s", idev->path);
529 flags = removal ? (1 << HIDP_VIRTUAL_CABLE_UNPLUG) : 0;
531 connection_disconnect(idev, flags);
534 static int input_device_connected(struct input_device *idev)
538 if (idev->intr_io == NULL || idev->ctrl_io == NULL)
541 err = hidp_add_connection(idev);
545 idev->dc_id = device_add_disconnect_watch(idev->device, disconnect_cb,
548 btd_service_connecting_complete(idev->service, 0);
553 static void interrupt_connect_cb(GIOChannel *chan, GError *conn_err,
556 struct input_device *idev = user_data;
564 err = input_device_connected(idev);
568 idev->intr_watch = g_io_add_watch(idev->intr_io,
569 G_IO_HUP | G_IO_ERR | G_IO_NVAL,
570 intr_watch_cb, idev);
575 btd_service_connecting_complete(idev->service, err);
577 /* So we guarantee the interrupt channel is closed before the
578 * control channel (if we only do unref GLib will close it only
579 * after returning control to the mainloop */
581 g_io_channel_shutdown(idev->intr_io, FALSE, NULL);
583 g_io_channel_unref(idev->intr_io);
584 idev->intr_io = NULL;
587 g_io_channel_unref(idev->ctrl_io);
588 idev->ctrl_io = NULL;
592 static void control_connect_cb(GIOChannel *chan, GError *conn_err,
595 struct input_device *idev = user_data;
600 error("%s", conn_err->message);
604 /* Connect to the HID interrupt channel */
605 io = bt_io_connect(interrupt_connect_cb, idev,
607 BT_IO_OPT_SOURCE_BDADDR, &idev->src,
608 BT_IO_OPT_DEST_BDADDR, &idev->dst,
609 BT_IO_OPT_PSM, L2CAP_PSM_HIDP_INTR,
610 BT_IO_OPT_SEC_LEVEL, BT_IO_SEC_LOW,
613 error("%s", err->message);
620 idev->ctrl_watch = g_io_add_watch(idev->ctrl_io,
621 G_IO_HUP | G_IO_ERR | G_IO_NVAL,
622 ctrl_watch_cb, idev);
627 btd_service_connecting_complete(idev->service, -EIO);
628 g_io_channel_unref(idev->ctrl_io);
629 idev->ctrl_io = NULL;
632 static int dev_connect(struct input_device *idev)
637 if (idev->disable_sdp)
638 bt_clear_cached_session(&idev->src, &idev->dst);
640 io = bt_io_connect(control_connect_cb, idev,
642 BT_IO_OPT_SOURCE_BDADDR, &idev->src,
643 BT_IO_OPT_DEST_BDADDR, &idev->dst,
644 BT_IO_OPT_PSM, L2CAP_PSM_HIDP_CTRL,
645 BT_IO_OPT_SEC_LEVEL, BT_IO_SEC_LOW,
652 error("%s", err->message);
658 static gboolean input_device_auto_reconnect(gpointer user_data)
660 struct input_device *idev = user_data;
662 DBG("path=%s, attempt=%d", idev->path, idev->reconnect_attempt);
664 /* Stop the recurrent reconnection attempts if the device is reconnected
665 * or is marked for removal. */
666 if (device_is_temporary(idev->device) ||
667 btd_device_is_connected(idev->device))
670 /* Only attempt an auto-reconnect for at most 3 minutes (6 * 30s). */
671 if (idev->reconnect_attempt >= 6)
674 /* Check if the profile is already connected. */
678 if (is_connected(idev))
681 idev->reconnect_attempt++;
687 static const char * const _reconnect_mode_str[] = {
694 static const char *reconnect_mode_to_string(const enum reconnect_mode_t mode)
696 return _reconnect_mode_str[mode];
699 static void input_device_enter_reconnect_mode(struct input_device *idev)
701 DBG("path=%s reconnect_mode=%s", idev->path,
702 reconnect_mode_to_string(idev->reconnect_mode));
704 /* Only attempt an auto-reconnect when the device is required to accept
705 * reconnections from the host. */
706 if (idev->reconnect_mode != RECONNECT_ANY &&
707 idev->reconnect_mode != RECONNECT_HOST)
710 /* If the device is temporary we are not required to reconnect with the
711 * device. This is likely the case of a removing device. */
712 if (device_is_temporary(idev->device) ||
713 btd_device_is_connected(idev->device))
716 if (idev->reconnect_timer > 0)
717 g_source_remove(idev->reconnect_timer);
719 DBG("registering auto-reconnect");
720 idev->reconnect_attempt = 0;
721 idev->reconnect_timer = g_timeout_add_seconds(30,
722 input_device_auto_reconnect, idev);
726 int input_device_connect(struct btd_service *service)
728 struct input_device *idev;
732 idev = btd_service_get_user_data(service);
737 if (is_connected(idev))
740 return dev_connect(idev);
743 int input_device_disconnect(struct btd_service *service)
745 struct input_device *idev;
750 idev = btd_service_get_user_data(service);
752 err = connection_disconnect(idev, 0);
759 static bool is_device_sdp_disable(const sdp_record_t *rec)
763 data = sdp_data_get(rec, SDP_ATTR_HID_SDP_DISABLE);
765 return data && data->val.uint8;
768 static enum reconnect_mode_t hid_reconnection_mode(bool reconnect_initiate,
769 bool normally_connectable)
771 if (!reconnect_initiate && !normally_connectable)
772 return RECONNECT_NONE;
773 else if (!reconnect_initiate && normally_connectable)
774 return RECONNECT_HOST;
775 else if (reconnect_initiate && !normally_connectable)
776 return RECONNECT_DEVICE;
777 else /* (reconnect_initiate && normally_connectable) */
778 return RECONNECT_ANY;
781 static void extract_hid_props(struct input_device *idev,
782 const sdp_record_t *rec)
784 /* Extract HID connectability */
785 bool reconnect_initiate, normally_connectable;
788 /* HIDNormallyConnectable is optional and assumed FALSE
790 pdlist = sdp_data_get(rec, SDP_ATTR_HID_RECONNECT_INITIATE);
791 reconnect_initiate = pdlist ? pdlist->val.uint8 : TRUE;
793 pdlist = sdp_data_get(rec, SDP_ATTR_HID_NORMALLY_CONNECTABLE);
794 normally_connectable = pdlist ? pdlist->val.uint8 : FALSE;
796 /* Update local values */
797 idev->reconnect_mode =
798 hid_reconnection_mode(reconnect_initiate, normally_connectable);
801 static struct input_device *input_device_new(struct btd_service *service)
803 struct btd_device *device = btd_service_get_device(service);
804 struct btd_profile *p = btd_service_get_profile(service);
805 const char *path = device_get_path(device);
806 const sdp_record_t *rec = btd_device_get_record(device, p->remote_uuid);
807 struct btd_adapter *adapter = device_get_adapter(device);
808 struct input_device *idev;
813 idev = g_new0(struct input_device, 1);
814 bacpy(&idev->src, btd_adapter_get_address(adapter));
815 bacpy(&idev->dst, device_get_address(device));
816 idev->service = btd_service_ref(service);
817 idev->device = btd_device_ref(device);
818 idev->path = g_strdup(path);
819 idev->handle = rec->handle;
820 idev->disable_sdp = is_device_sdp_disable(rec);
822 /* Initialize device properties */
823 extract_hid_props(idev, rec);
828 static gboolean property_get_reconnect_mode(
829 const GDBusPropertyTable *property,
830 DBusMessageIter *iter, void *data)
832 struct input_device *idev = data;
833 const char *str_mode = reconnect_mode_to_string(idev->reconnect_mode);
835 dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &str_mode);
840 static const GDBusPropertyTable input_properties[] = {
841 { "ReconnectMode", "s", property_get_reconnect_mode },
845 int input_device_register(struct btd_service *service)
847 struct btd_device *device = btd_service_get_device(service);
848 const char *path = device_get_path(device);
849 struct input_device *idev;
853 idev = input_device_new(service);
857 if (g_dbus_register_interface(btd_get_dbus_connection(),
858 idev->path, INPUT_INTERFACE,
860 input_properties, idev,
862 error("Unable to register %s interface", INPUT_INTERFACE);
863 input_device_free(idev);
867 btd_service_set_user_data(service, idev);
872 static struct input_device *find_device(const bdaddr_t *src,
875 struct btd_device *device;
876 struct btd_service *service;
878 device = btd_adapter_find_device(adapter_find(src), dst);
882 service = btd_device_get_service(device, HID_UUID);
886 return btd_service_get_user_data(service);
889 void input_device_unregister(struct btd_service *service)
891 struct btd_device *device = btd_service_get_device(service);
892 const char *path = device_get_path(device);
893 struct input_device *idev = btd_service_get_user_data(service);
897 g_dbus_unregister_interface(btd_get_dbus_connection(),
898 idev->path, INPUT_INTERFACE);
900 input_device_free(idev);
903 static int input_device_connadd(struct input_device *idev)
907 err = input_device_connected(idev);
915 g_io_channel_shutdown(idev->ctrl_io, FALSE, NULL);
916 g_io_channel_unref(idev->ctrl_io);
917 idev->ctrl_io = NULL;
920 g_io_channel_shutdown(idev->intr_io, FALSE, NULL);
921 g_io_channel_unref(idev->intr_io);
922 idev->intr_io = NULL;
928 bool input_device_exists(const bdaddr_t *src, const bdaddr_t *dst)
930 if (find_device(src, dst))
936 int input_device_set_channel(const bdaddr_t *src, const bdaddr_t *dst, int psm,
939 struct input_device *idev = find_device(src, dst);
941 DBG("idev %p psm %d", idev, psm);
947 case L2CAP_PSM_HIDP_CTRL:
950 idev->ctrl_io = g_io_channel_ref(io);
951 idev->ctrl_watch = g_io_add_watch(idev->ctrl_io,
952 G_IO_HUP | G_IO_ERR | G_IO_NVAL,
953 ctrl_watch_cb, idev);
955 case L2CAP_PSM_HIDP_INTR:
958 idev->intr_io = g_io_channel_ref(io);
959 idev->intr_watch = g_io_add_watch(idev->intr_io,
960 G_IO_HUP | G_IO_ERR | G_IO_NVAL,
961 intr_watch_cb, idev);
965 if (idev->intr_io && idev->ctrl_io)
966 input_device_connadd(idev);
971 int input_device_close_channels(const bdaddr_t *src, const bdaddr_t *dst)
973 struct input_device *idev = find_device(src, dst);
979 g_io_channel_shutdown(idev->intr_io, TRUE, NULL);
982 g_io_channel_shutdown(idev->ctrl_io, TRUE, NULL);