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