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