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