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