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