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