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