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