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