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