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