229897d2c39c4ad0a3a9b906cd65dfbbf84e433e
[platform/upstream/bluez.git] / src / shared / att.c
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 /*
3  *
4  *  BlueZ - Bluetooth protocol stack for Linux
5  *
6  *  Copyright (C) 2014  Google Inc.
7  *
8  *
9  */
10
11 #ifdef HAVE_CONFIG_H
12 #include <config.h>
13 #endif
14
15 #include <stdlib.h>
16 #include <unistd.h>
17 #include <errno.h>
18
19 #include "src/shared/io.h"
20 #include "src/shared/queue.h"
21 #include "src/shared/util.h"
22 #include "src/shared/timeout.h"
23 #include "lib/bluetooth.h"
24 #include "lib/l2cap.h"
25 #include "lib/uuid.h"
26 #include "src/shared/att.h"
27 #include "src/shared/crypto.h"
28
29 #define ATT_MIN_PDU_LEN                 1  /* At least 1 byte for the opcode. */
30 #define ATT_OP_CMD_MASK                 0x40
31 #define ATT_OP_SIGNED_MASK              0x80
32 #define ATT_TIMEOUT_INTERVAL            30000  /* 30000 ms */
33
34 /* Length of signature in write signed packet */
35 #define BT_ATT_SIGNATURE_LEN            12
36
37 struct att_send_op;
38
39 struct bt_att_chan {
40         struct bt_att *att;
41         int fd;
42         struct io *io;
43         uint8_t type;
44         int sec_level;                  /* Only used for non-L2CAP */
45
46         struct queue *queue;            /* Channel dedicated queue */
47
48         struct att_send_op *pending_req;
49         struct att_send_op *pending_ind;
50         bool writer_active;
51
52         bool in_req;                    /* There's a pending incoming request */
53
54         uint8_t *buf;
55         uint16_t mtu;
56 };
57
58 struct bt_att {
59         int ref_count;
60         bool close_on_unref;
61         struct queue *chans;
62         uint8_t enc_size;
63         uint16_t mtu;                   /* Biggest possible MTU */
64
65         struct queue *notify_list;      /* List of registered callbacks */
66         struct queue *disconn_list;     /* List of disconnect handlers */
67         struct queue *exchange_list;    /* List of MTU changed handlers */
68
69         unsigned int next_send_id;      /* IDs for "send" ops */
70         unsigned int next_reg_id;       /* IDs for registered callbacks */
71
72         struct queue *req_queue;        /* Queued ATT protocol requests */
73         struct queue *ind_queue;        /* Queued ATT protocol indications */
74         struct queue *write_queue;      /* Queue of PDUs ready to send */
75         bool in_disc;                   /* Cleanup queues on disconnect_cb */
76         bt_att_timeout_func_t timeout_callback;
77         bt_att_destroy_func_t timeout_destroy;
78         void *timeout_data;
79
80         uint8_t debug_level;
81         bt_att_debug_func_t debug_callback;
82         bt_att_destroy_func_t debug_destroy;
83
84 #ifdef TIZEN_FEATURE_BLUEZ_MODIFY
85         bdaddr_t bdaddr;
86         uint8_t bdaddr_type;
87         bool service_change_indication; /* Service changed indication status */
88 #endif
89
90         void *debug_data;
91
92         struct bt_crypto *crypto;
93
94         struct sign_info *local_sign;
95         struct sign_info *remote_sign;
96 };
97
98 struct sign_info {
99         uint8_t key[16];
100         bt_att_counter_func_t counter;
101         void *user_data;
102 };
103
104 enum att_op_type {
105         ATT_OP_TYPE_REQ,
106         ATT_OP_TYPE_RSP,
107         ATT_OP_TYPE_CMD,
108         ATT_OP_TYPE_IND,
109         ATT_OP_TYPE_NFY,
110         ATT_OP_TYPE_CONF,
111         ATT_OP_TYPE_UNKNOWN,
112 };
113
114 static const struct {
115         uint8_t opcode;
116         enum att_op_type type;
117 } att_opcode_type_table[] = {
118         { BT_ATT_OP_ERROR_RSP,                  ATT_OP_TYPE_RSP },
119         { BT_ATT_OP_MTU_REQ,                    ATT_OP_TYPE_REQ },
120         { BT_ATT_OP_MTU_RSP,                    ATT_OP_TYPE_RSP },
121         { BT_ATT_OP_FIND_INFO_REQ,              ATT_OP_TYPE_REQ },
122         { BT_ATT_OP_FIND_INFO_RSP,              ATT_OP_TYPE_RSP },
123         { BT_ATT_OP_FIND_BY_TYPE_REQ,           ATT_OP_TYPE_REQ },
124         { BT_ATT_OP_FIND_BY_TYPE_RSP,           ATT_OP_TYPE_RSP },
125         { BT_ATT_OP_READ_BY_TYPE_REQ,           ATT_OP_TYPE_REQ },
126         { BT_ATT_OP_READ_BY_TYPE_RSP,           ATT_OP_TYPE_RSP },
127         { BT_ATT_OP_READ_REQ,                   ATT_OP_TYPE_REQ },
128         { BT_ATT_OP_READ_RSP,                   ATT_OP_TYPE_RSP },
129         { BT_ATT_OP_READ_BLOB_REQ,              ATT_OP_TYPE_REQ },
130         { BT_ATT_OP_READ_BLOB_RSP,              ATT_OP_TYPE_RSP },
131         { BT_ATT_OP_READ_MULT_REQ,              ATT_OP_TYPE_REQ },
132         { BT_ATT_OP_READ_MULT_RSP,              ATT_OP_TYPE_RSP },
133         { BT_ATT_OP_READ_BY_GRP_TYPE_REQ,       ATT_OP_TYPE_REQ },
134         { BT_ATT_OP_READ_BY_GRP_TYPE_RSP,       ATT_OP_TYPE_RSP },
135         { BT_ATT_OP_WRITE_REQ,                  ATT_OP_TYPE_REQ },
136         { BT_ATT_OP_WRITE_RSP,                  ATT_OP_TYPE_RSP },
137         { BT_ATT_OP_WRITE_CMD,                  ATT_OP_TYPE_CMD },
138         { BT_ATT_OP_SIGNED_WRITE_CMD,           ATT_OP_TYPE_CMD },
139         { BT_ATT_OP_PREP_WRITE_REQ,             ATT_OP_TYPE_REQ },
140         { BT_ATT_OP_PREP_WRITE_RSP,             ATT_OP_TYPE_RSP },
141         { BT_ATT_OP_EXEC_WRITE_REQ,             ATT_OP_TYPE_REQ },
142         { BT_ATT_OP_EXEC_WRITE_RSP,             ATT_OP_TYPE_RSP },
143         { BT_ATT_OP_HANDLE_NFY,                 ATT_OP_TYPE_NFY },
144         { BT_ATT_OP_HANDLE_NFY_MULT,            ATT_OP_TYPE_NFY },
145         { BT_ATT_OP_HANDLE_IND,                 ATT_OP_TYPE_IND },
146         { BT_ATT_OP_HANDLE_CONF,                ATT_OP_TYPE_CONF },
147         { }
148 };
149
150 static enum att_op_type get_op_type(uint8_t opcode)
151 {
152         int i;
153
154         for (i = 0; att_opcode_type_table[i].opcode; i++) {
155                 if (att_opcode_type_table[i].opcode == opcode)
156                         return att_opcode_type_table[i].type;
157         }
158
159         if (opcode & ATT_OP_CMD_MASK)
160                 return ATT_OP_TYPE_CMD;
161
162         return ATT_OP_TYPE_UNKNOWN;
163 }
164
165 static const struct {
166         uint8_t req_opcode;
167         uint8_t rsp_opcode;
168 } att_req_rsp_mapping_table[] = {
169         { BT_ATT_OP_MTU_REQ,                    BT_ATT_OP_MTU_RSP },
170         { BT_ATT_OP_FIND_INFO_REQ,              BT_ATT_OP_FIND_INFO_RSP},
171         { BT_ATT_OP_FIND_BY_TYPE_REQ,           BT_ATT_OP_FIND_BY_TYPE_RSP },
172         { BT_ATT_OP_READ_BY_TYPE_REQ,           BT_ATT_OP_READ_BY_TYPE_RSP },
173         { BT_ATT_OP_READ_REQ,                   BT_ATT_OP_READ_RSP },
174         { BT_ATT_OP_READ_BLOB_REQ,              BT_ATT_OP_READ_BLOB_RSP },
175         { BT_ATT_OP_READ_MULT_REQ,              BT_ATT_OP_READ_MULT_RSP },
176         { BT_ATT_OP_READ_BY_GRP_TYPE_REQ,       BT_ATT_OP_READ_BY_GRP_TYPE_RSP },
177         { BT_ATT_OP_WRITE_REQ,                  BT_ATT_OP_WRITE_RSP },
178         { BT_ATT_OP_PREP_WRITE_REQ,             BT_ATT_OP_PREP_WRITE_RSP },
179         { BT_ATT_OP_EXEC_WRITE_REQ,             BT_ATT_OP_EXEC_WRITE_RSP },
180         { }
181 };
182
183 static uint8_t get_req_opcode(uint8_t rsp_opcode)
184 {
185         int i;
186
187         for (i = 0; att_req_rsp_mapping_table[i].rsp_opcode; i++) {
188                 if (att_req_rsp_mapping_table[i].rsp_opcode == rsp_opcode)
189                         return att_req_rsp_mapping_table[i].req_opcode;
190         }
191
192         return 0;
193 }
194
195 struct att_send_op {
196         unsigned int id;
197         unsigned int timeout_id;
198         enum att_op_type type;
199         uint8_t opcode;
200         void *pdu;
201         uint16_t len;
202         bt_att_response_func_t callback;
203         bt_att_destroy_func_t destroy;
204         void *user_data;
205 };
206
207 static void destroy_att_send_op(void *data)
208 {
209         struct att_send_op *op = data;
210
211         if (op->timeout_id)
212                 timeout_remove(op->timeout_id);
213
214         if (op->destroy)
215                 op->destroy(op->user_data);
216
217         free(op->pdu);
218         free(op);
219 }
220
221 static void cancel_att_send_op(void *data)
222 {
223         struct att_send_op *op = data;
224
225         if (op->destroy)
226                 op->destroy(op->user_data);
227
228         op->user_data = NULL;
229         op->callback = NULL;
230         op->destroy = NULL;
231 }
232
233 struct att_notify {
234         unsigned int id;
235         uint16_t opcode;
236         bt_att_notify_func_t callback;
237         bt_att_destroy_func_t destroy;
238         void *user_data;
239 };
240
241 static void destroy_att_notify(void *data)
242 {
243         struct att_notify *notify = data;
244
245         if (notify->destroy)
246                 notify->destroy(notify->user_data);
247
248         free(notify);
249 }
250
251 static bool match_notify_id(const void *a, const void *b)
252 {
253         const struct att_notify *notify = a;
254         unsigned int id = PTR_TO_UINT(b);
255
256         return notify->id == id;
257 }
258
259 struct att_disconn {
260         unsigned int id;
261         bool removed;
262         bt_att_disconnect_func_t callback;
263         bt_att_destroy_func_t destroy;
264         void *user_data;
265 };
266
267 struct att_exchange {
268         unsigned int id;
269         bool removed;
270         bt_att_exchange_func_t callback;
271         bt_att_destroy_func_t destroy;
272         void *user_data;
273 };
274
275 static void destroy_att_disconn(void *data)
276 {
277         struct att_disconn *disconn = data;
278
279         if (disconn->destroy)
280                 disconn->destroy(disconn->user_data);
281
282         free(disconn);
283 }
284
285 static void destroy_att_exchange(void *data)
286 {
287         struct att_exchange *exchange = data;
288
289         if (exchange->destroy)
290                 exchange->destroy(exchange->user_data);
291
292         free(exchange);
293 }
294
295 static bool match_disconn_id(const void *a, const void *b)
296 {
297         const struct att_disconn *disconn = a;
298         unsigned int id = PTR_TO_UINT(b);
299
300         return disconn->id == id;
301 }
302
303 static void att_log(struct bt_att *att, uint8_t level, const char *format,
304                                                                 ...)
305 {
306         va_list va;
307
308         if (att->debug_level < level)
309                 return;
310         va_start(va, format);
311
312         util_debug_va(att->debug_callback, att->debug_data, format, va);
313         va_end(va);
314 }
315
316 #define att_debug(_att, _format, _arg...) \
317         att_log(_att, BT_ATT_DEBUG, _format, ## _arg)
318
319 #define att_verbose(_att, _format, _arg...) \
320         att_log(_att, BT_ATT_DEBUG_VERBOSE, _format, ## _arg)
321
322 static void att_hexdump(struct bt_att *att, char dir, const void *data,
323                                                         size_t len)
324 {
325         if (att->debug_level < 2)
326                 return;
327
328         util_hexdump(dir, data, len, att->debug_callback, att->debug_data);
329 }
330 static bool encode_pdu(struct bt_att *att, struct att_send_op *op,
331                                         const void *pdu, uint16_t length)
332 {
333         uint16_t pdu_len = 1;
334         struct sign_info *sign = att->local_sign;
335         uint32_t sign_cnt;
336
337         if (sign && (op->opcode & ATT_OP_SIGNED_MASK))
338                 pdu_len += BT_ATT_SIGNATURE_LEN;
339
340         if (length && pdu)
341                 pdu_len += length;
342
343         if (pdu_len > att->mtu)
344                 return false;
345
346         op->len = pdu_len;
347         op->pdu = malloc(op->len);
348         if (!op->pdu)
349                 return false;
350
351         ((uint8_t *) op->pdu)[0] = op->opcode;
352         if (pdu_len > 1)
353                 memcpy(op->pdu + 1, pdu, length);
354
355         if (!sign || !(op->opcode & ATT_OP_SIGNED_MASK) || !att->crypto)
356                 return true;
357
358         if (!sign->counter(&sign_cnt, sign->user_data))
359                 goto fail;
360
361         if ((bt_crypto_sign_att(att->crypto, sign->key, op->pdu, 1 + length,
362                                 sign_cnt, &((uint8_t *) op->pdu)[1 + length])))
363                 return true;
364
365         att_debug(att, "ATT unable to generate signature");
366
367 fail:
368         free(op->pdu);
369         return false;
370 }
371
372 static struct att_send_op *create_att_send_op(struct bt_att *att,
373                                                 uint8_t opcode,
374                                                 const void *pdu,
375                                                 uint16_t length,
376                                                 bt_att_response_func_t callback,
377                                                 void *user_data,
378                                                 bt_att_destroy_func_t destroy)
379 {
380         struct att_send_op *op;
381         enum att_op_type type;
382
383         if (length && !pdu)
384                 return NULL;
385
386         type = get_op_type(opcode);
387         if (type == ATT_OP_TYPE_UNKNOWN)
388                 return NULL;
389
390         /* If the opcode corresponds to an operation type that does not elicit a
391          * response from the remote end, then no callback should have been
392          * provided, since it will never be called.
393          */
394 #ifdef TIZEN_FEATURE_BLUEZ_MODIFY
395         if (callback && type != ATT_OP_TYPE_REQ && type != ATT_OP_TYPE_IND
396                      && type != ATT_OP_TYPE_CMD)
397                 return NULL;
398 #else
399         if (callback && type != ATT_OP_TYPE_REQ && type != ATT_OP_TYPE_IND)
400                 return NULL;
401 #endif
402
403         /* Similarly, if the operation does elicit a response then a callback
404          * must be provided.
405          */
406         if (!callback && (type == ATT_OP_TYPE_REQ || type == ATT_OP_TYPE_IND))
407                 return NULL;
408
409         op = new0(struct att_send_op, 1);
410         op->type = type;
411         op->opcode = opcode;
412         op->callback = callback;
413         op->destroy = destroy;
414         op->user_data = user_data;
415
416         if (!encode_pdu(att, op, pdu, length)) {
417                 free(op);
418                 return NULL;
419         }
420
421         return op;
422 }
423
424 static struct att_send_op *pick_next_send_op(struct bt_att_chan *chan)
425 {
426         struct bt_att *att = chan->att;
427         struct att_send_op *op;
428
429         /* Check if there is anything queued on the channel */
430         op = queue_pop_head(chan->queue);
431         if (op)
432                 return op;
433
434         /* See if any operations are already in the write queue */
435         op = queue_peek_head(att->write_queue);
436         if (op && op->len <= chan->mtu)
437                 return queue_pop_head(att->write_queue);
438
439         /* If there is no pending request, pick an operation from the
440          * request queue.
441          */
442         if (!chan->pending_req) {
443                 op = queue_peek_head(att->req_queue);
444                 if (op && op->len <= chan->mtu) {
445                         /* Don't send Exchange MTU over EATT */
446                         if (op->opcode == BT_ATT_OP_MTU_REQ &&
447                                         chan->type == BT_ATT_EATT)
448                                 goto indicate;
449
450                         return queue_pop_head(att->req_queue);
451                 }
452         }
453
454 indicate:
455         /* There is either a request pending or no requests queued. If there is
456          * no pending indication, pick an operation from the indication queue.
457          */
458         if (!chan->pending_ind) {
459                 op = queue_peek_head(att->ind_queue);
460                 if (op && op->len <= chan->mtu)
461                         return queue_pop_head(att->ind_queue);
462         }
463
464         return NULL;
465 }
466
467 static void disc_att_send_op(void *data)
468 {
469         struct att_send_op *op = data;
470
471         if (op->callback)
472                 op->callback(BT_ATT_OP_ERROR_RSP, NULL, 0, op->user_data);
473
474         destroy_att_send_op(op);
475 }
476
477 struct timeout_data {
478         struct bt_att_chan *chan;
479         unsigned int id;
480 };
481
482 static bool timeout_cb(void *user_data)
483 {
484         struct timeout_data *timeout = user_data;
485         struct bt_att_chan *chan = timeout->chan;
486         struct bt_att *att = chan->att;
487         struct att_send_op *op = NULL;
488
489         if (chan->pending_req && chan->pending_req->id == timeout->id) {
490                 op = chan->pending_req;
491                 chan->pending_req = NULL;
492         } else if (chan->pending_ind && chan->pending_ind->id == timeout->id) {
493                 op = chan->pending_ind;
494                 chan->pending_ind = NULL;
495         }
496
497         if (!op)
498                 return false;
499
500         att_debug(att, "(chan %p) Operation timed out: 0x%02x", chan,
501                                                 op->opcode);
502
503         if (att->timeout_callback)
504                 att->timeout_callback(op->id, op->opcode, att->timeout_data);
505
506         op->timeout_id = 0;
507         disc_att_send_op(op);
508
509         /*
510          * Directly terminate the connection as required by the ATT protocol.
511          * This should trigger an io disconnect event which will clean up the
512          * io and notify the upper layer.
513          */
514         io_shutdown(chan->io);
515
516         return false;
517 }
518
519 static void write_watch_destroy(void *user_data)
520 {
521         struct bt_att_chan *chan = user_data;
522
523         chan->writer_active = false;
524 }
525
526 static ssize_t bt_att_chan_write(struct bt_att_chan *chan, uint8_t opcode,
527                                         const void *pdu, uint16_t len)
528 {
529         struct bt_att *att = chan->att;
530         ssize_t ret;
531         struct iovec iov;
532
533         iov.iov_base = (void *) pdu;
534         iov.iov_len = len;
535
536         att_verbose(att, "(chan %p) ATT op 0x%02x", chan, opcode);
537
538         ret = io_send(chan->io, &iov, 1);
539         if (ret < 0) {
540
541                 att_debug(att, "(chan %p) write failed: %s", chan,
542                                                 strerror(-ret));
543                 return ret;
544         }
545
546         if (att->debug_level)
547                 util_hexdump('<', pdu, ret, att->debug_callback,
548                                                 att->debug_data);
549
550         return ret;
551 }
552
553 static bool can_write_data(struct io *io, void *user_data)
554 {
555         struct bt_att_chan *chan = user_data;
556         struct att_send_op *op;
557         struct timeout_data *timeout;
558
559         op = pick_next_send_op(chan);
560         if (!op)
561                 return false;
562
563         if (!bt_att_chan_write(chan, op->opcode, op->pdu, op->len)) {
564                 if (op->callback)
565                         op->callback(BT_ATT_OP_ERROR_RSP, NULL, 0,
566                                                         op->user_data);
567
568                 destroy_att_send_op(op);
569                 return true;
570         }
571
572
573         /* Based on the operation type, set either the pending request or the
574          * pending indication. If it came from the write queue, then there is
575          * no need to keep it around.
576          */
577         switch (op->type) {
578         case ATT_OP_TYPE_REQ:
579                 chan->pending_req = op;
580                 break;
581         case ATT_OP_TYPE_IND:
582                 chan->pending_ind = op;
583                 break;
584 #ifdef TIZEN_FEATURE_BLUEZ_MODIFY
585         case ATT_OP_TYPE_CMD:
586                 if (op->callback)
587                         op->callback(0, NULL, 0, op->user_data);
588                 destroy_att_send_op(op);
589                 return true;
590 #endif
591         case ATT_OP_TYPE_RSP:
592                 /* Set in_req to false to indicate that no request is pending */
593                 chan->in_req = false;
594
595                 /* fall through */
596 #ifndef TIZEN_FEATURE_BLUEZ_MODIFY
597         case ATT_OP_TYPE_CMD:
598 #endif
599         case ATT_OP_TYPE_NFY:
600         case ATT_OP_TYPE_CONF:
601         case ATT_OP_TYPE_UNKNOWN:
602         default:
603                 destroy_att_send_op(op);
604                 return true;
605         }
606
607         timeout = new0(struct timeout_data, 1);
608         timeout->chan = chan;
609         timeout->id = op->id;
610         op->timeout_id = timeout_add(ATT_TIMEOUT_INTERVAL, timeout_cb,
611                                                                 timeout, free);
612
613         /* Return true as there may be more operations ready to write. */
614         return true;
615 }
616
617 static void wakeup_chan_writer(void *data, void *user_data)
618 {
619         struct bt_att_chan *chan = data;
620         struct bt_att *att = chan->att;
621
622         if (chan->writer_active)
623                 return;
624
625         /* Set the write handler only if there is anything that can be sent
626          * at all.
627          */
628         if (queue_isempty(chan->queue) && queue_isempty(att->write_queue)) {
629                 if ((chan->pending_req || queue_isempty(att->req_queue)) &&
630                         (chan->pending_ind || queue_isempty(att->ind_queue)))
631                         return;
632         }
633
634         if (!io_set_write_handler(chan->io, can_write_data, chan,
635                                                         write_watch_destroy))
636                 return;
637
638         chan->writer_active = true;
639 }
640
641 static void wakeup_writer(struct bt_att *att)
642 {
643         queue_foreach(att->chans, wakeup_chan_writer, NULL);
644 }
645
646 static void disconn_handler(void *data, void *user_data)
647 {
648         struct att_disconn *disconn = data;
649         int err = PTR_TO_INT(user_data);
650
651         if (disconn->removed)
652                 return;
653
654         if (disconn->callback)
655                 disconn->callback(err, disconn->user_data);
656 }
657
658 static void bt_att_chan_free(void *data)
659 {
660         struct bt_att_chan *chan = data;
661
662         if (chan->pending_req)
663                 destroy_att_send_op(chan->pending_req);
664
665         if (chan->pending_ind)
666                 destroy_att_send_op(chan->pending_ind);
667
668         queue_destroy(chan->queue, destroy_att_send_op);
669
670         io_destroy(chan->io);
671
672         free(chan->buf);
673         free(chan);
674 }
675
676 static bool disconnect_cb(struct io *io, void *user_data)
677 {
678         struct bt_att_chan *chan = user_data;
679         struct bt_att *att = chan->att;
680         int err;
681         socklen_t len;
682
683         len = sizeof(err);
684
685         if (getsockopt(chan->fd, SOL_SOCKET, SO_ERROR, &err, &len) < 0) {
686                 att_debug(att, "(chan %p) Failed to obtain disconnect "
687                                 "error: %s", chan, strerror(errno));
688                 err = 0;
689         }
690
691         att_debug(att, "Channel %p disconnected: %s", chan, strerror(err));
692
693         /* Dettach channel */
694         queue_remove(att->chans, chan);
695
696         if (chan->pending_req) {
697                 disc_att_send_op(chan->pending_req);
698                 chan->pending_req = NULL;
699         }
700
701         if (chan->pending_ind) {
702                 disc_att_send_op(chan->pending_ind);
703                 chan->pending_ind = NULL;
704         }
705
706         bt_att_chan_free(chan);
707
708         /* Don't run disconnect callback if there are channels left */
709         if (!queue_isempty(att->chans))
710                 return false;
711
712         bt_att_ref(att);
713         att->in_disc = true;
714
715         /* Notify request callbacks */
716         queue_remove_all(att->req_queue, NULL, NULL, disc_att_send_op);
717         queue_remove_all(att->ind_queue, NULL, NULL, disc_att_send_op);
718         queue_remove_all(att->write_queue, NULL, NULL, disc_att_send_op);
719
720         att->in_disc = false;
721
722         queue_foreach(att->disconn_list, disconn_handler, INT_TO_PTR(err));
723
724         bt_att_unregister_all(att);
725         bt_att_unref(att);
726
727         return false;
728 }
729
730 static int bt_att_chan_get_security(struct bt_att_chan *chan)
731 {
732         struct bt_security sec;
733         socklen_t len;
734
735         if (chan->type == BT_ATT_LOCAL)
736                 return chan->sec_level;
737
738         memset(&sec, 0, sizeof(sec));
739         len = sizeof(sec);
740         if (getsockopt(chan->fd, SOL_BLUETOOTH, BT_SECURITY, &sec, &len) < 0)
741                 return -EIO;
742
743         return sec.level;
744 }
745
746 static bool bt_att_chan_set_security(struct bt_att_chan *chan, int level)
747 {
748         struct bt_security sec;
749
750         if (chan->type == BT_ATT_LOCAL) {
751                 chan->sec_level = level;
752                 return true;
753         }
754
755         memset(&sec, 0, sizeof(sec));
756         sec.level = level;
757
758         if (setsockopt(chan->fd, SOL_BLUETOOTH, BT_SECURITY, &sec,
759                                                         sizeof(sec)) < 0)
760                 return false;
761
762         return true;
763 }
764
765 static bool change_security(struct bt_att_chan *chan, uint8_t ecode)
766 {
767         int security;
768
769         if (chan->sec_level != BT_ATT_SECURITY_AUTO)
770                 return false;
771
772         security = bt_att_chan_get_security(chan);
773
774         if (ecode == BT_ATT_ERROR_INSUFFICIENT_ENCRYPTION &&
775                                         security < BT_ATT_SECURITY_MEDIUM) {
776                 security = BT_ATT_SECURITY_MEDIUM;
777         } else if (ecode == BT_ATT_ERROR_AUTHENTICATION) {
778                 if (security < BT_ATT_SECURITY_MEDIUM)
779                         security = BT_ATT_SECURITY_MEDIUM;
780                 else if (security < BT_ATT_SECURITY_HIGH)
781                         security = BT_ATT_SECURITY_HIGH;
782                 else if (security < BT_ATT_SECURITY_FIPS)
783                         security = BT_ATT_SECURITY_FIPS;
784                 else
785                         return false;
786         } else {
787                 return false;
788         }
789
790         return bt_att_chan_set_security(chan, security);
791 }
792
793 static bool handle_error_rsp(struct bt_att_chan *chan, uint8_t *pdu,
794                                         ssize_t pdu_len, uint8_t *opcode)
795 {
796         struct bt_att *att = chan->att;
797         const struct bt_att_pdu_error_rsp *rsp;
798         struct att_send_op *op = chan->pending_req;
799
800         if (pdu_len != sizeof(*rsp)) {
801                 *opcode = 0;
802                 return false;
803         }
804
805         rsp = (void *) pdu;
806
807         *opcode = rsp->opcode;
808
809         /* Attempt to change security */
810         if (!change_security(chan, rsp->ecode))
811                 return false;
812
813         /* Remove timeout_id if outstanding */
814         if (op->timeout_id) {
815                 timeout_remove(op->timeout_id);
816                 op->timeout_id = 0;
817         }
818
819         att_debug(att, "(chan %p) Retrying operation %p", chan, op);
820
821         chan->pending_req = NULL;
822
823         /* Push operation back to request queue */
824         return queue_push_head(att->req_queue, op);
825 }
826
827 static void handle_rsp(struct bt_att_chan *chan, uint8_t opcode, uint8_t *pdu,
828                                                                 ssize_t pdu_len)
829 {
830         struct bt_att *att = chan->att;
831         struct att_send_op *op = chan->pending_req;
832         uint8_t req_opcode;
833         uint8_t rsp_opcode;
834         uint8_t *rsp_pdu = NULL;
835         uint16_t rsp_pdu_len = 0;
836
837         /*
838          * If no request is pending, then the response is unexpected. Disconnect
839          * the bearer.
840          */
841         if (!op) {
842                 att_debug(att, "(chan %p) Received unexpected ATT response",
843                                                                 chan);
844                 io_shutdown(chan->io);
845                 return;
846         }
847
848         /*
849          * If the received response doesn't match the pending request, or if
850          * the request is malformed, end the current request with failure.
851          */
852         if (opcode == BT_ATT_OP_ERROR_RSP) {
853                 /* Return if error response cause a retry */
854                 if (handle_error_rsp(chan, pdu, pdu_len, &req_opcode)) {
855                         wakeup_chan_writer(chan, NULL);
856                         return;
857                 }
858         } else if (!(req_opcode = get_req_opcode(opcode)))
859                 goto fail;
860
861         if (req_opcode != op->opcode)
862                 goto fail;
863
864         rsp_opcode = opcode;
865
866         if (pdu_len > 0) {
867                 rsp_pdu = pdu;
868                 rsp_pdu_len = pdu_len;
869         }
870
871         goto done;
872
873 fail:
874         att_debug(att, "(chan %p) Failed to handle response PDU; opcode: "
875                         "0x%02x", chan, opcode);
876
877         rsp_opcode = BT_ATT_OP_ERROR_RSP;
878
879 done:
880         if (op->callback)
881                 op->callback(rsp_opcode, rsp_pdu, rsp_pdu_len, op->user_data);
882
883         destroy_att_send_op(op);
884         chan->pending_req = NULL;
885
886         wakeup_chan_writer(chan, NULL);
887 }
888
889 static void handle_conf(struct bt_att_chan *chan, uint8_t *pdu, ssize_t pdu_len)
890 {
891         struct bt_att *att = chan->att;
892         struct att_send_op *op = chan->pending_ind;
893
894         /*
895          * Disconnect the bearer if the confirmation is unexpected or the PDU is
896          * invalid.
897          */
898         if (!op || pdu_len) {
899                 att_debug(att, "(chan %p) Received unexpected/invalid ATT "
900                                 "confirmation", chan);
901                 io_shutdown(chan->io);
902                 return;
903         }
904
905         if (op->callback)
906                 op->callback(BT_ATT_OP_HANDLE_CONF, NULL, 0, op->user_data);
907
908         destroy_att_send_op(op);
909         chan->pending_ind = NULL;
910
911         wakeup_chan_writer(chan, NULL);
912 }
913
914 struct notify_data {
915         uint8_t opcode;
916         uint8_t *pdu;
917         ssize_t pdu_len;
918         bool handler_found;
919 };
920
921 static bool opcode_match(uint8_t opcode, uint8_t test_opcode)
922 {
923         enum att_op_type op_type = get_op_type(test_opcode);
924
925         if (opcode == BT_ATT_ALL_REQUESTS && (op_type == ATT_OP_TYPE_REQ ||
926                                                 op_type == ATT_OP_TYPE_CMD))
927                 return true;
928
929         return opcode == test_opcode;
930 }
931
932 static void respond_not_supported(struct bt_att *att, uint8_t opcode)
933 {
934         struct bt_att_pdu_error_rsp pdu;
935
936         pdu.opcode = opcode;
937         pdu.handle = 0x0000;
938         pdu.ecode = BT_ATT_ERROR_REQUEST_NOT_SUPPORTED;
939
940         bt_att_send(att, BT_ATT_OP_ERROR_RSP, &pdu, sizeof(pdu), NULL, NULL,
941                                                                         NULL);
942 }
943
944 static bool handle_signed(struct bt_att *att, uint8_t *pdu, ssize_t pdu_len)
945 {
946         uint8_t *signature;
947         uint32_t sign_cnt;
948         struct sign_info *sign;
949         uint8_t opcode = pdu[0];
950
951         /* Check if there is enough data for a signature */
952         if (pdu_len < 3 + BT_ATT_SIGNATURE_LEN)
953                 goto fail;
954
955         sign = att->remote_sign;
956         if (!sign)
957                 goto fail;
958
959         signature = pdu + (pdu_len - BT_ATT_SIGNATURE_LEN);
960         sign_cnt = get_le32(signature);
961
962         /* Validate counter */
963         if (!sign->counter(&sign_cnt, sign->user_data))
964                 goto fail;
965
966         /* Verify received signature */
967         if (!bt_crypto_verify_att_sign(att->crypto, sign->key, pdu, pdu_len))
968                 goto fail;
969
970         return true;
971
972 fail:
973         att_debug(att, "ATT failed to verify signature: 0x%02x", opcode);
974
975         return false;
976 }
977
978 static void handle_notify(struct bt_att_chan *chan, uint8_t *pdu,
979                                                         ssize_t pdu_len)
980 {
981         struct bt_att *att = chan->att;
982         const struct queue_entry *entry;
983         bool found;
984         uint8_t opcode = pdu[0];
985
986         bt_att_ref(att);
987
988         found = false;
989         entry = queue_get_entries(att->notify_list);
990
991         while (entry) {
992                 struct att_notify *notify = entry->data;
993
994                 entry = entry->next;
995
996                 if (!opcode_match(notify->opcode, opcode))
997                         continue;
998
999                 if ((opcode & ATT_OP_SIGNED_MASK) && att->crypto) {
1000                         if (!handle_signed(att, pdu, pdu_len))
1001                                 return;
1002                         pdu_len -= BT_ATT_SIGNATURE_LEN;
1003                 }
1004
1005                 /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G
1006                  * page 2370
1007                  *
1008                  * 4.3.1 Exchange MTU
1009                  *
1010                  * This sub-procedure shall not be used on a BR/EDR physical
1011                  * link since the MTU size is negotiated using L2CAP channel
1012                  * configuration procedures.
1013                  */
1014                 if (bt_att_get_link_type(att) == BT_ATT_BREDR ||
1015                                 chan->type == BT_ATT_EATT) {
1016                         switch (opcode) {
1017                         case BT_ATT_OP_MTU_REQ:
1018                                 goto not_supported;
1019                         }
1020                 }
1021
1022                 found = true;
1023
1024                 if (notify->callback)
1025                         notify->callback(chan, opcode, pdu + 1, pdu_len - 1,
1026                                                         notify->user_data);
1027
1028                 /* callback could remove all entries from notify list */
1029                 if (queue_isempty(att->notify_list))
1030                         break;
1031         }
1032
1033 not_supported:
1034         /*
1035          * If this was not a command and no handler was registered for it,
1036          * respond with "Not Supported"
1037          */
1038         if (!found && get_op_type(opcode) != ATT_OP_TYPE_CMD)
1039                 respond_not_supported(att, opcode);
1040
1041         bt_att_unref(att);
1042 }
1043
1044 static bool can_read_data(struct io *io, void *user_data)
1045 {
1046         struct bt_att_chan *chan = user_data;
1047         struct bt_att *att = chan->att;
1048         uint8_t opcode;
1049         uint8_t *pdu;
1050         ssize_t bytes_read;
1051
1052         bytes_read = read(chan->fd, chan->buf, chan->mtu);
1053         if (bytes_read < 0)
1054                 return false;
1055
1056         att_verbose(att, "(chan %p) ATT received: %zd", chan, bytes_read);
1057
1058         att_hexdump(att, '>', chan->buf, bytes_read);
1059
1060         if (bytes_read < ATT_MIN_PDU_LEN)
1061                 return true;
1062
1063         pdu = chan->buf;
1064         opcode = pdu[0];
1065
1066         bt_att_ref(att);
1067
1068         /* Act on the received PDU based on the opcode type */
1069         switch (get_op_type(opcode)) {
1070         case ATT_OP_TYPE_RSP:
1071                 att_verbose(att, "(chan %p) ATT response received: 0x%02x",
1072                                 chan, opcode);
1073                 handle_rsp(chan, opcode, pdu + 1, bytes_read - 1);
1074                 break;
1075         case ATT_OP_TYPE_CONF:
1076                 att_verbose(att, "(chan %p) ATT confirmation received: 0x%02x",
1077                                 chan, opcode);
1078                 handle_conf(chan, pdu + 1, bytes_read - 1);
1079                 break;
1080         case ATT_OP_TYPE_REQ:
1081                 /*
1082                  * If a request is currently pending, then the sequential
1083                  * protocol was violated. Disconnect the bearer, which will
1084                  * promptly notify the upper layer via disconnect handlers.
1085                  */
1086                 if (chan->in_req) {
1087                         att_debug(att, "(chan %p) Received request while "
1088                                         "another is pending: 0x%02x",
1089                                         chan, opcode);
1090                         io_shutdown(chan->io);
1091                         bt_att_unref(chan->att);
1092
1093                         return false;
1094                 }
1095
1096                 chan->in_req = true;
1097                 /* fall through */
1098         case ATT_OP_TYPE_CMD:
1099         case ATT_OP_TYPE_NFY:
1100         case ATT_OP_TYPE_UNKNOWN:
1101         case ATT_OP_TYPE_IND:
1102                 /* fall through */
1103         default:
1104                 /* For all other opcodes notify the upper layer of the PDU and
1105                  * let them act on it.
1106                  */
1107                 att_debug(att, "(chan %p) ATT PDU received: 0x%02x", chan,
1108                                                         opcode);
1109                 handle_notify(chan, pdu, bytes_read);
1110                 break;
1111         }
1112
1113         bt_att_unref(att);
1114
1115         return true;
1116 }
1117
1118 static bool is_io_l2cap_based(int fd)
1119 {
1120         int domain;
1121         int proto;
1122         int err;
1123         socklen_t len;
1124
1125         domain = 0;
1126         len = sizeof(domain);
1127         err = getsockopt(fd, SOL_SOCKET, SO_DOMAIN, &domain, &len);
1128         if (err < 0)
1129                 return false;
1130
1131         if (domain != AF_BLUETOOTH)
1132                 return false;
1133
1134         proto = 0;
1135         len = sizeof(proto);
1136         err = getsockopt(fd, SOL_SOCKET, SO_PROTOCOL, &proto, &len);
1137         if (err < 0)
1138                 return false;
1139
1140         return proto == BTPROTO_L2CAP;
1141 }
1142
1143 static void bt_att_free(struct bt_att *att)
1144 {
1145         bt_crypto_unref(att->crypto);
1146
1147         if (att->timeout_destroy)
1148                 att->timeout_destroy(att->timeout_data);
1149
1150         if (att->debug_destroy)
1151                 att->debug_destroy(att->debug_data);
1152
1153         free(att->local_sign);
1154         free(att->remote_sign);
1155
1156         queue_destroy(att->req_queue, NULL);
1157         queue_destroy(att->ind_queue, NULL);
1158         queue_destroy(att->write_queue, NULL);
1159         queue_destroy(att->notify_list, NULL);
1160         queue_destroy(att->disconn_list, NULL);
1161         queue_destroy(att->exchange_list, NULL);
1162         queue_destroy(att->chans, bt_att_chan_free);
1163
1164         free(att);
1165 }
1166
1167 static uint16_t io_get_mtu(int fd)
1168 {
1169         socklen_t len;
1170         struct l2cap_options l2o;
1171
1172         len = sizeof(l2o);
1173         if (!getsockopt(fd, SOL_L2CAP, L2CAP_OPTIONS, &l2o, &len))
1174                 return l2o.omtu;
1175
1176         if (!getsockopt(fd, SOL_BLUETOOTH, BT_SNDMTU, &l2o.omtu, &len))
1177                 return l2o.omtu;
1178
1179         return 0;
1180 }
1181
1182 static uint8_t io_get_type(int fd)
1183 {
1184         struct sockaddr_l2 src;
1185         socklen_t len;
1186
1187         if (!is_io_l2cap_based(fd))
1188                 return BT_ATT_LOCAL;
1189
1190         len = sizeof(src);
1191         memset(&src, 0, len);
1192         if (getsockname(fd, (void *)&src, &len) < 0)
1193                 return -errno;
1194
1195         if (src.l2_bdaddr_type == BDADDR_BREDR)
1196                 return BT_ATT_BREDR;
1197
1198         return BT_ATT_LE;
1199 }
1200
1201 static struct bt_att_chan *bt_att_chan_new(int fd, uint8_t type)
1202 {
1203         struct bt_att_chan *chan;
1204
1205         if (fd < 0)
1206                 return NULL;
1207
1208         chan = new0(struct bt_att_chan, 1);
1209         chan->fd = fd;
1210
1211         chan->io = io_new(fd);
1212         if (!chan->io)
1213                 goto fail;
1214
1215         if (!io_set_read_handler(chan->io, can_read_data, chan, NULL))
1216                 goto fail;
1217
1218         if (!io_set_disconnect_handler(chan->io, disconnect_cb, chan, NULL))
1219                 goto fail;
1220
1221         chan->type = type;
1222         switch (chan->type) {
1223         case BT_ATT_LOCAL:
1224                 chan->sec_level = BT_ATT_SECURITY_LOW;
1225                 /* fall through */
1226         case BT_ATT_LE:
1227                 chan->mtu = BT_ATT_DEFAULT_LE_MTU;
1228                 break;
1229         default:
1230                 chan->mtu = io_get_mtu(chan->fd);
1231         }
1232
1233         if (chan->mtu < BT_ATT_DEFAULT_LE_MTU)
1234                 goto fail;
1235
1236         chan->buf = malloc(chan->mtu);
1237         if (!chan->buf)
1238                 goto fail;
1239
1240         chan->queue = queue_new();
1241
1242         return chan;
1243
1244 fail:
1245         bt_att_chan_free(chan);
1246
1247         return NULL;
1248 }
1249
1250 static void bt_att_attach_chan(struct bt_att *att, struct bt_att_chan *chan)
1251 {
1252         /* Push to head as EATT channels have higher priority */
1253         queue_push_head(att->chans, chan);
1254         chan->att = att;
1255
1256         if (chan->mtu > att->mtu)
1257                 att->mtu = chan->mtu;
1258
1259         io_set_close_on_destroy(chan->io, att->close_on_unref);
1260
1261         att_debug(att, "Channel %p attached", chan);
1262
1263         wakeup_chan_writer(chan, NULL);
1264 }
1265
1266 struct bt_att *bt_att_new(int fd, bool ext_signed)
1267 {
1268         struct bt_att *att;
1269         struct bt_att_chan *chan;
1270
1271         chan = bt_att_chan_new(fd, io_get_type(fd));
1272         if (!chan)
1273                 return NULL;
1274
1275         att = new0(struct bt_att, 1);
1276         att->chans = queue_new();
1277         att->mtu = chan->mtu;
1278
1279         /* crypto is optional, if not available leave it NULL */
1280         if (!ext_signed)
1281                 att->crypto = bt_crypto_new();
1282
1283         att->req_queue = queue_new();
1284         att->ind_queue = queue_new();
1285         att->write_queue = queue_new();
1286         att->notify_list = queue_new();
1287         att->disconn_list = queue_new();
1288         att->exchange_list = queue_new();
1289
1290         bt_att_attach_chan(att, chan);
1291
1292         return bt_att_ref(att);
1293 }
1294
1295 struct bt_att *bt_att_ref(struct bt_att *att)
1296 {
1297         if (!att)
1298                 return NULL;
1299
1300         __sync_fetch_and_add(&att->ref_count, 1);
1301
1302         return att;
1303 }
1304
1305 void bt_att_unref(struct bt_att *att)
1306 {
1307         if (!att)
1308                 return;
1309
1310         if (__sync_sub_and_fetch(&att->ref_count, 1))
1311                 return;
1312
1313         bt_att_unregister_all(att);
1314         bt_att_cancel_all(att);
1315
1316         bt_att_free(att);
1317 }
1318
1319 bool bt_att_set_close_on_unref(struct bt_att *att, bool do_close)
1320 {
1321         const struct queue_entry *entry;
1322
1323         if (!att)
1324                 return false;
1325
1326         att->close_on_unref = do_close;
1327
1328         for (entry = queue_get_entries(att->chans); entry;
1329                                                 entry = entry->next) {
1330                 struct bt_att_chan *chan = entry->data;
1331
1332                 if (!io_set_close_on_destroy(chan->io, do_close))
1333                         return false;
1334         }
1335
1336         return true;
1337 }
1338
1339 int bt_att_attach_fd(struct bt_att *att, int fd)
1340 {
1341         struct bt_att_chan *chan;
1342
1343         if (!att || fd < 0)
1344                 return -EINVAL;
1345
1346         chan = bt_att_chan_new(fd, BT_ATT_EATT);
1347         if (!chan)
1348                 return -EINVAL;
1349
1350         bt_att_attach_chan(att, chan);
1351
1352         return 0;
1353 }
1354
1355 int bt_att_get_fd(struct bt_att *att)
1356 {
1357         struct bt_att_chan *chan;
1358
1359         if (!att)
1360                 return -1;
1361
1362         if (queue_isempty(att->chans))
1363                 return -ENOTCONN;
1364
1365         chan = queue_peek_tail(att->chans);
1366
1367         return chan->fd;
1368 }
1369
1370 int bt_att_get_channels(struct bt_att *att)
1371 {
1372         if (!att)
1373                 return 0;
1374
1375         return queue_length(att->chans);
1376 }
1377
1378 bool bt_att_set_debug(struct bt_att *att, uint8_t level,
1379                         bt_att_debug_func_t callback, void *user_data,
1380                         bt_att_destroy_func_t destroy)
1381 {
1382         if (!att)
1383                 return false;
1384
1385         if (att->debug_destroy)
1386                 att->debug_destroy(att->debug_data);
1387
1388         att->debug_level = level;
1389         att->debug_callback = callback;
1390         att->debug_destroy = destroy;
1391         att->debug_data = user_data;
1392
1393         return true;
1394 }
1395
1396 uint16_t bt_att_get_mtu(struct bt_att *att)
1397 {
1398         if (!att)
1399                 return 0;
1400
1401         return att->mtu;
1402 }
1403
1404 static void exchange_handler(void *data, void *user_data)
1405 {
1406         struct att_exchange *exchange = data;
1407         uint16_t mtu = PTR_TO_INT(user_data);
1408
1409         if (exchange->removed)
1410                 return;
1411
1412         if (exchange->callback)
1413                 exchange->callback(mtu, exchange->user_data);
1414 }
1415
1416 bool bt_att_set_mtu(struct bt_att *att, uint16_t mtu)
1417 {
1418         struct bt_att_chan *chan;
1419         void *buf;
1420
1421         if (!att)
1422                 return false;
1423
1424         if (mtu < BT_ATT_DEFAULT_LE_MTU)
1425                 return false;
1426
1427         /* Original channel is always the last */
1428         chan = queue_peek_tail(att->chans);
1429         if (!chan)
1430                 return -ENOTCONN;
1431
1432         buf = malloc(mtu);
1433         if (!buf)
1434                 return false;
1435
1436         free(chan->buf);
1437
1438         chan->mtu = mtu;
1439         chan->buf = buf;
1440         if (chan->mtu > att->mtu) {
1441                 att->mtu = chan->mtu;
1442                 queue_foreach(att->exchange_list, exchange_handler,
1443                                                 INT_TO_PTR(att->mtu));
1444         }
1445
1446         return true;
1447 }
1448
1449 uint8_t bt_att_get_link_type(struct bt_att *att)
1450 {
1451         struct bt_att_chan *chan;
1452
1453         if (!att)
1454                 return -EINVAL;
1455
1456         chan = queue_peek_tail(att->chans);
1457         if (!chan)
1458                 return -ENOTCONN;
1459
1460         return chan->type;
1461 }
1462
1463 bool bt_att_set_timeout_cb(struct bt_att *att, bt_att_timeout_func_t callback,
1464                                                 void *user_data,
1465                                                 bt_att_destroy_func_t destroy)
1466 {
1467         if (!att)
1468                 return false;
1469
1470         if (att->timeout_destroy)
1471                 att->timeout_destroy(att->timeout_data);
1472
1473         att->timeout_callback = callback;
1474         att->timeout_destroy = destroy;
1475         att->timeout_data = user_data;
1476
1477         return true;
1478 }
1479
1480 unsigned int bt_att_register_disconnect(struct bt_att *att,
1481                                         bt_att_disconnect_func_t callback,
1482                                         void *user_data,
1483                                         bt_att_destroy_func_t destroy)
1484 {
1485         struct att_disconn *disconn;
1486
1487         if (!att || queue_isempty(att->chans))
1488                 return 0;
1489
1490         disconn = new0(struct att_disconn, 1);
1491         disconn->callback = callback;
1492         disconn->destroy = destroy;
1493         disconn->user_data = user_data;
1494
1495         if (att->next_reg_id < 1)
1496                 att->next_reg_id = 1;
1497
1498         disconn->id = att->next_reg_id++;
1499
1500         if (!queue_push_tail(att->disconn_list, disconn)) {
1501                 free(disconn);
1502                 return 0;
1503         }
1504
1505         return disconn->id;
1506 }
1507
1508 bool bt_att_unregister_disconnect(struct bt_att *att, unsigned int id)
1509 {
1510         struct att_disconn *disconn;
1511
1512         if (!att || !id)
1513                 return false;
1514
1515         /* Check if disconnect is running */
1516         if (queue_isempty(att->chans)) {
1517                 disconn = queue_find(att->disconn_list, match_disconn_id,
1518                                                         UINT_TO_PTR(id));
1519                 if (!disconn)
1520                         return false;
1521
1522                 disconn->removed = true;
1523                 return true;
1524         }
1525
1526         disconn = queue_remove_if(att->disconn_list, match_disconn_id,
1527                                                         UINT_TO_PTR(id));
1528         if (!disconn)
1529                 return false;
1530
1531         destroy_att_disconn(disconn);
1532         return true;
1533 }
1534
1535 unsigned int bt_att_register_exchange(struct bt_att *att,
1536                                         bt_att_exchange_func_t callback,
1537                                         void *user_data,
1538                                         bt_att_destroy_func_t destroy)
1539 {
1540         struct att_exchange *mtu;
1541
1542         if (!att || queue_isempty(att->chans))
1543                 return 0;
1544
1545         mtu = new0(struct att_exchange, 1);
1546         mtu->callback = callback;
1547         mtu->destroy = destroy;
1548         mtu->user_data = user_data;
1549
1550         if (att->next_reg_id < 1)
1551                 att->next_reg_id = 1;
1552
1553         mtu->id = att->next_reg_id++;
1554
1555         if (!queue_push_tail(att->exchange_list, mtu)) {
1556                 free(att);
1557                 return 0;
1558         }
1559
1560         return mtu->id;
1561 }
1562
1563 bool bt_att_unregister_exchange(struct bt_att *att, unsigned int id)
1564 {
1565         struct att_exchange *mtu;
1566
1567         if (!att || !id)
1568                 return false;
1569
1570         /* Check if disconnect is running */
1571         if (queue_isempty(att->chans)) {
1572                 mtu = queue_find(att->exchange_list, match_disconn_id,
1573                                                         UINT_TO_PTR(id));
1574                 if (!mtu)
1575                         return false;
1576
1577                 mtu->removed = true;
1578                 return true;
1579         }
1580
1581         mtu = queue_remove_if(att->exchange_list, match_disconn_id,
1582                                                         UINT_TO_PTR(id));
1583         if (!mtu)
1584                 return false;
1585
1586         destroy_att_exchange(mtu);
1587         return true;
1588 }
1589
1590 unsigned int bt_att_send(struct bt_att *att, uint8_t opcode,
1591                                 const void *pdu, uint16_t length,
1592                                 bt_att_response_func_t callback, void *user_data,
1593                                 bt_att_destroy_func_t destroy)
1594 {
1595         struct att_send_op *op;
1596         bool result;
1597
1598         if (!att || queue_isempty(att->chans))
1599                 return 0;
1600
1601         op = create_att_send_op(att, opcode, pdu, length, callback, user_data,
1602                                                                 destroy);
1603         if (!op)
1604                 return 0;
1605
1606         if (att->next_send_id < 1)
1607                 att->next_send_id = 1;
1608
1609         op->id = att->next_send_id++;
1610
1611         /* Add the op to the correct queue based on its type */
1612         switch (op->type) {
1613         case ATT_OP_TYPE_REQ:
1614                 result = queue_push_tail(att->req_queue, op);
1615                 break;
1616         case ATT_OP_TYPE_IND:
1617                 result = queue_push_tail(att->ind_queue, op);
1618                 break;
1619         case ATT_OP_TYPE_CMD:
1620         case ATT_OP_TYPE_NFY:
1621         case ATT_OP_TYPE_UNKNOWN:
1622         case ATT_OP_TYPE_RSP:
1623         case ATT_OP_TYPE_CONF:
1624         default:
1625                 result = queue_push_tail(att->write_queue, op);
1626                 break;
1627         }
1628
1629         if (!result) {
1630                 free(op->pdu);
1631                 free(op);
1632                 return 0;
1633         }
1634
1635         wakeup_writer(att);
1636
1637         return op->id;
1638 }
1639
1640 int bt_att_resend(struct bt_att *att, unsigned int id, uint8_t opcode,
1641                                 const void *pdu, uint16_t length,
1642                                 bt_att_response_func_t callback,
1643                                 void *user_data,
1644                                 bt_att_destroy_func_t destroy)
1645 {
1646         const struct queue_entry *entry;
1647         struct att_send_op *op;
1648         bool result;
1649
1650         if (!att || !id)
1651                 return -EINVAL;
1652
1653         /* Lookup request on each channel */
1654         for (entry = queue_get_entries(att->chans); entry;
1655                                                 entry = entry->next) {
1656                 struct bt_att_chan *chan = entry->data;
1657
1658                 if (chan->pending_req && chan->pending_req->id == id)
1659                         break;
1660         }
1661
1662         if (!entry)
1663                 return -ENOENT;
1664
1665         /* Only allow requests to be resend */
1666         if (get_op_type(opcode) != ATT_OP_TYPE_REQ)
1667                 return -EOPNOTSUPP;
1668
1669         op = create_att_send_op(att, opcode, pdu, length, callback, user_data,
1670                                                                 destroy);
1671         if (!op)
1672                 return -ENOMEM;
1673
1674         op->id = id;
1675
1676         switch (opcode) {
1677         /* Only prepend requests that could be a continuation */
1678         case BT_ATT_OP_READ_BLOB_REQ:
1679         case BT_ATT_OP_PREP_WRITE_REQ:
1680         case BT_ATT_OP_EXEC_WRITE_REQ:
1681                 result = queue_push_head(att->req_queue, op);
1682                 break;
1683         default:
1684                 result = queue_push_tail(att->req_queue, op);
1685                 break;
1686         }
1687
1688         if (!result) {
1689                 free(op->pdu);
1690                 free(op);
1691                 return -ENOMEM;
1692         }
1693
1694         wakeup_writer(att);
1695
1696         return 0;
1697 }
1698
1699 unsigned int bt_att_chan_send(struct bt_att_chan *chan, uint8_t opcode,
1700                                 const void *pdu, uint16_t len,
1701                                 bt_att_response_func_t callback,
1702                                 void *user_data,
1703                                 bt_att_destroy_func_t destroy)
1704 {
1705         struct att_send_op *op;
1706
1707         if (!chan || !chan->att)
1708                 return -EINVAL;
1709
1710         op = create_att_send_op(chan->att, opcode, pdu, len, callback,
1711                                                 user_data, destroy);
1712         if (!op)
1713                 return -EINVAL;
1714
1715         if (!queue_push_tail(chan->queue, op)) {
1716                 free(op->pdu);
1717                 free(op);
1718                 return 0;
1719         }
1720
1721         wakeup_chan_writer(chan, NULL);
1722
1723         return op->id;
1724 }
1725
1726 static bool match_op_id(const void *a, const void *b)
1727 {
1728         const struct att_send_op *op = a;
1729         unsigned int id = PTR_TO_UINT(b);
1730
1731         return op->id == id;
1732 }
1733
1734 bool bt_att_chan_cancel(struct bt_att_chan *chan, unsigned int id)
1735 {
1736         struct att_send_op *op;
1737
1738         if (chan->pending_req && chan->pending_req->id == id) {
1739                 /* Don't cancel the pending request; remove it's handlers */
1740                 cancel_att_send_op(chan->pending_req);
1741                 return true;
1742         }
1743
1744         if (chan->pending_ind && chan->pending_ind->id == id) {
1745                 /* Don't cancel the pending indication; remove it's handlers. */
1746                 cancel_att_send_op(chan->pending_ind);
1747                 return true;
1748         }
1749
1750         op = queue_remove_if(chan->queue, match_op_id, UINT_TO_PTR(id));
1751         if (!op)
1752                 return false;
1753
1754         destroy_att_send_op(op);
1755
1756         wakeup_chan_writer(chan, NULL);
1757
1758         return true;
1759 }
1760
1761 static bool bt_att_disc_cancel(struct bt_att *att, unsigned int id)
1762 {
1763         struct att_send_op *op;
1764
1765         op = queue_find(att->req_queue, match_op_id, UINT_TO_PTR(id));
1766         if (op)
1767                 goto done;
1768
1769         op = queue_find(att->ind_queue, match_op_id, UINT_TO_PTR(id));
1770         if (op)
1771                 goto done;
1772
1773         op = queue_find(att->write_queue, match_op_id, UINT_TO_PTR(id));
1774
1775 done:
1776         if (!op)
1777                 return false;
1778
1779         /* Just cancel since disconnect_cb will be cleaning up */
1780         cancel_att_send_op(op);
1781
1782         return true;
1783 }
1784
1785 bool bt_att_cancel(struct bt_att *att, unsigned int id)
1786 {
1787         const struct queue_entry *entry;
1788         struct att_send_op *op;
1789
1790         if (!att || !id)
1791                 return false;
1792
1793         for (entry = queue_get_entries(att->chans); entry;
1794                                                 entry = entry->next) {
1795                 struct bt_att_chan *chan = entry->data;
1796
1797                 if (bt_att_chan_cancel(chan, id))
1798                         return true;
1799                 }
1800
1801         if (att->in_disc)
1802                 return bt_att_disc_cancel(att, id);
1803
1804         op = queue_remove_if(att->req_queue, match_op_id, UINT_TO_PTR(id));
1805         if (op)
1806                 goto done;
1807
1808         op = queue_remove_if(att->ind_queue, match_op_id, UINT_TO_PTR(id));
1809         if (op)
1810                 goto done;
1811
1812         op = queue_remove_if(att->write_queue, match_op_id, UINT_TO_PTR(id));
1813         if (op)
1814                 goto done;
1815
1816         if (!op)
1817                 return false;
1818
1819 done:
1820         destroy_att_send_op(op);
1821
1822         wakeup_writer(att);
1823
1824         return true;
1825 }
1826
1827 bool bt_att_cancel_all(struct bt_att *att)
1828 {
1829         const struct queue_entry *entry;
1830
1831         if (!att)
1832                 return false;
1833
1834         queue_remove_all(att->req_queue, NULL, NULL, destroy_att_send_op);
1835         queue_remove_all(att->ind_queue, NULL, NULL, destroy_att_send_op);
1836         queue_remove_all(att->write_queue, NULL, NULL, destroy_att_send_op);
1837
1838         for (entry = queue_get_entries(att->chans); entry;
1839                                                 entry = entry->next) {
1840                 struct bt_att_chan *chan = entry->data;
1841
1842                 if (chan->pending_req)
1843                         /* Don't cancel the pending request; remove it's
1844                          * handlers
1845                          */
1846                         cancel_att_send_op(chan->pending_req);
1847
1848                 if (chan->pending_ind)
1849                         /* Don't cancel the pending request; remove it's
1850                          * handlers
1851                          */
1852                         cancel_att_send_op(chan->pending_ind);
1853         }
1854
1855         return true;
1856 }
1857
1858 static uint8_t att_ecode_from_error(int err)
1859 {
1860         /*
1861          * If the error fits in a single byte, treat it as an ATT protocol
1862          * error as is. Since "0" is not a valid ATT protocol error code, we map
1863          * that to UNLIKELY below.
1864          */
1865         if (err > 0 && err < UINT8_MAX)
1866                 return err;
1867
1868         /*
1869          * Since we allow UNIX errnos, map them to appropriate ATT protocol
1870          * and "Common Profile and Service" error codes.
1871          */
1872         switch (err) {
1873         case -ENOENT:
1874                 return BT_ATT_ERROR_INVALID_HANDLE;
1875         case -ENOMEM:
1876                 return BT_ATT_ERROR_INSUFFICIENT_RESOURCES;
1877         case -EALREADY:
1878                 return BT_ERROR_ALREADY_IN_PROGRESS;
1879         case -EOVERFLOW:
1880                 return BT_ERROR_OUT_OF_RANGE;
1881         }
1882
1883         return BT_ATT_ERROR_UNLIKELY;
1884 }
1885
1886 int bt_att_chan_send_error_rsp(struct bt_att_chan *chan, uint8_t opcode,
1887                                                 uint16_t handle, int error)
1888 {
1889         struct bt_att_pdu_error_rsp pdu;
1890         uint8_t ecode;
1891
1892         if (!chan || !chan->att || !opcode)
1893                 return -EINVAL;
1894
1895         ecode = att_ecode_from_error(error);
1896
1897         memset(&pdu, 0, sizeof(pdu));
1898
1899         pdu.opcode = opcode;
1900         put_le16(handle, &pdu.handle);
1901         pdu.ecode = ecode;
1902
1903         return bt_att_chan_send_rsp(chan, BT_ATT_OP_ERROR_RSP, &pdu,
1904                                                         sizeof(pdu));
1905 }
1906
1907 unsigned int bt_att_register(struct bt_att *att, uint8_t opcode,
1908                                                 bt_att_notify_func_t callback,
1909                                                 void *user_data,
1910                                                 bt_att_destroy_func_t destroy)
1911 {
1912         struct att_notify *notify;
1913
1914         if (!att || !callback || queue_isempty(att->chans))
1915                 return 0;
1916
1917         notify = new0(struct att_notify, 1);
1918         notify->opcode = opcode;
1919         notify->callback = callback;
1920         notify->destroy = destroy;
1921         notify->user_data = user_data;
1922
1923         if (att->next_reg_id < 1)
1924                 att->next_reg_id = 1;
1925
1926         notify->id = att->next_reg_id++;
1927
1928         if (!queue_push_tail(att->notify_list, notify)) {
1929                 free(notify);
1930                 return 0;
1931         }
1932
1933         return notify->id;
1934 }
1935
1936 bool bt_att_unregister(struct bt_att *att, unsigned int id)
1937 {
1938         struct att_notify *notify;
1939
1940         if (!att || !id)
1941                 return false;
1942
1943         notify = queue_remove_if(att->notify_list, match_notify_id,
1944                                                         UINT_TO_PTR(id));
1945         if (!notify)
1946                 return false;
1947
1948         destroy_att_notify(notify);
1949         return true;
1950 }
1951
1952 bool bt_att_unregister_all(struct bt_att *att)
1953 {
1954         if (!att)
1955                 return false;
1956
1957         queue_remove_all(att->notify_list, NULL, NULL, destroy_att_notify);
1958         queue_remove_all(att->disconn_list, NULL, NULL, destroy_att_disconn);
1959         queue_remove_all(att->exchange_list, NULL, NULL, destroy_att_exchange);
1960
1961         return true;
1962 }
1963
1964 int bt_att_get_security(struct bt_att *att, uint8_t *enc_size)
1965 {
1966         struct bt_att_chan *chan;
1967         int ret;
1968
1969         if (!att)
1970                 return -EINVAL;
1971
1972         chan = queue_peek_tail(att->chans);
1973         if (!chan)
1974                 return -ENOTCONN;
1975
1976         ret = bt_att_chan_get_security(chan);
1977         if (ret < 0)
1978                 return ret;
1979
1980         if (enc_size)
1981                 *enc_size = att->enc_size;
1982
1983         return ret;
1984 }
1985
1986 bool bt_att_set_security(struct bt_att *att, int level)
1987 {
1988         struct bt_att_chan *chan;
1989
1990         if (!att || level < BT_ATT_SECURITY_AUTO ||
1991                                                 level > BT_ATT_SECURITY_HIGH)
1992                 return false;
1993
1994         chan = queue_peek_tail(att->chans);
1995         if (!chan)
1996                 return -ENOTCONN;
1997
1998         return bt_att_chan_set_security(chan, level);
1999 }
2000
2001 void bt_att_set_enc_key_size(struct bt_att *att, uint8_t enc_size)
2002 {
2003         if (!att)
2004                 return;
2005
2006         att->enc_size = enc_size;
2007 }
2008
2009 static bool sign_set_key(struct sign_info **sign, uint8_t key[16],
2010                                 bt_att_counter_func_t func, void *user_data)
2011 {
2012         if (!(*sign))
2013                 *sign = new0(struct sign_info, 1);
2014
2015         (*sign)->counter = func;
2016         (*sign)->user_data = user_data;
2017         memcpy((*sign)->key, key, 16);
2018
2019         return true;
2020 }
2021
2022 bool bt_att_set_local_key(struct bt_att *att, uint8_t sign_key[16],
2023                                 bt_att_counter_func_t func, void *user_data)
2024 {
2025         if (!att)
2026                 return false;
2027
2028         return sign_set_key(&att->local_sign, sign_key, func, user_data);
2029 }
2030
2031 bool bt_att_set_remote_key(struct bt_att *att, uint8_t sign_key[16],
2032                                 bt_att_counter_func_t func, void *user_data)
2033 {
2034         if (!att)
2035                 return false;
2036
2037         return sign_set_key(&att->remote_sign, sign_key, func, user_data);
2038 }
2039
2040 bool bt_att_has_crypto(struct bt_att *att)
2041 {
2042         if (!att)
2043                 return false;
2044
2045         return att->crypto ? true : false;
2046 }
2047
2048 #ifdef TIZEN_FEATURE_BLUEZ_MODIFY
2049 bool bt_att_set_remote_addr(struct bt_att *att,
2050                                 const bdaddr_t *bdaddr, uint8_t bdaddr_type)
2051 {
2052         if (!att)
2053                 return false;
2054
2055         bacpy(&att->bdaddr, bdaddr);
2056         att->bdaddr_type = bdaddr_type;
2057
2058         return true;
2059 }
2060
2061 bool bt_att_get_remote_addr(struct bt_att *att,
2062                                 bdaddr_t *bdaddr, uint8_t *bdaddr_type)
2063 {
2064         if (!att)
2065                 return false;
2066
2067         if (!bacmp(&att->bdaddr, BDADDR_ANY))
2068                 return false;
2069
2070         bacpy(bdaddr, &att->bdaddr);
2071         *bdaddr_type = att->bdaddr_type;
2072
2073         return true;
2074 }
2075
2076 bool bt_att_set_svc_changed_indication_registered(struct bt_att *att, bool value)
2077 {
2078         if (!att)
2079                 return false;
2080
2081         att->service_change_indication = value;
2082
2083         return true;
2084 }
2085
2086 bool bt_att_get_svc_changed_indication_registered(struct bt_att *att)
2087 {
2088         if (!att)
2089                 return false;
2090
2091         return att->service_change_indication;
2092 }
2093 #endif