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