xref: /btstack/platform/daemon/src/daemon.c (revision 293fd5fb21e86fbb29e9789cc0a2c06dafbbf1b3)
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                 if (!intel_firmware_loaded){
940                     // before staring up the stack, load intel firmware
941                     btstack_chipset_intel_download_firmware(transport, &btstack_server_intel_firmware_done);
942                     break;
943                 }
944 #endif
945                 hci_power_control(HCI_POWER_ON);
946             }
947             break;
948         case BTSTACK_GET_VERSION:
949             log_info("BTSTACK_GET_VERSION");
950             hci_emit_btstack_version();
951             break;
952 #ifdef HAVE_PLATFORM_IPHONE_OS
953         case BTSTACK_SET_SYSTEM_BLUETOOTH_ENABLED:
954             log_info("BTSTACK_SET_SYSTEM_BLUETOOTH_ENABLED %u", packet[3]);
955             btstack_control_iphone_bt_set_enabled(packet[3]);
956             hci_emit_system_bluetooth_enabled(btstack_control_iphone_bt_enabled());
957             break;
958 
959         case BTSTACK_GET_SYSTEM_BLUETOOTH_ENABLED:
960             log_info("BTSTACK_GET_SYSTEM_BLUETOOTH_ENABLED");
961             hci_emit_system_bluetooth_enabled(btstack_control_iphone_bt_enabled());
962             break;
963 #else
964         case BTSTACK_SET_SYSTEM_BLUETOOTH_ENABLED:
965         case BTSTACK_GET_SYSTEM_BLUETOOTH_ENABLED:
966             hci_emit_system_bluetooth_enabled(0);
967             break;
968 #endif
969         case BTSTACK_SET_DISCOVERABLE:
970             log_info("BTSTACK_SET_DISCOVERABLE discoverable %u)", packet[3]);
971             // track client discoverable requests
972             client = client_for_connection(connection);
973             if (!client) break;
974             client->discoverable = packet[3];
975             // merge state
976             gap_discoverable_control(clients_require_discoverable());
977             break;
978         case BTSTACK_SET_BLUETOOTH_ENABLED:
979             log_info("BTSTACK_SET_BLUETOOTH_ENABLED: %u\n", packet[3]);
980             if (packet[3]) {
981                 // global enable
982                 global_enable = 1;
983                 hci_power_control(HCI_POWER_ON);
984             } else {
985                 global_enable = 0;
986                 clients_clear_power_request();
987                 hci_power_control(HCI_POWER_OFF);
988             }
989             break;
990         case L2CAP_CREATE_CHANNEL_MTU:
991             reverse_bd_addr(&packet[3], addr);
992             psm = little_endian_read_16(packet, 9);
993             mtu = little_endian_read_16(packet, 11);
994             status = l2cap_create_channel(NULL, addr, psm, mtu, &cid);
995             if (status){
996                 send_l2cap_connection_open_failed(connection, addr, psm, status);
997             } else {
998                 daemon_add_client_l2cap_channel(connection, cid);
999             }
1000             break;
1001         case L2CAP_CREATE_CHANNEL:
1002             reverse_bd_addr(&packet[3], addr);
1003             psm = little_endian_read_16(packet, 9);
1004             mtu = 150; // until r865
1005             status = l2cap_create_channel(NULL, addr, psm, mtu, &cid);
1006             if (status){
1007                 send_l2cap_connection_open_failed(connection, addr, psm, status);
1008             } else {
1009                 daemon_add_client_l2cap_channel(connection, cid);
1010             }
1011             break;
1012         case L2CAP_DISCONNECT:
1013             cid = little_endian_read_16(packet, 3);
1014             reason = packet[5];
1015             l2cap_disconnect(cid, reason);
1016             break;
1017         case L2CAP_REGISTER_SERVICE:
1018             psm = little_endian_read_16(packet, 3);
1019             mtu = little_endian_read_16(packet, 5);
1020             status = l2cap_register_service(NULL, psm, mtu, LEVEL_0);
1021             daemon_add_client_l2cap_service(connection, little_endian_read_16(packet, 3));
1022             l2cap_emit_service_registered(connection, status, psm);
1023             break;
1024         case L2CAP_UNREGISTER_SERVICE:
1025             psm = little_endian_read_16(packet, 3);
1026             daemon_remove_client_l2cap_service(connection, psm);
1027             l2cap_unregister_service(psm);
1028             break;
1029         case L2CAP_ACCEPT_CONNECTION:
1030             cid    = little_endian_read_16(packet, 3);
1031             l2cap_accept_connection(cid);
1032             break;
1033         case L2CAP_DECLINE_CONNECTION:
1034             cid    = little_endian_read_16(packet, 3);
1035             reason = packet[7];
1036             l2cap_decline_connection(cid);
1037             break;
1038         case RFCOMM_CREATE_CHANNEL:
1039             reverse_bd_addr(&packet[3], addr);
1040             rfcomm_channel = packet[9];
1041             status = rfcomm_create_channel(&stack_packet_handler, addr, rfcomm_channel, &cid);
1042             if (status){
1043                 send_rfcomm_create_channel_failed(connection, addr, rfcomm_channel, status);
1044             } else {
1045                 daemon_add_client_rfcomm_channel(connection, cid);
1046             }
1047             break;
1048         case RFCOMM_CREATE_CHANNEL_WITH_CREDITS:
1049             reverse_bd_addr(&packet[3], addr);
1050             rfcomm_channel = packet[9];
1051             rfcomm_credits = packet[10];
1052             status = rfcomm_create_channel_with_initial_credits(&stack_packet_handler, addr, rfcomm_channel, rfcomm_credits, &cid );
1053             if (status){
1054                 send_rfcomm_create_channel_failed(connection, addr, rfcomm_channel, status);
1055             } else {
1056                 daemon_add_client_rfcomm_channel(connection, cid);
1057             }
1058             break;
1059         case RFCOMM_DISCONNECT:
1060             cid = little_endian_read_16(packet, 3);
1061             reason = packet[5];
1062             rfcomm_disconnect(cid);
1063             break;
1064         case RFCOMM_REGISTER_SERVICE:
1065             rfcomm_channel = packet[3];
1066             mtu = little_endian_read_16(packet, 4);
1067             status = rfcomm_register_service(&stack_packet_handler, rfcomm_channel, mtu);
1068             rfcomm_emit_service_registered(connection, status, rfcomm_channel);
1069             break;
1070         case RFCOMM_REGISTER_SERVICE_WITH_CREDITS:
1071             rfcomm_channel = packet[3];
1072             mtu = little_endian_read_16(packet, 4);
1073             rfcomm_credits = packet[6];
1074             status = rfcomm_register_service_with_initial_credits(&stack_packet_handler, rfcomm_channel, mtu, rfcomm_credits);
1075             rfcomm_emit_service_registered(connection, status, rfcomm_channel);
1076             break;
1077         case RFCOMM_UNREGISTER_SERVICE:
1078             service_channel = little_endian_read_16(packet, 3);
1079             daemon_remove_client_rfcomm_service(connection, service_channel);
1080             rfcomm_unregister_service(service_channel);
1081             break;
1082         case RFCOMM_ACCEPT_CONNECTION:
1083             cid    = little_endian_read_16(packet, 3);
1084             rfcomm_accept_connection(cid);
1085             break;
1086         case RFCOMM_DECLINE_CONNECTION:
1087             cid    = little_endian_read_16(packet, 3);
1088             reason = packet[7];
1089             rfcomm_decline_connection(cid);
1090             break;
1091         case RFCOMM_GRANT_CREDITS:
1092             cid    = little_endian_read_16(packet, 3);
1093             rfcomm_credits = packet[5];
1094             rfcomm_grant_credits(cid, rfcomm_credits);
1095             break;
1096         case RFCOMM_PERSISTENT_CHANNEL: {
1097             // enforce \0
1098             packet[3+248] = 0;
1099             rfcomm_channel = rfcomm_service_db_channel_for_service((char*)&packet[3]);
1100             log_info("DAEMON_EVENT_RFCOMM_PERSISTENT_CHANNEL %u", rfcomm_channel);
1101             uint8_t event[4];
1102             event[0] = DAEMON_EVENT_RFCOMM_PERSISTENT_CHANNEL;
1103             event[1] = sizeof(event) - 2;
1104             event[2] = 0;
1105             event[3] = rfcomm_channel;
1106             hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
1107             socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, (uint8_t *) event, sizeof(event));
1108             break;
1109         }
1110         case SDP_REGISTER_SERVICE_RECORD:
1111             log_info("SDP_REGISTER_SERVICE_RECORD size %u\n", size);
1112             service_record_handle = daemon_sdp_create_and_register_service(&packet[3]);
1113             if (service_record_handle){
1114                 daemon_add_client_sdp_service_record_handle(connection, service_record_handle);
1115                 sdp_emit_service_registered(connection, service_record_handle, 0);
1116             } else {
1117                sdp_emit_service_registered(connection, 0, BTSTACK_MEMORY_ALLOC_FAILED);
1118             }
1119             break;
1120         case SDP_UNREGISTER_SERVICE_RECORD:
1121             service_record_handle = little_endian_read_32(packet, 3);
1122             log_info("SDP_UNREGISTER_SERVICE_RECORD handle 0x%x ", service_record_handle);
1123             data = sdp_get_record_for_handle(service_record_handle);
1124             sdp_unregister_service(service_record_handle);
1125             daemon_remove_client_sdp_service_record_handle(connection, service_record_handle);
1126             if (data){
1127                 free(data);
1128             }
1129             break;
1130         case SDP_CLIENT_QUERY_RFCOMM_SERVICES:
1131             reverse_bd_addr(&packet[3], addr);
1132 
1133             serviceSearchPatternLen = de_get_len(&packet[9]);
1134             memcpy(serviceSearchPattern, &packet[9], serviceSearchPatternLen);
1135 
1136             sdp_client_query_connection = connection;
1137             sdp_client_query_rfcomm_channel_and_name_for_search_pattern(&handle_sdp_rfcomm_service_result, addr, serviceSearchPattern);
1138 
1139             break;
1140         case SDP_CLIENT_QUERY_SERVICES:
1141             reverse_bd_addr(&packet[3], addr);
1142             sdp_client_query_connection = connection;
1143 
1144             serviceSearchPatternLen = de_get_len(&packet[9]);
1145             memcpy(serviceSearchPattern, &packet[9], serviceSearchPatternLen);
1146 
1147             attributeIDListLen = de_get_len(&packet[9+serviceSearchPatternLen]);
1148             memcpy(attributeIDList, &packet[9+serviceSearchPatternLen], attributeIDListLen);
1149 
1150             sdp_client_query(&handle_sdp_client_query_result, addr, (uint8_t*)&serviceSearchPattern[0], (uint8_t*)&attributeIDList[0]);
1151             break;
1152 #ifdef ENABLE_BLE
1153         case GAP_LE_SCAN_START:
1154             gap_start_scan();
1155             break;
1156         case GAP_LE_SCAN_STOP:
1157             gap_stop_scan();
1158             break;
1159         case GAP_LE_SET_SCAN_PARAMETERS:
1160             gap_set_scan_parameters(packet[3], little_endian_read_16(packet, 4), little_endian_read_16(packet, 6));
1161             break;
1162         case GAP_LE_CONNECT:
1163             reverse_bd_addr(&packet[4], addr);
1164             addr_type = packet[3];
1165             gap_connect(addr, addr_type);
1166             break;
1167         case GAP_LE_CONNECT_CANCEL:
1168             gap_connect_cancel();
1169             break;
1170         case GAP_DISCONNECT:
1171             handle = little_endian_read_16(packet, 3);
1172             gap_disconnect(handle);
1173             break;
1174 #endif
1175 #if defined(HAVE_MALLOC) && defined(ENABLE_BLE)
1176         case GATT_DISCOVER_ALL_PRIMARY_SERVICES:
1177             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1178             if (!gatt_helper) break;
1179             gatt_client_discover_primary_services(&handle_gatt_client_event, gatt_helper->con_handle);
1180             break;
1181         case GATT_DISCOVER_PRIMARY_SERVICES_BY_UUID16:
1182             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1183             if (!gatt_helper) break;
1184             gatt_client_discover_primary_services_by_uuid16(&handle_gatt_client_event, gatt_helper->con_handle, little_endian_read_16(packet, 5));
1185             break;
1186         case GATT_DISCOVER_PRIMARY_SERVICES_BY_UUID128:
1187             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1188             if (!gatt_helper) break;
1189             reverse_128(&packet[5], uuid128);
1190             gatt_client_discover_primary_services_by_uuid128(&handle_gatt_client_event, gatt_helper->con_handle, uuid128);
1191             break;
1192         case GATT_FIND_INCLUDED_SERVICES_FOR_SERVICE:
1193             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1194             if (!gatt_helper) break;
1195             gatt_client_deserialize_service(packet, 5, &service);
1196             gatt_client_find_included_services_for_service(&handle_gatt_client_event, gatt_helper->con_handle, &service);
1197             break;
1198 
1199         case GATT_DISCOVER_CHARACTERISTICS_FOR_SERVICE:
1200             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1201             if (!gatt_helper) break;
1202             gatt_client_deserialize_service(packet, 5, &service);
1203             gatt_client_discover_characteristics_for_service(&handle_gatt_client_event, gatt_helper->con_handle, &service);
1204             break;
1205         case GATT_DISCOVER_CHARACTERISTICS_FOR_SERVICE_BY_UUID128:
1206             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1207             if (!gatt_helper) break;
1208             gatt_client_deserialize_service(packet, 5, &service);
1209             reverse_128(&packet[5 + SERVICE_LENGTH], uuid128);
1210             gatt_client_discover_characteristics_for_service_by_uuid128(&handle_gatt_client_event, gatt_helper->con_handle, &service, uuid128);
1211             break;
1212         case GATT_DISCOVER_CHARACTERISTIC_DESCRIPTORS:
1213             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1214             if (!gatt_helper) break;
1215             gatt_client_deserialize_characteristic(packet, 5, &characteristic);
1216             gatt_client_discover_characteristic_descriptors(&handle_gatt_client_event, gatt_helper->con_handle, &characteristic);
1217             break;
1218 
1219         case GATT_READ_VALUE_OF_CHARACTERISTIC:
1220             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1221             if (!gatt_helper) break;
1222             gatt_client_deserialize_characteristic(packet, 5, &characteristic);
1223             gatt_client_read_value_of_characteristic(&handle_gatt_client_event, gatt_helper->con_handle, &characteristic);
1224             break;
1225         case GATT_READ_LONG_VALUE_OF_CHARACTERISTIC:
1226             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1227             if (!gatt_helper) break;
1228             gatt_client_deserialize_characteristic(packet, 5, &characteristic);
1229             gatt_client_read_long_value_of_characteristic(&handle_gatt_client_event, gatt_helper->con_handle, &characteristic);
1230             break;
1231 
1232         case GATT_WRITE_VALUE_OF_CHARACTERISTIC_WITHOUT_RESPONSE:
1233             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 0);  // note: don't track active connection
1234             if (!gatt_helper) break;
1235             gatt_client_deserialize_characteristic(packet, 5, &characteristic);
1236             data_length = little_endian_read_16(packet, 5 + CHARACTERISTIC_LENGTH);
1237             data = gatt_helper->characteristic_buffer;
1238             memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length);
1239             gatt_client_write_value_of_characteristic_without_response(gatt_helper->con_handle, characteristic.value_handle, data_length, data);
1240             break;
1241         case GATT_WRITE_VALUE_OF_CHARACTERISTIC:
1242             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1243             if (!gatt_helper) break;
1244             gatt_client_deserialize_characteristic(packet, 5, &characteristic);
1245             data_length = little_endian_read_16(packet, 5 + CHARACTERISTIC_LENGTH);
1246             data = gatt_helper->characteristic_buffer;
1247             memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length);
1248             gatt_client_write_value_of_characteristic(&handle_gatt_client_event, gatt_helper->con_handle, characteristic.value_handle, data_length, data);
1249             break;
1250         case GATT_WRITE_LONG_VALUE_OF_CHARACTERISTIC:
1251             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1252             if (!gatt_helper) break;
1253             gatt_client_deserialize_characteristic(packet, 5, &characteristic);
1254             data_length = little_endian_read_16(packet, 5 + CHARACTERISTIC_LENGTH);
1255             data = gatt_helper->characteristic_buffer;
1256             memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length);
1257             gatt_client_write_long_value_of_characteristic(&handle_gatt_client_event, gatt_helper->con_handle, characteristic.value_handle, data_length, data);
1258             break;
1259         case GATT_RELIABLE_WRITE_LONG_VALUE_OF_CHARACTERISTIC:
1260             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1261             if (!gatt_helper) break;
1262             gatt_client_deserialize_characteristic(packet, 5, &characteristic);
1263             data_length = little_endian_read_16(packet, 5 + CHARACTERISTIC_LENGTH);
1264             data = gatt_helper->characteristic_buffer;
1265             memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length);
1266             gatt_client_write_long_value_of_characteristic(&handle_gatt_client_event, gatt_helper->con_handle, characteristic.value_handle, data_length, data);
1267             break;
1268         case GATT_READ_CHARACTERISTIC_DESCRIPTOR:
1269             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1270             if (!gatt_helper) break;
1271             handle = little_endian_read_16(packet, 3);
1272             gatt_client_deserialize_characteristic_descriptor(packet, 5, &descriptor);
1273             gatt_client_read_characteristic_descriptor(&handle_gatt_client_event, gatt_helper->con_handle, &descriptor);
1274             break;
1275         case GATT_READ_LONG_CHARACTERISTIC_DESCRIPTOR:
1276             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1277             if (!gatt_helper) break;
1278             gatt_client_deserialize_characteristic_descriptor(packet, 5, &descriptor);
1279             gatt_client_read_long_characteristic_descriptor(&handle_gatt_client_event, gatt_helper->con_handle, &descriptor);
1280             break;
1281 
1282         case GATT_WRITE_CHARACTERISTIC_DESCRIPTOR:
1283             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1284             if (!gatt_helper) break;
1285             gatt_client_deserialize_characteristic_descriptor(packet, 5, &descriptor);
1286             data = gatt_helper->characteristic_buffer;
1287             data_length = little_endian_read_16(packet, 5 + CHARACTERISTIC_DESCRIPTOR_LENGTH);
1288             gatt_client_write_characteristic_descriptor(&handle_gatt_client_event, gatt_helper->con_handle, &descriptor, data_length, data);
1289             break;
1290         case GATT_WRITE_LONG_CHARACTERISTIC_DESCRIPTOR:
1291             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1292             if (!gatt_helper) break;
1293             gatt_client_deserialize_characteristic_descriptor(packet, 5, &descriptor);
1294             data = gatt_helper->characteristic_buffer;
1295             data_length = little_endian_read_16(packet, 5 + CHARACTERISTIC_DESCRIPTOR_LENGTH);
1296             gatt_client_write_long_characteristic_descriptor(&handle_gatt_client_event, gatt_helper->con_handle, &descriptor, data_length, data);
1297             break;
1298         case GATT_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION:{
1299             uint16_t configuration = little_endian_read_16(packet, 5 + CHARACTERISTIC_LENGTH);
1300             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1301             if (!gatt_helper) break;
1302             data = gatt_helper->characteristic_buffer;
1303             gatt_client_deserialize_characteristic(packet, 5, &characteristic);
1304             status = gatt_client_write_client_characteristic_configuration(&handle_gatt_client_event, gatt_helper->con_handle, &characteristic, configuration);
1305             if (status){
1306                 send_gatt_query_complete(connection, gatt_helper->con_handle, status);
1307                 break;
1308             }
1309             // ignore notification off
1310             if (configuration == 0) break;
1311 
1312             // TODO: we assume it works
1313 
1314             // start listening
1315             btstack_linked_list_gatt_client_notification_t * linked_notification = malloc(sizeof(btstack_linked_list_gatt_client_notification_t));
1316             if (!linked_notification) break;
1317             memset(linked_notification, 0, sizeof(btstack_linked_list_gatt_client_notification_t));
1318             log_info("Start gatt notification listener %p", linked_notification);
1319             gatt_client_listen_for_characteristic_value_updates(&linked_notification->notification_listener, &handle_gatt_client_event, gatt_helper->con_handle, &characteristic);
1320             btstack_linked_list_add(&gatt_helper->gatt_client_notifications, (btstack_linked_item_t *) linked_notification);
1321             break;
1322         }
1323         case GATT_GET_MTU:
1324             handle = little_endian_read_16(packet, 3);
1325             gatt_client_get_mtu(handle, &mtu);
1326             send_gatt_mtu_event(connection, handle, mtu);
1327             break;
1328 #endif
1329 #ifdef ENABLE_BLE
1330         case SM_SET_AUTHENTICATION_REQUIREMENTS:
1331             log_info("set auth %x", packet[3]);
1332             sm_set_authentication_requirements(packet[3]);
1333             break;
1334         case SM_SET_IO_CAPABILITIES:
1335             log_info("set io %x", packet[3]);
1336             sm_set_io_capabilities(packet[3]);
1337             break;
1338         case SM_BONDING_DECLINE:
1339             sm_bonding_decline(little_endian_read_16(packet, 3));
1340             break;
1341         case SM_JUST_WORKS_CONFIRM:
1342             sm_just_works_confirm(little_endian_read_16(packet, 3));
1343             break;
1344         case SM_NUMERIC_COMPARISON_CONFIRM:
1345             sm_numeric_comparison_confirm(little_endian_read_16(packet, 3));
1346             break;
1347         case SM_PASSKEY_INPUT:
1348             sm_passkey_input(little_endian_read_16(packet, 3), little_endian_read_32(packet, 5));
1349             break;
1350 #endif
1351     default:
1352             log_error("Error: command %u not implemented:", READ_CMD_OCF(packet));
1353             break;
1354     }
1355 
1356     return 0;
1357 }
1358 
1359 static int daemon_client_handler(connection_t *connection, uint16_t packet_type, uint16_t channel, uint8_t *data, uint16_t length){
1360 
1361     int err = 0;
1362     client_state_t * client;
1363 
1364     switch (packet_type){
1365         case HCI_COMMAND_DATA_PACKET:
1366             if (READ_CMD_OGF(data) != OGF_BTSTACK) {
1367                 // HCI Command
1368                 hci_send_cmd_packet(data, length);
1369             } else {
1370                 // BTstack command
1371                 btstack_command_handler(connection, data, length);
1372             }
1373             break;
1374         case L2CAP_DATA_PACKET:
1375             // process l2cap packet...
1376             err = l2cap_send(channel, data, length);
1377             break;
1378         case RFCOMM_DATA_PACKET:
1379             // process l2cap packet...
1380             err = rfcomm_send(channel, data, length);
1381             break;
1382         case DAEMON_EVENT_PACKET:
1383             switch (data[0]) {
1384                 case DAEMON_EVENT_CONNECTION_OPENED:
1385                     log_info("DAEMON_EVENT_CONNECTION_OPENED %p\n",connection);
1386 
1387                     client = calloc(sizeof(client_state_t), 1);
1388                     if (!client) break; // fail
1389                     client->connection   = connection;
1390                     client->power_mode   = HCI_POWER_OFF;
1391                     client->discoverable = 0;
1392                     btstack_linked_list_add(&clients, (btstack_linked_item_t *) client);
1393                     break;
1394                 case DAEMON_EVENT_CONNECTION_CLOSED:
1395                     log_info("DAEMON_EVENT_CONNECTION_CLOSED %p\n",connection);
1396                     daemon_disconnect_client(connection);
1397                     // no clients -> no HCI connections
1398                     if (!clients){
1399                         hci_disconnect_all();
1400                     }
1401 
1402                     // update discoverable mode
1403                     gap_discoverable_control(clients_require_discoverable());
1404                     // start power off, if last active client
1405                     if (!clients_require_power_on()){
1406                         start_power_off_timer();
1407                     }
1408                     break;
1409                 default:
1410                     break;
1411             }
1412             break;
1413     }
1414     if (err) {
1415         log_info("Daemon Handler: err %d\n", err);
1416     }
1417     return err;
1418 }
1419 
1420 
1421 static void daemon_set_logging_enabled(int enabled){
1422     if (enabled && !loggingEnabled){
1423         // construct path to log file
1424         switch (BTSTACK_LOG_TYPE){
1425             case HCI_DUMP_STDOUT:
1426                 snprintf(string_buffer, sizeof(string_buffer), "stdout");
1427                 break;
1428             case HCI_DUMP_PACKETLOGGER:
1429                 snprintf(string_buffer, sizeof(string_buffer), "%s/hci_dump.pklg", btstack_server_storage_path);
1430                 break;
1431             case HCI_DUMP_BLUEZ:
1432                 snprintf(string_buffer, sizeof(string_buffer), "%s/hci_dump.snoop", btstack_server_storage_path);
1433                 break;
1434             default:
1435                 break;
1436         }
1437         hci_dump_open(string_buffer, BTSTACK_LOG_TYPE);
1438         printf("Logging to %s\n", string_buffer);
1439     }
1440     if (!enabled && loggingEnabled){
1441         hci_dump_close();
1442     }
1443     loggingEnabled = enabled;
1444 }
1445 
1446 // local cache used to manage UI status
1447 static HCI_STATE hci_state = HCI_STATE_OFF;
1448 static int num_connections = 0;
1449 static void update_ui_status(void){
1450     if (hci_state != HCI_STATE_WORKING) {
1451         bluetooth_status_handler(BLUETOOTH_OFF);
1452     } else {
1453         if (num_connections) {
1454             bluetooth_status_handler(BLUETOOTH_ACTIVE);
1455         } else {
1456             bluetooth_status_handler(BLUETOOTH_ON);
1457         }
1458     }
1459 }
1460 
1461 #ifdef USE_SPRINGBOARD
1462 static void preferences_changed_callback(void){
1463     int logging = platform_iphone_logging_enabled();
1464     log_info("Logging enabled: %u\n", logging);
1465     daemon_set_logging_enabled(logging);
1466 }
1467 #endif
1468 
1469 static void deamon_status_event_handler(uint8_t *packet, uint16_t size){
1470 
1471     uint8_t update_status = 0;
1472 
1473     // handle state event
1474     switch (hci_event_packet_get_type(packet)) {
1475         case BTSTACK_EVENT_STATE:
1476             hci_state = packet[2];
1477             log_info("New state: %u\n", hci_state);
1478             update_status = 1;
1479             break;
1480         case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED:
1481             num_connections = packet[2];
1482             log_info("New nr connections: %u\n", num_connections);
1483             update_status = 1;
1484             break;
1485         default:
1486             break;
1487     }
1488 
1489     // choose full bluetooth state
1490     if (update_status) {
1491         update_ui_status();
1492     }
1493 }
1494 
1495 static void daemon_retry_parked(void){
1496 
1497     // socket_connection_retry_parked is not reentrant
1498     static int retry_mutex = 0;
1499 
1500     // lock mutex
1501     if (retry_mutex) return;
1502     retry_mutex = 1;
1503 
1504     // ... try sending again
1505     socket_connection_retry_parked();
1506 
1507     // unlock mutex
1508     retry_mutex = 0;
1509 }
1510 
1511 static void daemon_emit_packet(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1512     if (connection) {
1513         socket_connection_send_packet(connection, packet_type, channel, packet, size);
1514     } else {
1515         socket_connection_send_packet_all(packet_type, channel, packet, size);
1516     }
1517 }
1518 
1519 // copy from btstack_util, just using a '-'
1520 static char bd_addr_to_str_buffer[6*3];  // 12:45:78:01:34:67\0
1521 char * bd_addr_to_str_dashed(const bd_addr_t addr){
1522     // orig code
1523     // sprintf(bd_addr_to_str_buffer, "%02x:%02x:%02x:%02x:%02x:%02x", addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1524     // sprintf-free code
1525     char * p = bd_addr_to_str_buffer;
1526     int i;
1527     for (i = 0; i < 6 ; i++) {
1528         uint8_t byte = addr[i];
1529         *p++ = char_for_nibble(byte >> 4);
1530         *p++ = char_for_nibble(byte & 0x0f);
1531         *p++ = '-';
1532     }
1533     *--p = 0;
1534     return (char *) bd_addr_to_str_buffer;
1535 }
1536 
1537 static uint8_t remote_name_event[2+1+6+DEVICE_NAME_LEN+1]; // +1 for \0 in log_info
1538 static void daemon_packet_handler(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1539     uint16_t cid;
1540     int i;
1541     bd_addr_t addr;
1542     switch (packet_type) {
1543         case HCI_EVENT_PACKET:
1544             deamon_status_event_handler(packet, size);
1545             switch (hci_event_packet_get_type(packet)){
1546 
1547                 case BTSTACK_EVENT_STATE:
1548                     if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) break;
1549                     if (tlv_setup_done) break;
1550 
1551                     // setup TLV using local address as part of the name
1552                     gap_local_bd_addr(addr);
1553                     log_info("BTstack up and running at %s",  bd_addr_to_str(addr));
1554                     snprintf(string_buffer, sizeof(string_buffer), "%s/btstack_%s.tlv", btstack_server_storage_path, bd_addr_to_str_dashed(addr));
1555                     tlv_impl = btstack_tlv_posix_init_instance(&tlv_context, string_buffer);
1556                     btstack_tlv_set_instance(tlv_impl, &tlv_context);
1557 
1558                     // setup link key db
1559                     hci_set_link_key_db(btstack_link_key_db_tlv_get_instance(tlv_impl, &tlv_context));
1560 
1561                     // init le device db to use TLV
1562                     le_device_db_tlv_configure(tlv_impl, &tlv_context);
1563                     le_device_db_init();
1564                     le_device_db_set_local_bd_addr(addr);
1565 
1566                     tlv_setup_done = 1;
1567                     break;
1568 
1569                 case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
1570                     // ACL buffer freed...
1571                     daemon_retry_parked();
1572                     // no need to tell clients
1573                     return;
1574 
1575                 case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
1576                     if (!btstack_device_name_db) break;
1577                     if (packet[2]) break; // status not ok
1578 
1579                     reverse_bd_addr(&packet[3], addr);
1580                     // fix for invalid remote names - terminate on 0xff
1581                     for (i=0; i<248;i++){
1582                         if (packet[9+i] == 0xff){
1583                             packet[9+i] = 0;
1584                             break;
1585                         }
1586                     }
1587                     packet[9+248] = 0;
1588                     btstack_device_name_db->put_name(addr, (device_name_t *)&packet[9]);
1589                     break;
1590 
1591                 case HCI_EVENT_INQUIRY_RESULT:
1592                 case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:{
1593                     if (!btstack_device_name_db) break;
1594 
1595                     // first send inq result packet
1596                     daemon_emit_packet(connection, packet_type, channel, packet, size);
1597 
1598                     // then send cached remote names
1599                     int offset = 3;
1600                     for (i=0; i<packet[2];i++){
1601                         reverse_bd_addr(&packet[offset], addr);
1602                         if (btstack_device_name_db->get_name(addr, (device_name_t *) &remote_name_event[9])){
1603                             remote_name_event[0] = DAEMON_EVENT_REMOTE_NAME_CACHED;
1604                             remote_name_event[1] = sizeof(remote_name_event) - 2 - 1;
1605                             remote_name_event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
1606                             reverse_bd_addr(addr, &remote_name_event[3]);
1607 
1608                             remote_name_event[9+248] = 0;   // assert \0 for log_info
1609                             log_info("DAEMON_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(addr), &remote_name_event[9]);
1610                             hci_dump_packet(HCI_EVENT_PACKET, 0, remote_name_event, sizeof(remote_name_event)-1);
1611                             daemon_emit_packet(connection, HCI_EVENT_PACKET, channel, remote_name_event, sizeof(remote_name_event) -1);
1612                         }
1613                         offset += 14; // 6 + 1 + 1 + 1 + 3 + 2;
1614                     }
1615                     return;
1616                 }
1617 
1618                 case DAEMON_EVENT_RFCOMM_CREDITS:
1619                     // RFCOMM CREDITS received...
1620                     daemon_retry_parked();
1621                     break;
1622 
1623                 case RFCOMM_EVENT_CHANNEL_OPENED:
1624                     cid = little_endian_read_16(packet, 13);
1625                     connection = connection_for_rfcomm_cid(cid);
1626                     if (!connection) break;
1627                     if (packet[2]) {
1628                         daemon_remove_client_rfcomm_channel(connection, cid);
1629                     } else {
1630                         daemon_add_client_rfcomm_channel(connection, cid);
1631                     }
1632                     break;
1633                 case RFCOMM_EVENT_CHANNEL_CLOSED:
1634                     cid = little_endian_read_16(packet, 2);
1635                     connection = connection_for_rfcomm_cid(cid);
1636                     if (!connection) break;
1637                     daemon_remove_client_rfcomm_channel(connection, cid);
1638                     break;
1639                 case DAEMON_EVENT_RFCOMM_SERVICE_REGISTERED:
1640                     if (packet[2]) break;
1641                     daemon_add_client_rfcomm_service(connection, packet[3]);
1642                     break;
1643                 case L2CAP_EVENT_CHANNEL_OPENED:
1644                     cid = little_endian_read_16(packet, 13);
1645                     connection = connection_for_l2cap_cid(cid);
1646                     if (!connection) break;
1647                     if (packet[2]) {
1648                         daemon_remove_client_l2cap_channel(connection, cid);
1649                     } else {
1650                         daemon_add_client_l2cap_channel(connection, cid);
1651                     }
1652                     break;
1653                 case L2CAP_EVENT_CHANNEL_CLOSED:
1654                     cid = little_endian_read_16(packet, 2);
1655                     connection = connection_for_l2cap_cid(cid);
1656                     if (!connection) break;
1657                     daemon_remove_client_l2cap_channel(connection, cid);
1658                     break;
1659 #if defined(ENABLE_BLE) && defined(HAVE_MALLOC)
1660                 case HCI_EVENT_DISCONNECTION_COMPLETE:
1661                     daemon_remove_gatt_client_helper(little_endian_read_16(packet, 3));
1662                     break;
1663 #endif
1664                 default:
1665                     break;
1666             }
1667             break;
1668         case L2CAP_DATA_PACKET:
1669             connection = connection_for_l2cap_cid(channel);
1670             if (!connection) return;
1671             break;
1672         case RFCOMM_DATA_PACKET:
1673             connection = connection_for_l2cap_cid(channel);
1674             if (!connection) return;
1675             break;
1676         default:
1677             break;
1678     }
1679 
1680     daemon_emit_packet(connection, packet_type, channel, packet, size);
1681 }
1682 
1683 static void stack_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){
1684     daemon_packet_handler(NULL, packet_type, channel, packet, size);
1685 }
1686 
1687 static void handle_sdp_rfcomm_service_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1688     switch (hci_event_packet_get_type(packet)){
1689         case SDP_EVENT_QUERY_RFCOMM_SERVICE:
1690         case SDP_EVENT_QUERY_COMPLETE:
1691             // already HCI Events, just forward them
1692             hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size);
1693             socket_connection_send_packet(sdp_client_query_connection, HCI_EVENT_PACKET, 0, packet, size);
1694             break;
1695         default:
1696             break;
1697     }
1698 }
1699 
1700 static void sdp_client_assert_buffer(int size){
1701     if (size > attribute_value_buffer_size){
1702         log_error("SDP attribute value buffer size exceeded: available %d, required %d", attribute_value_buffer_size, size);
1703     }
1704 }
1705 
1706 // define new packet type SDP_CLIENT_PACKET
1707 static void handle_sdp_client_query_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1708     int event_len;
1709 
1710     switch (hci_event_packet_get_type(packet)){
1711         case SDP_EVENT_QUERY_ATTRIBUTE_BYTE:
1712             sdp_client_assert_buffer(sdp_event_query_attribute_byte_get_attribute_length(packet));
1713             attribute_value[sdp_event_query_attribute_byte_get_data_offset(packet)] = sdp_event_query_attribute_byte_get_data(packet);
1714             if ((uint16_t)(sdp_event_query_attribute_byte_get_data_offset(packet)+1) == sdp_event_query_attribute_byte_get_attribute_length(packet)){
1715                 log_info_hexdump(attribute_value, sdp_event_query_attribute_byte_get_attribute_length(packet));
1716 
1717                 int event_len = 1 + 3 * 2 + sdp_event_query_attribute_byte_get_attribute_length(packet);
1718                 uint8_t event[event_len];
1719                 event[0] = SDP_EVENT_QUERY_ATTRIBUTE_VALUE;
1720                 little_endian_store_16(event, 1, sdp_event_query_attribute_byte_get_record_id(packet));
1721                 little_endian_store_16(event, 3, sdp_event_query_attribute_byte_get_attribute_id(packet));
1722                 little_endian_store_16(event, 5, (uint16_t)sdp_event_query_attribute_byte_get_attribute_length(packet));
1723                 memcpy(&event[7], attribute_value, sdp_event_query_attribute_byte_get_attribute_length(packet));
1724                 hci_dump_packet(SDP_CLIENT_PACKET, 0, event, event_len);
1725                 socket_connection_send_packet(sdp_client_query_connection, SDP_CLIENT_PACKET, 0, event, event_len);
1726             }
1727             break;
1728         case SDP_EVENT_QUERY_COMPLETE:
1729             event_len = packet[1] + 2;
1730             hci_dump_packet(HCI_EVENT_PACKET, 0, packet, event_len);
1731             socket_connection_send_packet(sdp_client_query_connection, HCI_EVENT_PACKET, 0, packet, event_len);
1732             break;
1733     }
1734 }
1735 
1736 static void power_notification_callback(POWER_NOTIFICATION_t notification){
1737     switch (notification) {
1738         case POWER_WILL_SLEEP:
1739             // let's sleep
1740             power_management_sleep = 1;
1741             hci_power_control(HCI_POWER_SLEEP);
1742             break;
1743         case POWER_WILL_WAKE_UP:
1744             // assume that all clients use Bluetooth -> if connection, start Bluetooth
1745             power_management_sleep = 0;
1746             if (clients_require_power_on()) {
1747                 hci_power_control(HCI_POWER_ON);
1748             }
1749             break;
1750         default:
1751             break;
1752     }
1753 }
1754 
1755 static void daemon_sigint_handler(int param){
1756 
1757 #ifdef HAVE_PLATFORM_IPHONE_OS
1758     // notify daemons
1759     notify_post("ch.ringwald.btstack.stopped");
1760 #endif
1761 
1762     log_info(" <= SIGINT received, shutting down..\n");
1763 
1764     int send_power_off = 1;
1765 #ifdef HAVE_INTEL_USB
1766     // power off and close only if hci was initialized before
1767     send_power_off = intel_firmware_loaded;
1768 #endif
1769 
1770     if (send_power_off){
1771         hci_power_control( HCI_POWER_OFF);
1772         hci_close();
1773     }
1774 
1775     log_info("Good bye, see you.\n");
1776 
1777     exit(0);
1778 }
1779 
1780 // MARK: manage power off timer
1781 
1782 #define USE_POWER_OFF_TIMER
1783 
1784 static void stop_power_off_timer(void){
1785 #ifdef USE_POWER_OFF_TIMER
1786     if (timeout_active) {
1787         btstack_run_loop_remove_timer(&timeout);
1788         timeout_active = 0;
1789     }
1790 #endif
1791 }
1792 
1793 static void start_power_off_timer(void){
1794 #ifdef USE_POWER_OFF_TIMER
1795     stop_power_off_timer();
1796     btstack_run_loop_set_timer(&timeout, DAEMON_NO_ACTIVE_CLIENT_TIMEOUT);
1797     btstack_run_loop_add_timer(&timeout);
1798     timeout_active = 1;
1799 #else
1800     hci_power_control(HCI_POWER_OFF);
1801 #endif
1802 }
1803 
1804 // MARK: manage list of clients
1805 
1806 
1807 static client_state_t * client_for_connection(connection_t *connection) {
1808     btstack_linked_item_t *it;
1809     for (it = (btstack_linked_item_t *) clients; it ; it = it->next){
1810         client_state_t * client_state = (client_state_t *) it;
1811         if (client_state->connection == connection) {
1812             return client_state;
1813         }
1814     }
1815     return NULL;
1816 }
1817 
1818 static void clients_clear_power_request(void){
1819     btstack_linked_item_t *it;
1820     for (it = (btstack_linked_item_t *) clients; it ; it = it->next){
1821         client_state_t * client_state = (client_state_t *) it;
1822         client_state->power_mode = HCI_POWER_OFF;
1823     }
1824 }
1825 
1826 static int clients_require_power_on(void){
1827 
1828     if (global_enable) return 1;
1829 
1830     btstack_linked_item_t *it;
1831     for (it = (btstack_linked_item_t *) clients; it ; it = it->next){
1832         client_state_t * client_state = (client_state_t *) it;
1833         if (client_state->power_mode == HCI_POWER_ON) {
1834             return 1;
1835         }
1836     }
1837     return 0;
1838 }
1839 
1840 static int clients_require_discoverable(void){
1841     btstack_linked_item_t *it;
1842     for (it = (btstack_linked_item_t *) clients; it ; it = it->next){
1843         client_state_t * client_state = (client_state_t *) it;
1844         if (client_state->discoverable) {
1845             return 1;
1846         }
1847     }
1848     return 0;
1849 }
1850 
1851 static void usage(const char * name) {
1852     printf("%s, BTstack background daemon\n", name);
1853     printf("usage: %s [--help] [--tcp]\n", name);
1854     printf("    --help   display this usage\n");
1855     printf("    --tcp    use TCP server on port %u\n", BTSTACK_PORT);
1856     printf("Without the --tcp option, BTstack Server is listening on unix domain socket %s\n\n", BTSTACK_UNIX);
1857 }
1858 
1859 #ifdef HAVE_PLATFORM_IPHONE_OS
1860 static void * btstack_run_loop_thread(void *context){
1861     btstack_run_loop_execute();
1862     return NULL;
1863 }
1864 #endif
1865 
1866 #ifdef ENABLE_BLE
1867 
1868 static void handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){
1869 
1870     // only handle GATT Events
1871     switch(hci_event_packet_get_type(packet)){
1872         case GATT_EVENT_SERVICE_QUERY_RESULT:
1873         case GATT_EVENT_INCLUDED_SERVICE_QUERY_RESULT:
1874         case GATT_EVENT_NOTIFICATION:
1875         case GATT_EVENT_INDICATION:
1876         case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT:
1877         case GATT_EVENT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
1878         case GATT_EVENT_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
1879         case GATT_EVENT_LONG_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
1880         case GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT:
1881         case GATT_EVENT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT:
1882         case GATT_EVENT_QUERY_COMPLETE:
1883            break;
1884         default:
1885             return;
1886     }
1887 
1888     hci_con_handle_t con_handle = little_endian_read_16(packet, 2);
1889     btstack_linked_list_gatt_client_helper_t * gatt_client_helper = daemon_get_gatt_client_helper(con_handle);
1890     if (!gatt_client_helper){
1891         log_info("daemon handle_gatt_client_event: gc helper for handle 0x%2x is NULL.", con_handle);
1892         return;
1893     }
1894 
1895     connection_t *connection = NULL;
1896 
1897     // daemon doesn't track which connection subscribed to this particular handle, so we just notify all connections
1898     switch(hci_event_packet_get_type(packet)){
1899         case GATT_EVENT_NOTIFICATION:
1900         case GATT_EVENT_INDICATION:{
1901             hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size);
1902 
1903             btstack_linked_item_t *it;
1904             for (it = (btstack_linked_item_t *) clients; it ; it = it->next){
1905                 client_state_t * client_state = (client_state_t *) it;
1906                 socket_connection_send_packet(client_state->connection, HCI_EVENT_PACKET, 0, packet, size);
1907             }
1908             return;
1909         }
1910         default:
1911             break;
1912     }
1913 
1914     // otherwise, we have to have an active connection
1915     connection = gatt_client_helper->active_connection;
1916     uint16_t offset;
1917     uint16_t length;
1918 
1919     if (!connection) return;
1920 
1921     switch(hci_event_packet_get_type(packet)){
1922 
1923         case GATT_EVENT_SERVICE_QUERY_RESULT:
1924         case GATT_EVENT_INCLUDED_SERVICE_QUERY_RESULT:
1925         case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT:
1926         case GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT:
1927         case GATT_EVENT_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
1928         case GATT_EVENT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
1929             hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size);
1930             socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, packet, size);
1931             break;
1932 
1933         case GATT_EVENT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT:
1934         case GATT_EVENT_LONG_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
1935             offset = little_endian_read_16(packet, 6);
1936             length = little_endian_read_16(packet, 8);
1937             gatt_client_helper->characteristic_buffer[0] = hci_event_packet_get_type(packet);  // store type (characteristic/descriptor)
1938             gatt_client_helper->characteristic_handle    = little_endian_read_16(packet, 4);   // store attribute handle
1939             gatt_client_helper->characteristic_length = offset + length;            // update length
1940             memcpy(&gatt_client_helper->characteristic_buffer[10 + offset], &packet[10], length);
1941             break;
1942 
1943         case GATT_EVENT_QUERY_COMPLETE:{
1944             gatt_client_helper->active_connection = NULL;
1945             if (gatt_client_helper->characteristic_length){
1946                 // send re-combined long characteristic value or long characteristic descriptor value
1947                 uint8_t * event = gatt_client_helper->characteristic_buffer;
1948                 uint16_t event_size = 10 + gatt_client_helper->characteristic_length;
1949                 // event[0] == already set by previsous case
1950                 event[1] = 8 + gatt_client_helper->characteristic_length;
1951                 little_endian_store_16(event, 2, little_endian_read_16(packet, 2));
1952                 little_endian_store_16(event, 4, gatt_client_helper->characteristic_handle);
1953                 little_endian_store_16(event, 6, 0);   // offset
1954                 little_endian_store_16(event, 8, gatt_client_helper->characteristic_length);
1955                 hci_dump_packet(HCI_EVENT_PACKET, 0, event, event_size);
1956                 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, event_size);
1957                 gatt_client_helper->characteristic_length = 0;
1958             }
1959             hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size);
1960             socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, packet, size);
1961             break;
1962         }
1963         default:
1964             break;
1965     }
1966 }
1967 #endif
1968 
1969 static char hostname[30];
1970 
1971 static void btstack_server_configure_stack(void){
1972     // init HCI
1973     hci_init(transport, config);
1974     if (btstack_link_key_db){
1975         hci_set_link_key_db(btstack_link_key_db);
1976     }
1977     if (control){
1978         hci_set_control(control);
1979     }
1980 
1981     // hostname for POSIX systems
1982     gethostname(hostname, 30);
1983     hostname[29] = '\0';
1984     gap_set_local_name(hostname);
1985 
1986 #ifdef HAVE_PLATFORM_IPHONE_OS
1987     // iPhone doesn't use SSP yet as there's no UI for it yet and auto accept is not an option
1988     gap_ssp_set_enable(0);
1989 #endif
1990 
1991     // register for HCI events
1992     hci_event_callback_registration.callback = &stack_packet_handler;
1993     hci_add_event_handler(&hci_event_callback_registration);
1994 
1995     // init L2CAP
1996     l2cap_init();
1997     l2cap_register_packet_handler(&stack_packet_handler);
1998     timeout.process = daemon_no_connections_timeout;
1999 
2000 #ifdef ENABLE_RFCOMM
2001     log_info("config.h: ENABLE_RFCOMM\n");
2002     rfcomm_init();
2003 #endif
2004 
2005 #ifdef ENABLE_SDP
2006     sdp_init();
2007 #endif
2008 
2009 #ifdef ENABLE_BLE
2010     sm_init();
2011     sm_event_callback_registration.callback = &stack_packet_handler;
2012     sm_add_event_handler(&sm_event_callback_registration);
2013     // sm_set_io_capabilities(IO_CAPABILITY_DISPLAY_ONLY);
2014     // sm_set_authentication_requirements( SM_AUTHREQ_BONDING | SM_AUTHREQ_MITM_PROTECTION);
2015 
2016     // GATT Client
2017     gatt_client_init();
2018 
2019     // GATT Server - empty attribute database
2020     att_server_init(NULL, NULL, NULL);
2021 
2022 #endif
2023 }
2024 
2025 int btstack_server_run(int tcp_flag){
2026 
2027     if (tcp_flag){
2028         printf("BTstack Server started on port %u\n", BTSTACK_PORT);
2029     } else {
2030         printf("BTstack Server started on socket %s\n", BTSTACK_UNIX);
2031     }
2032 
2033     // handle default init
2034     if (!btstack_server_storage_path){
2035 #ifdef _WIN32
2036         btstack_server_storage_path = strdup(".");
2037 #else
2038         btstack_server_storage_path = strdup("/tmp");
2039 #endif
2040     }
2041 
2042     // make stdout unbuffered
2043     setbuf(stdout, NULL);
2044 
2045     // handle CTRL-c
2046     signal(SIGINT, daemon_sigint_handler);
2047     // handle SIGTERM - suggested for launchd
2048     signal(SIGTERM, daemon_sigint_handler);
2049 
2050     socket_connection_init();
2051 
2052     btstack_control_t * control = NULL;
2053     const btstack_uart_block_t * uart_block_implementation = NULL;
2054     (void) uart_block_implementation;
2055 
2056 #ifdef HAVE_TRANSPORT_H4
2057     hci_transport_config_uart.type = HCI_TRANSPORT_CONFIG_UART;
2058     hci_transport_config_uart.baudrate_init = UART_SPEED;
2059     hci_transport_config_uart.baudrate_main = 0;
2060     hci_transport_config_uart.flowcontrol = 1;
2061     hci_transport_config_uart.device_name   = UART_DEVICE;
2062 
2063 #ifndef HAVE_PLATFORM_IPHONE_OS
2064 #ifdef _WIN32
2065     uart_block_implementation = btstack_uart_block_windows_instance();
2066 #else
2067     uart_block_implementation = btstack_uart_block_posix_instance();
2068 #endif
2069 #endif
2070 
2071 #ifdef HAVE_PLATFORM_IPHONE_OS
2072     // use default (max) UART baudrate over netgraph interface
2073     hci_transport_config_uart.baudrate_init = 0;
2074 #endif
2075 
2076     config = &hci_transport_config_uart;
2077     transport = hci_transport_h4_instance(uart_block_implementation);
2078 #endif
2079 
2080 #ifdef HAVE_TRANSPORT_USB
2081     transport = hci_transport_usb_instance();
2082 #endif
2083 
2084 #ifdef HAVE_PLATFORM_IPHONE_OS
2085     control = &btstack_control_iphone;
2086     if (btstack_control_iphone_power_management_supported()){
2087         hci_transport_h4_iphone_set_enforce_wake_device("/dev/btwake");
2088     }
2089     bluetooth_status_handler = platform_iphone_status_handler;
2090     platform_iphone_register_window_manager_restart(update_ui_status);
2091     platform_iphone_register_preferences_changed(preferences_changed_callback);
2092 #endif
2093 
2094 #ifdef BTSTACK_DEVICE_NAME_DB_INSTANCE
2095     btstack_device_name_db = BTSTACK_DEVICE_NAME_DB_INSTANCE();
2096 #endif
2097 
2098 #ifdef _WIN32
2099     btstack_run_loop_init(btstack_run_loop_windows_get_instance());
2100 #else
2101     btstack_run_loop_init(btstack_run_loop_posix_get_instance());
2102 #endif
2103 
2104     // init power management notifications
2105     if (control && control->register_for_power_notifications){
2106         control->register_for_power_notifications(power_notification_callback);
2107     }
2108 
2109     // logging
2110     loggingEnabled = 0;
2111     int newLoggingEnabled = 1;
2112 #ifdef HAVE_PLATFORM_IPHONE_OS
2113     // iPhone has toggle in Preferences.app
2114     newLoggingEnabled = platform_iphone_logging_enabled();
2115 #endif
2116     daemon_set_logging_enabled(newLoggingEnabled);
2117 
2118     // dump version
2119     log_info("BTStack Server started\n");
2120     log_info("version %s, build %s", BTSTACK_VERSION, BTSTACK_DATE);
2121 
2122 #ifndef HAVE_INTEL_USB
2123     btstack_server_configure_stack();
2124 #endif
2125 
2126 #ifdef USE_LAUNCHD
2127     socket_connection_create_launchd();
2128 #else
2129     // create server
2130     if (tcp_flag) {
2131         socket_connection_create_tcp(BTSTACK_PORT);
2132     } else {
2133 #ifdef HAVE_UNIX_SOCKETS
2134         socket_connection_create_unix(BTSTACK_UNIX);
2135 #endif
2136     }
2137 #endif
2138     socket_connection_register_packet_callback(&daemon_client_handler);
2139 
2140 #ifdef HAVE_PLATFORM_IPHONE_OS
2141     // notify daemons
2142     notify_post("ch.ringwald.btstack.started");
2143 
2144     // spawn thread to have BTstack run loop on new thread, while main thread is used to keep CFRunLoop
2145     pthread_t run_loop;
2146     pthread_create(&run_loop, NULL, &btstack_run_loop_thread, NULL);
2147 
2148     // needed to receive notifications
2149     CFRunLoopRun();
2150 #endif
2151         // go!
2152     btstack_run_loop_execute();
2153     return 0;
2154 }
2155 
2156 int btstack_server_run_tcp(void){
2157      return btstack_server_run(1);
2158 }
2159 
2160 int main (int argc,  char * const * argv){
2161 
2162     int tcp_flag = 0;
2163     struct option long_options[] = {
2164         { "tcp", no_argument, &tcp_flag, 1 },
2165         { "help", no_argument, 0, 0 },
2166         { 0,0,0,0 } // This is a filler for -1
2167     };
2168 
2169     while (1) {
2170         int c;
2171         int option_index = -1;
2172         c = getopt_long(argc, argv, "h", long_options, &option_index);
2173         if (c == -1) break; // no more option
2174 
2175         // treat long parameter first
2176         if (option_index == -1) {
2177             switch (c) {
2178                 case '?':
2179                 case 'h':
2180                     usage(argv[0]);
2181                     return 0;
2182                     break;
2183             }
2184         } else {
2185             switch (option_index) {
2186                 case 1:
2187                     usage(argv[0]);
2188                     return 0;
2189                     break;
2190             }
2191         }
2192     }
2193 
2194 #ifndef HAVE_UNIX_SOCKETS
2195     // TCP is default if there are no unix sockets
2196     tcp_flag = 1;
2197 #endif
2198 
2199     btstack_server_run(tcp_flag);
2200 }
2201 
2202 void btstack_server_set_storage_path(const char * path){
2203     if (btstack_server_storage_path){
2204         free((void*)btstack_server_storage_path);
2205         btstack_server_storage_path = NULL;
2206     }
2207     btstack_server_storage_path = strdup(path);
2208     log_info("Storage path %s", btstack_server_storage_path);
2209 }
2210