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