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