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