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