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__ "daemon.c" 39 40 /* 41 * daemon.c 42 * 43 * Created by Matthias Ringwald on 7/1/09. 44 * 45 * BTstack background daemon 46 * 47 */ 48 49 #include "btstack_config.h" 50 51 #include <pthread.h> 52 #include <signal.h> 53 #include <stdio.h> 54 #include <stdlib.h> 55 #include <strings.h> 56 #include <unistd.h> 57 58 #ifdef _WIN32 59 #include "Winsock2.h" 60 #endif 61 62 #include <getopt.h> 63 64 #include "btstack.h" 65 #include "btstack_client.h" 66 #include "btstack_debug.h" 67 #include "btstack_device_name_db.h" 68 #include "btstack_event.h" 69 #include "btstack_linked_list.h" 70 #include "btstack_run_loop.h" 71 #include "btstack_server.h" 72 73 #ifdef _WIN32 74 #include "btstack_run_loop_windows.h" 75 #else 76 #include "btstack_run_loop_posix.h" 77 #endif 78 #include "btstack_version.h" 79 #include "classic/btstack_link_key_db.h" 80 #include "classic/rfcomm.h" 81 #include "classic/sdp_server.h" 82 #include "classic/sdp_client.h" 83 #include "classic/sdp_client_rfcomm.h" 84 #include "hci.h" 85 #include "hci_cmd.h" 86 #include "hci_dump.h" 87 #include "hci_transport.h" 88 #include "l2cap.h" 89 #include "rfcomm_service_db.h" 90 #include "socket_connection.h" 91 92 #ifdef ENABLE_BLE 93 #include "ble/gatt_client.h" 94 #include "ble/att_server.h" 95 #include "ble/att_db.h" 96 #include "ble/le_device_db.h" 97 #include "ble/sm.h" 98 #endif 99 100 #ifdef HAVE_PLATFORM_IPHONE_OS 101 #include <CoreFoundation/CoreFoundation.h> 102 #include <notify.h> 103 #include "../port/ios/src/btstack_control_iphone.h" 104 #include "../port/ios/src/platform_iphone.h" 105 // support for "enforece wake device" in h4 - used by iOS power management 106 extern void hci_transport_h4_iphone_set_enforce_wake_device(char *path); 107 #endif 108 109 // copy of prototypes 110 const btstack_device_name_db_t * btstack_device_name_db_corefoundation_instance(void); 111 const btstack_device_name_db_t * btstack_device_name_db_fs_instance(void); 112 const btstack_link_key_db_t * btstack_link_key_db_corefoundation_instance(void); 113 const btstack_link_key_db_t * btstack_link_key_db_fs_instance(void); 114 115 #ifndef BTSTACK_LOG_FILE 116 #define BTSTACK_LOG_FILE "/tmp/hci_dump.pklg" 117 #endif 118 119 // use logger: format HCI_DUMP_PACKETLOGGER, HCI_DUMP_BLUEZ or HCI_DUMP_STDOUT 120 #ifndef BTSTACK_LOG_TYPE 121 #define BTSTACK_LOG_TYPE HCI_DUMP_PACKETLOGGER 122 #endif 123 124 #define DAEMON_NO_ACTIVE_CLIENT_TIMEOUT 10000 125 126 #define ATT_MAX_LONG_ATTRIBUTE_SIZE 512 127 128 129 #define SERVICE_LENGTH 20 130 #define CHARACTERISTIC_LENGTH 24 131 #define CHARACTERISTIC_DESCRIPTOR_LENGTH 18 132 133 // ATT_MTU - 1 134 #define ATT_MAX_ATTRIBUTE_SIZE 22 135 136 // HCI CMD OGF/OCF 137 #define READ_CMD_OGF(buffer) (buffer[1] >> 2) 138 #define READ_CMD_OCF(buffer) ((buffer[1] & 0x03) << 8 | buffer[0]) 139 140 typedef struct { 141 // linked list - assert: first field 142 btstack_linked_item_t item; 143 144 // connection 145 connection_t * connection; 146 147 btstack_linked_list_t rfcomm_cids; 148 btstack_linked_list_t rfcomm_services; 149 btstack_linked_list_t l2cap_cids; 150 btstack_linked_list_t l2cap_psms; 151 btstack_linked_list_t sdp_record_handles; 152 btstack_linked_list_t gatt_con_handles; 153 // power mode 154 HCI_POWER_MODE power_mode; 155 156 // discoverable 157 uint8_t discoverable; 158 159 } client_state_t; 160 161 typedef struct btstack_linked_list_uint32 { 162 btstack_linked_item_t item; 163 uint32_t value; 164 } btstack_linked_list_uint32_t; 165 166 typedef struct btstack_linked_list_connection { 167 btstack_linked_item_t item; 168 connection_t * connection; 169 } btstack_linked_list_connection_t; 170 171 typedef struct btstack_linked_list_gatt_client_helper{ 172 btstack_linked_item_t item; 173 hci_con_handle_t con_handle; 174 connection_t * active_connection; // the one that started the current query 175 btstack_linked_list_t all_connections; // list of all connections that ever used this helper 176 uint16_t characteristic_length; 177 uint16_t characteristic_handle; 178 uint8_t characteristic_buffer[10 + ATT_MAX_LONG_ATTRIBUTE_SIZE]; // header for sending event right away 179 uint8_t long_query_type; 180 } btstack_linked_list_gatt_client_helper_t; 181 182 // MARK: prototypes 183 static void handle_sdp_rfcomm_service_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size); 184 static void handle_sdp_client_query_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size); 185 #ifdef ENABLE_BLE 186 static void handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size); 187 #endif 188 static void dummy_bluetooth_status_handler(BLUETOOTH_STATE state); 189 static client_state_t * client_for_connection(connection_t *connection); 190 static int clients_require_power_on(void); 191 static int clients_require_discoverable(void); 192 static void clients_clear_power_request(void); 193 static void start_power_off_timer(void); 194 static void stop_power_off_timer(void); 195 static client_state_t * client_for_connection(connection_t *connection); 196 static void hci_emit_system_bluetooth_enabled(uint8_t enabled); 197 static void rfcomm_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size); 198 199 200 // MARK: globals 201 202 #ifdef HAVE_TRANSPORT_H4 203 static hci_transport_config_uart_t hci_transport_config_uart; 204 #endif 205 206 static const hci_transport_t * transport; 207 static btstack_timer_source_t timeout; 208 static uint8_t timeout_active = 0; 209 static int power_management_sleep = 0; 210 static btstack_linked_list_t clients = NULL; // list of connected clients ` 211 #ifdef ENABLE_BLE 212 static btstack_linked_list_t gatt_client_helpers = NULL; // list of used gatt client (helpers) 213 #endif 214 215 static void (*bluetooth_status_handler)(BLUETOOTH_STATE state) = dummy_bluetooth_status_handler; 216 217 static btstack_packet_callback_registration_t hci_event_callback_registration; 218 219 static int global_enable = 0; 220 221 static btstack_link_key_db_t const * btstack_link_key_db = NULL; 222 static btstack_device_name_db_t const * btstack_device_name_db = NULL; 223 // static int rfcomm_channel_generator = 1; 224 225 static uint8_t attribute_value[1000]; 226 static const int attribute_value_buffer_size = sizeof(attribute_value); 227 static uint8_t serviceSearchPattern[200]; 228 static uint8_t attributeIDList[50]; 229 static void * sdp_client_query_connection; 230 231 static int loggingEnabled; 232 233 // stashed code from l2cap.c and rfcomm.c -- needed for new implementation 234 #if 0 235 static void l2cap_emit_credits(l2cap_channel_t *channel, uint8_t credits) { 236 237 log_info("DAEMON_EVENT_L2CAP_CREDITS local_cid 0x%x credits %u", channel->local_cid, credits); 238 239 uint8_t event[5]; 240 event[0] = DAEMON_EVENT_L2CAP_CREDITS; 241 event[1] = sizeof(event) - 2; 242 little_endian_store_16(event, 2, channel->local_cid); 243 event[4] = credits; 244 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 245 l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event)); 246 } 247 248 static void l2cap_hand_out_credits(void){ 249 btstack_linked_list_iterator_t it; 250 btstack_linked_list_iterator_init(&it, &l2cap_channels); 251 while (btstack_linked_list_iterator_has_next(&it)){ 252 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 253 if (channel->state != L2CAP_STATE_OPEN) continue; 254 if (!hci_number_free_acl_slots_for_handle(channel->handle)) return; 255 l2cap_emit_credits(channel, 1); 256 } 257 } 258 static void rfcomm_emit_credits(rfcomm_channel_t * channel, uint8_t credits) { 259 log_info("DAEMON_EVENT_RFCOMM_CREDITS cid 0x%02x credits %u", channel->rfcomm_cid, credits); 260 uint8_t event[5]; 261 event[0] = DAEMON_EVENT_RFCOMM_CREDITS; 262 event[1] = sizeof(event) - 2; 263 little_endian_store_16(event, 2, channel->rfcomm_cid); 264 event[4] = credits; 265 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 266 (*app_packet_handler)(HCI_EVENT_PACKET, 0, (uint8_t *) event, sizeof(event)); 267 } 268 static void rfcomm_hand_out_credits(void){ 269 btstack_linked_item_t * it; 270 for (it = (btstack_linked_item_t *) rfcomm_channels; it ; it = it->next){ 271 rfcomm_channel_t * channel = (rfcomm_channel_t *) it; 272 if (channel->state != RFCOMM_CHANNEL_OPEN) { 273 // log_info("DAEMON_EVENT_RFCOMM_CREDITS: multiplexer not open"); 274 continue; 275 } 276 if (!channel->credits_outgoing) { 277 // log_info("DAEMON_EVENT_RFCOMM_CREDITS: no outgoing credits"); 278 continue; 279 } 280 // channel open, multiplexer has l2cap credits and we didn't hand out credit before -> go! 281 // log_info("DAEMON_EVENT_RFCOMM_CREDITS: 1"); 282 rfcomm_emit_credits(channel, 1); 283 } 284 } 285 286 #endif 287 288 static void dummy_bluetooth_status_handler(BLUETOOTH_STATE state){ 289 log_info("Bluetooth status: %u\n", state); 290 }; 291 292 static void daemon_no_connections_timeout(struct btstack_timer_source *ts){ 293 if (clients_require_power_on()) return; // false alarm :) 294 log_info("No active client connection for %u seconds -> POWER OFF\n", DAEMON_NO_ACTIVE_CLIENT_TIMEOUT/1000); 295 hci_power_control(HCI_POWER_OFF); 296 } 297 298 299 static void add_uint32_to_list(btstack_linked_list_t *list, uint32_t value){ 300 btstack_linked_list_iterator_t it; 301 btstack_linked_list_iterator_init(&it, list); 302 while (btstack_linked_list_iterator_has_next(&it)){ 303 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 304 if ( item->value == value) return; // already in list 305 } 306 307 btstack_linked_list_uint32_t * item = malloc(sizeof(btstack_linked_list_uint32_t)); 308 if (!item) return; 309 item->value = value; 310 btstack_linked_list_add(list, (btstack_linked_item_t *) item); 311 } 312 313 static void remove_and_free_uint32_from_list(btstack_linked_list_t *list, uint32_t value){ 314 btstack_linked_list_iterator_t it; 315 btstack_linked_list_iterator_init(&it, list); 316 while (btstack_linked_list_iterator_has_next(&it)){ 317 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 318 if ( item->value != value) continue; 319 btstack_linked_list_remove(list, (btstack_linked_item_t *) item); 320 free(item); 321 } 322 } 323 324 static void daemon_add_client_rfcomm_service(connection_t * connection, uint16_t service_channel){ 325 client_state_t * client_state = client_for_connection(connection); 326 if (!client_state) return; 327 add_uint32_to_list(&client_state->rfcomm_services, service_channel); 328 } 329 330 static void daemon_remove_client_rfcomm_service(connection_t * connection, uint16_t service_channel){ 331 client_state_t * client_state = client_for_connection(connection); 332 if (!client_state) return; 333 remove_and_free_uint32_from_list(&client_state->rfcomm_services, service_channel); 334 } 335 336 static void daemon_add_client_rfcomm_channel(connection_t * connection, uint16_t cid){ 337 client_state_t * client_state = client_for_connection(connection); 338 if (!client_state) return; 339 add_uint32_to_list(&client_state->rfcomm_cids, cid); 340 } 341 342 static void daemon_remove_client_rfcomm_channel(connection_t * connection, uint16_t cid){ 343 client_state_t * client_state = client_for_connection(connection); 344 if (!client_state) return; 345 remove_and_free_uint32_from_list(&client_state->rfcomm_cids, cid); 346 } 347 348 static void daemon_add_client_l2cap_service(connection_t * connection, uint16_t psm){ 349 client_state_t * client_state = client_for_connection(connection); 350 if (!client_state) return; 351 add_uint32_to_list(&client_state->l2cap_psms, psm); 352 } 353 354 static void daemon_remove_client_l2cap_service(connection_t * connection, uint16_t psm){ 355 client_state_t * client_state = client_for_connection(connection); 356 if (!client_state) return; 357 remove_and_free_uint32_from_list(&client_state->l2cap_psms, psm); 358 } 359 360 static void daemon_add_client_l2cap_channel(connection_t * connection, uint16_t cid){ 361 client_state_t * client_state = client_for_connection(connection); 362 if (!client_state) return; 363 add_uint32_to_list(&client_state->l2cap_cids, cid); 364 } 365 366 static void daemon_remove_client_l2cap_channel(connection_t * connection, uint16_t cid){ 367 client_state_t * client_state = client_for_connection(connection); 368 if (!client_state) return; 369 remove_and_free_uint32_from_list(&client_state->l2cap_cids, cid); 370 } 371 372 static void daemon_add_client_sdp_service_record_handle(connection_t * connection, uint32_t handle){ 373 client_state_t * client_state = client_for_connection(connection); 374 if (!client_state) return; 375 add_uint32_to_list(&client_state->sdp_record_handles, handle); 376 } 377 378 static void daemon_remove_client_sdp_service_record_handle(connection_t * connection, uint32_t handle){ 379 client_state_t * client_state = client_for_connection(connection); 380 if (!client_state) return; 381 remove_and_free_uint32_from_list(&client_state->sdp_record_handles, handle); 382 } 383 384 #ifdef ENABLE_BLE 385 static void daemon_add_gatt_client_handle(connection_t * connection, uint32_t handle){ 386 client_state_t * client_state = client_for_connection(connection); 387 if (!client_state) return; 388 389 // check if handle already exists in the gatt_con_handles list 390 btstack_linked_list_iterator_t it; 391 int handle_found = 0; 392 btstack_linked_list_iterator_init(&it, &client_state->gatt_con_handles); 393 while (btstack_linked_list_iterator_has_next(&it)){ 394 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 395 if (item->value == handle){ 396 handle_found = 1; 397 break; 398 } 399 } 400 // if handle doesn't exist add it to gatt_con_handles 401 if (!handle_found){ 402 add_uint32_to_list(&client_state->gatt_con_handles, handle); 403 } 404 405 // check if there is a helper with given handle 406 btstack_linked_list_gatt_client_helper_t * gatt_helper = NULL; 407 btstack_linked_list_iterator_init(&it, &gatt_client_helpers); 408 while (btstack_linked_list_iterator_has_next(&it)){ 409 btstack_linked_list_gatt_client_helper_t * item = (btstack_linked_list_gatt_client_helper_t*) btstack_linked_list_iterator_next(&it); 410 if (item->con_handle == handle){ 411 gatt_helper = item; 412 break; 413 } 414 } 415 416 // if gatt_helper doesn't exist, create it and add it to gatt_client_helpers list 417 if (!gatt_helper){ 418 gatt_helper = calloc(sizeof(btstack_linked_list_gatt_client_helper_t), 1); 419 if (!gatt_helper) return; 420 gatt_helper->con_handle = handle; 421 btstack_linked_list_add(&gatt_client_helpers, (btstack_linked_item_t *) gatt_helper); 422 } 423 424 // check if connection exists 425 int connection_found = 0; 426 btstack_linked_list_iterator_init(&it, &gatt_helper->all_connections); 427 while (btstack_linked_list_iterator_has_next(&it)){ 428 btstack_linked_list_connection_t * item = (btstack_linked_list_connection_t*) btstack_linked_list_iterator_next(&it); 429 if (item->connection == connection){ 430 connection_found = 1; 431 break; 432 } 433 } 434 435 // if connection is not found, add it to the all_connections, and set it as active connection 436 if (!connection_found){ 437 btstack_linked_list_connection_t * con = calloc(sizeof(btstack_linked_list_connection_t), 1); 438 if (!con) return; 439 con->connection = connection; 440 btstack_linked_list_add(&gatt_helper->all_connections, (btstack_linked_item_t *)con); 441 } 442 } 443 444 445 static void daemon_remove_gatt_client_handle(connection_t * connection, uint32_t handle){ 446 // PART 1 - uses connection & handle 447 // might be extracted or vanish totally 448 client_state_t * client_state = client_for_connection(connection); 449 if (!client_state) return; 450 451 btstack_linked_list_iterator_t it; 452 // remove handle from gatt_con_handles list 453 btstack_linked_list_iterator_init(&it, &client_state->gatt_con_handles); 454 while (btstack_linked_list_iterator_has_next(&it)){ 455 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 456 if (item->value == handle){ 457 btstack_linked_list_remove(&client_state->gatt_con_handles, (btstack_linked_item_t *) item); 458 free(item); 459 } 460 } 461 462 // PART 2 - only uses handle 463 464 // find helper with given handle 465 btstack_linked_list_gatt_client_helper_t * helper = NULL; 466 btstack_linked_list_iterator_init(&it, &gatt_client_helpers); 467 while (btstack_linked_list_iterator_has_next(&it)){ 468 btstack_linked_list_gatt_client_helper_t * item = (btstack_linked_list_gatt_client_helper_t*) btstack_linked_list_iterator_next(&it); 469 if (item->con_handle == handle){ 470 helper = item; 471 break; 472 } 473 } 474 475 if (!helper) return; 476 // remove connection from helper 477 btstack_linked_list_iterator_init(&it, &helper->all_connections); 478 while (btstack_linked_list_iterator_has_next(&it)){ 479 btstack_linked_list_connection_t * item = (btstack_linked_list_connection_t*) btstack_linked_list_iterator_next(&it); 480 if (item->connection == connection){ 481 btstack_linked_list_remove(&helper->all_connections, (btstack_linked_item_t *) item); 482 free(item); 483 break; 484 } 485 } 486 487 if (helper->active_connection == connection){ 488 helper->active_connection = NULL; 489 } 490 // if helper has no more connections, call disconnect 491 if (helper->all_connections == NULL){ 492 gap_disconnect((hci_con_handle_t) helper->con_handle); 493 } 494 } 495 496 497 static void daemon_remove_gatt_client_helper(uint32_t con_handle){ 498 btstack_linked_list_iterator_t it, cl; 499 // find helper with given handle 500 btstack_linked_list_gatt_client_helper_t * helper = NULL; 501 btstack_linked_list_iterator_init(&it, &gatt_client_helpers); 502 while (btstack_linked_list_iterator_has_next(&it)){ 503 btstack_linked_list_gatt_client_helper_t * item = (btstack_linked_list_gatt_client_helper_t*) btstack_linked_list_iterator_next(&it); 504 if (item->con_handle == con_handle){ 505 helper = item; 506 break; 507 } 508 } 509 510 if (!helper) return; 511 512 // remove all connection from helper 513 btstack_linked_list_iterator_init(&it, &helper->all_connections); 514 while (btstack_linked_list_iterator_has_next(&it)){ 515 btstack_linked_list_connection_t * item = (btstack_linked_list_connection_t*) btstack_linked_list_iterator_next(&it); 516 btstack_linked_list_remove(&helper->all_connections, (btstack_linked_item_t *) item); 517 free(item); 518 } 519 520 btstack_linked_list_remove(&gatt_client_helpers, (btstack_linked_item_t *) helper); 521 free(helper); 522 523 btstack_linked_list_iterator_init(&cl, &clients); 524 while (btstack_linked_list_iterator_has_next(&cl)){ 525 client_state_t * client_state = (client_state_t *) btstack_linked_list_iterator_next(&cl); 526 btstack_linked_list_iterator_init(&it, &client_state->gatt_con_handles); 527 while (btstack_linked_list_iterator_has_next(&it)){ 528 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 529 if (item->value == con_handle){ 530 btstack_linked_list_remove(&client_state->gatt_con_handles, (btstack_linked_item_t *) item); 531 free(item); 532 } 533 } 534 } 535 } 536 #endif 537 538 static void daemon_rfcomm_close_connection(client_state_t * daemon_client){ 539 btstack_linked_list_iterator_t it; 540 btstack_linked_list_t *rfcomm_services = &daemon_client->rfcomm_services; 541 btstack_linked_list_t *rfcomm_cids = &daemon_client->rfcomm_cids; 542 543 btstack_linked_list_iterator_init(&it, rfcomm_services); 544 while (btstack_linked_list_iterator_has_next(&it)){ 545 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 546 rfcomm_unregister_service(item->value); 547 btstack_linked_list_remove(rfcomm_services, (btstack_linked_item_t *) item); 548 free(item); 549 } 550 551 btstack_linked_list_iterator_init(&it, rfcomm_cids); 552 while (btstack_linked_list_iterator_has_next(&it)){ 553 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 554 rfcomm_disconnect(item->value); 555 btstack_linked_list_remove(rfcomm_cids, (btstack_linked_item_t *) item); 556 free(item); 557 } 558 } 559 560 561 static void daemon_l2cap_close_connection(client_state_t * daemon_client){ 562 btstack_linked_list_iterator_t it; 563 btstack_linked_list_t *l2cap_psms = &daemon_client->l2cap_psms; 564 btstack_linked_list_t *l2cap_cids = &daemon_client->l2cap_cids; 565 566 btstack_linked_list_iterator_init(&it, l2cap_psms); 567 while (btstack_linked_list_iterator_has_next(&it)){ 568 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 569 l2cap_unregister_service(item->value); 570 btstack_linked_list_remove(l2cap_psms, (btstack_linked_item_t *) item); 571 free(item); 572 } 573 574 btstack_linked_list_iterator_init(&it, l2cap_cids); 575 while (btstack_linked_list_iterator_has_next(&it)){ 576 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 577 l2cap_disconnect(item->value, 0); // note: reason isn't used 578 btstack_linked_list_remove(l2cap_cids, (btstack_linked_item_t *) item); 579 free(item); 580 } 581 } 582 583 static void daemon_sdp_close_connection(client_state_t * daemon_client){ 584 btstack_linked_list_t * list = &daemon_client->sdp_record_handles; 585 btstack_linked_list_iterator_t it; 586 btstack_linked_list_iterator_init(&it, list); 587 while (btstack_linked_list_iterator_has_next(&it)){ 588 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 589 sdp_unregister_service(item->value); 590 btstack_linked_list_remove(list, (btstack_linked_item_t *) item); 591 free(item); 592 } 593 } 594 595 static connection_t * connection_for_l2cap_cid(uint16_t cid){ 596 btstack_linked_list_iterator_t cl; 597 btstack_linked_list_iterator_init(&cl, &clients); 598 while (btstack_linked_list_iterator_has_next(&cl)){ 599 client_state_t * client_state = (client_state_t *) btstack_linked_list_iterator_next(&cl); 600 btstack_linked_list_iterator_t it; 601 btstack_linked_list_iterator_init(&it, &client_state->l2cap_cids); 602 while (btstack_linked_list_iterator_has_next(&it)){ 603 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 604 if (item->value == cid){ 605 return client_state->connection; 606 } 607 } 608 } 609 return NULL; 610 } 611 612 static const uint8_t removeServiceRecordHandleAttributeIDList[] = { 0x36, 0x00, 0x05, 0x0A, 0x00, 0x01, 0xFF, 0xFF }; 613 614 // register a service record 615 // pre: AttributeIDs are in ascending order 616 // pre: ServiceRecordHandle is first attribute and is not already registered in database 617 // @returns status 618 static uint32_t daemon_sdp_create_and_register_service(uint8_t * record){ 619 620 // create new handle 621 uint32_t record_handle = sdp_create_service_record_handle(); 622 623 // calculate size of new service record: DES (2 byte len) 624 // + ServiceRecordHandle attribute (UINT16 UINT32) + size of existing attributes 625 uint16_t recordSize = 3 + (3 + 5) + de_get_data_size(record); 626 627 // alloc memory for new service record 628 uint8_t * newRecord = malloc(recordSize); 629 if (!newRecord) return 0; 630 631 // create DES for new record 632 de_create_sequence(newRecord); 633 634 // set service record handle 635 de_add_number(newRecord, DE_UINT, DE_SIZE_16, 0); 636 de_add_number(newRecord, DE_UINT, DE_SIZE_32, record_handle); 637 638 // add other attributes 639 sdp_append_attributes_in_attributeIDList(record, (uint8_t *) removeServiceRecordHandleAttributeIDList, 0, recordSize, newRecord); 640 641 uint8_t status = sdp_register_service(newRecord); 642 643 if (status) { 644 free(newRecord); 645 return 0; 646 } 647 648 return record_handle; 649 } 650 651 static connection_t * connection_for_rfcomm_cid(uint16_t cid){ 652 btstack_linked_list_iterator_t cl; 653 btstack_linked_list_iterator_init(&cl, &clients); 654 while (btstack_linked_list_iterator_has_next(&cl)){ 655 client_state_t * client_state = (client_state_t *) btstack_linked_list_iterator_next(&cl); 656 btstack_linked_list_iterator_t it; 657 btstack_linked_list_iterator_init(&it, &client_state->rfcomm_cids); 658 while (btstack_linked_list_iterator_has_next(&it)){ 659 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 660 if (item->value == cid){ 661 return client_state->connection; 662 } 663 } 664 } 665 return NULL; 666 } 667 668 #ifdef ENABLE_BLE 669 static void daemon_gatt_client_close_connection(connection_t * connection){ 670 client_state_t * client = client_for_connection(connection); 671 if (!client) return; 672 673 btstack_linked_list_iterator_t it; 674 btstack_linked_list_iterator_init(&it, &client->gatt_con_handles); 675 while (btstack_linked_list_iterator_has_next(&it)){ 676 btstack_linked_list_uint32_t * item = (btstack_linked_list_uint32_t*) btstack_linked_list_iterator_next(&it); 677 daemon_remove_gatt_client_handle(connection, item->value); 678 } 679 } 680 #endif 681 682 static void daemon_disconnect_client(connection_t * connection){ 683 log_info("Daemon disconnect client %p\n",connection); 684 685 client_state_t * client = client_for_connection(connection); 686 if (!client) return; 687 688 daemon_sdp_close_connection(client); 689 daemon_rfcomm_close_connection(client); 690 daemon_l2cap_close_connection(client); 691 #ifdef ENABLE_BLE 692 // NOTE: experimental - disconnect all LE connections where GATT Client was used 693 // gatt_client_disconnect_connection(connection); 694 daemon_gatt_client_close_connection(connection); 695 #endif 696 697 btstack_linked_list_remove(&clients, (btstack_linked_item_t *) client); 698 free(client); 699 } 700 701 static void hci_emit_btstack_version(void){ 702 log_info("DAEMON_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR); 703 uint8_t event[6]; 704 event[0] = DAEMON_EVENT_VERSION; 705 event[1] = sizeof(event) - 2; 706 event[2] = BTSTACK_MAJOR; 707 event[3] = BTSTACK_MINOR; 708 little_endian_store_16(event, 4, 3257); // last SVN commit on Google Code + 1 709 socket_connection_send_packet_all(HCI_EVENT_PACKET, 0, event, sizeof(event)); 710 } 711 712 static void hci_emit_system_bluetooth_enabled(uint8_t enabled){ 713 log_info("DAEMON_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled); 714 uint8_t event[3]; 715 event[0] = DAEMON_EVENT_SYSTEM_BLUETOOTH_ENABLED; 716 event[1] = sizeof(event) - 2; 717 event[2] = enabled; 718 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 719 socket_connection_send_packet_all(HCI_EVENT_PACKET, 0, event, sizeof(event)); 720 } 721 722 static void send_l2cap_connection_open_failed(connection_t * connection, bd_addr_t address, uint16_t psm, uint8_t status){ 723 // emit error - see l2cap.c:l2cap_emit_channel_opened(..) 724 uint8_t event[23]; 725 memset(event, 0, sizeof(event)); 726 event[0] = L2CAP_EVENT_CHANNEL_OPENED; 727 event[1] = sizeof(event) - 2; 728 event[2] = status; 729 reverse_bd_addr(address, &event[3]); 730 // little_endian_store_16(event, 9, channel->handle); 731 little_endian_store_16(event, 11, psm); 732 // little_endian_store_16(event, 13, channel->local_cid); 733 // little_endian_store_16(event, 15, channel->remote_cid); 734 // little_endian_store_16(event, 17, channel->local_mtu); 735 // little_endian_store_16(event, 19, channel->remote_mtu); 736 // little_endian_store_16(event, 21, channel->flush_timeout); 737 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 738 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event)); 739 } 740 741 static void l2cap_emit_service_registered(void *connection, uint8_t status, uint16_t psm){ 742 uint8_t event[5]; 743 event[0] = DAEMON_EVENT_L2CAP_SERVICE_REGISTERED; 744 event[1] = sizeof(event) - 2; 745 event[2] = status; 746 little_endian_store_16(event, 3, psm); 747 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 748 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event)); 749 } 750 751 static void rfcomm_emit_service_registered(void *connection, uint8_t status, uint8_t channel){ 752 uint8_t event[4]; 753 event[0] = DAEMON_EVENT_RFCOMM_SERVICE_REGISTERED; 754 event[1] = sizeof(event) - 2; 755 event[2] = status; 756 event[3] = channel; 757 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 758 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event)); 759 } 760 761 static void send_rfcomm_create_channel_failed(void * connection, bd_addr_t addr, uint8_t server_channel, uint8_t status){ 762 // emit error - see rfcom.c:rfcomm_emit_channel_open_failed_outgoing_memory(..) 763 uint8_t event[16]; 764 memset(event, 0, sizeof(event)); 765 uint8_t pos = 0; 766 event[pos++] = RFCOMM_EVENT_CHANNEL_OPENED; 767 event[pos++] = sizeof(event) - 2; 768 event[pos++] = status; 769 reverse_bd_addr(addr, &event[pos]); pos += 6; 770 little_endian_store_16(event, pos, 0); pos += 2; 771 event[pos++] = server_channel; 772 little_endian_store_16(event, pos, 0); pos += 2; // channel ID 773 little_endian_store_16(event, pos, 0); pos += 2; // max frame size 774 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 775 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event)); 776 } 777 778 // data: event(8), len(8), status(8), service_record_handle(32) 779 static void sdp_emit_service_registered(void *connection, uint32_t handle, uint8_t status) { 780 uint8_t event[7]; 781 event[0] = DAEMON_EVENT_SDP_SERVICE_REGISTERED; 782 event[1] = sizeof(event) - 2; 783 event[2] = status; 784 little_endian_store_32(event, 3, handle); 785 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 786 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event)); 787 } 788 789 #ifdef ENABLE_BLE 790 791 btstack_linked_list_gatt_client_helper_t * daemon_get_gatt_client_helper(hci_con_handle_t con_handle) { 792 btstack_linked_list_iterator_t it; 793 if (!gatt_client_helpers) return NULL; 794 log_info("daemon_get_gatt_client_helper for handle 0x%02x", con_handle); 795 796 btstack_linked_list_iterator_init(&it, &gatt_client_helpers); 797 while (btstack_linked_list_iterator_has_next(&it)){ 798 btstack_linked_list_gatt_client_helper_t * item = (btstack_linked_list_gatt_client_helper_t*) btstack_linked_list_iterator_next(&it); 799 if (!item ) { 800 log_info("daemon_get_gatt_client_helper gatt_client_helpers null item"); 801 break; 802 } 803 if (item->con_handle == con_handle){ 804 return item; 805 } 806 } 807 log_info("daemon_get_gatt_client_helper for handle 0x%02x is NULL.", con_handle); 808 return NULL; 809 } 810 811 static void send_gatt_query_complete(connection_t * connection, hci_con_handle_t con_handle, uint8_t status){ 812 // @format H1 813 uint8_t event[5]; 814 event[0] = GATT_EVENT_QUERY_COMPLETE; 815 event[1] = 3; 816 little_endian_store_16(event, 2, con_handle); 817 event[4] = status; 818 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 819 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event)); 820 } 821 822 static void send_gatt_mtu_event(connection_t * connection, hci_con_handle_t con_handle, uint16_t mtu){ 823 uint8_t event[6]; 824 int pos = 0; 825 event[pos++] = GATT_EVENT_MTU; 826 event[pos++] = sizeof(event) - 2; 827 little_endian_store_16(event, pos, con_handle); 828 pos += 2; 829 little_endian_store_16(event, pos, mtu); 830 pos += 2; 831 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 832 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event)); 833 } 834 835 btstack_linked_list_gatt_client_helper_t * daemon_setup_gatt_client_request(connection_t *connection, uint8_t *packet, int track_active_connection) { 836 hci_con_handle_t con_handle = little_endian_read_16(packet, 3); 837 log_info("daemon_setup_gatt_client_request for handle 0x%02x", con_handle); 838 hci_connection_t * hci_con = hci_connection_for_handle(con_handle); 839 if ((hci_con == NULL) || (hci_con->state != OPEN)){ 840 send_gatt_query_complete(connection, con_handle, GATT_CLIENT_NOT_CONNECTED); 841 return NULL; 842 } 843 844 btstack_linked_list_gatt_client_helper_t * helper = daemon_get_gatt_client_helper(con_handle); 845 846 if (!helper){ 847 log_info("helper does not exist"); 848 helper = calloc(sizeof(btstack_linked_list_gatt_client_helper_t), 1); 849 if (!helper) return NULL; 850 helper->con_handle = con_handle; 851 btstack_linked_list_add(&gatt_client_helpers, (btstack_linked_item_t *) helper); 852 } 853 854 if (track_active_connection && helper->active_connection){ 855 send_gatt_query_complete(connection, con_handle, GATT_CLIENT_BUSY); 856 return NULL; 857 } 858 859 daemon_add_gatt_client_handle(connection, con_handle); 860 861 if (track_active_connection){ 862 // remember connection responsible for this request 863 helper->active_connection = connection; 864 } 865 866 return helper; 867 } 868 869 // (de)serialize structs from/to HCI commands/events 870 871 void daemon_gatt_serialize_service(gatt_client_service_t * service, uint8_t * event, int offset){ 872 little_endian_store_16(event, offset, service->start_group_handle); 873 little_endian_store_16(event, offset+2, service->end_group_handle); 874 reverse_128(service->uuid128, &event[offset + 4]); 875 } 876 877 void daemon_gatt_serialize_characteristic(gatt_client_characteristic_t * characteristic, uint8_t * event, int offset){ 878 little_endian_store_16(event, offset, characteristic->start_handle); 879 little_endian_store_16(event, offset+2, characteristic->value_handle); 880 little_endian_store_16(event, offset+4, characteristic->end_handle); 881 little_endian_store_16(event, offset+6, characteristic->properties); 882 reverse_128(characteristic->uuid128, &event[offset+8]); 883 } 884 885 void daemon_gatt_serialize_characteristic_descriptor(gatt_client_characteristic_descriptor_t * characteristic_descriptor, uint8_t * event, int offset){ 886 little_endian_store_16(event, offset, characteristic_descriptor->handle); 887 reverse_128(characteristic_descriptor->uuid128, &event[offset+2]); 888 } 889 890 #endif 891 892 static int btstack_command_handler(connection_t *connection, uint8_t *packet, uint16_t size){ 893 894 bd_addr_t addr; 895 #ifdef ENABLE_BLE 896 bd_addr_type_t addr_type; 897 hci_con_handle_t handle; 898 #endif 899 uint16_t cid; 900 uint16_t psm; 901 uint16_t service_channel; 902 uint16_t mtu; 903 uint8_t reason; 904 uint8_t rfcomm_channel; 905 uint8_t rfcomm_credits; 906 uint32_t service_record_handle; 907 client_state_t *client; 908 uint8_t status; 909 uint8_t * data; 910 #if defined(HAVE_MALLOC) && defined(ENABLE_BLE) 911 uint8_t uuid128[16]; 912 gatt_client_service_t service; 913 gatt_client_characteristic_t characteristic; 914 gatt_client_characteristic_descriptor_t descriptor; 915 uint16_t data_length; 916 btstack_linked_list_gatt_client_helper_t * gatt_helper; 917 #endif 918 919 uint16_t serviceSearchPatternLen; 920 uint16_t attributeIDListLen; 921 922 // verbose log info before other info to allow for better tracking 923 hci_dump_packet( HCI_COMMAND_DATA_PACKET, 1, packet, size); 924 925 // BTstack internal commands - 16 Bit OpCode, 8 Bit ParamLen, Params... 926 switch (READ_CMD_OCF(packet)){ 927 case BTSTACK_GET_STATE: 928 log_info("BTSTACK_GET_STATE"); 929 hci_emit_state(); 930 break; 931 case BTSTACK_SET_POWER_MODE: 932 log_info("BTSTACK_SET_POWER_MODE %u", packet[3]); 933 // track client power requests 934 client = client_for_connection(connection); 935 if (!client) break; 936 client->power_mode = packet[3]; 937 // handle merged state 938 if (!clients_require_power_on()){ 939 start_power_off_timer(); 940 } else if (!power_management_sleep) { 941 stop_power_off_timer(); 942 hci_power_control(HCI_POWER_ON); 943 } 944 break; 945 case BTSTACK_GET_VERSION: 946 log_info("BTSTACK_GET_VERSION"); 947 hci_emit_btstack_version(); 948 break; 949 #ifdef HAVE_PLATFORM_IPHONE_OS 950 case BTSTACK_SET_SYSTEM_BLUETOOTH_ENABLED: 951 log_info("BTSTACK_SET_SYSTEM_BLUETOOTH_ENABLED %u", packet[3]); 952 btstack_control_iphone_bt_set_enabled(packet[3]); 953 hci_emit_system_bluetooth_enabled(btstack_control_iphone_bt_enabled()); 954 break; 955 956 case BTSTACK_GET_SYSTEM_BLUETOOTH_ENABLED: 957 log_info("BTSTACK_GET_SYSTEM_BLUETOOTH_ENABLED"); 958 hci_emit_system_bluetooth_enabled(btstack_control_iphone_bt_enabled()); 959 break; 960 #else 961 case BTSTACK_SET_SYSTEM_BLUETOOTH_ENABLED: 962 case BTSTACK_GET_SYSTEM_BLUETOOTH_ENABLED: 963 hci_emit_system_bluetooth_enabled(0); 964 break; 965 #endif 966 case BTSTACK_SET_DISCOVERABLE: 967 log_info("BTSTACK_SET_DISCOVERABLE discoverable %u)", packet[3]); 968 // track client discoverable requests 969 client = client_for_connection(connection); 970 if (!client) break; 971 client->discoverable = packet[3]; 972 // merge state 973 gap_discoverable_control(clients_require_discoverable()); 974 break; 975 case BTSTACK_SET_BLUETOOTH_ENABLED: 976 log_info("BTSTACK_SET_BLUETOOTH_ENABLED: %u\n", packet[3]); 977 if (packet[3]) { 978 // global enable 979 global_enable = 1; 980 hci_power_control(HCI_POWER_ON); 981 } else { 982 global_enable = 0; 983 clients_clear_power_request(); 984 hci_power_control(HCI_POWER_OFF); 985 } 986 break; 987 case L2CAP_CREATE_CHANNEL_MTU: 988 reverse_bd_addr(&packet[3], addr); 989 psm = little_endian_read_16(packet, 9); 990 mtu = little_endian_read_16(packet, 11); 991 status = l2cap_create_channel(NULL, addr, psm, mtu, &cid); 992 if (status){ 993 send_l2cap_connection_open_failed(connection, addr, psm, status); 994 } else { 995 daemon_add_client_l2cap_channel(connection, cid); 996 } 997 break; 998 case L2CAP_CREATE_CHANNEL: 999 reverse_bd_addr(&packet[3], addr); 1000 psm = little_endian_read_16(packet, 9); 1001 mtu = 150; // until r865 1002 status = l2cap_create_channel(NULL, addr, psm, mtu, &cid); 1003 if (status){ 1004 send_l2cap_connection_open_failed(connection, addr, psm, status); 1005 } else { 1006 daemon_add_client_l2cap_channel(connection, cid); 1007 } 1008 break; 1009 case L2CAP_DISCONNECT: 1010 cid = little_endian_read_16(packet, 3); 1011 reason = packet[5]; 1012 l2cap_disconnect(cid, reason); 1013 break; 1014 case L2CAP_REGISTER_SERVICE: 1015 psm = little_endian_read_16(packet, 3); 1016 mtu = little_endian_read_16(packet, 5); 1017 status = l2cap_register_service(NULL, psm, mtu, LEVEL_0); 1018 daemon_add_client_l2cap_service(connection, little_endian_read_16(packet, 3)); 1019 l2cap_emit_service_registered(connection, status, psm); 1020 break; 1021 case L2CAP_UNREGISTER_SERVICE: 1022 psm = little_endian_read_16(packet, 3); 1023 daemon_remove_client_l2cap_service(connection, psm); 1024 l2cap_unregister_service(psm); 1025 break; 1026 case L2CAP_ACCEPT_CONNECTION: 1027 cid = little_endian_read_16(packet, 3); 1028 l2cap_accept_connection(cid); 1029 break; 1030 case L2CAP_DECLINE_CONNECTION: 1031 cid = little_endian_read_16(packet, 3); 1032 reason = packet[7]; 1033 l2cap_decline_connection(cid); 1034 break; 1035 case RFCOMM_CREATE_CHANNEL: 1036 reverse_bd_addr(&packet[3], addr); 1037 rfcomm_channel = packet[9]; 1038 status = rfcomm_create_channel(&rfcomm_packet_handler, addr, rfcomm_channel, &cid); 1039 if (status){ 1040 send_rfcomm_create_channel_failed(connection, addr, rfcomm_channel, status); 1041 } else { 1042 daemon_add_client_rfcomm_channel(connection, cid); 1043 } 1044 break; 1045 case RFCOMM_CREATE_CHANNEL_WITH_CREDITS: 1046 reverse_bd_addr(&packet[3], addr); 1047 rfcomm_channel = packet[9]; 1048 rfcomm_credits = packet[10]; 1049 status = rfcomm_create_channel_with_initial_credits(&rfcomm_packet_handler, addr, rfcomm_channel, rfcomm_credits, &cid ); 1050 if (status){ 1051 send_rfcomm_create_channel_failed(connection, addr, rfcomm_channel, status); 1052 } else { 1053 daemon_add_client_rfcomm_channel(connection, cid); 1054 } 1055 break; 1056 case RFCOMM_DISCONNECT: 1057 cid = little_endian_read_16(packet, 3); 1058 reason = packet[5]; 1059 rfcomm_disconnect(cid); 1060 break; 1061 case RFCOMM_REGISTER_SERVICE: 1062 rfcomm_channel = packet[3]; 1063 mtu = little_endian_read_16(packet, 4); 1064 status = rfcomm_register_service(&rfcomm_packet_handler, rfcomm_channel, mtu); 1065 rfcomm_emit_service_registered(connection, status, rfcomm_channel); 1066 break; 1067 case RFCOMM_REGISTER_SERVICE_WITH_CREDITS: 1068 rfcomm_channel = packet[3]; 1069 mtu = little_endian_read_16(packet, 4); 1070 rfcomm_credits = packet[6]; 1071 status = rfcomm_register_service_with_initial_credits(&rfcomm_packet_handler, rfcomm_channel, mtu, rfcomm_credits); 1072 rfcomm_emit_service_registered(connection, status, rfcomm_channel); 1073 break; 1074 case RFCOMM_UNREGISTER_SERVICE: 1075 service_channel = little_endian_read_16(packet, 3); 1076 daemon_remove_client_rfcomm_service(connection, service_channel); 1077 rfcomm_unregister_service(service_channel); 1078 break; 1079 case RFCOMM_ACCEPT_CONNECTION: 1080 cid = little_endian_read_16(packet, 3); 1081 rfcomm_accept_connection(cid); 1082 break; 1083 case RFCOMM_DECLINE_CONNECTION: 1084 cid = little_endian_read_16(packet, 3); 1085 reason = packet[7]; 1086 rfcomm_decline_connection(cid); 1087 break; 1088 case RFCOMM_GRANT_CREDITS: 1089 cid = little_endian_read_16(packet, 3); 1090 rfcomm_credits = packet[5]; 1091 rfcomm_grant_credits(cid, rfcomm_credits); 1092 break; 1093 case RFCOMM_PERSISTENT_CHANNEL: { 1094 // enforce \0 1095 packet[3+248] = 0; 1096 rfcomm_channel = rfcomm_service_db_channel_for_service((char*)&packet[3]); 1097 log_info("DAEMON_EVENT_RFCOMM_PERSISTENT_CHANNEL %u", rfcomm_channel); 1098 uint8_t event[4]; 1099 event[0] = DAEMON_EVENT_RFCOMM_PERSISTENT_CHANNEL; 1100 event[1] = sizeof(event) - 2; 1101 event[2] = 0; 1102 event[3] = rfcomm_channel; 1103 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 1104 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, (uint8_t *) event, sizeof(event)); 1105 break; 1106 } 1107 case SDP_REGISTER_SERVICE_RECORD: 1108 log_info("SDP_REGISTER_SERVICE_RECORD size %u\n", size); 1109 service_record_handle = daemon_sdp_create_and_register_service(&packet[3]); 1110 if (service_record_handle){ 1111 daemon_add_client_sdp_service_record_handle(connection, service_record_handle); 1112 sdp_emit_service_registered(connection, service_record_handle, 0); 1113 } else { 1114 sdp_emit_service_registered(connection, 0, BTSTACK_MEMORY_ALLOC_FAILED); 1115 } 1116 break; 1117 case SDP_UNREGISTER_SERVICE_RECORD: 1118 service_record_handle = little_endian_read_32(packet, 3); 1119 log_info("SDP_UNREGISTER_SERVICE_RECORD handle 0x%x ", service_record_handle); 1120 data = sdp_get_record_for_handle(service_record_handle); 1121 sdp_unregister_service(service_record_handle); 1122 daemon_remove_client_sdp_service_record_handle(connection, service_record_handle); 1123 if (data){ 1124 free(data); 1125 } 1126 break; 1127 case SDP_CLIENT_QUERY_RFCOMM_SERVICES: 1128 reverse_bd_addr(&packet[3], addr); 1129 1130 serviceSearchPatternLen = de_get_len(&packet[9]); 1131 memcpy(serviceSearchPattern, &packet[9], serviceSearchPatternLen); 1132 1133 sdp_client_query_connection = connection; 1134 sdp_client_query_rfcomm_channel_and_name_for_search_pattern(&handle_sdp_rfcomm_service_result, addr, serviceSearchPattern); 1135 1136 break; 1137 case SDP_CLIENT_QUERY_SERVICES: 1138 reverse_bd_addr(&packet[3], addr); 1139 sdp_client_query_connection = connection; 1140 1141 serviceSearchPatternLen = de_get_len(&packet[9]); 1142 memcpy(serviceSearchPattern, &packet[9], serviceSearchPatternLen); 1143 1144 attributeIDListLen = de_get_len(&packet[9+serviceSearchPatternLen]); 1145 memcpy(attributeIDList, &packet[9+serviceSearchPatternLen], attributeIDListLen); 1146 1147 sdp_client_query(&handle_sdp_client_query_result, addr, (uint8_t*)&serviceSearchPattern[0], (uint8_t*)&attributeIDList[0]); 1148 break; 1149 #ifdef ENABLE_BLE 1150 case GAP_LE_SCAN_START: 1151 gap_start_scan(); 1152 break; 1153 case GAP_LE_SCAN_STOP: 1154 gap_stop_scan(); 1155 break; 1156 case GAP_LE_SET_SCAN_PARAMETERS: 1157 gap_set_scan_parameters(packet[3], little_endian_read_16(packet, 4), little_endian_read_16(packet, 6)); 1158 break; 1159 case GAP_LE_CONNECT: 1160 reverse_bd_addr(&packet[4], addr); 1161 addr_type = packet[3]; 1162 gap_connect(addr, addr_type); 1163 break; 1164 case GAP_LE_CONNECT_CANCEL: 1165 gap_connect_cancel(); 1166 break; 1167 case GAP_DISCONNECT: 1168 handle = little_endian_read_16(packet, 3); 1169 gap_disconnect(handle); 1170 break; 1171 #endif 1172 #if defined(HAVE_MALLOC) && defined(ENABLE_BLE) 1173 case GATT_DISCOVER_ALL_PRIMARY_SERVICES: 1174 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1175 if (!gatt_helper) break; 1176 gatt_client_discover_primary_services(&handle_gatt_client_event, gatt_helper->con_handle); 1177 break; 1178 case GATT_DISCOVER_PRIMARY_SERVICES_BY_UUID16: 1179 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1180 if (!gatt_helper) break; 1181 gatt_client_discover_primary_services_by_uuid16(&handle_gatt_client_event, gatt_helper->con_handle, little_endian_read_16(packet, 5)); 1182 break; 1183 case GATT_DISCOVER_PRIMARY_SERVICES_BY_UUID128: 1184 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1185 if (!gatt_helper) break; 1186 reverse_128(&packet[5], uuid128); 1187 gatt_client_discover_primary_services_by_uuid128(&handle_gatt_client_event, gatt_helper->con_handle, uuid128); 1188 break; 1189 case GATT_FIND_INCLUDED_SERVICES_FOR_SERVICE: 1190 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1191 if (!gatt_helper) break; 1192 gatt_client_deserialize_service(packet, 5, &service); 1193 gatt_client_find_included_services_for_service(&handle_gatt_client_event, gatt_helper->con_handle, &service); 1194 break; 1195 1196 case GATT_DISCOVER_CHARACTERISTICS_FOR_SERVICE: 1197 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1198 if (!gatt_helper) break; 1199 gatt_client_deserialize_service(packet, 5, &service); 1200 gatt_client_discover_characteristics_for_service(&handle_gatt_client_event, gatt_helper->con_handle, &service); 1201 break; 1202 case GATT_DISCOVER_CHARACTERISTICS_FOR_SERVICE_BY_UUID128: 1203 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1204 if (!gatt_helper) break; 1205 gatt_client_deserialize_service(packet, 5, &service); 1206 reverse_128(&packet[5 + SERVICE_LENGTH], uuid128); 1207 gatt_client_discover_characteristics_for_service_by_uuid128(&handle_gatt_client_event, gatt_helper->con_handle, &service, uuid128); 1208 break; 1209 case GATT_DISCOVER_CHARACTERISTIC_DESCRIPTORS: 1210 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1211 if (!gatt_helper) break; 1212 gatt_client_deserialize_characteristic(packet, 5, &characteristic); 1213 gatt_client_discover_characteristic_descriptors(&handle_gatt_client_event, gatt_helper->con_handle, &characteristic); 1214 break; 1215 1216 case GATT_READ_VALUE_OF_CHARACTERISTIC: 1217 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1218 if (!gatt_helper) break; 1219 gatt_client_deserialize_characteristic(packet, 5, &characteristic); 1220 gatt_client_read_value_of_characteristic(&handle_gatt_client_event, gatt_helper->con_handle, &characteristic); 1221 break; 1222 case GATT_READ_LONG_VALUE_OF_CHARACTERISTIC: 1223 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1224 if (!gatt_helper) break; 1225 gatt_client_deserialize_characteristic(packet, 5, &characteristic); 1226 gatt_client_read_long_value_of_characteristic(&handle_gatt_client_event, gatt_helper->con_handle, &characteristic); 1227 break; 1228 1229 case GATT_WRITE_VALUE_OF_CHARACTERISTIC_WITHOUT_RESPONSE: 1230 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 0); // note: don't track active connection 1231 if (!gatt_helper) break; 1232 gatt_client_deserialize_characteristic(packet, 5, &characteristic); 1233 data_length = little_endian_read_16(packet, 5 + CHARACTERISTIC_LENGTH); 1234 data = gatt_helper->characteristic_buffer; 1235 memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length); 1236 gatt_client_write_value_of_characteristic_without_response(gatt_helper->con_handle, characteristic.value_handle, data_length, data); 1237 break; 1238 case GATT_WRITE_VALUE_OF_CHARACTERISTIC: 1239 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1240 if (!gatt_helper) break; 1241 gatt_client_deserialize_characteristic(packet, 5, &characteristic); 1242 data_length = little_endian_read_16(packet, 5 + CHARACTERISTIC_LENGTH); 1243 data = gatt_helper->characteristic_buffer; 1244 memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length); 1245 gatt_client_write_value_of_characteristic(&handle_gatt_client_event, gatt_helper->con_handle, characteristic.value_handle, data_length, data); 1246 break; 1247 case GATT_WRITE_LONG_VALUE_OF_CHARACTERISTIC: 1248 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1249 if (!gatt_helper) break; 1250 gatt_client_deserialize_characteristic(packet, 5, &characteristic); 1251 data_length = little_endian_read_16(packet, 5 + CHARACTERISTIC_LENGTH); 1252 data = gatt_helper->characteristic_buffer; 1253 memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length); 1254 gatt_client_write_long_value_of_characteristic(&handle_gatt_client_event, gatt_helper->con_handle, characteristic.value_handle, data_length, data); 1255 break; 1256 case GATT_RELIABLE_WRITE_LONG_VALUE_OF_CHARACTERISTIC: 1257 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1258 if (!gatt_helper) break; 1259 gatt_client_deserialize_characteristic(packet, 5, &characteristic); 1260 data_length = little_endian_read_16(packet, 5 + CHARACTERISTIC_LENGTH); 1261 data = gatt_helper->characteristic_buffer; 1262 memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length); 1263 gatt_client_write_long_value_of_characteristic(&handle_gatt_client_event, gatt_helper->con_handle, characteristic.value_handle, data_length, data); 1264 break; 1265 case GATT_READ_CHARACTERISTIC_DESCRIPTOR: 1266 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1267 if (!gatt_helper) break; 1268 handle = little_endian_read_16(packet, 3); 1269 gatt_client_deserialize_characteristic_descriptor(packet, 5, &descriptor); 1270 gatt_client_read_characteristic_descriptor(&handle_gatt_client_event, gatt_helper->con_handle, &descriptor); 1271 break; 1272 case GATT_READ_LONG_CHARACTERISTIC_DESCRIPTOR: 1273 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1274 if (!gatt_helper) break; 1275 gatt_client_deserialize_characteristic_descriptor(packet, 5, &descriptor); 1276 gatt_client_read_long_characteristic_descriptor(&handle_gatt_client_event, gatt_helper->con_handle, &descriptor); 1277 break; 1278 1279 case GATT_WRITE_CHARACTERISTIC_DESCRIPTOR: 1280 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1281 if (!gatt_helper) break; 1282 gatt_client_deserialize_characteristic_descriptor(packet, 5, &descriptor); 1283 data = gatt_helper->characteristic_buffer; 1284 data_length = little_endian_read_16(packet, 5 + CHARACTERISTIC_DESCRIPTOR_LENGTH); 1285 gatt_client_write_characteristic_descriptor(&handle_gatt_client_event, gatt_helper->con_handle, &descriptor, data_length, data); 1286 break; 1287 case GATT_WRITE_LONG_CHARACTERISTIC_DESCRIPTOR: 1288 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1289 if (!gatt_helper) break; 1290 gatt_client_deserialize_characteristic_descriptor(packet, 5, &descriptor); 1291 data = gatt_helper->characteristic_buffer; 1292 data_length = little_endian_read_16(packet, 5 + CHARACTERISTIC_DESCRIPTOR_LENGTH); 1293 gatt_client_write_long_characteristic_descriptor(&handle_gatt_client_event, gatt_helper->con_handle, &descriptor, data_length, data); 1294 break; 1295 case GATT_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION:{ 1296 uint16_t configuration = little_endian_read_16(packet, 5 + CHARACTERISTIC_LENGTH); 1297 gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1); 1298 if (!gatt_helper) break; 1299 data = gatt_helper->characteristic_buffer; 1300 gatt_client_deserialize_characteristic(packet, 5, &characteristic); 1301 gatt_client_write_client_characteristic_configuration(&handle_gatt_client_event, gatt_helper->con_handle, &characteristic, configuration); 1302 break; 1303 case GATT_GET_MTU: 1304 handle = little_endian_read_16(packet, 3); 1305 gatt_client_get_mtu(handle, &mtu); 1306 send_gatt_mtu_event(connection, handle, mtu); 1307 break; 1308 } 1309 #endif 1310 default: 1311 log_error("Error: command %u not implemented:", READ_CMD_OCF(packet)); 1312 break; 1313 } 1314 1315 return 0; 1316 } 1317 1318 static int daemon_client_handler(connection_t *connection, uint16_t packet_type, uint16_t channel, uint8_t *data, uint16_t length){ 1319 1320 int err = 0; 1321 client_state_t * client; 1322 1323 switch (packet_type){ 1324 case HCI_COMMAND_DATA_PACKET: 1325 if (READ_CMD_OGF(data) != OGF_BTSTACK) { 1326 // HCI Command 1327 hci_send_cmd_packet(data, length); 1328 } else { 1329 // BTstack command 1330 btstack_command_handler(connection, data, length); 1331 } 1332 break; 1333 case L2CAP_DATA_PACKET: 1334 // process l2cap packet... 1335 err = l2cap_send(channel, data, length); 1336 break; 1337 case RFCOMM_DATA_PACKET: 1338 // process l2cap packet... 1339 err = rfcomm_send(channel, data, length); 1340 break; 1341 case DAEMON_EVENT_PACKET: 1342 switch (data[0]) { 1343 case DAEMON_EVENT_CONNECTION_OPENED: 1344 log_info("DAEMON_EVENT_CONNECTION_OPENED %p\n",connection); 1345 1346 client = calloc(sizeof(client_state_t), 1); 1347 if (!client) break; // fail 1348 client->connection = connection; 1349 client->power_mode = HCI_POWER_OFF; 1350 client->discoverable = 0; 1351 btstack_linked_list_add(&clients, (btstack_linked_item_t *) client); 1352 break; 1353 case DAEMON_EVENT_CONNECTION_CLOSED: 1354 log_info("DAEMON_EVENT_CONNECTION_CLOSED %p\n",connection); 1355 daemon_disconnect_client(connection); 1356 // no clients -> no HCI connections 1357 if (!clients){ 1358 hci_disconnect_all(); 1359 } 1360 1361 // update discoverable mode 1362 gap_discoverable_control(clients_require_discoverable()); 1363 // start power off, if last active client 1364 if (!clients_require_power_on()){ 1365 start_power_off_timer(); 1366 } 1367 break; 1368 default: 1369 break; 1370 } 1371 break; 1372 } 1373 if (err) { 1374 log_info("Daemon Handler: err %d\n", err); 1375 } 1376 return err; 1377 } 1378 1379 1380 static void daemon_set_logging_enabled(int enabled){ 1381 if (enabled && !loggingEnabled){ 1382 hci_dump_open(BTSTACK_LOG_FILE, BTSTACK_LOG_TYPE); 1383 } 1384 if (!enabled && loggingEnabled){ 1385 hci_dump_close(); 1386 } 1387 loggingEnabled = enabled; 1388 } 1389 1390 // local cache used to manage UI status 1391 static HCI_STATE hci_state = HCI_STATE_OFF; 1392 static int num_connections = 0; 1393 static void update_ui_status(void){ 1394 if (hci_state != HCI_STATE_WORKING) { 1395 bluetooth_status_handler(BLUETOOTH_OFF); 1396 } else { 1397 if (num_connections) { 1398 bluetooth_status_handler(BLUETOOTH_ACTIVE); 1399 } else { 1400 bluetooth_status_handler(BLUETOOTH_ON); 1401 } 1402 } 1403 } 1404 1405 #ifdef USE_SPRINGBOARD 1406 static void preferences_changed_callback(void){ 1407 int logging = platform_iphone_logging_enabled(); 1408 log_info("Logging enabled: %u\n", logging); 1409 daemon_set_logging_enabled(logging); 1410 } 1411 #endif 1412 1413 static void deamon_status_event_handler(uint8_t *packet, uint16_t size){ 1414 1415 uint8_t update_status = 0; 1416 1417 // handle state event 1418 switch (hci_event_packet_get_type(packet)) { 1419 case BTSTACK_EVENT_STATE: 1420 hci_state = packet[2]; 1421 log_info("New state: %u\n", hci_state); 1422 update_status = 1; 1423 break; 1424 case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED: 1425 num_connections = packet[2]; 1426 log_info("New nr connections: %u\n", num_connections); 1427 update_status = 1; 1428 break; 1429 default: 1430 break; 1431 } 1432 1433 // choose full bluetooth state 1434 if (update_status) { 1435 update_ui_status(); 1436 } 1437 } 1438 1439 static void daemon_retry_parked(void){ 1440 1441 // socket_connection_retry_parked is not reentrant 1442 static int retry_mutex = 0; 1443 1444 // lock mutex 1445 if (retry_mutex) return; 1446 retry_mutex = 1; 1447 1448 // ... try sending again 1449 socket_connection_retry_parked(); 1450 1451 // unlock mutex 1452 retry_mutex = 0; 1453 } 1454 1455 #if 0 1456 1457 Minimal Code for LE Peripheral 1458 1459 enum { 1460 SET_ADVERTISEMENT_PARAMS = 1 << 0, 1461 SET_ADVERTISEMENT_DATA = 1 << 1, 1462 ENABLE_ADVERTISEMENTS = 1 << 2, 1463 }; 1464 1465 const uint8_t adv_data[] = { 1466 // Flags general discoverable 1467 0x02, 0x01, 0x02, 1468 // Name 1469 0x08, 0x09, 'B', 'T', 's', 't', 'a', 'c', 'k' 1470 }; 1471 uint8_t adv_data_len = sizeof(adv_data); 1472 static uint16_t todos = 0; 1473 1474 static void app_run(void){ 1475 1476 if (!hci_can_send_command_packet_now()) return; 1477 1478 if (todos & SET_ADVERTISEMENT_DATA){ 1479 log_info("app_run: set advertisement data\n"); 1480 todos &= ~SET_ADVERTISEMENT_DATA; 1481 hci_send_cmd(&hci_le_set_advertising_data, adv_data_len, adv_data); 1482 return; 1483 } 1484 1485 if (todos & SET_ADVERTISEMENT_PARAMS){ 1486 todos &= ~SET_ADVERTISEMENT_PARAMS; 1487 uint8_t adv_type = 0; // default 1488 bd_addr_t null_addr; 1489 memset(null_addr, 0, 6); 1490 uint16_t adv_int_min = 0x0030; 1491 uint16_t adv_int_max = 0x0030; 1492 hci_send_cmd(&hci_le_set_advertising_parameters, adv_int_min, adv_int_max, adv_type, 0, 0, &null_addr, 0x07, 0x00); 1493 return; 1494 } 1495 1496 if (todos & ENABLE_ADVERTISEMENTS){ 1497 log_info("app_run: enable advertisements\n"); 1498 todos &= ~ENABLE_ADVERTISEMENTS; 1499 hci_send_cmd(&hci_le_set_advertise_enable, 1); 1500 return; 1501 } 1502 } 1503 #endif 1504 1505 static void daemon_emit_packet(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 1506 if (connection) { 1507 socket_connection_send_packet(connection, packet_type, channel, packet, size); 1508 } else { 1509 socket_connection_send_packet_all(packet_type, channel, packet, size); 1510 } 1511 } 1512 1513 static uint8_t remote_name_event[2+1+6+DEVICE_NAME_LEN+1]; // +1 for \0 in log_info 1514 static void daemon_packet_handler(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 1515 uint16_t cid; 1516 int i; 1517 bd_addr_t addr; 1518 switch (packet_type) { 1519 case HCI_EVENT_PACKET: 1520 deamon_status_event_handler(packet, size); 1521 switch (hci_event_packet_get_type(packet)){ 1522 1523 case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS: 1524 // ACL buffer freed... 1525 daemon_retry_parked(); 1526 // no need to tell clients 1527 return; 1528 1529 case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE: 1530 if (!btstack_device_name_db) break; 1531 if (packet[2]) break; // status not ok 1532 1533 reverse_bd_addr(&packet[3], addr); 1534 // fix for invalid remote names - terminate on 0xff 1535 for (i=0; i<248;i++){ 1536 if (packet[9+i] == 0xff){ 1537 packet[9+i] = 0; 1538 break; 1539 } 1540 } 1541 packet[9+248] = 0; 1542 btstack_device_name_db->put_name(addr, (device_name_t *)&packet[9]); 1543 break; 1544 1545 case HCI_EVENT_INQUIRY_RESULT: 1546 case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:{ 1547 if (!btstack_device_name_db) break; 1548 1549 // first send inq result packet 1550 daemon_emit_packet(connection, packet_type, channel, packet, size); 1551 1552 // then send cached remote names 1553 int offset = 3; 1554 for (i=0; i<packet[2];i++){ 1555 reverse_bd_addr(&packet[offset], addr); 1556 if (btstack_device_name_db->get_name(addr, (device_name_t *) &remote_name_event[9])){ 1557 remote_name_event[0] = DAEMON_EVENT_REMOTE_NAME_CACHED; 1558 remote_name_event[1] = sizeof(remote_name_event) - 2 - 1; 1559 remote_name_event[2] = 0; // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE 1560 reverse_bd_addr(addr, &remote_name_event[3]); 1561 1562 remote_name_event[9+248] = 0; // assert \0 for log_info 1563 log_info("DAEMON_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(addr), &remote_name_event[9]); 1564 hci_dump_packet(HCI_EVENT_PACKET, 0, remote_name_event, sizeof(remote_name_event)-1); 1565 daemon_emit_packet(connection, HCI_EVENT_PACKET, channel, remote_name_event, sizeof(remote_name_event) -1); 1566 } 1567 offset += 14; // 6 + 1 + 1 + 1 + 3 + 2; 1568 } 1569 return; 1570 } 1571 1572 case DAEMON_EVENT_RFCOMM_CREDITS: 1573 // RFCOMM CREDITS received... 1574 daemon_retry_parked(); 1575 break; 1576 1577 case RFCOMM_EVENT_CHANNEL_OPENED: 1578 cid = little_endian_read_16(packet, 13); 1579 connection = connection_for_rfcomm_cid(cid); 1580 if (!connection) break; 1581 if (packet[2]) { 1582 daemon_remove_client_rfcomm_channel(connection, cid); 1583 } else { 1584 daemon_add_client_rfcomm_channel(connection, cid); 1585 } 1586 break; 1587 case RFCOMM_EVENT_CHANNEL_CLOSED: 1588 cid = little_endian_read_16(packet, 2); 1589 connection = connection_for_rfcomm_cid(cid); 1590 if (!connection) break; 1591 daemon_remove_client_rfcomm_channel(connection, cid); 1592 break; 1593 case DAEMON_EVENT_RFCOMM_SERVICE_REGISTERED: 1594 if (packet[2]) break; 1595 daemon_add_client_rfcomm_service(connection, packet[3]); 1596 break; 1597 case L2CAP_EVENT_CHANNEL_OPENED: 1598 cid = little_endian_read_16(packet, 13); 1599 connection = connection_for_l2cap_cid(cid); 1600 if (!connection) break; 1601 if (packet[2]) { 1602 daemon_remove_client_l2cap_channel(connection, cid); 1603 } else { 1604 daemon_add_client_l2cap_channel(connection, cid); 1605 } 1606 break; 1607 case L2CAP_EVENT_CHANNEL_CLOSED: 1608 cid = little_endian_read_16(packet, 2); 1609 connection = connection_for_l2cap_cid(cid); 1610 if (!connection) break; 1611 daemon_remove_client_l2cap_channel(connection, cid); 1612 break; 1613 #if defined(ENABLE_BLE) && defined(HAVE_MALLOC) 1614 case HCI_EVENT_DISCONNECTION_COMPLETE: 1615 log_info("daemon : ignore HCI_EVENT_DISCONNECTION_COMPLETE ingnoring."); 1616 // note: moved to gatt_client_handler because it's received here prematurely 1617 // daemon_remove_gatt_client_helper(little_endian_read_16(packet, 3)); 1618 break; 1619 #endif 1620 default: 1621 break; 1622 } 1623 break; 1624 case L2CAP_DATA_PACKET: 1625 connection = connection_for_l2cap_cid(channel); 1626 if (!connection) return; 1627 break; 1628 case RFCOMM_DATA_PACKET: 1629 connection = connection_for_l2cap_cid(channel); 1630 if (!connection) return; 1631 break; 1632 default: 1633 break; 1634 } 1635 1636 daemon_emit_packet(connection, packet_type, channel, packet, size); 1637 } 1638 1639 static void l2cap_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){ 1640 daemon_packet_handler(NULL, packet_type, channel, packet, size); 1641 } 1642 static void rfcomm_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){ 1643 daemon_packet_handler(NULL, packet_type, channel, packet, size); 1644 } 1645 1646 static void handle_sdp_rfcomm_service_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 1647 switch (hci_event_packet_get_type(packet)){ 1648 case SDP_EVENT_QUERY_RFCOMM_SERVICE: 1649 case SDP_EVENT_QUERY_COMPLETE: 1650 // already HCI Events, just forward them 1651 hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size); 1652 socket_connection_send_packet(sdp_client_query_connection, HCI_EVENT_PACKET, 0, packet, size); 1653 break; 1654 default: 1655 break; 1656 } 1657 } 1658 1659 static void sdp_client_assert_buffer(int size){ 1660 if (size > attribute_value_buffer_size){ 1661 log_error("SDP attribute value buffer size exceeded: available %d, required %d", attribute_value_buffer_size, size); 1662 } 1663 } 1664 1665 // define new packet type SDP_CLIENT_PACKET 1666 static void handle_sdp_client_query_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 1667 int event_len; 1668 1669 switch (hci_event_packet_get_type(packet)){ 1670 case SDP_EVENT_QUERY_ATTRIBUTE_BYTE: 1671 sdp_client_assert_buffer(sdp_event_query_attribute_byte_get_attribute_length(packet)); 1672 attribute_value[sdp_event_query_attribute_byte_get_data_offset(packet)] = sdp_event_query_attribute_byte_get_data(packet); 1673 if ((uint16_t)(sdp_event_query_attribute_byte_get_data_offset(packet)+1) == sdp_event_query_attribute_byte_get_attribute_length(packet)){ 1674 log_info_hexdump(attribute_value, sdp_event_query_attribute_byte_get_attribute_length(packet)); 1675 1676 int event_len = 1 + 3 * 2 + sdp_event_query_attribute_byte_get_attribute_length(packet); 1677 uint8_t event[event_len]; 1678 event[0] = SDP_EVENT_QUERY_ATTRIBUTE_VALUE; 1679 little_endian_store_16(event, 1, sdp_event_query_attribute_byte_get_record_id(packet)); 1680 little_endian_store_16(event, 3, sdp_event_query_attribute_byte_get_attribute_id(packet)); 1681 little_endian_store_16(event, 5, (uint16_t)sdp_event_query_attribute_byte_get_attribute_length(packet)); 1682 memcpy(&event[7], attribute_value, sdp_event_query_attribute_byte_get_attribute_length(packet)); 1683 hci_dump_packet(SDP_CLIENT_PACKET, 0, event, event_len); 1684 socket_connection_send_packet(sdp_client_query_connection, SDP_CLIENT_PACKET, 0, event, event_len); 1685 } 1686 break; 1687 case SDP_EVENT_QUERY_COMPLETE: 1688 event_len = packet[1] + 2; 1689 hci_dump_packet(HCI_EVENT_PACKET, 0, packet, event_len); 1690 socket_connection_send_packet(sdp_client_query_connection, HCI_EVENT_PACKET, 0, packet, event_len); 1691 break; 1692 } 1693 } 1694 1695 static void power_notification_callback(POWER_NOTIFICATION_t notification){ 1696 switch (notification) { 1697 case POWER_WILL_SLEEP: 1698 // let's sleep 1699 power_management_sleep = 1; 1700 hci_power_control(HCI_POWER_SLEEP); 1701 break; 1702 case POWER_WILL_WAKE_UP: 1703 // assume that all clients use Bluetooth -> if connection, start Bluetooth 1704 power_management_sleep = 0; 1705 if (clients_require_power_on()) { 1706 hci_power_control(HCI_POWER_ON); 1707 } 1708 break; 1709 default: 1710 break; 1711 } 1712 } 1713 1714 static void daemon_sigint_handler(int param){ 1715 1716 #ifdef HAVE_PLATFORM_IPHONE_OS 1717 // notify daemons 1718 notify_post("ch.ringwald.btstack.stopped"); 1719 #endif 1720 1721 log_info(" <= SIGINT received, shutting down..\n"); 1722 1723 hci_power_control( HCI_POWER_OFF); 1724 hci_close(); 1725 1726 log_info("Good bye, see you.\n"); 1727 1728 exit(0); 1729 } 1730 1731 // MARK: manage power off timer 1732 1733 #define USE_POWER_OFF_TIMER 1734 1735 static void stop_power_off_timer(void){ 1736 #ifdef USE_POWER_OFF_TIMER 1737 if (timeout_active) { 1738 btstack_run_loop_remove_timer(&timeout); 1739 timeout_active = 0; 1740 } 1741 #endif 1742 } 1743 1744 static void start_power_off_timer(void){ 1745 #ifdef USE_POWER_OFF_TIMER 1746 stop_power_off_timer(); 1747 btstack_run_loop_set_timer(&timeout, DAEMON_NO_ACTIVE_CLIENT_TIMEOUT); 1748 btstack_run_loop_add_timer(&timeout); 1749 timeout_active = 1; 1750 #else 1751 hci_power_control(HCI_POWER_OFF); 1752 #endif 1753 } 1754 1755 // MARK: manage list of clients 1756 1757 1758 static client_state_t * client_for_connection(connection_t *connection) { 1759 btstack_linked_item_t *it; 1760 for (it = (btstack_linked_item_t *) clients; it ; it = it->next){ 1761 client_state_t * client_state = (client_state_t *) it; 1762 if (client_state->connection == connection) { 1763 return client_state; 1764 } 1765 } 1766 return NULL; 1767 } 1768 1769 static void clients_clear_power_request(void){ 1770 btstack_linked_item_t *it; 1771 for (it = (btstack_linked_item_t *) clients; it ; it = it->next){ 1772 client_state_t * client_state = (client_state_t *) it; 1773 client_state->power_mode = HCI_POWER_OFF; 1774 } 1775 } 1776 1777 static int clients_require_power_on(void){ 1778 1779 if (global_enable) return 1; 1780 1781 btstack_linked_item_t *it; 1782 for (it = (btstack_linked_item_t *) clients; it ; it = it->next){ 1783 client_state_t * client_state = (client_state_t *) it; 1784 if (client_state->power_mode == HCI_POWER_ON) { 1785 return 1; 1786 } 1787 } 1788 return 0; 1789 } 1790 1791 static int clients_require_discoverable(void){ 1792 btstack_linked_item_t *it; 1793 for (it = (btstack_linked_item_t *) clients; it ; it = it->next){ 1794 client_state_t * client_state = (client_state_t *) it; 1795 if (client_state->discoverable) { 1796 return 1; 1797 } 1798 } 1799 return 0; 1800 } 1801 1802 static void usage(const char * name) { 1803 printf("%s, BTstack background daemon\n", name); 1804 printf("usage: %s [--help] [--tcp]\n", name); 1805 printf(" --help display this usage\n"); 1806 printf(" --tcp use TCP server on port %u\n", BTSTACK_PORT); 1807 printf("Without the --tcp option, BTstack daemon is listening on unix domain socket %s\n\n", BTSTACK_UNIX); 1808 } 1809 1810 #ifdef HAVE_PLATFORM_IPHONE_OS 1811 static void * btstack_run_loop_thread(void *context){ 1812 btstack_run_loop_execute(); 1813 return NULL; 1814 } 1815 #endif 1816 1817 #ifdef ENABLE_BLE 1818 1819 static void handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){ 1820 1821 // hack: handle disconnection_complete_here instead of main hci event packet handler 1822 // we receive a HCI event packet in disguise 1823 if (hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE){ 1824 log_info("daemon hack: handle disconnection_complete in handle_gatt_client_event instead of main hci event packet handler"); 1825 hci_con_handle_t con_handle = little_endian_read_16(packet, 3); 1826 daemon_remove_gatt_client_helper(con_handle); 1827 return; 1828 } 1829 1830 // only handle GATT Events 1831 switch(hci_event_packet_get_type(packet)){ 1832 case GATT_EVENT_SERVICE_QUERY_RESULT: 1833 case GATT_EVENT_INCLUDED_SERVICE_QUERY_RESULT: 1834 case GATT_EVENT_NOTIFICATION: 1835 case GATT_EVENT_INDICATION: 1836 case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT: 1837 case GATT_EVENT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT: 1838 case GATT_EVENT_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT: 1839 case GATT_EVENT_LONG_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT: 1840 case GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT: 1841 case GATT_EVENT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT: 1842 case GATT_EVENT_QUERY_COMPLETE: 1843 break; 1844 default: 1845 return; 1846 } 1847 1848 hci_con_handle_t con_handle = little_endian_read_16(packet, 2); 1849 btstack_linked_list_gatt_client_helper_t * gatt_client_helper = daemon_get_gatt_client_helper(con_handle); 1850 if (!gatt_client_helper){ 1851 log_info("daemon handle_gatt_client_event: gc helper for handle 0x%2x is NULL.", con_handle); 1852 return; 1853 } 1854 1855 connection_t *connection = NULL; 1856 1857 // daemon doesn't track which connection subscribed to this particular handle, so we just notify all connections 1858 switch(hci_event_packet_get_type(packet)){ 1859 case GATT_EVENT_NOTIFICATION: 1860 case GATT_EVENT_INDICATION:{ 1861 hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size); 1862 1863 btstack_linked_item_t *it; 1864 for (it = (btstack_linked_item_t *) clients; it ; it = it->next){ 1865 client_state_t * client_state = (client_state_t *) it; 1866 socket_connection_send_packet(client_state->connection, HCI_EVENT_PACKET, 0, packet, size); 1867 } 1868 return; 1869 } 1870 default: 1871 break; 1872 } 1873 1874 // otherwise, we have to have an active connection 1875 connection = gatt_client_helper->active_connection; 1876 uint16_t offset; 1877 uint16_t length; 1878 1879 if (!connection) return; 1880 1881 switch(hci_event_packet_get_type(packet)){ 1882 1883 case GATT_EVENT_SERVICE_QUERY_RESULT: 1884 case GATT_EVENT_INCLUDED_SERVICE_QUERY_RESULT: 1885 case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT: 1886 case GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT: 1887 case GATT_EVENT_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT: 1888 case GATT_EVENT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT: 1889 hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size); 1890 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, packet, size); 1891 break; 1892 1893 case GATT_EVENT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT: 1894 case GATT_EVENT_LONG_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT: 1895 offset = little_endian_read_16(packet, 6); 1896 length = little_endian_read_16(packet, 8); 1897 gatt_client_helper->characteristic_buffer[0] = hci_event_packet_get_type(packet); // store type (characteristic/descriptor) 1898 gatt_client_helper->characteristic_handle = little_endian_read_16(packet, 4); // store attribute handle 1899 gatt_client_helper->characteristic_length = offset + length; // update length 1900 memcpy(&gatt_client_helper->characteristic_buffer[10 + offset], &packet[10], length); 1901 break; 1902 1903 case GATT_EVENT_QUERY_COMPLETE:{ 1904 gatt_client_helper->active_connection = NULL; 1905 if (gatt_client_helper->characteristic_length){ 1906 // send re-combined long characteristic value or long characteristic descriptor value 1907 uint8_t * event = gatt_client_helper->characteristic_buffer; 1908 uint16_t event_size = 10 + gatt_client_helper->characteristic_length; 1909 // event[0] == already set by previsous case 1910 event[1] = 8 + gatt_client_helper->characteristic_length; 1911 little_endian_store_16(event, 2, little_endian_read_16(packet, 2)); 1912 little_endian_store_16(event, 4, gatt_client_helper->characteristic_handle); 1913 little_endian_store_16(event, 6, 0); // offset 1914 little_endian_store_16(event, 8, gatt_client_helper->characteristic_length); 1915 hci_dump_packet(HCI_EVENT_PACKET, 0, event, event_size); 1916 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, event_size); 1917 gatt_client_helper->characteristic_length = 0; 1918 } 1919 hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size); 1920 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, packet, size); 1921 break; 1922 } 1923 default: 1924 break; 1925 } 1926 } 1927 #endif 1928 1929 static char hostname[30]; 1930 1931 int btstack_server_run(int tcp_flag){ 1932 1933 if (tcp_flag){ 1934 printf("BTstack Daemon started on port %u\n", BTSTACK_PORT); 1935 } else { 1936 printf("BTstack Daemon started on socket %s\n", BTSTACK_UNIX); 1937 } 1938 1939 // make stdout unbuffered 1940 setbuf(stdout, NULL); 1941 1942 // handle CTRL-c 1943 signal(SIGINT, daemon_sigint_handler); 1944 // handle SIGTERM - suggested for launchd 1945 signal(SIGTERM, daemon_sigint_handler); 1946 1947 socket_connection_init(); 1948 1949 btstack_control_t * control = NULL; 1950 void * config = NULL; 1951 const btstack_uart_block_t * uart_block_implementation = NULL; 1952 (void) uart_block_implementation; 1953 1954 #ifdef HAVE_TRANSPORT_H4 1955 hci_transport_config_uart.type = HCI_TRANSPORT_CONFIG_UART; 1956 hci_transport_config_uart.baudrate_init = UART_SPEED; 1957 hci_transport_config_uart.baudrate_main = 0; 1958 hci_transport_config_uart.flowcontrol = 1; 1959 hci_transport_config_uart.device_name = UART_DEVICE; 1960 1961 #ifndef HAVE_PLATFORM_IPHONE_OS 1962 #ifdef _WIN32 1963 uart_block_implementation = btstack_uart_block_windows_instance(); 1964 #else 1965 uart_block_implementation = btstack_uart_block_posix_instance(); 1966 #endif 1967 #endif 1968 1969 #ifdef HAVE_PLATFORM_IPHONE_OS 1970 // use default (max) UART baudrate over netgraph interface 1971 hci_transport_config_uart.baudrate_init = 0; 1972 #endif 1973 1974 config = &hci_transport_config_uart; 1975 transport = hci_transport_h4_instance(uart_block_implementation); 1976 #endif 1977 1978 #ifdef HAVE_TRANSPORT_USB 1979 transport = hci_transport_usb_instance(); 1980 #endif 1981 1982 #ifdef HAVE_PLATFORM_IPHONE_OS 1983 control = &btstack_control_iphone; 1984 if (btstack_control_iphone_power_management_supported()){ 1985 hci_transport_h4_iphone_set_enforce_wake_device("/dev/btwake"); 1986 } 1987 bluetooth_status_handler = platform_iphone_status_handler; 1988 platform_iphone_register_window_manager_restart(update_ui_status); 1989 platform_iphone_register_preferences_changed(preferences_changed_callback); 1990 #endif 1991 1992 #ifdef BTSTACK_LINK_KEY_DB_INSTANCE 1993 btstack_link_key_db = BTSTACK_LINK_KEY_DB_INSTANCE(); 1994 #endif 1995 1996 #ifdef BTSTACK_DEVICE_NAME_DB_INSTANCE 1997 btstack_device_name_db = BTSTACK_DEVICE_NAME_DB_INSTANCE(); 1998 #endif 1999 2000 #ifdef _WIN32 2001 btstack_run_loop_init(btstack_run_loop_windows_get_instance()); 2002 #else 2003 btstack_run_loop_init(btstack_run_loop_posix_get_instance()); 2004 #endif 2005 2006 // init power management notifications 2007 if (control && control->register_for_power_notifications){ 2008 control->register_for_power_notifications(power_notification_callback); 2009 } 2010 2011 // logging 2012 loggingEnabled = 0; 2013 int newLoggingEnabled = 1; 2014 #ifdef HAVE_PLATFORM_IPHONE_OS 2015 // iPhone has toggle in Preferences.app 2016 newLoggingEnabled = platform_iphone_logging_enabled(); 2017 #endif 2018 daemon_set_logging_enabled(newLoggingEnabled); 2019 2020 // dump version 2021 log_info("BTdaemon started\n"); 2022 log_info("version %s, build %s", BTSTACK_VERSION, BTSTACK_DATE); 2023 2024 // init HCI 2025 hci_init(transport, config); 2026 if (btstack_link_key_db){ 2027 hci_set_link_key_db(btstack_link_key_db); 2028 } 2029 if (control){ 2030 hci_set_control(control); 2031 } 2032 2033 // hostname for POSIX systems 2034 gethostname(hostname, 30); 2035 hostname[29] = '\0'; 2036 gap_set_local_name(hostname); 2037 2038 #ifdef HAVE_PLATFORM_IPHONE_OS 2039 // iPhone doesn't use SSP yet as there's no UI for it yet and auto accept is not an option 2040 gap_ssp_set_enable(0); 2041 #endif 2042 2043 // register for HCI events 2044 hci_event_callback_registration.callback = &l2cap_packet_handler; 2045 hci_add_event_handler(&hci_event_callback_registration); 2046 2047 // init L2CAP 2048 l2cap_init(); 2049 l2cap_register_packet_handler(&l2cap_packet_handler); 2050 timeout.process = daemon_no_connections_timeout; 2051 2052 #ifdef ENABLE_RFCOMM 2053 log_info("config.h: ENABLE_RFCOMM\n"); 2054 rfcomm_init(); 2055 #endif 2056 2057 #ifdef ENABLE_SDP 2058 sdp_init(); 2059 #endif 2060 2061 #ifdef ENABLE_BLE 2062 // GATT Client 2063 gatt_client_init(); 2064 2065 // sm_init(); 2066 // sm_set_io_capabilities(IO_CAPABILITY_DISPLAY_ONLY); 2067 // sm_set_authentication_requirements( SM_AUTHREQ_BONDING | SM_AUTHREQ_MITM_PROTECTION); 2068 2069 // GATT Server - empty attribute database 2070 le_device_db_init(); 2071 att_server_init(NULL, NULL, NULL); 2072 2073 #endif 2074 2075 #ifdef USE_LAUNCHD 2076 socket_connection_create_launchd(); 2077 #else 2078 // create server 2079 if (tcp_flag) { 2080 socket_connection_create_tcp(BTSTACK_PORT); 2081 } else { 2082 #ifdef HAVE_UNIX_SOCKETS 2083 socket_connection_create_unix(BTSTACK_UNIX); 2084 #endif 2085 } 2086 #endif 2087 socket_connection_register_packet_callback(&daemon_client_handler); 2088 2089 #ifdef HAVE_PLATFORM_IPHONE_OS 2090 // notify daemons 2091 notify_post("ch.ringwald.btstack.started"); 2092 2093 // spawn thread to have BTstack run loop on new thread, while main thread is used to keep CFRunLoop 2094 pthread_t run_loop; 2095 pthread_create(&run_loop, NULL, &btstack_run_loop_thread, NULL); 2096 2097 // needed to receive notifications 2098 CFRunLoopRun(); 2099 #endif 2100 // go! 2101 btstack_run_loop_execute(); 2102 return 0; 2103 } 2104 2105 2106 2107 int main (int argc, char * const * argv){ 2108 2109 int tcp_flag = 0; 2110 struct option long_options[] = { 2111 { "tcp", no_argument, &tcp_flag, 1 }, 2112 { "help", no_argument, 0, 0 }, 2113 { 0,0,0,0 } // This is a filler for -1 2114 }; 2115 2116 while (1) { 2117 int c; 2118 int option_index = -1; 2119 c = getopt_long(argc, argv, "h", long_options, &option_index); 2120 if (c == -1) break; // no more option 2121 2122 // treat long parameter first 2123 if (option_index == -1) { 2124 switch (c) { 2125 case '?': 2126 case 'h': 2127 usage(argv[0]); 2128 return 0; 2129 break; 2130 } 2131 } else { 2132 switch (option_index) { 2133 case 1: 2134 usage(argv[0]); 2135 return 0; 2136 break; 2137 } 2138 } 2139 } 2140 2141 #ifndef HAVE_UNIX_SOCKETS 2142 // TCP is default if there are no unix sockets 2143 tcp_flag = 1; 2144 #endif 2145 2146 btstack_server_run(tcp_flag); 2147 } 2148