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