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