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