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