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