Upgrade bluez5_37 :Merge the code from private
[platform/upstream/bluez.git] / android / hog.c
1 /*
2  *
3  *  BlueZ - Bluetooth protocol stack for Linux
4  *
5  *  Copyright (C) 2014  Intel Corporation.
6  *  Copyright (C) 2012  Marcel Holtmann <marcel@holtmann.org>
7  *  Copyright (C) 2012  Nordic Semiconductor Inc.
8  *  Copyright (C) 2012  Instituto Nokia de Tecnologia - INdT
9  *
10  *
11  *  This program is free software; you can redistribute it and/or modify
12  *  it under the terms of the GNU General Public License as published by
13  *  the Free Software Foundation; either version 2 of the License, or
14  *  (at your option) any later version.
15  *
16  *  This program is distributed in the hope that it will be useful,
17  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
18  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  *  GNU General Public License for more details.
20  *
21  *  You should have received a copy of the GNU General Public License
22  *  along with this program; if not, write to the Free Software
23  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
24  *
25  */
26
27 #ifdef HAVE_CONFIG_H
28 #include <config.h>
29 #endif
30
31 #include <stdlib.h>
32 #include <stdbool.h>
33 #include <errno.h>
34 #include <unistd.h>
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <fcntl.h>
38
39 #include <glib.h>
40
41 #include "lib/bluetooth.h"
42 #include "lib/sdp.h"
43 #include "lib/uuid.h"
44
45 #include "src/shared/util.h"
46 #include "src/shared/uhid.h"
47 #include "src/shared/queue.h"
48 #include "src/log.h"
49
50 #include "attrib/att.h"
51 #include "attrib/gattrib.h"
52 #include "attrib/gatt.h"
53
54 #include "btio/btio.h"
55
56 #include "android/scpp.h"
57 #include "android/dis.h"
58 #include "android/bas.h"
59 #include "android/hog.h"
60
61 #define HOG_UUID                "00001812-0000-1000-8000-00805f9b34fb"
62
63 #define HOG_INFO_UUID           0x2A4A
64 #define HOG_REPORT_MAP_UUID     0x2A4B
65 #define HOG_REPORT_UUID         0x2A4D
66 #define HOG_PROTO_MODE_UUID     0x2A4E
67 #define HOG_CONTROL_POINT_UUID  0x2A4C
68
69 #define HOG_REPORT_TYPE_INPUT   1
70 #define HOG_REPORT_TYPE_OUTPUT  2
71 #define HOG_REPORT_TYPE_FEATURE 3
72
73 #define HOG_PROTO_MODE_BOOT    0
74 #define HOG_PROTO_MODE_REPORT  1
75
76 #define HOG_REPORT_MAP_MAX_SIZE        512
77 #define HID_INFO_SIZE                   4
78 #define ATT_NOTIFICATION_HEADER_SIZE    3
79
80 struct bt_hog {
81         int                     ref_count;
82         char                    *name;
83         uint16_t                vendor;
84         uint16_t                product;
85         uint16_t                version;
86         struct gatt_primary     *primary;
87         GAttrib                 *attrib;
88         GSList                  *reports;
89         struct bt_uhid          *uhid;
90         int                     uhid_fd;
91         gboolean                has_report_id;
92         uint16_t                bcdhid;
93         uint8_t                 bcountrycode;
94         uint16_t                proto_mode_handle;
95         uint16_t                ctrlpt_handle;
96         uint8_t                 flags;
97         unsigned int            getrep_att;
98         uint16_t                getrep_id;
99         unsigned int            setrep_att;
100         uint16_t                setrep_id;
101         struct bt_scpp          *scpp;
102         struct bt_dis           *dis;
103         struct queue            *bas;
104         GSList                  *instances;
105         struct queue            *gatt_op;
106 };
107
108 struct report {
109         struct bt_hog           *hog;
110         uint8_t                 id;
111         uint8_t                 type;
112         uint16_t                ccc_handle;
113         guint                   notifyid;
114         struct gatt_char        *decl;
115         uint16_t                len;
116         uint8_t                 *value;
117 };
118
119 struct gatt_request {
120         unsigned int id;
121         struct bt_hog *hog;
122         void *user_data;
123 };
124
125 static struct gatt_request *create_request(struct bt_hog *hog,
126                                                         void *user_data)
127 {
128         struct gatt_request *req;
129
130         req = new0(struct gatt_request, 1);
131         if (!req)
132                 return NULL;
133
134         req->user_data = user_data;
135         req->hog = bt_hog_ref(hog);
136
137         return req;
138 }
139
140 static bool set_and_store_gatt_req(struct bt_hog *hog,
141                                                 struct gatt_request *req,
142                                                 unsigned int id)
143 {
144         req->id = id;
145         return queue_push_head(hog->gatt_op, req);
146 }
147
148 static void destroy_gatt_req(struct gatt_request *req)
149 {
150         queue_remove(req->hog->gatt_op, req);
151         bt_hog_unref(req->hog);
152         free(req);
153 }
154
155 static void write_char(struct bt_hog *hog, GAttrib *attrib, uint16_t handle,
156                                         const uint8_t *value, size_t vlen,
157                                         GAttribResultFunc func,
158                                         gpointer user_data)
159 {
160         struct gatt_request *req;
161         unsigned int id;
162
163         req = create_request(hog, user_data);
164         if (!req)
165                 return;
166
167         id = gatt_write_char(attrib, handle, value, vlen, func, req);
168
169         if (set_and_store_gatt_req(hog, req, id))
170                 return;
171
172         error("hog: Could not read char");
173         g_attrib_cancel(attrib, id);
174         free(req);
175 }
176
177 static void read_char(struct bt_hog *hog, GAttrib *attrib, uint16_t handle,
178                                 GAttribResultFunc func, gpointer user_data)
179 {
180         struct gatt_request *req;
181         unsigned int id;
182
183         req = create_request(hog, user_data);
184         if (!req)
185                 return;
186
187         id = gatt_read_char(attrib, handle, func, req);
188
189         if (set_and_store_gatt_req(hog, req, id))
190                 return;
191
192         error("hog: Could not read char");
193         g_attrib_cancel(attrib, id);
194         free(req);
195 }
196
197 static void discover_desc(struct bt_hog *hog, GAttrib *attrib,
198                                 uint16_t start, uint16_t end, gatt_cb_t func,
199                                 gpointer user_data)
200 {
201         struct gatt_request *req;
202         unsigned int id;
203
204         req = create_request(hog, user_data);
205         if (!req)
206                 return;
207
208         id = gatt_discover_desc(attrib, start, end, NULL, func, req);
209         if (set_and_store_gatt_req(hog, req, id))
210                 return;
211
212         error("hog: Could not discover descriptors");
213         g_attrib_cancel(attrib, id);
214         free(req);
215 }
216
217 static void discover_char(struct bt_hog *hog, GAttrib *attrib,
218                                                 uint16_t start, uint16_t end,
219                                                 bt_uuid_t *uuid, gatt_cb_t func,
220                                                 gpointer user_data)
221 {
222         struct gatt_request *req;
223         unsigned int id;
224
225         req = create_request(hog, user_data);
226         if (!req)
227                 return;
228
229         id = gatt_discover_char(attrib, start, end, uuid, func, req);
230
231         if (set_and_store_gatt_req(hog, req, id))
232                 return;
233
234         error("hog: Could not discover characteristic");
235         g_attrib_cancel(attrib, id);
236         free(req);
237 }
238
239 static void discover_primary(struct bt_hog *hog, GAttrib *attrib,
240                                                 bt_uuid_t *uuid, gatt_cb_t func,
241                                                 gpointer user_data)
242 {
243         struct gatt_request *req;
244         unsigned int id;
245
246         req = create_request(hog, user_data);
247         if (!req)
248                 return;
249
250         id = gatt_discover_primary(attrib, uuid, func, req);
251
252         if (set_and_store_gatt_req(hog, req, id))
253                 return;
254
255         error("hog: Could not send discover primary");
256         g_attrib_cancel(attrib, id);
257         free(req);
258 }
259
260 static void find_included(struct bt_hog *hog, GAttrib *attrib,
261                                         uint16_t start, uint16_t end,
262                                         gatt_cb_t func, gpointer user_data)
263 {
264         struct gatt_request *req;
265         unsigned int id;
266
267         req = create_request(hog, user_data);
268         if (!req)
269                 return;
270
271         id = gatt_find_included(attrib, start, end, func, req);
272
273         if (set_and_store_gatt_req(hog, req, id))
274                 return;
275
276         error("Could not find included");
277         g_attrib_cancel(attrib, id);
278         free(req);
279 }
280
281 static void report_value_cb(const guint8 *pdu, guint16 len, gpointer user_data)
282 {
283         struct report *report = user_data;
284         struct bt_hog *hog = report->hog;
285         struct uhid_event ev;
286         uint8_t *buf;
287         int err;
288
289         if (len < ATT_NOTIFICATION_HEADER_SIZE) {
290                 error("Malformed ATT notification");
291                 return;
292         }
293
294         pdu += ATT_NOTIFICATION_HEADER_SIZE;
295         len -= ATT_NOTIFICATION_HEADER_SIZE;
296
297         memset(&ev, 0, sizeof(ev));
298         ev.type = UHID_INPUT;
299         buf = ev.u.input.data;
300
301         if (hog->has_report_id) {
302                 buf[0] = report->id;
303                 len = MIN(len, sizeof(ev.u.input.data) - 1);
304                 memcpy(buf + 1, pdu, len);
305                 ev.u.input.size = ++len;
306         } else {
307                 len = MIN(len, sizeof(ev.u.input.data));
308                 memcpy(buf, pdu, len);
309                 ev.u.input.size = len;
310         }
311
312         err = bt_uhid_send(hog->uhid, &ev);
313         if (err < 0) {
314                 error("bt_uhid_send: %s (%d)", strerror(-err), -err);
315                 return;
316         }
317
318         DBG("HoG report (%u bytes)", ev.u.input.size);
319 }
320
321 static void report_ccc_written_cb(guint8 status, const guint8 *pdu,
322                                         guint16 plen, gpointer user_data)
323 {
324         struct gatt_request *req = user_data;
325         struct report *report = req->user_data;
326         struct bt_hog *hog = report->hog;
327
328         destroy_gatt_req(req);
329
330         if (status != 0) {
331                 error("Write report characteristic descriptor failed: %s",
332                                                         att_ecode2str(status));
333                 return;
334         }
335
336         report->notifyid = g_attrib_register(hog->attrib,
337                                         ATT_OP_HANDLE_NOTIFY,
338                                         report->decl->value_handle,
339                                         report_value_cb, report, NULL);
340
341         DBG("Report characteristic descriptor written: notifications enabled");
342 }
343
344 static void write_ccc(struct bt_hog *hog, GAttrib *attrib, uint16_t handle,
345                                                         void *user_data)
346 {
347         uint8_t value[2];
348
349         put_le16(GATT_CLIENT_CHARAC_CFG_NOTIF_BIT, value);
350
351         write_char(hog, attrib, handle, value, sizeof(value),
352                                         report_ccc_written_cb, user_data);
353 }
354
355 static void ccc_read_cb(guint8 status, const guint8 *pdu, guint16 len,
356                                                         gpointer user_data)
357 {
358         struct gatt_request *req = user_data;
359         struct report *report = req->user_data;
360
361         destroy_gatt_req(req);
362
363         if (status != 0) {
364                 error("Error reading CCC value: %s", att_ecode2str(status));
365                 return;
366         }
367
368         write_ccc(report->hog, report->hog->attrib, report->ccc_handle, report);
369 }
370
371 static void report_reference_cb(guint8 status, const guint8 *pdu,
372                                         guint16 plen, gpointer user_data)
373 {
374         struct gatt_request *req = user_data;
375         struct report *report = req->user_data;
376
377         destroy_gatt_req(req);
378
379         if (status != 0) {
380                 error("Read Report Reference descriptor failed: %s",
381                                                         att_ecode2str(status));
382                 return;
383         }
384
385         if (plen != 3) {
386                 error("Malformed ATT read response");
387                 return;
388         }
389
390         report->id = pdu[1];
391         report->type = pdu[2];
392         DBG("Report ID: 0x%02x Report type: 0x%02x", pdu[1], pdu[2]);
393
394         /* Enable notifications only for Input Reports */
395         if (report->type == HOG_REPORT_TYPE_INPUT)
396                 read_char(report->hog, report->hog->attrib, report->ccc_handle,
397                                                         ccc_read_cb, report);
398 }
399
400 static void external_report_reference_cb(guint8 status, const guint8 *pdu,
401                                         guint16 plen, gpointer user_data);
402
403 static void discover_external_cb(uint8_t status, GSList *descs, void *user_data)
404 {
405         struct gatt_request *req = user_data;
406         struct bt_hog *hog = req->user_data;
407
408         destroy_gatt_req(req);
409
410         if (status != 0) {
411                 error("Discover external descriptors failed: %s",
412                                                         att_ecode2str(status));
413                 return;
414         }
415
416         for ( ; descs; descs = descs->next) {
417                 struct gatt_desc *desc = descs->data;
418
419                 read_char(hog, hog->attrib, desc->handle,
420                                                 external_report_reference_cb,
421                                                 hog);
422         }
423 }
424
425 static void discover_external(struct bt_hog *hog, GAttrib *attrib,
426                                                 uint16_t start, uint16_t end,
427                                                 gpointer user_data)
428 {
429         bt_uuid_t uuid;
430
431         if (start > end)
432                 return;
433
434         bt_uuid16_create(&uuid, GATT_EXTERNAL_REPORT_REFERENCE);
435
436         discover_desc(hog, attrib, start, end, discover_external_cb,
437                                                                 user_data);
438 }
439
440 static void discover_report_cb(uint8_t status, GSList *descs, void *user_data)
441 {
442         struct gatt_request *req = user_data;
443         struct report *report = req->user_data;
444         struct bt_hog *hog = report->hog;
445
446         destroy_gatt_req(req);
447
448         if (status != 0) {
449                 error("Discover report descriptors failed: %s",
450                                                         att_ecode2str(status));
451                 return;
452         }
453
454         for ( ; descs; descs = descs->next) {
455                 struct gatt_desc *desc = descs->data;
456
457                 switch (desc->uuid16) {
458                 case GATT_CLIENT_CHARAC_CFG_UUID:
459                         report->ccc_handle = desc->handle;
460                         break;
461                 case GATT_REPORT_REFERENCE:
462                         read_char(hog, hog->attrib, desc->handle,
463                                                 report_reference_cb, report);
464                         break;
465                 }
466         }
467 }
468
469 static void discover_report(struct bt_hog *hog, GAttrib *attrib,
470                                                 uint16_t start, uint16_t end,
471                                                         gpointer user_data)
472 {
473         if (start > end)
474                 return;
475
476         discover_desc(hog, attrib, start, end, discover_report_cb, user_data);
477 }
478
479 static void report_read_cb(guint8 status, const guint8 *pdu, guint16 len,
480                                                         gpointer user_data)
481 {
482         struct gatt_request *req = user_data;
483         struct report *report = req->user_data;
484
485         destroy_gatt_req(req);
486
487         if (status != 0) {
488                 error("Error reading Report value: %s", att_ecode2str(status));
489                 return;
490         }
491
492         if (report->value)
493                 g_free(report->value);
494
495         report->value = g_memdup(pdu, len);
496         report->len = len;
497 }
498
499 static struct report *report_new(struct bt_hog *hog, struct gatt_char *chr)
500 {
501         struct report *report;
502
503         report = g_new0(struct report, 1);
504         report->hog = hog;
505         report->decl = g_memdup(chr, sizeof(*chr));
506         hog->reports = g_slist_append(hog->reports, report);
507
508         read_char(hog, hog->attrib, chr->value_handle, report_read_cb, report);
509
510         return report;
511 }
512
513 static void external_service_char_cb(uint8_t status, GSList *chars,
514                                                                 void *user_data)
515 {
516         struct gatt_request *req = user_data;
517         struct bt_hog *hog = req->user_data;
518         struct gatt_primary *primary = hog->primary;
519         struct report *report;
520         GSList *l;
521
522         destroy_gatt_req(req);
523
524         if (status != 0) {
525                 const char *str = att_ecode2str(status);
526                 DBG("Discover external service characteristic failed: %s", str);
527                 return;
528         }
529
530         for (l = chars; l; l = g_slist_next(l)) {
531                 struct gatt_char *chr, *next;
532                 uint16_t start, end;
533
534                 chr = l->data;
535                 next = l->next ? l->next->data : NULL;
536
537                 DBG("0x%04x UUID: %s properties: %02x",
538                                 chr->handle, chr->uuid, chr->properties);
539
540                 report = report_new(hog, chr);
541                 start = chr->value_handle + 1;
542                 end = (next ? next->handle - 1 : primary->range.end);
543                 discover_report(hog, hog->attrib, start, end, report);
544         }
545 }
546
547 static void external_report_reference_cb(guint8 status, const guint8 *pdu,
548                                         guint16 plen, gpointer user_data)
549 {
550         struct gatt_request *req = user_data;
551         struct bt_hog *hog = req->user_data;
552         uint16_t uuid16;
553         bt_uuid_t uuid;
554
555         destroy_gatt_req(req);
556
557         if (status != 0) {
558                 error("Read External Report Reference descriptor failed: %s",
559                                                         att_ecode2str(status));
560                 return;
561         }
562
563         if (plen != 3) {
564                 error("Malformed ATT read response");
565                 return;
566         }
567
568         uuid16 = get_le16(&pdu[1]);
569         DBG("External report reference read, external report characteristic "
570                                                 "UUID: 0x%04x", uuid16);
571
572         /* Do not discover if is not a Report */
573         if (uuid16 != HOG_REPORT_UUID)
574                 return;
575
576         bt_uuid16_create(&uuid, uuid16);
577         discover_char(hog, hog->attrib, 0x0001, 0xffff, &uuid,
578                                         external_service_char_cb, hog);
579 }
580
581 static int report_cmp(gconstpointer a, gconstpointer b)
582 {
583         const struct report *ra = a, *rb = b;
584
585         /* sort by type first.. */
586         if (ra->type != rb->type)
587                 return ra->type - rb->type;
588
589         /* skip id check in case of report id 0 */
590         if (!rb->id)
591                 return 0;
592
593         /* ..then by id */
594         return ra->id - rb->id;
595 }
596
597 static struct report *find_report(struct bt_hog *hog, uint8_t type, uint8_t id)
598 {
599         struct report cmp;
600         GSList *l;
601
602         cmp.type = type;
603         cmp.id = hog->has_report_id ? id : 0;
604
605         l = g_slist_find_custom(hog->reports, &cmp, report_cmp);
606
607         return l ? l->data : NULL;
608 }
609
610 static struct report *find_report_by_rtype(struct bt_hog *hog, uint8_t rtype,
611                                                                 uint8_t id)
612 {
613         uint8_t type;
614
615         switch (rtype) {
616         case UHID_FEATURE_REPORT:
617                 type = HOG_REPORT_TYPE_FEATURE;
618                 break;
619         case UHID_OUTPUT_REPORT:
620                 type = HOG_REPORT_TYPE_OUTPUT;
621                 break;
622         case UHID_INPUT_REPORT:
623                 type = HOG_REPORT_TYPE_INPUT;
624                 break;
625         default:
626                 return NULL;
627         }
628
629         return find_report(hog, type, id);
630 }
631
632 static void output_written_cb(guint8 status, const guint8 *pdu,
633                                         guint16 plen, gpointer user_data)
634 {
635         struct gatt_request *req = user_data;
636
637         destroy_gatt_req(req);
638
639         if (status != 0) {
640                 error("Write output report failed: %s", att_ecode2str(status));
641                 return;
642         }
643 }
644
645 static void forward_report(struct uhid_event *ev, void *user_data)
646 {
647         struct bt_hog *hog = user_data;
648         struct report *report;
649         void *data;
650         int size;
651
652         report = find_report_by_rtype(hog, ev->u.output.rtype,
653                                                         ev->u.output.data[0]);
654         if (!report)
655                 return;
656
657         data = ev->u.output.data;
658         size = ev->u.output.size;
659         if (hog->has_report_id && size > 0) {
660                 data++;
661                 --size;
662         }
663
664         DBG("Sending report type %d ID %d to handle 0x%X", report->type,
665                                 report->id, report->decl->value_handle);
666
667         if (hog->attrib == NULL)
668                 return;
669
670         if (report->decl->properties & GATT_CHR_PROP_WRITE)
671                 write_char(hog, hog->attrib, report->decl->value_handle,
672                                 data, size, output_written_cb, hog);
673         else if (report->decl->properties & GATT_CHR_PROP_WRITE_WITHOUT_RESP)
674                 gatt_write_cmd(hog->attrib, report->decl->value_handle,
675                                                 data, size, NULL, NULL);
676 }
677
678 static void get_feature(struct uhid_event *ev, void *user_data)
679 {
680         struct bt_hog *hog = user_data;
681         struct report *report;
682         struct uhid_event rsp;
683         int err;
684
685         memset(&rsp, 0, sizeof(rsp));
686         rsp.type = UHID_FEATURE_ANSWER;
687         rsp.u.feature_answer.id = ev->u.feature.id;
688
689         report = find_report_by_rtype(hog, ev->u.feature.rtype,
690                                                         ev->u.feature.rnum);
691         if (!report) {
692                 rsp.u.feature_answer.err = ENOTSUP;
693                 goto done;
694         }
695
696         if (!report->value) {
697                 rsp.u.feature_answer.err = EIO;
698                 goto done;
699         }
700
701         rsp.u.feature_answer.size = report->len;
702         memcpy(rsp.u.feature_answer.data, report->value, report->len);
703
704 done:
705         err = bt_uhid_send(hog->uhid, &rsp);
706         if (err < 0)
707                 error("bt_uhid_send: %s", strerror(-err));
708 }
709
710 static void set_report_cb(guint8 status, const guint8 *pdu,
711                                         guint16 plen, gpointer user_data)
712 {
713         struct bt_hog *hog = user_data;
714         struct uhid_event rsp;
715         int err;
716
717         hog->setrep_att = 0;
718
719         memset(&rsp, 0, sizeof(rsp));
720         rsp.type = UHID_SET_REPORT_REPLY;
721         rsp.u.set_report_reply.id = hog->setrep_id;
722         rsp.u.set_report_reply.err = status;
723
724         if (status != 0)
725                 error("Error setting Report value: %s", att_ecode2str(status));
726
727         err = bt_uhid_send(hog->uhid, &rsp);
728         if (err < 0)
729                 error("bt_uhid_send: %s", strerror(-err));
730 }
731
732 static void set_report(struct uhid_event *ev, void *user_data)
733 {
734         struct bt_hog *hog = user_data;
735         struct report *report;
736         void *data;
737         int size;
738         int err;
739
740         /* uhid never sends reqs in parallel; if there's a req, it timed out */
741         if (hog->setrep_att) {
742                 g_attrib_cancel(hog->attrib, hog->setrep_att);
743                 hog->setrep_att = 0;
744         }
745
746         hog->setrep_id = ev->u.set_report.id;
747
748         report = find_report_by_rtype(hog, ev->u.set_report.rtype,
749                                                         ev->u.set_report.rnum);
750         if (!report) {
751                 err = ENOTSUP;
752                 goto fail;
753         }
754
755         data = ev->u.set_report.data;
756         size = ev->u.set_report.size;
757         if (hog->has_report_id && size > 0) {
758                 data++;
759                 --size;
760         }
761
762         DBG("Sending report type %d ID %d to handle 0x%X", report->type,
763                                 report->id, report->decl->value_handle);
764
765         if (hog->attrib == NULL)
766                 return;
767
768         hog->setrep_att = gatt_write_char(hog->attrib,
769                                                 report->decl->value_handle,
770                                                 data, size, set_report_cb,
771                                                 hog);
772         if (!hog->setrep_att) {
773                 err = ENOMEM;
774                 goto fail;
775         }
776
777         return;
778 fail:
779         /* cancel the request on failure */
780         set_report_cb(err, NULL, 0, hog);
781 }
782
783 static void get_report_cb(guint8 status, const guint8 *pdu, guint16 len,
784                                                         gpointer user_data)
785 {
786         struct bt_hog *hog = user_data;
787         struct uhid_event rsp;
788         int err;
789
790         hog->getrep_att = 0;
791
792         memset(&rsp, 0, sizeof(rsp));
793         rsp.type = UHID_GET_REPORT_REPLY;
794         rsp.u.get_report_reply.id = hog->getrep_id;
795
796         if (status != 0) {
797                 error("Error reading Report value: %s", att_ecode2str(status));
798                 goto exit;
799         }
800
801         if (len == 0) {
802                 error("Error reading Report, length %d", len);
803                 status = EIO;
804                 goto exit;
805         }
806
807         if (pdu[0] != 0x0b) {
808                 error("Error reading Report, invalid response: %02x", pdu[0]);
809                 status = EPROTO;
810                 goto exit;
811         }
812
813         --len;
814         ++pdu;
815         if (hog->has_report_id && len > 0) {
816                 --len;
817                 ++pdu;
818         }
819
820         rsp.u.get_report_reply.size = len;
821         memcpy(rsp.u.get_report_reply.data, pdu, len);
822
823 exit:
824         rsp.u.get_report_reply.err = status;
825         err = bt_uhid_send(hog->uhid, &rsp);
826         if (err < 0)
827                 error("bt_uhid_send: %s", strerror(-err));
828 }
829
830 static void get_report(struct uhid_event *ev, void *user_data)
831 {
832         struct bt_hog *hog = user_data;
833         struct report *report;
834         guint8 err;
835
836         /* uhid never sends reqs in parallel; if there's a req, it timed out */
837         if (hog->getrep_att) {
838                 g_attrib_cancel(hog->attrib, hog->getrep_att);
839                 hog->getrep_att = 0;
840         }
841
842         hog->getrep_id = ev->u.get_report.id;
843
844         report = find_report_by_rtype(hog, ev->u.get_report.rtype,
845                                                         ev->u.get_report.rnum);
846         if (!report) {
847                 err = ENOTSUP;
848                 goto fail;
849         }
850
851         hog->getrep_att = gatt_read_char(hog->attrib,
852                                                 report->decl->value_handle,
853                                                 get_report_cb, hog);
854         if (!hog->getrep_att) {
855                 err = ENOMEM;
856                 goto fail;
857         }
858
859         return;
860
861 fail:
862         /* cancel the request on failure */
863         get_report_cb(err, NULL, 0, hog);
864 }
865
866 static bool get_descriptor_item_info(uint8_t *buf, ssize_t blen, ssize_t *len,
867                                                                 bool *is_long)
868 {
869         if (!blen)
870                 return false;
871
872         *is_long = (buf[0] == 0xfe);
873
874         if (*is_long) {
875                 if (blen < 3)
876                         return false;
877
878                 /*
879                  * long item:
880                  * byte 0 -> 0xFE
881                  * byte 1 -> data size
882                  * byte 2 -> tag
883                  * + data
884                  */
885
886                 *len = buf[1] + 3;
887         } else {
888                 uint8_t b_size;
889
890                 /*
891                  * short item:
892                  * byte 0[1..0] -> data size (=0, 1, 2, 4)
893                  * byte 0[3..2] -> type
894                  * byte 0[7..4] -> tag
895                  * + data
896                  */
897
898                 b_size = buf[0] & 0x03;
899                 *len = (b_size ? 1 << (b_size - 1) : 0) + 1;
900         }
901
902         /* item length should be no more than input buffer length */
903         return *len <= blen;
904 }
905
906 static char *item2string(char *str, uint8_t *buf, uint8_t len)
907 {
908         char *p = str;
909         int i;
910
911         /*
912          * Since long item tags are not defined except for vendor ones, we
913          * just ensure that short items are printed properly (up to 5 bytes).
914          */
915         for (i = 0; i < 6 && i < len; i++)
916                 p += sprintf(p, " %02x", buf[i]);
917
918         /*
919          * If there are some data left, just add continuation mark to indicate
920          * this.
921          */
922         if (i < len)
923                 sprintf(p, " ...");
924
925         return str;
926 }
927
928 static void report_map_read_cb(guint8 status, const guint8 *pdu, guint16 plen,
929                                                         gpointer user_data)
930 {
931         struct gatt_request *req = user_data;
932         struct bt_hog *hog = req->user_data;
933         uint8_t value[HOG_REPORT_MAP_MAX_SIZE];
934         struct uhid_event ev;
935         ssize_t vlen;
936         char itemstr[20]; /* 5x3 (data) + 4 (continuation) + 1 (null) */
937         int i, err;
938         GError *gerr = NULL;
939
940         destroy_gatt_req(req);
941
942         if (status != 0) {
943                 error("Report Map read failed: %s", att_ecode2str(status));
944                 return;
945         }
946
947         vlen = dec_read_resp(pdu, plen, value, sizeof(value));
948         if (vlen < 0) {
949                 error("ATT protocol error");
950                 return;
951         }
952
953         DBG("Report MAP:");
954         for (i = 0; i < vlen;) {
955                 ssize_t ilen = 0;
956                 bool long_item = false;
957
958                 if (get_descriptor_item_info(&value[i], vlen - i, &ilen,
959                                                                 &long_item)) {
960                         /* Report ID is short item with prefix 100001xx */
961                         if (!long_item && (value[i] & 0xfc) == 0x84)
962                                 hog->has_report_id = TRUE;
963
964                         DBG("\t%s", item2string(itemstr, &value[i], ilen));
965
966                         i += ilen;
967                 } else {
968                         error("Report Map parsing failed at %d", i);
969
970                         /* Just print remaining items at once and break */
971                         DBG("\t%s", item2string(itemstr, &value[i], vlen - i));
972                         break;
973                 }
974         }
975
976         /* create uHID device */
977         memset(&ev, 0, sizeof(ev));
978         ev.type = UHID_CREATE;
979
980         bt_io_get(g_attrib_get_channel(hog->attrib), &gerr,
981                         BT_IO_OPT_SOURCE, ev.u.create.phys,
982                         BT_IO_OPT_DEST, ev.u.create.uniq,
983                         BT_IO_OPT_INVALID);
984         if (gerr) {
985                 error("Failed to connection details: %s", gerr->message);
986                 g_error_free(gerr);
987                 return;
988         }
989
990         strcpy((char *) ev.u.create.name, hog->name);
991         ev.u.create.vendor = hog->vendor;
992         ev.u.create.product = hog->product;
993         ev.u.create.version = hog->version;
994         ev.u.create.country = hog->bcountrycode;
995         ev.u.create.bus = BUS_BLUETOOTH;
996         ev.u.create.rd_data = value;
997         ev.u.create.rd_size = vlen;
998
999         err = bt_uhid_send(hog->uhid, &ev);
1000         if (err < 0) {
1001                 error("bt_uhid_send: %s", strerror(-err));
1002                 return;
1003         }
1004
1005         bt_uhid_register(hog->uhid, UHID_OUTPUT, forward_report, hog);
1006         bt_uhid_register(hog->uhid, UHID_FEATURE, get_feature, hog);
1007         bt_uhid_register(hog->uhid, UHID_GET_REPORT, get_report, hog);
1008         bt_uhid_register(hog->uhid, UHID_SET_REPORT, set_report, hog);
1009 }
1010
1011 static void info_read_cb(guint8 status, const guint8 *pdu, guint16 plen,
1012                                                         gpointer user_data)
1013 {
1014         struct gatt_request *req = user_data;
1015         struct bt_hog *hog = req->user_data;
1016         uint8_t value[HID_INFO_SIZE];
1017         ssize_t vlen;
1018
1019         destroy_gatt_req(req);
1020
1021         if (status != 0) {
1022                 error("HID Information read failed: %s",
1023                                                 att_ecode2str(status));
1024                 return;
1025         }
1026
1027         vlen = dec_read_resp(pdu, plen, value, sizeof(value));
1028         if (vlen != 4) {
1029                 error("ATT protocol error");
1030                 return;
1031         }
1032
1033         hog->bcdhid = get_le16(&value[0]);
1034         hog->bcountrycode = value[2];
1035         hog->flags = value[3];
1036
1037         DBG("bcdHID: 0x%04X bCountryCode: 0x%02X Flags: 0x%02X",
1038                         hog->bcdhid, hog->bcountrycode, hog->flags);
1039 }
1040
1041 static void proto_mode_read_cb(guint8 status, const guint8 *pdu, guint16 plen,
1042                                                         gpointer user_data)
1043 {
1044         struct gatt_request *req = user_data;
1045         struct bt_hog *hog = req->user_data;
1046         uint8_t value;
1047         ssize_t vlen;
1048
1049         destroy_gatt_req(req);
1050
1051         if (status != 0) {
1052                 error("Protocol Mode characteristic read failed: %s",
1053                                                         att_ecode2str(status));
1054                 return;
1055         }
1056
1057         vlen = dec_read_resp(pdu, plen, &value, sizeof(value));
1058         if (vlen < 0) {
1059                 error("ATT protocol error");
1060                 return;
1061         }
1062
1063         if (value == HOG_PROTO_MODE_BOOT) {
1064                 uint8_t nval = HOG_PROTO_MODE_REPORT;
1065
1066                 DBG("HoG is operating in Boot Procotol Mode");
1067
1068                 gatt_write_cmd(hog->attrib, hog->proto_mode_handle, &nval,
1069                                                 sizeof(nval), NULL, NULL);
1070         } else if (value == HOG_PROTO_MODE_REPORT)
1071                 DBG("HoG is operating in Report Protocol Mode");
1072 }
1073
1074 static void char_discovered_cb(uint8_t status, GSList *chars, void *user_data)
1075 {
1076         struct gatt_request *req = user_data;
1077         struct bt_hog *hog = req->user_data;
1078         struct gatt_primary *primary = hog->primary;
1079         bt_uuid_t report_uuid, report_map_uuid, info_uuid;
1080         bt_uuid_t proto_mode_uuid, ctrlpt_uuid;
1081         struct report *report;
1082         GSList *l;
1083         uint16_t info_handle = 0, proto_mode_handle = 0;
1084
1085         destroy_gatt_req(req);
1086
1087         if (status != 0) {
1088                 const char *str = att_ecode2str(status);
1089                 DBG("Discover all characteristics failed: %s", str);
1090                 return;
1091         }
1092
1093         bt_uuid16_create(&report_uuid, HOG_REPORT_UUID);
1094         bt_uuid16_create(&report_map_uuid, HOG_REPORT_MAP_UUID);
1095         bt_uuid16_create(&info_uuid, HOG_INFO_UUID);
1096         bt_uuid16_create(&proto_mode_uuid, HOG_PROTO_MODE_UUID);
1097         bt_uuid16_create(&ctrlpt_uuid, HOG_CONTROL_POINT_UUID);
1098
1099         for (l = chars; l; l = g_slist_next(l)) {
1100                 struct gatt_char *chr, *next;
1101                 bt_uuid_t uuid;
1102                 uint16_t start, end;
1103
1104                 chr = l->data;
1105                 next = l->next ? l->next->data : NULL;
1106
1107                 DBG("0x%04x UUID: %s properties: %02x",
1108                                 chr->handle, chr->uuid, chr->properties);
1109
1110                 bt_string_to_uuid(&uuid, chr->uuid);
1111
1112                 start = chr->value_handle + 1;
1113                 end = (next ? next->handle - 1 : primary->range.end);
1114
1115                 if (bt_uuid_cmp(&uuid, &report_uuid) == 0) {
1116                         report = report_new(hog, chr);
1117                         discover_report(hog, hog->attrib, start, end, report);
1118                 } else if (bt_uuid_cmp(&uuid, &report_map_uuid) == 0) {
1119                         read_char(hog, hog->attrib, chr->value_handle,
1120                                                 report_map_read_cb, hog);
1121                         discover_external(hog, hog->attrib, start, end, hog);
1122                 } else if (bt_uuid_cmp(&uuid, &info_uuid) == 0)
1123                         info_handle = chr->value_handle;
1124                 else if (bt_uuid_cmp(&uuid, &proto_mode_uuid) == 0)
1125                         proto_mode_handle = chr->value_handle;
1126                 else if (bt_uuid_cmp(&uuid, &ctrlpt_uuid) == 0)
1127                         hog->ctrlpt_handle = chr->value_handle;
1128         }
1129
1130         if (proto_mode_handle) {
1131                 hog->proto_mode_handle = proto_mode_handle;
1132                 read_char(hog, hog->attrib, proto_mode_handle,
1133                                                 proto_mode_read_cb, hog);
1134         }
1135
1136         if (info_handle)
1137                 read_char(hog, hog->attrib, info_handle, info_read_cb, hog);
1138 }
1139
1140 static void report_free(void *data)
1141 {
1142         struct report *report = data;
1143
1144         g_free(report->value);
1145         g_free(report->decl);
1146         g_free(report);
1147 }
1148
1149 static void cancel_gatt_req(struct gatt_request *req)
1150 {
1151         if (g_attrib_cancel(req->hog->attrib, req->id))
1152                 destroy_gatt_req(req);
1153 }
1154
1155 static void hog_free(void *data)
1156 {
1157         struct bt_hog *hog = data;
1158
1159         bt_hog_detach(hog);
1160
1161         queue_destroy(hog->bas, (void *) bt_bas_unref);
1162         g_slist_free_full(hog->instances, hog_free);
1163
1164         bt_scpp_unref(hog->scpp);
1165         bt_dis_unref(hog->dis);
1166         bt_uhid_unref(hog->uhid);
1167         g_slist_free_full(hog->reports, report_free);
1168         g_free(hog->name);
1169         g_free(hog->primary);
1170         queue_destroy(hog->gatt_op, (void *) destroy_gatt_req);
1171         g_free(hog);
1172 }
1173
1174 struct bt_hog *bt_hog_new_default(const char *name, uint16_t vendor,
1175                                         uint16_t product, uint16_t version,
1176                                         void *primary)
1177 {
1178         return bt_hog_new(-1, name, vendor, product, version, primary);
1179 }
1180
1181 struct bt_hog *bt_hog_new(int fd, const char *name, uint16_t vendor,
1182                                         uint16_t product, uint16_t version,
1183                                         void *primary)
1184 {
1185         struct bt_hog *hog;
1186
1187         hog = g_try_new0(struct bt_hog, 1);
1188         if (!hog)
1189                 return NULL;
1190
1191         hog->gatt_op = queue_new();
1192         hog->bas = queue_new();
1193
1194         if (fd < 0)
1195                 hog->uhid = bt_uhid_new_default();
1196         else
1197                 hog->uhid = bt_uhid_new(fd);
1198
1199         hog->uhid_fd = fd;
1200
1201         if (!hog->gatt_op || !hog->bas || !hog->uhid) {
1202                 hog_free(hog);
1203                 return NULL;
1204         }
1205
1206         hog->name = g_strdup(name);
1207         hog->vendor = vendor;
1208         hog->product = product;
1209         hog->version = version;
1210
1211         if (primary)
1212                 hog->primary = g_memdup(primary, sizeof(*hog->primary));
1213
1214         return bt_hog_ref(hog);
1215 }
1216
1217 struct bt_hog *bt_hog_ref(struct bt_hog *hog)
1218 {
1219         if (!hog)
1220                 return NULL;
1221
1222         __sync_fetch_and_add(&hog->ref_count, 1);
1223
1224         return hog;
1225 }
1226
1227 void bt_hog_unref(struct bt_hog *hog)
1228 {
1229         if (!hog)
1230                 return;
1231
1232         if (__sync_sub_and_fetch(&hog->ref_count, 1))
1233                 return;
1234
1235         hog_free(hog);
1236 }
1237
1238 static void find_included_cb(uint8_t status, GSList *services, void *user_data)
1239 {
1240         struct gatt_request *req = user_data;
1241         GSList *l;
1242
1243         DBG("");
1244
1245         destroy_gatt_req(req);
1246
1247         if (status) {
1248                 const char *str = att_ecode2str(status);
1249                 DBG("Find included failed: %s", str);
1250                 return;
1251         }
1252
1253         for (l = services; l; l = l->next) {
1254                 struct gatt_included *include = l->data;
1255
1256                 DBG("included: handle %x, uuid %s",
1257                         include->handle, include->uuid);
1258         }
1259 }
1260
1261 static void hog_attach_scpp(struct bt_hog *hog, struct gatt_primary *primary)
1262 {
1263         if (hog->scpp) {
1264                 bt_scpp_attach(hog->scpp, hog->attrib);
1265                 return;
1266         }
1267
1268         hog->scpp = bt_scpp_new(primary);
1269         if (hog->scpp)
1270                 bt_scpp_attach(hog->scpp, hog->attrib);
1271 }
1272
1273 static void dis_notify(uint8_t source, uint16_t vendor, uint16_t product,
1274                                         uint16_t version, void *user_data)
1275 {
1276         struct bt_hog *hog = user_data;
1277
1278         hog->vendor = vendor;
1279         hog->product = product;
1280         hog->version = version;
1281 }
1282
1283 static void hog_attach_dis(struct bt_hog *hog, struct gatt_primary *primary)
1284 {
1285         if (hog->dis) {
1286                 bt_dis_attach(hog->dis, hog->attrib);
1287                 return;
1288         }
1289
1290         hog->dis = bt_dis_new(primary);
1291         if (hog->dis) {
1292                 bt_dis_set_notification(hog->dis, dis_notify, hog);
1293                 bt_dis_attach(hog->dis, hog->attrib);
1294         }
1295 }
1296
1297 static void hog_attach_bas(struct bt_hog *hog, struct gatt_primary *primary)
1298 {
1299         struct bt_bas *instance;
1300
1301         instance = bt_bas_new(primary);
1302         if (!instance)
1303                 return;
1304
1305         bt_bas_attach(instance, hog->attrib);
1306         queue_push_head(hog->bas, instance);
1307 }
1308
1309 static void hog_attach_hog(struct bt_hog *hog, struct gatt_primary *primary)
1310 {
1311         struct bt_hog *instance;
1312
1313         if (!hog->primary) {
1314                 hog->primary = g_memdup(primary, sizeof(*primary));
1315                 discover_char(hog, hog->attrib, primary->range.start,
1316                                                 primary->range.end, NULL,
1317                                                 char_discovered_cb, hog);
1318                 find_included(hog, hog->attrib, primary->range.start,
1319                                 primary->range.end, find_included_cb, hog);
1320                 return;
1321         }
1322
1323         instance = bt_hog_new(hog->uhid_fd, hog->name, hog->vendor,
1324                                         hog->product, hog->version, primary);
1325         if (!instance)
1326                 return;
1327
1328         find_included(instance, hog->attrib, primary->range.start,
1329                         primary->range.end, find_included_cb, instance);
1330
1331         bt_hog_attach(instance, hog->attrib);
1332         hog->instances = g_slist_append(hog->instances, instance);
1333 }
1334
1335 static void primary_cb(uint8_t status, GSList *services, void *user_data)
1336 {
1337         struct gatt_request *req = user_data;
1338         struct bt_hog *hog = req->user_data;
1339         struct gatt_primary *primary;
1340         GSList *l;
1341
1342         DBG("");
1343
1344         destroy_gatt_req(req);
1345
1346         if (status) {
1347                 const char *str = att_ecode2str(status);
1348                 DBG("Discover primary failed: %s", str);
1349                 return;
1350         }
1351
1352         if (!services) {
1353                 DBG("No primary service found");
1354                 return;
1355         }
1356
1357         for (l = services; l; l = l->next) {
1358                 primary = l->data;
1359
1360                 if (strcmp(primary->uuid, SCAN_PARAMETERS_UUID) == 0) {
1361                         hog_attach_scpp(hog, primary);
1362                         continue;
1363                 }
1364
1365                 if (strcmp(primary->uuid, DEVICE_INFORMATION_UUID) == 0) {
1366                         hog_attach_dis(hog, primary);
1367                         continue;
1368                 }
1369
1370                 if (strcmp(primary->uuid, BATTERY_UUID) == 0) {
1371                         hog_attach_bas(hog, primary);
1372                         continue;
1373                 }
1374
1375                 if (strcmp(primary->uuid, HOG_UUID) == 0)
1376                         hog_attach_hog(hog, primary);
1377         }
1378 }
1379
1380 bool bt_hog_attach(struct bt_hog *hog, void *gatt)
1381 {
1382         struct gatt_primary *primary = hog->primary;
1383         GSList *l;
1384
1385         if (hog->attrib)
1386                 return false;
1387
1388         hog->attrib = g_attrib_ref(gatt);
1389
1390         if (!primary) {
1391                 discover_primary(hog, hog->attrib, NULL, primary_cb, hog);
1392                 return true;
1393         }
1394
1395         if (hog->scpp)
1396                 bt_scpp_attach(hog->scpp, gatt);
1397
1398         if (hog->dis)
1399                 bt_dis_attach(hog->dis, gatt);
1400
1401         queue_foreach(hog->bas, (void *) bt_bas_attach, gatt);
1402
1403         for (l = hog->instances; l; l = l->next) {
1404                 struct bt_hog *instance = l->data;
1405
1406                 bt_hog_attach(instance, gatt);
1407         }
1408
1409         if (hog->reports == NULL) {
1410                 discover_char(hog, hog->attrib, primary->range.start,
1411                                                 primary->range.end, NULL,
1412                                                 char_discovered_cb, hog);
1413                 return true;
1414         }
1415
1416         for (l = hog->reports; l; l = l->next) {
1417                 struct report *r = l->data;
1418
1419                 r->notifyid = g_attrib_register(hog->attrib,
1420                                         ATT_OP_HANDLE_NOTIFY,
1421                                         r->decl->value_handle,
1422                                         report_value_cb, r, NULL);
1423         }
1424
1425         return true;
1426 }
1427
1428 void bt_hog_detach(struct bt_hog *hog)
1429 {
1430         GSList *l;
1431
1432         if (!hog->attrib)
1433                 return;
1434
1435         queue_foreach(hog->bas, (void *) bt_bas_detach, NULL);
1436
1437         for (l = hog->instances; l; l = l->next) {
1438                 struct bt_hog *instance = l->data;
1439
1440                 bt_hog_detach(instance);
1441         }
1442
1443         for (l = hog->reports; l; l = l->next) {
1444                 struct report *r = l->data;
1445
1446                 if (r->notifyid > 0) {
1447                         g_attrib_unregister(hog->attrib, r->notifyid);
1448                         r->notifyid = 0;
1449                 }
1450         }
1451
1452         if (hog->scpp)
1453                 bt_scpp_detach(hog->scpp);
1454
1455         if (hog->dis)
1456                 bt_dis_detach(hog->dis);
1457
1458         queue_foreach(hog->gatt_op, (void *) cancel_gatt_req, NULL);
1459         g_attrib_unref(hog->attrib);
1460         hog->attrib = NULL;
1461 }
1462
1463 int bt_hog_set_control_point(struct bt_hog *hog, bool suspend)
1464 {
1465         uint8_t value = suspend ? 0x00 : 0x01;
1466
1467         if (hog->attrib == NULL)
1468                 return -ENOTCONN;
1469
1470         if (hog->ctrlpt_handle == 0)
1471                 return -ENOTSUP;
1472
1473         gatt_write_cmd(hog->attrib, hog->ctrlpt_handle, &value,
1474                                         sizeof(value), NULL, NULL);
1475
1476         return 0;
1477 }
1478
1479 int bt_hog_send_report(struct bt_hog *hog, void *data, size_t size, int type)
1480 {
1481         struct report *report;
1482         GSList *l;
1483
1484         if (!hog)
1485                 return -EINVAL;
1486
1487         if (!hog->attrib)
1488                 return -ENOTCONN;
1489
1490         report = find_report(hog, type, 0);
1491         if (!report)
1492                 return -ENOTSUP;
1493
1494         DBG("hog: Write report, handle 0x%X", report->decl->value_handle);
1495
1496         if (report->decl->properties & GATT_CHR_PROP_WRITE)
1497                 write_char(hog, hog->attrib, report->decl->value_handle,
1498                                 data, size, output_written_cb, hog);
1499
1500         if (report->decl->properties & GATT_CHR_PROP_WRITE_WITHOUT_RESP)
1501                 gatt_write_cmd(hog->attrib, report->decl->value_handle,
1502                                                 data, size, NULL, NULL);
1503
1504         for (l = hog->instances; l; l = l->next) {
1505                 struct bt_hog *instance = l->data;
1506
1507                 bt_hog_send_report(instance, data, size, type);
1508         }
1509
1510         return 0;
1511 }