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