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