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