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 service_handlers; 94 static btstack_context_callback_registration_t att_client_waiting_for_can_send_registration; 95 96 static att_read_callback_t att_server_client_read_callback; 97 static att_write_callback_t att_server_client_write_callback; 98 99 // track CCC 1-entry cache 100 // static att_server_t * att_persistent_ccc_server; 101 // static hci_con_handle_t att_persistent_ccc_con_handle; 102 103 static att_server_t * att_server_for_handle(hci_con_handle_t con_handle){ 104 hci_connection_t * hci_connection = hci_connection_for_handle(con_handle); 105 if (!hci_connection) return NULL; 106 return &hci_connection->att_server; 107 } 108 109 #ifdef ENABLE_LE_SIGNED_WRITE 110 static att_server_t * att_server_for_state(att_server_state_t state){ 111 btstack_linked_list_iterator_t it; 112 hci_connections_get_iterator(&it); 113 while(btstack_linked_list_iterator_has_next(&it)){ 114 hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it); 115 att_server_t * att_server = &connection->att_server; 116 if (att_server->state == state) return att_server; 117 } 118 return NULL; 119 } 120 #endif 121 122 static void att_handle_value_indication_notify_client(uint8_t status, uint16_t client_handle, uint16_t attribute_handle){ 123 if (!att_client_packet_handler) return; 124 125 uint8_t event[7]; 126 int pos = 0; 127 event[pos++] = ATT_EVENT_HANDLE_VALUE_INDICATION_COMPLETE; 128 event[pos++] = sizeof(event) - 2; 129 event[pos++] = status; 130 little_endian_store_16(event, pos, client_handle); 131 pos += 2; 132 little_endian_store_16(event, pos, attribute_handle); 133 (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event)); 134 } 135 136 static void att_emit_mtu_event(hci_con_handle_t con_handle, uint16_t mtu){ 137 if (!att_client_packet_handler) return; 138 139 uint8_t event[6]; 140 int pos = 0; 141 event[pos++] = ATT_EVENT_MTU_EXCHANGE_COMPLETE; 142 event[pos++] = sizeof(event) - 2; 143 little_endian_store_16(event, pos, con_handle); 144 pos += 2; 145 little_endian_store_16(event, pos, mtu); 146 att_dispatch_server_mtu_exchanged(con_handle, mtu); 147 (*att_client_packet_handler)(HCI_EVENT_PACKET, 0, &event[0], sizeof(event)); 148 } 149 150 static void att_emit_can_send_now_event(void * context){ 151 UNUSED(context); 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 int can_send_now = 1; 481 482 // process all server requests 483 btstack_linked_list_iterator_t it; 484 hci_connections_get_iterator(&it); 485 while(btstack_linked_list_iterator_has_next(&it)){ 486 hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it); 487 att_server_t * att_server = &connection->att_server; 488 if (att_server->state == ATT_SERVER_REQUEST_RECEIVED_AND_VALIDATED){ 489 if (can_send_now){ 490 att_server_process_validated_request(att_server); 491 can_send_now = att_dispatch_server_can_send_now(att_server->connection.con_handle); 492 } else { 493 // can_send_now == 0 494 att_dispatch_server_request_can_send_now_event(att_server->connection.con_handle); 495 return; 496 } 497 } 498 } 499 500 hci_con_handle_t request_con_handle = HCI_CON_HANDLE_INVALID; 501 while (1){ 502 hci_connections_get_iterator(&it); 503 while(btstack_linked_list_iterator_has_next(&it)){ 504 hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it); 505 att_server_t * att_server = &connection->att_server; 506 507 // handle indications first 508 if (!btstack_linked_list_empty(&att_server->indication_requests) && att_server->value_indication_handle == 0){ 509 if (can_send_now){ 510 btstack_context_callback_registration_t * client = (btstack_context_callback_registration_t*) att_server->indication_requests; 511 btstack_linked_list_remove(&att_server->indication_requests, (btstack_linked_item_t *) client); 512 client->callback(client->context); 513 can_send_now = att_dispatch_server_can_send_now(att_server->connection.con_handle); 514 // track if there's more to send, but keep iterating - only true if callee didn't send indication 515 if (request_con_handle == HCI_CON_HANDLE_INVALID && att_server->value_indication_handle == 0 && !btstack_linked_list_empty(&att_server->indication_requests)){ 516 request_con_handle = att_server->connection.con_handle; 517 } 518 } else { 519 // can_send_now == 0 520 att_dispatch_server_request_can_send_now_event(att_server->connection.con_handle); 521 return; 522 } 523 } 524 525 // then notifications 526 if (!btstack_linked_list_empty(&att_server->notification_requests)){ 527 if (can_send_now){ 528 btstack_context_callback_registration_t * client = (btstack_context_callback_registration_t*) att_server->notification_requests; 529 btstack_linked_list_remove(&att_server->notification_requests, (btstack_linked_item_t *) client); 530 client->callback(client->context); 531 can_send_now = att_dispatch_server_can_send_now(att_server->connection.con_handle); 532 // track if there's more to send, but keep iterating 533 if (request_con_handle == HCI_CON_HANDLE_INVALID && !btstack_linked_list_empty(&att_server->notification_requests)){ 534 request_con_handle = att_server->connection.con_handle; 535 } 536 } else { 537 // can_send_now == 0 538 att_dispatch_server_request_can_send_now_event(att_server->connection.con_handle); 539 return; 540 } 541 } 542 } 543 544 // Exit loop, if we cannot send (request_con_handle will be set) 545 if (!can_send_now) break; 546 547 // Exit loop, if we can send but there are also no further request 548 if (request_con_handle == HCI_CON_HANDLE_INVALID) break; 549 550 // Finally, if we still can send and there are requests, just try again 551 request_con_handle = HCI_CON_HANDLE_INVALID; 552 } 553 554 if (request_con_handle == HCI_CON_HANDLE_INVALID) return; 555 556 att_dispatch_server_request_can_send_now_event(request_con_handle); 557 } 558 559 static void att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){ 560 561 att_server_t * att_server; 562 563 switch (packet_type){ 564 565 case HCI_EVENT_PACKET: 566 switch (packet[0]){ 567 case L2CAP_EVENT_CAN_SEND_NOW: 568 att_server_handle_can_send_now(); 569 break; 570 case ATT_EVENT_MTU_EXCHANGE_COMPLETE: 571 // GATT client has negotiated the mtu for this connection 572 att_server = att_server_for_handle(handle); 573 if (!att_server) break; 574 att_server->connection.mtu = little_endian_read_16(packet, 4); 575 break; 576 default: 577 break; 578 } 579 break; 580 581 case ATT_DATA_PACKET: 582 log_debug("ATT Packet, handle 0x%04x", handle); 583 att_server = att_server_for_handle(handle); 584 if (!att_server) break; 585 586 // handle value indication confirms 587 if (packet[0] == ATT_HANDLE_VALUE_CONFIRMATION && att_server->value_indication_handle){ 588 btstack_run_loop_remove_timer(&att_server->value_indication_timer); 589 uint16_t att_handle = att_server->value_indication_handle; 590 att_server->value_indication_handle = 0; 591 att_handle_value_indication_notify_client(0, att_server->connection.con_handle, att_handle); 592 att_dispatch_server_request_can_send_now_event(att_server->connection.con_handle); 593 return; 594 } 595 596 // directly process command 597 // note: signed write cannot be handled directly as authentication needs to be verified 598 if (packet[0] == ATT_WRITE_COMMAND){ 599 att_handle_request(&att_server->connection, packet, size, 0); 600 return; 601 } 602 603 // check size 604 if (size > sizeof(att_server->request_buffer)) { 605 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)); 606 return; 607 } 608 609 // last request still in processing? 610 if (att_server->state != ATT_SERVER_IDLE){ 611 log_info("att_packet_handler: skipping att pdu 0x%02x as server not idle (state %u)", packet[0], att_server->state); 612 return; 613 } 614 615 // store request 616 att_server->state = ATT_SERVER_REQUEST_RECEIVED; 617 att_server->request_size = size; 618 memcpy(att_server->request_buffer, packet, size); 619 620 att_run_for_context(att_server); 621 break; 622 } 623 } 624 625 // --------------------- 626 // persistent CCC writes 627 static uint32_t att_server_persistent_ccc_tag_for_index(uint8_t index){ 628 return 'B' << 24 | 'T' << 16 | 'C' << 8 | index; 629 } 630 631 static void att_server_persistent_ccc_write(hci_con_handle_t con_handle, uint16_t att_handle, uint16_t value){ 632 // lookup att_server instance 633 att_server_t * att_server = att_server_for_handle(con_handle); 634 if (!att_server) return; 635 int le_device_index = att_server->ir_le_device_db_index; 636 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); 637 638 // check if bonded 639 if (le_device_index < 0) return; 640 641 // get btstack_tlv 642 const btstack_tlv_t * tlv_impl = NULL; 643 void * tlv_context; 644 btstack_tlv_get_instance(&tlv_impl, &tlv_context); 645 if (!tlv_impl) return; 646 647 // update ccc tag 648 int index; 649 uint32_t highest_seq_nr = 0; 650 uint32_t lowest_seq_nr = 0; 651 uint32_t tag_for_lowest_seq_nr = 0; 652 uint32_t tag_for_empty = 0; 653 persistent_ccc_entry_t entry; 654 for (index=0;index<NVN_NUM_GATT_SERVER_CCC;index++){ 655 uint32_t tag = att_server_persistent_ccc_tag_for_index(index); 656 int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t)); 657 658 // empty/invalid tag 659 if (len != sizeof(persistent_ccc_entry_t)){ 660 tag_for_empty = tag; 661 continue; 662 } 663 // update highest seq nr 664 if (entry.seq_nr > highest_seq_nr){ 665 highest_seq_nr = entry.seq_nr; 666 } 667 // find entry with lowest seq nr 668 if ((tag_for_lowest_seq_nr == 0) || (entry.seq_nr < lowest_seq_nr)){ 669 tag_for_lowest_seq_nr = tag; 670 lowest_seq_nr = entry.seq_nr; 671 } 672 673 if (entry.device_index != le_device_index) continue; 674 if (entry.att_handle != att_handle) continue; 675 676 // found matching entry 677 if (value){ 678 // update 679 if (entry.value == value) { 680 log_info("CCC Index %u: Up-to-date", index); 681 return; 682 } 683 entry.value = value; 684 entry.seq_nr = highest_seq_nr + 1; 685 log_info("CCC Index %u: Store", index); 686 tlv_impl->store_tag(tlv_context, tag, (const uint8_t *) &entry, sizeof(persistent_ccc_entry_t)); 687 } else { 688 // delete 689 log_info("CCC Index %u: Delete", index); 690 tlv_impl->delete_tag(tlv_context, tag); 691 } 692 return; 693 } 694 695 log_info("tag_for_empy %"PRIx32", tag_for_lowest_seq_nr %"PRIx32, tag_for_empty, tag_for_lowest_seq_nr); 696 697 if (value == 0){ 698 // done 699 return; 700 } 701 702 uint32_t tag_to_use = 0; 703 if (tag_for_empty){ 704 tag_to_use = tag_for_empty; 705 } else if (tag_for_lowest_seq_nr){ 706 tag_to_use = tag_for_lowest_seq_nr; 707 } else { 708 // should not happen 709 return; 710 } 711 // store ccc tag 712 entry.seq_nr = highest_seq_nr + 1; 713 entry.device_index = le_device_index; 714 entry.att_handle = att_handle; 715 entry.value = value; 716 tlv_impl->store_tag(tlv_context, tag_to_use, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t)); 717 } 718 719 static void att_server_persistent_ccc_clear(att_server_t * att_server){ 720 if (!att_server) return; 721 int le_device_index = att_server->ir_le_device_db_index; 722 log_info("Clear CCC values of remote %s, le device id %d", bd_addr_to_str(att_server->peer_address), le_device_index); 723 // check if bonded 724 if (le_device_index < 0) return; 725 // get btstack_tlv 726 const btstack_tlv_t * tlv_impl = NULL; 727 void * tlv_context; 728 btstack_tlv_get_instance(&tlv_impl, &tlv_context); 729 if (!tlv_impl) return; 730 // get all ccc tag 731 int index; 732 persistent_ccc_entry_t entry; 733 for (index=0;index<NVN_NUM_GATT_SERVER_CCC;index++){ 734 uint32_t tag = att_server_persistent_ccc_tag_for_index(index); 735 int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t)); 736 if (len != sizeof(persistent_ccc_entry_t)) continue; 737 if (entry.device_index != le_device_index) continue; 738 // delete entry 739 log_info("CCC Index %u: Delete", index); 740 tlv_impl->delete_tag(tlv_context, tag); 741 } 742 } 743 744 static void att_server_persistent_ccc_restore(att_server_t * att_server){ 745 if (!att_server) return; 746 int le_device_index = att_server->ir_le_device_db_index; 747 log_info("Restore CCC values of remote %s, le device id %d", bd_addr_to_str(att_server->peer_address), le_device_index); 748 // check if bonded 749 if (le_device_index < 0) return; 750 // get btstack_tlv 751 const btstack_tlv_t * tlv_impl = NULL; 752 void * tlv_context; 753 btstack_tlv_get_instance(&tlv_impl, &tlv_context); 754 if (!tlv_impl) return; 755 // get all ccc tag 756 int index; 757 persistent_ccc_entry_t entry; 758 for (index=0;index<NVN_NUM_GATT_SERVER_CCC;index++){ 759 uint32_t tag = att_server_persistent_ccc_tag_for_index(index); 760 int len = tlv_impl->get_tag(tlv_context, tag, (uint8_t *) &entry, sizeof(persistent_ccc_entry_t)); 761 if (len != sizeof(persistent_ccc_entry_t)) continue; 762 if (entry.device_index != le_device_index) continue; 763 // simulate write callback 764 uint16_t attribute_handle = entry.att_handle; 765 uint8_t value[2]; 766 little_endian_store_16(value, 0, entry.value); 767 att_write_callback_t callback = att_server_write_callback_for_handle(attribute_handle); 768 if (!callback) continue; 769 log_info("CCC Index %u: Set Attribute handle 0x%04x to value 0x%04x", index, attribute_handle, entry.value ); 770 (*callback)(att_server->connection.con_handle, attribute_handle, ATT_TRANSACTION_MODE_NONE, 0, value, sizeof(value)); 771 } 772 } 773 774 // persistent CCC writes 775 // --------------------- 776 777 // gatt service management 778 static att_service_handler_t * att_service_handler_for_handle(uint16_t handle){ 779 btstack_linked_list_iterator_t it; 780 btstack_linked_list_iterator_init(&it, &service_handlers); 781 while (btstack_linked_list_iterator_has_next(&it)){ 782 att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it); 783 if (handler->start_handle > handle) continue; 784 if (handler->end_handle < handle) continue; 785 return handler; 786 } 787 return NULL; 788 } 789 static att_read_callback_t att_server_read_callback_for_handle(uint16_t handle){ 790 att_service_handler_t * handler = att_service_handler_for_handle(handle); 791 if (handler) return handler->read_callback; 792 return att_server_client_read_callback; 793 } 794 795 static att_write_callback_t att_server_write_callback_for_handle(uint16_t handle){ 796 att_service_handler_t * handler = att_service_handler_for_handle(handle); 797 if (handler) return handler->write_callback; 798 return att_server_client_write_callback; 799 } 800 801 static void att_notify_write_callbacks(hci_con_handle_t con_handle, uint16_t transaction_mode){ 802 // notify all callbacks 803 btstack_linked_list_iterator_t it; 804 btstack_linked_list_iterator_init(&it, &service_handlers); 805 while (btstack_linked_list_iterator_has_next(&it)){ 806 att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it); 807 if (!handler->write_callback) continue; 808 (*handler->write_callback)(con_handle, 0, transaction_mode, 0, NULL, 0); 809 } 810 if (!att_server_client_write_callback) return; 811 (*att_server_client_write_callback)(con_handle, 0, transaction_mode, 0, NULL, 0); 812 } 813 814 // returns first reported error or 0 815 static uint8_t att_validate_prepared_write(hci_con_handle_t con_handle){ 816 btstack_linked_list_iterator_t it; 817 btstack_linked_list_iterator_init(&it, &service_handlers); 818 while (btstack_linked_list_iterator_has_next(&it)){ 819 att_service_handler_t * handler = (att_service_handler_t*) btstack_linked_list_iterator_next(&it); 820 if (!handler->write_callback) continue; 821 uint8_t error_code = (*handler->write_callback)(con_handle, 0, ATT_TRANSACTION_MODE_VALIDATE, 0, NULL, 0); 822 if (error_code) return error_code; 823 } 824 if (!att_server_client_write_callback) return 0; 825 return (*att_server_client_write_callback)(con_handle, 0, ATT_TRANSACTION_MODE_VALIDATE, 0, NULL, 0); 826 } 827 828 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){ 829 att_read_callback_t callback = att_server_read_callback_for_handle(attribute_handle); 830 if (!callback) return 0; 831 return (*callback)(con_handle, attribute_handle, offset, buffer, buffer_size); 832 } 833 834 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){ 835 switch (transaction_mode){ 836 case ATT_TRANSACTION_MODE_VALIDATE: 837 return att_validate_prepared_write(con_handle); 838 case ATT_TRANSACTION_MODE_EXECUTE: 839 case ATT_TRANSACTION_MODE_CANCEL: 840 att_notify_write_callbacks(con_handle, transaction_mode); 841 return 0; 842 default: 843 break; 844 } 845 846 // track CCC writes 847 if (att_is_persistent_ccc(attribute_handle) && offset == 0 && buffer_size == 2){ 848 att_server_persistent_ccc_write(con_handle, attribute_handle, little_endian_read_16(buffer, 0)); 849 } 850 851 att_write_callback_t callback = att_server_write_callback_for_handle(attribute_handle); 852 if (!callback) return 0; 853 return (*callback)(con_handle, attribute_handle, transaction_mode, offset, buffer, buffer_size); 854 } 855 856 /** 857 * @brief register read/write callbacks for specific handle range 858 * @param att_service_handler_t 859 */ 860 void att_server_register_service_handler(att_service_handler_t * handler){ 861 if (att_service_handler_for_handle(handler->start_handle) || 862 att_service_handler_for_handle(handler->end_handle)){ 863 log_error("handler for range 0x%04x-0x%04x already registered", handler->start_handle, handler->end_handle); 864 return; 865 } 866 btstack_linked_list_add(&service_handlers, (btstack_linked_item_t*) handler); 867 } 868 869 void att_server_init(uint8_t const * db, att_read_callback_t read_callback, att_write_callback_t write_callback){ 870 871 // store callbacks 872 att_server_client_read_callback = read_callback; 873 att_server_client_write_callback = write_callback; 874 875 // register for HCI Events 876 hci_event_callback_registration.callback = &att_event_packet_handler; 877 hci_add_event_handler(&hci_event_callback_registration); 878 879 // register for SM events 880 sm_event_callback_registration.callback = &att_event_packet_handler; 881 sm_add_event_handler(&sm_event_callback_registration); 882 883 // and L2CAP ATT Server PDUs 884 att_dispatch_register_server(att_packet_handler); 885 886 att_set_db(db); 887 att_set_read_callback(att_server_read_callback); 888 att_set_write_callback(att_server_write_callback); 889 890 } 891 892 void att_server_register_packet_handler(btstack_packet_handler_t handler){ 893 att_client_packet_handler = handler; 894 } 895 896 897 // to be deprecated 898 int att_server_can_send_packet_now(hci_con_handle_t con_handle){ 899 return att_dispatch_server_can_send_now(con_handle); 900 } 901 902 int att_server_register_can_send_now_callback(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){ 903 return att_server_request_to_send_notification(callback_registration, con_handle); 904 } 905 906 void att_server_request_can_send_now_event(hci_con_handle_t con_handle){ 907 att_client_waiting_for_can_send_registration.callback = &att_emit_can_send_now_event; 908 att_server_request_to_send_notification(&att_client_waiting_for_can_send_registration, con_handle); 909 } 910 // end of deprecated 911 912 int att_server_request_to_send_notification(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){ 913 att_server_t * att_server = att_server_for_handle(con_handle); 914 if (!att_server) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 915 btstack_linked_list_add_tail(&att_server->notification_requests, (btstack_linked_item_t*) callback_registration); 916 att_dispatch_server_request_can_send_now_event(con_handle); 917 return ERROR_CODE_SUCCESS; 918 } 919 920 int att_server_request_to_send_indication(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){ 921 att_server_t * att_server = att_server_for_handle(con_handle); 922 if (!att_server) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 923 btstack_linked_list_add_tail(&att_server->indication_requests, (btstack_linked_item_t*) callback_registration); 924 att_dispatch_server_request_can_send_now_event(con_handle); 925 return ERROR_CODE_SUCCESS; 926 } 927 928 int att_server_notify(hci_con_handle_t con_handle, uint16_t attribute_handle, uint8_t *value, uint16_t value_len){ 929 att_server_t * att_server = att_server_for_handle(con_handle); 930 if (!att_server) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 931 932 if (!att_dispatch_server_can_send_now(con_handle)) return BTSTACK_ACL_BUFFERS_FULL; 933 934 l2cap_reserve_packet_buffer(); 935 uint8_t * packet_buffer = l2cap_get_outgoing_buffer(); 936 uint16_t size = att_prepare_handle_value_notification(&att_server->connection, attribute_handle, value, value_len, packet_buffer); 937 return l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size); 938 } 939 940 int att_server_indicate(hci_con_handle_t con_handle, uint16_t attribute_handle, uint8_t *value, uint16_t value_len){ 941 att_server_t * att_server = att_server_for_handle(con_handle); 942 if (!att_server) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 943 944 if (att_server->value_indication_handle) return ATT_HANDLE_VALUE_INDICATION_IN_PROGRESS; 945 if (!att_dispatch_server_can_send_now(con_handle)) return BTSTACK_ACL_BUFFERS_FULL; 946 947 // track indication 948 att_server->value_indication_handle = attribute_handle; 949 btstack_run_loop_set_timer_handler(&att_server->value_indication_timer, att_handle_value_indication_timeout); 950 btstack_run_loop_set_timer(&att_server->value_indication_timer, ATT_TRANSACTION_TIMEOUT_MS); 951 btstack_run_loop_add_timer(&att_server->value_indication_timer); 952 953 l2cap_reserve_packet_buffer(); 954 uint8_t * packet_buffer = l2cap_get_outgoing_buffer(); 955 uint16_t size = att_prepare_handle_value_indication(&att_server->connection, attribute_handle, value, value_len, packet_buffer); 956 l2cap_send_prepared_connectionless(att_server->connection.con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, size); 957 return 0; 958 } 959