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__ "panu_demo.c" 39 40 /* 41 * panu_demo.c 42 * Author: Ole Reinhardt <[email protected]> 43 */ 44 45 /* EXAMPLE_START(panu_demo): PANU Demo 46 * 47 * @text This example implements both a PANU client and a server. In server mode, it 48 * sets up a BNEP server and registers a PANU SDP record and waits for incoming connections. 49 * In client mode, it connects to a remote device, does an SDP Query to identify the PANU 50 * service and initiates a BNEP connection. 51 */ 52 53 #include "btstack_config.h" 54 55 #include <arpa/inet.h> 56 #include <errno.h> 57 #include <fcntl.h> 58 #include <ifaddrs.h> 59 #include <stdint.h> 60 #include <stdio.h> 61 #include <stdlib.h> 62 #include <string.h> 63 #include <unistd.h> 64 65 #include <net/if_arp.h> 66 67 #ifdef __APPLE__ 68 #include <net/if.h> 69 #include <net/if_types.h> 70 71 #include <netinet/if_ether.h> 72 #include <netinet/in.h> 73 #endif 74 75 #include <sys/ioctl.h> 76 #include <sys/param.h> 77 #include <sys/socket.h> 78 #include <sys/stat.h> 79 #include <sys/types.h> 80 81 #ifdef __linux 82 #include <linux/if.h> 83 #include <linux/if_tun.h> 84 #endif 85 86 #include "btstack.h" 87 88 static int record_id = -1; 89 static uint16_t bnep_l2cap_psm = 0; 90 static uint32_t bnep_remote_uuid = 0; 91 static uint16_t bnep_version = 0; 92 static uint16_t bnep_cid = 0; 93 94 static uint8_t attribute_value[1000]; 95 static const unsigned int attribute_value_buffer_size = sizeof(attribute_value); 96 97 //static bd_addr_t remote = {0x04,0x0C,0xCE,0xE4,0x85,0xD3}; 98 // static bd_addr_t remote = {0xE0,0x06,0xE6,0xBB,0x95,0x79}; // Ole Thinkpad 99 static bd_addr_t remote = {0x84,0x38,0x35,0x65,0xD1,0x15}; // MacBook 2013 100 101 static int tap_fd = -1; 102 static uint8_t network_buffer[BNEP_MTU_MIN]; 103 static size_t network_buffer_len = 0; 104 105 #ifdef __APPLE__ 106 // tuntaposx provides fixed set of tapX devices 107 static const char * tap_dev = "/dev/tap0"; 108 static char tap_dev_name[16] = "tap0"; 109 #endif 110 111 #ifdef __linux 112 // Linux uses single control device to bring up tunX or tapX interface 113 static const char * tap_dev = "/dev/net/tun"; 114 static char tap_dev_name[16] = "bnep%d"; 115 #endif 116 117 118 static btstack_data_source_t tap_dev_ds; 119 static btstack_packet_callback_registration_t hci_event_callback_registration; 120 121 /* @section Main application configuration 122 * 123 * @text In the application configuration, L2CAP and BNEP are initialized and a BNEP service, for server mode, 124 * is registered, before the Bluetooth stack gets started, as shown in Listing PanuSetup. 125 */ 126 127 /* LISTING_START(PanuSetup): Panu setup */ 128 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size); 129 static void handle_sdp_client_query_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size); 130 131 static void panu_setup(void){ 132 133 // register for HCI events 134 hci_event_callback_registration.callback = &packet_handler; 135 hci_add_event_handler(&hci_event_callback_registration); 136 137 // Initialize L2CAP 138 l2cap_init(); 139 140 // Initialise BNEP 141 bnep_init(); 142 // Minimum L2CAP MTU for bnep is 1691 bytes 143 bnep_register_service(packet_handler, BLUETOOTH_SERVICE_CLASS_PANU, 1691); 144 } 145 /* LISTING_END */ 146 147 /* @section TUN / TAP interface routines 148 * 149 * @text This example requires a TUN/TAP interface to connect the Bluetooth network interface 150 * with the native system. It has been tested on Linux and OS X, but should work on any 151 * system that provides TUN/TAP with minor modifications. 152 * 153 * On Linux, TUN/TAP is available by default. On OS X, tuntaposx from 154 * http://tuntaposx.sourceforge.net needs to be installed. 155 * 156 * The *tap_alloc* function sets up a virtual network interface with the given Bluetooth Address. 157 * It is rather low-level as it sets up and configures a network interface. 158 */ 159 160 static int tap_alloc(char *dev, bd_addr_t bd_addr) 161 { 162 struct ifreq ifr; 163 int fd_dev; 164 int fd_socket; 165 166 if( (fd_dev = open(tap_dev, O_RDWR)) < 0 ) { 167 fprintf(stderr, "TAP: Error opening %s: %s\n", tap_dev, strerror(errno)); 168 return -1; 169 } 170 171 #ifdef __linux 172 memset(&ifr, 0, sizeof(ifr)); 173 174 ifr.ifr_flags = IFF_TAP | IFF_NO_PI; 175 if( *dev ) { 176 strncpy(ifr.ifr_name, dev, IFNAMSIZ); 177 } 178 179 int err; 180 if( (err = ioctl(fd_dev, TUNSETIFF, (void *) &ifr)) < 0 ) { 181 fprintf(stderr, "TAP: Error setting device name: %s\n", strerror(errno)); 182 close(fd_dev); 183 return -1; 184 } 185 strcpy(dev, ifr.ifr_name); 186 #endif 187 #ifdef __APPLE__ 188 dev = tap_dev_name; 189 #endif 190 191 fd_socket = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP); 192 if (fd_socket < 0) { 193 close(fd_dev); 194 fprintf(stderr, "TAP: Error opening netlink socket: %s\n", strerror(errno)); 195 return -1; 196 } 197 198 // Configure the MAC address of the newly created bnep(x) 199 // device to the local bd_address 200 memset (&ifr, 0, sizeof(struct ifreq)); 201 strcpy(ifr.ifr_name, dev); 202 #ifdef __linux 203 ifr.ifr_hwaddr.sa_family = ARPHRD_ETHER; 204 memcpy(ifr.ifr_hwaddr.sa_data, bd_addr, sizeof(bd_addr_t)); 205 if (ioctl(fd_socket, SIOCSIFHWADDR, &ifr) == -1) { 206 close(fd_dev); 207 close(fd_socket); 208 fprintf(stderr, "TAP: Error setting hw addr: %s\n", strerror(errno)); 209 exit(1); 210 return -1; 211 } 212 #endif 213 #ifdef __APPLE__ 214 ifr.ifr_addr.sa_len = ETHER_ADDR_LEN; 215 ifr.ifr_addr.sa_family = AF_LINK; 216 (void)memcpy(ifr.ifr_addr.sa_data, bd_addr, ETHER_ADDR_LEN); 217 if (ioctl(fd_socket, SIOCSIFLLADDR, &ifr) == -1) { 218 close(fd_dev); 219 close(fd_socket); 220 fprintf(stderr, "TAP: Error setting hw addr: %s\n", strerror(errno)); 221 exit(1); 222 return -1; 223 } 224 #endif 225 226 // Bring the interface up 227 if (ioctl(fd_socket, SIOCGIFFLAGS, &ifr) == -1) { 228 close(fd_dev); 229 close(fd_socket); 230 fprintf(stderr, "TAP: Error reading interface flags: %s\n", strerror(errno)); 231 return -1; 232 } 233 234 if ((ifr.ifr_flags & IFF_UP) == 0) { 235 ifr.ifr_flags |= IFF_UP; 236 237 if (ioctl(fd_socket, SIOCSIFFLAGS, &ifr) == -1) { 238 close(fd_dev); 239 close(fd_socket); 240 fprintf(stderr, "TAP: Error set IFF_UP: %s\n", strerror(errno)); 241 return -1; 242 } 243 } 244 245 close(fd_socket); 246 247 return fd_dev; 248 } 249 250 /* 251 * @text Listing processTapData shows how a packet is received from the TAP network interface 252 * and forwarded over the BNEP connection. 253 * 254 * After successfully reading a network packet, the call to 255 * the *bnep_can_send_packet_now* function checks, if BTstack can forward 256 * a network packet now. If that's not possible, the received data stays 257 * in the network buffer and the data source elements is removed from the 258 * run loop. The *process_tap_dev_data* function will not be called until 259 * the data source is registered again. This provides a basic flow control. 260 */ 261 262 /* LISTING_START(processTapData): Process incoming network packets */ 263 static void process_tap_dev_data(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type) 264 { 265 UNUSED(ds); 266 UNUSED(callback_type); 267 268 ssize_t len; 269 len = read(ds->fd, network_buffer, sizeof(network_buffer)); 270 if (len <= 0){ 271 fprintf(stderr, "TAP: Error while reading: %s\n", strerror(errno)); 272 return; 273 } 274 275 network_buffer_len = len; 276 if (bnep_can_send_packet_now(bnep_cid)) { 277 bnep_send(bnep_cid, network_buffer, network_buffer_len); 278 network_buffer_len = 0; 279 } else { 280 // park the current network packet 281 btstack_run_loop_remove_data_source(&tap_dev_ds); 282 } 283 return; 284 } 285 /* LISTING_END */ 286 287 // PANU client routines 288 static char * get_string_from_data_element(uint8_t * element){ 289 de_size_t de_size = de_get_size_type(element); 290 int pos = de_get_header_size(element); 291 int len = 0; 292 switch (de_size){ 293 case DE_SIZE_VAR_8: 294 len = element[1]; 295 break; 296 case DE_SIZE_VAR_16: 297 len = big_endian_read_16(element, 1); 298 break; 299 default: 300 break; 301 } 302 char * str = (char*)malloc(len+1); 303 memcpy(str, &element[pos], len); 304 str[len] ='\0'; 305 return str; 306 } 307 308 309 /* @section SDP parser callback 310 * 311 * @text The SDP parsers retrieves the BNEP PAN UUID as explained in 312 * Section [on SDP BNEP Query example](#sec:sdpbnepqueryExample}. 313 */ 314 static void handle_sdp_client_query_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) { 315 316 UNUSED(packet_type); 317 UNUSED(channel); 318 UNUSED(size); 319 320 des_iterator_t des_list_it; 321 des_iterator_t prot_it; 322 char *str; 323 324 switch (hci_event_packet_get_type(packet)){ 325 case SDP_EVENT_QUERY_ATTRIBUTE_VALUE: 326 // Handle new SDP record 327 if (sdp_event_query_attribute_byte_get_record_id(packet) != record_id) { 328 record_id = sdp_event_query_attribute_byte_get_record_id(packet); 329 printf("SDP Record: Nr: %d\n", record_id); 330 } 331 332 if (sdp_event_query_attribute_byte_get_attribute_length(packet) <= attribute_value_buffer_size) { 333 attribute_value[sdp_event_query_attribute_byte_get_data_offset(packet)] = sdp_event_query_attribute_byte_get_data(packet); 334 335 if ((uint16_t)(sdp_event_query_attribute_byte_get_data_offset(packet)+1) == sdp_event_query_attribute_byte_get_attribute_length(packet)) { 336 337 switch(sdp_event_query_attribute_byte_get_attribute_id(packet)) { 338 case BLUETOOTH_ATTRIBUTE_SERVICE_CLASS_ID_LIST: 339 if (de_get_element_type(attribute_value) != DE_DES) break; 340 for (des_iterator_init(&des_list_it, attribute_value); des_iterator_has_more(&des_list_it); des_iterator_next(&des_list_it)) { 341 uint8_t * element = des_iterator_get_element(&des_list_it); 342 if (de_get_element_type(element) != DE_UUID) continue; 343 uint32_t uuid = de_get_uuid32(element); 344 switch (uuid){ 345 case BLUETOOTH_SERVICE_CLASS_PANU: 346 case BLUETOOTH_SERVICE_CLASS_NAP: 347 case BLUETOOTH_SERVICE_CLASS_GN: 348 printf("SDP Attribute 0x%04x: BNEP PAN protocol UUID: %04x\n", sdp_event_query_attribute_byte_get_attribute_id(packet), uuid); 349 bnep_remote_uuid = uuid; 350 break; 351 default: 352 break; 353 } 354 } 355 break; 356 case 0x0100: 357 case 0x0101: 358 str = get_string_from_data_element(attribute_value); 359 printf("SDP Attribute: 0x%04x: %s\n", sdp_event_query_attribute_byte_get_attribute_id(packet), str); 360 free(str); 361 break; 362 case BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST: { 363 printf("SDP Attribute: 0x%04x\n", sdp_event_query_attribute_byte_get_attribute_id(packet)); 364 365 for (des_iterator_init(&des_list_it, attribute_value); des_iterator_has_more(&des_list_it); des_iterator_next(&des_list_it)) { 366 uint8_t *des_element; 367 uint8_t *element; 368 uint32_t uuid; 369 370 if (des_iterator_get_type(&des_list_it) != DE_DES) continue; 371 372 des_element = des_iterator_get_element(&des_list_it); 373 des_iterator_init(&prot_it, des_element); 374 element = des_iterator_get_element(&prot_it); 375 376 if (de_get_element_type(element) != DE_UUID) continue; 377 378 uuid = de_get_uuid32(element); 379 switch (uuid){ 380 case BLUETOOTH_PROTOCOL_L2CAP: 381 if (!des_iterator_has_more(&prot_it)) continue; 382 des_iterator_next(&prot_it); 383 de_element_get_uint16(des_iterator_get_element(&prot_it), &bnep_l2cap_psm); 384 break; 385 case BLUETOOTH_PROTOCOL_BNEP: 386 if (!des_iterator_has_more(&prot_it)) continue; 387 des_iterator_next(&prot_it); 388 de_element_get_uint16(des_iterator_get_element(&prot_it), &bnep_version); 389 break; 390 default: 391 break; 392 } 393 } 394 printf("l2cap_psm 0x%04x, bnep_version 0x%04x\n", bnep_l2cap_psm, bnep_version); 395 396 /* Create BNEP connection */ 397 bnep_connect(packet_handler, remote, bnep_l2cap_psm, BLUETOOTH_SERVICE_CLASS_PANU, bnep_remote_uuid); 398 } 399 break; 400 default: 401 break; 402 } 403 } 404 } else { 405 fprintf(stderr, "SDP attribute value buffer size exceeded: available %d, required %d\n", attribute_value_buffer_size, sdp_event_query_attribute_byte_get_attribute_length(packet)); 406 } 407 break; 408 409 case SDP_EVENT_QUERY_COMPLETE: 410 fprintf(stderr, "General query done with status %d.\n", sdp_event_query_complete_get_status(packet)); 411 412 break; 413 } 414 } 415 416 /* 417 * @section Packet Handler 418 * 419 * @text The packet handler responds to various HCI Events. 420 */ 421 422 423 /* LISTING_START(packetHandler): Packet Handler */ 424 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) 425 { 426 /* LISTING_PAUSE */ 427 UNUSED(channel); 428 429 int rc; 430 uint8_t event; 431 bd_addr_t event_addr; 432 bd_addr_t local_addr; 433 uint16_t uuid_source; 434 uint16_t uuid_dest; 435 uint16_t mtu; 436 437 /* LISTING_RESUME */ 438 switch (packet_type) { 439 case HCI_EVENT_PACKET: 440 event = hci_event_packet_get_type(packet); 441 switch (event) { 442 /* @text When BTSTACK_EVENT_STATE with state HCI_STATE_WORKING 443 * is received and the example is started in client mode, the remote SDP BNEP query is started. 444 */ 445 case BTSTACK_EVENT_STATE: 446 if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){ 447 printf("Start SDP BNEP query.\n"); 448 sdp_client_query_uuid16(&handle_sdp_client_query_result, remote, BLUETOOTH_PROTOCOL_BNEP); 449 } 450 break; 451 452 /* LISTING_PAUSE */ 453 case HCI_EVENT_PIN_CODE_REQUEST: 454 // inform about pin code request 455 printf("Pin code request - using '0000'\n"); 456 hci_event_pin_code_request_get_bd_addr(packet, event_addr); 457 gap_pin_code_response(event_addr, "0000"); 458 break; 459 460 case HCI_EVENT_USER_CONFIRMATION_REQUEST: 461 // inform about user confirmation request 462 printf("SSP User Confirmation Request with numeric value '%06u'\n", little_endian_read_32(packet, 8)); 463 printf("SSP User Confirmation Auto accept\n"); 464 break; 465 466 /* LISTING_RESUME */ 467 468 /* @text BNEP_EVENT_CHANNEL_OPENED is received after a BNEP connection was established or 469 * or when the connection fails. The status field returns the error code. 470 * 471 * The TAP network interface is then configured. A data source is set up and registered with the 472 * run loop to receive Ethernet packets from the TAP interface. 473 * 474 * The event contains both the source and destination UUIDs, as well as the MTU for this connection and 475 * the BNEP Channel ID, which is used for sending Ethernet packets over BNEP. 476 */ 477 case BNEP_EVENT_CHANNEL_OPENED: 478 if (bnep_event_channel_opened_get_status(packet)) { 479 printf("BNEP channel open failed, status %02x\n", bnep_event_channel_opened_get_status(packet)); 480 } else { 481 bnep_cid = bnep_event_channel_opened_get_bnep_cid(packet); 482 uuid_source = bnep_event_channel_opened_get_source_uuid(packet); 483 uuid_dest = bnep_event_channel_opened_get_destination_uuid(packet); 484 mtu = bnep_event_channel_opened_get_mtu(packet); 485 //bt_flip_addr(event_addr, &packet[9]); 486 memcpy(&event_addr, &packet[11], sizeof(bd_addr_t)); 487 printf("BNEP connection open succeeded to %s source UUID 0x%04x dest UUID: 0x%04x, max frame size %u\n", bd_addr_to_str(event_addr), uuid_source, uuid_dest, mtu); 488 /* Create the tap interface */ 489 gap_local_bd_addr(local_addr); 490 tap_fd = tap_alloc(tap_dev_name, local_addr); 491 if (tap_fd < 0) { 492 printf("Creating BNEP tap device failed: %s\n", strerror(errno)); 493 } else { 494 printf("BNEP device \"%s\" allocated.\n", tap_dev_name); 495 /* Create and register a new runloop data source */ 496 btstack_run_loop_set_data_source_fd(&tap_dev_ds, tap_fd); 497 btstack_run_loop_set_data_source_handler(&tap_dev_ds, &process_tap_dev_data); 498 btstack_run_loop_add_data_source(&tap_dev_ds); 499 } 500 } 501 break; 502 503 /* @text If there is a timeout during the connection setup, BNEP_EVENT_CHANNEL_TIMEOUT will be received 504 * and the BNEP connection will be closed 505 */ 506 case BNEP_EVENT_CHANNEL_TIMEOUT: 507 printf("BNEP channel timeout! Channel will be closed\n"); 508 break; 509 510 /* @text BNEP_EVENT_CHANNEL_CLOSED is received when the connection gets closed. 511 */ 512 case BNEP_EVENT_CHANNEL_CLOSED: 513 printf("BNEP channel closed\n"); 514 btstack_run_loop_remove_data_source(&tap_dev_ds); 515 if (tap_fd > 0) { 516 close(tap_fd); 517 tap_fd = -1; 518 } 519 break; 520 521 /* @text BNEP_EVENT_CAN_SEND_NOW indicates that a new packet can be send. This triggers the retry of a 522 * parked network packet. If this succeeds, the data source element is added to the run loop again. 523 */ 524 case BNEP_EVENT_CAN_SEND_NOW: 525 // Check for parked network packets and send it out now 526 if (network_buffer_len > 0) { 527 bnep_send(bnep_cid, network_buffer, network_buffer_len); 528 network_buffer_len = 0; 529 // Re-add the tap device data source 530 btstack_run_loop_add_data_source(&tap_dev_ds); 531 } 532 533 break; 534 535 default: 536 break; 537 } 538 break; 539 540 /* @text Ethernet packets from the remote device are received in the packet handler with type BNEP_DATA_PACKET. 541 * It is forwarded to the TAP interface. 542 */ 543 case BNEP_DATA_PACKET: 544 // Write out the ethernet frame to the tap device 545 if (tap_fd > 0) { 546 rc = write(tap_fd, packet, size); 547 if (rc < 0) { 548 fprintf(stderr, "TAP: Could not write to TAP device: %s\n", strerror(errno)); 549 } else 550 if (rc != size) { 551 fprintf(stderr, "TAP: Package written only partially %d of %d bytes\n", rc, size); 552 } 553 } 554 break; 555 556 default: 557 break; 558 } 559 } 560 /* LISTING_END */ 561 562 563 int btstack_main(int argc, const char * argv[]); 564 int btstack_main(int argc, const char * argv[]){ 565 566 UNUSED(argc); 567 (void)(argv); 568 569 printf("Client HCI init done\n"); 570 571 panu_setup(); 572 // Turn on the device 573 hci_power_control(HCI_POWER_ON); 574 return 0; 575 } 576 577 /* EXAMPLE_END */ 578 /* -*- Mode: C; indent-tabs-mode: nil; c-basic-offset: 4; tab-width: 4 -*- */ 579 580