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