Upgrade bluez5_37 :Merge the code from private
[platform/upstream/bluez.git] / src / shared / att.c
1 /*
2  *
3  *  BlueZ - Bluetooth protocol stack for Linux
4  *
5  *  Copyright (C) 2014  Google Inc.
6  *
7  *
8  *  This library is free software; you can redistribute it and/or
9  *  modify it under the terms of the GNU Lesser General Public
10  *  License as published by the Free Software Foundation; either
11  *  version 2.1 of the License, or (at your option) any later version.
12  *
13  *  This library 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 GNU
16  *  Lesser General Public License for more details.
17  *
18  *  You should have received a copy of the GNU Lesser General Public
19  *  License along with this library; 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 <unistd.h>
30 #include <errno.h>
31
32 #include "src/shared/io.h"
33 #include "src/shared/queue.h"
34 #include "src/shared/util.h"
35 #include "src/shared/timeout.h"
36 #include "lib/bluetooth.h"
37 #include "lib/uuid.h"
38 #include "src/shared/att.h"
39 #include "src/shared/crypto.h"
40
41 #define ATT_MIN_PDU_LEN                 1  /* At least 1 byte for the opcode. */
42 #define ATT_OP_CMD_MASK                 0x40
43 #define ATT_OP_SIGNED_MASK              0x80
44 #define ATT_TIMEOUT_INTERVAL            30000  /* 30000 ms */
45
46 /* Length of signature in write signed packet */
47 #define BT_ATT_SIGNATURE_LEN            12
48
49 struct att_send_op;
50
51 struct bt_att {
52         int ref_count;
53         int fd;
54         struct io *io;
55         bool io_on_l2cap;
56         int io_sec_level;               /* Only used for non-L2CAP */
57
58         struct queue *req_queue;        /* Queued ATT protocol requests */
59         struct att_send_op *pending_req;
60         struct queue *ind_queue;        /* Queued ATT protocol indications */
61         struct att_send_op *pending_ind;
62         struct queue *write_queue;      /* Queue of PDUs ready to send */
63         bool writer_active;
64
65         struct queue *notify_list;      /* List of registered callbacks */
66         struct queue *disconn_list;     /* List of disconnect handlers */
67
68         bool in_req;                    /* There's a pending incoming request */
69
70         uint8_t *buf;
71         uint16_t mtu;
72
73         unsigned int next_send_id;      /* IDs for "send" ops */
74         unsigned int next_reg_id;       /* IDs for registered callbacks */
75
76         bt_att_timeout_func_t timeout_callback;
77         bt_att_destroy_func_t timeout_destroy;
78         void *timeout_data;
79
80         bt_att_debug_func_t debug_callback;
81         bt_att_destroy_func_t debug_destroy;
82         void *debug_data;
83
84         struct bt_crypto *crypto;
85
86         struct sign_info *local_sign;
87         struct sign_info *remote_sign;
88 };
89
90 struct sign_info {
91         uint8_t key[16];
92         bt_att_counter_func_t counter;
93         void *user_data;
94 };
95
96 enum att_op_type {
97         ATT_OP_TYPE_REQ,
98         ATT_OP_TYPE_RSP,
99         ATT_OP_TYPE_CMD,
100         ATT_OP_TYPE_IND,
101         ATT_OP_TYPE_NOT,
102         ATT_OP_TYPE_CONF,
103         ATT_OP_TYPE_UNKNOWN,
104 };
105
106 static const struct {
107         uint8_t opcode;
108         enum att_op_type type;
109 } att_opcode_type_table[] = {
110         { BT_ATT_OP_ERROR_RSP,                  ATT_OP_TYPE_RSP },
111         { BT_ATT_OP_MTU_REQ,                    ATT_OP_TYPE_REQ },
112         { BT_ATT_OP_MTU_RSP,                    ATT_OP_TYPE_RSP },
113         { BT_ATT_OP_FIND_INFO_REQ,              ATT_OP_TYPE_REQ },
114         { BT_ATT_OP_FIND_INFO_RSP,              ATT_OP_TYPE_RSP },
115         { BT_ATT_OP_FIND_BY_TYPE_REQ,           ATT_OP_TYPE_REQ },
116         { BT_ATT_OP_FIND_BY_TYPE_RSP,           ATT_OP_TYPE_RSP },
117         { BT_ATT_OP_READ_BY_TYPE_REQ,           ATT_OP_TYPE_REQ },
118         { BT_ATT_OP_READ_BY_TYPE_RSP,           ATT_OP_TYPE_RSP },
119         { BT_ATT_OP_READ_REQ,                   ATT_OP_TYPE_REQ },
120         { BT_ATT_OP_READ_RSP,                   ATT_OP_TYPE_RSP },
121         { BT_ATT_OP_READ_BLOB_REQ,              ATT_OP_TYPE_REQ },
122         { BT_ATT_OP_READ_BLOB_RSP,              ATT_OP_TYPE_RSP },
123         { BT_ATT_OP_READ_MULT_REQ,              ATT_OP_TYPE_REQ },
124         { BT_ATT_OP_READ_MULT_RSP,              ATT_OP_TYPE_RSP },
125         { BT_ATT_OP_READ_BY_GRP_TYPE_REQ,       ATT_OP_TYPE_REQ },
126         { BT_ATT_OP_READ_BY_GRP_TYPE_RSP,       ATT_OP_TYPE_RSP },
127         { BT_ATT_OP_WRITE_REQ,                  ATT_OP_TYPE_REQ },
128         { BT_ATT_OP_WRITE_RSP,                  ATT_OP_TYPE_RSP },
129         { BT_ATT_OP_WRITE_CMD,                  ATT_OP_TYPE_CMD },
130         { BT_ATT_OP_SIGNED_WRITE_CMD,           ATT_OP_TYPE_CMD },
131         { BT_ATT_OP_PREP_WRITE_REQ,             ATT_OP_TYPE_REQ },
132         { BT_ATT_OP_PREP_WRITE_RSP,             ATT_OP_TYPE_RSP },
133         { BT_ATT_OP_EXEC_WRITE_REQ,             ATT_OP_TYPE_REQ },
134         { BT_ATT_OP_EXEC_WRITE_RSP,             ATT_OP_TYPE_RSP },
135         { BT_ATT_OP_HANDLE_VAL_NOT,             ATT_OP_TYPE_NOT },
136         { BT_ATT_OP_HANDLE_VAL_IND,             ATT_OP_TYPE_IND },
137         { BT_ATT_OP_HANDLE_VAL_CONF,            ATT_OP_TYPE_CONF },
138         { }
139 };
140
141 static enum att_op_type get_op_type(uint8_t opcode)
142 {
143         int i;
144
145         for (i = 0; att_opcode_type_table[i].opcode; i++) {
146                 if (att_opcode_type_table[i].opcode == opcode)
147                         return att_opcode_type_table[i].type;
148         }
149
150         return ATT_OP_TYPE_UNKNOWN;
151 }
152
153 static const struct {
154         uint8_t req_opcode;
155         uint8_t rsp_opcode;
156 } att_req_rsp_mapping_table[] = {
157         { BT_ATT_OP_MTU_REQ,                    BT_ATT_OP_MTU_RSP },
158         { BT_ATT_OP_FIND_INFO_REQ,              BT_ATT_OP_FIND_INFO_RSP},
159         { BT_ATT_OP_FIND_BY_TYPE_REQ,           BT_ATT_OP_FIND_BY_TYPE_RSP },
160         { BT_ATT_OP_READ_BY_TYPE_REQ,           BT_ATT_OP_READ_BY_TYPE_RSP },
161         { BT_ATT_OP_READ_REQ,                   BT_ATT_OP_READ_RSP },
162         { BT_ATT_OP_READ_BLOB_REQ,              BT_ATT_OP_READ_BLOB_RSP },
163         { BT_ATT_OP_READ_MULT_REQ,              BT_ATT_OP_READ_MULT_RSP },
164         { BT_ATT_OP_READ_BY_GRP_TYPE_REQ,       BT_ATT_OP_READ_BY_GRP_TYPE_RSP },
165         { BT_ATT_OP_WRITE_REQ,                  BT_ATT_OP_WRITE_RSP },
166         { BT_ATT_OP_PREP_WRITE_REQ,             BT_ATT_OP_PREP_WRITE_RSP },
167         { BT_ATT_OP_EXEC_WRITE_REQ,             BT_ATT_OP_EXEC_WRITE_RSP },
168         { }
169 };
170
171 static uint8_t get_req_opcode(uint8_t rsp_opcode)
172 {
173         int i;
174
175         for (i = 0; att_req_rsp_mapping_table[i].rsp_opcode; i++) {
176                 if (att_req_rsp_mapping_table[i].rsp_opcode == rsp_opcode)
177                         return att_req_rsp_mapping_table[i].req_opcode;
178         }
179
180         return 0;
181 }
182
183 struct att_send_op {
184         unsigned int id;
185         unsigned int timeout_id;
186         enum att_op_type type;
187         uint16_t opcode;
188         void *pdu;
189         uint16_t len;
190         bt_att_response_func_t callback;
191         bt_att_destroy_func_t destroy;
192         void *user_data;
193 };
194
195 static void destroy_att_send_op(void *data)
196 {
197         struct att_send_op *op = data;
198
199         if (op->timeout_id)
200                 timeout_remove(op->timeout_id);
201
202         if (op->destroy)
203                 op->destroy(op->user_data);
204
205         free(op->pdu);
206         free(op);
207 }
208
209 static void cancel_att_send_op(struct att_send_op *op)
210 {
211 #ifdef __TIZEN_PATCH__
212         if (op->callback)
213                 op->callback(BT_ATT_OP_ERROR_RSP, NULL, 0, op->user_data);
214 #endif
215         if (op->destroy)
216                 op->destroy(op->user_data);
217
218         op->user_data = NULL;
219         op->callback = NULL;
220         op->destroy = NULL;
221 }
222
223 struct att_notify {
224         unsigned int id;
225         uint16_t opcode;
226         bt_att_notify_func_t callback;
227         bt_att_destroy_func_t destroy;
228         void *user_data;
229 };
230
231 static void destroy_att_notify(void *data)
232 {
233         struct att_notify *notify = data;
234
235         if (notify->destroy)
236                 notify->destroy(notify->user_data);
237
238         free(notify);
239 }
240
241 static bool match_notify_id(const void *a, const void *b)
242 {
243         const struct att_notify *notify = a;
244         unsigned int id = PTR_TO_UINT(b);
245
246         return notify->id == id;
247 }
248
249 struct att_disconn {
250         unsigned int id;
251         bool removed;
252         bt_att_disconnect_func_t callback;
253         bt_att_destroy_func_t destroy;
254         void *user_data;
255 };
256
257 static void destroy_att_disconn(void *data)
258 {
259         struct att_disconn *disconn = data;
260
261         if (disconn->destroy)
262                 disconn->destroy(disconn->user_data);
263
264         free(disconn);
265 }
266
267 static bool match_disconn_id(const void *a, const void *b)
268 {
269         const struct att_disconn *disconn = a;
270         unsigned int id = PTR_TO_UINT(b);
271
272         return disconn->id == id;
273 }
274
275 static bool encode_pdu(struct bt_att *att, struct att_send_op *op,
276                                         const void *pdu, uint16_t length)
277 {
278         uint16_t pdu_len = 1;
279         struct sign_info *sign = att->local_sign;
280         uint32_t sign_cnt;
281
282         if (sign && (op->opcode & ATT_OP_SIGNED_MASK))
283                 pdu_len += BT_ATT_SIGNATURE_LEN;
284
285         if (length && pdu)
286                 pdu_len += length;
287
288         if (pdu_len > att->mtu)
289                 return false;
290
291         op->len = pdu_len;
292         op->pdu = malloc(op->len);
293         if (!op->pdu)
294                 return false;
295
296         ((uint8_t *) op->pdu)[0] = op->opcode;
297         if (pdu_len > 1)
298                 memcpy(op->pdu + 1, pdu, length);
299
300         if (!sign || !(op->opcode & ATT_OP_SIGNED_MASK) || !att->crypto)
301                 return true;
302
303         if (!sign->counter(&sign_cnt, sign->user_data))
304                 goto fail;
305
306         if ((bt_crypto_sign_att(att->crypto, sign->key, op->pdu, 1 + length,
307                                 sign_cnt, &((uint8_t *) op->pdu)[1 + length])))
308                 return true;
309
310         util_debug(att->debug_callback, att->debug_data,
311                                         "ATT unable to generate signature");
312
313 fail:
314         free(op->pdu);
315         return false;
316 }
317
318 static struct att_send_op *create_att_send_op(struct bt_att *att,
319                                                 uint8_t opcode,
320                                                 const void *pdu,
321                                                 uint16_t length,
322                                                 bt_att_response_func_t callback,
323                                                 void *user_data,
324                                                 bt_att_destroy_func_t destroy)
325 {
326         struct att_send_op *op;
327         enum att_op_type type;
328
329         if (length && !pdu)
330                 return NULL;
331
332         type = get_op_type(opcode);
333         if (type == ATT_OP_TYPE_UNKNOWN)
334                 return NULL;
335
336         /* If the opcode corresponds to an operation type that does not elicit a
337          * response from the remote end, then no callback should have been
338          * provided, since it will never be called.
339          */
340 #ifdef __TIZEN_PATCH__
341         if (callback && type != ATT_OP_TYPE_REQ && type != ATT_OP_TYPE_IND
342                      && type != ATT_OP_TYPE_CMD)
343                 return NULL;
344 #else
345         if (callback && type != ATT_OP_TYPE_REQ && type != ATT_OP_TYPE_IND)
346                 return NULL;
347 #endif
348
349         /* Similarly, if the operation does elicit a response then a callback
350          * must be provided.
351          */
352         if (!callback && (type == ATT_OP_TYPE_REQ || type == ATT_OP_TYPE_IND))
353                 return NULL;
354
355         op = new0(struct att_send_op, 1);
356         op->type = type;
357         op->opcode = opcode;
358         op->callback = callback;
359         op->destroy = destroy;
360         op->user_data = user_data;
361
362         if (!encode_pdu(att, op, pdu, length)) {
363                 free(op);
364                 return NULL;
365         }
366
367         return op;
368 }
369
370 static struct att_send_op *pick_next_send_op(struct bt_att *att)
371 {
372         struct att_send_op *op;
373
374         /* See if any operations are already in the write queue */
375         op = queue_pop_head(att->write_queue);
376         if (op)
377                 return op;
378
379         /* If there is no pending request, pick an operation from the
380          * request queue.
381          */
382         if (!att->pending_req) {
383                 op = queue_pop_head(att->req_queue);
384                 if (op)
385                         return op;
386         }
387
388         /* There is either a request pending or no requests queued. If there is
389          * no pending indication, pick an operation from the indication queue.
390          */
391         if (!att->pending_ind) {
392                 op = queue_pop_head(att->ind_queue);
393                 if (op)
394                         return op;
395         }
396
397         return NULL;
398 }
399
400 struct timeout_data {
401         struct bt_att *att;
402         unsigned int id;
403 };
404
405 static bool timeout_cb(void *user_data)
406 {
407         struct timeout_data *timeout = user_data;
408         struct bt_att *att = timeout->att;
409         struct att_send_op *op = NULL;
410
411         if (att->pending_req && att->pending_req->id == timeout->id) {
412                 op = att->pending_req;
413                 att->pending_req = NULL;
414         } else if (att->pending_ind && att->pending_ind->id == timeout->id) {
415                 op = att->pending_ind;
416                 att->pending_ind = NULL;
417         }
418
419         if (!op)
420                 return false;
421
422         util_debug(att->debug_callback, att->debug_data,
423                                 "Operation timed out: 0x%02x", op->opcode);
424
425         if (att->timeout_callback)
426                 att->timeout_callback(op->id, op->opcode, att->timeout_data);
427
428         op->timeout_id = 0;
429         destroy_att_send_op(op);
430
431         /*
432          * Directly terminate the connection as required by the ATT protocol.
433          * This should trigger an io disconnect event which will clean up the
434          * io and notify the upper layer.
435          */
436         io_shutdown(att->io);
437
438         return false;
439 }
440
441 static void write_watch_destroy(void *user_data)
442 {
443         struct bt_att *att = user_data;
444
445         att->writer_active = false;
446 }
447
448 static bool can_write_data(struct io *io, void *user_data)
449 {
450         struct bt_att *att = user_data;
451         struct att_send_op *op;
452         struct timeout_data *timeout;
453         ssize_t ret;
454         struct iovec iov;
455
456         op = pick_next_send_op(att);
457         if (!op)
458                 return false;
459
460         iov.iov_base = op->pdu;
461         iov.iov_len = op->len;
462
463         ret = io_send(io, &iov, 1);
464         if (ret < 0) {
465                 util_debug(att->debug_callback, att->debug_data,
466                                         "write failed: %s", strerror(-ret));
467                 if (op->callback)
468                         op->callback(BT_ATT_OP_ERROR_RSP, NULL, 0,
469                                                         op->user_data);
470
471                 destroy_att_send_op(op);
472                 return true;
473         }
474
475         util_debug(att->debug_callback, att->debug_data,
476                                         "ATT op 0x%02x", op->opcode);
477
478         util_hexdump('<', op->pdu, ret, att->debug_callback, att->debug_data);
479
480         /* Based on the operation type, set either the pending request or the
481          * pending indication. If it came from the write queue, then there is
482          * no need to keep it around.
483          */
484         switch (op->type) {
485         case ATT_OP_TYPE_REQ:
486                 att->pending_req = op;
487                 break;
488         case ATT_OP_TYPE_IND:
489                 att->pending_ind = op;
490                 break;
491 #ifdef __TIZEN_PATCH__
492         case ATT_OP_TYPE_CMD:
493                 if (op->callback)
494                         op->callback(0, NULL, 0, op->user_data);
495                 destroy_att_send_op(op);
496                 return true;
497 #endif
498         case ATT_OP_TYPE_RSP:
499                 /* Set in_req to false to indicate that no request is pending */
500                 att->in_req = false;
501
502                 /* Fall through to the next case */
503 #ifndef __TIZEN_PATCH__
504         case ATT_OP_TYPE_CMD:
505 #endif
506         case ATT_OP_TYPE_NOT:
507         case ATT_OP_TYPE_CONF:
508         case ATT_OP_TYPE_UNKNOWN:
509         default:
510                 destroy_att_send_op(op);
511                 return true;
512         }
513
514         timeout = new0(struct timeout_data, 1);
515         timeout->att = att;
516         timeout->id = op->id;
517         op->timeout_id = timeout_add(ATT_TIMEOUT_INTERVAL, timeout_cb,
518                                                                 timeout, free);
519
520         /* Return true as there may be more operations ready to write. */
521         return true;
522 }
523
524 static void wakeup_writer(struct bt_att *att)
525 {
526         if (att->writer_active)
527                 return;
528
529         /* Set the write handler only if there is anything that can be sent
530          * at all.
531          */
532         if (queue_isempty(att->write_queue)) {
533                 if ((att->pending_req || queue_isempty(att->req_queue)) &&
534                         (att->pending_ind || queue_isempty(att->ind_queue)))
535                         return;
536         }
537
538         if (!io_set_write_handler(att->io, can_write_data, att,
539                                                         write_watch_destroy))
540                 return;
541
542         att->writer_active = true;
543 }
544
545 static void disconn_handler(void *data, void *user_data)
546 {
547         struct att_disconn *disconn = data;
548         int err = PTR_TO_INT(user_data);
549
550         if (disconn->removed)
551                 return;
552
553         if (disconn->callback)
554                 disconn->callback(err, disconn->user_data);
555 }
556
557 static bool disconnect_cb(struct io *io, void *user_data)
558 {
559         struct bt_att *att = user_data;
560         int err;
561         socklen_t len;
562
563         len = sizeof(err);
564
565         if (getsockopt(att->fd, SOL_SOCKET, SO_ERROR, &err, &len) < 0) {
566                 util_debug(att->debug_callback, att->debug_data,
567                                         "Failed to obtain disconnect error: %s",
568                                         strerror(errno));
569                 err = 0;
570         }
571
572         util_debug(att->debug_callback, att->debug_data,
573                                         "Physical link disconnected: %s",
574                                         strerror(err));
575
576         io_destroy(att->io);
577         att->io = NULL;
578
579         bt_att_cancel_all(att);
580
581         bt_att_ref(att);
582
583         queue_foreach(att->disconn_list, disconn_handler, INT_TO_PTR(err));
584
585         bt_att_unregister_all(att);
586         bt_att_unref(att);
587
588         return false;
589 }
590
591 static bool change_security(struct bt_att *att, uint8_t ecode)
592 {
593         int security;
594
595         security = bt_att_get_security(att);
596         if (security != BT_ATT_SECURITY_AUTO)
597                 return false;
598
599         if (ecode == BT_ATT_ERROR_INSUFFICIENT_ENCRYPTION &&
600                                         security < BT_ATT_SECURITY_MEDIUM)
601                 security = BT_ATT_SECURITY_MEDIUM;
602         else if (ecode == BT_ATT_ERROR_AUTHENTICATION &&
603                                         security < BT_ATT_SECURITY_HIGH)
604                 security = BT_ATT_SECURITY_HIGH;
605         else
606                 return false;
607
608         return bt_att_set_security(att, security);
609 }
610
611 static bool handle_error_rsp(struct bt_att *att, uint8_t *pdu,
612                                         ssize_t pdu_len, uint8_t *opcode)
613 {
614         const struct bt_att_pdu_error_rsp *rsp;
615         struct att_send_op *op = att->pending_req;
616
617         if (pdu_len != sizeof(*rsp)) {
618                 *opcode = 0;
619                 return false;
620         }
621
622         rsp = (void *) pdu;
623
624         *opcode = rsp->opcode;
625
626         /* Attempt to change security */
627         if (!change_security(att, rsp->ecode))
628                 return false;
629
630         util_debug(att->debug_callback, att->debug_data,
631                                                 "Retrying operation %p", op);
632
633         att->pending_req = NULL;
634
635 #ifdef __TIZEN_PATCH__
636         if (op->timeout_id) {
637                 timeout_remove(op->timeout_id);
638                 op->timeout_id = 0;
639         }
640 #endif
641
642         /* Push operation back to request queue */
643         return queue_push_head(att->req_queue, op);
644 }
645
646 static void handle_rsp(struct bt_att *att, uint8_t opcode, uint8_t *pdu,
647                                                                 ssize_t pdu_len)
648 {
649         struct att_send_op *op = att->pending_req;
650         uint8_t req_opcode;
651         uint8_t rsp_opcode;
652         uint8_t *rsp_pdu = NULL;
653         uint16_t rsp_pdu_len = 0;
654
655         /*
656          * If no request is pending, then the response is unexpected. Disconnect
657          * the bearer.
658          */
659         if (!op) {
660                 util_debug(att->debug_callback, att->debug_data,
661                                         "Received unexpected ATT response");
662                 io_shutdown(att->io);
663                 return;
664         }
665
666         /*
667          * If the received response doesn't match the pending request, or if
668          * the request is malformed, end the current request with failure.
669          */
670         if (opcode == BT_ATT_OP_ERROR_RSP) {
671                 /* Return if error response cause a retry */
672                 if (handle_error_rsp(att, pdu, pdu_len, &req_opcode)) {
673                         wakeup_writer(att);
674                         return;
675                 }
676         } else if (!(req_opcode = get_req_opcode(opcode)))
677                 goto fail;
678
679         if (req_opcode != op->opcode)
680                 goto fail;
681
682         rsp_opcode = opcode;
683
684         if (pdu_len > 0) {
685                 rsp_pdu = pdu;
686                 rsp_pdu_len = pdu_len;
687         }
688
689         goto done;
690
691 fail:
692         util_debug(att->debug_callback, att->debug_data,
693                         "Failed to handle response PDU; opcode: 0x%02x", opcode);
694
695         rsp_opcode = BT_ATT_OP_ERROR_RSP;
696
697 done:
698         if (op->callback)
699                 op->callback(rsp_opcode, rsp_pdu, rsp_pdu_len, op->user_data);
700
701         destroy_att_send_op(op);
702         att->pending_req = NULL;
703
704         wakeup_writer(att);
705 }
706
707 static void handle_conf(struct bt_att *att, uint8_t *pdu, ssize_t pdu_len)
708 {
709         struct att_send_op *op = att->pending_ind;
710
711         /*
712          * Disconnect the bearer if the confirmation is unexpected or the PDU is
713          * invalid.
714          */
715         if (!op || pdu_len) {
716                 util_debug(att->debug_callback, att->debug_data,
717                                 "Received unexpected/invalid ATT confirmation");
718                 io_shutdown(att->io);
719                 return;
720         }
721
722         if (op->callback)
723                 op->callback(BT_ATT_OP_HANDLE_VAL_CONF, NULL, 0, op->user_data);
724
725         destroy_att_send_op(op);
726         att->pending_ind = NULL;
727
728         wakeup_writer(att);
729 }
730
731 struct notify_data {
732         uint8_t opcode;
733         uint8_t *pdu;
734         ssize_t pdu_len;
735         bool handler_found;
736 };
737
738 static bool opcode_match(uint8_t opcode, uint8_t test_opcode)
739 {
740         enum att_op_type op_type = get_op_type(test_opcode);
741
742         if (opcode == BT_ATT_ALL_REQUESTS && (op_type == ATT_OP_TYPE_REQ ||
743                                                 op_type == ATT_OP_TYPE_CMD))
744                 return true;
745
746         return opcode == test_opcode;
747 }
748
749 static void respond_not_supported(struct bt_att *att, uint8_t opcode)
750 {
751         struct bt_att_pdu_error_rsp pdu;
752
753         pdu.opcode = opcode;
754         pdu.handle = 0x0000;
755         pdu.ecode = BT_ATT_ERROR_REQUEST_NOT_SUPPORTED;
756
757         bt_att_send(att, BT_ATT_OP_ERROR_RSP, &pdu, sizeof(pdu), NULL, NULL,
758                                                                         NULL);
759 }
760
761 static bool handle_signed(struct bt_att *att, uint8_t opcode, uint8_t *pdu,
762                                                                 ssize_t pdu_len)
763 {
764         uint8_t *signature;
765         uint32_t sign_cnt;
766         struct sign_info *sign;
767
768         /* Check if there is enough data for a signature */
769         if (pdu_len < 2 + BT_ATT_SIGNATURE_LEN)
770                 goto fail;
771
772         sign = att->remote_sign;
773         if (!sign)
774                 goto fail;
775
776         signature = pdu + (pdu_len - BT_ATT_SIGNATURE_LEN);
777         sign_cnt = get_le32(signature);
778
779         /* Validate counter */
780         if (!sign->counter(&sign_cnt, sign->user_data))
781                 goto fail;
782
783         /* Generate signature and verify it */
784         if (!bt_crypto_sign_att(att->crypto, sign->key, pdu,
785                                 pdu_len - BT_ATT_SIGNATURE_LEN, sign_cnt,
786                                 signature))
787                 goto fail;
788
789         return true;
790
791 fail:
792         util_debug(att->debug_callback, att->debug_data,
793                         "ATT failed to verify signature: 0x%02x", opcode);
794
795         return false;
796 }
797
798 static void handle_notify(struct bt_att *att, uint8_t opcode, uint8_t *pdu,
799                                                                 ssize_t pdu_len)
800 {
801         const struct queue_entry *entry;
802         bool found;
803
804         if ((opcode & ATT_OP_SIGNED_MASK) && !att->crypto) {
805                 if (!handle_signed(att, opcode, pdu, pdu_len))
806                         return;
807                 pdu_len -= BT_ATT_SIGNATURE_LEN;
808         }
809
810         bt_att_ref(att);
811
812         found = false;
813         entry = queue_get_entries(att->notify_list);
814
815         while (entry) {
816                 struct att_notify *notify = entry->data;
817
818                 entry = entry->next;
819
820                 if (!opcode_match(notify->opcode, opcode))
821                         continue;
822
823                 found = true;
824
825                 if (notify->callback)
826                         notify->callback(opcode, pdu, pdu_len,
827                                                         notify->user_data);
828
829                 /* callback could remove all entries from notify list */
830                 if (queue_isempty(att->notify_list))
831                         break;
832         }
833
834         /*
835          * If this was a request and no handler was registered for it, respond
836          * with "Not Supported"
837          */
838         if (!found && get_op_type(opcode) == ATT_OP_TYPE_REQ)
839                 respond_not_supported(att, opcode);
840
841         bt_att_unref(att);
842 }
843
844 static bool can_read_data(struct io *io, void *user_data)
845 {
846         struct bt_att *att = user_data;
847         uint8_t opcode;
848         uint8_t *pdu;
849         ssize_t bytes_read;
850
851         bytes_read = read(att->fd, att->buf, att->mtu);
852         if (bytes_read < 0)
853                 return false;
854
855         util_hexdump('>', att->buf, bytes_read,
856                                         att->debug_callback, att->debug_data);
857
858         if (bytes_read < ATT_MIN_PDU_LEN)
859                 return true;
860
861         pdu = att->buf;
862         opcode = pdu[0];
863
864         bt_att_ref(att);
865
866         /* Act on the received PDU based on the opcode type */
867         switch (get_op_type(opcode)) {
868         case ATT_OP_TYPE_RSP:
869                 util_debug(att->debug_callback, att->debug_data,
870                                 "ATT response received: 0x%02x", opcode);
871                 handle_rsp(att, opcode, pdu + 1, bytes_read - 1);
872                 break;
873         case ATT_OP_TYPE_CONF:
874                 util_debug(att->debug_callback, att->debug_data,
875                                 "ATT confirmation received: 0x%02x", opcode);
876                 handle_conf(att, pdu + 1, bytes_read - 1);
877                 break;
878         case ATT_OP_TYPE_REQ:
879                 /*
880                  * If a request is currently pending, then the sequential
881                  * protocol was violated. Disconnect the bearer, which will
882                  * promptly notify the upper layer via disconnect handlers.
883                  */
884                 if (att->in_req) {
885                         util_debug(att->debug_callback, att->debug_data,
886                                         "Received request while another is "
887                                         "pending: 0x%02x", opcode);
888                         io_shutdown(att->io);
889                         bt_att_unref(att);
890
891                         return false;
892                 }
893
894                 att->in_req = true;
895
896                 /* Fall through to the next case */
897         case ATT_OP_TYPE_CMD:
898         case ATT_OP_TYPE_NOT:
899         case ATT_OP_TYPE_UNKNOWN:
900         case ATT_OP_TYPE_IND:
901         default:
902                 /* For all other opcodes notify the upper layer of the PDU and
903                  * let them act on it.
904                  */
905                 util_debug(att->debug_callback, att->debug_data,
906                                         "ATT PDU received: 0x%02x", opcode);
907                 handle_notify(att, opcode, pdu + 1, bytes_read - 1);
908                 break;
909         }
910
911         bt_att_unref(att);
912
913         return true;
914 }
915
916 static bool is_io_l2cap_based(int fd)
917 {
918         int domain;
919         int proto;
920         int err;
921         socklen_t len;
922
923         domain = 0;
924         len = sizeof(domain);
925         err = getsockopt(fd, SOL_SOCKET, SO_DOMAIN, &domain, &len);
926         if (err < 0)
927                 return false;
928
929         if (domain != AF_BLUETOOTH)
930                 return false;
931
932         proto = 0;
933         len = sizeof(proto);
934         err = getsockopt(fd, SOL_SOCKET, SO_PROTOCOL, &proto, &len);
935         if (err < 0)
936                 return false;
937
938         return proto == BTPROTO_L2CAP;
939 }
940
941 static void bt_att_free(struct bt_att *att)
942 {
943         if (att->pending_req)
944                 destroy_att_send_op(att->pending_req);
945
946         if (att->pending_ind)
947                 destroy_att_send_op(att->pending_ind);
948
949         io_destroy(att->io);
950         bt_crypto_unref(att->crypto);
951
952         queue_destroy(att->req_queue, NULL);
953         queue_destroy(att->ind_queue, NULL);
954         queue_destroy(att->write_queue, NULL);
955         queue_destroy(att->notify_list, NULL);
956         queue_destroy(att->disconn_list, NULL);
957
958         if (att->timeout_destroy)
959                 att->timeout_destroy(att->timeout_data);
960
961         if (att->debug_destroy)
962                 att->debug_destroy(att->debug_data);
963
964         free(att->local_sign);
965         free(att->remote_sign);
966
967         free(att->buf);
968
969         free(att);
970 }
971
972 struct bt_att *bt_att_new(int fd, bool ext_signed)
973 {
974         struct bt_att *att;
975
976         if (fd < 0)
977                 return NULL;
978
979         att = new0(struct bt_att, 1);
980         att->fd = fd;
981         att->mtu = BT_ATT_DEFAULT_LE_MTU;
982         att->buf = malloc(att->mtu);
983         if (!att->buf)
984                 goto fail;
985
986         att->io = io_new(fd);
987         if (!att->io)
988                 goto fail;
989
990         /* crypto is optional, if not available leave it NULL */
991         if (!ext_signed)
992                 att->crypto = bt_crypto_new();
993
994         att->req_queue = queue_new();
995         att->ind_queue = queue_new();
996         att->write_queue = queue_new();
997         att->notify_list = queue_new();
998         att->disconn_list = queue_new();
999
1000         if (!io_set_read_handler(att->io, can_read_data, att, NULL))
1001                 goto fail;
1002
1003         if (!io_set_disconnect_handler(att->io, disconnect_cb, att, NULL))
1004                 goto fail;
1005
1006         att->io_on_l2cap = is_io_l2cap_based(att->fd);
1007         if (!att->io_on_l2cap)
1008                 att->io_sec_level = BT_SECURITY_LOW;
1009
1010         return bt_att_ref(att);
1011
1012 fail:
1013         bt_att_free(att);
1014
1015         return NULL;
1016 }
1017
1018 struct bt_att *bt_att_ref(struct bt_att *att)
1019 {
1020         if (!att)
1021                 return NULL;
1022
1023         __sync_fetch_and_add(&att->ref_count, 1);
1024
1025         return att;
1026 }
1027
1028 void bt_att_unref(struct bt_att *att)
1029 {
1030         if (!att)
1031                 return;
1032
1033         if (__sync_sub_and_fetch(&att->ref_count, 1))
1034                 return;
1035
1036         bt_att_unregister_all(att);
1037         bt_att_cancel_all(att);
1038
1039         bt_att_free(att);
1040 }
1041
1042 bool bt_att_set_close_on_unref(struct bt_att *att, bool do_close)
1043 {
1044         if (!att || !att->io)
1045                 return false;
1046
1047         return io_set_close_on_destroy(att->io, do_close);
1048 }
1049
1050 int bt_att_get_fd(struct bt_att *att)
1051 {
1052         if (!att)
1053                 return -1;
1054
1055         return att->fd;
1056 }
1057
1058 bool bt_att_set_debug(struct bt_att *att, bt_att_debug_func_t callback,
1059                                 void *user_data, bt_att_destroy_func_t destroy)
1060 {
1061         if (!att)
1062                 return false;
1063
1064         if (att->debug_destroy)
1065                 att->debug_destroy(att->debug_data);
1066
1067         att->debug_callback = callback;
1068         att->debug_destroy = destroy;
1069         att->debug_data = user_data;
1070
1071         return true;
1072 }
1073
1074 uint16_t bt_att_get_mtu(struct bt_att *att)
1075 {
1076         if (!att)
1077                 return 0;
1078
1079         return att->mtu;
1080 }
1081
1082 bool bt_att_set_mtu(struct bt_att *att, uint16_t mtu)
1083 {
1084         void *buf;
1085
1086         if (!att)
1087                 return false;
1088
1089         if (mtu < BT_ATT_DEFAULT_LE_MTU)
1090                 return false;
1091
1092         buf = malloc(mtu);
1093         if (!buf)
1094                 return false;
1095
1096         free(att->buf);
1097
1098         att->mtu = mtu;
1099         att->buf = buf;
1100
1101         return true;
1102 }
1103
1104 bool bt_att_set_timeout_cb(struct bt_att *att, bt_att_timeout_func_t callback,
1105                                                 void *user_data,
1106                                                 bt_att_destroy_func_t destroy)
1107 {
1108         if (!att)
1109                 return false;
1110
1111         if (att->timeout_destroy)
1112                 att->timeout_destroy(att->timeout_data);
1113
1114         att->timeout_callback = callback;
1115         att->timeout_destroy = destroy;
1116         att->timeout_data = user_data;
1117
1118         return true;
1119 }
1120
1121 unsigned int bt_att_register_disconnect(struct bt_att *att,
1122                                         bt_att_disconnect_func_t callback,
1123                                         void *user_data,
1124                                         bt_att_destroy_func_t destroy)
1125 {
1126         struct att_disconn *disconn;
1127
1128         if (!att || !att->io)
1129                 return 0;
1130
1131         disconn = new0(struct att_disconn, 1);
1132         disconn->callback = callback;
1133         disconn->destroy = destroy;
1134         disconn->user_data = user_data;
1135
1136         if (att->next_reg_id < 1)
1137                 att->next_reg_id = 1;
1138
1139         disconn->id = att->next_reg_id++;
1140
1141         if (!queue_push_tail(att->disconn_list, disconn)) {
1142                 free(disconn);
1143                 return 0;
1144         }
1145
1146         return disconn->id;
1147 }
1148
1149 bool bt_att_unregister_disconnect(struct bt_att *att, unsigned int id)
1150 {
1151         struct att_disconn *disconn;
1152
1153         if (!att || !id)
1154                 return false;
1155
1156         disconn = queue_remove_if(att->disconn_list, match_disconn_id,
1157                                                         UINT_TO_PTR(id));
1158         if (!disconn)
1159                 return false;
1160
1161         destroy_att_disconn(disconn);
1162         return true;
1163 }
1164
1165 unsigned int bt_att_send(struct bt_att *att, uint8_t opcode,
1166                                 const void *pdu, uint16_t length,
1167                                 bt_att_response_func_t callback, void *user_data,
1168                                 bt_att_destroy_func_t destroy)
1169 {
1170         struct att_send_op *op;
1171         bool result;
1172
1173         if (!att || !att->io)
1174                 return 0;
1175
1176         op = create_att_send_op(att, opcode, pdu, length, callback, user_data,
1177                                                                 destroy);
1178         if (!op)
1179                 return 0;
1180
1181         if (att->next_send_id < 1)
1182                 att->next_send_id = 1;
1183
1184         op->id = att->next_send_id++;
1185
1186         /* Add the op to the correct queue based on its type */
1187         switch (op->type) {
1188         case ATT_OP_TYPE_REQ:
1189                 result = queue_push_tail(att->req_queue, op);
1190                 break;
1191         case ATT_OP_TYPE_IND:
1192                 result = queue_push_tail(att->ind_queue, op);
1193                 break;
1194         case ATT_OP_TYPE_CMD:
1195         case ATT_OP_TYPE_NOT:
1196         case ATT_OP_TYPE_UNKNOWN:
1197         case ATT_OP_TYPE_RSP:
1198         case ATT_OP_TYPE_CONF:
1199         default:
1200                 result = queue_push_tail(att->write_queue, op);
1201                 break;
1202         }
1203
1204         if (!result) {
1205                 free(op->pdu);
1206                 free(op);
1207                 return 0;
1208         }
1209
1210         wakeup_writer(att);
1211
1212         return op->id;
1213 }
1214
1215 static bool match_op_id(const void *a, const void *b)
1216 {
1217         const struct att_send_op *op = a;
1218         unsigned int id = PTR_TO_UINT(b);
1219
1220         return op->id == id;
1221 }
1222
1223 bool bt_att_cancel(struct bt_att *att, unsigned int id)
1224 {
1225         struct att_send_op *op;
1226
1227         if (!att || !id)
1228                 return false;
1229
1230         if (att->pending_req && att->pending_req->id == id) {
1231                 /* Don't cancel the pending request; remove it's handlers */
1232                 cancel_att_send_op(att->pending_req);
1233                 return true;
1234         }
1235
1236         if (att->pending_ind && att->pending_ind->id == id) {
1237                 /* Don't cancel the pending indication; remove it's handlers */
1238                 cancel_att_send_op(att->pending_ind);
1239                 return true;
1240         }
1241
1242         op = queue_remove_if(att->req_queue, match_op_id, UINT_TO_PTR(id));
1243         if (op)
1244                 goto done;
1245
1246         op = queue_remove_if(att->ind_queue, match_op_id, UINT_TO_PTR(id));
1247         if (op)
1248                 goto done;
1249
1250         op = queue_remove_if(att->write_queue, match_op_id, UINT_TO_PTR(id));
1251         if (op)
1252                 goto done;
1253
1254         if (!op)
1255                 return false;
1256
1257 done:
1258         destroy_att_send_op(op);
1259
1260         wakeup_writer(att);
1261
1262         return true;
1263 }
1264
1265 bool bt_att_cancel_all(struct bt_att *att)
1266 {
1267         if (!att)
1268                 return false;
1269
1270         queue_remove_all(att->req_queue, NULL, NULL, destroy_att_send_op);
1271         queue_remove_all(att->ind_queue, NULL, NULL, destroy_att_send_op);
1272         queue_remove_all(att->write_queue, NULL, NULL, destroy_att_send_op);
1273
1274         if (att->pending_req)
1275                 /* Don't cancel the pending request; remove it's handlers */
1276                 cancel_att_send_op(att->pending_req);
1277
1278         if (att->pending_ind)
1279                 /* Don't cancel the pending request; remove it's handlers */
1280                 cancel_att_send_op(att->pending_ind);
1281
1282         return true;
1283 }
1284
1285 static uint8_t att_ecode_from_error(int err)
1286 {
1287         /*
1288          * If the error fits in a single byte, treat it as an ATT protocol
1289          * error as is. Since "0" is not a valid ATT protocol error code, we map
1290          * that to UNLIKELY below.
1291          */
1292         if (err > 0 && err < UINT8_MAX)
1293                 return err;
1294
1295         /*
1296          * Since we allow UNIX errnos, map them to appropriate ATT protocol
1297          * and "Common Profile and Service" error codes.
1298          */
1299         switch (err) {
1300         case -ENOENT:
1301                 return BT_ATT_ERROR_INVALID_HANDLE;
1302         case -ENOMEM:
1303                 return BT_ATT_ERROR_INSUFFICIENT_RESOURCES;
1304         case -EALREADY:
1305                 return BT_ERROR_ALREADY_IN_PROGRESS;
1306         case -EOVERFLOW:
1307                 return BT_ERROR_OUT_OF_RANGE;
1308         }
1309
1310         return BT_ATT_ERROR_UNLIKELY;
1311 }
1312
1313 unsigned int bt_att_send_error_rsp(struct bt_att *att, uint8_t opcode,
1314                                                 uint16_t handle, int error)
1315 {
1316         struct bt_att_pdu_error_rsp pdu;
1317         uint8_t ecode;
1318
1319         if (!att || !opcode)
1320                 return 0;
1321
1322         ecode = att_ecode_from_error(error);
1323
1324         memset(&pdu, 0, sizeof(pdu));
1325
1326         pdu.opcode = opcode;
1327         put_le16(handle, &pdu.handle);
1328         pdu.ecode = ecode;
1329
1330         return bt_att_send(att, BT_ATT_OP_ERROR_RSP, &pdu, sizeof(pdu),
1331                                                         NULL, NULL, NULL);
1332 }
1333
1334 unsigned int bt_att_register(struct bt_att *att, uint8_t opcode,
1335                                                 bt_att_notify_func_t callback,
1336                                                 void *user_data,
1337                                                 bt_att_destroy_func_t destroy)
1338 {
1339         struct att_notify *notify;
1340
1341         if (!att || !callback || !att->io)
1342                 return 0;
1343
1344         notify = new0(struct att_notify, 1);
1345         notify->opcode = opcode;
1346         notify->callback = callback;
1347         notify->destroy = destroy;
1348         notify->user_data = user_data;
1349
1350         if (att->next_reg_id < 1)
1351                 att->next_reg_id = 1;
1352
1353         notify->id = att->next_reg_id++;
1354
1355         if (!queue_push_tail(att->notify_list, notify)) {
1356                 free(notify);
1357                 return 0;
1358         }
1359
1360         return notify->id;
1361 }
1362
1363 bool bt_att_unregister(struct bt_att *att, unsigned int id)
1364 {
1365         struct att_notify *notify;
1366
1367         if (!att || !id)
1368                 return false;
1369
1370         notify = queue_remove_if(att->notify_list, match_notify_id,
1371                                                         UINT_TO_PTR(id));
1372         if (!notify)
1373                 return false;
1374
1375         destroy_att_notify(notify);
1376         return true;
1377 }
1378
1379 bool bt_att_unregister_all(struct bt_att *att)
1380 {
1381         if (!att)
1382                 return false;
1383
1384         queue_remove_all(att->notify_list, NULL, NULL, destroy_att_notify);
1385         queue_remove_all(att->disconn_list, NULL, NULL, destroy_att_disconn);
1386
1387         return true;
1388 }
1389
1390 int bt_att_get_security(struct bt_att *att)
1391 {
1392         struct bt_security sec;
1393         socklen_t len;
1394
1395         if (!att)
1396                 return -EINVAL;
1397
1398         if (!att->io_on_l2cap)
1399                 return att->io_sec_level;
1400
1401         memset(&sec, 0, sizeof(sec));
1402         len = sizeof(sec);
1403         if (getsockopt(att->fd, SOL_BLUETOOTH, BT_SECURITY, &sec, &len) < 0)
1404                 return -EIO;
1405
1406         return sec.level;
1407 }
1408
1409 bool bt_att_set_security(struct bt_att *att, int level)
1410 {
1411         struct bt_security sec;
1412
1413         if (!att || level < BT_ATT_SECURITY_AUTO ||
1414                                                 level > BT_ATT_SECURITY_HIGH)
1415                 return false;
1416
1417         if (!att->io_on_l2cap) {
1418                 att->io_sec_level = level;
1419                 return true;
1420         }
1421
1422         memset(&sec, 0, sizeof(sec));
1423         sec.level = level;
1424
1425         if (setsockopt(att->fd, SOL_BLUETOOTH, BT_SECURITY, &sec,
1426                                                         sizeof(sec)) < 0)
1427                 return false;
1428
1429         return true;
1430 }
1431
1432 static bool sign_set_key(struct sign_info **sign, uint8_t key[16],
1433                                 bt_att_counter_func_t func, void *user_data)
1434 {
1435         if (!(*sign))
1436                 *sign = new0(struct sign_info, 1);
1437
1438         (*sign)->counter = func;
1439         (*sign)->user_data = user_data;
1440         memcpy((*sign)->key, key, 16);
1441
1442         return true;
1443 }
1444
1445 bool bt_att_set_local_key(struct bt_att *att, uint8_t sign_key[16],
1446                                 bt_att_counter_func_t func, void *user_data)
1447 {
1448         if (!att)
1449                 return false;
1450
1451         return sign_set_key(&att->local_sign, sign_key, func, user_data);
1452 }
1453
1454 bool bt_att_set_remote_key(struct bt_att *att, uint8_t sign_key[16],
1455                                 bt_att_counter_func_t func, void *user_data)
1456 {
1457         if (!att)
1458                 return false;
1459
1460         return sign_set_key(&att->remote_sign, sign_key, func, user_data);
1461 }
1462
1463 bool bt_att_has_crypto(struct bt_att *att)
1464 {
1465         if (!att)
1466                 return false;
1467
1468         return att->crypto ? true : false;
1469 }