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 #ifdef ENABLE_ATT_DELAYED_READ_RESPONSE 344 if (att_response_size == ATT_READ_RESPONSE_PENDING){ 345 // update state 346 att_server->state = ATT_SERVER_READ_RESPONSE_PENDING; 347 348 // callback with handle ATT_READ_RESPONSE_PENDING 349 att_server_client_read_callback(att_server->connection.con_handle, ATT_READ_RESPONSE_PENDING, 0, NULL, 0); 350 351 // free reserved buffer 352 l2cap_release_packet_buffer(); 353 return 0; 354 } 355 #endif 356 357 // intercept "insufficient authorization" for authenticated connections to allow for user authorization 358 if ((att_response_size >= 4) 359 && (att_response_buffer[0] == ATT_ERROR_RESPONSE) 360 && (att_response_buffer[4] == ATT_ERROR_INSUFFICIENT_AUTHORIZATION) 361 && (att_server->connection.authenticated)){ 362 363 switch (gap_authorization_state(att_server->connection.con_handle)){ 364 case AUTHORIZATION_UNKNOWN: 365 l2cap_release_packet_buffer(); 366 sm_request_pairing(att_server->connection.con_handle); 367 return 0; 368 case AUTHORIZATION_PENDING: 369 l2cap_release_packet_buffer(); 370 return 0; 371 default: 372 break; 373 } 374 } 375 376 att_server->state = ATT_SERVER_IDLE; 377 if (att_response_size == 0) { 378 l2cap_release_packet_buffer(); 379 return 0; 380 } 381 382 l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, att_response_size); 383 384 // notify client about MTU exchange result 385 if (att_response_buffer[0] == ATT_EXCHANGE_MTU_RESPONSE){ 386 att_emit_mtu_event(att_server->connection.con_handle, att_server->connection.mtu); 387 } 388 return 1; 389 } 390 391 #ifdef ENABLE_ATT_DELAYED_READ_RESPONSE 392 int att_server_read_response_ready(hci_con_handle_t con_handle){ 393 att_server_t * att_server = att_server_for_handle(con_handle); 394 if (!att_server) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 395 if (att_server->state != ATT_SERVER_READ_RESPONSE_PENDING) return ERROR_CODE_COMMAND_DISALLOWED; 396 397 att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED; 398 att_dispatch_server_request_can_send_now_event(con_handle); 399 return ERROR_CODE_SUCCESS; 400 } 401 #endif 402 403 static void att_run_for_context(att_server_t * att_server){ 404 switch (att_server->state){ 405 case ATT_SERVER_REQUEST_RECEIVED: 406 407 // wait until pairing is complete 408 if (att_server->pairing_active) break; 409 410 #ifdef ENABLE_LE_SIGNED_WRITE 411 if (att_server->request_buffer[0] == ATT_SIGNED_WRITE_COMMAND){ 412 log_info("ATT Signed Write!"); 413 if (!sm_cmac_ready()) { 414 log_info("ATT Signed Write, sm_cmac engine not ready. Abort"); 415 att_server->state = ATT_SERVER_IDLE; 416 return; 417 } 418 if (att_server->request_size < (3 + 12)) { 419 log_info("ATT Signed Write, request to short. Abort."); 420 att_server->state = ATT_SERVER_IDLE; 421 return; 422 } 423 if (att_server->ir_lookup_active){ 424 return; 425 } 426 if (att_server->ir_le_device_db_index < 0){ 427 log_info("ATT Signed Write, CSRK not available"); 428 att_server->state = ATT_SERVER_IDLE; 429 return; 430 } 431 432 // check counter 433 uint32_t counter_packet = little_endian_read_32(att_server->request_buffer, att_server->request_size-12); 434 uint32_t counter_db = le_device_db_remote_counter_get(att_server->ir_le_device_db_index); 435 log_info("ATT Signed Write, DB counter %"PRIu32", packet counter %"PRIu32, counter_db, counter_packet); 436 if (counter_packet < counter_db){ 437 log_info("ATT Signed Write, db reports higher counter, abort"); 438 att_server->state = ATT_SERVER_IDLE; 439 return; 440 } 441 442 // signature is { sequence counter, secure hash } 443 sm_key_t csrk; 444 le_device_db_remote_csrk_get(att_server->ir_le_device_db_index, csrk); 445 att_server->state = ATT_SERVER_W4_SIGNED_WRITE_VALIDATION; 446 log_info("Orig Signature: "); 447 log_info_hexdump( &att_server->request_buffer[att_server->request_size-8], 8); 448 uint16_t attribute_handle = little_endian_read_16(att_server->request_buffer, 1); 449 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); 450 return; 451 } 452 #endif 453 // move on 454 att_server->state = ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED; 455 att_dispatch_server_request_can_send_now_event(att_server->connection.con_handle); 456 break; 457 458 default: 459 break; 460 } 461 } 462 463 static void att_server_handle_can_send_now(void){ 464 465 // NOTE: we get l2cap fixed channel instead of con_handle 466 467 btstack_linked_list_iterator_t it; 468 hci_connections_get_iterator(&it); 469 while(btstack_linked_list_iterator_has_next(&it)){ 470 hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it); 471 att_server_t * att_server = &connection->att_server; 472 if (att_server->state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED){ 473 int sent = att_server_process_validated_request(att_server); 474 if (sent && (att_client_waiting_for_can_send || !btstack_linked_list_empty(&can_send_now_clients))){ 475 att_dispatch_server_request_can_send_now_event(att_server->connection.con_handle); 476 return; 477 } 478 } 479 } 480 481 while (!btstack_linked_list_empty(&can_send_now_clients)){ 482 // handle first client 483 btstack_context_callback_registration_t * client = (btstack_context_callback_registration_t*) can_send_now_clients; 484 hci_con_handle_t con_handle = (uintptr_t) client->context; 485 btstack_linked_list_remove(&can_send_now_clients, (btstack_linked_item_t *) client); 486 client->callback(client->context); 487 488 // request again if needed 489 if (!att_dispatch_server_can_send_now(con_handle)){ 490 if (!btstack_linked_list_empty(&can_send_now_clients) || att_client_waiting_for_can_send){ 491 att_dispatch_server_request_can_send_now_event(con_handle); 492 } 493 return; 494 } 495 } 496 497 if (att_client_waiting_for_can_send){ 498 att_client_waiting_for_can_send = 0; 499 att_emit_can_send_now_event(); 500 } 501 } 502 503 static void att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){ 504 505 att_server_t * att_server; 506 507 switch (packet_type){ 508 509 case HCI_EVENT_PACKET: 510 switch (packet[0]){ 511 case L2CAP_EVENT_CAN_SEND_NOW: 512 att_server_handle_can_send_now(); 513 break; 514 case ATT_EVENT_MTU_EXCHANGE_COMPLETE: 515 // GATT client has negotiated the mtu for this connection 516 att_server = att_server_for_handle(handle); 517 if (!att_server) break; 518 att_server->connection.mtu = little_endian_read_16(packet, 4); 519 break; 520 default: 521 break; 522 } 523 break; 524 525 case ATT_DATA_PACKET: 526 log_debug("ATT Packet, handle 0x%04x", handle); 527 att_server = att_server_for_handle(handle); 528 if (!att_server) break; 529 530 // handle value indication confirms 531 if (packet[0] == ATT_HANDLE_VALUE_CONFIRMATION && att_server->value_indication_handle){ 532 btstack_run_loop_remove_timer(&att_server->value_indication_timer); 533 uint16_t att_handle = att_server->value_indication_handle; 534 att_server->value_indication_handle = 0; 535 att_handle_value_indication_notify_client(0, att_server->connection.con_handle, att_handle); 536 return; 537 } 538 539 // directly process command 540 // note: signed write cannot be handled directly as authentication needs to be verified 541 if (packet[0] == ATT_WRITE_COMMAND){ 542 att_handle_request(&att_server->connection, packet, size, 0); 543 return; 544 } 545 546 // check size 547 if (size > sizeof(att_server->request_buffer)) { 548 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)); 549 return; 550 } 551 552 // last request still in processing? 553 if (att_server->state != ATT_SERVER_IDLE){ 554 log_info("att_packet_handler: skipping att pdu 0x%02x as server not idle (state %u)", packet[0], att_server->state); 555 return; 556 } 557 558 // store request 559 att_server->state = ATT_SERVER_REQUEST_RECEIVED; 560 att_server->request_size = size; 561 memcpy(att_server->request_buffer, packet, size); 562 563 att_run_for_context(att_server); 564 break; 565 } 566 } 567 568 // --------------------- 569 // persistent CCC writes 570 static uint32_t att_server_persistent_ccc_tag_for_index(uint8_t index){ 571 return 'B' << 24 | 'T' << 16 | 'C' << 8 | index; 572 } 573 574 static void att_server_persistent_ccc_write(hci_con_handle_t con_handle, uint16_t att_handle, uint16_t value){ 575 // lookup att_server instance 576 att_server_t * att_server = att_server_for_handle(con_handle); 577 if (!att_server) return; 578 int le_device_index = att_server->ir_le_device_db_index; 579 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); 580 581 // check if bonded 582 if (le_device_index < 0) return; 583 584 // get btstack_tlv 585 const btstack_tlv_t * tlv_impl = NULL; 586 void * tlv_context; 587 btstack_tlv_get_instance(&tlv_impl, &tlv_context); 588 if (!tlv_impl) return; 589 590 // update ccc tag 591 int index; 592 uint32_t highest_seq_nr = 0; 593 uint32_t lowest_seq_nr = 0; 594 uint32_t tag_for_lowest_seq_nr = 0; 595 uint32_t tag_for_empty = 0; 596 persistent_ccc_entry_t entry; 597 for (index=0;index<NVN_NUM_GATT_SERVER_CCC;index++){ 598 uint32_t tag = att_server_persistent_ccc_tag_for_index(index); 599 int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t)); 600 601 // empty/invalid tag 602 if (len != sizeof(persistent_ccc_entry_t)){ 603 tag_for_empty = tag; 604 continue; 605 } 606 // update highest seq nr 607 if (entry.seq_nr > highest_seq_nr){ 608 highest_seq_nr = entry.seq_nr; 609 } 610 // find entry with lowest seq nr 611 if ((tag_for_lowest_seq_nr == 0) || (entry.seq_nr < lowest_seq_nr)){ 612 tag_for_lowest_seq_nr = tag; 613 lowest_seq_nr = entry.seq_nr; 614 } 615 616 if (entry.device_index != le_device_index) continue; 617 if (entry.att_handle != att_handle) continue; 618 619 // found matching entry 620 if (value){ 621 // update 622 if (entry.value == value) { 623 log_info("CCC Index %u: Up-to-date", index); 624 return; 625 } 626 entry.value = value; 627 entry.seq_nr = highest_seq_nr + 1; 628 log_info("CCC Index %u: Store", index); 629 tlv_impl->store_tag(tlv_context, tag, (const uint8_t *) &entry, sizeof(persistent_ccc_entry_t)); 630 } else { 631 // delete 632 log_info("CCC Index %u: Delete", index); 633 tlv_impl->delete_tag(tlv_context, tag); 634 } 635 return; 636 } 637 638 log_info("tag_for_empy %"PRIx32", tag_for_lowest_seq_nr %"PRIx32, tag_for_empty, tag_for_lowest_seq_nr); 639 640 if (value == 0){ 641 // done 642 return; 643 } 644 645 uint32_t tag_to_use = 0; 646 if (tag_for_empty){ 647 tag_to_use = tag_for_empty; 648 } else if (tag_for_lowest_seq_nr){ 649 tag_to_use = tag_for_lowest_seq_nr; 650 } else { 651 // should not happen 652 return; 653 } 654 // store ccc tag 655 entry.seq_nr = highest_seq_nr + 1; 656 entry.device_index = le_device_index; 657 entry.att_handle = att_handle; 658 entry.value = value; 659 tlv_impl->store_tag(tlv_context, tag_to_use, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t)); 660 } 661 662 static void att_server_persistent_ccc_clear(att_server_t * att_server){ 663 if (!att_server) return; 664 int le_device_index = att_server->ir_le_device_db_index; 665 log_info("Clear CCC values of remote %s, le device id %d", bd_addr_to_str(att_server->peer_address), le_device_index); 666 // check if bonded 667 if (le_device_index < 0) return; 668 // get btstack_tlv 669 const btstack_tlv_t * tlv_impl = NULL; 670 void * tlv_context; 671 btstack_tlv_get_instance(&tlv_impl, &tlv_context); 672 if (!tlv_impl) return; 673 // get all ccc tag 674 int index; 675 persistent_ccc_entry_t entry; 676 for (index=0;index<NVN_NUM_GATT_SERVER_CCC;index++){ 677 uint32_t tag = att_server_persistent_ccc_tag_for_index(index); 678 int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t)); 679 if (len != sizeof(persistent_ccc_entry_t)) continue; 680 if (entry.device_index != le_device_index) continue; 681 // delete entry 682 log_info("CCC Index %u: Delete", index); 683 tlv_impl->delete_tag(tlv_context, tag); 684 } 685 } 686 687 static void att_server_persistent_ccc_restore(att_server_t * att_server){ 688 if (!att_server) return; 689 int le_device_index = att_server->ir_le_device_db_index; 690 log_info("Restore CCC values of remote %s, le device id %d", bd_addr_to_str(att_server->peer_address), le_device_index); 691 // get btstack_tlv 692 const btstack_tlv_t * tlv_impl = NULL; 693 void * tlv_context; 694 btstack_tlv_get_instance(&tlv_impl, &tlv_context); 695 if (!tlv_impl) return; 696 // get all ccc tag 697 int index; 698 persistent_ccc_entry_t entry; 699 for (index=0;index<NVN_NUM_GATT_SERVER_CCC;index++){ 700 uint32_t tag = att_server_persistent_ccc_tag_for_index(index); 701 int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t)); 702 if (len != sizeof(persistent_ccc_entry_t)) continue; 703 if (entry.device_index != le_device_index) continue; 704 // simulate write callback 705 uint16_t attribute_handle = entry.att_handle; 706 uint8_t value[2]; 707 little_endian_store_16(value, 0, entry.value); 708 att_write_callback_t callback = att_server_write_callback_for_handle(attribute_handle); 709 if (!callback) continue; 710 log_info("CCC Index %u: Set Attribute handle 0x%04x to value 0x%04x", index, attribute_handle, entry.value ); 711 (*callback)(att_server->connection.con_handle, attribute_handle, ATT_TRANSACTION_MODE_NONE, 0, value, sizeof(value)); 712 } 713 } 714 715 // persistent CCC writes 716 // --------------------- 717 718 // gatt service management 719 static att_service_handler_t * att_service_handler_for_handle(uint16_t handle){ 720 btstack_linked_list_iterator_t it; 721 btstack_linked_list_iterator_init(&it, &service_handlers); 722 while (btstack_linked_list_iterator_has_next(&it)){ 723 att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it); 724 if (handler->start_handle > handle) continue; 725 if (handler->end_handle < handle) continue; 726 return handler; 727 } 728 return NULL; 729 } 730 static att_read_callback_t att_server_read_callback_for_handle(uint16_t handle){ 731 att_service_handler_t * handler = att_service_handler_for_handle(handle); 732 if (handler) return handler->read_callback; 733 return att_server_client_read_callback; 734 } 735 736 static att_write_callback_t att_server_write_callback_for_handle(uint16_t handle){ 737 att_service_handler_t * handler = att_service_handler_for_handle(handle); 738 if (handler) return handler->write_callback; 739 return att_server_client_write_callback; 740 } 741 742 static void att_notify_write_callbacks(hci_con_handle_t con_handle, uint16_t transaction_mode){ 743 // notify all callbacks 744 btstack_linked_list_iterator_t it; 745 btstack_linked_list_iterator_init(&it, &service_handlers); 746 while (btstack_linked_list_iterator_has_next(&it)){ 747 att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it); 748 if (!handler->write_callback) continue; 749 (*handler->write_callback)(con_handle, 0, transaction_mode, 0, NULL, 0); 750 } 751 if (!att_server_client_write_callback) return; 752 (*att_server_client_write_callback)(con_handle, 0, transaction_mode, 0, NULL, 0); 753 } 754 755 // returns first reported error or 0 756 static uint8_t att_validate_prepared_write(hci_con_handle_t con_handle){ 757 btstack_linked_list_iterator_t it; 758 btstack_linked_list_iterator_init(&it, &service_handlers); 759 while (btstack_linked_list_iterator_has_next(&it)){ 760 att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it); 761 if (!handler->write_callback) continue; 762 uint8_t error_code = (*handler->write_callback)(con_handle, 0, ATT_TRANSACTION_MODE_VALIDATE, 0, NULL, 0); 763 if (error_code) return error_code; 764 } 765 if (!att_server_client_write_callback) return 0; 766 return (*att_server_client_write_callback)(con_handle, 0, ATT_TRANSACTION_MODE_VALIDATE, 0, NULL, 0); 767 } 768 769 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){ 770 att_read_callback_t callback = att_server_read_callback_for_handle(attribute_handle); 771 if (!callback) return 0; 772 return (*callback)(con_handle, attribute_handle, offset, buffer, buffer_size); 773 } 774 775 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){ 776 switch (transaction_mode){ 777 case ATT_TRANSACTION_MODE_VALIDATE: 778 return att_validate_prepared_write(con_handle); 779 case ATT_TRANSACTION_MODE_EXECUTE: 780 case ATT_TRANSACTION_MODE_CANCEL: 781 att_notify_write_callbacks(con_handle, transaction_mode); 782 return 0; 783 default: 784 break; 785 } 786 787 // track CCC writes 788 if (att_is_persistent_ccc(attribute_handle) && offset == 0 && buffer_size == 2){ 789 att_server_persistent_ccc_write(con_handle, attribute_handle, little_endian_read_16(buffer, 0)); 790 } 791 792 att_write_callback_t callback = att_server_write_callback_for_handle(attribute_handle); 793 if (!callback) return 0; 794 return (*callback)(con_handle, attribute_handle, transaction_mode, offset, buffer, buffer_size); 795 } 796 797 /** 798 * @brief register read/write callbacks for specific handle range 799 * @param att_service_handler_t 800 */ 801 void att_server_register_service_handler(att_service_handler_t * handler){ 802 if (att_service_handler_for_handle(handler->start_handle) || 803 att_service_handler_for_handle(handler->end_handle)){ 804 log_error("handler for range 0x%04x-0x%04x already registered", handler->start_handle, handler->end_handle); 805 return; 806 } 807 btstack_linked_list_add(&service_handlers, (btstack_linked_item_t*) handler); 808 } 809 810 void att_server_init(uint8_t const * db, att_read_callback_t read_callback, att_write_callback_t write_callback){ 811 812 // store callbacks 813 att_server_client_read_callback = read_callback; 814 att_server_client_write_callback = write_callback; 815 816 // register for HCI Events 817 hci_event_callback_registration.callback = &att_event_packet_handler; 818 hci_add_event_handler(&hci_event_callback_registration); 819 820 // register for SM events 821 sm_event_callback_registration.callback = &att_event_packet_handler; 822 sm_add_event_handler(&sm_event_callback_registration); 823 824 // and L2CAP ATT Server PDUs 825 att_dispatch_register_server(att_packet_handler); 826 827 att_set_db(db); 828 att_set_read_callback(att_server_read_callback); 829 att_set_write_callback(att_server_write_callback); 830 831 } 832 833 void att_server_register_packet_handler(btstack_packet_handler_t handler){ 834 att_client_packet_handler = handler; 835 } 836 837 int att_server_can_send_packet_now(hci_con_handle_t con_handle){ 838 return att_dispatch_server_can_send_now(con_handle); 839 } 840 841 void att_server_request_can_send_now_event(hci_con_handle_t con_handle){ 842 log_debug("att_server_request_can_send_now_event 0x%04x", con_handle); 843 att_client_waiting_for_can_send = 1; 844 att_dispatch_server_request_can_send_now_event(con_handle); 845 } 846 847 void att_server_register_can_send_now_callback(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){ 848 // check if can send already 849 if (att_dispatch_server_can_send_now(con_handle)){ 850 callback_registration->callback(callback_registration->context); 851 return; 852 } 853 callback_registration->context = (void*)(uintptr_t) con_handle; 854 btstack_linked_list_add_tail(&can_send_now_clients, (btstack_linked_item_t*) callback_registration); 855 att_dispatch_server_request_can_send_now_event(con_handle); 856 } 857 858 int att_server_notify(hci_con_handle_t con_handle, uint16_t attribute_handle, uint8_t *value, uint16_t value_len){ 859 att_server_t * att_server = att_server_for_handle(con_handle); 860 if (!att_server) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 861 862 if (!att_dispatch_server_can_send_now(con_handle)) return BTSTACK_ACL_BUFFERS_FULL; 863 864 l2cap_reserve_packet_buffer(); 865 uint8_t * packet_buffer = l2cap_get_outgoing_buffer(); 866 uint16_t size = att_prepare_handle_value_notification(&att_server->connection, attribute_handle, value, value_len, packet_buffer); 867 return l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size); 868 } 869 870 int att_server_indicate(hci_con_handle_t con_handle, uint16_t attribute_handle, uint8_t *value, uint16_t value_len){ 871 att_server_t * att_server = att_server_for_handle(con_handle); 872 if (!att_server) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 873 874 if (att_server->value_indication_handle) return ATT_HANDLE_VALUE_INDICATION_IN_PROGRESS; 875 if (!att_dispatch_server_can_send_now(con_handle)) return BTSTACK_ACL_BUFFERS_FULL; 876 877 // track indication 878 att_server->value_indication_handle = attribute_handle; 879 btstack_run_loop_set_timer_handler(&att_server->value_indication_timer, att_handle_value_indication_timeout); 880 btstack_run_loop_set_timer(&att_server->value_indication_timer, ATT_TRANSACTION_TIMEOUT_MS); 881 btstack_run_loop_add_timer(&att_server->value_indication_timer); 882 883 l2cap_reserve_packet_buffer(); 884 uint8_t * packet_buffer = l2cap_get_outgoing_buffer(); 885 uint16_t size = att_prepare_handle_value_indication(&att_server->connection, attribute_handle, value, value_len, packet_buffer); 886 l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size); 887 return 0; 888 } 889