xref: /btstack/platform/daemon/src/daemon.c (revision 1ca3442b095800932529ce1cb5cf48a479563c50)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 /*
39  *  daemon.c
40  *
41  *  Created by Matthias Ringwald on 7/1/09.
42  *
43  *  BTstack background daemon
44  *
45  */
46 
47 #include "btstack-config.h"
48 
49 #include <pthread.h>
50 #include <signal.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <strings.h>
54 #include <unistd.h>
55 
56 #include <getopt.h>
57 
58 #include "btstack.h"
59 #include "linked_list.h"
60 #include "run_loop.h"
61 #include "hci_cmds.h"
62 #include "version.h"
63 
64 #include "debug.h"
65 #include "hci.h"
66 #include "hci_dump.h"
67 #include "hci_transport.h"
68 #include "l2cap.h"
69 #include "rfcomm.h"
70 #include "sdp.h"
71 #include "sdp_parser.h"
72 #include "sdp_client.h"
73 #include "sdp_query_util.h"
74 #include "sdp_query_rfcomm.h"
75 #include "socket_connection.h"
76 
77 #ifdef HAVE_BLE
78 #include "gatt_client.h"
79 #include "att_server.h"
80 #include "att.h"
81 #include "le_device_db.h"
82 #include "sm.h"
83 #endif
84 
85 #ifdef USE_BLUETOOL
86 #include <CoreFoundation/CoreFoundation.h>
87 #include "../platforms/ios/src/bt_control_iphone.h"
88 #include <notify.h>
89 #endif
90 
91 #ifdef USE_SPRINGBOARD
92 #include "../platforms/ios/src/platform_iphone.h"
93 #endif
94 
95 #ifndef BTSTACK_LOG_FILE
96 #define BTSTACK_LOG_FILE "/tmp/hci_dump.pklg"
97 #endif
98 
99 // use logger: format HCI_DUMP_PACKETLOGGER, HCI_DUMP_BLUEZ or HCI_DUMP_STDOUT
100 #ifndef BTSTACK_LOG_TYPE
101 #define BTSTACK_LOG_TYPE HCI_DUMP_PACKETLOGGER
102 #endif
103 
104 #define DAEMON_NO_ACTIVE_CLIENT_TIMEOUT 10000
105 
106 #define ATT_MAX_LONG_ATTRIBUTE_SIZE 512
107 
108 
109 #define SERVICE_LENGTH                      20
110 #define CHARACTERISTIC_LENGTH               24
111 #define CHARACTERISTIC_DESCRIPTOR_LENGTH    18
112 
113 // ATT_MTU - 1
114 #define ATT_MAX_ATTRIBUTE_SIZE 22
115 
116 typedef struct {
117     // linked list - assert: first field
118     linked_item_t    item;
119 
120     // connection
121     connection_t * connection;
122 
123     linked_list_t rfcomm_cids;
124     linked_list_t rfcomm_services;
125     linked_list_t l2cap_cids;
126     linked_list_t l2cap_psms;
127     linked_list_t sdp_record_handles;
128     linked_list_t gatt_con_handles;
129     // power mode
130     HCI_POWER_MODE power_mode;
131 
132     // discoverable
133     uint8_t        discoverable;
134 
135 } client_state_t;
136 
137 typedef struct linked_list_uint32 {
138     linked_item_t   item;
139     uint32_t        value;
140 } linked_list_uint32_t;
141 
142 typedef struct linked_list_connection {
143     linked_item_t   item;
144     connection_t  * connection;
145 } linked_list_connection_t;
146 
147 typedef struct linked_list_gatt_client_helper{
148     linked_item_t item;
149     uint16_t con_handle;
150     connection_t * active_connection;   // the one that started the current query
151     linked_list_t  all_connections;     // list of all connections that ever used this helper
152     uint16_t characteristic_length;
153     uint16_t characteristic_handle;
154     uint8_t  characteristic_buffer[10 + ATT_MAX_LONG_ATTRIBUTE_SIZE];   // header for sending event right away
155     uint8_t  long_query_type;
156 } linked_list_gatt_client_helper_t;
157 
158 // MARK: prototypes
159 static void handle_sdp_rfcomm_service_result(sdp_query_event_t * event, void * context);
160 static void handle_sdp_client_query_result(sdp_query_event_t * event);
161 static void dummy_bluetooth_status_handler(BLUETOOTH_STATE state);
162 static client_state_t * client_for_connection(connection_t *connection);
163 static int              clients_require_power_on(void);
164 static int              clients_require_discoverable(void);
165 static void              clients_clear_power_request(void);
166 static void start_power_off_timer(void);
167 static void stop_power_off_timer(void);
168 static client_state_t * client_for_connection(connection_t *connection);
169 
170 
171 // MARK: globals
172 static hci_transport_t * transport;
173 static hci_uart_config_t config;
174 static timer_source_t timeout;
175 static uint8_t timeout_active = 0;
176 static int power_management_sleep = 0;
177 static linked_list_t clients = NULL;        // list of connected clients `
178 #ifdef HAVE_BLE
179 static linked_list_t gatt_client_helpers = NULL;   // list of used gatt client (helpers)
180 static uint16_t gatt_client_id = 0;
181 #endif
182 
183 static void (*bluetooth_status_handler)(BLUETOOTH_STATE state) = dummy_bluetooth_status_handler;
184 
185 static int global_enable = 0;
186 
187 static remote_device_db_t const * remote_device_db = NULL;
188 static int rfcomm_channel_generator = 1;
189 
190 static uint8_t   attribute_value[1000];
191 static const int attribute_value_buffer_size = sizeof(attribute_value);
192 static uint8_t serviceSearchPattern[200];
193 static uint8_t attributeIDList[50];
194 static void * sdp_client_query_connection;
195 
196 static int loggingEnabled;
197 
198 static void dummy_bluetooth_status_handler(BLUETOOTH_STATE state){
199     log_info("Bluetooth status: %u\n", state);
200 };
201 
202 static void daemon_no_connections_timeout(struct timer *ts){
203     if (clients_require_power_on()) return;    // false alarm :)
204     log_info("No active client connection for %u seconds -> POWER OFF\n", DAEMON_NO_ACTIVE_CLIENT_TIMEOUT/1000);
205     hci_power_control(HCI_POWER_OFF);
206 }
207 
208 
209 static void add_uint32_to_list(linked_list_t *list, uint32_t value){
210     linked_list_uint32_t * item = malloc(sizeof(linked_list_uint32_t));
211     if (!item) return;
212     item->value = value;
213     linked_list_add(list, (linked_item_t *) item);
214 }
215 
216 static void remove_and_free_uint32_from_list(linked_list_t *list, uint32_t value){
217     linked_list_iterator_t it;
218     linked_list_iterator_init(&it, list);
219     while (linked_list_iterator_has_next(&it)){
220         linked_list_uint32_t * item = (linked_list_uint32_t*) linked_list_iterator_next(&it);
221         if ( item->value != value) continue;
222         linked_list_remove(list, (linked_item_t *) item);
223         free(item);
224     }
225 }
226 
227 static void daemon_add_client_rfcomm_service(connection_t * connection, uint16_t service_channel){
228     client_state_t * client_state = client_for_connection(connection);
229     if (!client_state) return;
230     add_uint32_to_list(&client_state->rfcomm_services, service_channel);
231 }
232 
233 static void daemon_remove_client_rfcomm_service(connection_t * connection, uint16_t service_channel){
234     client_state_t * client_state = client_for_connection(connection);
235     if (!client_state) return;
236     remove_and_free_uint32_from_list(&client_state->rfcomm_services, service_channel);
237 }
238 
239 static void daemon_add_client_rfcomm_channel(connection_t * connection, uint16_t cid){
240     client_state_t * client_state = client_for_connection(connection);
241     if (!client_state) return;
242     add_uint32_to_list(&client_state->rfcomm_cids, cid);
243 }
244 
245 static void daemon_remove_client_rfcomm_channel(connection_t * connection, uint16_t cid){
246     client_state_t * client_state = client_for_connection(connection);
247     if (!client_state) return;
248     remove_and_free_uint32_from_list(&client_state->rfcomm_cids, cid);
249 }
250 
251 static void daemon_add_client_l2cap_service(connection_t * connection, uint16_t psm){
252     client_state_t * client_state = client_for_connection(connection);
253     if (!client_state) return;
254     add_uint32_to_list(&client_state->l2cap_psms, psm);
255 }
256 
257 static void daemon_remove_client_l2cap_service(connection_t * connection, uint16_t psm){
258     client_state_t * client_state = client_for_connection(connection);
259     if (!client_state) return;
260     remove_and_free_uint32_from_list(&client_state->l2cap_psms, psm);
261 }
262 
263 static void daemon_add_client_l2cap_channel(connection_t * connection, uint16_t cid){
264     client_state_t * client_state = client_for_connection(connection);
265     if (!client_state) return;
266     add_uint32_to_list(&client_state->l2cap_cids, cid);
267 }
268 
269 static void daemon_remove_client_l2cap_channel(connection_t * connection, uint16_t cid){
270     client_state_t * client_state = client_for_connection(connection);
271     if (!client_state) return;
272     remove_and_free_uint32_from_list(&client_state->l2cap_cids, cid);
273 }
274 
275 static void daemon_add_client_sdp_service_record_handle(connection_t * connection, uint32_t handle){
276     client_state_t * client_state = client_for_connection(connection);
277     if (!client_state) return;
278     add_uint32_to_list(&client_state->sdp_record_handles, handle);
279 }
280 
281 static void daemon_remove_client_sdp_service_record_handle(connection_t * connection, uint32_t handle){
282     client_state_t * client_state = client_for_connection(connection);
283     if (!client_state) return;
284     remove_and_free_uint32_from_list(&client_state->sdp_record_handles, handle);
285 }
286 
287 #ifdef HAVE_BLE
288 static void daemon_add_gatt_client_handle(connection_t * connection, uint32_t handle){
289     client_state_t * client_state = client_for_connection(connection);
290     if (!client_state) return;
291 
292     // check if handle already exists in the gatt_con_handles list
293     linked_list_iterator_t it;
294     int handle_found = 0;
295     linked_list_iterator_init(&it, &client_state->gatt_con_handles);
296     while (linked_list_iterator_has_next(&it)){
297         linked_list_uint32_t * item = (linked_list_uint32_t*) linked_list_iterator_next(&it);
298         if (item->value == handle){
299             handle_found = 1;
300             break;
301         }
302     }
303     // if handle doesn't exist add it to gatt_con_handles
304     if (!handle_found){
305         add_uint32_to_list(&client_state->gatt_con_handles, handle);
306     }
307 
308     // check if there is a helper with given handle
309     linked_list_gatt_client_helper_t * gatt_helper = NULL;
310     linked_list_iterator_init(&it, &gatt_client_helpers);
311     while (linked_list_iterator_has_next(&it)){
312         linked_list_gatt_client_helper_t * item = (linked_list_gatt_client_helper_t*) linked_list_iterator_next(&it);
313         if (item->con_handle == handle){
314             gatt_helper = item;
315             break;
316         }
317     }
318 
319     // if gatt_helper doesn't exist, create it and add it to gatt_client_helpers list
320     if (!gatt_helper){
321         gatt_helper = malloc(sizeof(linked_list_gatt_client_helper_t));
322         if (!gatt_helper) return;
323         memset(gatt_helper, 0, sizeof(linked_list_gatt_client_helper_t));
324         gatt_helper->con_handle = handle;
325         linked_list_add(&gatt_client_helpers, (linked_item_t *) gatt_helper);
326     }
327 
328     // check if connection exists
329     int connection_found = 0;
330     linked_list_iterator_init(&it, &gatt_helper->all_connections);
331     while (linked_list_iterator_has_next(&it)){
332         linked_list_connection_t * item = (linked_list_connection_t*) linked_list_iterator_next(&it);
333         if (item->connection == connection){
334             connection_found = 1;
335             break;
336         }
337     }
338 
339     // if connection is not found, add it to the all_connections, and set it as active connection
340     if (!connection_found){
341         linked_list_connection_t * con = malloc(sizeof(linked_list_connection_t));
342         if (!con) return;
343         memset(con, 0, sizeof(linked_list_connection_t));
344         con->connection = connection;
345         linked_list_add(&gatt_helper->all_connections, (linked_item_t *)con);
346     }
347 }
348 
349 
350 static void daemon_remove_gatt_client_handle(connection_t * connection, uint32_t handle){
351     // PART 1 - uses connection & handle
352     // might be extracted or vanish totally
353     client_state_t * client_state = client_for_connection(connection);
354     if (!client_state) return;
355 
356     linked_list_iterator_t it;
357     // remove handle from gatt_con_handles list
358     linked_list_iterator_init(&it, &client_state->gatt_con_handles);
359     while (linked_list_iterator_has_next(&it)){
360         linked_list_uint32_t * item = (linked_list_uint32_t*) linked_list_iterator_next(&it);
361         if (item->value == handle){
362             linked_list_remove(&client_state->gatt_con_handles, (linked_item_t *) item);
363             free(item);
364         }
365     }
366 
367     // PART 2 - only uses handle
368 
369     // find helper with given handle
370     linked_list_gatt_client_helper_t * helper = NULL;
371     linked_list_iterator_init(&it, &gatt_client_helpers);
372     while (linked_list_iterator_has_next(&it)){
373         linked_list_gatt_client_helper_t * item = (linked_list_gatt_client_helper_t*) linked_list_iterator_next(&it);
374         if (item->con_handle == handle){
375             helper = item;
376             break;
377         }
378     }
379 
380     if (!helper) return;
381     // remove connection from helper
382     linked_list_iterator_init(&it, &helper->all_connections);
383     while (linked_list_iterator_has_next(&it)){
384         linked_list_connection_t * item = (linked_list_connection_t*) linked_list_iterator_next(&it);
385         if (item->connection == connection){
386             linked_list_remove(&helper->all_connections, (linked_item_t *) item);
387             free(item);
388             break;
389         }
390     }
391 
392     if (helper->active_connection == connection){
393         helper->active_connection = NULL;
394     }
395     // if helper has no more connections, call disconnect
396     if (helper->all_connections == NULL){
397         gap_disconnect((hci_con_handle_t) helper->con_handle);
398     }
399 }
400 
401 
402 static void daemon_remove_gatt_client_helper(uint32_t con_handle){
403     linked_list_iterator_t it, cl;
404     // find helper with given handle
405     linked_list_gatt_client_helper_t * helper = NULL;
406     linked_list_iterator_init(&it, &gatt_client_helpers);
407     while (linked_list_iterator_has_next(&it)){
408         linked_list_gatt_client_helper_t * item = (linked_list_gatt_client_helper_t*) linked_list_iterator_next(&it);
409         if (item->con_handle == con_handle){
410             helper = item;
411             break;
412         }
413     }
414 
415     if (!helper) return;
416 
417     // remove all connection from helper
418     linked_list_iterator_init(&it, &helper->all_connections);
419     while (linked_list_iterator_has_next(&it)){
420         linked_list_connection_t * item = (linked_list_connection_t*) linked_list_iterator_next(&it);
421         linked_list_remove(&helper->all_connections, (linked_item_t *) item);
422         free(item);
423     }
424 
425     linked_list_remove(&gatt_client_helpers, (linked_item_t *) helper);
426     free(helper);
427 
428     linked_list_iterator_init(&cl, &clients);
429     while (linked_list_iterator_has_next(&cl)){
430         client_state_t * client_state = (client_state_t *) linked_list_iterator_next(&cl);
431         linked_list_iterator_init(&it, &client_state->gatt_con_handles);
432         while (linked_list_iterator_has_next(&it)){
433             linked_list_uint32_t * item = (linked_list_uint32_t*) linked_list_iterator_next(&it);
434             if (item->value == con_handle){
435                 linked_list_remove(&client_state->gatt_con_handles, (linked_item_t *) item);
436                 free(item);
437             }
438         }
439     }
440 }
441 #endif
442 
443 static void daemon_rfcomm_close_connection(client_state_t * gatt_client){
444     linked_list_iterator_t it;
445     linked_list_t *rfcomm_services = &gatt_client->rfcomm_services;
446     linked_list_t *rfcomm_cids = &gatt_client->rfcomm_cids;
447 
448     linked_list_iterator_init(&it, rfcomm_services);
449     while (linked_list_iterator_has_next(&it)){
450         linked_list_uint32_t * item = (linked_list_uint32_t*) linked_list_iterator_next(&it);
451         rfcomm_unregister_service_internal(item->value);
452         linked_list_remove(rfcomm_services, (linked_item_t *) item);
453         free(item);
454     }
455 
456     linked_list_iterator_init(&it, rfcomm_cids);
457     while (linked_list_iterator_has_next(&it)){
458         linked_list_uint32_t * item = (linked_list_uint32_t*) linked_list_iterator_next(&it);
459         rfcomm_disconnect_internal(item->value);
460         linked_list_remove(rfcomm_cids, (linked_item_t *) item);
461         free(item);
462     }
463 }
464 
465 
466 static void daemon_l2cap_close_connection(client_state_t * gatt_client){
467     linked_list_iterator_t it;
468     linked_list_t *l2cap_psms = &gatt_client->l2cap_psms;
469     linked_list_t *l2cap_cids = &gatt_client->l2cap_cids;
470 
471     linked_list_iterator_init(&it, l2cap_psms);
472     while (linked_list_iterator_has_next(&it)){
473         linked_list_uint32_t * item = (linked_list_uint32_t*) linked_list_iterator_next(&it);
474         l2cap_unregister_service_internal(NULL, item->value);
475         linked_list_remove(l2cap_psms, (linked_item_t *) item);
476         free(item);
477     }
478 
479     linked_list_iterator_init(&it, l2cap_cids);
480     while (linked_list_iterator_has_next(&it)){
481         linked_list_uint32_t * item = (linked_list_uint32_t*) linked_list_iterator_next(&it);
482         l2cap_disconnect_internal(item->value, 0); // note: reason isn't used
483         linked_list_remove(l2cap_cids, (linked_item_t *) item);
484         free(item);
485     }
486 }
487 
488 static void daemon_sdp_close_connection(client_state_t * gatt_client){
489     linked_list_t * list = &gatt_client->sdp_record_handles;
490     linked_list_iterator_t it;
491     linked_list_iterator_init(&it, list);
492     while (linked_list_iterator_has_next(&it)){
493         linked_list_uint32_t * item = (linked_list_uint32_t*) linked_list_iterator_next(&it);
494         sdp_unregister_service_internal(&gatt_client->connection, item->value);
495         linked_list_remove(list, (linked_item_t *) item);
496         free(item);
497     }
498 }
499 
500 #ifdef HAVE_BLE
501 static void daemon_gatt_client_close_connection(connection_t * connection){
502     client_state_t * client = client_for_connection(connection);
503     if (!client) return;
504 
505     linked_list_iterator_t it;
506     linked_list_iterator_init(&it, &client->gatt_con_handles);
507     while (linked_list_iterator_has_next(&it)){
508         linked_list_uint32_t * item = (linked_list_uint32_t*) linked_list_iterator_next(&it);
509         daemon_remove_gatt_client_handle(connection, item->value);
510     }
511 }
512 #endif
513 
514 static void daemon_disconnect_client(connection_t * connection){
515     log_info("Daemon disconnect client %p\n",connection);
516 
517     client_state_t * client = client_for_connection(connection);
518     if (!client) return;
519 
520     daemon_sdp_close_connection(client);
521     daemon_rfcomm_close_connection(client);
522     daemon_l2cap_close_connection(client);
523 #ifdef HAVE_BLE
524     // NOTE: experimental - disconnect all LE connections where GATT Client was used
525     // gatt_client_disconnect_connection(connection);
526     daemon_gatt_client_close_connection(connection);
527 #endif
528 
529     linked_list_remove(&clients, (linked_item_t *) client);
530     free(client);
531 }
532 
533 #ifdef HAVE_BLE
534 
535 linked_list_gatt_client_helper_t * daemon_get_gatt_client_helper(uint16_t handle) {
536     linked_list_iterator_t it;
537     if (!gatt_client_helpers) return NULL;
538     log_info("daemon_get_gatt_client_helper for handle 0x%02x", handle);
539 
540     linked_list_iterator_init(&it, &gatt_client_helpers);
541     while (linked_list_iterator_has_next(&it)){
542         linked_list_gatt_client_helper_t * item = (linked_list_gatt_client_helper_t*) linked_list_iterator_next(&it);
543         if (!item ) {
544             log_info("daemon_get_gatt_client_helper gatt_client_helpers null item");
545             break;
546         }
547         if (item->con_handle == handle){
548             return item;
549         }
550     }
551     log_info("daemon_get_gatt_client_helper for handle 0x%02x is NULL.", handle);
552     return NULL;
553 }
554 
555 static void send_gatt_query_complete(connection_t * connection, uint16_t handle, uint8_t status){
556     // @format H1
557     uint8_t event[5];
558     event[0] = GATT_QUERY_COMPLETE;
559     event[1] = 3;
560     bt_store_16(event, 2, handle);
561     event[4] = status;
562     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
563     socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event));
564 }
565 
566 static void send_gatt_mtu_event(connection_t * connection, uint16_t handle, uint16_t mtu){
567     uint8_t event[6];
568     int pos = 0;
569     event[pos++] = GATT_MTU;
570     event[pos++] = sizeof(event) - 2;
571     bt_store_16(event, pos, handle);
572     pos += 2;
573     bt_store_16(event, pos, mtu);
574     pos += 2;
575     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
576     socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event));
577 }
578 
579 linked_list_gatt_client_helper_t * daemon_setup_gatt_client_request(connection_t *connection, uint8_t *packet, int track_active_connection) {
580     hci_con_handle_t handle = READ_BT_16(packet, 3);
581     log_info("daemon_setup_gatt_client_request for handle 0x%02x", handle);
582     hci_connection_t * hci_con = hci_connection_for_handle(handle);
583     if ((hci_con == NULL) || (hci_con->state != OPEN)){
584         send_gatt_query_complete(connection, handle, GATT_CLIENT_NOT_CONNECTED);
585         return NULL;
586     }
587 
588     linked_list_gatt_client_helper_t * helper = daemon_get_gatt_client_helper(handle);
589 
590     if (!helper){
591         log_info("helper does not exist");
592         helper = malloc(sizeof(linked_list_gatt_client_helper_t));
593         if (!helper) return NULL;
594         memset(helper, 0, sizeof(linked_list_gatt_client_helper_t));
595         helper->con_handle = handle;
596         linked_list_add(&gatt_client_helpers, (linked_item_t *) helper);
597     }
598 
599     if (track_active_connection && helper->active_connection){
600         send_gatt_query_complete(connection, handle, GATT_CLIENT_BUSY);
601         return NULL;
602     }
603 
604     daemon_add_gatt_client_handle(connection, handle);
605 
606     if (track_active_connection){
607         // remember connection responsible for this request
608         helper->active_connection = connection;
609     }
610 
611     return helper;
612 }
613 
614 // (de)serialize structs from/to HCI commands/events
615 
616 void daemon_gatt_deserialize_service(uint8_t *packet, int offset, le_service_t *service){
617     service->start_group_handle = READ_BT_16(packet, offset);
618     service->end_group_handle = READ_BT_16(packet, offset + 2);
619     swap128(&packet[offset + 4], service->uuid128);
620 }
621 
622 void daemon_gatt_serialize_service(le_service_t * service, uint8_t * event, int offset){
623     bt_store_16(event, offset, service->start_group_handle);
624     bt_store_16(event, offset+2, service->end_group_handle);
625     swap128(service->uuid128, &event[offset + 4]);
626 }
627 
628 void daemon_gatt_deserialize_characteristic(uint8_t * packet, int offset, le_characteristic_t * characteristic){
629     characteristic->start_handle = READ_BT_16(packet, offset);
630     characteristic->value_handle = READ_BT_16(packet, offset + 2);
631     characteristic->end_handle = READ_BT_16(packet, offset + 4);
632     characteristic->properties = READ_BT_16(packet, offset + 6);
633     characteristic->uuid16 = READ_BT_16(packet, offset + 8);
634     swap128(&packet[offset+10], characteristic->uuid128);
635 }
636 
637 void daemon_gatt_serialize_characteristic(le_characteristic_t * characteristic, uint8_t * event, int offset){
638     bt_store_16(event, offset, characteristic->start_handle);
639     bt_store_16(event, offset+2, characteristic->value_handle);
640     bt_store_16(event, offset+4, characteristic->end_handle);
641     bt_store_16(event, offset+6, characteristic->properties);
642     swap128(characteristic->uuid128, &event[offset+8]);
643 }
644 
645 void daemon_gatt_deserialize_characteristic_descriptor(uint8_t * packet, int offset, le_characteristic_descriptor_t * descriptor){
646     descriptor->handle = READ_BT_16(packet, offset);
647     swap128(&packet[offset+2], descriptor->uuid128);
648 }
649 
650 void daemon_gatt_serialize_characteristic_descriptor(le_characteristic_descriptor_t * characteristic_descriptor, uint8_t * event, int offset){
651     bt_store_16(event, offset, characteristic_descriptor->handle);
652     swap128(characteristic_descriptor->uuid128, &event[offset+2]);
653 }
654 
655 #endif
656 
657 static int btstack_command_handler(connection_t *connection, uint8_t *packet, uint16_t size){
658 
659     bd_addr_t addr;
660     bd_addr_type_t addr_type;
661     hci_con_handle_t handle;
662     uint16_t cid;
663     uint16_t psm;
664     uint16_t service_channel;
665     uint16_t mtu;
666     uint8_t  reason;
667     uint8_t  rfcomm_channel;
668     uint8_t  rfcomm_credits;
669     uint32_t service_record_handle;
670     client_state_t *client;
671 
672 #if defined(HAVE_MALLOC) && defined(HAVE_BLE)
673     uint8_t uuid128[16];
674     le_service_t service;
675     le_characteristic_t characteristic;
676     le_characteristic_descriptor_t descriptor;
677     uint16_t data_length;
678     uint8_t  * data;
679     linked_list_gatt_client_helper_t * gatt_helper;
680 #endif
681 
682     uint16_t serviceSearchPatternLen;
683     uint16_t attributeIDListLen;
684 
685     // verbose log info before other info to allow for better tracking
686     hci_dump_packet( HCI_COMMAND_DATA_PACKET, 1, packet, size);
687 
688     // BTstack internal commands - 16 Bit OpCode, 8 Bit ParamLen, Params...
689     switch (READ_CMD_OCF(packet)){
690         case BTSTACK_GET_STATE:
691             log_info("BTSTACK_GET_STATE");
692             hci_emit_state();
693             break;
694         case BTSTACK_SET_POWER_MODE:
695             log_info("BTSTACK_SET_POWER_MODE %u", packet[3]);
696             // track client power requests
697             client = client_for_connection(connection);
698             if (!client) break;
699             client->power_mode = packet[3];
700             // handle merged state
701             if (!clients_require_power_on()){
702                 start_power_off_timer();
703             } else if (!power_management_sleep) {
704                 stop_power_off_timer();
705                 hci_power_control(HCI_POWER_ON);
706             }
707             break;
708         case BTSTACK_GET_VERSION:
709             log_info("BTSTACK_GET_VERSION");
710             hci_emit_btstack_version();
711             break;
712 #ifdef USE_BLUETOOL
713         case BTSTACK_SET_SYSTEM_BLUETOOTH_ENABLED:
714             log_info("BTSTACK_SET_SYSTEM_BLUETOOTH_ENABLED %u", packet[3]);
715             iphone_system_bt_set_enabled(packet[3]);
716             hci_emit_system_bluetooth_enabled(iphone_system_bt_enabled());
717             break;
718 
719         case BTSTACK_GET_SYSTEM_BLUETOOTH_ENABLED:
720             log_info("BTSTACK_GET_SYSTEM_BLUETOOTH_ENABLED");
721             hci_emit_system_bluetooth_enabled(iphone_system_bt_enabled());
722             break;
723 #else
724         case BTSTACK_SET_SYSTEM_BLUETOOTH_ENABLED:
725         case BTSTACK_GET_SYSTEM_BLUETOOTH_ENABLED:
726             hci_emit_system_bluetooth_enabled(0);
727             break;
728 #endif
729         case BTSTACK_SET_DISCOVERABLE:
730             log_info("BTSTACK_SET_DISCOVERABLE discoverable %u)", packet[3]);
731             // track client discoverable requests
732             client = client_for_connection(connection);
733             if (!client) break;
734             client->discoverable = packet[3];
735             // merge state
736             hci_discoverable_control(clients_require_discoverable());
737             break;
738         case BTSTACK_SET_BLUETOOTH_ENABLED:
739             log_info("BTSTACK_SET_BLUETOOTH_ENABLED: %u\n", packet[3]);
740             if (packet[3]) {
741                 // global enable
742                 global_enable = 1;
743                 hci_power_control(HCI_POWER_ON);
744             } else {
745                 global_enable = 0;
746                 clients_clear_power_request();
747                 hci_power_control(HCI_POWER_OFF);
748             }
749             break;
750         case L2CAP_CREATE_CHANNEL_MTU:
751             bt_flip_addr(addr, &packet[3]);
752             psm = READ_BT_16(packet, 9);
753             mtu = READ_BT_16(packet, 11);
754             l2cap_create_channel_internal( connection, NULL, addr, psm, mtu);
755             break;
756         case L2CAP_CREATE_CHANNEL:
757             bt_flip_addr(addr, &packet[3]);
758             psm = READ_BT_16(packet, 9);
759             l2cap_create_channel_internal( connection, NULL, addr, psm, 150);   // until r865
760             break;
761         case L2CAP_DISCONNECT:
762             cid = READ_BT_16(packet, 3);
763             reason = packet[5];
764             l2cap_disconnect_internal(cid, reason);
765             break;
766         case L2CAP_REGISTER_SERVICE:
767             psm = READ_BT_16(packet, 3);
768             mtu = READ_BT_16(packet, 5);
769             l2cap_register_service_internal(connection, NULL, psm, mtu, LEVEL_0);
770             break;
771         case L2CAP_UNREGISTER_SERVICE:
772             psm = READ_BT_16(packet, 3);
773             daemon_remove_client_l2cap_service(connection, psm);
774             l2cap_unregister_service_internal(connection, psm);
775             break;
776         case L2CAP_ACCEPT_CONNECTION:
777             cid    = READ_BT_16(packet, 3);
778             l2cap_accept_connection_internal(cid);
779             break;
780         case L2CAP_DECLINE_CONNECTION:
781             cid    = READ_BT_16(packet, 3);
782             reason = packet[7];
783             l2cap_decline_connection_internal(cid, reason);
784             break;
785         case RFCOMM_CREATE_CHANNEL:
786             bt_flip_addr(addr, &packet[3]);
787             rfcomm_channel = packet[9];
788             rfcomm_create_channel_internal( connection, addr, rfcomm_channel );
789             break;
790         case RFCOMM_CREATE_CHANNEL_WITH_CREDITS:
791             bt_flip_addr(addr, &packet[3]);
792             rfcomm_channel = packet[9];
793             rfcomm_credits = packet[10];
794             rfcomm_create_channel_with_initial_credits_internal( connection, addr, rfcomm_channel, rfcomm_credits );
795             break;
796         case RFCOMM_DISCONNECT:
797             cid = READ_BT_16(packet, 3);
798             reason = packet[5];
799             rfcomm_disconnect_internal(cid);
800             break;
801         case RFCOMM_REGISTER_SERVICE:
802             rfcomm_channel = packet[3];
803             mtu = READ_BT_16(packet, 4);
804             rfcomm_register_service_internal(connection, rfcomm_channel, mtu);
805             break;
806         case RFCOMM_REGISTER_SERVICE_WITH_CREDITS:
807             rfcomm_channel = packet[3];
808             mtu = READ_BT_16(packet, 4);
809             rfcomm_credits = packet[6];
810             rfcomm_register_service_with_initial_credits_internal(connection, rfcomm_channel, mtu, rfcomm_credits);
811             break;
812         case RFCOMM_UNREGISTER_SERVICE:
813             service_channel = READ_BT_16(packet, 3);
814             daemon_remove_client_rfcomm_service(connection, service_channel);
815             rfcomm_unregister_service_internal(service_channel);
816             break;
817         case RFCOMM_ACCEPT_CONNECTION:
818             cid    = READ_BT_16(packet, 3);
819             rfcomm_accept_connection_internal(cid);
820             break;
821         case RFCOMM_DECLINE_CONNECTION:
822             cid    = READ_BT_16(packet, 3);
823             reason = packet[7];
824             rfcomm_decline_connection_internal(cid);
825             break;
826         case RFCOMM_GRANT_CREDITS:
827             cid    = READ_BT_16(packet, 3);
828             rfcomm_credits = packet[5];
829             rfcomm_grant_credits(cid, rfcomm_credits);
830             break;
831         case RFCOMM_PERSISTENT_CHANNEL: {
832             if (remote_device_db) {
833                 // enforce \0
834                 packet[3+248] = 0;
835                 rfcomm_channel = remote_device_db->persistent_rfcomm_channel((char*)&packet[3]);
836             } else {
837                 // NOTE: hack for non-iOS platforms
838                 rfcomm_channel = rfcomm_channel_generator++;
839             }
840             log_info("RFCOMM_EVENT_PERSISTENT_CHANNEL %u", rfcomm_channel);
841             uint8_t event[4];
842             event[0] = RFCOMM_EVENT_PERSISTENT_CHANNEL;
843             event[1] = sizeof(event) - 2;
844             event[2] = 0;
845             event[3] = rfcomm_channel;
846             hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
847             socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, (uint8_t *) event, sizeof(event));
848             break;
849         }
850 
851         case SDP_REGISTER_SERVICE_RECORD:
852             log_info("SDP_REGISTER_SERVICE_RECORD size %u\n", size);
853             service_record_handle = sdp_register_service_internal(connection, &packet[3]);
854             daemon_add_client_sdp_service_record_handle(connection, service_record_handle);
855             break;
856         case SDP_UNREGISTER_SERVICE_RECORD:
857             service_record_handle = READ_BT_32(packet, 3);
858             log_info("SDP_UNREGISTER_SERVICE_RECORD handle 0x%x ", service_record_handle);
859             sdp_unregister_service_internal(connection, service_record_handle);
860             daemon_remove_client_sdp_service_record_handle(connection, service_record_handle);
861             break;
862         case SDP_CLIENT_QUERY_RFCOMM_SERVICES:
863             bt_flip_addr(addr, &packet[3]);
864 
865             serviceSearchPatternLen = de_get_len(&packet[9]);
866             memcpy(serviceSearchPattern, &packet[9], serviceSearchPatternLen);
867 
868             sdp_query_rfcomm_register_callback(handle_sdp_rfcomm_service_result, connection);
869             sdp_query_rfcomm_channel_and_name_for_search_pattern(addr, serviceSearchPattern);
870 
871             break;
872         case SDP_CLIENT_QUERY_SERVICES:
873             bt_flip_addr(addr, &packet[3]);
874             sdp_parser_init();
875             sdp_client_query_connection = connection;
876             sdp_parser_register_callback(handle_sdp_client_query_result);
877 
878             serviceSearchPatternLen = de_get_len(&packet[9]);
879             memcpy(serviceSearchPattern, &packet[9], serviceSearchPatternLen);
880 
881             attributeIDListLen = de_get_len(&packet[9+serviceSearchPatternLen]);
882             memcpy(attributeIDList, &packet[9+serviceSearchPatternLen], attributeIDListLen);
883 
884             sdp_client_query(addr, (uint8_t*)&serviceSearchPattern[0], (uint8_t*)&attributeIDList[0]);
885 
886             // sdp_general_query_for_uuid(addr, SDP_PublicBrowseGroup);
887             break;
888         case GAP_LE_SCAN_START:
889             le_central_start_scan();
890             break;
891         case GAP_LE_SCAN_STOP:
892             le_central_stop_scan();
893             break;
894         case GAP_LE_SET_SCAN_PARAMETERS:
895             le_central_set_scan_parameters(packet[3], READ_BT_16(packet, 4), READ_BT_16(packet, 6));
896             break;
897         case GAP_LE_CONNECT:
898             bt_flip_addr(addr, &packet[4]);
899             addr_type = packet[3];
900             le_central_connect(addr, addr_type);
901             break;
902         case GAP_LE_CONNECT_CANCEL:
903             le_central_connect_cancel();
904             break;
905         case GAP_DISCONNECT:
906             handle = READ_BT_16(packet, 3);
907             gap_disconnect(handle);
908             break;
909 #if defined(HAVE_MALLOC) && defined(HAVE_BLE)
910         case GATT_DISCOVER_ALL_PRIMARY_SERVICES:
911             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
912             if (!gatt_helper) break;
913             gatt_client_discover_primary_services(gatt_client_id, gatt_helper->con_handle);
914             break;
915         case GATT_DISCOVER_PRIMARY_SERVICES_BY_UUID16:
916             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
917             if (!gatt_helper) break;
918             gatt_client_discover_primary_services_by_uuid16(gatt_client_id, gatt_helper->con_handle, READ_BT_16(packet, 5));
919             break;
920         case GATT_DISCOVER_PRIMARY_SERVICES_BY_UUID128:
921             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
922             if (!gatt_helper) break;
923             swap128(&packet[5], uuid128);
924             gatt_client_discover_primary_services_by_uuid128(gatt_client_id, gatt_helper->con_handle, uuid128);
925             break;
926         case GATT_FIND_INCLUDED_SERVICES_FOR_SERVICE:
927             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
928             if (!gatt_helper) break;
929             daemon_gatt_deserialize_service(packet, 5, &service);
930             gatt_client_find_included_services_for_service(gatt_client_id, gatt_helper->con_handle, &service);
931             break;
932 
933         case GATT_DISCOVER_CHARACTERISTICS_FOR_SERVICE:
934             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
935             if (!gatt_helper) break;
936             daemon_gatt_deserialize_service(packet, 5, &service);
937             gatt_client_discover_characteristics_for_service(gatt_client_id, gatt_helper->con_handle, &service);
938             break;
939         case GATT_DISCOVER_CHARACTERISTICS_FOR_SERVICE_BY_UUID128:
940             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
941             if (!gatt_helper) break;
942             daemon_gatt_deserialize_service(packet, 5, &service);
943             swap128(&packet[5 + SERVICE_LENGTH], uuid128);
944             gatt_client_discover_characteristics_for_service_by_uuid128(gatt_client_id, gatt_helper->con_handle, &service, uuid128);
945             break;
946         case GATT_DISCOVER_CHARACTERISTIC_DESCRIPTORS:
947             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
948             if (!gatt_helper) break;
949             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
950             gatt_client_discover_characteristic_descriptors(gatt_client_id, gatt_helper->con_handle, &characteristic);
951             break;
952 
953         case GATT_READ_VALUE_OF_CHARACTERISTIC:
954             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
955             if (!gatt_helper) break;
956             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
957             gatt_client_read_value_of_characteristic(gatt_client_id, gatt_helper->con_handle, &characteristic);
958             break;
959         case GATT_READ_LONG_VALUE_OF_CHARACTERISTIC:
960             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
961             if (!gatt_helper) break;
962             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
963             gatt_client_read_long_value_of_characteristic(gatt_client_id, gatt_helper->con_handle, &characteristic);
964             break;
965 
966         case GATT_WRITE_VALUE_OF_CHARACTERISTIC_WITHOUT_RESPONSE:
967             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 0);  // note: don't track active connection
968             if (!gatt_helper) break;
969             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
970             data_length = READ_BT_16(packet, 5 + CHARACTERISTIC_LENGTH);
971             data = gatt_helper->characteristic_buffer;
972             memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length);
973             gatt_client_write_value_of_characteristic_without_response(gatt_client_id, gatt_helper->con_handle, characteristic.value_handle, data_length, data);
974             break;
975         case GATT_WRITE_VALUE_OF_CHARACTERISTIC:
976             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
977             if (!gatt_helper) break;
978             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
979             data_length = READ_BT_16(packet, 5 + CHARACTERISTIC_LENGTH);
980             data = gatt_helper->characteristic_buffer;
981             memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length);
982             gatt_client_write_value_of_characteristic(gatt_client_id, gatt_helper->con_handle, characteristic.value_handle, data_length, data);
983             break;
984         case GATT_WRITE_LONG_VALUE_OF_CHARACTERISTIC:
985             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
986             if (!gatt_helper) break;
987             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
988             data_length = READ_BT_16(packet, 5 + CHARACTERISTIC_LENGTH);
989             data = gatt_helper->characteristic_buffer;
990             memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length);
991             gatt_client_write_long_value_of_characteristic(gatt_client_id, gatt_helper->con_handle, characteristic.value_handle, data_length, data);
992             break;
993         case GATT_RELIABLE_WRITE_LONG_VALUE_OF_CHARACTERISTIC:
994             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
995             if (!gatt_helper) break;
996             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
997             data_length = READ_BT_16(packet, 5 + CHARACTERISTIC_LENGTH);
998             data = gatt_helper->characteristic_buffer;
999             memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length);
1000             gatt_client_write_long_value_of_characteristic(gatt_client_id, gatt_helper->con_handle, characteristic.value_handle, data_length, data);
1001             break;
1002         case GATT_READ_CHARACTERISTIC_DESCRIPTOR:
1003             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1004             if (!gatt_helper) break;
1005             handle = READ_BT_16(packet, 3);
1006             daemon_gatt_deserialize_characteristic_descriptor(packet, 5, &descriptor);
1007             gatt_client_read_characteristic_descriptor(gatt_client_id, gatt_helper->con_handle, &descriptor);
1008             break;
1009         case GATT_READ_LONG_CHARACTERISTIC_DESCRIPTOR:
1010             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1011             if (!gatt_helper) break;
1012             daemon_gatt_deserialize_characteristic_descriptor(packet, 5, &descriptor);
1013             gatt_client_read_long_characteristic_descriptor(gatt_client_id, gatt_helper->con_handle, &descriptor);
1014             break;
1015 
1016         case GATT_WRITE_CHARACTERISTIC_DESCRIPTOR:
1017             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1018             if (!gatt_helper) break;
1019             daemon_gatt_deserialize_characteristic_descriptor(packet, 5, &descriptor);
1020             data = gatt_helper->characteristic_buffer;
1021             data_length = READ_BT_16(packet, 5 + CHARACTERISTIC_DESCRIPTOR_LENGTH);
1022             gatt_client_write_characteristic_descriptor(gatt_client_id, gatt_helper->con_handle, &descriptor, data_length, data);
1023             break;
1024         case GATT_WRITE_LONG_CHARACTERISTIC_DESCRIPTOR:
1025             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1026             if (!gatt_helper) break;
1027             daemon_gatt_deserialize_characteristic_descriptor(packet, 5, &descriptor);
1028             data = gatt_helper->characteristic_buffer;
1029             data_length = READ_BT_16(packet, 5 + CHARACTERISTIC_DESCRIPTOR_LENGTH);
1030             gatt_client_write_long_characteristic_descriptor(gatt_client_id, gatt_helper->con_handle, &descriptor, data_length, data);
1031             break;
1032         case GATT_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION:{
1033             uint16_t configuration = READ_BT_16(packet, 5 + CHARACTERISTIC_LENGTH);
1034             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1035             if (!gatt_helper) break;
1036             data = gatt_helper->characteristic_buffer;
1037             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
1038             gatt_client_write_client_characteristic_configuration(gatt_client_id, gatt_helper->con_handle, &characteristic, configuration);
1039             break;
1040         case GATT_GET_MTU:
1041             handle = READ_BT_16(packet, 3);
1042             gatt_client_get_mtu(handle, &mtu);
1043             send_gatt_mtu_event(connection, handle, mtu);
1044             break;
1045         }
1046 #endif
1047     default:
1048             log_error("Error: command %u not implemented:", READ_CMD_OCF(packet));
1049             break;
1050     }
1051 
1052     return 0;
1053 }
1054 
1055 static int daemon_client_handler(connection_t *connection, uint16_t packet_type, uint16_t channel, uint8_t *data, uint16_t length){
1056 
1057     int err = 0;
1058     client_state_t * client;
1059 
1060     switch (packet_type){
1061         case HCI_COMMAND_DATA_PACKET:
1062             if (READ_CMD_OGF(data) != OGF_BTSTACK) {
1063                 // HCI Command
1064                 hci_send_cmd_packet(data, length);
1065             } else {
1066                 // BTstack command
1067                 btstack_command_handler(connection, data, length);
1068             }
1069             break;
1070         case L2CAP_DATA_PACKET:
1071             // process l2cap packet...
1072             err = l2cap_send_internal(channel, data, length);
1073             if (err == BTSTACK_ACL_BUFFERS_FULL) {
1074                 l2cap_block_new_credits(1);
1075             }
1076             break;
1077         case RFCOMM_DATA_PACKET:
1078             // process l2cap packet...
1079             err = rfcomm_send_internal(channel, data, length);
1080             break;
1081         case DAEMON_EVENT_PACKET:
1082             switch (data[0]) {
1083                 case DAEMON_EVENT_CONNECTION_OPENED:
1084                     log_info("DAEMON_EVENT_CONNECTION_OPENED %p\n",connection);
1085 
1086                     client = malloc(sizeof(client_state_t));
1087                     if (!client) break; // fail
1088                     memset(client, 0, sizeof(client_state_t));
1089                     client->connection   = connection;
1090                     client->power_mode   = HCI_POWER_OFF;
1091                     client->discoverable = 0;
1092                     linked_list_add(&clients, (linked_item_t *) client);
1093                     break;
1094                 case DAEMON_EVENT_CONNECTION_CLOSED:
1095                     log_info("DAEMON_EVENT_CONNECTION_CLOSED %p\n",connection);
1096                     daemon_disconnect_client(connection);
1097                     sdp_query_rfcomm_deregister_callback();
1098                     // no clients -> no HCI connections
1099                     if (!clients){
1100                         hci_disconnect_all();
1101                     }
1102 
1103                     // update discoverable mode
1104                     hci_discoverable_control(clients_require_discoverable());
1105                     // start power off, if last active client
1106                     if (!clients_require_power_on()){
1107                         start_power_off_timer();
1108                     }
1109                     break;
1110                 case DAEMON_NR_CONNECTIONS_CHANGED:
1111                     log_info("Nr Connections changed, new %u\n",data[1]);
1112                     break;
1113                 default:
1114                     break;
1115             }
1116             break;
1117     }
1118     if (err) {
1119         log_info("Daemon Handler: err %d\n", err);
1120     }
1121     return err;
1122 }
1123 
1124 
1125 static void daemon_set_logging_enabled(int enabled){
1126     if (enabled && !loggingEnabled){
1127         hci_dump_open(BTSTACK_LOG_FILE, BTSTACK_LOG_TYPE);
1128     }
1129     if (!enabled && loggingEnabled){
1130         hci_dump_close();
1131     }
1132     loggingEnabled = enabled;
1133 }
1134 
1135 // local cache used to manage UI status
1136 static HCI_STATE hci_state = HCI_STATE_OFF;
1137 static int num_connections = 0;
1138 static void update_ui_status(void){
1139     if (hci_state != HCI_STATE_WORKING) {
1140         bluetooth_status_handler(BLUETOOTH_OFF);
1141     } else {
1142         if (num_connections) {
1143             bluetooth_status_handler(BLUETOOTH_ACTIVE);
1144         } else {
1145             bluetooth_status_handler(BLUETOOTH_ON);
1146         }
1147     }
1148 }
1149 
1150 #ifdef USE_SPRINGBOARD
1151 static void preferences_changed_callback(void){
1152     int logging = platform_iphone_logging_enabled();
1153     log_info("Logging enabled: %u\n", logging);
1154     daemon_set_logging_enabled(logging);
1155 }
1156 #endif
1157 
1158 static void deamon_status_event_handler(uint8_t *packet, uint16_t size){
1159 
1160     uint8_t update_status = 0;
1161 
1162     // handle state event
1163     switch (packet[0]) {
1164         case BTSTACK_EVENT_STATE:
1165             hci_state = packet[2];
1166             log_info("New state: %u\n", hci_state);
1167             update_status = 1;
1168             break;
1169         case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED:
1170             num_connections = packet[2];
1171             log_info("New nr connections: %u\n", num_connections);
1172             update_status = 1;
1173             break;
1174         default:
1175             break;
1176     }
1177 
1178     // choose full bluetooth state
1179     if (update_status) {
1180         update_ui_status();
1181     }
1182 }
1183 
1184 static void daemon_retry_parked(void){
1185 
1186     // socket_connection_retry_parked is not reentrant
1187     static int retry_mutex = 0;
1188 
1189     // lock mutex
1190     if (retry_mutex) return;
1191     retry_mutex = 1;
1192 
1193     // ... try sending again
1194     socket_connection_retry_parked();
1195 
1196     if (!socket_connection_has_parked_connections()){
1197         l2cap_block_new_credits(0);
1198     }
1199 
1200     // unlock mutex
1201     retry_mutex = 0;
1202 }
1203 
1204 #if 0
1205 
1206 Minimal Code for LE Peripheral
1207 
1208 enum {
1209     SET_ADVERTISEMENT_PARAMS = 1 << 0,
1210     SET_ADVERTISEMENT_DATA   = 1 << 1,
1211     ENABLE_ADVERTISEMENTS    = 1 << 2,
1212 };
1213 
1214 const uint8_t adv_data[] = {
1215     // Flags general discoverable
1216     0x02, 0x01, 0x02,
1217     // Name
1218     0x08, 0x09, 'B', 'T', 's', 't', 'a', 'c', 'k'
1219 };
1220 uint8_t adv_data_len = sizeof(adv_data);
1221 static uint16_t todos = 0;
1222 
1223 static void app_run(void){
1224 
1225     if (!hci_can_send_command_packet_now()) return;
1226 
1227     if (todos & SET_ADVERTISEMENT_DATA){
1228         log_info("app_run: set advertisement data\n");
1229         todos &= ~SET_ADVERTISEMENT_DATA;
1230         hci_send_cmd(&hci_le_set_advertising_data, adv_data_len, adv_data);
1231         return;
1232     }
1233 
1234     if (todos & SET_ADVERTISEMENT_PARAMS){
1235         todos &= ~SET_ADVERTISEMENT_PARAMS;
1236         uint8_t adv_type = 0;   // default
1237         bd_addr_t null_addr;
1238         memset(null_addr, 0, 6);
1239         uint16_t adv_int_min = 0x0030;
1240         uint16_t adv_int_max = 0x0030;
1241         hci_send_cmd(&hci_le_set_advertising_parameters, adv_int_min, adv_int_max, adv_type, 0, 0, &null_addr, 0x07, 0x00);
1242         return;
1243     }
1244 
1245     if (todos & ENABLE_ADVERTISEMENTS){
1246         log_info("app_run: enable advertisements\n");
1247         todos &= ~ENABLE_ADVERTISEMENTS;
1248         hci_send_cmd(&hci_le_set_advertise_enable, 1);
1249         return;
1250     }
1251 }
1252 #endif
1253 
1254 static void daemon_packet_handler(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1255 
1256     switch (packet_type) {
1257         case HCI_EVENT_PACKET:
1258             deamon_status_event_handler(packet, size);
1259             switch (packet[0]){
1260 
1261                 case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
1262                     // ACL buffer freed...
1263                     daemon_retry_parked();
1264                     // no need to tell clients
1265                     return;
1266                 case RFCOMM_EVENT_CREDITS:
1267                     // RFCOMM CREDITS received...
1268                     daemon_retry_parked();
1269                     break;
1270                  case RFCOMM_EVENT_OPEN_CHANNEL_COMPLETE:
1271                     if (packet[2]) break;
1272                     daemon_add_client_rfcomm_channel(connection, READ_BT_16(packet, 9));
1273                     break;
1274                 case RFCOMM_EVENT_CHANNEL_CLOSED:
1275                     daemon_remove_client_rfcomm_channel(connection, READ_BT_16(packet, 2));
1276                     break;
1277                 case RFCOMM_EVENT_SERVICE_REGISTERED:
1278                     if (packet[2]) break;
1279                     daemon_add_client_rfcomm_service(connection, packet[3]);
1280                     break;
1281                 case L2CAP_EVENT_CHANNEL_OPENED:
1282                     if (packet[2]) break;
1283                     daemon_add_client_l2cap_channel(connection, READ_BT_16(packet, 13));
1284                     break;
1285                 case L2CAP_EVENT_CHANNEL_CLOSED:
1286                     daemon_remove_client_l2cap_channel(connection, READ_BT_16(packet, 2));
1287                     break;
1288                 case L2CAP_EVENT_SERVICE_REGISTERED:
1289                     if (packet[2]) break;
1290                     daemon_add_client_l2cap_service(connection, READ_BT_16(packet, 3));
1291                     break;
1292 #if defined(HAVE_BLE) && defined(HAVE_MALLOC)
1293                 case HCI_EVENT_DISCONNECTION_COMPLETE:
1294                     log_info("daemon : ignore HCI_EVENT_DISCONNECTION_COMPLETE ingnoring.");
1295                     // note: moved to gatt_client_handler because it's received here prematurely
1296                     // daemon_remove_gatt_client_helper(READ_BT_16(packet, 3));
1297                     break;
1298 #endif
1299                 default:
1300                     break;
1301             }
1302         case DAEMON_EVENT_PACKET:
1303             switch (packet[0]){
1304                 case DAEMON_EVENT_NEW_RFCOMM_CREDITS:
1305                     daemon_retry_parked();
1306                     break;
1307                 default:
1308                     break;
1309             }
1310         default:
1311             break;
1312     }
1313     if (connection) {
1314         socket_connection_send_packet(connection, packet_type, channel, packet, size);
1315     } else {
1316         socket_connection_send_packet_all(packet_type, channel, packet, size);
1317     }
1318 }
1319 
1320 static void handle_sdp_rfcomm_service_result(sdp_query_event_t * rfcomm_event, void * context){
1321     switch (rfcomm_event->type){
1322         case SDP_QUERY_RFCOMM_SERVICE: {
1323             sdp_query_rfcomm_service_event_t * service_event = (sdp_query_rfcomm_service_event_t*) rfcomm_event;
1324             int name_len = (int)strlen((const char*)service_event->service_name);
1325             int event_len = 3 + name_len;
1326             uint8_t event[event_len];
1327             event[0] = rfcomm_event->type;
1328             event[1] = 1 + name_len;
1329             event[2] = service_event->channel_nr;
1330             memcpy(&event[3], service_event->service_name, name_len);
1331             hci_dump_packet(HCI_EVENT_PACKET, 0, event, event_len);
1332             socket_connection_send_packet(context, HCI_EVENT_PACKET, 0, event, event_len);
1333             break;
1334         }
1335         case SDP_QUERY_COMPLETE: {
1336             sdp_query_complete_event_t * complete_event = (sdp_query_complete_event_t*) rfcomm_event;
1337             uint8_t event[] = { rfcomm_event->type, 1, complete_event->status};
1338             hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
1339             socket_connection_send_packet(context, HCI_EVENT_PACKET, 0, event, sizeof(event));
1340             break;
1341         }
1342     }
1343 }
1344 
1345 static void sdp_client_assert_buffer(int size){
1346     if (size > attribute_value_buffer_size){
1347         log_error("SDP attribute value buffer size exceeded: available %d, required %d", attribute_value_buffer_size, size);
1348     }
1349 }
1350 
1351 // define new packet type SDP_CLIENT_PACKET
1352 static void handle_sdp_client_query_result(sdp_query_event_t * event){
1353     sdp_query_attribute_value_event_t * ve;
1354     sdp_query_complete_event_t * complete_event;
1355 
1356     switch (event->type){
1357         case SDP_QUERY_ATTRIBUTE_VALUE:
1358             ve = (sdp_query_attribute_value_event_t*) event;
1359 
1360             sdp_client_assert_buffer(ve->attribute_length);
1361 
1362             attribute_value[ve->data_offset] = ve->data;
1363 
1364             if ((uint16_t)(ve->data_offset+1) == ve->attribute_length){
1365                 hexdump(attribute_value, ve->attribute_length);
1366 
1367                 int event_len = 1 + 3 * 2 + ve->attribute_length;
1368                 uint8_t event[event_len];
1369                 event[0] = SDP_QUERY_ATTRIBUTE_VALUE;
1370                 bt_store_16(event, 1, (uint16_t)ve->record_id);
1371                 bt_store_16(event, 3, ve->attribute_id);
1372                 bt_store_16(event, 5, (uint16_t)ve->attribute_length);
1373                 memcpy(&event[7], attribute_value, ve->attribute_length);
1374                 hci_dump_packet(SDP_CLIENT_PACKET, 0, event, event_len);
1375                 socket_connection_send_packet(sdp_client_query_connection, SDP_CLIENT_PACKET, 0, event, event_len);
1376             }
1377 
1378             break;
1379         case SDP_QUERY_COMPLETE:
1380             complete_event = (sdp_query_complete_event_t*) event;
1381             uint8_t event[] = { SDP_QUERY_COMPLETE, 1, complete_event->status};
1382             hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
1383             socket_connection_send_packet(sdp_client_query_connection, HCI_EVENT_PACKET, 0, event, sizeof(event));
1384             break;
1385     }
1386 }
1387 
1388 static void power_notification_callback(POWER_NOTIFICATION_t notification){
1389     switch (notification) {
1390         case POWER_WILL_SLEEP:
1391             // let's sleep
1392             power_management_sleep = 1;
1393             hci_power_control(HCI_POWER_SLEEP);
1394             break;
1395         case POWER_WILL_WAKE_UP:
1396             // assume that all clients use Bluetooth -> if connection, start Bluetooth
1397             power_management_sleep = 0;
1398             if (clients_require_power_on()) {
1399                 hci_power_control(HCI_POWER_ON);
1400             }
1401             break;
1402         default:
1403             break;
1404     }
1405 }
1406 
1407 static void daemon_sigint_handler(int param){
1408 
1409 #ifdef USE_BLUETOOL
1410     // notify daemons
1411     notify_post("ch.ringwald.btstack.stopped");
1412 #endif
1413 
1414     log_info(" <= SIGINT received, shutting down..\n");
1415 
1416     hci_power_control( HCI_POWER_OFF);
1417     hci_close();
1418 
1419     log_info("Good bye, see you.\n");
1420 
1421     exit(0);
1422 }
1423 
1424 // MARK: manage power off timer
1425 
1426 #define USE_POWER_OFF_TIMER
1427 
1428 static void stop_power_off_timer(void){
1429 #ifdef USE_POWER_OFF_TIMER
1430     if (timeout_active) {
1431         run_loop_remove_timer(&timeout);
1432         timeout_active = 0;
1433     }
1434 #endif
1435 }
1436 
1437 static void start_power_off_timer(void){
1438 #ifdef USE_POWER_OFF_TIMER
1439     stop_power_off_timer();
1440     run_loop_set_timer(&timeout, DAEMON_NO_ACTIVE_CLIENT_TIMEOUT);
1441     run_loop_add_timer(&timeout);
1442     timeout_active = 1;
1443 #else
1444     hci_power_control(HCI_POWER_OFF);
1445 #endif
1446 }
1447 
1448 // MARK: manage list of clients
1449 
1450 
1451 static client_state_t * client_for_connection(connection_t *connection) {
1452     linked_item_t *it;
1453     for (it = (linked_item_t *) clients; it ; it = it->next){
1454         client_state_t * client_state = (client_state_t *) it;
1455         if (client_state->connection == connection) {
1456             return client_state;
1457         }
1458     }
1459     return NULL;
1460 }
1461 
1462 static void clients_clear_power_request(void){
1463     linked_item_t *it;
1464     for (it = (linked_item_t *) clients; it ; it = it->next){
1465         client_state_t * client_state = (client_state_t *) it;
1466         client_state->power_mode = HCI_POWER_OFF;
1467     }
1468 }
1469 
1470 static int clients_require_power_on(void){
1471 
1472     if (global_enable) return 1;
1473 
1474     linked_item_t *it;
1475     for (it = (linked_item_t *) clients; it ; it = it->next){
1476         client_state_t * client_state = (client_state_t *) it;
1477         if (client_state->power_mode == HCI_POWER_ON) {
1478             return 1;
1479         }
1480     }
1481     return 0;
1482 }
1483 
1484 static int clients_require_discoverable(void){
1485     linked_item_t *it;
1486     for (it = (linked_item_t *) clients; it ; it = it->next){
1487         client_state_t * client_state = (client_state_t *) it;
1488         if (client_state->discoverable) {
1489             return 1;
1490         }
1491     }
1492     return 0;
1493 }
1494 
1495 static void usage(const char * name) {
1496     printf("%s, BTstack background daemon\n", name);
1497     printf("usage: %s [--help] [--tcp port]\n", name);
1498     printf("    --help   display this usage\n");
1499     printf("    --tcp    use TCP server on port %u\n", BTSTACK_PORT);
1500     printf("Without the --tcp option, BTstack daemon is listening on unix domain socket %s\n\n", BTSTACK_UNIX);
1501 }
1502 
1503 #ifdef USE_BLUETOOL
1504 static void * run_loop_thread(void *context){
1505     run_loop_execute();
1506     return NULL;
1507 }
1508 #endif
1509 
1510 #ifdef HAVE_BLE
1511 
1512 static void handle_gatt_client_event(uint8_t packet_type, uint8_t * packet, uint16_t size){
1513 
1514     // hack: handle disconnection_complete_here instead of main hci event packet handler
1515     // we receive a HCI event packet in disguise
1516     if (packet[0] == HCI_EVENT_DISCONNECTION_COMPLETE){
1517         log_info("daemon hack: handle disconnection_complete in handle_gatt_client_event instead of main hci event packet handler");
1518         uint16_t handle = READ_BT_16(packet, 3);
1519         daemon_remove_gatt_client_helper(handle);
1520         return;
1521     }
1522 
1523     // only handle GATT Events
1524     switch(packet[0]){
1525         case GATT_SERVICE_QUERY_RESULT:
1526         case GATT_INCLUDED_SERVICE_QUERY_RESULT:
1527         case GATT_NOTIFICATION:
1528         case GATT_INDICATION:
1529         case GATT_CHARACTERISTIC_QUERY_RESULT:
1530         case GATT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
1531         case GATT_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
1532         case GATT_LONG_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
1533         case GATT_CHARACTERISTIC_VALUE_QUERY_RESULT:
1534         case GATT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT:
1535         case GATT_QUERY_COMPLETE:
1536            break;
1537         default:
1538             return;
1539     }
1540 
1541     uint16_t con_handle = READ_BT_16(packet, 2);
1542     linked_list_gatt_client_helper_t * gatt_client_helper = daemon_get_gatt_client_helper(con_handle);
1543     if (!gatt_client_helper){
1544         log_info("daemon handle_gatt_client_event: gc helper for handle 0x%2x is NULL.", con_handle);
1545         return;
1546     }
1547 
1548     connection_t *connection = NULL;
1549 
1550     // daemon doesn't track which connection subscribed to this particular handle, so we just notify all connections
1551     switch(packet[0]){
1552         case GATT_NOTIFICATION:
1553         case GATT_INDICATION:{
1554             hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size);
1555 
1556             linked_item_t *it;
1557             for (it = (linked_item_t *) clients; it ; it = it->next){
1558                 client_state_t * client_state = (client_state_t *) it;
1559                 socket_connection_send_packet(client_state->connection, HCI_EVENT_PACKET, 0, packet, size);
1560             }
1561             return;
1562         }
1563         default:
1564             break;
1565     }
1566 
1567     // otherwise, we have to have an active connection
1568     connection = gatt_client_helper->active_connection;
1569     uint16_t offset;
1570     uint16_t length;
1571 
1572     if (!connection) return;
1573 
1574     switch(packet[0]){
1575 
1576         case GATT_SERVICE_QUERY_RESULT:
1577         case GATT_INCLUDED_SERVICE_QUERY_RESULT:
1578         case GATT_CHARACTERISTIC_QUERY_RESULT:
1579         case GATT_CHARACTERISTIC_VALUE_QUERY_RESULT:
1580         case GATT_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
1581         case GATT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
1582             hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size);
1583             socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, packet, size);
1584             break;
1585 
1586         case GATT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT:
1587         case GATT_LONG_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
1588             offset = READ_BT_16(packet, 6);
1589             length = READ_BT_16(packet, 8);
1590             gatt_client_helper->characteristic_buffer[0] = packet[0];               // store type (characteristic/descriptor)
1591             gatt_client_helper->characteristic_handle    = READ_BT_16(packet, 4);   // store attribute handle
1592             gatt_client_helper->characteristic_length = offset + length;            // update length
1593             memcpy(&gatt_client_helper->characteristic_buffer[10 + offset], &packet[10], length);
1594             break;
1595 
1596         case GATT_QUERY_COMPLETE:{
1597             gatt_client_helper->active_connection = NULL;
1598             if (gatt_client_helper->characteristic_length){
1599                 // send re-combined long characteristic value or long characteristic descriptor value
1600                 uint8_t * event = gatt_client_helper->characteristic_buffer;
1601                 uint16_t event_size = 10 + gatt_client_helper->characteristic_length;
1602                 // event[0] == already set by previsous case
1603                 event[1] = 8 + gatt_client_helper->characteristic_length;
1604                 bt_store_16(event, 2, READ_BT_16(packet, 2));
1605                 bt_store_16(event, 4, gatt_client_helper->characteristic_handle);
1606                 bt_store_16(event, 6, 0);   // offset
1607                 bt_store_16(event, 8, gatt_client_helper->characteristic_length);
1608                 hci_dump_packet(HCI_EVENT_PACKET, 0, event, event_size);
1609                 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, event_size);
1610                 gatt_client_helper->characteristic_length = 0;
1611             }
1612             hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size);
1613             socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, packet, size);
1614             break;
1615         }
1616         default:
1617             break;
1618     }
1619 }
1620 #endif
1621 
1622 int main (int argc,  char * const * argv){
1623 
1624     static int tcp_flag = 0;
1625 
1626     while (1) {
1627         static struct option long_options[] = {
1628             { "tcp", no_argument, &tcp_flag, 1 },
1629             { "help", no_argument, 0, 0 },
1630             { 0,0,0,0 } // This is a filler for -1
1631         };
1632 
1633         int c;
1634         int option_index = -1;
1635 
1636         c = getopt_long(argc, argv, "h", long_options, &option_index);
1637 
1638         if (c == -1) break; // no more option
1639 
1640         // treat long parameter first
1641         if (option_index == -1) {
1642             switch (c) {
1643                 case '?':
1644                 case 'h':
1645                     usage(argv[0]);
1646                     return 0;
1647                     break;
1648             }
1649         } else {
1650             switch (option_index) {
1651                 case 1:
1652                     usage(argv[0]);
1653                     return 0;
1654                     break;
1655             }
1656         }
1657     }
1658 
1659     if (tcp_flag){
1660         printf("BTstack Daemon started on port %u\n", BTSTACK_PORT);
1661     } else {
1662         printf("BTstack Daemon started on socket %s\n", BTSTACK_UNIX);
1663     }
1664 
1665     // make stdout unbuffered
1666     setbuf(stdout, NULL);
1667 
1668     // handle CTRL-c
1669     signal(SIGINT, daemon_sigint_handler);
1670     // handle SIGTERM - suggested for launchd
1671     signal(SIGTERM, daemon_sigint_handler);
1672 
1673     // TODO: win32 variant
1674 #ifndef _WIN32
1675     // handle SIGPIPE
1676     struct sigaction act;
1677     act.sa_handler = SIG_IGN;
1678     sigemptyset (&act.sa_mask);
1679     act.sa_flags = 0;
1680     sigaction (SIGPIPE, &act, NULL);
1681 #endif
1682 
1683     bt_control_t * control = NULL;
1684 
1685 #ifdef HAVE_TRANSPORT_H4
1686     config.device_name   = UART_DEVICE;
1687     config.baudrate_init = UART_SPEED;
1688     config.baudrate_main = 0;
1689     config.flowcontrol = 1;
1690 #if defined(USE_BLUETOOL) && defined(USE_POWERMANAGEMENT)
1691     if (bt_control_iphone_power_management_supported()){
1692         // use default (max) UART baudrate over netraph interface
1693         config.baudrate_init = 0;
1694         transport = hci_transport_h4_iphone_instance();
1695     } else {
1696         transport = hci_transport_h4_instance();
1697     }
1698 #else
1699     transport = hci_transport_h4_instance();
1700 #endif
1701 #endif
1702 
1703 #ifdef HAVE_TRANSPORT_USB
1704     transport = hci_transport_usb_instance();
1705 #endif
1706 
1707 #ifdef USE_BLUETOOL
1708     control = &bt_control_iphone;
1709 #endif
1710 
1711 #if defined(USE_BLUETOOL) && defined(USE_POWERMANAGEMENT)
1712     if (bt_control_iphone_power_management_supported()){
1713         hci_transport_h4_iphone_set_enforce_wake_device("/dev/btwake");
1714     }
1715 #endif
1716 
1717 #ifdef USE_SPRINGBOARD
1718     bluetooth_status_handler = platform_iphone_status_handler;
1719     platform_iphone_register_window_manager_restart(update_ui_status);
1720     platform_iphone_register_preferences_changed(preferences_changed_callback);
1721 #endif
1722 
1723 #ifdef REMOTE_DEVICE_DB
1724     remote_device_db = &REMOTE_DEVICE_DB;
1725 #endif
1726 
1727     run_loop_init(RUN_LOOP_POSIX);
1728 
1729     // init power management notifications
1730     if (control && control->register_for_power_notifications){
1731         control->register_for_power_notifications(power_notification_callback);
1732     }
1733 
1734     // logging
1735     loggingEnabled = 0;
1736     int newLoggingEnabled = 1;
1737 #ifdef USE_BLUETOOL
1738     // iPhone has toggle in Preferences.app
1739     newLoggingEnabled = platform_iphone_logging_enabled();
1740 #endif
1741     daemon_set_logging_enabled(newLoggingEnabled);
1742 
1743     // dump version
1744     log_info("BTdaemon started\n");
1745     log_info("version %s, build %s", BTSTACK_VERSION, BTSTACK_DATE);
1746 
1747     // init HCI
1748     hci_init(transport, &config, control, remote_device_db);
1749 
1750 #ifdef USE_BLUETOOL
1751     // iPhone doesn't use SSP yet as there's no UI for it yet and auto accept is not an option
1752     hci_ssp_set_enable(0);
1753 #endif
1754     // init L2CAP
1755     l2cap_init();
1756     l2cap_register_packet_handler(&daemon_packet_handler);
1757     timeout.process = daemon_no_connections_timeout;
1758 
1759 #ifdef HAVE_RFCOMM
1760     log_info("config.h: HAVE_RFCOMM\n");
1761     rfcomm_init();
1762     rfcomm_register_packet_handler(&daemon_packet_handler);
1763 #endif
1764 
1765 #ifdef HAVE_SDP
1766     sdp_init();
1767     sdp_register_packet_handler(&daemon_packet_handler);
1768 #endif
1769 
1770 #ifdef HAVE_BLE
1771     // GATT Client
1772     gatt_client_init();
1773     gatt_client_id = gatt_client_register_packet_handler(&handle_gatt_client_event);
1774 
1775     // sm_init();
1776     // sm_set_io_capabilities(IO_CAPABILITY_DISPLAY_ONLY);
1777     // sm_set_authentication_requirements( SM_AUTHREQ_BONDING | SM_AUTHREQ_MITM_PROTECTION);
1778 
1779     // GATT Server - empty attribute database
1780     le_device_db_init();
1781     att_server_init(NULL, NULL, NULL);
1782 
1783 #endif
1784 
1785 #ifdef USE_LAUNCHD
1786     socket_connection_create_launchd();
1787 #else
1788     // create server
1789     if (tcp_flag) {
1790         socket_connection_create_tcp(BTSTACK_PORT);
1791     } else {
1792         socket_connection_create_unix(BTSTACK_UNIX);
1793     }
1794 #endif
1795     socket_connection_register_packet_callback(&daemon_client_handler);
1796 
1797 #ifdef USE_BLUETOOL
1798     // notify daemons
1799     notify_post("ch.ringwald.btstack.started");
1800 
1801     // spawn thread to have BTstack run loop on new thread, while main thread is used to keep CFRunLoop
1802     pthread_t run_loop;
1803     pthread_create(&run_loop, NULL, &run_loop_thread, NULL);
1804 
1805     // needed to receive notifications
1806     CFRunLoopRun();
1807 #endif
1808         // go!
1809     run_loop_execute();
1810     return 0;
1811 }
1812