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