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