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