tizen 2.3 release
[framework/connectivity/bluez.git] / profiles / input / device.c
1 /*
2  *
3  *  BlueZ - Bluetooth protocol stack for Linux
4  *
5  *  Copyright (C) 2004-2010  Marcel Holtmann <marcel@holtmann.org>
6  *
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21  *
22  */
23
24 #ifdef HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27
28 #include <stdlib.h>
29 #include <stdbool.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <unistd.h>
33 #include <sys/ioctl.h>
34
35 #include <bluetooth/bluetooth.h>
36 #include <bluetooth/hidp.h>
37 #include <bluetooth/sdp.h>
38 #include <bluetooth/sdp_lib.h>
39
40 #include <gdbus/gdbus.h>
41
42 #include "src/log.h"
43
44 #include "btio/btio.h"
45 #include "lib/uuid.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"
54
55 #include "device.h"
56
57 #define INPUT_INTERFACE "org.bluez.Input1"
58
59 enum reconnect_mode_t {
60         RECONNECT_NONE = 0,
61         RECONNECT_DEVICE,
62         RECONNECT_HOST,
63         RECONNECT_ANY
64 };
65
66 struct input_device {
67         struct btd_service      *service;
68         struct btd_device       *device;
69         char                    *path;
70         bdaddr_t                src;
71         bdaddr_t                dst;
72         uint32_t                handle;
73         GIOChannel              *ctrl_io;
74         GIOChannel              *intr_io;
75         guint                   ctrl_watch;
76         guint                   intr_watch;
77         guint                   sec_watch;
78         struct hidp_connadd_req *req;
79         guint                   dc_id;
80         bool                    disable_sdp;
81         enum reconnect_mode_t   reconnect_mode;
82         guint                   reconnect_timer;
83         uint32_t                reconnect_attempt;
84 };
85
86 static int idle_timeout = 0;
87
88 void input_set_idle_timeout(int timeout)
89 {
90         idle_timeout = timeout;
91 }
92
93 static void input_device_enter_reconnect_mode(struct input_device *idev);
94
95 static void input_device_free(struct input_device *idev)
96 {
97         if (idev->dc_id)
98                 device_remove_disconnect_watch(idev->device, idev->dc_id);
99
100         btd_service_unref(idev->service);
101         btd_device_unref(idev->device);
102         g_free(idev->path);
103
104         if (idev->ctrl_watch > 0)
105                 g_source_remove(idev->ctrl_watch);
106
107         if (idev->intr_watch > 0)
108                 g_source_remove(idev->intr_watch);
109
110         if (idev->sec_watch > 0)
111                 g_source_remove(idev->sec_watch);
112
113         if (idev->intr_io)
114                 g_io_channel_unref(idev->intr_io);
115
116         if (idev->ctrl_io)
117                 g_io_channel_unref(idev->ctrl_io);
118
119         if (idev->req) {
120                 g_free(idev->req->rd_data);
121                 g_free(idev->req);
122         }
123
124         if (idev->reconnect_timer > 0)
125                 g_source_remove(idev->reconnect_timer);
126
127         g_free(idev);
128 }
129
130 static gboolean intr_watch_cb(GIOChannel *chan, GIOCondition cond, gpointer data)
131 {
132         struct input_device *idev = data;
133         char address[18];
134
135         ba2str(&idev->dst, address);
136
137         DBG("Device %s disconnected", address);
138
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);
144
145         device_remove_disconnect_watch(idev->device, idev->dc_id);
146         idev->dc_id = 0;
147
148         idev->intr_watch = 0;
149
150         if (idev->intr_io) {
151                 g_io_channel_unref(idev->intr_io);
152                 idev->intr_io = NULL;
153         }
154
155         /* Close control channel */
156         if (idev->ctrl_io && !(cond & G_IO_NVAL))
157                 g_io_channel_shutdown(idev->ctrl_io, TRUE, NULL);
158
159         btd_service_disconnecting_complete(idev->service, 0);
160
161         /* Enter the auto-reconnect mode if needed */
162         input_device_enter_reconnect_mode(idev);
163
164         return FALSE;
165 }
166
167 static gboolean ctrl_watch_cb(GIOChannel *chan, GIOCondition cond, gpointer data)
168 {
169         struct input_device *idev = data;
170         char address[18];
171
172         ba2str(&idev->dst, address);
173
174         DBG("Device %s disconnected", address);
175
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);
181
182         idev->ctrl_watch = 0;
183
184         if (idev->ctrl_io) {
185                 g_io_channel_unref(idev->ctrl_io);
186                 idev->ctrl_io = NULL;
187         }
188
189         /* Close interrupt channel */
190         if (idev->intr_io && !(cond & G_IO_NVAL))
191                 g_io_channel_shutdown(idev->intr_io, TRUE, NULL);
192
193         return FALSE;
194 }
195
196 static void epox_endian_quirk(unsigned char *data, int size)
197 {
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
203          */
204         unsigned char pattern[] = { 0x05, 0x07, 0x19, 0x00, 0x2a, 0x00, 0xff,
205                                                 0x15, 0x00, 0x26, 0x00, 0xff };
206         unsigned int i;
207
208         if (!data)
209                 return;
210
211         for (i = 0; i < size - sizeof(pattern); i++) {
212                 if (!memcmp(data + i, pattern, sizeof(pattern))) {
213                         data[i + 5] = 0xff;
214                         data[i + 6] = 0x00;
215                         data[i + 10] = 0xff;
216                         data[i + 11] = 0x00;
217                 }
218         }
219 }
220
221 static int create_hid_dev_name(sdp_record_t *rec, struct hidp_connadd_req *req)
222 {
223         char sdesc[sizeof(req->name)];
224
225         if (sdp_get_service_desc(rec, sdesc, sizeof(sdesc)) == 0) {
226                 char pname[sizeof(req->name)];
227
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,
231                                                                         sdesc);
232                 else
233                         snprintf(req->name, sizeof(req->name), "%s", sdesc);
234         } else {
235                 return sdp_get_service_name(rec, req->name, sizeof(req->name));
236         }
237
238         return 0;
239 }
240
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)
245 {
246         sdp_data_t *d;
247
248         d = sdp_data_get(rec, SDP_ATTR_HID_DESCRIPTOR_LIST);
249         if (!d)
250                 goto invalid_desc;
251
252         if (!SDP_IS_SEQ(d->dtd))
253                 goto invalid_desc;
254
255         /* First HIDDescriptor */
256         d = d->val.dataseq;
257         if (!SDP_IS_SEQ(d->dtd))
258                 goto invalid_desc;
259
260         /* ClassDescriptorType */
261         d = d->val.dataseq;
262         if (d->dtd != SDP_UINT8)
263                 goto invalid_desc;
264
265         /* ClassDescriptorData */
266         d = d->next;
267         if (!d || !SDP_IS_TEXT_STR(d->dtd))
268                 goto invalid_desc;
269
270         req->rd_data = g_try_malloc0(d->unitSize);
271         if (req->rd_data) {
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);
275         }
276
277         return 0;
278
279 invalid_desc:
280         error("Missing or invalid HIDDescriptorList SDP attribute");
281         return -EINVAL;
282 }
283
284 static int extract_hid_record(sdp_record_t *rec, struct hidp_connadd_req *req)
285 {
286         sdp_data_t *pdlist;
287         uint8_t attr_val;
288         int err;
289
290         err = create_hid_dev_name(rec, req);
291         if (err < 0)
292                 DBG("No valid Service Name or Service Description found");
293
294         pdlist = sdp_data_get(rec, SDP_ATTR_HID_PARSER_VERSION);
295         req->parser = pdlist ? pdlist->val.uint16 : 0x0100;
296
297         pdlist = sdp_data_get(rec, SDP_ATTR_HID_DEVICE_SUBCLASS);
298         req->subclass = pdlist ? pdlist->val.uint8 : 0;
299
300         pdlist = sdp_data_get(rec, SDP_ATTR_HID_COUNTRY_CODE);
301         req->country = pdlist ? pdlist->val.uint8 : 0;
302
303         pdlist = sdp_data_get(rec, SDP_ATTR_HID_VIRTUAL_CABLE);
304         attr_val = pdlist ? pdlist->val.uint8 : 0;
305         if (attr_val)
306                 req->flags |= (1 << HIDP_VIRTUAL_CABLE_UNPLUG);
307
308         pdlist = sdp_data_get(rec, SDP_ATTR_HID_BOOT_DEVICE);
309         attr_val = pdlist ? pdlist->val.uint8 : 0;
310         if (attr_val)
311                 req->flags |= (1 << HIDP_BOOT_PROTOCOL_MODE);
312
313         err = extract_hid_desc_data(rec, req);
314         if (err < 0)
315                 return err;
316
317         return 0;
318 }
319
320 static int ioctl_connadd(struct hidp_connadd_req *req)
321 {
322         int ctl, err = 0;
323
324         ctl = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HIDP);
325         if (ctl < 0)
326                 return -errno;
327
328         if (ioctl(ctl, HIDPCONNADD, req) < 0)
329                 err = -errno;
330
331         close(ctl);
332
333         return err;
334 }
335
336 static gboolean encrypt_notify(GIOChannel *io, GIOCondition condition,
337                                                                 gpointer data)
338 {
339         struct input_device *idev = data;
340         int err;
341
342         DBG("");
343
344         err = ioctl_connadd(idev->req);
345         if (err < 0) {
346                 error("ioctl_connadd(): %s (%d)", strerror(-err), -err);
347
348                 if (idev->ctrl_io) {
349                         g_io_channel_shutdown(idev->ctrl_io, FALSE, NULL);
350                         g_io_channel_unref(idev->ctrl_io);
351                         idev->ctrl_io = NULL;
352                 }
353
354                 if (idev->intr_io) {
355                         g_io_channel_shutdown(idev->intr_io, FALSE, NULL);
356                         g_io_channel_unref(idev->intr_io);
357                         idev->intr_io = NULL;
358                 }
359         }
360
361         idev->sec_watch = 0;
362
363         g_free(idev->req->rd_data);
364         g_free(idev->req);
365         idev->req = NULL;
366
367         return FALSE;
368 }
369
370 static int hidp_add_connection(struct input_device *idev)
371 {
372         struct hidp_connadd_req *req;
373         sdp_record_t *rec;
374         char src_addr[18], dst_addr[18];
375         char filename[PATH_MAX + 1];
376         GKeyFile *key_file;
377         char handle[11], *str;
378         GError *gerr = NULL;
379         int err;
380
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);
384         req->flags     = 0;
385         req->idle_to   = idle_timeout;
386
387         ba2str(&idev->src, src_addr);
388         ba2str(&idev->dst, dst_addr);
389
390         snprintf(filename, PATH_MAX, STORAGEDIR "/%s/cache/%s", src_addr,
391                                                                 dst_addr);
392         filename[PATH_MAX] = '\0';
393         sprintf(handle, "0x%8.8X", idev->handle);
394
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);
399
400         if (!str) {
401                 error("Rejected connection from unknown device %s", dst_addr);
402                 err = -EPERM;
403                 goto cleanup;
404         }
405
406         rec = record_from_string(str);
407         g_free(str);
408
409         err = extract_hid_record(rec, req);
410         sdp_record_free(rec);
411         if (err < 0) {
412                 error("Could not parse HID SDP record: %s (%d)", strerror(-err),
413                                                                         -err);
414                 goto cleanup;
415         }
416
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);
420
421         if (device_name_known(idev->device))
422                 device_get_name(idev->device, req->name, sizeof(req->name));
423
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);
430                         g_error_free(gerr);
431                         err = -EFAULT;
432                         goto cleanup;
433                 }
434
435                 idev->req = req;
436                 idev->sec_watch = g_io_add_watch(idev->intr_io, G_IO_OUT,
437                                                         encrypt_notify, idev);
438
439                 return 0;
440         }
441
442         err = ioctl_connadd(req);
443
444 cleanup:
445         g_free(req->rd_data);
446         g_free(req);
447
448         return err;
449 }
450
451 static int is_connected(struct input_device *idev)
452 {
453         struct hidp_conninfo ci;
454         int ctl;
455
456         /* Standard HID */
457         ctl = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HIDP);
458         if (ctl < 0)
459                 return 0;
460
461         memset(&ci, 0, sizeof(ci));
462         bacpy(&ci.bdaddr, &idev->dst);
463         if (ioctl(ctl, HIDPGETCONNINFO, &ci) < 0) {
464                 close(ctl);
465                 return 0;
466         }
467
468         close(ctl);
469
470         if (ci.state != BT_CONNECTED)
471                 return 0;
472         else
473                 return 1;
474 }
475
476 static int connection_disconnect(struct input_device *idev, uint32_t flags)
477 {
478         struct hidp_conndel_req req;
479         struct hidp_conninfo ci;
480         int ctl, err = 0;
481
482         if (!is_connected(idev))
483                 return -ENOTCONN;
484
485         /* Standard HID disconnect */
486         if (idev->intr_io)
487                 g_io_channel_shutdown(idev->intr_io, TRUE, NULL);
488         if (idev->ctrl_io)
489                 g_io_channel_shutdown(idev->ctrl_io, TRUE, NULL);
490
491         ctl = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HIDP);
492         if (ctl < 0) {
493                 error("Can't open HIDP control socket");
494                 return -errno;
495         }
496
497         memset(&ci, 0, sizeof(ci));
498         bacpy(&ci.bdaddr, &idev->dst);
499         if ((ioctl(ctl, HIDPGETCONNINFO, &ci) < 0) ||
500                                 (ci.state != BT_CONNECTED)) {
501                 err = -ENOTCONN;
502                 goto fail;
503         }
504
505         memset(&req, 0, sizeof(req));
506         bacpy(&req.bdaddr, &idev->dst);
507         req.flags = flags;
508         if (ioctl(ctl, HIDPCONNDEL, &req) < 0) {
509                 err = -errno;
510                 error("Can't delete the HID device: %s(%d)",
511                                 strerror(-err), -err);
512                 goto fail;
513         }
514
515 fail:
516         close(ctl);
517
518         return err;
519 }
520
521 static void disconnect_cb(struct btd_device *device, gboolean removal,
522                                 void *user_data)
523 {
524         struct input_device *idev = user_data;
525         int flags;
526
527         info("Input: disconnect %s", idev->path);
528
529         flags = removal ? (1 << HIDP_VIRTUAL_CABLE_UNPLUG) : 0;
530
531         connection_disconnect(idev, flags);
532 }
533
534 static int input_device_connected(struct input_device *idev)
535 {
536         int err;
537
538         if (idev->intr_io == NULL || idev->ctrl_io == NULL)
539                 return -ENOTCONN;
540
541         err = hidp_add_connection(idev);
542         if (err < 0)
543                 return err;
544
545         idev->dc_id = device_add_disconnect_watch(idev->device, disconnect_cb,
546                                                         idev, NULL);
547
548         btd_service_connecting_complete(idev->service, 0);
549
550         return 0;
551 }
552
553 static void interrupt_connect_cb(GIOChannel *chan, GError *conn_err,
554                                                         gpointer user_data)
555 {
556         struct input_device *idev = user_data;
557         int err;
558
559         if (conn_err) {
560                 err = -EIO;
561                 goto failed;
562         }
563
564         err = input_device_connected(idev);
565         if (err < 0)
566                 goto failed;
567
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);
571
572         return;
573
574 failed:
575         btd_service_connecting_complete(idev->service, err);
576
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 */
580         if (!conn_err)
581                 g_io_channel_shutdown(idev->intr_io, FALSE, NULL);
582
583         g_io_channel_unref(idev->intr_io);
584         idev->intr_io = NULL;
585
586         if (idev->ctrl_io) {
587                 g_io_channel_unref(idev->ctrl_io);
588                 idev->ctrl_io = NULL;
589         }
590 }
591
592 static void control_connect_cb(GIOChannel *chan, GError *conn_err,
593                                                         gpointer user_data)
594 {
595         struct input_device *idev = user_data;
596         GIOChannel *io;
597         GError *err = NULL;
598
599         if (conn_err) {
600                 error("%s", conn_err->message);
601                 goto failed;
602         }
603
604         /* Connect to the HID interrupt channel */
605         io = bt_io_connect(interrupt_connect_cb, idev,
606                                 NULL, &err,
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,
611                                 BT_IO_OPT_INVALID);
612         if (!io) {
613                 error("%s", err->message);
614                 g_error_free(err);
615                 goto failed;
616         }
617
618         idev->intr_io = io;
619
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);
623
624         return;
625
626 failed:
627         btd_service_connecting_complete(idev->service, -EIO);
628         g_io_channel_unref(idev->ctrl_io);
629         idev->ctrl_io = NULL;
630 }
631
632 static int dev_connect(struct input_device *idev)
633 {
634         GError *err = NULL;
635         GIOChannel *io;
636
637         if (idev->disable_sdp)
638                 bt_clear_cached_session(&idev->src, &idev->dst);
639
640         io = bt_io_connect(control_connect_cb, idev,
641                         NULL, &err,
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,
646                         BT_IO_OPT_INVALID);
647         idev->ctrl_io = io;
648
649         if (err == NULL)
650                 return 0;
651
652         error("%s", err->message);
653         g_error_free(err);
654
655         return -EIO;
656 }
657
658 static gboolean input_device_auto_reconnect(gpointer user_data)
659 {
660         struct input_device *idev = user_data;
661
662         DBG("path=%s, attempt=%d", idev->path, idev->reconnect_attempt);
663
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))
668                 return FALSE;
669
670         /* Only attempt an auto-reconnect for at most 3 minutes (6 * 30s). */
671         if (idev->reconnect_attempt >= 6)
672                 return FALSE;
673
674         /* Check if the profile is already connected. */
675         if (idev->ctrl_io)
676                 return FALSE;
677
678         if (is_connected(idev))
679                 return FALSE;
680
681         idev->reconnect_attempt++;
682         dev_connect(idev);
683
684         return TRUE;
685 }
686
687 static const char * const _reconnect_mode_str[] = {
688         "none",
689         "device",
690         "host",
691         "any"
692 };
693
694 static const char *reconnect_mode_to_string(const enum reconnect_mode_t mode)
695 {
696         return _reconnect_mode_str[mode];
697 }
698
699 static void input_device_enter_reconnect_mode(struct input_device *idev)
700 {
701         DBG("path=%s reconnect_mode=%s", idev->path,
702                                 reconnect_mode_to_string(idev->reconnect_mode));
703
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)
708                 return;
709
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))
714                 return;
715
716         if (idev->reconnect_timer > 0)
717                 g_source_remove(idev->reconnect_timer);
718
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);
723
724 }
725
726 int input_device_connect(struct btd_service *service)
727 {
728         struct input_device *idev;
729
730         DBG("");
731
732         idev = btd_service_get_user_data(service);
733
734         if (idev->ctrl_io)
735                 return -EBUSY;
736
737         if (is_connected(idev))
738                 return -EALREADY;
739
740         return dev_connect(idev);
741 }
742
743 int input_device_disconnect(struct btd_service *service)
744 {
745         struct input_device *idev;
746         int err;
747
748         DBG("");
749
750         idev = btd_service_get_user_data(service);
751
752         err = connection_disconnect(idev, 0);
753         if (err < 0)
754                 return err;
755
756         return 0;
757 }
758
759 static bool is_device_sdp_disable(const sdp_record_t *rec)
760 {
761         sdp_data_t *data;
762
763         data = sdp_data_get(rec, SDP_ATTR_HID_SDP_DISABLE);
764
765         return data && data->val.uint8;
766 }
767
768 static enum reconnect_mode_t hid_reconnection_mode(bool reconnect_initiate,
769                                                 bool normally_connectable)
770 {
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;
779 }
780
781 static void extract_hid_props(struct input_device *idev,
782                                         const sdp_record_t *rec)
783 {
784         /* Extract HID connectability */
785         bool reconnect_initiate, normally_connectable;
786         sdp_data_t *pdlist;
787
788         /* HIDNormallyConnectable is optional and assumed FALSE
789         * if not present. */
790         pdlist = sdp_data_get(rec, SDP_ATTR_HID_RECONNECT_INITIATE);
791         reconnect_initiate = pdlist ? pdlist->val.uint8 : TRUE;
792
793         pdlist = sdp_data_get(rec, SDP_ATTR_HID_NORMALLY_CONNECTABLE);
794         normally_connectable = pdlist ? pdlist->val.uint8 : FALSE;
795
796         /* Update local values */
797         idev->reconnect_mode =
798                 hid_reconnection_mode(reconnect_initiate, normally_connectable);
799 }
800
801 static struct input_device *input_device_new(struct btd_service *service)
802 {
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;
809
810         if (!rec)
811                 return NULL;
812
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);
821
822         /* Initialize device properties */
823         extract_hid_props(idev, rec);
824
825         return idev;
826 }
827
828 static gboolean property_get_reconnect_mode(
829                                         const GDBusPropertyTable *property,
830                                         DBusMessageIter *iter, void *data)
831 {
832         struct input_device *idev = data;
833         const char *str_mode = reconnect_mode_to_string(idev->reconnect_mode);
834
835         dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &str_mode);
836
837         return TRUE;
838 }
839
840 static const GDBusPropertyTable input_properties[] = {
841         { "ReconnectMode", "s", property_get_reconnect_mode },
842         { }
843 };
844
845 int input_device_register(struct btd_service *service)
846 {
847         struct btd_device *device = btd_service_get_device(service);
848         const char *path = device_get_path(device);
849         struct input_device *idev;
850
851         DBG("%s", path);
852
853         idev = input_device_new(service);
854         if (!idev)
855                 return -EINVAL;
856
857         if (g_dbus_register_interface(btd_get_dbus_connection(),
858                                         idev->path, INPUT_INTERFACE,
859                                         NULL, NULL,
860                                         input_properties, idev,
861                                         NULL) == FALSE) {
862                 error("Unable to register %s interface", INPUT_INTERFACE);
863                 input_device_free(idev);
864                 return -EINVAL;
865         }
866
867         btd_service_set_user_data(service, idev);
868
869         return 0;
870 }
871
872 static struct input_device *find_device(const bdaddr_t *src,
873                                         const bdaddr_t *dst)
874 {
875         struct btd_device *device;
876         struct btd_service *service;
877
878         device = btd_adapter_find_device(adapter_find(src), dst);
879         if (device == NULL)
880                 return NULL;
881
882         service = btd_device_get_service(device, HID_UUID);
883         if (service == NULL)
884                 return NULL;
885
886         return btd_service_get_user_data(service);
887 }
888
889 void input_device_unregister(struct btd_service *service)
890 {
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);
894
895         DBG("%s", path);
896
897         g_dbus_unregister_interface(btd_get_dbus_connection(),
898                                                 idev->path, INPUT_INTERFACE);
899
900         input_device_free(idev);
901 }
902
903 static int input_device_connadd(struct input_device *idev)
904 {
905         int err;
906
907         err = input_device_connected(idev);
908         if (err < 0)
909                 goto error;
910
911         return 0;
912
913 error:
914         if (idev->ctrl_io) {
915                 g_io_channel_shutdown(idev->ctrl_io, FALSE, NULL);
916                 g_io_channel_unref(idev->ctrl_io);
917                 idev->ctrl_io = NULL;
918         }
919         if (idev->intr_io) {
920                 g_io_channel_shutdown(idev->intr_io, FALSE, NULL);
921                 g_io_channel_unref(idev->intr_io);
922                 idev->intr_io = NULL;
923         }
924
925         return err;
926 }
927
928 bool input_device_exists(const bdaddr_t *src, const bdaddr_t *dst)
929 {
930         if (find_device(src, dst))
931                 return true;
932
933         return false;
934 }
935
936 int input_device_set_channel(const bdaddr_t *src, const bdaddr_t *dst, int psm,
937                                                                 GIOChannel *io)
938 {
939         struct input_device *idev = find_device(src, dst);
940
941         DBG("idev %p psm %d", idev, psm);
942
943         if (!idev)
944                 return -ENOENT;
945
946         switch (psm) {
947         case L2CAP_PSM_HIDP_CTRL:
948                 if (idev->ctrl_io)
949                         return -EALREADY;
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);
954                 break;
955         case L2CAP_PSM_HIDP_INTR:
956                 if (idev->intr_io)
957                         return -EALREADY;
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);
962                 break;
963         }
964
965         if (idev->intr_io && idev->ctrl_io)
966                 input_device_connadd(idev);
967
968         return 0;
969 }
970
971 int input_device_close_channels(const bdaddr_t *src, const bdaddr_t *dst)
972 {
973         struct input_device *idev = find_device(src, dst);
974
975         if (!idev)
976                 return -ENOENT;
977
978         if (idev->intr_io)
979                 g_io_channel_shutdown(idev->intr_io, TRUE, NULL);
980
981         if (idev->ctrl_io)
982                 g_io_channel_shutdown(idev->ctrl_io, TRUE, NULL);
983
984         return 0;
985 }