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