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