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