xref: /btstack/src/ble/att_server.c (revision e07b53a61840d4ca0866385b8fc553ed6dbd96aa)
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_server.c"
39 
40 
41 //
42 // ATT Server Globals
43 //
44 
45 #include <stdint.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <inttypes.h>
50 
51 #include "btstack_config.h"
52 
53 #include "att_dispatch.h"
54 #include "ble/att_db.h"
55 #include "ble/att_server.h"
56 #include "ble/core.h"
57 #include "ble/le_device_db.h"
58 #include "ble/sm.h"
59 #include "btstack_debug.h"
60 #include "btstack_event.h"
61 #include "btstack_memory.h"
62 #include "btstack_run_loop.h"
63 #include "gap.h"
64 #include "hci.h"
65 #include "hci_dump.h"
66 #include "l2cap.h"
67 #include "btstack_tlv.h"
68 
69 #ifndef GATT_SERVER_NUM_PERSISTENT_CCC
70 #define GATT_SERVER_NUM_PERSISTENT_CCC 20
71 #endif
72 
73 static void att_run_for_context(att_server_t * att_server);
74 static att_write_callback_t att_server_write_callback_for_handle(uint16_t handle);
75 static void att_server_persistent_ccc_restore(att_server_t * att_server);
76 static void att_server_persistent_ccc_clear(att_server_t * att_server);
77 
78 // global
79 static btstack_packet_callback_registration_t hci_event_callback_registration;
80 static btstack_packet_callback_registration_t sm_event_callback_registration;
81 static btstack_packet_handler_t               att_client_packet_handler = NULL;
82 static btstack_linked_list_t                  can_send_now_clients;
83 static btstack_linked_list_t                  service_handlers;
84 static uint8_t                                att_client_waiting_for_can_send;
85 
86 static att_read_callback_t                    att_server_client_read_callback;
87 static att_write_callback_t                   att_server_client_write_callback;
88 
89 // track CCC 1-entry cache
90 // static att_server_t *    att_persistent_ccc_server;
91 // static hci_con_handle_t  att_persistent_ccc_con_handle;
92 
93 static att_server_t * att_server_for_handle(hci_con_handle_t con_handle){
94     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
95     if (!hci_connection) return NULL;
96     return &hci_connection->att_server;
97 }
98 
99 #ifdef ENABLE_LE_SIGNED_WRITE
100 static att_server_t * att_server_for_state(att_server_state_t state){
101     btstack_linked_list_iterator_t it;
102     hci_connections_get_iterator(&it);
103     while(btstack_linked_list_iterator_has_next(&it)){
104         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
105         att_server_t * att_server = &connection->att_server;
106         if (att_server->state == state) return att_server;
107     }
108     return NULL;
109 }
110 #endif
111 
112 static void att_handle_value_indication_notify_client(uint8_t status, uint16_t client_handle, uint16_t attribute_handle){
113     if (!att_client_packet_handler) return;
114 
115     uint8_t event[7];
116     int pos = 0;
117     event[pos++] = ATT_EVENT_HANDLE_VALUE_INDICATION_COMPLETE;
118     event[pos++] = sizeof(event) - 2;
119     event[pos++] = status;
120     little_endian_store_16(event, pos, client_handle);
121     pos += 2;
122     little_endian_store_16(event, pos, attribute_handle);
123     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
124 }
125 
126 static void att_emit_mtu_event(hci_con_handle_t con_handle, uint16_t mtu){
127     if (!att_client_packet_handler) return;
128 
129     uint8_t event[6];
130     int pos = 0;
131     event[pos++] = ATT_EVENT_MTU_EXCHANGE_COMPLETE;
132     event[pos++] = sizeof(event) - 2;
133     little_endian_store_16(event, pos, con_handle);
134     pos += 2;
135     little_endian_store_16(event, pos, mtu);
136     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
137 }
138 
139 static void att_emit_can_send_now_event(void){
140     if (!att_client_packet_handler) return;
141 
142     uint8_t event[] = { ATT_EVENT_CAN_SEND_NOW, 0};
143     (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event));
144 }
145 
146 static void att_handle_value_indication_timeout(btstack_timer_source_t *ts){
147     void * context = btstack_run_loop_get_timer_context(ts);
148     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) context;
149     att_server_t * att_server = att_server_for_handle(con_handle);
150     if (!att_server) return;
151     uint16_t att_handle = att_server->value_indication_handle;
152     att_handle_value_indication_notify_client(ATT_HANDLE_VALUE_INDICATION_TIMEOUT, att_server->connection.con_handle, att_handle);
153 }
154 
155 static void att_device_identified(att_server_t * att_server, uint8_t index){
156     att_server->ir_lookup_active = 0;
157     att_server->ir_le_device_db_index = index;
158     log_info("Remote device with conn 0%04x registered with index id %u", (int) att_server->connection.con_handle, att_server->ir_le_device_db_index);
159     att_run_for_context(att_server);
160 }
161 
162 static void att_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
163 
164     UNUSED(channel); // ok: there is no channel
165     UNUSED(size);    // ok: handling own l2cap events
166 
167     att_server_t * att_server;
168     hci_con_handle_t con_handle;
169 
170     switch (packet_type) {
171 
172         case HCI_EVENT_PACKET:
173             switch (hci_event_packet_get_type(packet)) {
174 
175                 case HCI_EVENT_LE_META:
176                     switch (packet[2]) {
177                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
178                             con_handle = little_endian_read_16(packet, 4);
179                             att_server = att_server_for_handle(con_handle);
180                             if (!att_server) break;
181                         	// store connection info
182                         	att_server->peer_addr_type = packet[7];
183                             reverse_bd_addr(&packet[8], att_server->peer_address);
184                             att_server->connection.con_handle = con_handle;
185                             // reset connection properties
186                             att_server->state = ATT_SERVER_IDLE;
187                             att_server->connection.mtu = ATT_DEFAULT_MTU;
188                             att_server->connection.max_mtu = l2cap_max_le_mtu();
189                             if (att_server->connection.max_mtu > ATT_REQUEST_BUFFER_SIZE){
190                                 att_server->connection.max_mtu = ATT_REQUEST_BUFFER_SIZE;
191                             }
192                             att_server->connection.encryption_key_size = 0;
193                             att_server->connection.authenticated = 0;
194 		                	att_server->connection.authorized = 0;
195                             att_server->ir_le_device_db_index = -1;
196                             att_server->pairing_active = 0;
197                             break;
198 
199                         default:
200                             break;
201                     }
202                     break;
203 
204                 case HCI_EVENT_ENCRYPTION_CHANGE:
205                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
206                 	// check handle
207                     con_handle = little_endian_read_16(packet, 3);
208                     att_server = att_server_for_handle(con_handle);
209                     if (!att_server) break;
210                 	att_server->connection.encryption_key_size = sm_encryption_key_size(con_handle);
211                 	att_server->connection.authenticated = sm_authenticated(con_handle);
212                     if (hci_event_packet_get_type(packet) == HCI_EVENT_ENCRYPTION_CHANGE){
213                         // restore CCC values when encrypted
214                         if (hci_event_encryption_change_get_encryption_enabled(packet)){
215                             att_server_persistent_ccc_restore(att_server);
216                         }
217                     }
218                 	break;
219 
220                 case HCI_EVENT_DISCONNECTION_COMPLETE:
221                     // check handle
222                     con_handle = hci_event_disconnection_complete_get_connection_handle(packet);
223                     att_server = att_server_for_handle(con_handle);
224                     if (!att_server) break;
225                     att_clear_transaction_queue(&att_server->connection);
226                     att_server->connection.con_handle = 0;
227                     att_server->value_indication_handle = 0; // reset error state
228                     att_server->pairing_active = 0;
229                     att_server->state = ATT_SERVER_IDLE;
230                     break;
231 
232                 // Identity Resolving
233                 case SM_EVENT_IDENTITY_RESOLVING_STARTED:
234                     con_handle = sm_event_identity_resolving_started_get_handle(packet);
235                     att_server = att_server_for_handle(con_handle);
236                     if (!att_server) break;
237                     log_info("SM_EVENT_IDENTITY_RESOLVING_STARTED");
238                     att_server->ir_lookup_active = 1;
239                     break;
240                 case SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED:
241                     con_handle = sm_event_identity_created_get_handle(packet);
242                     att_server = att_server_for_handle(con_handle);
243                     if (!att_server) return;
244                     att_device_identified(att_server, sm_event_identity_resolving_succeeded_get_index(packet));
245                     break;
246                 case SM_EVENT_IDENTITY_RESOLVING_FAILED:
247                     con_handle = sm_event_identity_resolving_failed_get_handle(packet);
248                     att_server = att_server_for_handle(con_handle);
249                     if (!att_server) break;
250                     log_info("SM_EVENT_IDENTITY_RESOLVING_FAILED");
251                     att_server->ir_lookup_active = 0;
252                     att_server->ir_le_device_db_index = -1;
253                     att_run_for_context(att_server);
254                     break;
255 
256                 // Pairing started - delete stored CCC values
257                 // - assumes pairing indicates either new device or re-pairing, in both cases there should be no stored CCC values
258                 // - assumes that all events have the con handle as the first field
259                 case SM_EVENT_JUST_WORKS_REQUEST:
260                 case SM_EVENT_PASSKEY_DISPLAY_NUMBER:
261                 case SM_EVENT_PASSKEY_INPUT_NUMBER:
262                 case SM_EVENT_NUMERIC_COMPARISON_REQUEST:
263                     con_handle = sm_event_just_works_request_get_handle(packet);
264                     att_server = att_server_for_handle(con_handle);
265                     if (!att_server) break;
266                     att_server->pairing_active = 1;
267                     log_info("SM Pairing started");
268                     if (att_server->ir_le_device_db_index < 0) break;
269                     att_server_persistent_ccc_clear(att_server);
270                     // index not valid anymore
271                     att_server->ir_le_device_db_index = -1;
272                     break;
273 
274                 // Pairing completed
275                 case SM_EVENT_IDENTITY_CREATED:
276                     con_handle = sm_event_identity_created_get_handle(packet);
277                     att_server = att_server_for_handle(con_handle);
278                     if (!att_server) return;
279                     att_server->pairing_active = 0;
280                     att_device_identified(att_server, sm_event_identity_created_get_index(packet));
281                     break;
282 
283                 // Authorization
284                 case SM_EVENT_AUTHORIZATION_RESULT: {
285                     con_handle = sm_event_authorization_result_get_handle(packet);
286                     att_server = att_server_for_handle(con_handle);
287                     if (!att_server) break;
288                     att_server->connection.authorized = sm_event_authorization_result_get_authorization_result(packet);
289                     att_dispatch_server_request_can_send_now_event(con_handle);
290                 	break;
291                 }
292                 default:
293                     break;
294             }
295             break;
296         default:
297             break;
298     }
299 }
300 
301 #ifdef ENABLE_LE_SIGNED_WRITE
302 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
303 
304     att_server_t * att_server = att_server_for_state(ATT_SERVER_W4_SIGNED_WRITE_VALIDATION);
305     if (!att_server) return;
306 
307     uint8_t hash_flipped[8];
308     reverse_64(hash, hash_flipped);
309     if (memcmp(hash_flipped, &att_server->request_buffer[att_server->request_size-8], 8)){
310         log_info("ATT Signed Write, invalid signature");
311         att_server->state = ATT_SERVER_IDLE;
312         return;
313     }
314     log_info("ATT Signed Write, valid signature");
315 
316     // update sequence number
317     uint32_t counter_packet = little_endian_read_32(att_server->request_buffer, att_server->request_size-12);
318     le_device_db_remote_counter_set(att_server->ir_le_device_db_index, counter_packet+1);
319     att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
320     att_dispatch_server_request_can_send_now_event(att_server->connection.con_handle);
321 }
322 #endif
323 
324 // pre: att_server->state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED
325 // pre: can send now
326 // returns: 1 if packet was sent
327 static int att_server_process_validated_request(att_server_t * att_server){
328 
329     l2cap_reserve_packet_buffer();
330     uint8_t * att_response_buffer = l2cap_get_outgoing_buffer();
331     uint16_t  att_response_size   = att_handle_request(&att_server->connection, att_server->request_buffer, att_server->request_size, att_response_buffer);
332 
333     // intercept "insufficient authorization" for authenticated connections to allow for user authorization
334     if ((att_response_size     >= 4)
335     && (att_response_buffer[0] == ATT_ERROR_RESPONSE)
336     && (att_response_buffer[4] == ATT_ERROR_INSUFFICIENT_AUTHORIZATION)
337     && (att_server->connection.authenticated)){
338 
339         switch (sm_authorization_state(att_server->connection.con_handle)){
340             case AUTHORIZATION_UNKNOWN:
341                 l2cap_release_packet_buffer();
342                 sm_request_pairing(att_server->connection.con_handle);
343                 return 0;
344             case AUTHORIZATION_PENDING:
345                 l2cap_release_packet_buffer();
346                 return 0;
347             default:
348                 break;
349         }
350     }
351 
352     att_server->state = ATT_SERVER_IDLE;
353     if (att_response_size == 0) {
354         l2cap_release_packet_buffer();
355         return 0;
356     }
357 
358     l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, att_response_size);
359 
360     // notify client about MTU exchange result
361     if (att_response_buffer[0] == ATT_EXCHANGE_MTU_RESPONSE){
362         att_emit_mtu_event(att_server->connection.con_handle, att_server->connection.mtu);
363     }
364     return 1;
365 }
366 
367 static void att_run_for_context(att_server_t * att_server){
368     switch (att_server->state){
369         case ATT_SERVER_REQUEST_RECEIVED:
370 
371             // wait until pairing is complete
372             if (att_server->pairing_active) break;
373 
374 #ifdef ENABLE_LE_SIGNED_WRITE
375             if (att_server->request_buffer[0] == ATT_SIGNED_WRITE_COMMAND){
376                 log_info("ATT Signed Write!");
377                 if (!sm_cmac_ready()) {
378                     log_info("ATT Signed Write, sm_cmac engine not ready. Abort");
379                     att_server->state = ATT_SERVER_IDLE;
380                     return;
381                 }
382                 if (att_server->request_size < (3 + 12)) {
383                     log_info("ATT Signed Write, request to short. Abort.");
384                     att_server->state = ATT_SERVER_IDLE;
385                     return;
386                 }
387                 if (att_server->ir_lookup_active){
388                     return;
389                 }
390                 if (att_server->ir_le_device_db_index < 0){
391                     log_info("ATT Signed Write, CSRK not available");
392                     att_server->state = ATT_SERVER_IDLE;
393                     return;
394                 }
395 
396                 // check counter
397                 uint32_t counter_packet = little_endian_read_32(att_server->request_buffer, att_server->request_size-12);
398                 uint32_t counter_db     = le_device_db_remote_counter_get(att_server->ir_le_device_db_index);
399                 log_info("ATT Signed Write, DB counter %"PRIu32", packet counter %"PRIu32, counter_db, counter_packet);
400                 if (counter_packet < counter_db){
401                     log_info("ATT Signed Write, db reports higher counter, abort");
402                     att_server->state = ATT_SERVER_IDLE;
403                     return;
404                 }
405 
406                 // signature is { sequence counter, secure hash }
407                 sm_key_t csrk;
408                 le_device_db_remote_csrk_get(att_server->ir_le_device_db_index, csrk);
409                 att_server->state = ATT_SERVER_W4_SIGNED_WRITE_VALIDATION;
410                 log_info("Orig Signature: ");
411                 log_info_hexdump( &att_server->request_buffer[att_server->request_size-8], 8);
412                 uint16_t attribute_handle = little_endian_read_16(att_server->request_buffer, 1);
413                 sm_cmac_signed_write_start(csrk, att_server->request_buffer[0], attribute_handle, att_server->request_size - 15, &att_server->request_buffer[3], counter_packet, att_signed_write_handle_cmac_result);
414                 return;
415             }
416 #endif
417             // move on
418             att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED;
419             att_dispatch_server_request_can_send_now_event(att_server->connection.con_handle);
420             break;
421 
422         default:
423             break;
424     }
425 }
426 
427 static void att_server_handle_can_send_now(void){
428 
429     // NOTE: we get l2cap fixed channel instead of con_handle
430 
431     btstack_linked_list_iterator_t it;
432     hci_connections_get_iterator(&it);
433     while(btstack_linked_list_iterator_has_next(&it)){
434         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
435         att_server_t * att_server = &connection->att_server;
436         if (att_server->state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED){
437             int sent = att_server_process_validated_request(att_server);
438             if (sent && (att_client_waiting_for_can_send || !btstack_linked_list_empty(&can_send_now_clients))){
439                 att_dispatch_server_request_can_send_now_event(att_server->connection.con_handle);
440                 return;
441             }
442         }
443     }
444 
445     while (!btstack_linked_list_empty(&can_send_now_clients)){
446         // handle first client
447         btstack_context_callback_registration_t * client = (btstack_context_callback_registration_t*) can_send_now_clients;
448         hci_con_handle_t con_handle = (uintptr_t) client->context;
449         btstack_linked_list_remove(&can_send_now_clients, (btstack_linked_item_t *) client);
450         client->callback(client->context);
451 
452         // request again if needed
453         if (!att_dispatch_server_can_send_now(con_handle)){
454             if (!btstack_linked_list_empty(&can_send_now_clients) || att_client_waiting_for_can_send){
455                 att_dispatch_server_request_can_send_now_event(con_handle);
456             }
457             return;
458         }
459     }
460 
461     if (att_client_waiting_for_can_send){
462         att_client_waiting_for_can_send = 0;
463         att_emit_can_send_now_event();
464     }
465 }
466 
467 static void att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
468 
469     att_server_t * att_server;
470 
471     switch (packet_type){
472 
473         case HCI_EVENT_PACKET:
474             if (packet[0] != L2CAP_EVENT_CAN_SEND_NOW) break;
475             att_server_handle_can_send_now();
476             break;
477 
478         case ATT_DATA_PACKET:
479             log_info("ATT Packet, handle 0x%04x", handle);
480             att_server = att_server_for_handle(handle);
481             if (!att_server) break;
482 
483             // handle value indication confirms
484             if (packet[0] == ATT_HANDLE_VALUE_CONFIRMATION && att_server->value_indication_handle){
485                 btstack_run_loop_remove_timer(&att_server->value_indication_timer);
486                 uint16_t att_handle = att_server->value_indication_handle;
487                 att_server->value_indication_handle = 0;
488                 att_handle_value_indication_notify_client(0, att_server->connection.con_handle, att_handle);
489                 return;
490             }
491 
492             // directly process command
493             // note: signed write cannot be handled directly as authentication needs to be verified
494             if (packet[0] == ATT_WRITE_COMMAND){
495                 att_handle_request(&att_server->connection, packet, size, 0);
496                 return;
497             }
498 
499             // check size
500             if (size > sizeof(att_server->request_buffer)) {
501                 log_info("att_packet_handler: dropping att pdu 0x%02x as size %u > att_server->request_buffer %u", packet[0], size, (int) sizeof(att_server->request_buffer));
502                 return;
503             }
504 
505             // last request still in processing?
506             if (att_server->state != ATT_SERVER_IDLE){
507                 log_info("att_packet_handler: skipping att pdu 0x%02x as server not idle (state %u)", packet[0], att_server->state);
508                 return;
509             }
510 
511             // store request
512             att_server->state = ATT_SERVER_REQUEST_RECEIVED;
513             att_server->request_size = size;
514             memcpy(att_server->request_buffer, packet, size);
515 
516             att_run_for_context(att_server);
517             break;
518     }
519 }
520 
521 // ---------------------
522 // persistent CCC writes
523 // TLV value format: le_device_index(8), attribute_handle(16), value (8)
524 static uint32_t att_server_persistent_ccc_tag_for_index(uint8_t index){
525     return 'B' << 24 | 'T' << 16 | 'C' << 8 | index;
526 }
527 
528 static void att_server_persistent_ccc_write(hci_con_handle_t con_handle, uint16_t att_handle, uint16_t value){
529     // lookup att_server instance
530     att_server_t * att_server = att_server_for_handle(con_handle);
531     if (!att_server) return;
532     int le_device_index = att_server->ir_le_device_db_index;
533     log_info("Store CCC value 0x%04x for handle 0x%04x of remote %s, le device id %d", value, att_handle, bd_addr_to_str(att_server->peer_address), le_device_index);
534     // check if bonded
535     if (le_device_index < 0) return;
536     // get btstack_tlv
537     const btstack_tlv_t * tlv_impl = NULL;
538     void * tlv_context;
539     btstack_tlv_get_instance(&tlv_impl, &tlv_context);
540     if (!tlv_impl) return;
541     // update ccc tag
542     int index;
543     uint8_t buffer[4];
544     int free_index = -1;
545     for (index=0;index<GATT_SERVER_NUM_PERSISTENT_CCC;index++){
546         uint32_t tag = att_server_persistent_ccc_tag_for_index(index);
547         int len = tlv_impl->get_tag(tlv_context, tag, buffer, sizeof(buffer));
548         if (len == 0){
549             free_index = index;
550             continue;
551         }
552         if (len != sizeof(buffer)) continue;
553         if (buffer[0] != le_device_index) continue;
554         if (little_endian_read_16(buffer, 1) != att_handle) continue;
555         if (value){
556             // update
557             if (buffer[3] == value) {
558                 log_info("CCC Index %u: Up-to-date", index);
559                 return;
560             }
561             buffer[3] = value;
562             log_info("CCC Index %u: Store", index);
563             tlv_impl->store_tag(tlv_context, tag, buffer, sizeof(buffer));
564         } else {
565             // delete
566             log_info("CCC Index %u: Delete", index);
567             tlv_impl->delete_tag(tlv_context, tag);
568         }
569         return;
570     }
571     if (free_index < 0) return;
572     // store ccc tag
573     buffer[0] = le_device_index;
574     little_endian_store_16(buffer, 1, att_handle);
575     buffer[3] = value;
576     uint32_t tag = att_server_persistent_ccc_tag_for_index(free_index);
577     tlv_impl->store_tag(tlv_context, tag, buffer, sizeof(buffer));
578 }
579 
580 static void att_server_persistent_ccc_clear(att_server_t * att_server){
581     if (!att_server) return;
582     int le_device_index = att_server->ir_le_device_db_index;
583     log_info("Clear CCC values of remote %s, le device id %d", bd_addr_to_str(att_server->peer_address), le_device_index);
584     // check if bonded
585     if (le_device_index < 0) return;
586     // get btstack_tlv
587     const btstack_tlv_t * tlv_impl = NULL;
588     void * tlv_context;
589     btstack_tlv_get_instance(&tlv_impl, &tlv_context);
590     if (!tlv_impl) return;
591     // get all ccc tag
592     int index;
593     uint8_t buffer[4];
594     for (index=0;index<GATT_SERVER_NUM_PERSISTENT_CCC;index++){
595         uint32_t tag = att_server_persistent_ccc_tag_for_index(index);
596         int len = tlv_impl->get_tag(tlv_context, tag, buffer, sizeof(buffer));
597         if (len != sizeof(buffer)) continue;
598         if (buffer[0] != le_device_index) continue;
599         // delete entry
600         log_info("CCC Index %u: Delete", index);
601         tlv_impl->delete_tag(tlv_context, tag);
602     }
603 }
604 
605 static void att_server_persistent_ccc_restore(att_server_t * att_server){
606     if (!att_server) return;
607     int le_device_index = att_server->ir_le_device_db_index;
608     log_info("Restore CCC values of remote %s, le device id %d", bd_addr_to_str(att_server->peer_address), le_device_index);
609     // get btstack_tlv
610     const btstack_tlv_t * tlv_impl = NULL;
611     void * tlv_context;
612     btstack_tlv_get_instance(&tlv_impl, &tlv_context);
613     if (!tlv_impl) return;
614     // get all ccc tag
615     int index;
616     uint8_t buffer[4];
617     for (index=0;index<GATT_SERVER_NUM_PERSISTENT_CCC;index++){
618         uint32_t tag = att_server_persistent_ccc_tag_for_index(index);
619         int len = tlv_impl->get_tag(tlv_context, tag, buffer, sizeof(buffer));
620         if (len != sizeof(buffer)) continue;
621         if (buffer[0] != le_device_index) continue;
622         // simulate write callback
623         uint16_t attribute_handle = little_endian_read_16(buffer, 1);
624         uint8_t  value[2];
625         little_endian_store_16(value, 0, buffer[3]);
626         att_write_callback_t callback = att_server_write_callback_for_handle(attribute_handle);
627         if (!callback) continue;
628         log_info("CCC Index %u: Set Attribute handle 0x%04x to value 0x%04x", index, attribute_handle, buffer[3]);
629         (*callback)(att_server->connection.con_handle, attribute_handle, ATT_TRANSACTION_MODE_NONE, 0, value, sizeof(value));
630     }
631 }
632 
633 // persistent CCC writes
634 // ---------------------
635 
636 // gatt service management
637 static att_service_handler_t * att_service_handler_for_handle(uint16_t handle){
638     btstack_linked_list_iterator_t it;
639     btstack_linked_list_iterator_init(&it, &service_handlers);
640     while (btstack_linked_list_iterator_has_next(&it)){
641         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
642         if (handler->start_handle > handle) continue;
643         if (handler->end_handle   < handle) continue;
644         return handler;
645     }
646     return NULL;
647 }
648 static att_read_callback_t att_server_read_callback_for_handle(uint16_t handle){
649     att_service_handler_t * handler = att_service_handler_for_handle(handle);
650     if (handler) return handler->read_callback;
651     return att_server_client_read_callback;
652 }
653 
654 static att_write_callback_t att_server_write_callback_for_handle(uint16_t handle){
655     att_service_handler_t * handler = att_service_handler_for_handle(handle);
656     if (handler) return handler->write_callback;
657     return att_server_client_write_callback;
658 }
659 
660 static void att_notify_write_callbacks(hci_con_handle_t con_handle, uint16_t transaction_mode){
661     // notify all callbacks
662     btstack_linked_list_iterator_t it;
663     btstack_linked_list_iterator_init(&it, &service_handlers);
664     while (btstack_linked_list_iterator_has_next(&it)){
665         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
666         if (!handler->write_callback) continue;
667         (*handler->write_callback)(con_handle, 0, transaction_mode, 0, NULL, 0);
668     }
669     if (!att_server_client_write_callback) return;
670     (*att_server_client_write_callback)(con_handle, 0, transaction_mode, 0, NULL, 0);
671 }
672 
673 // returns first reported error or 0
674 static uint8_t att_validate_prepared_write(hci_con_handle_t con_handle){
675     btstack_linked_list_iterator_t it;
676     btstack_linked_list_iterator_init(&it, &service_handlers);
677     while (btstack_linked_list_iterator_has_next(&it)){
678         att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it);
679         if (!handler->write_callback) continue;
680         uint8_t error_code = (*handler->write_callback)(con_handle, 0, ATT_TRANSACTION_MODE_VALIDATE, 0, NULL, 0);
681         if (error_code) return error_code;
682     }
683     if (!att_server_client_write_callback) return 0;
684     return (*att_server_client_write_callback)(con_handle, 0, ATT_TRANSACTION_MODE_VALIDATE, 0, NULL, 0);
685 }
686 
687 static uint16_t att_server_read_callback(hci_con_handle_t con_handle, uint16_t attribute_handle, uint16_t offset, uint8_t * buffer, uint16_t buffer_size){
688     att_read_callback_t callback = att_server_read_callback_for_handle(attribute_handle);
689     if (!callback) return 0;
690     return (*callback)(con_handle, attribute_handle, offset, buffer, buffer_size);
691 }
692 
693 static int att_server_write_callback(hci_con_handle_t con_handle, uint16_t attribute_handle, uint16_t transaction_mode, uint16_t offset, uint8_t *buffer, uint16_t buffer_size){
694     switch (transaction_mode){
695         case ATT_TRANSACTION_MODE_VALIDATE:
696             return att_validate_prepared_write(con_handle);
697         case ATT_TRANSACTION_MODE_EXECUTE:
698         case ATT_TRANSACTION_MODE_CANCEL:
699             att_notify_write_callbacks(con_handle, transaction_mode);
700             return 0;
701         default:
702             break;
703     }
704 
705     // track CCC writes
706     if (att_is_persistent_ccc(attribute_handle) && offset == 0 && buffer_size == 2){
707         att_server_persistent_ccc_write(con_handle, attribute_handle, little_endian_read_16(buffer, 0));
708     }
709 
710     att_write_callback_t callback = att_server_write_callback_for_handle(attribute_handle);
711     if (!callback) return 0;
712     return (*callback)(con_handle, attribute_handle, transaction_mode, offset, buffer, buffer_size);
713 }
714 
715 /**
716  * @brief register read/write callbacks for specific handle range
717  * @param att_service_handler_t
718  */
719 void att_server_register_service_handler(att_service_handler_t * handler){
720     if (att_service_handler_for_handle(handler->start_handle) ||
721         att_service_handler_for_handle(handler->end_handle)){
722         log_error("handler for range 0x%04x-0x%04x already registered", handler->start_handle, handler->end_handle);
723         return;
724     }
725     btstack_linked_list_add(&service_handlers, (btstack_linked_item_t*) handler);
726 }
727 
728 void att_server_init(uint8_t const * db, att_read_callback_t read_callback, att_write_callback_t write_callback){
729 
730     // store callbacks
731     att_server_client_read_callback  = read_callback;
732     att_server_client_write_callback = write_callback;
733 
734     // register for HCI Events
735     hci_event_callback_registration.callback = &att_event_packet_handler;
736     hci_add_event_handler(&hci_event_callback_registration);
737 
738     // register for SM events
739     sm_event_callback_registration.callback = &att_event_packet_handler;
740     sm_add_event_handler(&sm_event_callback_registration);
741 
742     // and L2CAP ATT Server PDUs
743     att_dispatch_register_server(att_packet_handler);
744 
745     att_set_db(db);
746     att_set_read_callback(att_server_read_callback);
747     att_set_write_callback(att_server_write_callback);
748 
749 }
750 
751 void att_server_register_packet_handler(btstack_packet_handler_t handler){
752     att_client_packet_handler = handler;
753 }
754 
755 int  att_server_can_send_packet_now(hci_con_handle_t con_handle){
756 	return att_dispatch_server_can_send_now(con_handle);
757 }
758 
759 void att_server_request_can_send_now_event(hci_con_handle_t con_handle){
760     log_debug("att_server_request_can_send_now_event 0x%04x", con_handle);
761     att_client_waiting_for_can_send = 1;
762     att_dispatch_server_request_can_send_now_event(con_handle);
763 }
764 
765 void att_server_register_can_send_now_callback(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
766     // check if can send already
767     if (att_dispatch_server_can_send_now(con_handle)){
768         callback_registration->callback(callback_registration->context);
769         return;
770     }
771     callback_registration->context = (void*)(uintptr_t) con_handle;
772     btstack_linked_list_add_tail(&can_send_now_clients, (btstack_linked_item_t*) callback_registration);
773     att_dispatch_server_request_can_send_now_event(con_handle);
774 }
775 
776 
777 int att_server_notify(hci_con_handle_t con_handle, uint16_t attribute_handle, uint8_t *value, uint16_t value_len){
778     att_server_t * att_server = att_server_for_handle(con_handle);
779     if (!att_server) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
780 
781     if (!att_dispatch_server_can_send_now(con_handle)) return BTSTACK_ACL_BUFFERS_FULL;
782 
783     l2cap_reserve_packet_buffer();
784     uint8_t * packet_buffer = l2cap_get_outgoing_buffer();
785     uint16_t size = att_prepare_handle_value_notification(&att_server->connection, attribute_handle, value, value_len, packet_buffer);
786 	return l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size);
787 }
788 
789 int att_server_indicate(hci_con_handle_t con_handle, uint16_t attribute_handle, uint8_t *value, uint16_t value_len){
790     att_server_t * att_server = att_server_for_handle(con_handle);
791     if (!att_server) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
792 
793     if (att_server->value_indication_handle) return ATT_HANDLE_VALUE_INDICATION_IN_PROGRESS;
794     if (!att_dispatch_server_can_send_now(con_handle)) return BTSTACK_ACL_BUFFERS_FULL;
795 
796     // track indication
797     att_server->value_indication_handle = attribute_handle;
798     btstack_run_loop_set_timer_handler(&att_server->value_indication_timer, att_handle_value_indication_timeout);
799     btstack_run_loop_set_timer(&att_server->value_indication_timer, ATT_TRANSACTION_TIMEOUT_MS);
800     btstack_run_loop_add_timer(&att_server->value_indication_timer);
801 
802     l2cap_reserve_packet_buffer();
803     uint8_t * packet_buffer = l2cap_get_outgoing_buffer();
804     uint16_t size = att_prepare_handle_value_indication(&att_server->connection, attribute_handle, value, value_len, packet_buffer);
805 	l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size);
806     return 0;
807 }
808