xref: /btstack/src/ble/att_db.c (revision 1dd680d7767752df3749ae70fa9c02d095989839)
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 
41 #include <stdio.h>
42 #include <string.h>
43 
44 #include "ble/att_db.h"
45 #include "ble/core.h"
46 #include "bluetooth.h"
47 #include "btstack_debug.h"
48 #include "btstack_util.h"
49 
50 typedef enum {
51     ATT_READ,
52     ATT_WRITE,
53 } att_operation_t;
54 
55 // Buetooth Base UUID 00000000-0000-1000-8000-00805F9B34FB in little endian
56 static const uint8_t bluetooth_base_uuid[] = { 0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
57 
58 
59 static int is_Bluetooth_Base_UUID(uint8_t const *uuid){
60     if (memcmp(&uuid[0],  &bluetooth_base_uuid[0], 12)) return 0;
61     if (memcmp(&uuid[14], &bluetooth_base_uuid[14], 2)) return 0;
62     return 1;
63 
64 }
65 
66 static uint16_t uuid16_from_uuid(uint16_t uuid_len, uint8_t * uuid){
67     if (uuid_len == 2) return little_endian_read_16(uuid, 0);
68     if (!is_Bluetooth_Base_UUID(uuid)) return 0;
69     return little_endian_read_16(uuid, 12);
70 }
71 
72 // ATT Database
73 
74 // new java-style iterator
75 typedef struct att_iterator {
76     // private
77     uint8_t const * att_ptr;
78     // public
79     uint16_t size;
80     uint16_t flags;
81     uint16_t handle;
82     uint8_t  const * uuid;
83     uint16_t value_len;
84     uint8_t  const * value;
85 } att_iterator_t;
86 
87 static void att_persistent_ccc_cache(att_iterator_t * it);
88 
89 static uint8_t const * att_db = NULL;
90 static att_read_callback_t  att_read_callback  = NULL;
91 static att_write_callback_t att_write_callback = NULL;
92 static uint8_t  att_prepare_write_error_code   = 0;
93 static uint16_t att_prepare_write_error_handle = 0x0000;
94 
95 // single cache for att_is_persistent_ccc - stores flags before write callback
96 static uint16_t att_persistent_ccc_handle;
97 static uint16_t att_persistent_ccc_uuid16;
98 
99 static void att_iterator_init(att_iterator_t *it){
100     it->att_ptr = att_db;
101 }
102 
103 static int att_iterator_has_next(att_iterator_t *it){
104     return it->att_ptr != NULL;
105 }
106 
107 static void att_iterator_fetch_next(att_iterator_t *it){
108     it->size   = little_endian_read_16(it->att_ptr, 0);
109     if (it->size == 0){
110         it->flags = 0;
111         it->handle = 0;
112         it->uuid = NULL;
113         it->value_len = 0;
114         it->value = NULL;
115         it->att_ptr = NULL;
116         return;
117     }
118     it->flags  = little_endian_read_16(it->att_ptr, 2);
119     it->handle = little_endian_read_16(it->att_ptr, 4);
120     it->uuid   = &it->att_ptr[6];
121     // handle 128 bit UUIDs
122     if (it->flags & ATT_PROPERTY_UUID128){
123         it->value_len = it->size - 22;
124         it->value  = &it->att_ptr[22];
125     } else {
126         it->value_len = it->size - 8;
127         it->value  = &it->att_ptr[8];
128     }
129     // advance AFTER setting values
130     it->att_ptr += it->size;
131 }
132 
133 static int att_iterator_match_uuid16(att_iterator_t *it, uint16_t uuid){
134     if (it->handle == 0) return 0;
135     if (it->flags & ATT_PROPERTY_UUID128){
136         if (!is_Bluetooth_Base_UUID(it->uuid)) return 0;
137         return little_endian_read_16(it->uuid, 12) == uuid;
138     }
139     return little_endian_read_16(it->uuid, 0)  == uuid;
140 }
141 
142 static int att_iterator_match_uuid(att_iterator_t *it, uint8_t *uuid, uint16_t uuid_len){
143     if (it->handle == 0) return 0;
144     // input: UUID16
145     if (uuid_len == 2) {
146         return att_iterator_match_uuid16(it, little_endian_read_16(uuid, 0));
147     }
148     // input and db: UUID128
149     if (it->flags & ATT_PROPERTY_UUID128){
150         return memcmp(it->uuid, uuid, 16) == 0;
151     }
152     // input: UUID128, db: UUID16
153     if (!is_Bluetooth_Base_UUID(uuid)) return 0;
154     return little_endian_read_16(uuid, 12) == little_endian_read_16(it->uuid, 0);
155 }
156 
157 
158 static int att_find_handle(att_iterator_t *it, uint16_t handle){
159     if (handle == 0) return 0;
160     att_iterator_init(it);
161     while (att_iterator_has_next(it)){
162         att_iterator_fetch_next(it);
163         if (it->handle != handle) continue;
164         return 1;
165     }
166     return 0;
167 }
168 
169 // experimental client API
170 uint16_t att_uuid_for_handle(uint16_t attribute_handle){
171     att_iterator_t it;
172     int ok = att_find_handle(&it, attribute_handle);
173     if (!ok) return 0;
174     if (it.flags & ATT_PROPERTY_UUID128) return 0;
175     return little_endian_read_16(it.uuid, 0);
176 }
177 // end of client API
178 
179 static void att_update_value_len(att_iterator_t *it, hci_con_handle_t con_handle){
180     if ((it->flags & ATT_PROPERTY_DYNAMIC) == 0) return;
181     it->value_len = (*att_read_callback)(con_handle, it->handle, 0, NULL, 0);
182     return;
183 }
184 
185 // copy attribute value from offset into buffer with given size
186 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){
187 
188     // DYNAMIC
189     if (it->flags & ATT_PROPERTY_DYNAMIC){
190         return (*att_read_callback)(con_handle, it->handle, offset, buffer, buffer_size);
191     }
192 
193     // STATIC
194     uint16_t bytes_to_copy = it->value_len - offset;
195     if (bytes_to_copy > buffer_size){
196         bytes_to_copy = buffer_size;
197     }
198     memcpy(buffer, it->value, bytes_to_copy);
199     return bytes_to_copy;
200 }
201 
202 void att_set_db(uint8_t const * db){
203     att_db = db;
204 }
205 
206 void att_set_read_callback(att_read_callback_t callback){
207     att_read_callback = callback;
208 }
209 
210 void att_set_write_callback(att_write_callback_t callback){
211     att_write_callback = callback;
212 }
213 
214 void att_dump_attributes(void){
215     att_iterator_t it;
216     att_iterator_init(&it);
217     uint8_t uuid128[16];
218     while (att_iterator_has_next(&it)){
219         att_iterator_fetch_next(&it);
220         if (it.handle == 0) {
221             log_info("Handle: END");
222             return;
223         }
224         log_info("Handle: 0x%04x, flags: 0x%04x, uuid: ", it.handle, it.flags);
225         if (it.flags & ATT_PROPERTY_UUID128){
226             reverse_128(it.uuid, uuid128);
227             log_info("%s", uuid128_to_str(uuid128));
228         } else {
229             log_info("%04x", little_endian_read_16(it.uuid, 0));
230         }
231         log_info(", value_len: %u, value: ", it.value_len);
232         log_info_hexdump(it.value, it.value_len);
233     }
234 }
235 
236 static void att_prepare_write_reset(void){
237     att_prepare_write_error_code = 0;
238     att_prepare_write_error_handle = 0x0000;
239 }
240 
241 static void att_prepare_write_update_errors(uint8_t error_code, uint16_t handle){
242     // first ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH has highest priority
243     if (error_code == ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH && error_code != att_prepare_write_error_code){
244         att_prepare_write_error_code = error_code;
245         att_prepare_write_error_handle = handle;
246         return;
247     }
248     // first ATT_ERROR_INVALID_OFFSET is next
249     if (error_code == ATT_ERROR_INVALID_OFFSET && att_prepare_write_error_code == 0){
250         att_prepare_write_error_code = error_code;
251         att_prepare_write_error_handle = handle;
252         return;
253     }
254 }
255 
256 static uint16_t setup_error(uint8_t * response_buffer, uint16_t request, uint16_t handle, uint8_t error_code){
257     response_buffer[0] = ATT_ERROR_RESPONSE;
258     response_buffer[1] = request;
259     little_endian_store_16(response_buffer, 2, handle);
260     response_buffer[4] = error_code;
261     return 5;
262 }
263 
264 static inline uint16_t setup_error_read_not_permitted(uint8_t * response_buffer, uint16_t request, uint16_t start_handle){
265     return setup_error(response_buffer, request, start_handle, ATT_ERROR_READ_NOT_PERMITTED);
266 }
267 
268 static inline uint16_t setup_error_write_not_permitted(uint8_t * response_buffer, uint16_t request, uint16_t start_handle){
269     return setup_error(response_buffer, request, start_handle, ATT_ERROR_WRITE_NOT_PERMITTED);
270 }
271 
272 static inline uint16_t setup_error_atribute_not_found(uint8_t * response_buffer, uint16_t request, uint16_t start_handle){
273     return setup_error(response_buffer, request, start_handle, ATT_ERROR_ATTRIBUTE_NOT_FOUND);
274 }
275 
276 static inline uint16_t setup_error_invalid_handle(uint8_t * response_buffer, uint16_t request, uint16_t handle){
277     return setup_error(response_buffer, request, handle, ATT_ERROR_INVALID_HANDLE);
278 }
279 
280 static inline uint16_t setup_error_invalid_offset(uint8_t * response_buffer, uint16_t request, uint16_t handle){
281     return setup_error(response_buffer, request, handle, ATT_ERROR_INVALID_OFFSET);
282 }
283 
284 static uint8_t att_validate_security(att_connection_t * att_connection, att_operation_t operation, att_iterator_t * it){
285     int required_security_level = 0;
286     switch (operation){
287         case ATT_READ:
288             if (it->flags & ATT_PROPERTY_READ_PERMISSION_BIT_0) {
289                 required_security_level |= 1;
290             }
291             if (it->flags & ATT_PROPERTY_READ_PERMISSION_BIT_1) {
292                 required_security_level |= 2;
293             }
294             break;
295         case ATT_WRITE:
296             if (it->flags & ATT_PROPERTY_WRITE_PERMISSION_BIT_0) {
297                 required_security_level |= 1;
298             }
299             if (it->flags & ATT_PROPERTY_WRITE_PERMISSION_BIT_1) {
300                 required_security_level |= 2;
301             }
302             break;
303     }
304 
305     int required_encryption_size = it->flags >> 12;
306     if (required_encryption_size) required_encryption_size++;   // store -1 to fit into 4 bit
307 
308     log_debug("att_validate_security. flags 0x%04x - req enc size %u, req security level %u, authorized %u, authenticated %u, encryption_key_size %u",
309         it->flags, required_encryption_size, required_security_level, att_connection->authorized, att_connection->authenticated, att_connection->encryption_key_size);
310 
311     if ((required_security_level >= ATT_SECURITY_AUTHORIZED) && (att_connection->authorized == 0)) {
312         return ATT_ERROR_INSUFFICIENT_AUTHORIZATION;
313     }
314     if ((required_security_level >= ATT_SECURITY_AUTHENTICATED) && (att_connection->authenticated == 0)) {
315         return ATT_ERROR_INSUFFICIENT_AUTHENTICATION;
316     }
317     if (required_security_level >= ATT_SECURITY_ENCRYPTED) {
318         if ((required_encryption_size > 0) && (att_connection->encryption_key_size == 0)){
319             return ATT_ERROR_INSUFFICIENT_ENCRYPTION;
320         }
321         if (required_encryption_size > att_connection->encryption_key_size){
322             return ATT_ERROR_INSUFFICIENT_ENCRYPTION_KEY_SIZE;
323         }
324     }
325     return 0;
326 }
327 
328 //
329 // MARK: ATT_EXCHANGE_MTU_REQUEST
330 //
331 static uint16_t handle_exchange_mtu_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
332                                          uint8_t * response_buffer){
333 
334     UNUSED(request_len);
335 
336     uint16_t client_rx_mtu = little_endian_read_16(request_buffer, 1);
337 
338     // find min(local max mtu, remote mtu) and use as mtu for this connection
339     if (client_rx_mtu < att_connection->max_mtu){
340         att_connection->mtu = client_rx_mtu;
341     } else {
342         att_connection->mtu = att_connection->max_mtu;
343     }
344 
345     response_buffer[0] = ATT_EXCHANGE_MTU_RESPONSE;
346     little_endian_store_16(response_buffer, 1, att_connection->mtu);
347     return 3;
348 }
349 
350 
351 //
352 // MARK: ATT_FIND_INFORMATION_REQUEST
353 //
354 // TODO: handle other types then GATT_PRIMARY_SERVICE_UUID and GATT_SECONDARY_SERVICE_UUID
355 //
356 static uint16_t handle_find_information_request2(att_connection_t * att_connection, uint8_t * response_buffer, uint16_t response_buffer_size,
357                                            uint16_t start_handle, uint16_t end_handle){
358 
359     UNUSED(att_connection);
360 
361     log_info("ATT_FIND_INFORMATION_REQUEST: from %04X to %04X", start_handle, end_handle);
362     uint8_t request_type = ATT_FIND_INFORMATION_REQUEST;
363 
364     if (start_handle > end_handle || start_handle == 0){
365         return setup_error_invalid_handle(response_buffer, request_type, start_handle);
366     }
367 
368     uint16_t offset   = 1;
369     uint16_t uuid_len = 0;
370 
371     att_iterator_t it;
372     att_iterator_init(&it);
373     while (att_iterator_has_next(&it)){
374         att_iterator_fetch_next(&it);
375         if (!it.handle) break;
376         if (it.handle > end_handle) break;
377         if (it.handle < start_handle) continue;
378 
379         // log_info("Handle 0x%04x", it.handle);
380 
381         uint16_t this_uuid_len = (it.flags & ATT_PROPERTY_UUID128) ? 16 : 2;
382 
383         // check if value has same len as last one if not first result
384         if (offset > 1){
385             if (this_uuid_len != uuid_len) {
386                 break;
387             }
388         }
389 
390         // first
391         if (offset == 1) {
392             uuid_len = this_uuid_len;
393             // set format field
394             response_buffer[offset] = (it.flags & ATT_PROPERTY_UUID128) ? 0x02 : 0x01;
395             offset++;
396         }
397 
398         // space?
399         if (offset + 2 + uuid_len > response_buffer_size) break;
400 
401         // store
402         little_endian_store_16(response_buffer, offset, it.handle);
403         offset += 2;
404 
405         memcpy(response_buffer + offset, it.uuid, uuid_len);
406         offset += uuid_len;
407     }
408 
409     if (offset == 1){
410         return setup_error_atribute_not_found(response_buffer, request_type, start_handle);
411     }
412 
413     response_buffer[0] = ATT_FIND_INFORMATION_REPLY;
414     return offset;
415 }
416 
417 static uint16_t handle_find_information_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
418                                          uint8_t * response_buffer, uint16_t response_buffer_size){
419     UNUSED(request_len);
420     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));
421 }
422 
423 //
424 // MARK: ATT_FIND_BY_TYPE_VALUE
425 //
426 // "Only attributes with attribute handles between and including the Starting Handle parameter
427 // and the Ending Handle parameter that match the requested attri- bute type and the attribute
428 // value that have sufficient permissions to allow reading will be returned" -> (1)
429 //
430 // TODO: handle other types then GATT_PRIMARY_SERVICE_UUID and GATT_SECONDARY_SERVICE_UUID
431 //
432 // NOTE: doesn't handle DYNAMIC values
433 // NOTE: only supports 16 bit UUIDs
434 //
435 static uint16_t handle_find_by_type_value_request2(att_connection_t * att_connection, uint8_t * response_buffer, uint16_t response_buffer_size,
436                                            uint16_t start_handle, uint16_t end_handle,
437                                            uint16_t attribute_type, uint16_t attribute_len, uint8_t* attribute_value){
438 
439     UNUSED(att_connection);
440 
441     log_info("ATT_FIND_BY_TYPE_VALUE_REQUEST: from %04X to %04X, type %04X, value: ", start_handle, end_handle, attribute_type);
442     log_info_hexdump(attribute_value, attribute_len);
443     uint8_t request_type = ATT_FIND_BY_TYPE_VALUE_REQUEST;
444 
445     if (start_handle > end_handle || start_handle == 0){
446         return setup_error_invalid_handle(response_buffer, request_type, start_handle);
447     }
448 
449     uint16_t offset      = 1;
450     uint16_t in_group    = 0;
451     uint16_t prev_handle = 0;
452 
453     att_iterator_t it;
454     att_iterator_init(&it);
455     while (att_iterator_has_next(&it)){
456         att_iterator_fetch_next(&it);
457 
458         if (it.handle && it.handle < start_handle) continue;
459         if (it.handle > end_handle) break;  // (1)
460 
461         // close current tag, if within a group and a new service definition starts or we reach end of att db
462         if (in_group &&
463             (it.handle == 0 || att_iterator_match_uuid16(&it, GATT_PRIMARY_SERVICE_UUID) || att_iterator_match_uuid16(&it, GATT_SECONDARY_SERVICE_UUID))){
464 
465             log_info("End of group, handle 0x%04x", prev_handle);
466             little_endian_store_16(response_buffer, offset, prev_handle);
467             offset += 2;
468             in_group = 0;
469 
470             // check if space for another handle pair available
471             if (offset + 4 > response_buffer_size){
472                 break;
473             }
474         }
475 
476         // keep track of previous handle
477         prev_handle = it.handle;
478 
479         // does current attribute match
480         if (it.handle && att_iterator_match_uuid16(&it, attribute_type) && attribute_len == it.value_len && memcmp(attribute_value, it.value, it.value_len) == 0){
481             log_info("Begin of group, handle 0x%04x", it.handle);
482             little_endian_store_16(response_buffer, offset, it.handle);
483             offset += 2;
484             in_group = 1;
485         }
486     }
487 
488     if (offset == 1){
489         return setup_error_atribute_not_found(response_buffer, request_type, start_handle);
490     }
491 
492     response_buffer[0] = ATT_FIND_BY_TYPE_VALUE_RESPONSE;
493     return offset;
494 }
495 
496 static uint16_t handle_find_by_type_value_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
497                                            uint8_t * response_buffer, uint16_t response_buffer_size){
498     int attribute_len = request_len - 7;
499     return handle_find_by_type_value_request2(att_connection, response_buffer, response_buffer_size, little_endian_read_16(request_buffer, 1),
500                                               little_endian_read_16(request_buffer, 3), little_endian_read_16(request_buffer, 5), attribute_len, &request_buffer[7]);
501 }
502 
503 //
504 // MARK: ATT_READ_BY_TYPE_REQUEST
505 //
506 static uint16_t handle_read_by_type_request2(att_connection_t * att_connection, uint8_t * response_buffer, uint16_t response_buffer_size,
507                                       uint16_t start_handle, uint16_t end_handle,
508                                       uint16_t attribute_type_len, uint8_t * attribute_type){
509 
510     log_info("ATT_READ_BY_TYPE_REQUEST: from %04X to %04X, type: ", start_handle, end_handle);
511     log_info_hexdump(attribute_type, attribute_type_len);
512     uint8_t request_type = ATT_READ_BY_TYPE_REQUEST;
513 
514     if (start_handle > end_handle || start_handle == 0){
515         return setup_error_invalid_handle(response_buffer, request_type, start_handle);
516     }
517 
518     uint16_t offset   = 1;
519     uint16_t pair_len = 0;
520 
521     att_iterator_t it;
522     att_iterator_init(&it);
523     uint8_t error_code = 0;
524     uint16_t first_matching_but_unreadable_handle = 0;
525 
526 #ifdef ENABLE_ATT_DELAYED_READ_RESPONSE
527     int read_request_pending = 0;
528 #endif
529 
530     while (att_iterator_has_next(&it)){
531         att_iterator_fetch_next(&it);
532 
533         if (!it.handle) break;
534         if (it.handle < start_handle) continue;
535         if (it.handle > end_handle) break;  // (1)
536 
537         // does current attribute match
538         if (!att_iterator_match_uuid(&it, attribute_type, attribute_type_len)) continue;
539 
540         // skip handles that cannot be read but rembember that there has been at least one
541         if ((it.flags & ATT_PROPERTY_READ) == 0) {
542             if (first_matching_but_unreadable_handle == 0) {
543                 first_matching_but_unreadable_handle = it.handle;
544             }
545             continue;
546         }
547 
548         // check security requirements
549         if ((it.flags & ATT_DB_FLAGS_READ_WITHOUT_AUTHENTICATION) == 0){
550             error_code = att_validate_security(att_connection, ATT_READ, &it);
551             if (error_code) break;
552         }
553 
554         att_update_value_len(&it, att_connection->con_handle);
555 
556 #ifdef ENABLE_ATT_DELAYED_READ_RESPONSE
557         if (it.value_len == ATT_READ_RESPONSE_PENDING){
558             read_request_pending = 1;
559         }
560         if (read_request_pending) continue;
561 #endif
562 
563         // check if value has same len as last one
564         uint16_t this_pair_len = 2 + it.value_len;
565         if (offset > 1){
566             if (pair_len != this_pair_len) {
567                 break;
568             }
569         }
570 
571         // first
572         if (offset == 1) {
573             pair_len = this_pair_len;
574             response_buffer[offset] = pair_len;
575             offset++;
576         }
577 
578         // space?
579         if (offset + pair_len > response_buffer_size) {
580             if (offset > 2) break;
581             it.value_len = response_buffer_size - 4;
582             response_buffer[1] = 2 + it.value_len;
583         }
584 
585         // store
586         little_endian_store_16(response_buffer, offset, it.handle);
587         offset += 2;
588         uint16_t bytes_copied = att_copy_value(&it, 0, response_buffer + offset, it.value_len, att_connection->con_handle);
589         offset += bytes_copied;
590     }
591 
592 #ifdef ENABLE_ATT_DELAYED_READ_RESPONSE
593     if (read_request_pending) return ATT_READ_RESPONSE_PENDING;
594 #endif
595 
596     // at least one attribute could be read
597     if (offset > 1){
598         response_buffer[0] = ATT_READ_BY_TYPE_RESPONSE;
599         return offset;
600     }
601 
602     // first attribute had an error
603     if (error_code){
604         return setup_error(response_buffer, request_type, start_handle, error_code);
605     }
606 
607     // no other errors, but all found attributes had been non-readable
608     if (first_matching_but_unreadable_handle){
609         return setup_error_read_not_permitted(response_buffer, request_type, first_matching_but_unreadable_handle);
610     }
611 
612     // attribute not found
613     return setup_error_atribute_not_found(response_buffer, request_type, start_handle);
614 }
615 
616 static uint16_t handle_read_by_type_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
617                                      uint8_t * response_buffer, uint16_t response_buffer_size){
618     int attribute_type_len;
619     if (request_len <= 7){
620         attribute_type_len = 2;
621     } else {
622         attribute_type_len = 16;
623     }
624     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]);
625 }
626 
627 //
628 // MARK: ATT_READ_BY_TYPE_REQUEST
629 //
630 static uint16_t handle_read_request2(att_connection_t * att_connection, uint8_t * response_buffer, uint16_t response_buffer_size, uint16_t handle){
631 
632     log_info("ATT_READ_REQUEST: handle %04x", handle);
633     uint8_t request_type = ATT_READ_REQUEST;
634 
635     att_iterator_t it;
636     int ok = att_find_handle(&it, handle);
637     if (!ok){
638         return setup_error_invalid_handle(response_buffer, request_type, handle);
639     }
640 
641     // check if handle can be read
642     if ((it.flags & ATT_PROPERTY_READ) == 0) {
643         return setup_error_read_not_permitted(response_buffer, request_type, handle);
644     }
645 
646     // check security requirements
647     if ((it.flags & ATT_DB_FLAGS_READ_WITHOUT_AUTHENTICATION) == 0){
648         uint8_t error_code = att_validate_security(att_connection, ATT_READ, &it);
649         if (error_code) {
650             return setup_error(response_buffer, request_type, handle, error_code);
651         }
652     }
653 
654     att_update_value_len(&it, att_connection->con_handle);
655 
656 #ifdef ENABLE_ATT_DELAYED_READ_RESPONSE
657     if (it.value_len == ATT_READ_RESPONSE_PENDING) return ATT_READ_RESPONSE_PENDING;
658 #endif
659 
660     uint16_t offset   = 1;
661     // limit data
662     if (offset + it.value_len > response_buffer_size) {
663         it.value_len = response_buffer_size - 1;
664     }
665 
666     // store
667     uint16_t bytes_copied = att_copy_value(&it, 0, response_buffer + offset, it.value_len, att_connection->con_handle);
668     offset += bytes_copied;
669 
670     response_buffer[0] = ATT_READ_RESPONSE;
671     return offset;
672 }
673 
674 static uint16_t handle_read_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
675                              uint8_t * response_buffer, uint16_t response_buffer_size){
676     UNUSED(request_len);
677     return handle_read_request2(att_connection, response_buffer, response_buffer_size, little_endian_read_16(request_buffer, 1));
678 }
679 
680 //
681 // MARK: ATT_READ_BLOB_REQUEST 0x0c
682 //
683 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){
684     log_info("ATT_READ_BLOB_REQUEST: handle %04x, offset %u", handle, value_offset);
685     uint8_t request_type = ATT_READ_BLOB_REQUEST;
686 
687     att_iterator_t it;
688     int ok = att_find_handle(&it, handle);
689     if (!ok){
690         return setup_error_invalid_handle(response_buffer, request_type, handle);
691     }
692 
693     // check if handle can be read
694     if ((it.flags & ATT_PROPERTY_READ) == 0) {
695         return setup_error_read_not_permitted(response_buffer, request_type, handle);
696     }
697 
698     // check security requirements
699     if ((it.flags & ATT_DB_FLAGS_READ_WITHOUT_AUTHENTICATION) == 0){
700         uint8_t error_code = att_validate_security(att_connection, ATT_READ, &it);
701         if (error_code) {
702             return setup_error(response_buffer, request_type, handle, error_code);
703         }
704     }
705 
706     att_update_value_len(&it, att_connection->con_handle);
707 
708 #ifdef ENABLE_ATT_DELAYED_READ_RESPONSE
709     if (it.value_len == ATT_READ_RESPONSE_PENDING) return ATT_READ_RESPONSE_PENDING;
710 #endif
711 
712     if (value_offset > it.value_len){
713         return setup_error_invalid_offset(response_buffer, request_type, handle);
714     }
715 
716     // limit data
717     uint16_t offset   = 1;
718     if (offset + it.value_len - value_offset > response_buffer_size) {
719         it.value_len = response_buffer_size - 1 + value_offset;
720     }
721 
722     // store
723     uint16_t bytes_copied = att_copy_value(&it, value_offset, response_buffer + offset, it.value_len - value_offset, att_connection->con_handle);
724     offset += bytes_copied;
725 
726     response_buffer[0] = ATT_READ_BLOB_RESPONSE;
727     return offset;
728 }
729 
730 static uint16_t handle_read_blob_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
731                                   uint8_t * response_buffer, uint16_t response_buffer_size){
732     UNUSED(request_len);
733     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));
734 }
735 
736 //
737 // MARK: ATT_READ_MULTIPLE_REQUEST 0x0e
738 //
739 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){
740     log_info("ATT_READ_MULTIPLE_REQUEST: num handles %u", num_handles);
741     uint8_t request_type = ATT_READ_MULTIPLE_REQUEST;
742 
743     // TODO: figure out which error to respond with
744     // if (num_handles < 2){
745     //     return setup_error(response_buffer, ATT_READ_MULTIPLE_REQUEST, handle, ???);
746     // }
747 
748     uint16_t offset   = 1;
749 
750     int i;
751     uint8_t error_code = 0;
752     uint16_t handle = 0;
753 
754 #ifdef ENABLE_ATT_DELAYED_READ_RESPONSE
755     int read_request_pending = 0;
756 #endif
757 
758     for (i=0;i<num_handles;i++){
759         handle = little_endian_read_16(handles, i << 1);
760 
761         if (handle == 0){
762             return setup_error_invalid_handle(response_buffer, request_type, handle);
763         }
764 
765         att_iterator_t it;
766 
767         int ok = att_find_handle(&it, handle);
768         if (!ok){
769             return setup_error_invalid_handle(response_buffer, request_type, handle);
770         }
771 
772         // check if handle can be read
773         if ((it.flags & ATT_PROPERTY_READ) == 0) {
774             error_code = ATT_ERROR_READ_NOT_PERMITTED;
775             break;
776         }
777 
778         // check security requirements
779         if ((it.flags & ATT_DB_FLAGS_READ_WITHOUT_AUTHENTICATION) == 0){
780             error_code = att_validate_security(att_connection, ATT_READ, &it);
781             if (error_code) break;
782         }
783         att_update_value_len(&it, att_connection->con_handle);
784 
785 #ifdef ENABLE_ATT_DELAYED_READ_RESPONSE
786         if (it.value_len == ATT_READ_RESPONSE_PENDING) {
787             read_request_pending = 1;
788         }
789         if (read_request_pending) continue;
790 #endif
791 
792         // limit data
793         if (offset + it.value_len > response_buffer_size) {
794             it.value_len = response_buffer_size - 1;
795         }
796 
797         // store
798         uint16_t bytes_copied = att_copy_value(&it, 0, response_buffer + offset, it.value_len, att_connection->con_handle);
799         offset += bytes_copied;
800     }
801 
802     if (error_code){
803         return setup_error(response_buffer, request_type, handle, error_code);
804     }
805 
806     response_buffer[0] = ATT_READ_MULTIPLE_RESPONSE;
807     return offset;
808 }
809 static uint16_t handle_read_multiple_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
810                                       uint8_t * response_buffer, uint16_t response_buffer_size){
811     int num_handles = (request_len - 1) >> 1;
812     return handle_read_multiple_request2(att_connection, response_buffer, response_buffer_size, num_handles, &request_buffer[1]);
813 }
814 
815 //
816 // MARK: ATT_READ_BY_GROUP_TYPE_REQUEST 0x10
817 //
818 // Only handles GATT_PRIMARY_SERVICE_UUID and GATT_SECONDARY_SERVICE_UUID
819 // Core v4.0, vol 3, part g, 2.5.3
820 // "The «Primary Service» and «Secondary Service» grouping types may be used in the Read By Group Type Request.
821 //  The «Characteristic» grouping type shall not be used in the ATT Read By Group Type Request."
822 //
823 // NOTE: doesn't handle DYNAMIC values
824 //
825 // NOTE: we don't check for security as PRIMARY and SECONDAY SERVICE definition shouldn't be protected
826 // Core 4.0, vol 3, part g, 8.1
827 // "The list of services and characteristics that a device supports is not considered private or
828 //  confidential information, and therefore the Service and Characteristic Discovery procedures
829 //  shall always be permitted. "
830 //
831 static uint16_t handle_read_by_group_type_request2(att_connection_t * att_connection, uint8_t * response_buffer, uint16_t response_buffer_size,
832                                             uint16_t start_handle, uint16_t end_handle,
833                                             uint16_t attribute_type_len, uint8_t * attribute_type){
834 
835     UNUSED(att_connection);
836 
837     log_info("ATT_READ_BY_GROUP_TYPE_REQUEST: from %04X to %04X, buffer size %u, type: ", start_handle, end_handle, response_buffer_size);
838     log_info_hexdump(attribute_type, attribute_type_len);
839     uint8_t request_type = ATT_READ_BY_GROUP_TYPE_REQUEST;
840 
841     if (start_handle > end_handle || start_handle == 0){
842         return setup_error_invalid_handle(response_buffer, request_type, start_handle);
843     }
844 
845     // assert UUID is primary or secondary service uuid
846     uint16_t uuid16 = uuid16_from_uuid(attribute_type_len, attribute_type);
847     if (uuid16 != GATT_PRIMARY_SERVICE_UUID && uuid16 != GATT_SECONDARY_SERVICE_UUID){
848         return setup_error(response_buffer, request_type, start_handle, ATT_ERROR_UNSUPPORTED_GROUP_TYPE);
849     }
850 
851     uint16_t offset   = 1;
852     uint16_t pair_len = 0;
853     uint16_t in_group = 0;
854     uint16_t group_start_handle = 0;
855     uint8_t const * group_start_value = NULL;
856     uint16_t prev_handle = 0;
857 
858     att_iterator_t it;
859     att_iterator_init(&it);
860     while (att_iterator_has_next(&it)){
861         att_iterator_fetch_next(&it);
862 
863         if (it.handle && it.handle < start_handle) continue;
864         if (it.handle > end_handle) break;  // (1)
865 
866         // log_info("Handle 0x%04x", it.handle);
867 
868         // close current tag, if within a group and a new service definition starts or we reach end of att db
869         if (in_group &&
870             (it.handle == 0 || att_iterator_match_uuid16(&it, GATT_PRIMARY_SERVICE_UUID) || att_iterator_match_uuid16(&it, GATT_SECONDARY_SERVICE_UUID))){
871             // log_info("End of group, handle 0x%04x, val_len: %u", prev_handle, pair_len - 4);
872 
873             little_endian_store_16(response_buffer, offset, group_start_handle);
874             offset += 2;
875             little_endian_store_16(response_buffer, offset, prev_handle);
876             offset += 2;
877             memcpy(response_buffer + offset, group_start_value, pair_len - 4);
878             offset += pair_len - 4;
879             in_group = 0;
880 
881             // check if space for another handle pair available
882             if (offset + pair_len > response_buffer_size){
883                 break;
884             }
885         }
886 
887         // keep track of previous handle
888         prev_handle = it.handle;
889 
890         // does current attribute match
891         // log_info("compare: %04x == %04x", *(uint16_t*) context->attribute_type, *(uint16_t*) uuid);
892         if (it.handle && att_iterator_match_uuid(&it, attribute_type, attribute_type_len)) {
893 
894             // check if value has same len as last one
895             uint16_t this_pair_len = 4 + it.value_len;
896             if (offset > 1){
897                 if (this_pair_len != pair_len) {
898                     break;
899                 }
900             }
901 
902             // log_info("Begin of group, handle 0x%04x", it.handle);
903 
904             // first
905             if (offset == 1) {
906                 pair_len = this_pair_len;
907                 response_buffer[offset] = this_pair_len;
908                 offset++;
909             }
910 
911             group_start_handle = it.handle;
912             group_start_value  = it.value;
913             in_group = 1;
914         }
915     }
916 
917     if (offset == 1){
918         return setup_error_atribute_not_found(response_buffer, request_type, start_handle);
919     }
920 
921     response_buffer[0] = ATT_READ_BY_GROUP_TYPE_RESPONSE;
922     return offset;
923 }
924 static uint16_t handle_read_by_group_type_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
925                                            uint8_t * response_buffer, uint16_t response_buffer_size){
926     int attribute_type_len;
927     if (request_len <= 7){
928         attribute_type_len = 2;
929     } else {
930         attribute_type_len = 16;
931     }
932     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]);
933 }
934 
935 //
936 // MARK: ATT_WRITE_REQUEST 0x12
937 static uint16_t handle_write_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
938                               uint8_t * response_buffer, uint16_t response_buffer_size){
939 
940     UNUSED(response_buffer_size);
941 
942     uint8_t request_type = ATT_WRITE_REQUEST;
943 
944     uint16_t handle = little_endian_read_16(request_buffer, 1);
945     att_iterator_t it;
946     int ok = att_find_handle(&it, handle);
947     if (!ok) {
948         return setup_error_invalid_handle(response_buffer, request_type, handle);
949     }
950     if (!att_write_callback) {
951         return setup_error_write_not_permitted(response_buffer, request_type, handle);
952     }
953     if ((it.flags & ATT_PROPERTY_WRITE) == 0) {
954         return setup_error_write_not_permitted(response_buffer, request_type, handle);
955     }
956     if ((it.flags & ATT_PROPERTY_DYNAMIC) == 0) {
957         return setup_error_write_not_permitted(response_buffer, request_type, handle);
958     }
959     // check security requirements
960     uint8_t error_code = att_validate_security(att_connection, ATT_WRITE, &it);
961     if (error_code) {
962         return setup_error(response_buffer, request_type, handle, error_code);
963     }
964     att_persistent_ccc_cache(&it);
965     error_code = (*att_write_callback)(att_connection->con_handle, handle, ATT_TRANSACTION_MODE_NONE, 0, request_buffer + 3, request_len - 3);
966     if (error_code) {
967         return setup_error(response_buffer, request_type, handle, error_code);
968     }
969     response_buffer[0] = ATT_WRITE_RESPONSE;
970     return 1;
971 }
972 
973 //
974 // MARK: ATT_PREPARE_WRITE_REQUEST 0x16
975 static uint16_t handle_prepare_write_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
976                                       uint8_t * response_buffer, uint16_t response_buffer_size){
977 
978     UNUSED(response_buffer_size);
979 
980     uint8_t request_type = ATT_PREPARE_WRITE_REQUEST;
981 
982     uint16_t handle = little_endian_read_16(request_buffer, 1);
983     uint16_t offset = little_endian_read_16(request_buffer, 3);
984     if (!att_write_callback) {
985         return setup_error_write_not_permitted(response_buffer, request_type, handle);
986     }
987     att_iterator_t it;
988     int ok = att_find_handle(&it, handle);
989     if (!ok) {
990         return setup_error_invalid_handle(response_buffer, request_type, handle);
991     }
992     if ((it.flags & ATT_PROPERTY_WRITE) == 0) {
993         return setup_error_write_not_permitted(response_buffer, request_type, handle);
994     }
995     if ((it.flags & ATT_PROPERTY_DYNAMIC) == 0) {
996         return setup_error_write_not_permitted(response_buffer, request_type, handle);
997     }
998     // check security requirements
999     uint8_t error_code = att_validate_security(att_connection, ATT_WRITE, &it);
1000     if (error_code) {
1001         return setup_error(response_buffer, request_type, handle, error_code);
1002     }
1003 
1004     error_code = (*att_write_callback)(att_connection->con_handle, handle, ATT_TRANSACTION_MODE_ACTIVE, offset, request_buffer + 5, request_len - 5);
1005     switch (error_code){
1006         case 0:
1007             break;
1008         case ATT_ERROR_INVALID_OFFSET:
1009         case ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH:
1010             // postpone to execute write request
1011             att_prepare_write_update_errors(error_code, handle);
1012             break;
1013         default:
1014             return setup_error(response_buffer, request_type, handle, error_code);
1015     }
1016 
1017     // response: echo request
1018     memcpy(response_buffer, request_buffer, request_len);
1019     response_buffer[0] = ATT_PREPARE_WRITE_RESPONSE;
1020     return request_len;
1021 }
1022 
1023 /*
1024  * @brief transcation queue of prepared writes, e.g., after disconnect
1025  */
1026 void att_clear_transaction_queue(att_connection_t * att_connection){
1027     (*att_write_callback)(att_connection->con_handle, 0, ATT_TRANSACTION_MODE_CANCEL, 0, NULL, 0);
1028 }
1029 
1030 // MARK: ATT_EXECUTE_WRITE_REQUEST 0x18
1031 // NOTE: security has been verified by handle_prepare_write_request
1032 static uint16_t handle_execute_write_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
1033                                       uint8_t * response_buffer, uint16_t response_buffer_size){
1034 
1035     UNUSED(request_len);
1036     UNUSED(response_buffer_size);
1037 
1038     uint8_t request_type = ATT_EXECUTE_WRITE_REQUEST;
1039     if (request_buffer[1]) {
1040         // validate queued write
1041         if (att_prepare_write_error_code == 0){
1042             att_prepare_write_error_code = (*att_write_callback)(att_connection->con_handle, 0, ATT_TRANSACTION_MODE_VALIDATE, 0, NULL, 0);
1043         }
1044         // deliver queued errors
1045         if (att_prepare_write_error_code){
1046             att_clear_transaction_queue(att_connection);
1047             uint8_t  error_code = att_prepare_write_error_code;
1048             uint16_t handle     = att_prepare_write_error_handle;
1049             att_prepare_write_reset();
1050             return setup_error(response_buffer, request_type, handle, error_code);
1051         }
1052         att_write_callback(att_connection->con_handle, 0, ATT_TRANSACTION_MODE_EXECUTE, 0, NULL, 0);
1053     } else {
1054         att_clear_transaction_queue(att_connection);
1055     }
1056     response_buffer[0] = ATT_EXECUTE_WRITE_RESPONSE;
1057     return 1;
1058 }
1059 
1060 // MARK: ATT_WRITE_COMMAND 0x52
1061 // Core 4.0, vol 3, part F, 3.4.5.3
1062 // "No Error Response or Write Response shall be sent in response to this command"
1063 static void handle_write_command(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
1064                                            uint8_t * response_buffer, uint16_t response_buffer_size){
1065 
1066     UNUSED(response_buffer);
1067     UNUSED(response_buffer_size);
1068 
1069     uint16_t handle = little_endian_read_16(request_buffer, 1);
1070     if (!att_write_callback) return;
1071 
1072     att_iterator_t it;
1073     int ok = att_find_handle(&it, handle);
1074     if (!ok) return;
1075     if ((it.flags & ATT_PROPERTY_DYNAMIC) == 0) return;
1076     if ((it.flags & ATT_PROPERTY_WRITE_WITHOUT_RESPONSE) == 0) return;
1077     if (att_validate_security(att_connection, ATT_WRITE, &it)) return;
1078     att_persistent_ccc_cache(&it);
1079     (*att_write_callback)(att_connection->con_handle, handle, ATT_TRANSACTION_MODE_NONE, 0, request_buffer + 3, request_len - 3);
1080 }
1081 
1082 // MARK: helper for ATT_HANDLE_VALUE_NOTIFICATION and ATT_HANDLE_VALUE_INDICATION
1083 static uint16_t prepare_handle_value(att_connection_t * att_connection,
1084                                      uint16_t handle,
1085                                      uint8_t *value,
1086                                      uint16_t value_len,
1087                                      uint8_t * response_buffer){
1088     little_endian_store_16(response_buffer, 1, handle);
1089     if (value_len > att_connection->mtu - 3){
1090         value_len = att_connection->mtu - 3;
1091     }
1092     memcpy(&response_buffer[3], value, value_len);
1093     return value_len + 3;
1094 }
1095 
1096 // MARK: ATT_HANDLE_VALUE_NOTIFICATION 0x1b
1097 uint16_t att_prepare_handle_value_notification(att_connection_t * att_connection,
1098                                                uint16_t handle,
1099                                                uint8_t *value,
1100                                                uint16_t value_len,
1101                                                uint8_t * response_buffer){
1102 
1103     response_buffer[0] = ATT_HANDLE_VALUE_NOTIFICATION;
1104     return prepare_handle_value(att_connection, handle, value, value_len, response_buffer);
1105 }
1106 
1107 // MARK: ATT_HANDLE_VALUE_INDICATION 0x1d
1108 uint16_t att_prepare_handle_value_indication(att_connection_t * att_connection,
1109                                              uint16_t handle,
1110                                              uint8_t *value,
1111                                              uint16_t value_len,
1112                                              uint8_t * response_buffer){
1113 
1114     response_buffer[0] = ATT_HANDLE_VALUE_INDICATION;
1115     return prepare_handle_value(att_connection, handle, value, value_len, response_buffer);
1116 }
1117 
1118 // MARK: Dispatcher
1119 uint16_t att_handle_request(att_connection_t * att_connection,
1120                             uint8_t * request_buffer,
1121                             uint16_t request_len,
1122                             uint8_t * response_buffer){
1123     uint16_t response_len = 0;
1124     uint16_t response_buffer_size = att_connection->mtu;
1125 
1126     switch (request_buffer[0]){
1127         case ATT_EXCHANGE_MTU_REQUEST:
1128             response_len = handle_exchange_mtu_request(att_connection, request_buffer, request_len, response_buffer);
1129             break;
1130         case ATT_FIND_INFORMATION_REQUEST:
1131             response_len = handle_find_information_request(att_connection, request_buffer, request_len,response_buffer, response_buffer_size);
1132             break;
1133         case ATT_FIND_BY_TYPE_VALUE_REQUEST:
1134             response_len = handle_find_by_type_value_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1135             break;
1136         case ATT_READ_BY_TYPE_REQUEST:
1137             response_len = handle_read_by_type_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1138             break;
1139         case ATT_READ_REQUEST:
1140             response_len = handle_read_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1141             break;
1142         case ATT_READ_BLOB_REQUEST:
1143             response_len = handle_read_blob_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1144             break;
1145         case ATT_READ_MULTIPLE_REQUEST:
1146             response_len = handle_read_multiple_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1147             break;
1148         case ATT_READ_BY_GROUP_TYPE_REQUEST:
1149             response_len = handle_read_by_group_type_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1150             break;
1151         case ATT_WRITE_REQUEST:
1152             response_len = handle_write_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1153             break;
1154         case ATT_PREPARE_WRITE_REQUEST:
1155             response_len = handle_prepare_write_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1156             break;
1157         case ATT_EXECUTE_WRITE_REQUEST:
1158             response_len = handle_execute_write_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1159             break;
1160         case ATT_WRITE_COMMAND:
1161             handle_write_command(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1162             break;
1163 #ifdef ENABLE_LE_SIGNED_WRITE
1164         case ATT_SIGNED_WRITE_COMMAND:
1165             log_info("handle_signed_write_command preprocessed by att_server.c");
1166             break;
1167 #endif
1168         default:
1169             log_info("Unhandled ATT Command: %02X, DATA: ", request_buffer[0]);
1170             log_info_hexdump(&request_buffer[9], request_len-9);
1171             break;
1172     }
1173     return response_len;
1174 }
1175 
1176 // returns 1 if service found. only primary service.
1177 int gatt_server_get_get_handle_range_for_service_with_uuid16(uint16_t uuid16, uint16_t * start_handle, uint16_t * end_handle){
1178     uint16_t in_group    = 0;
1179     uint16_t prev_handle = 0;
1180 
1181     uint8_t attribute_value[2];
1182     int attribute_len = sizeof(attribute_value);
1183     little_endian_store_16(attribute_value, 0, uuid16);
1184 
1185     att_iterator_t it;
1186     att_iterator_init(&it);
1187     while (att_iterator_has_next(&it)){
1188         att_iterator_fetch_next(&it);
1189         int new_service_started = att_iterator_match_uuid16(&it, GATT_PRIMARY_SERVICE_UUID) || att_iterator_match_uuid16(&it, GATT_SECONDARY_SERVICE_UUID);
1190 
1191         // close current tag, if within a group and a new service definition starts or we reach end of att db
1192         if (in_group &&
1193             (it.handle == 0 || new_service_started)){
1194             *end_handle = prev_handle;
1195             return 1;
1196         }
1197 
1198         // keep track of previous handle
1199         prev_handle = it.handle;
1200 
1201         // check if found
1202         if (it.handle && new_service_started && attribute_len == it.value_len && memcmp(attribute_value, it.value, it.value_len) == 0){
1203             *start_handle = it.handle;
1204             in_group = 1;
1205         }
1206     }
1207     return 0;
1208 }
1209 
1210 // returns 0 if not found
1211 uint16_t gatt_server_get_value_handle_for_characteristic_with_uuid16(uint16_t start_handle, uint16_t end_handle, uint16_t uuid16){
1212     att_iterator_t it;
1213     att_iterator_init(&it);
1214     while (att_iterator_has_next(&it)){
1215         att_iterator_fetch_next(&it);
1216         if (it.handle && it.handle < start_handle) continue;
1217         if (it.handle > end_handle) break;  // (1)
1218         if (it.handle == 0) break;
1219         if (att_iterator_match_uuid16(&it, uuid16)) return it.handle;
1220     }
1221     return 0;
1222 }
1223 
1224 // returns 0 if not found
1225 uint16_t gatt_server_get_client_configuration_handle_for_characteristic_with_uuid16(uint16_t start_handle, uint16_t end_handle, uint16_t uuid16){
1226     att_iterator_t it;
1227     att_iterator_init(&it);
1228     int characteristic_found = 0;
1229     while (att_iterator_has_next(&it)){
1230         att_iterator_fetch_next(&it);
1231         if (it.handle && it.handle < start_handle) continue;
1232         if (it.handle > end_handle) break;  // (1)
1233         if (it.handle == 0) break;
1234         if (att_iterator_match_uuid16(&it, uuid16)){
1235             characteristic_found = 1;
1236             continue;
1237         }
1238         if (att_iterator_match_uuid16(&it, GATT_PRIMARY_SERVICE_UUID)
1239          || att_iterator_match_uuid16(&it, GATT_SECONDARY_SERVICE_UUID)
1240          || att_iterator_match_uuid16(&it, GATT_CHARACTERISTICS_UUID)){
1241             if (characteristic_found) break;
1242             continue;
1243         }
1244         if (att_iterator_match_uuid16(&it, GATT_CLIENT_CHARACTERISTICS_CONFIGURATION)){
1245             return it.handle;
1246         }
1247     }
1248     return 0;
1249 }
1250 
1251 // 1-item cache to optimize query during write_callback
1252 static void att_persistent_ccc_cache(att_iterator_t * it){
1253     att_persistent_ccc_handle = it->handle;
1254     if (it->flags & ATT_PROPERTY_UUID128){
1255         att_persistent_ccc_uuid16 = 0;
1256     } else {
1257         att_persistent_ccc_uuid16 = little_endian_read_16(it->uuid, 0);
1258     }
1259 }
1260 
1261 int att_is_persistent_ccc(uint16_t handle){
1262     if (handle != att_persistent_ccc_handle){
1263         att_iterator_t it;
1264         int ok = att_find_handle(&it, handle);
1265         if (!ok) return 0;
1266         att_persistent_ccc_cache(&it);
1267     }
1268     return att_persistent_ccc_uuid16 == GATT_CLIENT_CHARACTERISTICS_CONFIGURATION;
1269 }
1270 
1271 // att_read_callback helpers
1272 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){
1273     if (buffer){
1274         uint16_t bytes_to_copy = btstack_min(blob_size - offset, buffer_size);
1275         memcpy(buffer, &blob[offset], bytes_to_copy);
1276         return bytes_to_copy;
1277     } else {
1278         return blob_size;
1279     }
1280 }
1281 
1282 uint16_t att_read_callback_handle_little_endian_32(uint32_t value, uint16_t offset, uint8_t * buffer, uint16_t buffer_size){
1283     uint8_t value_buffer[4];
1284     little_endian_store_32(value_buffer, 0, value);
1285     return att_read_callback_handle_blob(value_buffer, sizeof(value_buffer), offset, buffer, buffer_size);
1286 }
1287 
1288 uint16_t att_read_callback_handle_little_endian_16(uint16_t value, uint16_t offset, uint8_t * buffer, uint16_t buffer_size){
1289     uint8_t value_buffer[2];
1290     little_endian_store_16(value_buffer, 0, value);
1291     return att_read_callback_handle_blob(value_buffer, sizeof(value_buffer), offset, buffer, buffer_size);
1292 }
1293 
1294 uint16_t att_read_callback_handle_byte(uint8_t value, uint16_t offset, uint8_t * buffer, uint16_t buffer_size){
1295     uint8_t value_buffer[1];
1296     value_buffer[0] = value;
1297     return att_read_callback_handle_blob(value_buffer, sizeof(value_buffer), offset, buffer, buffer_size);
1298 }
1299