xref: /btstack/src/ble/att_db.c (revision f400efd4c34c2c3d094122d9c99ddcc5357e2a2e)
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 
59 static int is_Bluetooth_Base_UUID(uint8_t const *uuid){
60     // Bluetooth Base UUID 00000000-0000-1000-8000-00805F9B34FB in little endian
61     static const uint8_t bluetooth_base_uuid[] = { 0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
62 
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 == 2u) return little_endian_read_16(uuid, 0u);
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 == 0u){
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) != 0u){
126         it->value_len = it->size - 22u;
127         it->value  = &it->att_ptr[22];
128     } else {
129         it->value_len = it->size - 8u;
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 == 0u) return 0u;
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 == 0u) return 0u;
147     // input: UUID16
148     if (uuid_len == 2u) {
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) != 0u){
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 == 0u) return 0u;
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) != 0u) return 0u;
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) == 0u) 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) != 0u){
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     log_info("att_set_db %p", db);
213     att_db = db;
214 }
215 
216 void att_set_read_callback(att_read_callback_t callback){
217     att_read_callback = callback;
218 }
219 
220 void att_set_write_callback(att_write_callback_t callback){
221     att_write_callback = callback;
222 }
223 
224 void att_dump_attributes(void){
225     att_iterator_t it;
226     att_iterator_init(&it);
227     uint8_t uuid128[16];
228     log_info("att_dump_attributes, table %p", att_db);
229     while (att_iterator_has_next(&it)){
230         att_iterator_fetch_next(&it);
231         if (it.handle == 0u) {
232             log_info("Handle: END");
233             return;
234         }
235         log_info("Handle: 0x%04x, flags: 0x%04x, uuid: ", it.handle, it.flags);
236         if ((it.flags & ATT_PROPERTY_UUID128) != 0u){
237             reverse_128(it.uuid, uuid128);
238             log_info("%s", uuid128_to_str(uuid128));
239         } else {
240             log_info("%04x", little_endian_read_16(it.uuid, 0));
241         }
242         log_info(", value_len: %u, value: ", it.value_len);
243         log_info_hexdump(it.value, it.value_len);
244     }
245 }
246 
247 static void att_prepare_write_reset(void){
248     att_prepare_write_error_code = 0;
249     att_prepare_write_error_handle = 0x0000;
250 }
251 
252 static void att_prepare_write_update_errors(uint8_t error_code, uint16_t handle){
253     // first ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH has highest priority
254     if ((error_code == ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH) && (error_code != att_prepare_write_error_code)){
255         att_prepare_write_error_code = error_code;
256         att_prepare_write_error_handle = handle;
257         return;
258     }
259     // first ATT_ERROR_INVALID_OFFSET is next
260     if ((error_code == ATT_ERROR_INVALID_OFFSET) && (att_prepare_write_error_code == 0)){
261         att_prepare_write_error_code = error_code;
262         att_prepare_write_error_handle = handle;
263         return;
264     }
265 }
266 
267 static uint16_t setup_error(uint8_t * response_buffer, uint16_t request, uint16_t handle, uint8_t error_code){
268     response_buffer[0] = ATT_ERROR_RESPONSE;
269     response_buffer[1] = request;
270     little_endian_store_16(response_buffer, 2, handle);
271     response_buffer[4] = error_code;
272     return 5;
273 }
274 
275 static inline uint16_t setup_error_read_not_permitted(uint8_t * response_buffer, uint16_t request, uint16_t start_handle){
276     return setup_error(response_buffer, request, start_handle, ATT_ERROR_READ_NOT_PERMITTED);
277 }
278 
279 static inline uint16_t setup_error_write_not_permitted(uint8_t * response_buffer, uint16_t request, uint16_t start_handle){
280     return setup_error(response_buffer, request, start_handle, ATT_ERROR_WRITE_NOT_PERMITTED);
281 }
282 
283 static inline uint16_t setup_error_atribute_not_found(uint8_t * response_buffer, uint16_t request, uint16_t start_handle){
284     return setup_error(response_buffer, request, start_handle, ATT_ERROR_ATTRIBUTE_NOT_FOUND);
285 }
286 
287 static inline uint16_t setup_error_invalid_handle(uint8_t * response_buffer, uint16_t request, uint16_t handle){
288     return setup_error(response_buffer, request, handle, ATT_ERROR_INVALID_HANDLE);
289 }
290 
291 static inline uint16_t setup_error_invalid_offset(uint8_t * response_buffer, uint16_t request, uint16_t handle){
292     return setup_error(response_buffer, request, handle, ATT_ERROR_INVALID_OFFSET);
293 }
294 
295 static inline uint16_t setup_error_invalid_pdu(uint8_t *response_buffer, uint16_t request) {
296     return setup_error(response_buffer, request, 0, ATT_ERROR_INVALID_PDU);
297 }
298 
299 static uint8_t att_validate_security(att_connection_t * att_connection, att_operation_t operation, att_iterator_t * it){
300     int required_security_level = 0;
301     bool requires_secure_connection = false;
302     switch (operation){
303         case ATT_READ:
304             if ((it->flags & ATT_PROPERTY_READ_PERMISSION_BIT_0) != 0u){
305                 required_security_level |= 1;
306             }
307             if ((it->flags & ATT_PROPERTY_READ_PERMISSION_BIT_1) != 0u){
308                 required_security_level |= 2;
309             }
310             if ((it->flags & ATT_PROPERTY_READ_PERMISSION_SC) != 0u){
311                 requires_secure_connection = true;
312             }
313             break;
314         case ATT_WRITE:
315             if ((it->flags & ATT_PROPERTY_WRITE_PERMISSION_BIT_0) != 0u){
316                 required_security_level |= 1;
317             }
318             if ((it->flags & ATT_PROPERTY_WRITE_PERMISSION_BIT_1) != 0u){
319                 required_security_level |= 2;
320             }
321             if ((it->flags & ATT_PROPERTY_WRITE_PERMISSION_SC) != 0u){
322                 requires_secure_connection = true;
323             }
324             break;
325     }
326 
327     uint8_t required_encryption_size = it->flags >> 12;
328     if (required_encryption_size != 0) required_encryption_size++;   // store -1 to fit into 4 bit
329 
330     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",
331         it->flags, required_security_level, required_encryption_size, att_connection->authorized, att_connection->authenticated, att_connection->encryption_key_size, att_connection->secure_connection);
332 
333     bool sc_missing = requires_secure_connection && (att_connection->secure_connection == 0u);
334     switch (required_security_level){
335         case ATT_SECURITY_AUTHORIZED:
336             if ((att_connection->authorized == 0u) || sc_missing){
337                 return ATT_ERROR_INSUFFICIENT_AUTHORIZATION;
338             }
339             /* fall through */
340         case ATT_SECURITY_AUTHENTICATED:
341             if ((att_connection->authenticated == 0u) || sc_missing){
342                 return ATT_ERROR_INSUFFICIENT_AUTHENTICATION;
343             }
344             /* fall through */
345         case ATT_SECURITY_ENCRYPTED:
346             if ((required_encryption_size > 0u) && ((att_connection->encryption_key_size == 0u) || sc_missing)){
347                 return ATT_ERROR_INSUFFICIENT_ENCRYPTION;
348             }
349             if (required_encryption_size > att_connection->encryption_key_size){
350                 return ATT_ERROR_INSUFFICIENT_ENCRYPTION_KEY_SIZE;
351             }
352             break;
353         default:
354             break;
355     }
356     return ATT_ERROR_SUCCESS;
357 }
358 
359 //
360 // MARK: ATT_EXCHANGE_MTU_REQUEST
361 //
362 static uint16_t handle_exchange_mtu_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
363                                          uint8_t * response_buffer){
364 
365     if (request_len != 3u) return setup_error_invalid_pdu(response_buffer, ATT_EXCHANGE_MTU_REQUEST);
366 
367     uint16_t client_rx_mtu = little_endian_read_16(request_buffer, 1);
368 
369     // find min(local max mtu, remote mtu) >= ATT_DEFAULT_MTU and use as mtu for this connection
370     uint16_t min_mtu = btstack_min(client_rx_mtu, att_connection->max_mtu);
371     uint16_t new_mtu = btstack_max(ATT_DEFAULT_MTU, min_mtu);
372     att_connection->mtu = new_mtu;
373 
374     response_buffer[0] = ATT_EXCHANGE_MTU_RESPONSE;
375     little_endian_store_16(response_buffer, 1, att_connection->mtu);
376     return 3;
377 }
378 
379 
380 //
381 // MARK: ATT_FIND_INFORMATION_REQUEST
382 //
383 // TODO: handle other types then GATT_PRIMARY_SERVICE_UUID and GATT_SECONDARY_SERVICE_UUID
384 //
385 static uint16_t handle_find_information_request2(att_connection_t * att_connection, uint8_t * response_buffer, uint16_t response_buffer_size,
386                                            uint16_t start_handle, uint16_t end_handle){
387 
388     UNUSED(att_connection);
389 
390     log_info("ATT_FIND_INFORMATION_REQUEST: from %04X to %04X", start_handle, end_handle);
391     uint8_t request_type = ATT_FIND_INFORMATION_REQUEST;
392 
393     if ((start_handle > end_handle) || (start_handle == 0u)){
394         return setup_error_invalid_handle(response_buffer, request_type, start_handle);
395     }
396 
397     uint16_t offset   = 1;
398     uint16_t uuid_len = 0;
399 
400     att_iterator_t it;
401     att_iterator_init(&it);
402     while (att_iterator_has_next(&it)){
403         att_iterator_fetch_next(&it);
404         if (!it.handle) break;
405         if (it.handle > end_handle) break;
406         if (it.handle < start_handle) continue;
407 
408         // log_info("Handle 0x%04x", it.handle);
409 
410         uint16_t this_uuid_len = (it.flags & ATT_PROPERTY_UUID128) ? 16 : 2;
411 
412         // check if value has same len as last one if not first result
413         if (offset > 1u){
414             if (this_uuid_len != uuid_len) {
415                 break;
416             }
417         }
418 
419         // first
420         if (offset == 1u) {
421             uuid_len = this_uuid_len;
422             // set format field
423             response_buffer[offset] = (it.flags & ATT_PROPERTY_UUID128) ? 0x02 : 0x01;
424             offset++;
425         }
426 
427         // space?
428         if ((offset + 2u + uuid_len) > response_buffer_size) break;
429 
430         // store
431         little_endian_store_16(response_buffer, offset, it.handle);
432         offset += 2u;
433 
434         (void)memcpy(response_buffer + offset, it.uuid, uuid_len);
435         offset += uuid_len;
436     }
437 
438     if (offset == 1u){
439         return setup_error_atribute_not_found(response_buffer, request_type, start_handle);
440     }
441 
442     response_buffer[0] = ATT_FIND_INFORMATION_REPLY;
443     return offset;
444 }
445 
446 static uint16_t handle_find_information_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
447                                          uint8_t * response_buffer, uint16_t response_buffer_size){
448 
449     if (request_len != 5u) return setup_error_invalid_pdu(response_buffer, ATT_FIND_INFORMATION_REQUEST);
450 
451     uint16_t start_handle = little_endian_read_16(request_buffer, 1);
452     uint16_t end_handle = little_endian_read_16(request_buffer, 3);
453     return handle_find_information_request2(att_connection, response_buffer, response_buffer_size, start_handle, end_handle);
454 }
455 
456 //
457 // MARK: ATT_FIND_BY_TYPE_VALUE
458 //
459 // "Only attributes with attribute handles between and including the Starting Handle parameter
460 // and the Ending Handle parameter that match the requested attri- bute type and the attribute
461 // value that have sufficient permissions to allow reading will be returned" -> (1)
462 //
463 // TODO: handle other types then GATT_PRIMARY_SERVICE_UUID and GATT_SECONDARY_SERVICE_UUID
464 //
465 // NOTE: doesn't handle DYNAMIC values
466 // NOTE: only supports 16 bit UUIDs
467 //
468 static uint16_t handle_find_by_type_value_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
469                                            uint8_t * response_buffer, uint16_t response_buffer_size){
470     UNUSED(att_connection);
471 
472     if (request_len < 7u) return setup_error_invalid_pdu(response_buffer, ATT_FIND_BY_TYPE_VALUE_REQUEST);
473 
474     // parse request
475     uint16_t start_handle = little_endian_read_16(request_buffer, 1);
476     uint16_t end_handle = little_endian_read_16(request_buffer, 3);
477     uint16_t attribute_type = little_endian_read_16(request_buffer, 5);
478     const uint8_t *attribute_value = &request_buffer[7];
479     uint16_t attribute_len = request_len - 7u;
480 
481     log_info("ATT_FIND_BY_TYPE_VALUE_REQUEST: from %04X to %04X, type %04X, value: ", start_handle, end_handle, attribute_type);
482     log_info_hexdump(attribute_value, attribute_len);
483     uint8_t request_type = ATT_FIND_BY_TYPE_VALUE_REQUEST;
484 
485     if ((start_handle > end_handle) || (start_handle == 0u)){
486         return setup_error_invalid_handle(response_buffer, request_type, start_handle);
487     }
488 
489     uint16_t offset      = 1;
490     uint16_t in_group    = 0;
491     uint16_t prev_handle = 0;
492 
493     att_iterator_t it;
494     att_iterator_init(&it);
495     while (att_iterator_has_next(&it)){
496         att_iterator_fetch_next(&it);
497 
498         if (it.handle && (it.handle < start_handle)) continue;
499         if (it.handle > end_handle) break;  // (1)
500 
501         // close current tag, if within a group and a new service definition starts or we reach end of att db
502         if (in_group &&
503             ((it.handle == 0u) || att_iterator_match_uuid16(&it, GATT_PRIMARY_SERVICE_UUID) || att_iterator_match_uuid16(&it, GATT_SECONDARY_SERVICE_UUID))){
504 
505             log_info("End of group, handle 0x%04x", prev_handle);
506             little_endian_store_16(response_buffer, offset, prev_handle);
507             offset += 2u;
508             in_group = 0;
509 
510             // check if space for another handle pair available
511             if ((offset + 4u) > response_buffer_size){
512                 break;
513             }
514         }
515 
516         // keep track of previous handle
517         prev_handle = it.handle;
518 
519         // does current attribute match
520         if (it.handle && att_iterator_match_uuid16(&it, attribute_type) && (attribute_len == it.value_len) && (memcmp(attribute_value, it.value, it.value_len) == 0)){
521             log_info("Begin of group, handle 0x%04x", it.handle);
522             little_endian_store_16(response_buffer, offset, it.handle);
523             offset += 2u;
524             in_group = 1;
525         }
526     }
527 
528     if (offset == 1u){
529         return setup_error_atribute_not_found(response_buffer, request_type, start_handle);
530     }
531 
532     response_buffer[0] = ATT_FIND_BY_TYPE_VALUE_RESPONSE;
533     return offset;
534 }
535 
536 //
537 // MARK: ATT_READ_BY_TYPE_REQUEST
538 //
539 static uint16_t handle_read_by_type_request2(att_connection_t * att_connection, uint8_t * response_buffer, uint16_t response_buffer_size,
540                                       uint16_t start_handle, uint16_t end_handle,
541                                       uint16_t attribute_type_len, uint8_t * attribute_type){
542 
543     log_info("ATT_READ_BY_TYPE_REQUEST: from %04X to %04X, type: ", start_handle, end_handle);
544     log_info_hexdump(attribute_type, attribute_type_len);
545     uint8_t request_type = ATT_READ_BY_TYPE_REQUEST;
546 
547     if ((start_handle > end_handle) || (start_handle == 0u)){
548         return setup_error_invalid_handle(response_buffer, request_type, start_handle);
549     }
550 
551     uint16_t offset   = 1;
552     uint16_t pair_len = 0;
553 
554     att_iterator_t it;
555     att_iterator_init(&it);
556     uint8_t error_code = 0;
557     uint16_t first_matching_but_unreadable_handle = 0;
558 
559     while (att_iterator_has_next(&it)){
560         att_iterator_fetch_next(&it);
561 
562         if ((it.handle == 0u ) || (it.handle > end_handle)) break;
563 
564         if (it.handle < start_handle) continue;
565 
566         // does current attribute match
567         if (!att_iterator_match_uuid(&it, attribute_type, attribute_type_len)) continue;
568 
569         // skip handles that cannot be read but remember that there has been at least one
570         if ((it.flags & ATT_PROPERTY_READ) == 0u) {
571             if (first_matching_but_unreadable_handle == 0u) {
572                 first_matching_but_unreadable_handle = it.handle;
573             }
574             continue;
575         }
576 
577         // check security requirements
578         error_code = att_validate_security(att_connection, ATT_READ, &it);
579         if (error_code != 0u) break;
580 
581         att_update_value_len(&it, att_connection->con_handle);
582 
583 #ifdef ENABLE_ATT_DELAYED_RESPONSE
584         if (it.value_len == ATT_READ_RESPONSE_PENDING){
585             return ATT_READ_RESPONSE_PENDING;
586         }
587 #endif
588 
589         // check if value has same len as last one
590         uint16_t this_pair_len = 2u + it.value_len;
591         if ((offset > 1u) && (pair_len != this_pair_len)) {
592             break;
593         }
594 
595         // first
596         if (offset == 1u) {
597             pair_len = this_pair_len;
598             response_buffer[offset] = pair_len;
599             offset++;
600         }
601 
602         // space?
603         if ((offset + pair_len) > response_buffer_size) {
604             if (offset > 2u) break;
605             it.value_len = response_buffer_size - 4u;
606             response_buffer[1u] = 2u + it.value_len;
607         }
608 
609         // store
610         little_endian_store_16(response_buffer, offset, it.handle);
611         offset += 2u;
612         uint16_t bytes_copied = att_copy_value(&it, 0, response_buffer + offset, it.value_len, att_connection->con_handle);
613         offset += bytes_copied;
614     }
615 
616     // at least one attribute could be read
617     if (offset > 1u){
618         response_buffer[0] = ATT_READ_BY_TYPE_RESPONSE;
619         return offset;
620     }
621 
622     // first attribute had an error
623     if (error_code != 0u){
624         return setup_error(response_buffer, request_type, start_handle, error_code);
625     }
626 
627     // no other errors, but all found attributes had been non-readable
628     if (first_matching_but_unreadable_handle != 0u){
629         return setup_error_read_not_permitted(response_buffer, request_type, first_matching_but_unreadable_handle);
630     }
631 
632     // attribute not found
633     return setup_error_atribute_not_found(response_buffer, request_type, start_handle);
634 }
635 
636 static uint16_t handle_read_by_type_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
637                                      uint8_t * response_buffer, uint16_t response_buffer_size){
638 
639     uint16_t attribute_type_len;
640     switch (request_len){
641         case 7:
642             attribute_type_len = 2;
643             break;
644         case 21:
645             attribute_type_len = 16;
646             break;
647         default:
648             return setup_error_invalid_pdu(response_buffer, ATT_READ_BY_TYPE_REQUEST);
649     }
650 
651     uint16_t start_handle = little_endian_read_16(request_buffer, 1);
652     uint16_t end_handle = little_endian_read_16(request_buffer, 3);
653     return handle_read_by_type_request2(att_connection, response_buffer, response_buffer_size, start_handle, end_handle, attribute_type_len, &request_buffer[5]);
654 }
655 
656 //
657 // MARK: ATT_READ_BY_TYPE_REQUEST
658 //
659 static uint16_t handle_read_request2(att_connection_t * att_connection, uint8_t * response_buffer, uint16_t response_buffer_size, uint16_t handle){
660 
661     log_info("ATT_READ_REQUEST: handle %04x", handle);
662     uint8_t request_type = ATT_READ_REQUEST;
663 
664     att_iterator_t it;
665     int ok = att_find_handle(&it, handle);
666     if (!ok){
667         return setup_error_invalid_handle(response_buffer, request_type, handle);
668     }
669 
670     // check if handle can be read
671     if ((it.flags & ATT_PROPERTY_READ) == 0u) {
672         return setup_error_read_not_permitted(response_buffer, request_type, handle);
673     }
674 
675     // check security requirements
676     uint8_t error_code = att_validate_security(att_connection, ATT_READ, &it);
677     if (error_code) {
678         return setup_error(response_buffer, request_type, handle, error_code);
679     }
680 
681     att_update_value_len(&it, att_connection->con_handle);
682 
683 #ifdef ENABLE_ATT_DELAYED_RESPONSE
684     if (it.value_len == ATT_READ_RESPONSE_PENDING) return ATT_READ_RESPONSE_PENDING;
685 #endif
686 
687     // store
688     uint16_t offset   = 1;
689     uint16_t bytes_copied = att_copy_value(&it, 0, response_buffer + offset, response_buffer_size - offset, att_connection->con_handle);
690     offset += bytes_copied;
691 
692     response_buffer[0] = ATT_READ_RESPONSE;
693     return offset;
694 }
695 
696 static uint16_t handle_read_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
697                              uint8_t * response_buffer, uint16_t response_buffer_size){
698 
699     if (request_len != 3u) return setup_error_invalid_pdu(response_buffer, ATT_READ_REQUEST);
700 
701     uint16_t handle = little_endian_read_16(request_buffer, 1);
702     return handle_read_request2(att_connection, response_buffer, response_buffer_size, handle);
703 }
704 
705 //s
706 // MARK: ATT_READ_BLOB_REQUEST 0x0c
707 //
708 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){
709     log_info("ATT_READ_BLOB_REQUEST: handle %04x, offset %u", handle, value_offset);
710     uint8_t request_type = ATT_READ_BLOB_REQUEST;
711 
712     att_iterator_t it;
713     int ok = att_find_handle(&it, handle);
714     if (!ok){
715         return setup_error_invalid_handle(response_buffer, request_type, handle);
716     }
717 
718     // check if handle can be read
719     if ((it.flags & ATT_PROPERTY_READ) == 0u) {
720         return setup_error_read_not_permitted(response_buffer, request_type, handle);
721     }
722 
723     // check security requirements
724     uint8_t error_code = att_validate_security(att_connection, ATT_READ, &it);
725     if (error_code) {
726         return setup_error(response_buffer, request_type, handle, error_code);
727     }
728 
729     att_update_value_len(&it, att_connection->con_handle);
730 
731 #ifdef ENABLE_ATT_DELAYED_RESPONSE
732     if (it.value_len == ATT_READ_RESPONSE_PENDING) return ATT_READ_RESPONSE_PENDING;
733 #endif
734 
735     if (value_offset > it.value_len){
736         return setup_error_invalid_offset(response_buffer, request_type, handle);
737     }
738 
739     // prepare response
740     response_buffer[0] = ATT_READ_BLOB_RESPONSE;
741     uint16_t offset   = 1;
742 
743     // fetch more data if available
744     if (value_offset < it.value_len){
745         uint16_t bytes_copied = att_copy_value(&it, value_offset, &response_buffer[offset], response_buffer_size - offset, att_connection->con_handle);
746         offset += bytes_copied;
747     }
748     return offset;
749 }
750 
751 static uint16_t handle_read_blob_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
752                                   uint8_t * response_buffer, uint16_t response_buffer_size){
753 
754     if (request_len != 5u) return setup_error_invalid_pdu(response_buffer, ATT_READ_BLOB_REQUEST);
755 
756     uint16_t handle = little_endian_read_16(request_buffer, 1);
757     uint16_t value_offset = little_endian_read_16(request_buffer, 3);
758     return handle_read_blob_request2(att_connection, response_buffer, response_buffer_size, handle, value_offset);
759 }
760 
761 //
762 // MARK: ATT_READ_MULTIPLE_REQUEST 0x0e
763 //
764 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){
765     log_info("ATT_READ_MULTIPLE_REQUEST: num handles %u", num_handles);
766     uint8_t request_type = ATT_READ_MULTIPLE_REQUEST;
767 
768     // TODO: figure out which error to respond with
769     // if (num_handles < 2){
770     //     return setup_error(response_buffer, ATT_READ_MULTIPLE_REQUEST, handle, ???);
771     // }
772 
773     uint16_t offset   = 1;
774 
775     int i;
776     uint8_t error_code = 0;
777     uint16_t handle = 0;
778 
779 #ifdef ENABLE_ATT_DELAYED_RESPONSE
780     bool read_request_pending = false;
781 #endif
782 
783     for (i=0;i<num_handles;i++){
784         handle = little_endian_read_16(handles, i << 1);
785 
786         if (handle == 0u){
787             return setup_error_invalid_handle(response_buffer, request_type, handle);
788         }
789 
790         att_iterator_t it;
791 
792         int ok = att_find_handle(&it, handle);
793         if (!ok){
794             return setup_error_invalid_handle(response_buffer, request_type, handle);
795         }
796 
797         // check if handle can be read
798         if ((it.flags & ATT_PROPERTY_READ) == 0u) {
799             error_code = ATT_ERROR_READ_NOT_PERMITTED;
800             break;
801         }
802 
803         // check security requirements
804         error_code = att_validate_security(att_connection, ATT_READ, &it);
805         if (error_code) break;
806 
807         att_update_value_len(&it, att_connection->con_handle);
808 
809 #ifdef ENABLE_ATT_DELAYED_RESPONSE
810         if (it.value_len == ATT_READ_RESPONSE_PENDING) {
811             read_request_pending = true;
812         }
813         if (read_request_pending) continue;
814 #endif
815 
816         // store
817         uint16_t bytes_copied = att_copy_value(&it, 0, response_buffer + offset, response_buffer_size - offset, att_connection->con_handle);
818         offset += bytes_copied;
819     }
820 
821     if (error_code){
822         return setup_error(response_buffer, request_type, handle, error_code);
823     }
824 
825     response_buffer[0] = ATT_READ_MULTIPLE_RESPONSE;
826     return offset;
827 }
828 static uint16_t handle_read_multiple_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
829                                       uint8_t * response_buffer, uint16_t response_buffer_size){
830 
831     // 1 byte opcode + two or more attribute handles (2 bytes each)
832     if ( (request_len < 5u) || ((request_len & 1u) == 0u) ) return setup_error_invalid_pdu(response_buffer,
833                                                                                         ATT_READ_MULTIPLE_REQUEST);
834 
835     int num_handles = (request_len - 1u) >> 1u;
836     return handle_read_multiple_request2(att_connection, response_buffer, response_buffer_size, num_handles, &request_buffer[1]);
837 }
838 
839 //
840 // MARK: ATT_READ_BY_GROUP_TYPE_REQUEST 0x10
841 //
842 // Only handles GATT_PRIMARY_SERVICE_UUID and GATT_SECONDARY_SERVICE_UUID
843 // Core v4.0, vol 3, part g, 2.5.3
844 // "The «Primary Service» and «Secondary Service» grouping types may be used in the Read By Group Type Request.
845 //  The «Characteristic» grouping type shall not be used in the ATT Read By Group Type Request."
846 //
847 // NOTE: doesn't handle DYNAMIC values
848 //
849 // NOTE: we don't check for security as PRIMARY and SECONDAY SERVICE definition shouldn't be protected
850 // Core 4.0, vol 3, part g, 8.1
851 // "The list of services and characteristics that a device supports is not considered private or
852 //  confidential information, and therefore the Service and Characteristic Discovery procedures
853 //  shall always be permitted. "
854 //
855 static uint16_t handle_read_by_group_type_request2(att_connection_t * att_connection, uint8_t * response_buffer, uint16_t response_buffer_size,
856                                             uint16_t start_handle, uint16_t end_handle,
857                                             uint16_t attribute_type_len, uint8_t * attribute_type){
858 
859     UNUSED(att_connection);
860 
861     log_info("ATT_READ_BY_GROUP_TYPE_REQUEST: from %04X to %04X, buffer size %u, type: ", start_handle, end_handle, response_buffer_size);
862     log_info_hexdump(attribute_type, attribute_type_len);
863     uint8_t request_type = ATT_READ_BY_GROUP_TYPE_REQUEST;
864 
865     if ((start_handle > end_handle) || (start_handle == 0u)){
866         return setup_error_invalid_handle(response_buffer, request_type, start_handle);
867     }
868 
869     // assert UUID is primary or secondary service uuid
870     uint16_t uuid16 = uuid16_from_uuid(attribute_type_len, attribute_type);
871     if ((uuid16 != GATT_PRIMARY_SERVICE_UUID) && (uuid16 != GATT_SECONDARY_SERVICE_UUID)){
872         return setup_error(response_buffer, request_type, start_handle, ATT_ERROR_UNSUPPORTED_GROUP_TYPE);
873     }
874 
875     uint16_t offset   = 1;
876     uint16_t pair_len = 0;
877     uint16_t in_group = 0;
878     uint16_t group_start_handle = 0;
879     uint8_t const * group_start_value = NULL;
880     uint16_t prev_handle = 0;
881 
882     att_iterator_t it;
883     att_iterator_init(&it);
884     while (att_iterator_has_next(&it)){
885         att_iterator_fetch_next(&it);
886 
887         if (it.handle && (it.handle < start_handle)) continue;
888         if (it.handle > end_handle) break;  // (1)
889 
890         // log_info("Handle 0x%04x", it.handle);
891 
892         // close current tag, if within a group and a new service definition starts or we reach end of att db
893         if (in_group &&
894             ((it.handle == 0u) || att_iterator_match_uuid16(&it, GATT_PRIMARY_SERVICE_UUID) || att_iterator_match_uuid16(&it, GATT_SECONDARY_SERVICE_UUID))){
895             // log_info("End of group, handle 0x%04x, val_len: %u", prev_handle, pair_len - 4);
896 
897             little_endian_store_16(response_buffer, offset, group_start_handle);
898             offset += 2u;
899             little_endian_store_16(response_buffer, offset, prev_handle);
900             offset += 2u;
901             (void)memcpy(response_buffer + offset, group_start_value,
902                          pair_len - 4u);
903             offset += pair_len - 4u;
904             in_group = 0;
905 
906             // check if space for another handle pair available
907             if ((offset + pair_len) > response_buffer_size){
908                 break;
909             }
910         }
911 
912         // keep track of previous handle
913         prev_handle = it.handle;
914 
915         // does current attribute match
916         // log_info("compare: %04x == %04x", *(uint16_t*) context->attribute_type, *(uint16_t*) uuid);
917         if (it.handle && att_iterator_match_uuid(&it, attribute_type, attribute_type_len)) {
918 
919             // check if value has same len as last one
920             uint16_t this_pair_len = 4u + it.value_len;
921             if (offset > 1u){
922                 if (this_pair_len != pair_len) {
923                     break;
924                 }
925             }
926 
927             // log_info("Begin of group, handle 0x%04x", it.handle);
928 
929             // first
930             if (offset == 1u) {
931                 pair_len = this_pair_len;
932                 response_buffer[offset] = this_pair_len;
933                 offset++;
934             }
935 
936             group_start_handle = it.handle;
937             group_start_value  = it.value;
938             in_group = 1;
939         }
940     }
941 
942     if (offset == 1u){
943         return setup_error_atribute_not_found(response_buffer, request_type, start_handle);
944     }
945 
946     response_buffer[0] = ATT_READ_BY_GROUP_TYPE_RESPONSE;
947     return offset;
948 }
949 static uint16_t handle_read_by_group_type_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
950                                            uint8_t * response_buffer, uint16_t response_buffer_size){
951     uint16_t attribute_type_len;
952     switch (request_len){
953         case 7:
954             attribute_type_len = 2;
955             break;
956         case 21:
957             attribute_type_len = 16;
958             break;
959         default:
960             return setup_error_invalid_pdu(response_buffer, ATT_READ_BY_GROUP_TYPE_REQUEST);
961     }
962 
963     uint16_t start_handle = little_endian_read_16(request_buffer, 1);
964     uint16_t end_handle = little_endian_read_16(request_buffer, 3);
965     return handle_read_by_group_type_request2(att_connection, response_buffer, response_buffer_size, start_handle, end_handle, attribute_type_len, &request_buffer[5]);
966 }
967 
968 //
969 // MARK: ATT_WRITE_REQUEST 0x12
970 static uint16_t handle_write_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
971                               uint8_t * response_buffer, uint16_t response_buffer_size){
972 
973     UNUSED(response_buffer_size);
974 
975     if (request_len < 3u) return setup_error_invalid_pdu(response_buffer, ATT_WRITE_REQUEST);
976 
977     uint8_t request_type = ATT_WRITE_REQUEST;
978 
979     uint16_t handle = little_endian_read_16(request_buffer, 1);
980     att_iterator_t it;
981     int ok = att_find_handle(&it, handle);
982     if (!ok) {
983         return setup_error_invalid_handle(response_buffer, request_type, handle);
984     }
985     if (att_write_callback == NULL) {
986         return setup_error_write_not_permitted(response_buffer, request_type, handle);
987     }
988     if ((it.flags & ATT_PROPERTY_WRITE) == 0u) {
989         return setup_error_write_not_permitted(response_buffer, request_type, handle);
990     }
991     if ((it.flags & ATT_PROPERTY_DYNAMIC) == 0u) {
992         return setup_error_write_not_permitted(response_buffer, request_type, handle);
993     }
994     // check security requirements
995     int error_code = att_validate_security(att_connection, ATT_WRITE, &it);
996     if (error_code) {
997         return setup_error(response_buffer, request_type, handle, error_code);
998     }
999     att_persistent_ccc_cache(&it);
1000     error_code = (*att_write_callback)(att_connection->con_handle, handle, ATT_TRANSACTION_MODE_NONE, 0u, request_buffer + 3u, request_len - 3u);
1001 
1002 #ifdef ENABLE_ATT_DELAYED_RESPONSE
1003     if (error_code == ATT_ERROR_WRITE_RESPONSE_PENDING) return ATT_INTERNAL_WRITE_RESPONSE_PENDING;
1004 #endif
1005 
1006     if (error_code) {
1007         return setup_error(response_buffer, request_type, handle, error_code);
1008     }
1009     response_buffer[0] = ATT_WRITE_RESPONSE;
1010     return 1;
1011 }
1012 
1013 //
1014 // MARK: ATT_PREPARE_WRITE_REQUEST 0x16
1015 static uint16_t handle_prepare_write_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
1016                                       uint8_t * response_buffer, uint16_t response_buffer_size){
1017 
1018     uint8_t request_type = ATT_PREPARE_WRITE_REQUEST;
1019 
1020     if (request_len < 5u) return setup_error_invalid_pdu(response_buffer, request_type);
1021 
1022     uint16_t handle = little_endian_read_16(request_buffer, 1);
1023     uint16_t offset = little_endian_read_16(request_buffer, 3);
1024     if (att_write_callback == NULL) {
1025         return setup_error_write_not_permitted(response_buffer, request_type, handle);
1026     }
1027     att_iterator_t it;
1028     if (att_find_handle(&it, handle) == 0) {
1029         return setup_error_invalid_handle(response_buffer, request_type, handle);
1030     }
1031     if ((it.flags & ATT_PROPERTY_WRITE) == 0u) {
1032         return setup_error_write_not_permitted(response_buffer, request_type, handle);
1033     }
1034     if ((it.flags & ATT_PROPERTY_DYNAMIC) == 0u) {
1035         return setup_error_write_not_permitted(response_buffer, request_type, handle);
1036     }
1037     // check security requirements
1038     int error_code = att_validate_security(att_connection, ATT_WRITE, &it);
1039     if (error_code) {
1040         return setup_error(response_buffer, request_type, handle, error_code);
1041     }
1042 
1043     error_code = (*att_write_callback)(att_connection->con_handle, handle, ATT_TRANSACTION_MODE_ACTIVE, offset, request_buffer + 5u, request_len - 5u);
1044     switch (error_code){
1045         case 0:
1046             break;
1047         case ATT_ERROR_INVALID_OFFSET:
1048         case ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH:
1049             // postpone to execute write request
1050             att_prepare_write_update_errors(error_code, handle);
1051             break;
1052 #ifdef ENABLE_ATT_DELAYED_RESPONSE
1053         case ATT_ERROR_WRITE_RESPONSE_PENDING:
1054             return ATT_INTERNAL_WRITE_RESPONSE_PENDING;
1055 #endif
1056         default:
1057             return setup_error(response_buffer, request_type, handle, error_code);
1058     }
1059 
1060     // response: echo request
1061     uint16_t bytes_to_echo = btstack_min(request_len, response_buffer_size);
1062     (void)memcpy(response_buffer, request_buffer, bytes_to_echo);
1063     response_buffer[0] = ATT_PREPARE_WRITE_RESPONSE;
1064     return request_len;
1065 }
1066 
1067 /*
1068  * @brief transcation queue of prepared writes, e.g., after disconnect
1069  */
1070 void att_clear_transaction_queue(att_connection_t * att_connection){
1071     (*att_write_callback)(att_connection->con_handle, 0, ATT_TRANSACTION_MODE_CANCEL, 0, NULL, 0);
1072 }
1073 
1074 // MARK: ATT_EXECUTE_WRITE_REQUEST 0x18
1075 // NOTE: security has been verified by handle_prepare_write_request
1076 static uint16_t handle_execute_write_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
1077                                       uint8_t * response_buffer, uint16_t response_buffer_size){
1078 
1079     UNUSED(response_buffer_size);
1080 
1081     uint8_t request_type = ATT_EXECUTE_WRITE_REQUEST;
1082 
1083     if (request_len < 2u) return setup_error_invalid_pdu(response_buffer, request_type);
1084 
1085     if (att_write_callback == NULL) {
1086         return setup_error_write_not_permitted(response_buffer, request_type, 0);
1087     }
1088 
1089     if (request_buffer[1]) {
1090         // validate queued write
1091         if (att_prepare_write_error_code == 0){
1092             att_prepare_write_error_code = (*att_write_callback)(att_connection->con_handle, 0, ATT_TRANSACTION_MODE_VALIDATE, 0, NULL, 0);
1093         }
1094 #ifdef ENABLE_ATT_DELAYED_RESPONSE
1095         if (att_prepare_write_error_code == ATT_ERROR_WRITE_RESPONSE_PENDING) return ATT_INTERNAL_WRITE_RESPONSE_PENDING;
1096 #endif
1097         // deliver queued errors
1098         if (att_prepare_write_error_code){
1099             att_clear_transaction_queue(att_connection);
1100             uint8_t  error_code = att_prepare_write_error_code;
1101             uint16_t handle     = att_prepare_write_error_handle;
1102             att_prepare_write_reset();
1103             return setup_error(response_buffer, request_type, handle, error_code);
1104         }
1105         att_write_callback(att_connection->con_handle, 0, ATT_TRANSACTION_MODE_EXECUTE, 0, NULL, 0);
1106     } else {
1107         att_clear_transaction_queue(att_connection);
1108     }
1109     response_buffer[0] = ATT_EXECUTE_WRITE_RESPONSE;
1110     return 1;
1111 }
1112 
1113 // MARK: ATT_WRITE_COMMAND 0x52
1114 // Core 4.0, vol 3, part F, 3.4.5.3
1115 // "No Error Response or Write Response shall be sent in response to this command"
1116 static void handle_write_command(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len, uint16_t required_flags){
1117 
1118     if (request_len < 3u) return;
1119 
1120     uint16_t handle = little_endian_read_16(request_buffer, 1);
1121     if (att_write_callback == NULL) return;
1122 
1123     att_iterator_t it;
1124     int ok = att_find_handle(&it, handle);
1125     if (!ok) return;
1126     if ((it.flags & ATT_PROPERTY_DYNAMIC) == 0u) return;
1127     if ((it.flags & required_flags) == 0u) return;
1128     if (att_validate_security(att_connection, ATT_WRITE, &it)) return;
1129     att_persistent_ccc_cache(&it);
1130     (*att_write_callback)(att_connection->con_handle, handle, ATT_TRANSACTION_MODE_NONE, 0u, request_buffer + 3u, request_len - 3u);
1131 }
1132 
1133 // MARK: helper for ATT_HANDLE_VALUE_NOTIFICATION and ATT_HANDLE_VALUE_INDICATION
1134 static uint16_t prepare_handle_value(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     little_endian_store_16(response_buffer, 1, handle);
1140     if (value_len > (att_connection->mtu - 3u)){
1141         value_len = att_connection->mtu - 3u;
1142     }
1143     (void)memcpy(&response_buffer[3], value, value_len);
1144     return value_len + 3u;
1145 }
1146 
1147 // MARK: ATT_HANDLE_VALUE_NOTIFICATION 0x1b
1148 uint16_t att_prepare_handle_value_notification(att_connection_t * att_connection,
1149                                                uint16_t handle,
1150                                                const uint8_t *value,
1151                                                uint16_t value_len,
1152                                                uint8_t * response_buffer){
1153 
1154     response_buffer[0] = ATT_HANDLE_VALUE_NOTIFICATION;
1155     return prepare_handle_value(att_connection, handle, value, value_len, response_buffer);
1156 }
1157 
1158 // MARK: ATT_HANDLE_VALUE_INDICATION 0x1d
1159 uint16_t att_prepare_handle_value_indication(att_connection_t * att_connection,
1160                                              uint16_t handle,
1161                                              const uint8_t *value,
1162                                              uint16_t value_len,
1163                                              uint8_t * response_buffer){
1164 
1165     response_buffer[0] = ATT_HANDLE_VALUE_INDICATION;
1166     return prepare_handle_value(att_connection, handle, value, value_len, response_buffer);
1167 }
1168 
1169 // MARK: Dispatcher
1170 uint16_t att_handle_request(att_connection_t * att_connection,
1171                             uint8_t * request_buffer,
1172                             uint16_t request_len,
1173                             uint8_t * response_buffer){
1174     uint16_t response_len = 0;
1175     uint16_t response_buffer_size = att_connection->mtu;
1176 
1177     switch (request_buffer[0]){
1178         case ATT_EXCHANGE_MTU_REQUEST:
1179             response_len = handle_exchange_mtu_request(att_connection, request_buffer, request_len, response_buffer);
1180             break;
1181         case ATT_FIND_INFORMATION_REQUEST:
1182             response_len = handle_find_information_request(att_connection, request_buffer, request_len,response_buffer, response_buffer_size);
1183             break;
1184         case ATT_FIND_BY_TYPE_VALUE_REQUEST:
1185             response_len = handle_find_by_type_value_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1186             break;
1187         case ATT_READ_BY_TYPE_REQUEST:
1188             response_len = handle_read_by_type_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1189             break;
1190         case ATT_READ_REQUEST:
1191             response_len = handle_read_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1192             break;
1193         case ATT_READ_BLOB_REQUEST:
1194             response_len = handle_read_blob_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1195             break;
1196         case ATT_READ_MULTIPLE_REQUEST:
1197             response_len = handle_read_multiple_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1198             break;
1199         case ATT_READ_BY_GROUP_TYPE_REQUEST:
1200             response_len = handle_read_by_group_type_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1201             break;
1202         case ATT_WRITE_REQUEST:
1203             response_len = handle_write_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1204             break;
1205         case ATT_PREPARE_WRITE_REQUEST:
1206             response_len = handle_prepare_write_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1207             break;
1208         case ATT_EXECUTE_WRITE_REQUEST:
1209             response_len = handle_execute_write_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1210             break;
1211         case ATT_WRITE_COMMAND:
1212             handle_write_command(att_connection, request_buffer, request_len, ATT_PROPERTY_WRITE_WITHOUT_RESPONSE);
1213             break;
1214 #ifdef ENABLE_LE_SIGNED_WRITE
1215         case ATT_SIGNED_WRITE_COMMAND:
1216             handle_write_command(att_connection, request_buffer, request_len, ATT_PROPERTY_AUTHENTICATED_SIGNED_WRITE);
1217             break;
1218 #endif
1219         default:
1220             log_info("Unhandled ATT Command: %02X, DATA: ", request_buffer[0]);
1221             log_info_hexdump(&request_buffer[9u], request_len-9u);
1222             break;
1223     }
1224     return response_len;
1225 }
1226 
1227 // returns 1 if service found. only primary service.
1228 bool gatt_server_get_get_handle_range_for_service_with_uuid16(uint16_t uuid16, uint16_t * start_handle, uint16_t * end_handle){
1229     uint16_t in_group    = 0;
1230     uint16_t prev_handle = 0;
1231 
1232     uint8_t attribute_value[2];
1233     int attribute_len = sizeof(attribute_value);
1234     little_endian_store_16(attribute_value, 0, uuid16);
1235 
1236     att_iterator_t it;
1237     att_iterator_init(&it);
1238     while (att_iterator_has_next(&it)){
1239         att_iterator_fetch_next(&it);
1240         int new_service_started = att_iterator_match_uuid16(&it, GATT_PRIMARY_SERVICE_UUID) || att_iterator_match_uuid16(&it, GATT_SECONDARY_SERVICE_UUID);
1241 
1242         // close current tag, if within a group and a new service definition starts or we reach end of att db
1243         if (in_group &&
1244             ((it.handle == 0u) || new_service_started)){
1245             *end_handle = prev_handle;
1246             return true;
1247         }
1248 
1249         // keep track of previous handle
1250         prev_handle = it.handle;
1251 
1252         // check if found
1253         if (it.handle && new_service_started && (attribute_len == it.value_len) && (memcmp(attribute_value, it.value, it.value_len) == 0)){
1254             *start_handle = it.handle;
1255             in_group = true;
1256         }
1257     }
1258     return false;
1259 }
1260 
1261 // returns false if not found
1262 uint16_t gatt_server_get_value_handle_for_characteristic_with_uuid16(uint16_t start_handle, uint16_t end_handle, uint16_t uuid16){
1263     att_iterator_t it;
1264     att_iterator_init(&it);
1265     while (att_iterator_has_next(&it)){
1266         att_iterator_fetch_next(&it);
1267         if (it.handle && (it.handle < start_handle)) continue;
1268         if (it.handle > end_handle) break;  // (1)
1269         if (it.handle == 0u) break;
1270         if (att_iterator_match_uuid16(&it, uuid16)) return it.handle;
1271     }
1272     return 0;
1273 }
1274 
1275 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){
1276     att_iterator_t it;
1277     att_iterator_init(&it);
1278     int characteristic_found = 0;
1279     while (att_iterator_has_next(&it)){
1280         att_iterator_fetch_next(&it);
1281         if (it.handle && (it.handle < start_handle)) continue;
1282         if (it.handle > end_handle) break;  // (1)
1283         if (it.handle == 0u) break;
1284         if (att_iterator_match_uuid16(&it, characteristic_uuid16)){
1285             characteristic_found = 1;
1286             continue;
1287         }
1288         if (att_iterator_match_uuid16(&it, GATT_PRIMARY_SERVICE_UUID)
1289          || att_iterator_match_uuid16(&it, GATT_SECONDARY_SERVICE_UUID)
1290          || att_iterator_match_uuid16(&it, GATT_CHARACTERISTICS_UUID)){
1291             if (characteristic_found) break;
1292             continue;
1293         }
1294         if (characteristic_found && att_iterator_match_uuid16(&it, descriptor_uuid16)){
1295             return it.handle;
1296         }
1297     }
1298     return 0;
1299 }
1300 
1301 // returns 0 if not found
1302 uint16_t gatt_server_get_client_configuration_handle_for_characteristic_with_uuid16(uint16_t start_handle, uint16_t end_handle, uint16_t characteristic_uuid16){
1303     return gatt_server_get_descriptor_handle_for_characteristic_with_uuid16(start_handle, end_handle, characteristic_uuid16, GATT_CLIENT_CHARACTERISTICS_CONFIGURATION);
1304 }
1305 // returns 0 if not found
1306 
1307 uint16_t gatt_server_get_server_configuration_handle_for_characteristic_with_uuid16(uint16_t start_handle, uint16_t end_handle, uint16_t characteristic_uuid16){
1308     return gatt_server_get_descriptor_handle_for_characteristic_with_uuid16(start_handle, end_handle, characteristic_uuid16, GATT_SERVER_CHARACTERISTICS_CONFIGURATION);
1309 }
1310 
1311 // returns 1 if service found. only primary service.
1312 int gatt_server_get_get_handle_range_for_service_with_uuid128(const uint8_t * uuid128, uint16_t * start_handle, uint16_t * end_handle){
1313     uint16_t in_group    = 0;
1314     uint16_t prev_handle = 0;
1315 
1316     uint8_t attribute_value[16];
1317     int attribute_len = sizeof(attribute_value);
1318     reverse_128(uuid128, attribute_value);
1319 
1320     att_iterator_t it;
1321     att_iterator_init(&it);
1322     while (att_iterator_has_next(&it)){
1323         att_iterator_fetch_next(&it);
1324         int new_service_started = att_iterator_match_uuid16(&it, GATT_PRIMARY_SERVICE_UUID) || att_iterator_match_uuid16(&it, GATT_SECONDARY_SERVICE_UUID);
1325 
1326         // close current tag, if within a group and a new service definition starts or we reach end of att db
1327         if (in_group &&
1328             ((it.handle == 0u) || new_service_started)){
1329             *end_handle = prev_handle;
1330             return 1;
1331         }
1332 
1333         // keep track of previous handle
1334         prev_handle = it.handle;
1335 
1336         // check if found
1337         if (it.handle && new_service_started && (attribute_len == it.value_len) && (memcmp(attribute_value, it.value, it.value_len) == 0)){
1338             *start_handle = it.handle;
1339             in_group = 1;
1340         }
1341     }
1342     return 0;
1343 }
1344 
1345 // returns 0 if not found
1346 uint16_t gatt_server_get_value_handle_for_characteristic_with_uuid128(uint16_t start_handle, uint16_t end_handle, const uint8_t * uuid128){
1347     uint8_t attribute_value[16];
1348     reverse_128(uuid128, attribute_value);
1349     att_iterator_t it;
1350     att_iterator_init(&it);
1351     while (att_iterator_has_next(&it)){
1352         att_iterator_fetch_next(&it);
1353         if (it.handle && (it.handle < start_handle)) continue;
1354         if (it.handle > end_handle) break;  // (1)
1355         if (it.handle == 0u) break;
1356         if (att_iterator_match_uuid(&it, attribute_value, 16)) return it.handle;
1357     }
1358     return 0;
1359 }
1360 
1361 // returns 0 if not found
1362 uint16_t gatt_server_get_client_configuration_handle_for_characteristic_with_uuid128(uint16_t start_handle, uint16_t end_handle, const uint8_t * uuid128){
1363     uint8_t attribute_value[16];
1364     reverse_128(uuid128, attribute_value);
1365     att_iterator_t it;
1366     att_iterator_init(&it);
1367     int characteristic_found = 0;
1368     while (att_iterator_has_next(&it)){
1369         att_iterator_fetch_next(&it);
1370         if (it.handle && (it.handle < start_handle)) continue;
1371         if (it.handle > end_handle) break;  // (1)
1372         if (it.handle == 0u) break;
1373         if (att_iterator_match_uuid(&it, attribute_value, 16)){
1374             characteristic_found = 1;
1375             continue;
1376         }
1377         if (att_iterator_match_uuid16(&it, GATT_PRIMARY_SERVICE_UUID)
1378          || att_iterator_match_uuid16(&it, GATT_SECONDARY_SERVICE_UUID)
1379          || att_iterator_match_uuid16(&it, GATT_CHARACTERISTICS_UUID)){
1380             if (characteristic_found) break;
1381             continue;
1382         }
1383         if (characteristic_found && att_iterator_match_uuid16(&it, GATT_CLIENT_CHARACTERISTICS_CONFIGURATION)){
1384             return it.handle;
1385         }
1386     }
1387     return 0;
1388 }
1389 
1390 
1391 // 1-item cache to optimize query during write_callback
1392 static void att_persistent_ccc_cache(att_iterator_t * it){
1393     att_persistent_ccc_handle = it->handle;
1394     if (it->flags & ATT_PROPERTY_UUID128){
1395         att_persistent_ccc_uuid16 = 0;
1396     } else {
1397         att_persistent_ccc_uuid16 = little_endian_read_16(it->uuid, 0);
1398     }
1399 }
1400 
1401 bool att_is_persistent_ccc(uint16_t handle){
1402     if (handle != att_persistent_ccc_handle){
1403         att_iterator_t it;
1404         int ok = att_find_handle(&it, handle);
1405         if (!ok) return false;
1406         att_persistent_ccc_cache(&it);
1407     }
1408     return att_persistent_ccc_uuid16 == GATT_CLIENT_CHARACTERISTICS_CONFIGURATION;
1409 }
1410 
1411 // att_read_callback helpers
1412 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){
1413     if (buffer){
1414         uint16_t bytes_to_copy = btstack_min(blob_size - offset, buffer_size);
1415         (void)memcpy(buffer, &blob[offset], bytes_to_copy);
1416         return bytes_to_copy;
1417     } else {
1418         return blob_size;
1419     }
1420 }
1421 
1422 uint16_t att_read_callback_handle_little_endian_32(uint32_t value, uint16_t offset, uint8_t * buffer, uint16_t buffer_size){
1423     uint8_t value_buffer[4];
1424     little_endian_store_32(value_buffer, 0, value);
1425     return att_read_callback_handle_blob(value_buffer, sizeof(value_buffer), offset, buffer, buffer_size);
1426 }
1427 
1428 uint16_t att_read_callback_handle_little_endian_16(uint16_t value, uint16_t offset, uint8_t * buffer, uint16_t buffer_size){
1429     uint8_t value_buffer[2];
1430     little_endian_store_16(value_buffer, 0, value);
1431     return att_read_callback_handle_blob(value_buffer, sizeof(value_buffer), offset, buffer, buffer_size);
1432 }
1433 
1434 uint16_t att_read_callback_handle_byte(uint8_t value, uint16_t offset, uint8_t * buffer, uint16_t buffer_size){
1435     uint8_t value_buffer[1];
1436     value_buffer[0] = value;
1437     return att_read_callback_handle_blob(value_buffer, sizeof(value_buffer), offset, buffer, buffer_size);
1438 }
1439 
1440 #ifdef ENABLE_BTP
1441 
1442 #include "btp.h"
1443 
1444 static uint8_t btp_permissions_for_flags(uint16_t flags){
1445 
1446     // see BT_GATT_PERM_*
1447     // https://docs.zephyrproject.org/latest/reference/bluetooth/gatt.html
1448     // set bit indicates requirement, e.g. BTP_GATT_PERM_READ_AUTHN requires authenticated connection
1449 
1450     uint8_t permissions = 0;
1451 
1452     uint8_t read_security_level = 0;
1453     uint8_t write_security_level = 0;
1454     if (flags & ATT_PROPERTY_READ){
1455         if (flags & ATT_PROPERTY_READ_PERMISSION_BIT_0) {
1456             read_security_level |= 1;
1457         }
1458         if (flags & ATT_PROPERTY_READ_PERMISSION_BIT_1) {
1459             read_security_level |= 2;
1460         }
1461         if (read_security_level == ATT_SECURITY_AUTHORIZED) {
1462             permissions |= BTP_GATT_PERM_READ_AUTHZ;
1463         }
1464         if (read_security_level == ATT_SECURITY_AUTHENTICATED) {
1465             permissions |= BTP_GATT_PERM_READ_AUTHN;
1466         }
1467         if (read_security_level == ATT_SECURITY_ENCRYPTED) {
1468             permissions |= BTP_GATT_PERM_READ_ENC;
1469         }
1470         if (read_security_level == ATT_SECURITY_NONE) {
1471             permissions |= BTP_GATT_PERM_READ;
1472         }
1473     }
1474     if (flags & (ATT_PROPERTY_WRITE | ATT_PROPERTY_WRITE_WITHOUT_RESPONSE)){
1475         if (flags & ATT_PROPERTY_WRITE_PERMISSION_BIT_0) {
1476             write_security_level |= 1;
1477         }
1478         if (flags & ATT_PROPERTY_WRITE_PERMISSION_BIT_1) {
1479             write_security_level |= 2;
1480         }
1481         if (write_security_level == ATT_SECURITY_AUTHORIZED) {
1482             permissions |= BTP_GATT_PERM_WRITE_AUTHZ;
1483         }
1484         if (write_security_level == ATT_SECURITY_AUTHENTICATED) {
1485             permissions |= BTP_GATT_PERM_WRITE_AUTHN;
1486         }
1487         if (write_security_level == ATT_SECURITY_ENCRYPTED) {
1488             permissions |= BTP_GATT_PERM_WRITE_ENC;
1489         }
1490         if (write_security_level == ATT_SECURITY_NONE) {
1491             permissions |= BTP_GATT_PERM_WRITE;
1492         }
1493     }
1494     return permissions;
1495 }
1496 
1497 uint16_t btp_att_get_attributes_by_uuid16(uint16_t start_handle, uint16_t end_handle, uint16_t uuid16, uint8_t * response_buffer, uint16_t response_buffer_size){
1498     log_info("btp_att_get_attributes_by_uuid16 %04x from 0x%04x to 0x%04x, db %p", uuid16, start_handle, end_handle, att_db);
1499     att_dump_attributes();
1500 
1501     uint8_t num_attributes = 0;
1502     uint16_t pos = 1;
1503 
1504     att_iterator_t  it;
1505     att_iterator_init(&it);
1506     while (att_iterator_has_next(&it) && ((pos + 6) < response_buffer_size)){
1507         att_iterator_fetch_next(&it);
1508         log_info("handle %04x", it.handle);
1509         if (it.handle == 0) break;
1510         if (it.handle < start_handle) continue;
1511         if (it.handle > end_handle) break;
1512         if ((uuid16 == 0) || att_iterator_match_uuid16(&it, uuid16)){
1513             little_endian_store_16(response_buffer, pos, it.handle);
1514             pos += 2;
1515             response_buffer[pos++] = btp_permissions_for_flags(it.flags);
1516             response_buffer[pos++] = 2;
1517             little_endian_store_16(response_buffer, pos, uuid16);
1518             pos += 2;
1519             num_attributes++;
1520         }
1521     }
1522     response_buffer[0] = num_attributes;
1523     return pos;
1524 }
1525 
1526 uint16_t btp_att_get_attributes_by_uuid128(uint16_t start_handle, uint16_t end_handle, const uint8_t * uuid128, uint8_t * response_buffer, uint16_t response_buffer_size){
1527     uint8_t num_attributes = 0;
1528     uint16_t pos = 1;
1529     att_iterator_t  it;
1530     att_iterator_init(&it);
1531     while (att_iterator_has_next(&it) && ((pos + 20) < response_buffer_size)){
1532         att_iterator_fetch_next(&it);
1533         if (it.handle == 0) break;
1534         if (it.handle < start_handle) continue;
1535         if (it.handle > end_handle) break;
1536         if (att_iterator_match_uuid(&it, (uint8_t*) uuid128, 16)){
1537             little_endian_store_16(response_buffer, pos, it.handle);
1538             pos += 2;
1539             response_buffer[pos++] = btp_permissions_for_flags(it.flags);
1540             response_buffer[pos++] = 16;
1541             reverse_128(uuid128, &response_buffer[pos]);
1542             pos += 16;
1543             num_attributes++;
1544         }
1545     }
1546     response_buffer[0] = num_attributes;
1547     return pos;
1548 }
1549 
1550 uint16_t btp_att_get_attribute_value(att_connection_t * att_connection, uint16_t attribute_handle, uint8_t * response_buffer, uint16_t response_buffer_size){
1551     att_iterator_t it;
1552     int ok = att_find_handle(&it, attribute_handle);
1553     if (!ok) return 0;
1554 
1555     uint16_t pos = 0;
1556     // field: ATT_Response - simulate READ operation on given connection
1557     response_buffer[pos++] = att_validate_security(att_connection, ATT_READ, &it);
1558     // fetch len
1559     // assume: con handle not relevant here, else, it needs to get passed in
1560     // att_update_value_len(&it, HCI_CON_HANDLE_INVALID);
1561     uint16_t bytes_to_copy = btstack_min( response_buffer_size - 3, it.value_len);
1562     little_endian_store_16(response_buffer, pos, bytes_to_copy);
1563     pos += 2;
1564     // get value - only works for non-dynamic data
1565     if (it.value){
1566         memcpy(&response_buffer[pos], it.value, bytes_to_copy);
1567         pos += bytes_to_copy;
1568     }
1569     return pos;
1570 }
1571 #endif
1572