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