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