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