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