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