xref: /btstack/test/security_manager_sc/main.c (revision 4930cef6e21e6da2d7571b9259c7f0fb8bed3d01)
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__ "main.c"
39 
40 // *****************************************************************************
41 //
42 // minimal setup for HCI code
43 //
44 // *****************************************************************************
45 #include <getopt.h>
46 #include <errno.h>
47 #include <stdint.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <signal.h>
52 #include <unistd.h>
53 
54 #include "btstack_config.h"
55 
56 #include "bluetooth_company_id.h"
57 #include "btstack_debug.h"
58 #include "btstack_event.h"
59 #include "ble/le_device_db_tlv.h"
60 #include "classic/btstack_link_key_db_tlv.h"
61 #include "btstack_memory.h"
62 #include "btstack_run_loop.h"
63 #include "btstack_run_loop_posix.h"
64 #include "hal_led.h"
65 #include "hci.h"
66 #include "hci_transport.h"
67 #include "hci_transport_usb.h"
68 #include "hci_dump.h"
69 #include "hci_dump_posix_fs.h"
70 #include "btstack_stdin.h"
71 #include "btstack_audio.h"
72 #include "btstack_tlv_posix.h"
73 #include "btstack_chipset_zephyr.h"
74 
75 #define TLV_DB_PATH_PREFIX "/tmp/btstack_"
76 #define TLV_DB_PATH_POSTFIX ".tlv"
77 static char tlv_db_path[100];
78 static bool tlv_clear = false;
79 static const btstack_tlv_t * tlv_impl;
80 static btstack_tlv_posix_t   tlv_context;
81 static bd_addr_t             local_addr;
82 
83 #define MAX_CMD_LINE_ITEMS  100
84 static int app_argc = 0;
85 static const char *app_argv[MAX_CMD_LINE_ITEMS] = { NULL };
86 
87 int btstack_main(int argc, const char * argv[]);
88 
89 static const uint8_t read_static_address_command_complete_prefix[] = { 0x0e, 0x1b, 0x01, 0x09, 0xfc };
90 
91 static bd_addr_t static_address;
92 static int using_static_address;
93 
94 static btstack_packet_callback_registration_t hci_event_callback_registration;
95 
96 static void local_version_information_handler(uint8_t * packet){
97     printf("Local version information:\n");
98     uint16_t hci_version    = packet[6];
99     uint16_t hci_revision   = little_endian_read_16(packet, 7);
100     uint16_t lmp_version    = packet[9];
101     uint16_t manufacturer   = little_endian_read_16(packet, 10);
102     uint16_t lmp_subversion = little_endian_read_16(packet, 12);
103     printf("- HCI Version    0x%04x\n", hci_version);
104     printf("- HCI Revision   0x%04x\n", hci_revision);
105     printf("- LMP Version    0x%04x\n", lmp_version);
106     printf("- LMP Subversion 0x%04x\n", lmp_subversion);
107     printf("- Manufacturer 0x%04x\n", manufacturer);
108     switch (manufacturer){
109         case BLUETOOTH_COMPANY_ID_THE_LINUX_FOUNDATION:
110             printf("Linux Foundation - assume Zephyr hci_usb example running on nRF52xx\n");
111             hci_set_chipset(btstack_chipset_zephyr_instance());
112             break;
113         default:
114             break;
115     }
116 }
117 
118 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
119     UNUSED(channel);
120     UNUSED(size);
121     if (packet_type != HCI_EVENT_PACKET) return;
122     switch (hci_event_packet_get_type(packet)){
123         case BTSTACK_EVENT_STATE:
124             switch (btstack_event_state_get_state(packet)){
125                 case HCI_STATE_WORKING:
126                     gap_local_bd_addr(local_addr);
127                     if (using_static_address){
128                         memcpy(local_addr, static_address, 6);
129                     }
130                     printf("BTstack up and running on %s.\n", bd_addr_to_str(local_addr));
131                     btstack_strcpy(tlv_db_path, sizeof(tlv_db_path), TLV_DB_PATH_PREFIX);
132                     btstack_strcat(tlv_db_path, sizeof(tlv_db_path), bd_addr_to_str(local_addr));
133                     btstack_strcat(tlv_db_path, sizeof(tlv_db_path), TLV_DB_PATH_POSTFIX);
134                     printf("TLV path: %s", tlv_db_path);
135                     if (tlv_clear){
136                         int rc = unlink(tlv_db_path);
137                         if((rc == 0) || ( errno == ENOENT )){
138                             printf(", clear ok\n");
139                         } else {
140                             printf(", clear failed because %s\n", strerror(errno));
141                         }
142                     }
143 
144                     tlv_impl = btstack_tlv_posix_init_instance(&tlv_context, tlv_db_path);
145                     btstack_tlv_set_instance(tlv_impl, &tlv_context);
146 #ifdef ENABLE_CLASSIC
147                     hci_set_link_key_db(btstack_link_key_db_tlv_get_instance(tlv_impl, &tlv_context));
148 #endif
149 #ifdef ENABLE_BLE
150                     le_device_db_tlv_configure(tlv_impl, &tlv_context);
151 #endif
152                     break;
153                 case HCI_STATE_OFF:
154                     btstack_tlv_posix_deinit(&tlv_context);
155                     break;
156                 default:
157                     break;
158             }
159             if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) return;
160             break;
161         case HCI_EVENT_COMMAND_COMPLETE:
162             if (hci_event_command_complete_get_command_opcode(packet) == HCI_OPCODE_HCI_READ_LOCAL_VERSION_INFORMATION){
163                 local_version_information_handler(packet);
164             }
165             if (memcmp(packet, read_static_address_command_complete_prefix, sizeof(read_static_address_command_complete_prefix)) == 0){
166                 reverse_48(&packet[7], static_address);
167                 gap_random_address_set(static_address);
168                 using_static_address = 1;
169             }
170             break;
171         default:
172             break;
173     }
174 }
175 
176 static void sigint_handler(int param){
177     UNUSED(param);
178 
179     printf("CTRL-C - SIGINT received, shutting down..\n");
180     log_info("sigint_handler: shutting down");
181 
182     // reset anyway
183     btstack_stdin_reset();
184 
185     // power down
186     hci_power_control(HCI_POWER_OFF);
187     hci_close();
188     log_info("Good bye, see you.\n");
189     exit(0);
190 }
191 
192 static int led_state = 0;
193 void hal_led_toggle(void){
194     led_state = 1 - led_state;
195     printf("LED State %u\n", led_state);
196 }
197 
198 static void btstack_log_cmd_line( int argc, const char *args[] )
199 {
200     char buf[2048] = "command line:";
201     char *ptr = buf+strlen(buf);
202     size_t len = sizeof(buf);
203     for( int i=0; i<argc; ++i )
204     {
205         int ret = snprintf(ptr, len, " %s", args[i]);
206         // avoid overflow
207         if((ret < 0) || ( (size_t)ret >= len ))
208         {
209             log_error("command line truncated!");
210             break;
211         }
212         // terminate string
213         ptr[ret] = 0;
214         len -= ret;
215         ptr += ret;
216     }
217     log_info("%s", buf);
218 
219 }
220 
221 static const char short_options[] = "-hu:l:c";
222 
223 static const struct option long_options[] = {
224     {"help",       no_argument,        NULL,   'h'},
225     {"logfile",    required_argument,  NULL,   'l'},
226     {"clear-tlv",  no_argument,        NULL,   'c'},
227     {"usbpath",    required_argument,  NULL,   'u'},
228     {0, 0, 0, 0}
229 };
230 
231 static const char *help_options[] = {
232     "print (this) help.",
233     "set file to store debug output and HCI trace.",
234     "clear bonding information stored in TLV.",
235     "set USB path to Bluetooth Controller.",
236 };
237 
238 static const char *option_arg_name[] = {
239     "",
240     "LOGFILE",
241     "",
242     "USBPATH",
243 };
244 
245 static void usage(const char *name){
246     unsigned int i;
247     printf( "usage:\n\t%s [options]\n", name );
248     printf("valid options:\n");
249     for( i=0; long_options[i].name != 0; i++) {
250         printf("--%-10s| -%c  %-10s\t\t%s\n", long_options[i].name, long_options[i].val, option_arg_name[i], help_options[i] );
251     }
252 }
253 
254 static void clear_argv(int idx){
255     app_argv[idx] = NULL;
256 }
257 
258 static void shift_argv(int idx){
259     for( int i=idx; i<app_argc-1; ++i )
260     {
261         app_argv[i] = app_argv[i+1];
262     }
263     app_argc--;
264 }
265 
266 static void cleanup_argv(void){
267     for( int i=0; i<app_argc; ){
268         if( app_argv[i] == NULL )
269             shift_argv( i );
270         else{
271             ++i;
272         }
273     }
274 }
275 
276 #define USB_MAX_PATH_LEN 7
277 int main(int argc, const char * argv[]){
278 
279     uint8_t usb_path[USB_MAX_PATH_LEN];
280     int usb_path_len = 0;
281     const char * usb_path_string = NULL;
282     const char * log_file_path = NULL;
283 
284     btstack_assert( argc < MAX_CMD_LINE_ITEMS );
285     app_argc = argc;
286     for( int i=0; i<argc; ++i ){
287         app_argv[i] = argv[i];
288     }
289 
290     opterr = 0; // disable error message on unknown options
291     // parse command line parameters
292     while(true){
293         int c = getopt_long( argc, (char* const *)argv, short_options, long_options, NULL );
294         if (c < 0) {
295             break;
296         }
297         switch (c) {
298             case 'u':
299                 usb_path_string = optarg;
300                 clear_argv( optind - 1 );
301                 clear_argv( optind - 2 );
302                 break;
303             case 'l':
304                 log_file_path = optarg;
305                 clear_argv( optind - 1 );
306                 clear_argv( optind - 2 );
307                 break;
308             case 'c':
309                 tlv_clear = true;
310                 clear_argv( optind - 1 );
311                 break;
312             case '?':
313             case 1:
314                 break;
315             case 'h':
316             default:
317                 usage(argv[0]);
318                 return EXIT_FAILURE;
319         }
320     }
321 
322     if (usb_path_string != NULL){
323         // parse command line options for "-u 11:22:33"
324         printf("Specified USB Path: ");
325         while (1){
326             char * delimiter;
327             int port = strtol(usb_path_string, &delimiter, 16);
328             usb_path[usb_path_len] = port;
329             usb_path_len++;
330             printf("%02x ", port);
331             if (!delimiter) break;
332             if (*delimiter != ':' && *delimiter != '-') break;
333             usb_path_string = delimiter+1;
334         }
335         printf("\n");
336     }
337 
338     // remove used up command line args
339     cleanup_argv();
340 
341     /// GET STARTED with BTstack ///
342     btstack_memory_init();
343     btstack_run_loop_init(btstack_run_loop_posix_get_instance());
344 
345     if (usb_path_len){
346         hci_transport_usb_set_path(usb_path_len, usb_path);
347     }
348 
349     // use logger: format HCI_DUMP_PACKETLOGGER, HCI_DUMP_BLUEZ or HCI_DUMP_STDOUT
350     char pklg_path[100];
351     btstack_strcpy(pklg_path, sizeof(pklg_path),  "/tmp/hci_dump");
352     if (usb_path_len){
353         btstack_strcat(pklg_path, sizeof(pklg_path), "_");
354         btstack_strcat(pklg_path, sizeof(pklg_path), usb_path_string);
355     }
356     btstack_strcat(pklg_path, sizeof(pklg_path), ".pklg");
357 
358     // use path from command line if given
359     if( log_file_path != NULL ){
360         btstack_strcpy(pklg_path, sizeof(pklg_path), log_file_path );
361     }
362 
363     // log into file using HCI_DUMP_PACKETLOGGER format
364     hci_dump_posix_fs_open(pklg_path, HCI_DUMP_PACKETLOGGER);
365     hci_dump_init(hci_dump_posix_fs_get_instance());
366     printf("Packet Log: %s\n", pklg_path);
367 
368     // let the log contain the calling parameters
369     btstack_log_cmd_line( app_argc, app_argv );
370 
371     // init HCI
372     hci_init(hci_transport_usb_instance(), NULL);
373 
374 #ifdef HAVE_PORTAUDIO
375     btstack_audio_sink_set_instance(btstack_audio_portaudio_sink_get_instance());
376     btstack_audio_source_set_instance(btstack_audio_portaudio_source_get_instance());
377 #endif
378 
379     // inform about BTstack state
380     hci_event_callback_registration.callback = &packet_handler;
381     hci_add_event_handler(&hci_event_callback_registration);
382 
383     // handle CTRL-c
384     signal(SIGINT, sigint_handler);
385 
386     // setup app
387     btstack_main(app_argc, app_argv);
388 
389     // go
390     btstack_run_loop_execute();
391 
392     return 0;
393 }
394