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