xref: /btstack/src/ble/att_db.c (revision cd5f23a3250874824c01a2b3326a9522fea3f99f)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define BTSTACK_FILE__ "att_db.c"
39 
40 #include <string.h>
41 
42 #include "ble/att_db.h"
43 #include "ble/core.h"
44 #include "bluetooth.h"
45 #include "btstack_debug.h"
46 #include "btstack_util.h"
47 
48 // check for ENABLE_ATT_DELAYED_READ_RESPONSE -> ENABLE_ATT_DELAYED_RESPONSE,
49 #ifdef ENABLE_ATT_DELAYED_READ_RESPONSE
50     #error "ENABLE_ATT_DELAYED_READ_RESPONSE was replaced by ENABLE_ATT_DELAYED_RESPONSE. Please update btstack_config.h"
51 #endif
52 
53 typedef enum {
54     ATT_READ,
55     ATT_WRITE,
56 } att_operation_t;
57 
58 
59 static int is_Bluetooth_Base_UUID(uint8_t const *uuid){
60     // Bluetooth Base UUID 00000000-0000-1000-8000-00805F9B34FB in little endian
61     static const uint8_t bluetooth_base_uuid[] = { 0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
62 
63     if (memcmp(&uuid[0],  &bluetooth_base_uuid[0], 12) != 0) return false;
64     if (memcmp(&uuid[14], &bluetooth_base_uuid[14], 2) != 0) return false;
65     return true;
66 
67 }
68 
69 static uint16_t uuid16_from_uuid(uint16_t uuid_len, uint8_t * uuid){
70     if (uuid_len == 2u) return little_endian_read_16(uuid, 0u);
71     if (!is_Bluetooth_Base_UUID(uuid)) return 0;
72     return little_endian_read_16(uuid, 12);
73 }
74 
75 // ATT Database
76 
77 // new java-style iterator
78 typedef struct att_iterator {
79     // private
80     uint8_t const * att_ptr;
81     // public
82     uint16_t size;
83     uint16_t flags;
84     uint16_t handle;
85     uint8_t  const * uuid;
86     uint16_t value_len;
87     uint8_t  const * value;
88 } att_iterator_t;
89 
90 static void att_persistent_ccc_cache(att_iterator_t * it);
91 
92 static uint8_t const * att_db = NULL;
93 static att_read_callback_t  att_read_callback  = NULL;
94 static att_write_callback_t att_write_callback = NULL;
95 static int      att_prepare_write_error_code   = 0;
96 static uint16_t att_prepare_write_error_handle = 0x0000;
97 
98 // single cache for att_is_persistent_ccc - stores flags before write callback
99 static uint16_t att_persistent_ccc_handle;
100 static uint16_t att_persistent_ccc_uuid16;
101 
102 static void att_iterator_init(att_iterator_t *it){
103     it->att_ptr = att_db;
104 }
105 
106 static bool att_iterator_has_next(att_iterator_t *it){
107     return it->att_ptr != NULL;
108 }
109 
110 static void att_iterator_fetch_next(att_iterator_t *it){
111     it->size   = little_endian_read_16(it->att_ptr, 0);
112     if (it->size == 0u){
113         it->flags = 0;
114         it->handle = 0;
115         it->uuid = NULL;
116         it->value_len = 0;
117         it->value = NULL;
118         it->att_ptr = NULL;
119         return;
120     }
121     it->flags  = little_endian_read_16(it->att_ptr, 2);
122     it->handle = little_endian_read_16(it->att_ptr, 4);
123     it->uuid   = &it->att_ptr[6];
124     // handle 128 bit UUIDs
125     if ((it->flags & ATT_PROPERTY_UUID128) != 0u){
126         it->value_len = it->size - 22u;
127         it->value  = &it->att_ptr[22];
128     } else {
129         it->value_len = it->size - 8u;
130         it->value  = &it->att_ptr[8];
131     }
132     // advance AFTER setting values
133     it->att_ptr += it->size;
134 }
135 
136 static int att_iterator_match_uuid16(att_iterator_t *it, uint16_t uuid){
137     if (it->handle == 0u) return 0u;
138     if (it->flags & ATT_PROPERTY_UUID128){
139         if (!is_Bluetooth_Base_UUID(it->uuid)) return 0;
140         return little_endian_read_16(it->uuid, 12) == uuid;
141     }
142     return little_endian_read_16(it->uuid, 0)  == uuid;
143 }
144 
145 static int att_iterator_match_uuid(att_iterator_t *it, uint8_t *uuid, uint16_t uuid_len){
146     if (it->handle == 0u) return 0u;
147     // input: UUID16
148     if (uuid_len == 2u) {
149         return att_iterator_match_uuid16(it, little_endian_read_16(uuid, 0));
150     }
151     // input and db: UUID128
152     if ((it->flags & ATT_PROPERTY_UUID128) != 0u){
153         return memcmp(it->uuid, uuid, 16) == 0;
154     }
155     // input: UUID128, db: UUID16
156     if (!is_Bluetooth_Base_UUID(uuid)) return 0;
157     return little_endian_read_16(uuid, 12) == little_endian_read_16(it->uuid, 0);
158 }
159 
160 
161 static int att_find_handle(att_iterator_t *it, uint16_t handle){
162     if (handle == 0u) return 0u;
163     att_iterator_init(it);
164     while (att_iterator_has_next(it)){
165         att_iterator_fetch_next(it);
166         if (it->handle != handle) continue;
167         return 1;
168     }
169     return 0;
170 }
171 
172 // experimental client API
173 uint16_t att_uuid_for_handle(uint16_t attribute_handle){
174     att_iterator_t it;
175     int ok = att_find_handle(&it, attribute_handle);
176     if (!ok) return 0;
177     if ((it.flags & ATT_PROPERTY_UUID128) != 0u) return 0u;
178     return little_endian_read_16(it.uuid, 0);
179 }
180 // end of client API
181 
182 static void att_update_value_len(att_iterator_t *it, hci_con_handle_t con_handle){
183     if ((it->flags & ATT_PROPERTY_DYNAMIC) == 0u) return;
184     it->value_len = (*att_read_callback)(con_handle, it->handle, 0, NULL, 0);
185     return;
186 }
187 
188 // copy attribute value from offset into buffer with given size
189 static int att_copy_value(att_iterator_t *it, uint16_t offset, uint8_t * buffer, uint16_t buffer_size, hci_con_handle_t con_handle){
190 
191     // DYNAMIC
192     if ((it->flags & ATT_PROPERTY_DYNAMIC) != 0u){
193         return (*att_read_callback)(con_handle, it->handle, offset, buffer, buffer_size);
194     }
195 
196     // STATIC
197     uint16_t bytes_to_copy = 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     att_db = db;
211 }
212 
213 void att_set_read_callback(att_read_callback_t callback){
214     att_read_callback = callback;
215 }
216 
217 void att_set_write_callback(att_write_callback_t callback){
218     att_write_callback = callback;
219 }
220 
221 void att_dump_attributes(void){
222     att_iterator_t it;
223     att_iterator_init(&it);
224     uint8_t uuid128[16];
225     log_info("att_dump_attributes, table %p", att_db);
226     while (att_iterator_has_next(&it)){
227         att_iterator_fetch_next(&it);
228         if (it.handle == 0u) {
229             log_info("Handle: END");
230             return;
231         }
232         log_info("Handle: 0x%04x, flags: 0x%04x, uuid: ", it.handle, it.flags);
233         if ((it.flags & ATT_PROPERTY_UUID128) != 0u){
234             reverse_128(it.uuid, uuid128);
235             log_info("%s", uuid128_to_str(uuid128));
236         } else {
237             log_info("%04x", little_endian_read_16(it.uuid, 0));
238         }
239         log_info(", value_len: %u, value: ", it.value_len);
240         log_info_hexdump(it.value, it.value_len);
241     }
242 }
243 
244 static void att_prepare_write_reset(void){
245     att_prepare_write_error_code = 0;
246     att_prepare_write_error_handle = 0x0000;
247 }
248 
249 static void att_prepare_write_update_errors(uint8_t error_code, uint16_t handle){
250     // first ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH has highest priority
251     if ((error_code == ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH) && (error_code != att_prepare_write_error_code)){
252         att_prepare_write_error_code = error_code;
253         att_prepare_write_error_handle = handle;
254         return;
255     }
256     // first ATT_ERROR_INVALID_OFFSET is next
257     if ((error_code == ATT_ERROR_INVALID_OFFSET) && (att_prepare_write_error_code == 0)){
258         att_prepare_write_error_code = error_code;
259         att_prepare_write_error_handle = handle;
260         return;
261     }
262 }
263 
264 static uint16_t setup_error(uint8_t * response_buffer, uint16_t request, uint16_t handle, uint8_t error_code){
265     response_buffer[0] = ATT_ERROR_RESPONSE;
266     response_buffer[1] = request;
267     little_endian_store_16(response_buffer, 2, handle);
268     response_buffer[4] = error_code;
269     return 5;
270 }
271 
272 static inline uint16_t setup_error_read_not_permitted(uint8_t * response_buffer, uint16_t request, uint16_t start_handle){
273     return setup_error(response_buffer, request, start_handle, ATT_ERROR_READ_NOT_PERMITTED);
274 }
275 
276 static inline uint16_t setup_error_write_not_permitted(uint8_t * response_buffer, uint16_t request, uint16_t start_handle){
277     return setup_error(response_buffer, request, start_handle, ATT_ERROR_WRITE_NOT_PERMITTED);
278 }
279 
280 static inline uint16_t setup_error_atribute_not_found(uint8_t * response_buffer, uint16_t request, uint16_t start_handle){
281     return setup_error(response_buffer, request, start_handle, ATT_ERROR_ATTRIBUTE_NOT_FOUND);
282 }
283 
284 static inline uint16_t setup_error_invalid_handle(uint8_t * response_buffer, uint16_t request, uint16_t handle){
285     return setup_error(response_buffer, request, handle, ATT_ERROR_INVALID_HANDLE);
286 }
287 
288 static inline uint16_t setup_error_invalid_offset(uint8_t * response_buffer, uint16_t request, uint16_t handle){
289     return setup_error(response_buffer, request, handle, ATT_ERROR_INVALID_OFFSET);
290 }
291 
292 static inline uint16_t setup_error_invalid_pdu(uint8_t *response_buffer, uint16_t request) {
293     return setup_error(response_buffer, request, 0, ATT_ERROR_INVALID_PDU);
294 }
295 
296 static uint8_t att_validate_security(att_connection_t * att_connection, att_operation_t operation, att_iterator_t * it){
297     int required_security_level = 0;
298     bool requires_secure_connection = false;
299     switch (operation){
300         case ATT_READ:
301             if ((it->flags & ATT_PROPERTY_READ_PERMISSION_BIT_0) != 0u){
302                 required_security_level |= 1;
303             }
304             if ((it->flags & ATT_PROPERTY_READ_PERMISSION_BIT_1) != 0u){
305                 required_security_level |= 2;
306             }
307             if ((it->flags & ATT_PROPERTY_READ_PERMISSION_SC) != 0u){
308                 requires_secure_connection = true;
309             }
310             break;
311         case ATT_WRITE:
312             if ((it->flags & ATT_PROPERTY_WRITE_PERMISSION_BIT_0) != 0u){
313                 required_security_level |= 1;
314             }
315             if ((it->flags & ATT_PROPERTY_WRITE_PERMISSION_BIT_1) != 0u){
316                 required_security_level |= 2;
317             }
318             if ((it->flags & ATT_PROPERTY_WRITE_PERMISSION_SC) != 0u){
319                 requires_secure_connection = true;
320             }
321             break;
322         default:
323             btstack_assert(false);
324             break;
325     }
326 
327     uint8_t required_encryption_size = it->flags >> 12;
328     if (required_encryption_size != 0) required_encryption_size++;   // store -1 to fit into 4 bit
329 
330     log_debug("att_validate_security. flags 0x%04x (=> security level %u, key size %u) authorized %u, authenticated %u, encryption_key_size %u, secure connection %u",
331         it->flags, required_security_level, required_encryption_size, att_connection->authorized, att_connection->authenticated, att_connection->encryption_key_size, att_connection->secure_connection);
332 
333     bool sc_missing = requires_secure_connection && (att_connection->secure_connection == 0u);
334     switch (required_security_level){
335         case ATT_SECURITY_AUTHORIZED:
336             if ((att_connection->authorized == 0u) || sc_missing){
337                 return ATT_ERROR_INSUFFICIENT_AUTHORIZATION;
338             }
339             /* fall through */
340         case ATT_SECURITY_AUTHENTICATED:
341             if ((att_connection->authenticated == 0u) || sc_missing){
342                 return ATT_ERROR_INSUFFICIENT_AUTHENTICATION;
343             }
344             /* fall through */
345         case ATT_SECURITY_ENCRYPTED:
346             if ((required_encryption_size > 0u) && ((att_connection->encryption_key_size == 0u) || sc_missing)){
347                 return ATT_ERROR_INSUFFICIENT_ENCRYPTION;
348             }
349             if (required_encryption_size > att_connection->encryption_key_size){
350                 return ATT_ERROR_INSUFFICIENT_ENCRYPTION_KEY_SIZE;
351             }
352             break;
353         default:
354             break;
355     }
356     return ATT_ERROR_SUCCESS;
357 }
358 
359 //
360 // MARK: ATT_EXCHANGE_MTU_REQUEST
361 //
362 static uint16_t handle_exchange_mtu_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
363                                          uint8_t * response_buffer){
364 
365     if (request_len != 3u) return setup_error_invalid_pdu(response_buffer, ATT_EXCHANGE_MTU_REQUEST);
366 
367     uint16_t client_rx_mtu = little_endian_read_16(request_buffer, 1);
368 
369     // find min(local max mtu, remote mtu) >= ATT_DEFAULT_MTU and use as mtu for this connection
370     uint16_t min_mtu = btstack_min(client_rx_mtu, att_connection->max_mtu);
371     uint16_t new_mtu = btstack_max(ATT_DEFAULT_MTU, min_mtu);
372     att_connection->mtu_exchanged = true;
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 != 0) {
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 != 0) {
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     uint16_t offset   = 1;
770 
771     int i;
772     uint8_t error_code = 0;
773     uint16_t handle = 0;
774 
775 #ifdef ENABLE_ATT_DELAYED_RESPONSE
776     bool read_request_pending = false;
777 #endif
778 
779     for (i=0;i<num_handles;i++){
780         handle = little_endian_read_16(handles, i << 1);
781 
782         if (handle == 0u){
783             return setup_error_invalid_handle(response_buffer, request_type, handle);
784         }
785 
786         att_iterator_t it;
787 
788         int ok = att_find_handle(&it, handle);
789         if (!ok){
790             return setup_error_invalid_handle(response_buffer, request_type, handle);
791         }
792 
793         // check if handle can be read
794         if ((it.flags & ATT_PROPERTY_READ) == 0u) {
795             error_code = ATT_ERROR_READ_NOT_PERMITTED;
796             break;
797         }
798 
799         // check security requirements
800         error_code = att_validate_security(att_connection, ATT_READ, &it);
801         if (error_code != 0) break;
802 
803         att_update_value_len(&it, att_connection->con_handle);
804 
805 #ifdef ENABLE_ATT_DELAYED_RESPONSE
806         if (it.value_len == ATT_READ_RESPONSE_PENDING) {
807             read_request_pending = true;
808         }
809         if (read_request_pending) continue;
810 #endif
811 
812         // store
813         uint16_t bytes_copied = att_copy_value(&it, 0, response_buffer + offset, response_buffer_size - offset, att_connection->con_handle);
814         offset += bytes_copied;
815     }
816 
817     if (error_code != 0){
818         return setup_error(response_buffer, request_type, handle, error_code);
819     }
820 
821     response_buffer[0] = ATT_READ_MULTIPLE_RESPONSE;
822     return offset;
823 }
824 static uint16_t handle_read_multiple_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
825                                       uint8_t * response_buffer, uint16_t response_buffer_size){
826 
827     // 1 byte opcode + two or more attribute handles (2 bytes each)
828     if ( (request_len < 5u) || ((request_len & 1u) == 0u) ) return setup_error_invalid_pdu(response_buffer,
829                                                                                         ATT_READ_MULTIPLE_REQUEST);
830 
831     int num_handles = (request_len - 1u) >> 1u;
832     return handle_read_multiple_request2(att_connection, response_buffer, response_buffer_size, num_handles, &request_buffer[1]);
833 }
834 
835 //
836 // MARK: ATT_READ_BY_GROUP_TYPE_REQUEST 0x10
837 //
838 // Only handles GATT_PRIMARY_SERVICE_UUID and GATT_SECONDARY_SERVICE_UUID
839 // Core v4.0, vol 3, part g, 2.5.3
840 // "The «Primary Service» and «Secondary Service» grouping types may be used in the Read By Group Type Request.
841 //  The «Characteristic» grouping type shall not be used in the ATT Read By Group Type Request."
842 //
843 // NOTE: doesn't handle DYNAMIC values
844 //
845 // NOTE: we don't check for security as PRIMARY and SECONDAY SERVICE definition shouldn't be protected
846 // Core 4.0, vol 3, part g, 8.1
847 // "The list of services and characteristics that a device supports is not considered private or
848 //  confidential information, and therefore the Service and Characteristic Discovery procedures
849 //  shall always be permitted. "
850 //
851 static uint16_t handle_read_by_group_type_request2(att_connection_t * att_connection, uint8_t * response_buffer, uint16_t response_buffer_size,
852                                             uint16_t start_handle, uint16_t end_handle,
853                                             uint16_t attribute_type_len, uint8_t * attribute_type){
854 
855     UNUSED(att_connection);
856 
857     log_info("ATT_READ_BY_GROUP_TYPE_REQUEST: from %04X to %04X, buffer size %u, type: ", start_handle, end_handle, response_buffer_size);
858     log_info_hexdump(attribute_type, attribute_type_len);
859     uint8_t request_type = ATT_READ_BY_GROUP_TYPE_REQUEST;
860 
861     if ((start_handle > end_handle) || (start_handle == 0u)){
862         return setup_error_invalid_handle(response_buffer, request_type, start_handle);
863     }
864 
865     // assert UUID is primary or secondary service uuid
866     uint16_t uuid16 = uuid16_from_uuid(attribute_type_len, attribute_type);
867     if ((uuid16 != GATT_PRIMARY_SERVICE_UUID) && (uuid16 != GATT_SECONDARY_SERVICE_UUID)){
868         return setup_error(response_buffer, request_type, start_handle, ATT_ERROR_UNSUPPORTED_GROUP_TYPE);
869     }
870 
871     uint16_t offset   = 1;
872     uint16_t pair_len = 0;
873     uint16_t in_group = 0;
874     uint16_t group_start_handle = 0;
875     uint8_t const * group_start_value = NULL;
876     uint16_t prev_handle = 0;
877 
878     att_iterator_t it;
879     att_iterator_init(&it);
880     while (att_iterator_has_next(&it)){
881         att_iterator_fetch_next(&it);
882 
883         if (it.handle && (it.handle < start_handle)) continue;
884         if (it.handle > end_handle) break;  // (1)
885 
886         // log_info("Handle 0x%04x", it.handle);
887 
888         // close current tag, if within a group and a new service definition starts or we reach end of att db
889         if (in_group &&
890             ((it.handle == 0u) || att_iterator_match_uuid16(&it, GATT_PRIMARY_SERVICE_UUID) || att_iterator_match_uuid16(&it, GATT_SECONDARY_SERVICE_UUID))){
891             // log_info("End of group, handle 0x%04x, val_len: %u", prev_handle, pair_len - 4);
892 
893             little_endian_store_16(response_buffer, offset, group_start_handle);
894             offset += 2u;
895             little_endian_store_16(response_buffer, offset, prev_handle);
896             offset += 2u;
897             (void)memcpy(response_buffer + offset, group_start_value,
898                          pair_len - 4u);
899             offset += pair_len - 4u;
900             in_group = 0;
901 
902             // check if space for another handle pair available
903             if ((offset + pair_len) > response_buffer_size){
904                 break;
905             }
906         }
907 
908         // keep track of previous handle
909         prev_handle = it.handle;
910 
911         // does current attribute match
912         // log_info("compare: %04x == %04x", *(uint16_t*) context->attribute_type, *(uint16_t*) uuid);
913         if (it.handle && att_iterator_match_uuid(&it, attribute_type, attribute_type_len)) {
914 
915             // check if value has same len as last one
916             uint16_t this_pair_len = 4u + it.value_len;
917             if (offset > 1u){
918                 if (this_pair_len != pair_len) {
919                     break;
920                 }
921             }
922 
923             // log_info("Begin of group, handle 0x%04x", it.handle);
924 
925             // first
926             if (offset == 1u) {
927                 pair_len = this_pair_len;
928                 response_buffer[offset] = this_pair_len;
929                 offset++;
930             }
931 
932             group_start_handle = it.handle;
933             group_start_value  = it.value;
934             in_group = 1;
935         }
936     }
937 
938     if (offset == 1u){
939         return setup_error_atribute_not_found(response_buffer, request_type, start_handle);
940     }
941 
942     response_buffer[0] = ATT_READ_BY_GROUP_TYPE_RESPONSE;
943     return offset;
944 }
945 static uint16_t handle_read_by_group_type_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
946                                            uint8_t * response_buffer, uint16_t response_buffer_size){
947     uint16_t attribute_type_len;
948     switch (request_len){
949         case 7:
950             attribute_type_len = 2;
951             break;
952         case 21:
953             attribute_type_len = 16;
954             break;
955         default:
956             return setup_error_invalid_pdu(response_buffer, ATT_READ_BY_GROUP_TYPE_REQUEST);
957     }
958 
959     uint16_t start_handle = little_endian_read_16(request_buffer, 1);
960     uint16_t end_handle = little_endian_read_16(request_buffer, 3);
961     return handle_read_by_group_type_request2(att_connection, response_buffer, response_buffer_size, start_handle, end_handle, attribute_type_len, &request_buffer[5]);
962 }
963 
964 //
965 // MARK: ATT_WRITE_REQUEST 0x12
966 static uint16_t handle_write_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
967                               uint8_t * response_buffer, uint16_t response_buffer_size){
968 
969     UNUSED(response_buffer_size);
970 
971     if (request_len < 3u) return setup_error_invalid_pdu(response_buffer, ATT_WRITE_REQUEST);
972 
973     uint8_t request_type = ATT_WRITE_REQUEST;
974 
975     uint16_t handle = little_endian_read_16(request_buffer, 1);
976     att_iterator_t it;
977     int ok = att_find_handle(&it, handle);
978     if (!ok) {
979         return setup_error_invalid_handle(response_buffer, request_type, handle);
980     }
981     if (att_write_callback == NULL) {
982         return setup_error_write_not_permitted(response_buffer, request_type, handle);
983     }
984     if ((it.flags & ATT_PROPERTY_WRITE) == 0u) {
985         return setup_error_write_not_permitted(response_buffer, request_type, handle);
986     }
987     if ((it.flags & ATT_PROPERTY_DYNAMIC) == 0u) {
988         return setup_error_write_not_permitted(response_buffer, request_type, handle);
989     }
990     // check security requirements
991     int error_code = att_validate_security(att_connection, ATT_WRITE, &it);
992     if (error_code != 0) {
993         return setup_error(response_buffer, request_type, handle, error_code);
994     }
995     att_persistent_ccc_cache(&it);
996     error_code = (*att_write_callback)(att_connection->con_handle, handle, ATT_TRANSACTION_MODE_NONE, 0u, request_buffer + 3u, request_len - 3u);
997 
998 #ifdef ENABLE_ATT_DELAYED_RESPONSE
999     if (error_code == ATT_ERROR_WRITE_RESPONSE_PENDING) return ATT_INTERNAL_WRITE_RESPONSE_PENDING;
1000 #endif
1001 
1002     if (error_code != 0) {
1003         return setup_error(response_buffer, request_type, handle, error_code);
1004     }
1005     response_buffer[0] = ATT_WRITE_RESPONSE;
1006     return 1;
1007 }
1008 
1009 //
1010 // MARK: ATT_PREPARE_WRITE_REQUEST 0x16
1011 static uint16_t handle_prepare_write_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
1012                                       uint8_t * response_buffer, uint16_t response_buffer_size){
1013 
1014     uint8_t request_type = ATT_PREPARE_WRITE_REQUEST;
1015 
1016     if (request_len < 5u) return setup_error_invalid_pdu(response_buffer, request_type);
1017 
1018     uint16_t handle = little_endian_read_16(request_buffer, 1);
1019     uint16_t offset = little_endian_read_16(request_buffer, 3);
1020     if (att_write_callback == NULL) {
1021         return setup_error_write_not_permitted(response_buffer, request_type, handle);
1022     }
1023     att_iterator_t it;
1024     if (att_find_handle(&it, handle) == 0) {
1025         return setup_error_invalid_handle(response_buffer, request_type, handle);
1026     }
1027     if ((it.flags & ATT_PROPERTY_WRITE) == 0u) {
1028         return setup_error_write_not_permitted(response_buffer, request_type, handle);
1029     }
1030     if ((it.flags & ATT_PROPERTY_DYNAMIC) == 0u) {
1031         return setup_error_write_not_permitted(response_buffer, request_type, handle);
1032     }
1033     // check security requirements
1034     int error_code = att_validate_security(att_connection, ATT_WRITE, &it);
1035     if (error_code != 0) {
1036         return setup_error(response_buffer, request_type, handle, error_code);
1037     }
1038 
1039     error_code = (*att_write_callback)(att_connection->con_handle, handle, ATT_TRANSACTION_MODE_ACTIVE, offset, request_buffer + 5u, request_len - 5u);
1040     switch (error_code){
1041         case 0:
1042             break;
1043         case ATT_ERROR_INVALID_OFFSET:
1044         case ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH:
1045             // postpone to execute write request
1046             att_prepare_write_update_errors(error_code, handle);
1047             break;
1048 #ifdef ENABLE_ATT_DELAYED_RESPONSE
1049         case ATT_ERROR_WRITE_RESPONSE_PENDING:
1050             return ATT_INTERNAL_WRITE_RESPONSE_PENDING;
1051 #endif
1052         default:
1053             return setup_error(response_buffer, request_type, handle, error_code);
1054     }
1055 
1056     // response: echo request
1057     uint16_t bytes_to_echo = btstack_min(request_len, response_buffer_size);
1058     (void)memcpy(response_buffer, request_buffer, bytes_to_echo);
1059     response_buffer[0] = ATT_PREPARE_WRITE_RESPONSE;
1060     return request_len;
1061 }
1062 
1063 /*
1064  * @brief transcation queue of prepared writes, e.g., after disconnect
1065  */
1066 void att_clear_transaction_queue(att_connection_t * att_connection){
1067     (*att_write_callback)(att_connection->con_handle, 0, ATT_TRANSACTION_MODE_CANCEL, 0, NULL, 0);
1068 }
1069 
1070 // MARK: ATT_EXECUTE_WRITE_REQUEST 0x18
1071 // NOTE: security has been verified by handle_prepare_write_request
1072 static uint16_t handle_execute_write_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
1073                                       uint8_t * response_buffer, uint16_t response_buffer_size){
1074 
1075     UNUSED(response_buffer_size);
1076 
1077     uint8_t request_type = ATT_EXECUTE_WRITE_REQUEST;
1078 
1079     if (request_len < 2u) return setup_error_invalid_pdu(response_buffer, request_type);
1080 
1081     if (att_write_callback == NULL) {
1082         return setup_error_write_not_permitted(response_buffer, request_type, 0);
1083     }
1084 
1085     if (request_buffer[1]) {
1086         // validate queued write
1087         if (att_prepare_write_error_code == 0){
1088             att_prepare_write_error_code = (*att_write_callback)(att_connection->con_handle, 0, ATT_TRANSACTION_MODE_VALIDATE, 0, NULL, 0);
1089         }
1090 #ifdef ENABLE_ATT_DELAYED_RESPONSE
1091         if (att_prepare_write_error_code == ATT_ERROR_WRITE_RESPONSE_PENDING) return ATT_INTERNAL_WRITE_RESPONSE_PENDING;
1092 #endif
1093         // deliver queued errors
1094         if (att_prepare_write_error_code != 0){
1095             att_clear_transaction_queue(att_connection);
1096             uint8_t  error_code = att_prepare_write_error_code;
1097             uint16_t handle     = att_prepare_write_error_handle;
1098             att_prepare_write_reset();
1099             return setup_error(response_buffer, request_type, handle, error_code);
1100         }
1101         att_write_callback(att_connection->con_handle, 0, ATT_TRANSACTION_MODE_EXECUTE, 0, NULL, 0);
1102     } else {
1103         att_clear_transaction_queue(att_connection);
1104     }
1105     response_buffer[0] = ATT_EXECUTE_WRITE_RESPONSE;
1106     return 1;
1107 }
1108 
1109 // MARK: ATT_WRITE_COMMAND 0x52
1110 // Core 4.0, vol 3, part F, 3.4.5.3
1111 // "No Error Response or Write Response shall be sent in response to this command"
1112 static void handle_write_command(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len, uint16_t required_flags){
1113 
1114     if (request_len < 3u) return;
1115 
1116     uint16_t handle = little_endian_read_16(request_buffer, 1);
1117     if (att_write_callback == NULL) return;
1118 
1119     att_iterator_t it;
1120     int ok = att_find_handle(&it, handle);
1121     if (!ok) return;
1122     if ((it.flags & ATT_PROPERTY_DYNAMIC) == 0u) return;
1123     if ((it.flags & required_flags) == 0u) return;
1124     if (att_validate_security(att_connection, ATT_WRITE, &it)) return;
1125     att_persistent_ccc_cache(&it);
1126     (*att_write_callback)(att_connection->con_handle, handle, ATT_TRANSACTION_MODE_NONE, 0u, request_buffer + 3u, request_len - 3u);
1127 }
1128 
1129 // MARK: helper for ATT_HANDLE_VALUE_NOTIFICATION and ATT_HANDLE_VALUE_INDICATION
1130 static uint16_t prepare_handle_value(att_connection_t * att_connection,
1131                                      uint16_t handle,
1132                                      const uint8_t *value,
1133                                      uint16_t value_len,
1134                                      uint8_t * response_buffer){
1135     little_endian_store_16(response_buffer, 1, handle);
1136     if (value_len > (att_connection->mtu - 3u)){
1137         value_len = att_connection->mtu - 3u;
1138     }
1139     (void)memcpy(&response_buffer[3], value, value_len);
1140     return value_len + 3u;
1141 }
1142 
1143 // MARK: ATT_HANDLE_VALUE_NOTIFICATION 0x1b
1144 uint16_t att_prepare_handle_value_notification(att_connection_t * att_connection,
1145                                                uint16_t handle,
1146                                                const uint8_t *value,
1147                                                uint16_t value_len,
1148                                                uint8_t * response_buffer){
1149 
1150     response_buffer[0] = ATT_HANDLE_VALUE_NOTIFICATION;
1151     return prepare_handle_value(att_connection, handle, value, value_len, response_buffer);
1152 }
1153 
1154 // MARK: ATT_HANDLE_VALUE_INDICATION 0x1d
1155 uint16_t att_prepare_handle_value_indication(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 
1161     response_buffer[0] = ATT_HANDLE_VALUE_INDICATION;
1162     return prepare_handle_value(att_connection, handle, value, value_len, response_buffer);
1163 }
1164 
1165 // MARK: Dispatcher
1166 uint16_t att_handle_request(att_connection_t * att_connection,
1167                             uint8_t * request_buffer,
1168                             uint16_t request_len,
1169                             uint8_t * response_buffer){
1170     uint16_t response_len = 0;
1171     uint16_t response_buffer_size = att_connection->mtu;
1172 
1173     switch (request_buffer[0]){
1174         case ATT_EXCHANGE_MTU_REQUEST:
1175             response_len = handle_exchange_mtu_request(att_connection, request_buffer, request_len, response_buffer);
1176             break;
1177         case ATT_FIND_INFORMATION_REQUEST:
1178             response_len = handle_find_information_request(att_connection, request_buffer, request_len,response_buffer, response_buffer_size);
1179             break;
1180         case ATT_FIND_BY_TYPE_VALUE_REQUEST:
1181             response_len = handle_find_by_type_value_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1182             break;
1183         case ATT_READ_BY_TYPE_REQUEST:
1184             response_len = handle_read_by_type_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1185             break;
1186         case ATT_READ_REQUEST:
1187             response_len = handle_read_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1188             break;
1189         case ATT_READ_BLOB_REQUEST:
1190             response_len = handle_read_blob_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1191             break;
1192         case ATT_READ_MULTIPLE_REQUEST:
1193             response_len = handle_read_multiple_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1194             break;
1195         case ATT_READ_BY_GROUP_TYPE_REQUEST:
1196             response_len = handle_read_by_group_type_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1197             break;
1198         case ATT_WRITE_REQUEST:
1199             response_len = handle_write_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1200             break;
1201         case ATT_PREPARE_WRITE_REQUEST:
1202             response_len = handle_prepare_write_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1203             break;
1204         case ATT_EXECUTE_WRITE_REQUEST:
1205             response_len = handle_execute_write_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1206             break;
1207         case ATT_WRITE_COMMAND:
1208             handle_write_command(att_connection, request_buffer, request_len, ATT_PROPERTY_WRITE_WITHOUT_RESPONSE);
1209             break;
1210 #ifdef ENABLE_LE_SIGNED_WRITE
1211         case ATT_SIGNED_WRITE_COMMAND:
1212             handle_write_command(att_connection, request_buffer, request_len, ATT_PROPERTY_AUTHENTICATED_SIGNED_WRITE);
1213             break;
1214 #endif
1215         default:
1216             log_info("Unhandled ATT Command: %02X, DATA: ", request_buffer[0]);
1217             log_info_hexdump(&request_buffer[9u], request_len-9u);
1218             break;
1219     }
1220     return response_len;
1221 }
1222 
1223 // returns 1 if service found. only primary service.
1224 bool gatt_server_get_get_handle_range_for_service_with_uuid16(uint16_t uuid16, uint16_t * start_handle, uint16_t * end_handle){
1225     uint16_t in_group    = 0;
1226     uint16_t prev_handle = 0;
1227 
1228     uint8_t attribute_value[2];
1229     int attribute_len = sizeof(attribute_value);
1230     little_endian_store_16(attribute_value, 0, uuid16);
1231 
1232     att_iterator_t it;
1233     att_iterator_init(&it);
1234     while (att_iterator_has_next(&it)){
1235         att_iterator_fetch_next(&it);
1236         int new_service_started = att_iterator_match_uuid16(&it, GATT_PRIMARY_SERVICE_UUID) || att_iterator_match_uuid16(&it, GATT_SECONDARY_SERVICE_UUID);
1237 
1238         // close current tag, if within a group and a new service definition starts or we reach end of att db
1239         if (in_group &&
1240             ((it.handle == 0u) || new_service_started)){
1241             *end_handle = prev_handle;
1242             return true;
1243         }
1244 
1245         // keep track of previous handle
1246         prev_handle = it.handle;
1247 
1248         // check if found
1249         if (it.handle && new_service_started && (attribute_len == it.value_len) && (memcmp(attribute_value, it.value, it.value_len) == 0)){
1250             *start_handle = it.handle;
1251             in_group = true;
1252         }
1253     }
1254     return false;
1255 }
1256 
1257 // returns false if not found
1258 uint16_t gatt_server_get_value_handle_for_characteristic_with_uuid16(uint16_t start_handle, uint16_t end_handle, uint16_t uuid16){
1259     att_iterator_t it;
1260     att_iterator_init(&it);
1261     while (att_iterator_has_next(&it)){
1262         att_iterator_fetch_next(&it);
1263         if (it.handle && (it.handle < start_handle)) continue;
1264         if (it.handle > end_handle) break;  // (1)
1265         if (it.handle == 0u) break;
1266         if (att_iterator_match_uuid16(&it, uuid16)) return it.handle;
1267     }
1268     return 0;
1269 }
1270 
1271 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){
1272     att_iterator_t it;
1273     att_iterator_init(&it);
1274     bool characteristic_found = false;
1275     while (att_iterator_has_next(&it)){
1276         att_iterator_fetch_next(&it);
1277         if (it.handle && (it.handle < start_handle)) continue;
1278         if (it.handle > end_handle) break;  // (1)
1279         if (it.handle == 0u) break;
1280         if (att_iterator_match_uuid16(&it, characteristic_uuid16)){
1281             characteristic_found = true;
1282             continue;
1283         }
1284         if (att_iterator_match_uuid16(&it, GATT_PRIMARY_SERVICE_UUID)
1285          || att_iterator_match_uuid16(&it, GATT_SECONDARY_SERVICE_UUID)
1286          || att_iterator_match_uuid16(&it, GATT_CHARACTERISTICS_UUID)){
1287             if (characteristic_found) break;
1288             continue;
1289         }
1290         if (characteristic_found && att_iterator_match_uuid16(&it, descriptor_uuid16)){
1291             return it.handle;
1292         }
1293     }
1294     return 0;
1295 }
1296 
1297 // returns 0 if not found
1298 uint16_t gatt_server_get_client_configuration_handle_for_characteristic_with_uuid16(uint16_t start_handle, uint16_t end_handle, uint16_t characteristic_uuid16){
1299     return gatt_server_get_descriptor_handle_for_characteristic_with_uuid16(start_handle, end_handle, characteristic_uuid16, GATT_CLIENT_CHARACTERISTICS_CONFIGURATION);
1300 }
1301 // returns 0 if not found
1302 
1303 uint16_t gatt_server_get_server_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_SERVER_CHARACTERISTICS_CONFIGURATION);
1305 }
1306 
1307 // returns 1 if service found. only primary service.
1308 int gatt_server_get_get_handle_range_for_service_with_uuid128(const uint8_t * uuid128, uint16_t * start_handle, uint16_t * end_handle){
1309     uint16_t in_group    = 0;
1310     uint16_t prev_handle = 0;
1311 
1312     uint8_t attribute_value[16];
1313     int attribute_len = sizeof(attribute_value);
1314     reverse_128(uuid128, attribute_value);
1315 
1316     att_iterator_t it;
1317     att_iterator_init(&it);
1318     while (att_iterator_has_next(&it)){
1319         att_iterator_fetch_next(&it);
1320         int new_service_started = att_iterator_match_uuid16(&it, GATT_PRIMARY_SERVICE_UUID) || att_iterator_match_uuid16(&it, GATT_SECONDARY_SERVICE_UUID);
1321 
1322         // close current tag, if within a group and a new service definition starts or we reach end of att db
1323         if (in_group &&
1324             ((it.handle == 0u) || new_service_started)){
1325             *end_handle = prev_handle;
1326             return 1;
1327         }
1328 
1329         // keep track of previous handle
1330         prev_handle = it.handle;
1331 
1332         // check if found
1333         if (it.handle && new_service_started && (attribute_len == it.value_len) && (memcmp(attribute_value, it.value, it.value_len) == 0)){
1334             *start_handle = it.handle;
1335             in_group = 1;
1336         }
1337     }
1338     return 0;
1339 }
1340 
1341 // returns 0 if not found
1342 uint16_t gatt_server_get_value_handle_for_characteristic_with_uuid128(uint16_t start_handle, uint16_t end_handle, const uint8_t * uuid128){
1343     uint8_t attribute_value[16];
1344     reverse_128(uuid128, attribute_value);
1345     att_iterator_t it;
1346     att_iterator_init(&it);
1347     while (att_iterator_has_next(&it)){
1348         att_iterator_fetch_next(&it);
1349         if (it.handle && (it.handle < start_handle)) continue;
1350         if (it.handle > end_handle) break;  // (1)
1351         if (it.handle == 0u) break;
1352         if (att_iterator_match_uuid(&it, attribute_value, 16)) return it.handle;
1353     }
1354     return 0;
1355 }
1356 
1357 // returns 0 if not found
1358 uint16_t gatt_server_get_client_configuration_handle_for_characteristic_with_uuid128(uint16_t start_handle, uint16_t end_handle, const uint8_t * uuid128){
1359     uint8_t attribute_value[16];
1360     reverse_128(uuid128, attribute_value);
1361     att_iterator_t it;
1362     att_iterator_init(&it);
1363     int characteristic_found = 0;
1364     while (att_iterator_has_next(&it)){
1365         att_iterator_fetch_next(&it);
1366         if (it.handle && (it.handle < start_handle)) continue;
1367         if (it.handle > end_handle) break;  // (1)
1368         if (it.handle == 0u) break;
1369         if (att_iterator_match_uuid(&it, attribute_value, 16)){
1370             characteristic_found = 1;
1371             continue;
1372         }
1373         if (att_iterator_match_uuid16(&it, GATT_PRIMARY_SERVICE_UUID)
1374          || att_iterator_match_uuid16(&it, GATT_SECONDARY_SERVICE_UUID)
1375          || att_iterator_match_uuid16(&it, GATT_CHARACTERISTICS_UUID)){
1376             if (characteristic_found) break;
1377             continue;
1378         }
1379         if (characteristic_found && att_iterator_match_uuid16(&it, GATT_CLIENT_CHARACTERISTICS_CONFIGURATION)){
1380             return it.handle;
1381         }
1382     }
1383     return 0;
1384 }
1385 
1386 
1387 // 1-item cache to optimize query during write_callback
1388 static void att_persistent_ccc_cache(att_iterator_t * it){
1389     att_persistent_ccc_handle = it->handle;
1390     if (it->flags & ATT_PROPERTY_UUID128){
1391         att_persistent_ccc_uuid16 = 0;
1392     } else {
1393         att_persistent_ccc_uuid16 = little_endian_read_16(it->uuid, 0);
1394     }
1395 }
1396 
1397 bool att_is_persistent_ccc(uint16_t handle){
1398     if (handle != att_persistent_ccc_handle){
1399         att_iterator_t it;
1400         int ok = att_find_handle(&it, handle);
1401         if (!ok) return false;
1402         att_persistent_ccc_cache(&it);
1403     }
1404     return att_persistent_ccc_uuid16 == GATT_CLIENT_CHARACTERISTICS_CONFIGURATION;
1405 }
1406 
1407 // att_read_callback helpers
1408 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){
1409     btstack_assert(blob != NULL);
1410 
1411     if (buffer != NULL){
1412         uint16_t bytes_to_copy = 0;
1413         if (blob_size >= offset){
1414             bytes_to_copy = btstack_min(blob_size - offset, buffer_size);
1415             (void)memcpy(buffer, &blob[offset], bytes_to_copy);
1416         }
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 
1442 #ifdef ENABLE_BTP
1443 
1444 // start of auto-PTS testing code, not used in production
1445 // LCOV_EXCL_START
1446 #include "btp.h"
1447 
1448 static uint8_t btp_permissions_for_flags(uint16_t flags){
1449 
1450     // see BT_GATT_PERM_*
1451     // https://docs.zephyrproject.org/latest/reference/bluetooth/gatt.html
1452     // set bit indicates requirement, e.g. BTP_GATT_PERM_READ_AUTHN requires authenticated connection
1453 
1454     uint8_t permissions = 0;
1455 
1456     uint8_t read_security_level = 0;
1457     uint8_t write_security_level = 0;
1458     if (flags & ATT_PROPERTY_READ){
1459         if (flags & ATT_PROPERTY_READ_PERMISSION_BIT_0) {
1460             read_security_level |= 1;
1461         }
1462         if (flags & ATT_PROPERTY_READ_PERMISSION_BIT_1) {
1463             read_security_level |= 2;
1464         }
1465         if (read_security_level == ATT_SECURITY_AUTHORIZED) {
1466             permissions |= BTP_GATT_PERM_READ_AUTHZ;
1467         }
1468         if (read_security_level == ATT_SECURITY_AUTHENTICATED) {
1469             permissions |= BTP_GATT_PERM_READ_AUTHN;
1470         }
1471         if (read_security_level == ATT_SECURITY_ENCRYPTED) {
1472             permissions |= BTP_GATT_PERM_READ_ENC;
1473         }
1474         if (read_security_level == ATT_SECURITY_NONE) {
1475             permissions |= BTP_GATT_PERM_READ;
1476         }
1477     }
1478     if (flags & (ATT_PROPERTY_WRITE | ATT_PROPERTY_WRITE_WITHOUT_RESPONSE)){
1479         if (flags & ATT_PROPERTY_WRITE_PERMISSION_BIT_0) {
1480             write_security_level |= 1;
1481         }
1482         if (flags & ATT_PROPERTY_WRITE_PERMISSION_BIT_1) {
1483             write_security_level |= 2;
1484         }
1485         if (write_security_level == ATT_SECURITY_AUTHORIZED) {
1486             permissions |= BTP_GATT_PERM_WRITE_AUTHZ;
1487         }
1488         if (write_security_level == ATT_SECURITY_AUTHENTICATED) {
1489             permissions |= BTP_GATT_PERM_WRITE_AUTHN;
1490         }
1491         if (write_security_level == ATT_SECURITY_ENCRYPTED) {
1492             permissions |= BTP_GATT_PERM_WRITE_ENC;
1493         }
1494         if (write_security_level == ATT_SECURITY_NONE) {
1495             permissions |= BTP_GATT_PERM_WRITE;
1496         }
1497     }
1498     return permissions;
1499 }
1500 
1501 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){
1502     log_info("btp_att_get_attributes_by_uuid16 %04x from 0x%04x to 0x%04x, db %p", uuid16, start_handle, end_handle, att_db);
1503     att_dump_attributes();
1504 
1505     uint8_t num_attributes = 0;
1506     uint16_t pos = 1;
1507 
1508     att_iterator_t  it;
1509     att_iterator_init(&it);
1510     while (att_iterator_has_next(&it) && ((pos + 6) < response_buffer_size)){
1511         att_iterator_fetch_next(&it);
1512         log_info("handle %04x", it.handle);
1513         if (it.handle == 0) break;
1514         if (it.handle < start_handle) continue;
1515         if (it.handle > end_handle) break;
1516         if ((uuid16 == 0) || att_iterator_match_uuid16(&it, uuid16)){
1517             little_endian_store_16(response_buffer, pos, it.handle);
1518             pos += 2;
1519             response_buffer[pos++] = btp_permissions_for_flags(it.flags);
1520             response_buffer[pos++] = 2;
1521             little_endian_store_16(response_buffer, pos, uuid16);
1522             pos += 2;
1523             num_attributes++;
1524         }
1525     }
1526     response_buffer[0] = num_attributes;
1527     return pos;
1528 }
1529 
1530 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){
1531     uint8_t num_attributes = 0;
1532     uint16_t pos = 1;
1533     att_iterator_t  it;
1534     att_iterator_init(&it);
1535     while (att_iterator_has_next(&it) && ((pos + 20) < response_buffer_size)){
1536         att_iterator_fetch_next(&it);
1537         if (it.handle == 0) break;
1538         if (it.handle < start_handle) continue;
1539         if (it.handle > end_handle) break;
1540         if (att_iterator_match_uuid(&it, (uint8_t*) uuid128, 16)){
1541             little_endian_store_16(response_buffer, pos, it.handle);
1542             pos += 2;
1543             response_buffer[pos++] = btp_permissions_for_flags(it.flags);
1544             response_buffer[pos++] = 16;
1545             reverse_128(uuid128, &response_buffer[pos]);
1546             pos += 16;
1547             num_attributes++;
1548         }
1549     }
1550     response_buffer[0] = num_attributes;
1551     return pos;
1552 }
1553 
1554 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){
1555     att_iterator_t it;
1556     int ok = att_find_handle(&it, attribute_handle);
1557     if (!ok) return 0;
1558 
1559     uint16_t pos = 0;
1560     // field: ATT_Response - simulate READ operation on given connection
1561     response_buffer[pos++] = att_validate_security(att_connection, ATT_READ, &it);
1562     // fetch len
1563     // assume: con handle not relevant here, else, it needs to get passed in
1564     // att_update_value_len(&it, HCI_CON_HANDLE_INVALID);
1565     uint16_t bytes_to_copy = btstack_min( response_buffer_size - 3, it.value_len);
1566     little_endian_store_16(response_buffer, pos, bytes_to_copy);
1567     pos += 2;
1568     // get value - only works for non-dynamic data
1569     if (it.value){
1570         memcpy(&response_buffer[pos], it.value, bytes_to_copy);
1571         pos += bytes_to_copy;
1572     }
1573     return pos;
1574 }
1575 // LCOV_EXCL_STOP
1576 #endif
1577