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