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