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