xref: /btstack/src/ble/att_db.c (revision eeeae29572c0a80881040fd86b562c1534c37727)
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_info("att_validate_security. flags 0x%04x (=> security level %u, key size %u) authorized %u, authenticated %u, encryption_key_size %u",
309         it->flags, required_security_level, required_encryption_size, 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         error_code = att_validate_security(att_connection, ATT_READ, &it);
550         if (error_code) break;
551 
552         att_update_value_len(&it, att_connection->con_handle);
553 
554 #ifdef ENABLE_ATT_DELAYED_READ_RESPONSE
555         if (it.value_len == ATT_READ_RESPONSE_PENDING){
556             read_request_pending = 1;
557         }
558         if (read_request_pending) continue;
559 #endif
560 
561         // check if value has same len as last one
562         uint16_t this_pair_len = 2 + it.value_len;
563         if (offset > 1){
564             if (pair_len != this_pair_len) {
565                 break;
566             }
567         }
568 
569         // first
570         if (offset == 1) {
571             pair_len = this_pair_len;
572             response_buffer[offset] = pair_len;
573             offset++;
574         }
575 
576         // space?
577         if (offset + pair_len > response_buffer_size) {
578             if (offset > 2) break;
579             it.value_len = response_buffer_size - 4;
580             response_buffer[1] = 2 + it.value_len;
581         }
582 
583         // store
584         little_endian_store_16(response_buffer, offset, it.handle);
585         offset += 2;
586         uint16_t bytes_copied = att_copy_value(&it, 0, response_buffer + offset, it.value_len, att_connection->con_handle);
587         offset += bytes_copied;
588     }
589 
590 #ifdef ENABLE_ATT_DELAYED_READ_RESPONSE
591     if (read_request_pending) return ATT_READ_RESPONSE_PENDING;
592 #endif
593 
594     // at least one attribute could be read
595     if (offset > 1){
596         response_buffer[0] = ATT_READ_BY_TYPE_RESPONSE;
597         return offset;
598     }
599 
600     // first attribute had an error
601     if (error_code){
602         return setup_error(response_buffer, request_type, start_handle, error_code);
603     }
604 
605     // no other errors, but all found attributes had been non-readable
606     if (first_matching_but_unreadable_handle){
607         return setup_error_read_not_permitted(response_buffer, request_type, first_matching_but_unreadable_handle);
608     }
609 
610     // attribute not found
611     return setup_error_atribute_not_found(response_buffer, request_type, start_handle);
612 }
613 
614 static uint16_t handle_read_by_type_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
615                                      uint8_t * response_buffer, uint16_t response_buffer_size){
616     int attribute_type_len;
617     if (request_len <= 7){
618         attribute_type_len = 2;
619     } else {
620         attribute_type_len = 16;
621     }
622     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]);
623 }
624 
625 //
626 // MARK: ATT_READ_BY_TYPE_REQUEST
627 //
628 static uint16_t handle_read_request2(att_connection_t * att_connection, uint8_t * response_buffer, uint16_t response_buffer_size, uint16_t handle){
629 
630     log_info("ATT_READ_REQUEST: handle %04x", handle);
631     uint8_t request_type = ATT_READ_REQUEST;
632 
633     att_iterator_t it;
634     int ok = att_find_handle(&it, handle);
635     if (!ok){
636         return setup_error_invalid_handle(response_buffer, request_type, handle);
637     }
638 
639     // check if handle can be read
640     if ((it.flags & ATT_PROPERTY_READ) == 0) {
641         return setup_error_read_not_permitted(response_buffer, request_type, handle);
642     }
643 
644     // check security requirements
645     uint8_t error_code = att_validate_security(att_connection, ATT_READ, &it);
646     if (error_code) {
647         return setup_error(response_buffer, request_type, handle, error_code);
648     }
649 
650     att_update_value_len(&it, att_connection->con_handle);
651 
652 #ifdef ENABLE_ATT_DELAYED_READ_RESPONSE
653     if (it.value_len == ATT_READ_RESPONSE_PENDING) return ATT_READ_RESPONSE_PENDING;
654 #endif
655 
656     uint16_t offset   = 1;
657     // limit data
658     if (offset + it.value_len > response_buffer_size) {
659         it.value_len = response_buffer_size - 1;
660     }
661 
662     // store
663     uint16_t bytes_copied = att_copy_value(&it, 0, response_buffer + offset, it.value_len, att_connection->con_handle);
664     offset += bytes_copied;
665 
666     response_buffer[0] = ATT_READ_RESPONSE;
667     return offset;
668 }
669 
670 static uint16_t handle_read_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
671                              uint8_t * response_buffer, uint16_t response_buffer_size){
672     UNUSED(request_len);
673     return handle_read_request2(att_connection, response_buffer, response_buffer_size, little_endian_read_16(request_buffer, 1));
674 }
675 
676 //
677 // MARK: ATT_READ_BLOB_REQUEST 0x0c
678 //
679 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){
680     log_info("ATT_READ_BLOB_REQUEST: handle %04x, offset %u", handle, value_offset);
681     uint8_t request_type = ATT_READ_BLOB_REQUEST;
682 
683     att_iterator_t it;
684     int ok = att_find_handle(&it, handle);
685     if (!ok){
686         return setup_error_invalid_handle(response_buffer, request_type, handle);
687     }
688 
689     // check if handle can be read
690     if ((it.flags & ATT_PROPERTY_READ) == 0) {
691         return setup_error_read_not_permitted(response_buffer, request_type, handle);
692     }
693 
694     // check security requirements
695     uint8_t error_code = att_validate_security(att_connection, ATT_READ, &it);
696     if (error_code) {
697         return setup_error(response_buffer, request_type, handle, error_code);
698     }
699 
700     att_update_value_len(&it, att_connection->con_handle);
701 
702 #ifdef ENABLE_ATT_DELAYED_READ_RESPONSE
703     if (it.value_len == ATT_READ_RESPONSE_PENDING) return ATT_READ_RESPONSE_PENDING;
704 #endif
705 
706     if (value_offset > it.value_len){
707         return setup_error_invalid_offset(response_buffer, request_type, handle);
708     }
709 
710     // limit data
711     uint16_t offset   = 1;
712     if (offset + it.value_len - value_offset > response_buffer_size) {
713         it.value_len = response_buffer_size - 1 + value_offset;
714     }
715 
716     // store
717     uint16_t bytes_copied = att_copy_value(&it, value_offset, response_buffer + offset, it.value_len - value_offset, att_connection->con_handle);
718     offset += bytes_copied;
719 
720     response_buffer[0] = ATT_READ_BLOB_RESPONSE;
721     return offset;
722 }
723 
724 static uint16_t handle_read_blob_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
725                                   uint8_t * response_buffer, uint16_t response_buffer_size){
726     UNUSED(request_len);
727     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));
728 }
729 
730 //
731 // MARK: ATT_READ_MULTIPLE_REQUEST 0x0e
732 //
733 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){
734     log_info("ATT_READ_MULTIPLE_REQUEST: num handles %u", num_handles);
735     uint8_t request_type = ATT_READ_MULTIPLE_REQUEST;
736 
737     // TODO: figure out which error to respond with
738     // if (num_handles < 2){
739     //     return setup_error(response_buffer, ATT_READ_MULTIPLE_REQUEST, handle, ???);
740     // }
741 
742     uint16_t offset   = 1;
743 
744     int i;
745     uint8_t error_code = 0;
746     uint16_t handle = 0;
747 
748 #ifdef ENABLE_ATT_DELAYED_READ_RESPONSE
749     int read_request_pending = 0;
750 #endif
751 
752     for (i=0;i<num_handles;i++){
753         handle = little_endian_read_16(handles, i << 1);
754 
755         if (handle == 0){
756             return setup_error_invalid_handle(response_buffer, request_type, handle);
757         }
758 
759         att_iterator_t it;
760 
761         int ok = att_find_handle(&it, handle);
762         if (!ok){
763             return setup_error_invalid_handle(response_buffer, request_type, handle);
764         }
765 
766         // check if handle can be read
767         if ((it.flags & ATT_PROPERTY_READ) == 0) {
768             error_code = ATT_ERROR_READ_NOT_PERMITTED;
769             break;
770         }
771 
772         // check security requirements
773         error_code = att_validate_security(att_connection, ATT_READ, &it);
774         if (error_code) break;
775 
776         att_update_value_len(&it, att_connection->con_handle);
777 
778 #ifdef ENABLE_ATT_DELAYED_READ_RESPONSE
779         if (it.value_len == ATT_READ_RESPONSE_PENDING) {
780             read_request_pending = 1;
781         }
782         if (read_request_pending) continue;
783 #endif
784 
785         // limit data
786         if (offset + it.value_len > response_buffer_size) {
787             it.value_len = response_buffer_size - 1;
788         }
789 
790         // store
791         uint16_t bytes_copied = att_copy_value(&it, 0, response_buffer + offset, it.value_len, att_connection->con_handle);
792         offset += bytes_copied;
793     }
794 
795     if (error_code){
796         return setup_error(response_buffer, request_type, handle, error_code);
797     }
798 
799     response_buffer[0] = ATT_READ_MULTIPLE_RESPONSE;
800     return offset;
801 }
802 static uint16_t handle_read_multiple_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
803                                       uint8_t * response_buffer, uint16_t response_buffer_size){
804     int num_handles = (request_len - 1) >> 1;
805     return handle_read_multiple_request2(att_connection, response_buffer, response_buffer_size, num_handles, &request_buffer[1]);
806 }
807 
808 //
809 // MARK: ATT_READ_BY_GROUP_TYPE_REQUEST 0x10
810 //
811 // Only handles GATT_PRIMARY_SERVICE_UUID and GATT_SECONDARY_SERVICE_UUID
812 // Core v4.0, vol 3, part g, 2.5.3
813 // "The «Primary Service» and «Secondary Service» grouping types may be used in the Read By Group Type Request.
814 //  The «Characteristic» grouping type shall not be used in the ATT Read By Group Type Request."
815 //
816 // NOTE: doesn't handle DYNAMIC values
817 //
818 // NOTE: we don't check for security as PRIMARY and SECONDAY SERVICE definition shouldn't be protected
819 // Core 4.0, vol 3, part g, 8.1
820 // "The list of services and characteristics that a device supports is not considered private or
821 //  confidential information, and therefore the Service and Characteristic Discovery procedures
822 //  shall always be permitted. "
823 //
824 static uint16_t handle_read_by_group_type_request2(att_connection_t * att_connection, uint8_t * response_buffer, uint16_t response_buffer_size,
825                                             uint16_t start_handle, uint16_t end_handle,
826                                             uint16_t attribute_type_len, uint8_t * attribute_type){
827 
828     UNUSED(att_connection);
829 
830     log_info("ATT_READ_BY_GROUP_TYPE_REQUEST: from %04X to %04X, buffer size %u, type: ", start_handle, end_handle, response_buffer_size);
831     log_info_hexdump(attribute_type, attribute_type_len);
832     uint8_t request_type = ATT_READ_BY_GROUP_TYPE_REQUEST;
833 
834     if (start_handle > end_handle || start_handle == 0){
835         return setup_error_invalid_handle(response_buffer, request_type, start_handle);
836     }
837 
838     // assert UUID is primary or secondary service uuid
839     uint16_t uuid16 = uuid16_from_uuid(attribute_type_len, attribute_type);
840     if (uuid16 != GATT_PRIMARY_SERVICE_UUID && uuid16 != GATT_SECONDARY_SERVICE_UUID){
841         return setup_error(response_buffer, request_type, start_handle, ATT_ERROR_UNSUPPORTED_GROUP_TYPE);
842     }
843 
844     uint16_t offset   = 1;
845     uint16_t pair_len = 0;
846     uint16_t in_group = 0;
847     uint16_t group_start_handle = 0;
848     uint8_t const * group_start_value = NULL;
849     uint16_t prev_handle = 0;
850 
851     att_iterator_t it;
852     att_iterator_init(&it);
853     while (att_iterator_has_next(&it)){
854         att_iterator_fetch_next(&it);
855 
856         if (it.handle && it.handle < start_handle) continue;
857         if (it.handle > end_handle) break;  // (1)
858 
859         // log_info("Handle 0x%04x", it.handle);
860 
861         // close current tag, if within a group and a new service definition starts or we reach end of att db
862         if (in_group &&
863             (it.handle == 0 || att_iterator_match_uuid16(&it, GATT_PRIMARY_SERVICE_UUID) || att_iterator_match_uuid16(&it, GATT_SECONDARY_SERVICE_UUID))){
864             // log_info("End of group, handle 0x%04x, val_len: %u", prev_handle, pair_len - 4);
865 
866             little_endian_store_16(response_buffer, offset, group_start_handle);
867             offset += 2;
868             little_endian_store_16(response_buffer, offset, prev_handle);
869             offset += 2;
870             memcpy(response_buffer + offset, group_start_value, pair_len - 4);
871             offset += pair_len - 4;
872             in_group = 0;
873 
874             // check if space for another handle pair available
875             if (offset + pair_len > response_buffer_size){
876                 break;
877             }
878         }
879 
880         // keep track of previous handle
881         prev_handle = it.handle;
882 
883         // does current attribute match
884         // log_info("compare: %04x == %04x", *(uint16_t*) context->attribute_type, *(uint16_t*) uuid);
885         if (it.handle && att_iterator_match_uuid(&it, attribute_type, attribute_type_len)) {
886 
887             // check if value has same len as last one
888             uint16_t this_pair_len = 4 + it.value_len;
889             if (offset > 1){
890                 if (this_pair_len != pair_len) {
891                     break;
892                 }
893             }
894 
895             // log_info("Begin of group, handle 0x%04x", it.handle);
896 
897             // first
898             if (offset == 1) {
899                 pair_len = this_pair_len;
900                 response_buffer[offset] = this_pair_len;
901                 offset++;
902             }
903 
904             group_start_handle = it.handle;
905             group_start_value  = it.value;
906             in_group = 1;
907         }
908     }
909 
910     if (offset == 1){
911         return setup_error_atribute_not_found(response_buffer, request_type, start_handle);
912     }
913 
914     response_buffer[0] = ATT_READ_BY_GROUP_TYPE_RESPONSE;
915     return offset;
916 }
917 static uint16_t handle_read_by_group_type_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
918                                            uint8_t * response_buffer, uint16_t response_buffer_size){
919     int attribute_type_len;
920     if (request_len <= 7){
921         attribute_type_len = 2;
922     } else {
923         attribute_type_len = 16;
924     }
925     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]);
926 }
927 
928 //
929 // MARK: ATT_WRITE_REQUEST 0x12
930 static uint16_t handle_write_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
931                               uint8_t * response_buffer, uint16_t response_buffer_size){
932 
933     UNUSED(response_buffer_size);
934 
935     uint8_t request_type = ATT_WRITE_REQUEST;
936 
937     uint16_t handle = little_endian_read_16(request_buffer, 1);
938     att_iterator_t it;
939     int ok = att_find_handle(&it, handle);
940     if (!ok) {
941         return setup_error_invalid_handle(response_buffer, request_type, handle);
942     }
943     if (!att_write_callback) {
944         return setup_error_write_not_permitted(response_buffer, request_type, handle);
945     }
946     if ((it.flags & ATT_PROPERTY_WRITE) == 0) {
947         return setup_error_write_not_permitted(response_buffer, request_type, handle);
948     }
949     if ((it.flags & ATT_PROPERTY_DYNAMIC) == 0) {
950         return setup_error_write_not_permitted(response_buffer, request_type, handle);
951     }
952     // check security requirements
953     uint8_t error_code = att_validate_security(att_connection, ATT_WRITE, &it);
954     if (error_code) {
955         return setup_error(response_buffer, request_type, handle, error_code);
956     }
957     att_persistent_ccc_cache(&it);
958     error_code = (*att_write_callback)(att_connection->con_handle, handle, ATT_TRANSACTION_MODE_NONE, 0, request_buffer + 3, request_len - 3);
959     if (error_code) {
960         return setup_error(response_buffer, request_type, handle, error_code);
961     }
962     response_buffer[0] = ATT_WRITE_RESPONSE;
963     return 1;
964 }
965 
966 //
967 // MARK: ATT_PREPARE_WRITE_REQUEST 0x16
968 static uint16_t handle_prepare_write_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
969                                       uint8_t * response_buffer, uint16_t response_buffer_size){
970 
971     UNUSED(response_buffer_size);
972 
973     uint8_t request_type = ATT_PREPARE_WRITE_REQUEST;
974 
975     uint16_t handle = little_endian_read_16(request_buffer, 1);
976     uint16_t offset = little_endian_read_16(request_buffer, 3);
977     if (!att_write_callback) {
978         return setup_error_write_not_permitted(response_buffer, request_type, handle);
979     }
980     att_iterator_t it;
981     int ok = att_find_handle(&it, handle);
982     if (!ok) {
983         return setup_error_invalid_handle(response_buffer, request_type, handle);
984     }
985     if ((it.flags & ATT_PROPERTY_WRITE) == 0) {
986         return setup_error_write_not_permitted(response_buffer, request_type, handle);
987     }
988     if ((it.flags & ATT_PROPERTY_DYNAMIC) == 0) {
989         return setup_error_write_not_permitted(response_buffer, request_type, handle);
990     }
991     // check security requirements
992     uint8_t error_code = att_validate_security(att_connection, ATT_WRITE, &it);
993     if (error_code) {
994         return setup_error(response_buffer, request_type, handle, error_code);
995     }
996 
997     error_code = (*att_write_callback)(att_connection->con_handle, handle, ATT_TRANSACTION_MODE_ACTIVE, offset, request_buffer + 5, request_len - 5);
998     switch (error_code){
999         case 0:
1000             break;
1001         case ATT_ERROR_INVALID_OFFSET:
1002         case ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH:
1003             // postpone to execute write request
1004             att_prepare_write_update_errors(error_code, handle);
1005             break;
1006         default:
1007             return setup_error(response_buffer, request_type, handle, error_code);
1008     }
1009 
1010     // response: echo request
1011     memcpy(response_buffer, request_buffer, request_len);
1012     response_buffer[0] = ATT_PREPARE_WRITE_RESPONSE;
1013     return request_len;
1014 }
1015 
1016 /*
1017  * @brief transcation queue of prepared writes, e.g., after disconnect
1018  */
1019 void att_clear_transaction_queue(att_connection_t * att_connection){
1020     (*att_write_callback)(att_connection->con_handle, 0, ATT_TRANSACTION_MODE_CANCEL, 0, NULL, 0);
1021 }
1022 
1023 // MARK: ATT_EXECUTE_WRITE_REQUEST 0x18
1024 // NOTE: security has been verified by handle_prepare_write_request
1025 static uint16_t handle_execute_write_request(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
1026                                       uint8_t * response_buffer, uint16_t response_buffer_size){
1027 
1028     UNUSED(request_len);
1029     UNUSED(response_buffer_size);
1030 
1031     uint8_t request_type = ATT_EXECUTE_WRITE_REQUEST;
1032     if (request_buffer[1]) {
1033         // validate queued write
1034         if (att_prepare_write_error_code == 0){
1035             att_prepare_write_error_code = (*att_write_callback)(att_connection->con_handle, 0, ATT_TRANSACTION_MODE_VALIDATE, 0, NULL, 0);
1036         }
1037         // deliver queued errors
1038         if (att_prepare_write_error_code){
1039             att_clear_transaction_queue(att_connection);
1040             uint8_t  error_code = att_prepare_write_error_code;
1041             uint16_t handle     = att_prepare_write_error_handle;
1042             att_prepare_write_reset();
1043             return setup_error(response_buffer, request_type, handle, error_code);
1044         }
1045         att_write_callback(att_connection->con_handle, 0, ATT_TRANSACTION_MODE_EXECUTE, 0, NULL, 0);
1046     } else {
1047         att_clear_transaction_queue(att_connection);
1048     }
1049     response_buffer[0] = ATT_EXECUTE_WRITE_RESPONSE;
1050     return 1;
1051 }
1052 
1053 // MARK: ATT_WRITE_COMMAND 0x52
1054 // Core 4.0, vol 3, part F, 3.4.5.3
1055 // "No Error Response or Write Response shall be sent in response to this command"
1056 static void handle_write_command(att_connection_t * att_connection, uint8_t * request_buffer,  uint16_t request_len,
1057                                            uint8_t * response_buffer, uint16_t response_buffer_size){
1058 
1059     UNUSED(response_buffer);
1060     UNUSED(response_buffer_size);
1061 
1062     uint16_t handle = little_endian_read_16(request_buffer, 1);
1063     if (!att_write_callback) return;
1064 
1065     att_iterator_t it;
1066     int ok = att_find_handle(&it, handle);
1067     if (!ok) return;
1068     if ((it.flags & ATT_PROPERTY_DYNAMIC) == 0) return;
1069     if ((it.flags & ATT_PROPERTY_WRITE_WITHOUT_RESPONSE) == 0) return;
1070     if (att_validate_security(att_connection, ATT_WRITE, &it)) return;
1071     att_persistent_ccc_cache(&it);
1072     (*att_write_callback)(att_connection->con_handle, handle, ATT_TRANSACTION_MODE_NONE, 0, request_buffer + 3, request_len - 3);
1073 }
1074 
1075 // MARK: helper for ATT_HANDLE_VALUE_NOTIFICATION and ATT_HANDLE_VALUE_INDICATION
1076 static uint16_t prepare_handle_value(att_connection_t * att_connection,
1077                                      uint16_t handle,
1078                                      uint8_t *value,
1079                                      uint16_t value_len,
1080                                      uint8_t * response_buffer){
1081     little_endian_store_16(response_buffer, 1, handle);
1082     if (value_len > att_connection->mtu - 3){
1083         value_len = att_connection->mtu - 3;
1084     }
1085     memcpy(&response_buffer[3], value, value_len);
1086     return value_len + 3;
1087 }
1088 
1089 // MARK: ATT_HANDLE_VALUE_NOTIFICATION 0x1b
1090 uint16_t att_prepare_handle_value_notification(att_connection_t * att_connection,
1091                                                uint16_t handle,
1092                                                uint8_t *value,
1093                                                uint16_t value_len,
1094                                                uint8_t * response_buffer){
1095 
1096     response_buffer[0] = ATT_HANDLE_VALUE_NOTIFICATION;
1097     return prepare_handle_value(att_connection, handle, value, value_len, response_buffer);
1098 }
1099 
1100 // MARK: ATT_HANDLE_VALUE_INDICATION 0x1d
1101 uint16_t att_prepare_handle_value_indication(att_connection_t * att_connection,
1102                                              uint16_t handle,
1103                                              uint8_t *value,
1104                                              uint16_t value_len,
1105                                              uint8_t * response_buffer){
1106 
1107     response_buffer[0] = ATT_HANDLE_VALUE_INDICATION;
1108     return prepare_handle_value(att_connection, handle, value, value_len, response_buffer);
1109 }
1110 
1111 // MARK: Dispatcher
1112 uint16_t att_handle_request(att_connection_t * att_connection,
1113                             uint8_t * request_buffer,
1114                             uint16_t request_len,
1115                             uint8_t * response_buffer){
1116     uint16_t response_len = 0;
1117     uint16_t response_buffer_size = att_connection->mtu;
1118 
1119     switch (request_buffer[0]){
1120         case ATT_EXCHANGE_MTU_REQUEST:
1121             response_len = handle_exchange_mtu_request(att_connection, request_buffer, request_len, response_buffer);
1122             break;
1123         case ATT_FIND_INFORMATION_REQUEST:
1124             response_len = handle_find_information_request(att_connection, request_buffer, request_len,response_buffer, response_buffer_size);
1125             break;
1126         case ATT_FIND_BY_TYPE_VALUE_REQUEST:
1127             response_len = handle_find_by_type_value_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1128             break;
1129         case ATT_READ_BY_TYPE_REQUEST:
1130             response_len = handle_read_by_type_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1131             break;
1132         case ATT_READ_REQUEST:
1133             response_len = handle_read_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1134             break;
1135         case ATT_READ_BLOB_REQUEST:
1136             response_len = handle_read_blob_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1137             break;
1138         case ATT_READ_MULTIPLE_REQUEST:
1139             response_len = handle_read_multiple_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1140             break;
1141         case ATT_READ_BY_GROUP_TYPE_REQUEST:
1142             response_len = handle_read_by_group_type_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1143             break;
1144         case ATT_WRITE_REQUEST:
1145             response_len = handle_write_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1146             break;
1147         case ATT_PREPARE_WRITE_REQUEST:
1148             response_len = handle_prepare_write_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1149             break;
1150         case ATT_EXECUTE_WRITE_REQUEST:
1151             response_len = handle_execute_write_request(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1152             break;
1153         case ATT_WRITE_COMMAND:
1154             handle_write_command(att_connection, request_buffer, request_len, response_buffer, response_buffer_size);
1155             break;
1156 #ifdef ENABLE_LE_SIGNED_WRITE
1157         case ATT_SIGNED_WRITE_COMMAND:
1158             log_info("handle_signed_write_command preprocessed by att_server.c");
1159             break;
1160 #endif
1161         default:
1162             log_info("Unhandled ATT Command: %02X, DATA: ", request_buffer[0]);
1163             log_info_hexdump(&request_buffer[9], request_len-9);
1164             break;
1165     }
1166     return response_len;
1167 }
1168 
1169 // returns 1 if service found. only primary service.
1170 int gatt_server_get_get_handle_range_for_service_with_uuid16(uint16_t uuid16, uint16_t * start_handle, uint16_t * end_handle){
1171     uint16_t in_group    = 0;
1172     uint16_t prev_handle = 0;
1173 
1174     uint8_t attribute_value[2];
1175     int attribute_len = sizeof(attribute_value);
1176     little_endian_store_16(attribute_value, 0, uuid16);
1177 
1178     att_iterator_t it;
1179     att_iterator_init(&it);
1180     while (att_iterator_has_next(&it)){
1181         att_iterator_fetch_next(&it);
1182         int new_service_started = att_iterator_match_uuid16(&it, GATT_PRIMARY_SERVICE_UUID) || att_iterator_match_uuid16(&it, GATT_SECONDARY_SERVICE_UUID);
1183 
1184         // close current tag, if within a group and a new service definition starts or we reach end of att db
1185         if (in_group &&
1186             (it.handle == 0 || new_service_started)){
1187             *end_handle = prev_handle;
1188             return 1;
1189         }
1190 
1191         // keep track of previous handle
1192         prev_handle = it.handle;
1193 
1194         // check if found
1195         if (it.handle && new_service_started && attribute_len == it.value_len && memcmp(attribute_value, it.value, it.value_len) == 0){
1196             *start_handle = it.handle;
1197             in_group = 1;
1198         }
1199     }
1200     return 0;
1201 }
1202 
1203 // returns 0 if not found
1204 uint16_t gatt_server_get_value_handle_for_characteristic_with_uuid16(uint16_t start_handle, uint16_t end_handle, uint16_t uuid16){
1205     att_iterator_t it;
1206     att_iterator_init(&it);
1207     while (att_iterator_has_next(&it)){
1208         att_iterator_fetch_next(&it);
1209         if (it.handle && it.handle < start_handle) continue;
1210         if (it.handle > end_handle) break;  // (1)
1211         if (it.handle == 0) break;
1212         if (att_iterator_match_uuid16(&it, uuid16)) return it.handle;
1213     }
1214     return 0;
1215 }
1216 
1217 // returns 0 if not found
1218 uint16_t gatt_server_get_client_configuration_handle_for_characteristic_with_uuid16(uint16_t start_handle, uint16_t end_handle, uint16_t uuid16){
1219     att_iterator_t it;
1220     att_iterator_init(&it);
1221     int characteristic_found = 0;
1222     while (att_iterator_has_next(&it)){
1223         att_iterator_fetch_next(&it);
1224         if (it.handle && it.handle < start_handle) continue;
1225         if (it.handle > end_handle) break;  // (1)
1226         if (it.handle == 0) break;
1227         if (att_iterator_match_uuid16(&it, uuid16)){
1228             characteristic_found = 1;
1229             continue;
1230         }
1231         if (att_iterator_match_uuid16(&it, GATT_PRIMARY_SERVICE_UUID)
1232          || att_iterator_match_uuid16(&it, GATT_SECONDARY_SERVICE_UUID)
1233          || att_iterator_match_uuid16(&it, GATT_CHARACTERISTICS_UUID)){
1234             if (characteristic_found) break;
1235             continue;
1236         }
1237         if (att_iterator_match_uuid16(&it, GATT_CLIENT_CHARACTERISTICS_CONFIGURATION)){
1238             return it.handle;
1239         }
1240     }
1241     return 0;
1242 }
1243 
1244 // 1-item cache to optimize query during write_callback
1245 static void att_persistent_ccc_cache(att_iterator_t * it){
1246     att_persistent_ccc_handle = it->handle;
1247     if (it->flags & ATT_PROPERTY_UUID128){
1248         att_persistent_ccc_uuid16 = 0;
1249     } else {
1250         att_persistent_ccc_uuid16 = little_endian_read_16(it->uuid, 0);
1251     }
1252 }
1253 
1254 int att_is_persistent_ccc(uint16_t handle){
1255     if (handle != att_persistent_ccc_handle){
1256         att_iterator_t it;
1257         int ok = att_find_handle(&it, handle);
1258         if (!ok) return 0;
1259         att_persistent_ccc_cache(&it);
1260     }
1261     return att_persistent_ccc_uuid16 == GATT_CLIENT_CHARACTERISTICS_CONFIGURATION;
1262 }
1263 
1264 // att_read_callback helpers
1265 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){
1266     if (buffer){
1267         uint16_t bytes_to_copy = btstack_min(blob_size - offset, buffer_size);
1268         memcpy(buffer, &blob[offset], bytes_to_copy);
1269         return bytes_to_copy;
1270     } else {
1271         return blob_size;
1272     }
1273 }
1274 
1275 uint16_t att_read_callback_handle_little_endian_32(uint32_t value, uint16_t offset, uint8_t * buffer, uint16_t buffer_size){
1276     uint8_t value_buffer[4];
1277     little_endian_store_32(value_buffer, 0, value);
1278     return att_read_callback_handle_blob(value_buffer, sizeof(value_buffer), offset, buffer, buffer_size);
1279 }
1280 
1281 uint16_t att_read_callback_handle_little_endian_16(uint16_t value, uint16_t offset, uint8_t * buffer, uint16_t buffer_size){
1282     uint8_t value_buffer[2];
1283     little_endian_store_16(value_buffer, 0, value);
1284     return att_read_callback_handle_blob(value_buffer, sizeof(value_buffer), offset, buffer, buffer_size);
1285 }
1286 
1287 uint16_t att_read_callback_handle_byte(uint8_t value, uint16_t offset, uint8_t * buffer, uint16_t buffer_size){
1288     uint8_t value_buffer[1];
1289     value_buffer[0] = value;
1290     return att_read_callback_handle_blob(value_buffer, sizeof(value_buffer), offset, buffer, buffer_size);
1291 }
1292