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