xref: /btstack/src/ble/att_db.c (revision 0561b2d8d5dba972c7daa57d5e677f7a1327edfd)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define BTSTACK_FILE__ "att_db.c"
39 
40 #include <string.h>
41 
42 #include "ble/att_db.h"
43 #include "ble/core.h"
44 #include "bluetooth.h"
45 #include "btstack_debug.h"
46 #include "btstack_util.h"
47 
48 // check for ENABLE_ATT_DELAYED_READ_RESPONSE -> ENABLE_ATT_DELAYED_RESPONSE,
49 #ifdef ENABLE_ATT_DELAYED_READ_RESPONSE
50     #error "ENABLE_ATT_DELAYED_READ_RESPONSE was replaced by ENABLE_ATT_DELAYED_RESPONSE. Please update btstack_config.h"
51 #endif
52 
53 typedef enum {
54     ATT_READ,
55     ATT_WRITE,
56 } att_operation_t;
57 
58 // Buetooth Base UUID 00000000-0000-1000-8000-00805F9B34FB in little endian
59 static const uint8_t bluetooth_base_uuid[] = { 0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
60 
61 
62 static int is_Bluetooth_Base_UUID(uint8_t const *uuid){
63     if (memcmp(&uuid[0],  &bluetooth_base_uuid[0], 12) != 0) return false;
64     if (memcmp(&uuid[14], &bluetooth_base_uuid[14], 2) != 0) return false;
65     return true;
66 
67 }
68 
69 static uint16_t uuid16_from_uuid(uint16_t uuid_len, uint8_t * uuid){
70     if (uuid_len == 2) return little_endian_read_16(uuid, 0);
71     if (!is_Bluetooth_Base_UUID(uuid)) return 0;
72     return little_endian_read_16(uuid, 12);
73 }
74 
75 // ATT Database
76 
77 // new java-style iterator
78 typedef struct att_iterator {
79     // private
80     uint8_t const * att_ptr;
81     // public
82     uint16_t size;
83     uint16_t flags;
84     uint16_t handle;
85     uint8_t  const * uuid;
86     uint16_t value_len;
87     uint8_t  const * value;
88 } att_iterator_t;
89 
90 static void att_persistent_ccc_cache(att_iterator_t * it);
91 
92 static uint8_t const * att_db = NULL;
93 static att_read_callback_t  att_read_callback  = NULL;
94 static att_write_callback_t att_write_callback = NULL;
95 static int      att_prepare_write_error_code   = 0;
96 static uint16_t att_prepare_write_error_handle = 0x0000;
97 
98 // single cache for att_is_persistent_ccc - stores flags before write callback
99 static uint16_t att_persistent_ccc_handle;
100 static uint16_t att_persistent_ccc_uuid16;
101 
102 static void att_iterator_init(att_iterator_t *it){
103     it->att_ptr = att_db;
104 }
105 
106 static bool att_iterator_has_next(att_iterator_t *it){
107     return it->att_ptr != NULL;
108 }
109 
110 static void att_iterator_fetch_next(att_iterator_t *it){
111     it->size   = little_endian_read_16(it->att_ptr, 0);
112     if (it->size == 0){
113         it->flags = 0;
114         it->handle = 0;
115         it->uuid = NULL;
116         it->value_len = 0;
117         it->value = NULL;
118         it->att_ptr = NULL;
119         return;
120     }
121     it->flags  = little_endian_read_16(it->att_ptr, 2);
122     it->handle = little_endian_read_16(it->att_ptr, 4);
123     it->uuid   = &it->att_ptr[6];
124     // handle 128 bit UUIDs
125     if ((it->flags & ATT_PROPERTY_UUID128) != 0){
126         it->value_len = it->size - 22;
127         it->value  = &it->att_ptr[22];
128     } else {
129         it->value_len = it->size - 8;
130         it->value  = &it->att_ptr[8];
131     }
132     // advance AFTER setting values
133     it->att_ptr += it->size;
134 }
135 
136 static int att_iterator_match_uuid16(att_iterator_t *it, uint16_t uuid){
137     if (it->handle == 0) return 0;
138     if (it->flags & ATT_PROPERTY_UUID128){
139         if (!is_Bluetooth_Base_UUID(it->uuid)) return 0;
140         return little_endian_read_16(it->uuid, 12) == uuid;
141     }
142     return little_endian_read_16(it->uuid, 0)  == uuid;
143 }
144 
145 static int att_iterator_match_uuid(att_iterator_t *it, uint8_t *uuid, uint16_t uuid_len){
146     if (it->handle == 0) return 0;
147     // input: UUID16
148     if (uuid_len == 2) {
149         return att_iterator_match_uuid16(it, little_endian_read_16(uuid, 0));
150     }
151     // input and db: UUID128
152     if ((it->flags & ATT_PROPERTY_UUID128) != 0){
153         return memcmp(it->uuid, uuid, 16) == 0;
154     }
155     // input: UUID128, db: UUID16
156     if (!is_Bluetooth_Base_UUID(uuid)) return 0;
157     return little_endian_read_16(uuid, 12) == little_endian_read_16(it->uuid, 0);
158 }
159 
160 
161 static int att_find_handle(att_iterator_t *it, uint16_t handle){
162     if (handle == 0) return 0;
163     att_iterator_init(it);
164     while (att_iterator_has_next(it)){
165         att_iterator_fetch_next(it);
166         if (it->handle != handle) continue;
167         return 1;
168     }
169     return 0;
170 }
171 
172 // experimental client API
173 uint16_t att_uuid_for_handle(uint16_t attribute_handle){
174     att_iterator_t it;
175     int ok = att_find_handle(&it, attribute_handle);
176     if (!ok) return 0;
177     if ((it.flags & ATT_PROPERTY_UUID128) != 0) return 0;
178     return little_endian_read_16(it.uuid, 0);
179 }
180 // end of client API
181 
182 static void att_update_value_len(att_iterator_t *it, hci_con_handle_t con_handle){
183     if ((it->flags & ATT_PROPERTY_DYNAMIC) == 0) return;
184     it->value_len = (*att_read_callback)(con_handle, it->handle, 0, NULL, 0);
185     return;
186 }
187 
188 // copy attribute value from offset into buffer with given size
189 static int att_copy_value(att_iterator_t *it, uint16_t offset, uint8_t * buffer, uint16_t buffer_size, hci_con_handle_t con_handle){
190 
191     // DYNAMIC
192     if ((it->flags & ATT_PROPERTY_DYNAMIC) != 0){
193         return (*att_read_callback)(con_handle, it->handle, offset, buffer, buffer_size);
194     }
195 
196     // STATIC
197     uint16_t bytes_to_copy = it->value_len - offset;
198     if (bytes_to_copy > buffer_size){
199         bytes_to_copy = buffer_size;
200     }
201     (void)memcpy(buffer, it->value, bytes_to_copy);
202     return bytes_to_copy;
203 }
204 
205 void att_set_db(uint8_t const * db){
206     // validate db version
207     if (db == NULL) return;
208     if (*db++ != ATT_DB_VERSION){
209         log_error("ATT DB version differs, please regenerate .h from .gatt file or update att_db_util.c");
210         return;
211     }
212     att_db = db;
213 }
214 
215 void att_set_read_callback(att_read_callback_t callback){
216     att_read_callback = callback;
217 }
218 
219 void att_set_write_callback(att_write_callback_t callback){
220     att_write_callback = callback;
221 }
222 
223 void att_dump_attributes(void){
224     att_iterator_t it;
225     att_iterator_init(&it);
226     uint8_t uuid128[16];
227     while (att_iterator_has_next(&it)){
228         att_iterator_fetch_next(&it);
229         if (it.handle == 0) {
230             log_info("Handle: END");
231             return;
232         }
233         log_info("Handle: 0x%04x, flags: 0x%04x, uuid: ", it.handle, it.flags);
234         if ((it.flags & ATT_PROPERTY_UUID128) != 0){
235             reverse_128(it.uuid, uuid128);
236             log_info("%s", uuid128_to_str(uuid128));
237         } else {
238             log_info("%04x", little_endian_read_16(it.uuid, 0));
239         }
240         log_info(", value_len: %u, value: ", it.value_len);
241         log_info_hexdump(it.value, it.value_len);
242     }
243 }
244 
245 static void att_prepare_write_reset(void){
246     att_prepare_write_error_code = 0;
247     att_prepare_write_error_handle = 0x0000;
248 }
249 
250 static void att_prepare_write_update_errors(uint8_t error_code, uint16_t handle){
251     // first ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH has highest priority
252     if ((error_code == ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH) && (error_code != att_prepare_write_error_code)){
253         att_prepare_write_error_code = error_code;
254         att_prepare_write_error_handle = handle;
255         return;
256     }
257     // first ATT_ERROR_INVALID_OFFSET is next
258     if ((error_code == ATT_ERROR_INVALID_OFFSET) && (att_prepare_write_error_code == 0)){
259         att_prepare_write_error_code = error_code;
260         att_prepare_write_error_handle = handle;
261         return;
262     }
263 }
264 
265 static uint16_t setup_error(uint8_t * response_buffer, uint16_t request, uint16_t handle, uint8_t error_code){
266     response_buffer[0] = ATT_ERROR_RESPONSE;
267     response_buffer[1] = request;
268     little_endian_store_16(response_buffer, 2, handle);
269     response_buffer[4] = error_code;
270     return 5;
271 }
272 
273 static inline uint16_t setup_error_read_not_permitted(uint8_t * response_buffer, uint16_t request, uint16_t start_handle){
274     return setup_error(response_buffer, request, start_handle, ATT_ERROR_READ_NOT_PERMITTED);
275 }
276 
277 static inline uint16_t setup_error_write_not_permitted(uint8_t * response_buffer, uint16_t request, uint16_t start_handle){
278     return setup_error(response_buffer, request, start_handle, ATT_ERROR_WRITE_NOT_PERMITTED);
279 }
280 
281 static inline uint16_t setup_error_atribute_not_found(uint8_t * response_buffer, uint16_t request, uint16_t start_handle){
282     return setup_error(response_buffer, request, start_handle, ATT_ERROR_ATTRIBUTE_NOT_FOUND);
283 }
284 
285 static inline uint16_t setup_error_invalid_handle(uint8_t * response_buffer, uint16_t request, uint16_t handle){
286     return setup_error(response_buffer, request, handle, ATT_ERROR_INVALID_HANDLE);
287 }
288 
289 static inline uint16_t setup_error_invalid_offset(uint8_t * response_buffer, uint16_t request, uint16_t handle){
290     return setup_error(response_buffer, request, handle, ATT_ERROR_INVALID_OFFSET);
291 }
292 
293 static uint8_t att_validate_security(att_connection_t * att_connection, att_operation_t operation, att_iterator_t * it){
294     int required_security_level = 0;
295     int requires_secure_connection = 0;
296     switch (operation){
297         case ATT_READ:
298             if ((it->flags & ATT_PROPERTY_READ_PERMISSION_BIT_0) != 0){
299                 required_security_level |= 1;
300             }
301             if ((it->flags & ATT_PROPERTY_READ_PERMISSION_BIT_1) != 0){
302                 required_security_level |= 2;
303             }
304             if ((it->flags & ATT_PROPERTY_READ_PERMISSION_SC) != 0){
305                 requires_secure_connection = 1;
306             }
307             break;
308         case ATT_WRITE:
309             if ((it->flags & ATT_PROPERTY_WRITE_PERMISSION_BIT_0) != 0){
310                 required_security_level |= 1;
311             }
312             if ((it->flags & ATT_PROPERTY_WRITE_PERMISSION_BIT_1) != 0){
313                 required_security_level |= 2;
314             }
315             if ((it->flags & ATT_PROPERTY_WRITE_PERMISSION_SC) != 0){
316                 requires_secure_connection = 1;
317             }
318             break;
319     }
320 
321     int required_encryption_size = it->flags >> 12;
322     if (required_encryption_size != 0) required_encryption_size++;   // store -1 to fit into 4 bit
323 
324     log_debug("att_validate_security. flags 0x%04x (=> security level %u, key size %u) authorized %u, authenticated %u, encryption_key_size %u, secure connection %u",
325         it->flags, required_security_level, required_encryption_size, att_connection->authorized, att_connection->authenticated, att_connection->encryption_key_size, att_connection->secure_connection);
326 
327     int sc_missing = requires_secure_connection && (att_connection->secure_connection == 0);
328     switch (required_security_level){
329         case ATT_SECURITY_AUTHORIZED:
330             if ((att_connection->authorized == 0) || sc_missing){
331                 return ATT_ERROR_INSUFFICIENT_AUTHORIZATION;
332             }
333             /* explicit fall through */
334         case ATT_SECURITY_AUTHENTICATED:
335             if ((att_connection->authenticated == 0) || sc_missing){
336                 return ATT_ERROR_INSUFFICIENT_AUTHENTICATION;
337             }
338             /* explicit fall through */
339         case ATT_SECURITY_ENCRYPTED:
340             if ((required_encryption_size > 0) && ((att_connection->encryption_key_size == 0) || sc_missing)){
341                 return ATT_ERROR_INSUFFICIENT_ENCRYPTION;
342             }
343             if (required_encryption_size > att_connection->encryption_key_size){
344                 return ATT_ERROR_INSUFFICIENT_ENCRYPTION_KEY_SIZE;
345             }
346             break;
347         default:
348             break;
349     }
350     return ATT_ERROR_SUCCESS;
351 }
352 
353 //
354 // MARK: ATT_EXCHANGE_MTU_REQUEST
355 //
356 static uint16_t handle_exchange_mtu_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
357                                          uint8_t * response_buffer){
358 
359     UNUSED(request_len);
360 
361     uint16_t client_rx_mtu = little_endian_read_16(request_buffer, 1);
362 
363     // find min(local max mtu, remote mtu) and use as mtu for this connection
364     if (client_rx_mtu < att_connection->max_mtu){
365         att_connection->mtu = client_rx_mtu;
366     } else {
367         att_connection->mtu = att_connection->max_mtu;
368     }
369 
370     response_buffer[0] = ATT_EXCHANGE_MTU_RESPONSE;
371     little_endian_store_16(response_buffer, 1, att_connection->mtu);
372     return 3;
373 }
374 
375 
376 //
377 // MARK: ATT_FIND_INFORMATION_REQUEST
378 //
379 // TODO: handle other types then GATT_PRIMARY_SERVICE_UUID and GATT_SECONDARY_SERVICE_UUID
380 //
381 static uint16_t handle_find_information_request2(att_connection_t * att_connection, uint8_t * response_buffer, uint16_t response_buffer_size,
382                                            uint16_t start_handle, uint16_t end_handle){
383 
384     UNUSED(att_connection);
385 
386     log_info("ATT_FIND_INFORMATION_REQUEST: from %04X to %04X", start_handle, end_handle);
387     uint8_t request_type = ATT_FIND_INFORMATION_REQUEST;
388 
389     if ((start_handle > end_handle) || (start_handle == 0)){
390         return setup_error_invalid_handle(response_buffer, request_type, start_handle);
391     }
392 
393     uint16_t offset   = 1;
394     uint16_t uuid_len = 0;
395 
396     att_iterator_t it;
397     att_iterator_init(&it);
398     while (att_iterator_has_next(&it)){
399         att_iterator_fetch_next(&it);
400         if (!it.handle) break;
401         if (it.handle > end_handle) break;
402         if (it.handle < start_handle) continue;
403 
404         // log_info("Handle 0x%04x", it.handle);
405 
406         uint16_t this_uuid_len = (it.flags & ATT_PROPERTY_UUID128) ? 16 : 2;
407 
408         // check if value has same len as last one if not first result
409         if (offset > 1){
410             if (this_uuid_len != uuid_len) {
411                 break;
412             }
413         }
414 
415         // first
416         if (offset == 1) {
417             uuid_len = this_uuid_len;
418             // set format field
419             response_buffer[offset] = (it.flags & ATT_PROPERTY_UUID128) ? 0x02 : 0x01;
420             offset++;
421         }
422 
423         // space?
424         if ((offset + 2 + uuid_len) > response_buffer_size) break;
425 
426         // store
427         little_endian_store_16(response_buffer, offset, it.handle);
428         offset += 2;
429 
430         (void)memcpy(response_buffer + offset, it.uuid, uuid_len);
431         offset += uuid_len;
432     }
433 
434     if (offset == 1){
435         return setup_error_atribute_not_found(response_buffer, request_type, start_handle);
436     }
437 
438     response_buffer[0] = ATT_FIND_INFORMATION_REPLY;
439     return offset;
440 }
441 
442 static uint16_t handle_find_information_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
443                                          uint8_t * response_buffer, uint16_t response_buffer_size){
444     UNUSED(request_len);
445     return handle_find_information_request2(att_connection, response_buffer, response_buffer_size, little_endian_read_16(request_buffer, 1), little_endian_read_16(request_buffer, 3));
446 }
447 
448 //
449 // MARK: ATT_FIND_BY_TYPE_VALUE
450 //
451 // "Only attributes with attribute handles between and including the Starting Handle parameter
452 // and the Ending Handle parameter that match the requested attri- bute type and the attribute
453 // value that have sufficient permissions to allow reading will be returned" -> (1)
454 //
455 // TODO: handle other types then GATT_PRIMARY_SERVICE_UUID and GATT_SECONDARY_SERVICE_UUID
456 //
457 // NOTE: doesn't handle DYNAMIC values
458 // NOTE: only supports 16 bit UUIDs
459 //
460 static uint16_t handle_find_by_type_value_request2(att_connection_t * att_connection, uint8_t * response_buffer, uint16_t response_buffer_size,
461                                            uint16_t start_handle, uint16_t end_handle,
462                                            uint16_t attribute_type, uint16_t attribute_len, uint8_t* attribute_value){
463 
464     UNUSED(att_connection);
465 
466     log_info("ATT_FIND_BY_TYPE_VALUE_REQUEST: from %04X to %04X, type %04X, value: ", start_handle, end_handle, attribute_type);
467     log_info_hexdump(attribute_value, attribute_len);
468     uint8_t request_type = ATT_FIND_BY_TYPE_VALUE_REQUEST;
469 
470     if ((start_handle > end_handle) || (start_handle == 0)){
471         return setup_error_invalid_handle(response_buffer, request_type, start_handle);
472     }
473 
474     uint16_t offset      = 1;
475     uint16_t in_group    = 0;
476     uint16_t prev_handle = 0;
477 
478     att_iterator_t it;
479     att_iterator_init(&it);
480     while (att_iterator_has_next(&it)){
481         att_iterator_fetch_next(&it);
482 
483         if (it.handle && (it.handle < start_handle)) continue;
484         if (it.handle > end_handle) break;  // (1)
485 
486         // close current tag, if within a group and a new service definition starts or we reach end of att db
487         if (in_group &&
488             ((it.handle == 0) || att_iterator_match_uuid16(&it, GATT_PRIMARY_SERVICE_UUID) || att_iterator_match_uuid16(&it, GATT_SECONDARY_SERVICE_UUID))){
489 
490             log_info("End of group, handle 0x%04x", prev_handle);
491             little_endian_store_16(response_buffer, offset, prev_handle);
492             offset += 2;
493             in_group = 0;
494 
495             // check if space for another handle pair available
496             if ((offset + 4) > response_buffer_size){
497                 break;
498             }
499         }
500 
501         // keep track of previous handle
502         prev_handle = it.handle;
503 
504         // does current attribute match
505         if (it.handle && att_iterator_match_uuid16(&it, attribute_type) && (attribute_len == it.value_len) && (memcmp(attribute_value, it.value, it.value_len) == 0)){
506             log_info("Begin of group, handle 0x%04x", it.handle);
507             little_endian_store_16(response_buffer, offset, it.handle);
508             offset += 2;
509             in_group = 1;
510         }
511     }
512 
513     if (offset == 1){
514         return setup_error_atribute_not_found(response_buffer, request_type, start_handle);
515     }
516 
517     response_buffer[0] = ATT_FIND_BY_TYPE_VALUE_RESPONSE;
518     return offset;
519 }
520 
521 static uint16_t handle_find_by_type_value_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
522                                            uint8_t * response_buffer, uint16_t response_buffer_size){
523     int attribute_len = request_len - 7;
524     return handle_find_by_type_value_request2(att_connection, response_buffer, response_buffer_size, little_endian_read_16(request_buffer, 1),
525                                               little_endian_read_16(request_buffer, 3), little_endian_read_16(request_buffer, 5), attribute_len, &request_buffer[7]);
526 }
527 
528 //
529 // MARK: ATT_READ_BY_TYPE_REQUEST
530 //
531 static uint16_t handle_read_by_type_request2(att_connection_t * att_connection, uint8_t * response_buffer, uint16_t response_buffer_size,
532                                       uint16_t start_handle, uint16_t end_handle,
533                                       uint16_t attribute_type_len, uint8_t * attribute_type){
534 
535     log_info("ATT_READ_BY_TYPE_REQUEST: from %04X to %04X, type: ", start_handle, end_handle);
536     log_info_hexdump(attribute_type, attribute_type_len);
537     uint8_t request_type = ATT_READ_BY_TYPE_REQUEST;
538 
539     if ((start_handle > end_handle) || (start_handle == 0)){
540         return setup_error_invalid_handle(response_buffer, request_type, start_handle);
541     }
542 
543     uint16_t offset   = 1;
544     uint16_t pair_len = 0;
545 
546     att_iterator_t it;
547     att_iterator_init(&it);
548     uint8_t error_code = 0;
549     uint16_t first_matching_but_unreadable_handle = 0;
550 
551 #ifdef ENABLE_ATT_DELAYED_RESPONSE
552     bool read_request_pending = false;
553 #endif
554 
555     while (att_iterator_has_next(&it)){
556         att_iterator_fetch_next(&it);
557 
558         if (!it.handle) break;
559         if (it.handle < start_handle) continue;
560         if (it.handle > end_handle) break;  // (1)
561 
562         // does current attribute match
563         if (!att_iterator_match_uuid(&it, attribute_type, attribute_type_len)) continue;
564 
565         // skip handles that cannot be read but rembember that there has been at least one
566         if ((it.flags & ATT_PROPERTY_READ) == 0) {
567             if (first_matching_but_unreadable_handle == 0) {
568                 first_matching_but_unreadable_handle = it.handle;
569             }
570             continue;
571         }
572 
573         // check security requirements
574         error_code = att_validate_security(att_connection, ATT_READ, &it);
575         if (error_code != 0) break;
576 
577         att_update_value_len(&it, att_connection->con_handle);
578 
579 #ifdef ENABLE_ATT_DELAYED_RESPONSE
580         if (it.value_len == ATT_READ_RESPONSE_PENDING){
581             read_request_pending = true;
582         }
583         if (read_request_pending) continue;
584 #endif
585 
586         // check if value has same len as last one
587         uint16_t this_pair_len = 2 + it.value_len;
588         if (offset > 1){
589             if (pair_len != this_pair_len) {
590                 break;
591             }
592         }
593 
594         // first
595         if (offset == 1) {
596             pair_len = this_pair_len;
597             response_buffer[offset] = pair_len;
598             offset++;
599         }
600 
601         // space?
602         if ((offset + pair_len) > response_buffer_size) {
603             if (offset > 2) break;
604             it.value_len = response_buffer_size - 4;
605             response_buffer[1] = 2 + it.value_len;
606         }
607 
608         // store
609         little_endian_store_16(response_buffer, offset, it.handle);
610         offset += 2;
611         uint16_t bytes_copied = att_copy_value(&it, 0, response_buffer + offset, it.value_len, att_connection->con_handle);
612         offset += bytes_copied;
613     }
614 
615 #ifdef ENABLE_ATT_DELAYED_RESPONSE
616     if (read_request_pending) return ATT_READ_RESPONSE_PENDING;
617 #endif
618 
619     // at least one attribute could be read
620     if (offset > 1){
621         response_buffer[0] = ATT_READ_BY_TYPE_RESPONSE;
622         return offset;
623     }
624 
625     // first attribute had an error
626     if (error_code != 0){
627         return setup_error(response_buffer, request_type, start_handle, error_code);
628     }
629 
630     // no other errors, but all found attributes had been non-readable
631     if (first_matching_but_unreadable_handle != 0){
632         return setup_error_read_not_permitted(response_buffer, request_type, first_matching_but_unreadable_handle);
633     }
634 
635     // attribute not found
636     return setup_error_atribute_not_found(response_buffer, request_type, start_handle);
637 }
638 
639 static uint16_t handle_read_by_type_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
640                                      uint8_t * response_buffer, uint16_t response_buffer_size){
641     int attribute_type_len;
642     if (request_len <= 7){
643         attribute_type_len = 2;
644     } else {
645         attribute_type_len = 16;
646     }
647     return handle_read_by_type_request2(att_connection, response_buffer, response_buffer_size, little_endian_read_16(request_buffer, 1), little_endian_read_16(request_buffer, 3), attribute_type_len, &request_buffer[5]);
648 }
649 
650 //
651 // MARK: ATT_READ_BY_TYPE_REQUEST
652 //
653 static uint16_t handle_read_request2(att_connection_t * att_connection, uint8_t * response_buffer, uint16_t response_buffer_size, uint16_t handle){
654 
655     log_info("ATT_READ_REQUEST: handle %04x", handle);
656     uint8_t request_type = ATT_READ_REQUEST;
657 
658     att_iterator_t it;
659     int ok = att_find_handle(&it, handle);
660     if (!ok){
661         return setup_error_invalid_handle(response_buffer, request_type, handle);
662     }
663 
664     // check if handle can be read
665     if ((it.flags & ATT_PROPERTY_READ) == 0) {
666         return setup_error_read_not_permitted(response_buffer, request_type, handle);
667     }
668 
669     // check security requirements
670     uint8_t error_code = att_validate_security(att_connection, ATT_READ, &it);
671     if (error_code) {
672         return setup_error(response_buffer, request_type, handle, error_code);
673     }
674 
675     att_update_value_len(&it, att_connection->con_handle);
676 
677 #ifdef ENABLE_ATT_DELAYED_RESPONSE
678     if (it.value_len == ATT_READ_RESPONSE_PENDING) return ATT_READ_RESPONSE_PENDING;
679 #endif
680 
681     uint16_t offset   = 1;
682     // limit data
683     if ((offset + it.value_len) > response_buffer_size) {
684         it.value_len = response_buffer_size - 1;
685     }
686 
687     // store
688     uint16_t bytes_copied = att_copy_value(&it, 0, response_buffer + offset, it.value_len, att_connection->con_handle);
689     offset += bytes_copied;
690 
691     response_buffer[0] = ATT_READ_RESPONSE;
692     return offset;
693 }
694 
695 static uint16_t handle_read_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
696                              uint8_t * response_buffer, uint16_t response_buffer_size){
697     UNUSED(request_len);
698     return handle_read_request2(att_connection, response_buffer, response_buffer_size, little_endian_read_16(request_buffer, 1));
699 }
700 
701 //
702 // MARK: ATT_READ_BLOB_REQUEST 0x0c
703 //
704 static uint16_t handle_read_blob_request2(att_connection_t * att_connection, uint8_t * response_buffer, uint16_t response_buffer_size, uint16_t handle, uint16_t value_offset){
705     log_info("ATT_READ_BLOB_REQUEST: handle %04x, offset %u", handle, value_offset);
706     uint8_t request_type = ATT_READ_BLOB_REQUEST;
707 
708     att_iterator_t it;
709     int ok = att_find_handle(&it, handle);
710     if (!ok){
711         return setup_error_invalid_handle(response_buffer, request_type, handle);
712     }
713 
714     // check if handle can be read
715     if ((it.flags & ATT_PROPERTY_READ) == 0) {
716         return setup_error_read_not_permitted(response_buffer, request_type, handle);
717     }
718 
719     // check security requirements
720     uint8_t error_code = att_validate_security(att_connection, ATT_READ, &it);
721     if (error_code) {
722         return setup_error(response_buffer, request_type, handle, error_code);
723     }
724 
725     att_update_value_len(&it, att_connection->con_handle);
726 
727 #ifdef ENABLE_ATT_DELAYED_RESPONSE
728     if (it.value_len == ATT_READ_RESPONSE_PENDING) return ATT_READ_RESPONSE_PENDING;
729 #endif
730 
731     if (value_offset > it.value_len){
732         return setup_error_invalid_offset(response_buffer, request_type, handle);
733     }
734 
735     // limit data
736     uint16_t offset   = 1;
737     if ((offset + it.value_len - value_offset) > response_buffer_size) {
738         it.value_len = response_buffer_size - 1 + value_offset;
739     }
740 
741     // store
742     uint16_t bytes_copied = att_copy_value(&it, value_offset, response_buffer + offset, it.value_len - value_offset, att_connection->con_handle);
743     offset += bytes_copied;
744 
745     response_buffer[0] = ATT_READ_BLOB_RESPONSE;
746     return offset;
747 }
748 
749 static uint16_t handle_read_blob_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
750                                   uint8_t * response_buffer, uint16_t response_buffer_size){
751     UNUSED(request_len);
752     return handle_read_blob_request2(att_connection, response_buffer, response_buffer_size, little_endian_read_16(request_buffer, 1), little_endian_read_16(request_buffer, 3));
753 }
754 
755 //
756 // MARK: ATT_READ_MULTIPLE_REQUEST 0x0e
757 //
758 static uint16_t handle_read_multiple_request2(att_connection_t * att_connection, uint8_t * response_buffer, uint16_t response_buffer_size, uint16_t num_handles, uint8_t * handles){
759     log_info("ATT_READ_MULTIPLE_REQUEST: num handles %u", num_handles);
760     uint8_t request_type = ATT_READ_MULTIPLE_REQUEST;
761 
762     // TODO: figure out which error to respond with
763     // if (num_handles < 2){
764     //     return setup_error(response_buffer, ATT_READ_MULTIPLE_REQUEST, handle, ???);
765     // }
766 
767     uint16_t offset   = 1;
768 
769     int i;
770     uint8_t error_code = 0;
771     uint16_t handle = 0;
772 
773 #ifdef ENABLE_ATT_DELAYED_RESPONSE
774     bool read_request_pending = false;
775 #endif
776 
777     for (i=0;i<num_handles;i++){
778         handle = little_endian_read_16(handles, i << 1);
779 
780         if (handle == 0){
781             return setup_error_invalid_handle(response_buffer, request_type, handle);
782         }
783 
784         att_iterator_t it;
785 
786         int ok = att_find_handle(&it, handle);
787         if (!ok){
788             return setup_error_invalid_handle(response_buffer, request_type, handle);
789         }
790 
791         // check if handle can be read
792         if ((it.flags & ATT_PROPERTY_READ) == 0) {
793             error_code = ATT_ERROR_READ_NOT_PERMITTED;
794             break;
795         }
796 
797         // check security requirements
798         error_code = att_validate_security(att_connection, ATT_READ, &it);
799         if (error_code) break;
800 
801         att_update_value_len(&it, att_connection->con_handle);
802 
803 #ifdef ENABLE_ATT_DELAYED_RESPONSE
804         if (it.value_len == ATT_READ_RESPONSE_PENDING) {
805             read_request_pending = true;
806         }
807         if (read_request_pending) continue;
808 #endif
809 
810         // limit data
811         if ((offset + it.value_len) > response_buffer_size) {
812             it.value_len = response_buffer_size - 1;
813         }
814 
815         // store
816         uint16_t bytes_copied = att_copy_value(&it, 0, response_buffer + offset, it.value_len, att_connection->con_handle);
817         offset += bytes_copied;
818     }
819 
820     if (error_code){
821         return setup_error(response_buffer, request_type, handle, error_code);
822     }
823 
824     response_buffer[0] = ATT_READ_MULTIPLE_RESPONSE;
825     return offset;
826 }
827 static uint16_t handle_read_multiple_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
828                                       uint8_t * response_buffer, uint16_t response_buffer_size){
829     int num_handles = (request_len - 1) >> 1;
830     return handle_read_multiple_request2(att_connection, response_buffer, response_buffer_size, num_handles, &request_buffer[1]);
831 }
832 
833 //
834 // MARK: ATT_READ_BY_GROUP_TYPE_REQUEST 0x10
835 //
836 // Only handles GATT_PRIMARY_SERVICE_UUID and GATT_SECONDARY_SERVICE_UUID
837 // Core v4.0, vol 3, part g, 2.5.3
838 // "The «Primary Service» and «Secondary Service» grouping types may be used in the Read By Group Type Request.
839 //  The «Characteristic» grouping type shall not be used in the ATT Read By Group Type Request."
840 //
841 // NOTE: doesn't handle DYNAMIC values
842 //
843 // NOTE: we don't check for security as PRIMARY and SECONDAY SERVICE definition shouldn't be protected
844 // Core 4.0, vol 3, part g, 8.1
845 // "The list of services and characteristics that a device supports is not considered private or
846 //  confidential information, and therefore the Service and Characteristic Discovery procedures
847 //  shall always be permitted. "
848 //
849 static uint16_t handle_read_by_group_type_request2(att_connection_t * att_connection, uint8_t * response_buffer, uint16_t response_buffer_size,
850                                             uint16_t start_handle, uint16_t end_handle,
851                                             uint16_t attribute_type_len, uint8_t * attribute_type){
852 
853     UNUSED(att_connection);
854 
855     log_info("ATT_READ_BY_GROUP_TYPE_REQUEST: from %04X to %04X, buffer size %u, type: ", start_handle, end_handle, response_buffer_size);
856     log_info_hexdump(attribute_type, attribute_type_len);
857     uint8_t request_type = ATT_READ_BY_GROUP_TYPE_REQUEST;
858 
859     if ((start_handle > end_handle) || (start_handle == 0)){
860         return setup_error_invalid_handle(response_buffer, request_type, start_handle);
861     }
862 
863     // assert UUID is primary or secondary service uuid
864     uint16_t uuid16 = uuid16_from_uuid(attribute_type_len, attribute_type);
865     if ((uuid16 != GATT_PRIMARY_SERVICE_UUID) && (uuid16 != GATT_SECONDARY_SERVICE_UUID)){
866         return setup_error(response_buffer, request_type, start_handle, ATT_ERROR_UNSUPPORTED_GROUP_TYPE);
867     }
868 
869     uint16_t offset   = 1;
870     uint16_t pair_len = 0;
871     uint16_t in_group = 0;
872     uint16_t group_start_handle = 0;
873     uint8_t const * group_start_value = NULL;
874     uint16_t prev_handle = 0;
875 
876     att_iterator_t it;
877     att_iterator_init(&it);
878     while (att_iterator_has_next(&it)){
879         att_iterator_fetch_next(&it);
880 
881         if (it.handle && (it.handle < start_handle)) continue;
882         if (it.handle > end_handle) break;  // (1)
883 
884         // log_info("Handle 0x%04x", it.handle);
885 
886         // close current tag, if within a group and a new service definition starts or we reach end of att db
887         if (in_group &&
888             ((it.handle == 0) || att_iterator_match_uuid16(&it, GATT_PRIMARY_SERVICE_UUID) || att_iterator_match_uuid16(&it, GATT_SECONDARY_SERVICE_UUID))){
889             // log_info("End of group, handle 0x%04x, val_len: %u", prev_handle, pair_len - 4);
890 
891             little_endian_store_16(response_buffer, offset, group_start_handle);
892             offset += 2;
893             little_endian_store_16(response_buffer, offset, prev_handle);
894             offset += 2;
895             (void)memcpy(response_buffer + offset, group_start_value,
896                          pair_len - 4);
897             offset += pair_len - 4;
898             in_group = 0;
899 
900             // check if space for another handle pair available
901             if ((offset + pair_len) > response_buffer_size){
902                 break;
903             }
904         }
905 
906         // keep track of previous handle
907         prev_handle = it.handle;
908 
909         // does current attribute match
910         // log_info("compare: %04x == %04x", *(uint16_t*) context->attribute_type, *(uint16_t*) uuid);
911         if (it.handle && att_iterator_match_uuid(&it, attribute_type, attribute_type_len)) {
912 
913             // check if value has same len as last one
914             uint16_t this_pair_len = 4 + it.value_len;
915             if (offset > 1){
916                 if (this_pair_len != pair_len) {
917                     break;
918                 }
919             }
920 
921             // log_info("Begin of group, handle 0x%04x", it.handle);
922 
923             // first
924             if (offset == 1) {
925                 pair_len = this_pair_len;
926                 response_buffer[offset] = this_pair_len;
927                 offset++;
928             }
929 
930             group_start_handle = it.handle;
931             group_start_value  = it.value;
932             in_group = 1;
933         }
934     }
935 
936     if (offset == 1){
937         return setup_error_atribute_not_found(response_buffer, request_type, start_handle);
938     }
939 
940     response_buffer[0] = ATT_READ_BY_GROUP_TYPE_RESPONSE;
941     return offset;
942 }
943 static uint16_t handle_read_by_group_type_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
944                                            uint8_t * response_buffer, uint16_t response_buffer_size){
945     int attribute_type_len;
946     if (request_len <= 7){
947         attribute_type_len = 2;
948     } else {
949         attribute_type_len = 16;
950     }
951     return handle_read_by_group_type_request2(att_connection, response_buffer, response_buffer_size, little_endian_read_16(request_buffer, 1), little_endian_read_16(request_buffer, 3), attribute_type_len, &request_buffer[5]);
952 }
953 
954 //
955 // MARK: ATT_WRITE_REQUEST 0x12
956 static uint16_t handle_write_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
957                               uint8_t * response_buffer, uint16_t response_buffer_size){
958 
959     UNUSED(response_buffer_size);
960 
961     uint8_t request_type = ATT_WRITE_REQUEST;
962 
963     uint16_t handle = little_endian_read_16(request_buffer, 1);
964     att_iterator_t it;
965     int ok = att_find_handle(&it, handle);
966     if (!ok) {
967         return setup_error_invalid_handle(response_buffer, request_type, handle);
968     }
969     if (att_write_callback == NULL) {
970         return setup_error_write_not_permitted(response_buffer, request_type, handle);
971     }
972     if ((it.flags & ATT_PROPERTY_WRITE) == 0) {
973         return setup_error_write_not_permitted(response_buffer, request_type, handle);
974     }
975     if ((it.flags & ATT_PROPERTY_DYNAMIC) == 0) {
976         return setup_error_write_not_permitted(response_buffer, request_type, handle);
977     }
978     // check security requirements
979     int error_code = att_validate_security(att_connection, ATT_WRITE, &it);
980     if (error_code) {
981         return setup_error(response_buffer, request_type, handle, error_code);
982     }
983     att_persistent_ccc_cache(&it);
984     error_code = (*att_write_callback)(att_connection->con_handle, handle, ATT_TRANSACTION_MODE_NONE, 0, request_buffer + 3, request_len - 3);
985 
986 #ifdef ENABLE_ATT_DELAYED_RESPONSE
987     if (error_code == ATT_ERROR_WRITE_RESPONSE_PENDING) return ATT_INTERNAL_WRITE_RESPONSE_PENDING;
988 #endif
989 
990     if (error_code) {
991         return setup_error(response_buffer, request_type, handle, error_code);
992     }
993     response_buffer[0] = ATT_WRITE_RESPONSE;
994     return 1;
995 }
996 
997 //
998 // MARK: ATT_PREPARE_WRITE_REQUEST 0x16
999 static uint16_t handle_prepare_write_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
1000                                       uint8_t * response_buffer, uint16_t response_buffer_size){
1001 
1002     UNUSED(response_buffer_size);
1003 
1004     uint8_t request_type = ATT_PREPARE_WRITE_REQUEST;
1005 
1006     uint16_t handle = little_endian_read_16(request_buffer, 1);
1007     uint16_t offset = little_endian_read_16(request_buffer, 3);
1008     if (att_write_callback == NULL) {
1009         return setup_error_write_not_permitted(response_buffer, request_type, handle);
1010     }
1011     att_iterator_t it;
1012     if (att_find_handle(&it, handle) == 0) {
1013         return setup_error_invalid_handle(response_buffer, request_type, handle);
1014     }
1015     if ((it.flags & ATT_PROPERTY_WRITE) == 0) {
1016         return setup_error_write_not_permitted(response_buffer, request_type, handle);
1017     }
1018     if ((it.flags & ATT_PROPERTY_DYNAMIC) == 0) {
1019         return setup_error_write_not_permitted(response_buffer, request_type, handle);
1020     }
1021     // check security requirements
1022     int error_code = att_validate_security(att_connection, ATT_WRITE, &it);
1023     if (error_code) {
1024         return setup_error(response_buffer, request_type, handle, error_code);
1025     }
1026 
1027     error_code = (*att_write_callback)(att_connection->con_handle, handle, ATT_TRANSACTION_MODE_ACTIVE, offset, request_buffer + 5, request_len - 5);
1028     switch (error_code){
1029         case 0:
1030             break;
1031         case ATT_ERROR_INVALID_OFFSET:
1032         case ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH:
1033             // postpone to execute write request
1034             att_prepare_write_update_errors(error_code, handle);
1035             break;
1036 #ifdef ENABLE_ATT_DELAYED_RESPONSE
1037         case ATT_ERROR_WRITE_RESPONSE_PENDING:
1038             return ATT_INTERNAL_WRITE_RESPONSE_PENDING;
1039 #endif
1040         default:
1041             return setup_error(response_buffer, request_type, handle, error_code);
1042     }
1043 
1044     // response: echo request
1045     (void)memcpy(response_buffer, request_buffer, request_len);
1046     response_buffer[0] = ATT_PREPARE_WRITE_RESPONSE;
1047     return request_len;
1048 }
1049 
1050 /*
1051  * @brief transcation queue of prepared writes, e.g., after disconnect
1052  */
1053 void att_clear_transaction_queue(att_connection_t * att_connection){
1054     (*att_write_callback)(att_connection->con_handle, 0, ATT_TRANSACTION_MODE_CANCEL, 0, NULL, 0);
1055 }
1056 
1057 // MARK: ATT_EXECUTE_WRITE_REQUEST 0x18
1058 // NOTE: security has been verified by handle_prepare_write_request
1059 static uint16_t handle_execute_write_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
1060                                       uint8_t * response_buffer, uint16_t response_buffer_size){
1061 
1062     UNUSED(request_len);
1063     UNUSED(response_buffer_size);
1064 
1065     uint8_t request_type = ATT_EXECUTE_WRITE_REQUEST;
1066     if (request_buffer[1]) {
1067         // validate queued write
1068         if (att_prepare_write_error_code == 0){
1069             att_prepare_write_error_code = (*att_write_callback)(att_connection->con_handle, 0, ATT_TRANSACTION_MODE_VALIDATE, 0, NULL, 0);
1070         }
1071 #ifdef ENABLE_ATT_DELAYED_RESPONSE
1072         if (att_prepare_write_error_code == ATT_ERROR_WRITE_RESPONSE_PENDING) return ATT_INTERNAL_WRITE_RESPONSE_PENDING;
1073 #endif
1074         // deliver queued errors
1075         if (att_prepare_write_error_code){
1076             att_clear_transaction_queue(att_connection);
1077             uint8_t  error_code = att_prepare_write_error_code;
1078             uint16_t handle     = att_prepare_write_error_handle;
1079             att_prepare_write_reset();
1080             return setup_error(response_buffer, request_type, handle, error_code);
1081         }
1082         att_write_callback(att_connection->con_handle, 0, ATT_TRANSACTION_MODE_EXECUTE, 0, NULL, 0);
1083     } else {
1084         att_clear_transaction_queue(att_connection);
1085     }
1086     response_buffer[0] = ATT_EXECUTE_WRITE_RESPONSE;
1087     return 1;
1088 }
1089 
1090 // MARK: ATT_WRITE_COMMAND 0x52
1091 // Core 4.0, vol 3, part F, 3.4.5.3
1092 // "No Error Response or Write Response shall be sent in response to this command"
1093 static void handle_write_command(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len, uint16_t required_flags){
1094 
1095     uint16_t handle = little_endian_read_16(request_buffer, 1);
1096     if (att_write_callback == NULL) return;
1097 
1098     att_iterator_t it;
1099     int ok = att_find_handle(&it, handle);
1100     if (!ok) return;
1101     if ((it.flags & ATT_PROPERTY_DYNAMIC) == 0) return;
1102     if ((it.flags & required_flags) == 0) return;
1103     if (att_validate_security(att_connection, ATT_WRITE, &it)) return;
1104     att_persistent_ccc_cache(&it);
1105     (*att_write_callback)(att_connection->con_handle, handle, ATT_TRANSACTION_MODE_NONE, 0, request_buffer + 3, request_len - 3);
1106 }
1107 
1108 // MARK: helper for ATT_HANDLE_VALUE_NOTIFICATION and ATT_HANDLE_VALUE_INDICATION
1109 static uint16_t prepare_handle_value(att_connection_t * att_connection,
1110                                      uint16_t handle,
1111                                      const uint8_t *value,
1112                                      uint16_t value_len,
1113                                      uint8_t * response_buffer){
1114     little_endian_store_16(response_buffer, 1, handle);
1115     if (value_len > (att_connection->mtu - 3)){
1116         value_len = att_connection->mtu - 3;
1117     }
1118     (void)memcpy(&response_buffer[3], value, value_len);
1119     return value_len + 3;
1120 }
1121 
1122 // MARK: ATT_HANDLE_VALUE_NOTIFICATION 0x1b
1123 uint16_t att_prepare_handle_value_notification(att_connection_t * att_connection,
1124                                                uint16_t handle,
1125                                                const uint8_t *value,
1126                                                uint16_t value_len,
1127                                                uint8_t * response_buffer){
1128 
1129     response_buffer[0] = ATT_HANDLE_VALUE_NOTIFICATION;
1130     return prepare_handle_value(att_connection, handle, value, value_len, response_buffer);
1131 }
1132 
1133 // MARK: ATT_HANDLE_VALUE_INDICATION 0x1d
1134 uint16_t att_prepare_handle_value_indication(att_connection_t * att_connection,
1135                                              uint16_t handle,
1136                                              const uint8_t *value,
1137                                              uint16_t value_len,
1138                                              uint8_t * response_buffer){
1139 
1140     response_buffer[0] = ATT_HANDLE_VALUE_INDICATION;
1141     return prepare_handle_value(att_connection, handle, value, value_len, response_buffer);
1142 }
1143 
1144 // MARK: Dispatcher
1145 uint16_t att_handle_request(att_connection_t * att_connection,
1146                             uint8_t * request_buffer,
1147                             uint16_t request_len,
1148                             uint8_t * response_buffer){
1149     uint16_t response_len = 0;
1150     uint16_t response_buffer_size = att_connection->mtu;
1151 
1152     switch (request_buffer[0]){
1153         case ATT_EXCHANGE_MTU_REQUEST:
1154             response_len = handle_exchange_mtu_request(att_connection, request_buffer, request_len, response_buffer);
1155             break;
1156         case ATT_FIND_INFORMATION_REQUEST:
1157             response_len = handle_find_information_request(att_connection, request_buffer, request_len,response_buffer, response_buffer_size);
1158             break;
1159         case ATT_FIND_BY_TYPE_VALUE_REQUEST:
1160             response_len = handle_find_by_type_value_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1161             break;
1162         case ATT_READ_BY_TYPE_REQUEST:
1163             response_len = handle_read_by_type_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1164             break;
1165         case ATT_READ_REQUEST:
1166             response_len = handle_read_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1167             break;
1168         case ATT_READ_BLOB_REQUEST:
1169             response_len = handle_read_blob_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1170             break;
1171         case ATT_READ_MULTIPLE_REQUEST:
1172             response_len = handle_read_multiple_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1173             break;
1174         case ATT_READ_BY_GROUP_TYPE_REQUEST:
1175             response_len = handle_read_by_group_type_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1176             break;
1177         case ATT_WRITE_REQUEST:
1178             response_len = handle_write_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1179             break;
1180         case ATT_PREPARE_WRITE_REQUEST:
1181             response_len = handle_prepare_write_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1182             break;
1183         case ATT_EXECUTE_WRITE_REQUEST:
1184             response_len = handle_execute_write_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1185             break;
1186         case ATT_WRITE_COMMAND:
1187             handle_write_command(att_connection, request_buffer, request_len, ATT_PROPERTY_WRITE_WITHOUT_RESPONSE);
1188             break;
1189 #ifdef ENABLE_LE_SIGNED_WRITE
1190         case ATT_SIGNED_WRITE_COMMAND:
1191             handle_write_command(att_connection, request_buffer, request_len, ATT_PROPERTY_AUTHENTICATED_SIGNED_WRITE);
1192             break;
1193 #endif
1194         default:
1195             log_info("Unhandled ATT Command: %02X, DATA: ", request_buffer[0]);
1196             log_info_hexdump(&request_buffer[9], request_len-9);
1197             break;
1198     }
1199     return response_len;
1200 }
1201 
1202 // returns 1 if service found. only primary service.
1203 bool gatt_server_get_get_handle_range_for_service_with_uuid16(uint16_t uuid16, uint16_t * start_handle, uint16_t * end_handle){
1204     uint16_t in_group    = 0;
1205     uint16_t prev_handle = 0;
1206 
1207     uint8_t attribute_value[2];
1208     int attribute_len = sizeof(attribute_value);
1209     little_endian_store_16(attribute_value, 0, uuid16);
1210 
1211     att_iterator_t it;
1212     att_iterator_init(&it);
1213     while (att_iterator_has_next(&it)){
1214         att_iterator_fetch_next(&it);
1215         int new_service_started = att_iterator_match_uuid16(&it, GATT_PRIMARY_SERVICE_UUID) || att_iterator_match_uuid16(&it, GATT_SECONDARY_SERVICE_UUID);
1216 
1217         // close current tag, if within a group and a new service definition starts or we reach end of att db
1218         if (in_group &&
1219             ((it.handle == 0) || new_service_started)){
1220             *end_handle = prev_handle;
1221             return true;
1222         }
1223 
1224         // keep track of previous handle
1225         prev_handle = it.handle;
1226 
1227         // check if found
1228         if (it.handle && new_service_started && (attribute_len == it.value_len) && (memcmp(attribute_value, it.value, it.value_len) == 0)){
1229             *start_handle = it.handle;
1230             in_group = true;
1231         }
1232     }
1233     return false;
1234 }
1235 
1236 // returns false if not found
1237 uint16_t gatt_server_get_value_handle_for_characteristic_with_uuid16(uint16_t start_handle, uint16_t end_handle, uint16_t uuid16){
1238     att_iterator_t it;
1239     att_iterator_init(&it);
1240     while (att_iterator_has_next(&it)){
1241         att_iterator_fetch_next(&it);
1242         if (it.handle && (it.handle < start_handle)) continue;
1243         if (it.handle > end_handle) break;  // (1)
1244         if (it.handle == 0) break;
1245         if (att_iterator_match_uuid16(&it, uuid16)) return it.handle;
1246     }
1247     return 0;
1248 }
1249 
1250 uint16_t gatt_server_get_descriptor_handle_for_characteristic_with_uuid16(uint16_t start_handle, uint16_t end_handle, uint16_t characteristic_uuid16, uint16_t descriptor_uuid16){
1251     att_iterator_t it;
1252     att_iterator_init(&it);
1253     int characteristic_found = 0;
1254     while (att_iterator_has_next(&it)){
1255         att_iterator_fetch_next(&it);
1256         if (it.handle && (it.handle < start_handle)) continue;
1257         if (it.handle > end_handle) break;  // (1)
1258         if (it.handle == 0) break;
1259         if (att_iterator_match_uuid16(&it, characteristic_uuid16)){
1260             characteristic_found = 1;
1261             continue;
1262         }
1263         if (att_iterator_match_uuid16(&it, GATT_PRIMARY_SERVICE_UUID)
1264          || att_iterator_match_uuid16(&it, GATT_SECONDARY_SERVICE_UUID)
1265          || att_iterator_match_uuid16(&it, GATT_CHARACTERISTICS_UUID)){
1266             if (characteristic_found) break;
1267             continue;
1268         }
1269         if (characteristic_found && att_iterator_match_uuid16(&it, descriptor_uuid16)){
1270             return it.handle;
1271         }
1272     }
1273     return 0;
1274 }
1275 
1276 // returns 0 if not found
1277 uint16_t gatt_server_get_client_configuration_handle_for_characteristic_with_uuid16(uint16_t start_handle, uint16_t end_handle, uint16_t characteristic_uuid16){
1278     return gatt_server_get_descriptor_handle_for_characteristic_with_uuid16(start_handle, end_handle, characteristic_uuid16, GATT_CLIENT_CHARACTERISTICS_CONFIGURATION);
1279 }
1280 // returns 0 if not found
1281 
1282 uint16_t gatt_server_get_server_configuration_handle_for_characteristic_with_uuid16(uint16_t start_handle, uint16_t end_handle, uint16_t characteristic_uuid16){
1283     return gatt_server_get_descriptor_handle_for_characteristic_with_uuid16(start_handle, end_handle, characteristic_uuid16, GATT_SERVER_CHARACTERISTICS_CONFIGURATION);
1284 }
1285 
1286 // returns 1 if service found. only primary service.
1287 int gatt_server_get_get_handle_range_for_service_with_uuid128(const uint8_t * uuid128, uint16_t * start_handle, uint16_t * end_handle){
1288     uint16_t in_group    = 0;
1289     uint16_t prev_handle = 0;
1290 
1291     uint8_t attribute_value[16];
1292     int attribute_len = sizeof(attribute_value);
1293     reverse_128(uuid128, attribute_value);
1294 
1295     att_iterator_t it;
1296     att_iterator_init(&it);
1297     while (att_iterator_has_next(&it)){
1298         att_iterator_fetch_next(&it);
1299         int new_service_started = att_iterator_match_uuid16(&it, GATT_PRIMARY_SERVICE_UUID) || att_iterator_match_uuid16(&it, GATT_SECONDARY_SERVICE_UUID);
1300 
1301         // close current tag, if within a group and a new service definition starts or we reach end of att db
1302         if (in_group &&
1303             ((it.handle == 0) || new_service_started)){
1304             *end_handle = prev_handle;
1305             return 1;
1306         }
1307 
1308         // keep track of previous handle
1309         prev_handle = it.handle;
1310 
1311         // check if found
1312         if (it.handle && new_service_started && (attribute_len == it.value_len) && (memcmp(attribute_value, it.value, it.value_len) == 0)){
1313             *start_handle = it.handle;
1314             in_group = 1;
1315         }
1316     }
1317     return 0;
1318 }
1319 
1320 // returns 0 if not found
1321 uint16_t gatt_server_get_value_handle_for_characteristic_with_uuid128(uint16_t start_handle, uint16_t end_handle, const uint8_t * uuid128){
1322     uint8_t attribute_value[16];
1323     reverse_128(uuid128, attribute_value);
1324     att_iterator_t it;
1325     att_iterator_init(&it);
1326     while (att_iterator_has_next(&it)){
1327         att_iterator_fetch_next(&it);
1328         if (it.handle && (it.handle < start_handle)) continue;
1329         if (it.handle > end_handle) break;  // (1)
1330         if (it.handle == 0) break;
1331         if (att_iterator_match_uuid(&it, attribute_value, 16)) return it.handle;
1332     }
1333     return 0;
1334 }
1335 
1336 // returns 0 if not found
1337 uint16_t gatt_server_get_client_configuration_handle_for_characteristic_with_uuid128(uint16_t start_handle, uint16_t end_handle, const uint8_t * uuid128){
1338     uint8_t attribute_value[16];
1339     reverse_128(uuid128, attribute_value);
1340     att_iterator_t it;
1341     att_iterator_init(&it);
1342     int characteristic_found = 0;
1343     while (att_iterator_has_next(&it)){
1344         att_iterator_fetch_next(&it);
1345         if (it.handle && (it.handle < start_handle)) continue;
1346         if (it.handle > end_handle) break;  // (1)
1347         if (it.handle == 0) break;
1348         if (att_iterator_match_uuid(&it, attribute_value, 16)){
1349             characteristic_found = 1;
1350             continue;
1351         }
1352         if (att_iterator_match_uuid16(&it, GATT_PRIMARY_SERVICE_UUID)
1353          || att_iterator_match_uuid16(&it, GATT_SECONDARY_SERVICE_UUID)
1354          || att_iterator_match_uuid16(&it, GATT_CHARACTERISTICS_UUID)){
1355             if (characteristic_found) break;
1356             continue;
1357         }
1358         if (characteristic_found && att_iterator_match_uuid16(&it, GATT_CLIENT_CHARACTERISTICS_CONFIGURATION)){
1359             return it.handle;
1360         }
1361     }
1362     return 0;
1363 }
1364 
1365 
1366 // 1-item cache to optimize query during write_callback
1367 static void att_persistent_ccc_cache(att_iterator_t * it){
1368     att_persistent_ccc_handle = it->handle;
1369     if (it->flags & ATT_PROPERTY_UUID128){
1370         att_persistent_ccc_uuid16 = 0;
1371     } else {
1372         att_persistent_ccc_uuid16 = little_endian_read_16(it->uuid, 0);
1373     }
1374 }
1375 
1376 bool att_is_persistent_ccc(uint16_t handle){
1377     if (handle != att_persistent_ccc_handle){
1378         att_iterator_t it;
1379         int ok = att_find_handle(&it, handle);
1380         if (!ok) return false;
1381         att_persistent_ccc_cache(&it);
1382     }
1383     return att_persistent_ccc_uuid16 == GATT_CLIENT_CHARACTERISTICS_CONFIGURATION;
1384 }
1385 
1386 // att_read_callback helpers
1387 uint16_t att_read_callback_handle_blob(const uint8_t * blob, uint16_t blob_size, uint16_t offset, uint8_t * buffer, uint16_t buffer_size){
1388     if (buffer){
1389         uint16_t bytes_to_copy = btstack_min(blob_size - offset, buffer_size);
1390         (void)memcpy(buffer, &blob[offset], bytes_to_copy);
1391         return bytes_to_copy;
1392     } else {
1393         return blob_size;
1394     }
1395 }
1396 
1397 uint16_t att_read_callback_handle_little_endian_32(uint32_t value, uint16_t offset, uint8_t * buffer, uint16_t buffer_size){
1398     uint8_t value_buffer[4];
1399     little_endian_store_32(value_buffer, 0, value);
1400     return att_read_callback_handle_blob(value_buffer, sizeof(value_buffer), offset, buffer, buffer_size);
1401 }
1402 
1403 uint16_t att_read_callback_handle_little_endian_16(uint16_t value, uint16_t offset, uint8_t * buffer, uint16_t buffer_size){
1404     uint8_t value_buffer[2];
1405     little_endian_store_16(value_buffer, 0, value);
1406     return att_read_callback_handle_blob(value_buffer, sizeof(value_buffer), offset, buffer, buffer_size);
1407 }
1408 
1409 uint16_t att_read_callback_handle_byte(uint8_t value, uint16_t offset, uint8_t * buffer, uint16_t buffer_size){
1410     uint8_t value_buffer[1];
1411     value_buffer[0] = value;
1412     return att_read_callback_handle_blob(value_buffer, sizeof(value_buffer), offset, buffer, buffer_size);
1413 }
1414