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