xref: /btstack/platform/daemon/src/daemon.c (revision 9293bfa465772fe235b803158dc699ffd991663d)
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 #ifdef HAVE_BLE
614 
615 linked_list_gatt_client_helper_t * daemon_get_gatt_client_helper(uint16_t handle) {
616     linked_list_iterator_t it;
617     if (!gatt_client_helpers) return NULL;
618     log_info("daemon_get_gatt_client_helper for handle 0x%02x", handle);
619 
620     linked_list_iterator_init(&it, &gatt_client_helpers);
621     while (linked_list_iterator_has_next(&it)){
622         linked_list_gatt_client_helper_t * item = (linked_list_gatt_client_helper_t*) linked_list_iterator_next(&it);
623         if (!item ) {
624             log_info("daemon_get_gatt_client_helper gatt_client_helpers null item");
625             break;
626         }
627         if (item->con_handle == handle){
628             return item;
629         }
630     }
631     log_info("daemon_get_gatt_client_helper for handle 0x%02x is NULL.", handle);
632     return NULL;
633 }
634 
635 static void send_gatt_query_complete(connection_t * connection, uint16_t handle, uint8_t status){
636     // @format H1
637     uint8_t event[5];
638     event[0] = GATT_QUERY_COMPLETE;
639     event[1] = 3;
640     bt_store_16(event, 2, handle);
641     event[4] = status;
642     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
643     socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event));
644 }
645 
646 static void send_gatt_mtu_event(connection_t * connection, uint16_t handle, uint16_t mtu){
647     uint8_t event[6];
648     int pos = 0;
649     event[pos++] = GATT_MTU;
650     event[pos++] = sizeof(event) - 2;
651     bt_store_16(event, pos, handle);
652     pos += 2;
653     bt_store_16(event, pos, mtu);
654     pos += 2;
655     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
656     socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event));
657 }
658 
659 static void send_l2cap_connection_open_failed(connection_t * connection, bd_addr_t address, uint16_t psm, uint8_t status){
660     // emit error - see l2cap.c:l2cap_emit_channel_opened(..)
661     uint8_t event[23];
662     memset(event, 0, sizeof(event));
663     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
664     event[1] = sizeof(event) - 2;
665     event[2] = status;
666     bt_flip_addr(&event[3], address);
667     // bt_store_16(event,  9, channel->handle);
668     bt_store_16(event, 11, psm);
669     // bt_store_16(event, 13, channel->local_cid);
670     // bt_store_16(event, 15, channel->remote_cid);
671     // bt_store_16(event, 17, channel->local_mtu);
672     // bt_store_16(event, 19, channel->remote_mtu);
673     // bt_store_16(event, 21, channel->flush_timeout);
674     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
675     socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event));
676 }
677 
678 static void l2cap_emit_service_registered(void *connection, uint8_t status, uint16_t psm){
679     uint8_t event[5];
680     event[0] = L2CAP_EVENT_SERVICE_REGISTERED;
681     event[1] = sizeof(event) - 2;
682     event[2] = status;
683     bt_store_16(event, 3, psm);
684     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
685     socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event));
686 }
687 
688 static void rfcomm_emit_service_registered(void *connection, uint8_t status, uint8_t channel){
689     uint8_t event[4];
690     event[0] = RFCOMM_EVENT_SERVICE_REGISTERED;
691     event[1] = sizeof(event) - 2;
692     event[2] = status;
693     event[3] = channel;
694     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
695     socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event));
696 }
697 
698 static void send_rfcomm_create_channel_failed(void * connection, bd_addr_t addr, uint8_t server_channel, uint8_t status){
699     // emit error - see rfcom.c:rfcomm_emit_channel_open_failed_outgoing_memory(..)
700     uint8_t event[16];
701     memset(event, 0, sizeof(event));
702     uint8_t pos = 0;
703     event[pos++] = RFCOMM_EVENT_OPEN_CHANNEL_COMPLETE;
704     event[pos++] = sizeof(event) - 2;
705     event[pos++] = status;
706     bt_flip_addr(&event[pos], addr); pos += 6;
707     bt_store_16(event,  pos, 0);   pos += 2;
708     event[pos++] = server_channel;
709     bt_store_16(event, pos, 0); pos += 2;   // channel ID
710     bt_store_16(event, pos, 0); pos += 2;   // max frame size
711     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
712     socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event));
713 }
714 
715 // data: event(8), len(8), status(8), service_record_handle(32)
716 static void sdp_emit_service_registered(void *connection, uint32_t handle, uint8_t status) {
717     uint8_t event[7];
718     event[0] = SDP_SERVICE_REGISTERED;
719     event[1] = sizeof(event) - 2;
720     event[2] = status;
721     bt_store_32(event, 3, handle);
722     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
723     socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event));
724 }
725 
726 linked_list_gatt_client_helper_t * daemon_setup_gatt_client_request(connection_t *connection, uint8_t *packet, int track_active_connection) {
727     hci_con_handle_t handle = READ_BT_16(packet, 3);
728     log_info("daemon_setup_gatt_client_request for handle 0x%02x", handle);
729     hci_connection_t * hci_con = hci_connection_for_handle(handle);
730     if ((hci_con == NULL) || (hci_con->state != OPEN)){
731         send_gatt_query_complete(connection, handle, GATT_CLIENT_NOT_CONNECTED);
732         return NULL;
733     }
734 
735     linked_list_gatt_client_helper_t * helper = daemon_get_gatt_client_helper(handle);
736 
737     if (!helper){
738         log_info("helper does not exist");
739         helper = malloc(sizeof(linked_list_gatt_client_helper_t));
740         if (!helper) return NULL;
741         memset(helper, 0, sizeof(linked_list_gatt_client_helper_t));
742         helper->con_handle = handle;
743         linked_list_add(&gatt_client_helpers, (linked_item_t *) helper);
744     }
745 
746     if (track_active_connection && helper->active_connection){
747         send_gatt_query_complete(connection, handle, GATT_CLIENT_BUSY);
748         return NULL;
749     }
750 
751     daemon_add_gatt_client_handle(connection, handle);
752 
753     if (track_active_connection){
754         // remember connection responsible for this request
755         helper->active_connection = connection;
756     }
757 
758     return helper;
759 }
760 
761 // (de)serialize structs from/to HCI commands/events
762 
763 void daemon_gatt_deserialize_service(uint8_t *packet, int offset, le_service_t *service){
764     service->start_group_handle = READ_BT_16(packet, offset);
765     service->end_group_handle = READ_BT_16(packet, offset + 2);
766     swap128(&packet[offset + 4], service->uuid128);
767 }
768 
769 void daemon_gatt_serialize_service(le_service_t * service, uint8_t * event, int offset){
770     bt_store_16(event, offset, service->start_group_handle);
771     bt_store_16(event, offset+2, service->end_group_handle);
772     swap128(service->uuid128, &event[offset + 4]);
773 }
774 
775 void daemon_gatt_deserialize_characteristic(uint8_t * packet, int offset, le_characteristic_t * characteristic){
776     characteristic->start_handle = READ_BT_16(packet, offset);
777     characteristic->value_handle = READ_BT_16(packet, offset + 2);
778     characteristic->end_handle = READ_BT_16(packet, offset + 4);
779     characteristic->properties = READ_BT_16(packet, offset + 6);
780     characteristic->uuid16 = READ_BT_16(packet, offset + 8);
781     swap128(&packet[offset+10], characteristic->uuid128);
782 }
783 
784 void daemon_gatt_serialize_characteristic(le_characteristic_t * characteristic, uint8_t * event, int offset){
785     bt_store_16(event, offset, characteristic->start_handle);
786     bt_store_16(event, offset+2, characteristic->value_handle);
787     bt_store_16(event, offset+4, characteristic->end_handle);
788     bt_store_16(event, offset+6, characteristic->properties);
789     swap128(characteristic->uuid128, &event[offset+8]);
790 }
791 
792 void daemon_gatt_deserialize_characteristic_descriptor(uint8_t * packet, int offset, le_characteristic_descriptor_t * descriptor){
793     descriptor->handle = READ_BT_16(packet, offset);
794     swap128(&packet[offset+2], descriptor->uuid128);
795 }
796 
797 void daemon_gatt_serialize_characteristic_descriptor(le_characteristic_descriptor_t * characteristic_descriptor, uint8_t * event, int offset){
798     bt_store_16(event, offset, characteristic_descriptor->handle);
799     swap128(characteristic_descriptor->uuid128, &event[offset+2]);
800 }
801 
802 #endif
803 
804 static int btstack_command_handler(connection_t *connection, uint8_t *packet, uint16_t size){
805 
806     bd_addr_t addr;
807     bd_addr_type_t addr_type;
808     hci_con_handle_t handle;
809     uint16_t cid;
810     uint16_t psm;
811     uint16_t service_channel;
812     uint16_t mtu;
813     uint8_t  reason;
814     uint8_t  rfcomm_channel;
815     uint8_t  rfcomm_credits;
816     uint32_t service_record_handle;
817     client_state_t *client;
818     uint8_t status;
819     uint8_t  * data;
820 #if defined(HAVE_MALLOC) && defined(HAVE_BLE)
821     uint8_t uuid128[16];
822     le_service_t service;
823     le_characteristic_t characteristic;
824     le_characteristic_descriptor_t descriptor;
825     uint16_t data_length;
826     linked_list_gatt_client_helper_t * gatt_helper;
827 #endif
828 
829     uint16_t serviceSearchPatternLen;
830     uint16_t attributeIDListLen;
831 
832     // verbose log info before other info to allow for better tracking
833     hci_dump_packet( HCI_COMMAND_DATA_PACKET, 1, packet, size);
834 
835     // BTstack internal commands - 16 Bit OpCode, 8 Bit ParamLen, Params...
836     switch (READ_CMD_OCF(packet)){
837         case BTSTACK_GET_STATE:
838             log_info("BTSTACK_GET_STATE");
839             hci_emit_state();
840             break;
841         case BTSTACK_SET_POWER_MODE:
842             log_info("BTSTACK_SET_POWER_MODE %u", packet[3]);
843             // track client power requests
844             client = client_for_connection(connection);
845             if (!client) break;
846             client->power_mode = packet[3];
847             // handle merged state
848             if (!clients_require_power_on()){
849                 start_power_off_timer();
850             } else if (!power_management_sleep) {
851                 stop_power_off_timer();
852                 hci_power_control(HCI_POWER_ON);
853             }
854             break;
855         case BTSTACK_GET_VERSION:
856             log_info("BTSTACK_GET_VERSION");
857             hci_emit_btstack_version();
858             break;
859 #ifdef USE_BLUETOOL
860         case BTSTACK_SET_SYSTEM_BLUETOOTH_ENABLED:
861             log_info("BTSTACK_SET_SYSTEM_BLUETOOTH_ENABLED %u", packet[3]);
862             iphone_system_bt_set_enabled(packet[3]);
863             hci_emit_system_bluetooth_enabled(iphone_system_bt_enabled());
864             break;
865 
866         case BTSTACK_GET_SYSTEM_BLUETOOTH_ENABLED:
867             log_info("BTSTACK_GET_SYSTEM_BLUETOOTH_ENABLED");
868             hci_emit_system_bluetooth_enabled(iphone_system_bt_enabled());
869             break;
870 #else
871         case BTSTACK_SET_SYSTEM_BLUETOOTH_ENABLED:
872         case BTSTACK_GET_SYSTEM_BLUETOOTH_ENABLED:
873             hci_emit_system_bluetooth_enabled(0);
874             break;
875 #endif
876         case BTSTACK_SET_DISCOVERABLE:
877             log_info("BTSTACK_SET_DISCOVERABLE discoverable %u)", packet[3]);
878             // track client discoverable requests
879             client = client_for_connection(connection);
880             if (!client) break;
881             client->discoverable = packet[3];
882             // merge state
883             hci_discoverable_control(clients_require_discoverable());
884             break;
885         case BTSTACK_SET_BLUETOOTH_ENABLED:
886             log_info("BTSTACK_SET_BLUETOOTH_ENABLED: %u\n", packet[3]);
887             if (packet[3]) {
888                 // global enable
889                 global_enable = 1;
890                 hci_power_control(HCI_POWER_ON);
891             } else {
892                 global_enable = 0;
893                 clients_clear_power_request();
894                 hci_power_control(HCI_POWER_OFF);
895             }
896             break;
897         case L2CAP_CREATE_CHANNEL_MTU:
898             bt_flip_addr(addr, &packet[3]);
899             psm = READ_BT_16(packet, 9);
900             mtu = READ_BT_16(packet, 11);
901             status = l2cap_create_channel(NULL, addr, psm, mtu, &cid);
902             if (status){
903                 send_l2cap_connection_open_failed(connection, addr, psm, status);
904             } else {
905                 daemon_add_client_l2cap_channel(connection, cid);
906             }
907             break;
908         case L2CAP_CREATE_CHANNEL:
909             bt_flip_addr(addr, &packet[3]);
910             psm = READ_BT_16(packet, 9);
911             mtu = 150; // until r865
912             status = l2cap_create_channel(NULL, addr, psm, mtu, &cid);
913             if (status){
914                 send_l2cap_connection_open_failed(connection, addr, psm, status);
915             } else {
916                 daemon_add_client_l2cap_channel(connection, cid);
917             }
918             break;
919         case L2CAP_DISCONNECT:
920             cid = READ_BT_16(packet, 3);
921             reason = packet[5];
922             l2cap_disconnect_internal(cid, reason);
923             break;
924         case L2CAP_REGISTER_SERVICE:
925             psm = READ_BT_16(packet, 3);
926             mtu = READ_BT_16(packet, 5);
927             status = l2cap_register_service(NULL, psm, mtu, LEVEL_0);
928             daemon_add_client_l2cap_service(connection, READ_BT_16(packet, 3));
929             l2cap_emit_service_registered(connection, status, psm);
930             break;
931         case L2CAP_UNREGISTER_SERVICE:
932             psm = READ_BT_16(packet, 3);
933             daemon_remove_client_l2cap_service(connection, psm);
934             l2cap_unregister_service(psm);
935             break;
936         case L2CAP_ACCEPT_CONNECTION:
937             cid    = READ_BT_16(packet, 3);
938             l2cap_accept_connection_internal(cid);
939             break;
940         case L2CAP_DECLINE_CONNECTION:
941             cid    = READ_BT_16(packet, 3);
942             reason = packet[7];
943             l2cap_decline_connection_internal(cid, reason);
944             break;
945         case RFCOMM_CREATE_CHANNEL:
946             bt_flip_addr(addr, &packet[3]);
947             rfcomm_channel = packet[9];
948             status = rfcomm_create_channel(addr, rfcomm_channel, &cid);
949             if (status){
950                 send_rfcomm_create_channel_failed(connection, addr, rfcomm_channel, status);
951             } else {
952                 daemon_add_client_rfcomm_channel(connection, cid);
953             }
954             break;
955         case RFCOMM_CREATE_CHANNEL_WITH_CREDITS:
956             bt_flip_addr(addr, &packet[3]);
957             rfcomm_channel = packet[9];
958             rfcomm_credits = packet[10];
959             status = rfcomm_create_channel_with_initial_credits(addr, rfcomm_channel, rfcomm_credits, &cid );
960             if (status){
961                 send_rfcomm_create_channel_failed(connection, addr, rfcomm_channel, status);
962             } else {
963                 daemon_add_client_rfcomm_channel(connection, cid);
964             }
965             break;
966         case RFCOMM_DISCONNECT:
967             cid = READ_BT_16(packet, 3);
968             reason = packet[5];
969             rfcomm_disconnect_internal(cid);
970             break;
971         case RFCOMM_REGISTER_SERVICE:
972             rfcomm_channel = packet[3];
973             mtu = READ_BT_16(packet, 4);
974             status = rfcomm_register_service(rfcomm_channel, mtu);
975             rfcomm_emit_service_registered(connection, status, rfcomm_channel);
976             break;
977         case RFCOMM_REGISTER_SERVICE_WITH_CREDITS:
978             rfcomm_channel = packet[3];
979             mtu = READ_BT_16(packet, 4);
980             rfcomm_credits = packet[6];
981             status = rfcomm_register_service_with_initial_credits(rfcomm_channel, mtu, rfcomm_credits);
982             rfcomm_emit_service_registered(connection, status, rfcomm_channel);
983             break;
984         case RFCOMM_UNREGISTER_SERVICE:
985             service_channel = READ_BT_16(packet, 3);
986             daemon_remove_client_rfcomm_service(connection, service_channel);
987             rfcomm_unregister_service(service_channel);
988             break;
989         case RFCOMM_ACCEPT_CONNECTION:
990             cid    = READ_BT_16(packet, 3);
991             rfcomm_accept_connection_internal(cid);
992             break;
993         case RFCOMM_DECLINE_CONNECTION:
994             cid    = READ_BT_16(packet, 3);
995             reason = packet[7];
996             rfcomm_decline_connection_internal(cid);
997             break;
998         case RFCOMM_GRANT_CREDITS:
999             cid    = READ_BT_16(packet, 3);
1000             rfcomm_credits = packet[5];
1001             rfcomm_grant_credits(cid, rfcomm_credits);
1002             break;
1003         case RFCOMM_PERSISTENT_CHANNEL: {
1004             if (remote_device_db) {
1005                 // enforce \0
1006                 packet[3+248] = 0;
1007                 rfcomm_channel = remote_device_db->persistent_rfcomm_channel((char*)&packet[3]);
1008             } else {
1009                 // NOTE: hack for non-iOS platforms
1010                 rfcomm_channel = rfcomm_channel_generator++;
1011             }
1012             log_info("RFCOMM_EVENT_PERSISTENT_CHANNEL %u", rfcomm_channel);
1013             uint8_t event[4];
1014             event[0] = RFCOMM_EVENT_PERSISTENT_CHANNEL;
1015             event[1] = sizeof(event) - 2;
1016             event[2] = 0;
1017             event[3] = rfcomm_channel;
1018             hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
1019             socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, (uint8_t *) event, sizeof(event));
1020             break;
1021         }
1022         case SDP_REGISTER_SERVICE_RECORD:
1023             log_info("SDP_REGISTER_SERVICE_RECORD size %u\n", size);
1024             service_record_handle = daemon_sdp_create_and_register_service(&packet[3]);
1025             if (service_record_handle){
1026                 daemon_add_client_sdp_service_record_handle(connection, service_record_handle);
1027                 sdp_emit_service_registered(connection, service_record_handle, 0);
1028             } else {
1029                sdp_emit_service_registered(connection, 0, BTSTACK_MEMORY_ALLOC_FAILED);
1030             }
1031             break;
1032         case SDP_UNREGISTER_SERVICE_RECORD:
1033             service_record_handle = READ_BT_32(packet, 3);
1034             log_info("SDP_UNREGISTER_SERVICE_RECORD handle 0x%x ", service_record_handle);
1035             data = sdp_get_record_for_handle(service_record_handle);
1036             sdp_unregister_service(service_record_handle);
1037             daemon_remove_client_sdp_service_record_handle(connection, service_record_handle);
1038             if (data){
1039                 free(data);
1040             }
1041             break;
1042         case SDP_CLIENT_QUERY_RFCOMM_SERVICES:
1043             bt_flip_addr(addr, &packet[3]);
1044 
1045             serviceSearchPatternLen = de_get_len(&packet[9]);
1046             memcpy(serviceSearchPattern, &packet[9], serviceSearchPatternLen);
1047 
1048             sdp_query_rfcomm_register_callback(handle_sdp_rfcomm_service_result, connection);
1049             sdp_query_rfcomm_channel_and_name_for_search_pattern(addr, serviceSearchPattern);
1050 
1051             break;
1052         case SDP_CLIENT_QUERY_SERVICES:
1053             bt_flip_addr(addr, &packet[3]);
1054             sdp_parser_init();
1055             sdp_client_query_connection = connection;
1056             sdp_parser_register_callback(handle_sdp_client_query_result);
1057 
1058             serviceSearchPatternLen = de_get_len(&packet[9]);
1059             memcpy(serviceSearchPattern, &packet[9], serviceSearchPatternLen);
1060 
1061             attributeIDListLen = de_get_len(&packet[9+serviceSearchPatternLen]);
1062             memcpy(attributeIDList, &packet[9+serviceSearchPatternLen], attributeIDListLen);
1063 
1064             sdp_client_query(addr, (uint8_t*)&serviceSearchPattern[0], (uint8_t*)&attributeIDList[0]);
1065 
1066             // sdp_general_query_for_uuid(addr, SDP_PublicBrowseGroup);
1067             break;
1068         case GAP_LE_SCAN_START:
1069             le_central_start_scan();
1070             break;
1071         case GAP_LE_SCAN_STOP:
1072             le_central_stop_scan();
1073             break;
1074         case GAP_LE_SET_SCAN_PARAMETERS:
1075             le_central_set_scan_parameters(packet[3], READ_BT_16(packet, 4), READ_BT_16(packet, 6));
1076             break;
1077         case GAP_LE_CONNECT:
1078             bt_flip_addr(addr, &packet[4]);
1079             addr_type = packet[3];
1080             le_central_connect(addr, addr_type);
1081             break;
1082         case GAP_LE_CONNECT_CANCEL:
1083             le_central_connect_cancel();
1084             break;
1085         case GAP_DISCONNECT:
1086             handle = READ_BT_16(packet, 3);
1087             gap_disconnect(handle);
1088             break;
1089 #if defined(HAVE_MALLOC) && defined(HAVE_BLE)
1090         case GATT_DISCOVER_ALL_PRIMARY_SERVICES:
1091             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1092             if (!gatt_helper) break;
1093             gatt_client_discover_primary_services(gatt_client_id, gatt_helper->con_handle);
1094             break;
1095         case GATT_DISCOVER_PRIMARY_SERVICES_BY_UUID16:
1096             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1097             if (!gatt_helper) break;
1098             gatt_client_discover_primary_services_by_uuid16(gatt_client_id, gatt_helper->con_handle, READ_BT_16(packet, 5));
1099             break;
1100         case GATT_DISCOVER_PRIMARY_SERVICES_BY_UUID128:
1101             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1102             if (!gatt_helper) break;
1103             swap128(&packet[5], uuid128);
1104             gatt_client_discover_primary_services_by_uuid128(gatt_client_id, gatt_helper->con_handle, uuid128);
1105             break;
1106         case GATT_FIND_INCLUDED_SERVICES_FOR_SERVICE:
1107             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1108             if (!gatt_helper) break;
1109             daemon_gatt_deserialize_service(packet, 5, &service);
1110             gatt_client_find_included_services_for_service(gatt_client_id, gatt_helper->con_handle, &service);
1111             break;
1112 
1113         case GATT_DISCOVER_CHARACTERISTICS_FOR_SERVICE:
1114             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1115             if (!gatt_helper) break;
1116             daemon_gatt_deserialize_service(packet, 5, &service);
1117             gatt_client_discover_characteristics_for_service(gatt_client_id, gatt_helper->con_handle, &service);
1118             break;
1119         case GATT_DISCOVER_CHARACTERISTICS_FOR_SERVICE_BY_UUID128:
1120             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1121             if (!gatt_helper) break;
1122             daemon_gatt_deserialize_service(packet, 5, &service);
1123             swap128(&packet[5 + SERVICE_LENGTH], uuid128);
1124             gatt_client_discover_characteristics_for_service_by_uuid128(gatt_client_id, gatt_helper->con_handle, &service, uuid128);
1125             break;
1126         case GATT_DISCOVER_CHARACTERISTIC_DESCRIPTORS:
1127             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1128             if (!gatt_helper) break;
1129             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
1130             gatt_client_discover_characteristic_descriptors(gatt_client_id, gatt_helper->con_handle, &characteristic);
1131             break;
1132 
1133         case GATT_READ_VALUE_OF_CHARACTERISTIC:
1134             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1135             if (!gatt_helper) break;
1136             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
1137             gatt_client_read_value_of_characteristic(gatt_client_id, gatt_helper->con_handle, &characteristic);
1138             break;
1139         case GATT_READ_LONG_VALUE_OF_CHARACTERISTIC:
1140             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1141             if (!gatt_helper) break;
1142             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
1143             gatt_client_read_long_value_of_characteristic(gatt_client_id, gatt_helper->con_handle, &characteristic);
1144             break;
1145 
1146         case GATT_WRITE_VALUE_OF_CHARACTERISTIC_WITHOUT_RESPONSE:
1147             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 0);  // note: don't track active connection
1148             if (!gatt_helper) break;
1149             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
1150             data_length = READ_BT_16(packet, 5 + CHARACTERISTIC_LENGTH);
1151             data = gatt_helper->characteristic_buffer;
1152             memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length);
1153             gatt_client_write_value_of_characteristic_without_response(gatt_client_id, gatt_helper->con_handle, characteristic.value_handle, data_length, data);
1154             break;
1155         case GATT_WRITE_VALUE_OF_CHARACTERISTIC:
1156             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1157             if (!gatt_helper) break;
1158             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
1159             data_length = READ_BT_16(packet, 5 + CHARACTERISTIC_LENGTH);
1160             data = gatt_helper->characteristic_buffer;
1161             memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length);
1162             gatt_client_write_value_of_characteristic(gatt_client_id, gatt_helper->con_handle, characteristic.value_handle, data_length, data);
1163             break;
1164         case GATT_WRITE_LONG_VALUE_OF_CHARACTERISTIC:
1165             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1166             if (!gatt_helper) break;
1167             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
1168             data_length = READ_BT_16(packet, 5 + CHARACTERISTIC_LENGTH);
1169             data = gatt_helper->characteristic_buffer;
1170             memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length);
1171             gatt_client_write_long_value_of_characteristic(gatt_client_id, gatt_helper->con_handle, characteristic.value_handle, data_length, data);
1172             break;
1173         case GATT_RELIABLE_WRITE_LONG_VALUE_OF_CHARACTERISTIC:
1174             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1175             if (!gatt_helper) break;
1176             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
1177             data_length = READ_BT_16(packet, 5 + CHARACTERISTIC_LENGTH);
1178             data = gatt_helper->characteristic_buffer;
1179             memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length);
1180             gatt_client_write_long_value_of_characteristic(gatt_client_id, gatt_helper->con_handle, characteristic.value_handle, data_length, data);
1181             break;
1182         case GATT_READ_CHARACTERISTIC_DESCRIPTOR:
1183             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1184             if (!gatt_helper) break;
1185             handle = READ_BT_16(packet, 3);
1186             daemon_gatt_deserialize_characteristic_descriptor(packet, 5, &descriptor);
1187             gatt_client_read_characteristic_descriptor(gatt_client_id, gatt_helper->con_handle, &descriptor);
1188             break;
1189         case GATT_READ_LONG_CHARACTERISTIC_DESCRIPTOR:
1190             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1191             if (!gatt_helper) break;
1192             daemon_gatt_deserialize_characteristic_descriptor(packet, 5, &descriptor);
1193             gatt_client_read_long_characteristic_descriptor(gatt_client_id, gatt_helper->con_handle, &descriptor);
1194             break;
1195 
1196         case GATT_WRITE_CHARACTERISTIC_DESCRIPTOR:
1197             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1198             if (!gatt_helper) break;
1199             daemon_gatt_deserialize_characteristic_descriptor(packet, 5, &descriptor);
1200             data = gatt_helper->characteristic_buffer;
1201             data_length = READ_BT_16(packet, 5 + CHARACTERISTIC_DESCRIPTOR_LENGTH);
1202             gatt_client_write_characteristic_descriptor(gatt_client_id, gatt_helper->con_handle, &descriptor, data_length, data);
1203             break;
1204         case GATT_WRITE_LONG_CHARACTERISTIC_DESCRIPTOR:
1205             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1206             if (!gatt_helper) break;
1207             daemon_gatt_deserialize_characteristic_descriptor(packet, 5, &descriptor);
1208             data = gatt_helper->characteristic_buffer;
1209             data_length = READ_BT_16(packet, 5 + CHARACTERISTIC_DESCRIPTOR_LENGTH);
1210             gatt_client_write_long_characteristic_descriptor(gatt_client_id, gatt_helper->con_handle, &descriptor, data_length, data);
1211             break;
1212         case GATT_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION:{
1213             uint16_t configuration = READ_BT_16(packet, 5 + CHARACTERISTIC_LENGTH);
1214             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1215             if (!gatt_helper) break;
1216             data = gatt_helper->characteristic_buffer;
1217             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
1218             gatt_client_write_client_characteristic_configuration(gatt_client_id, gatt_helper->con_handle, &characteristic, configuration);
1219             break;
1220         case GATT_GET_MTU:
1221             handle = READ_BT_16(packet, 3);
1222             gatt_client_get_mtu(handle, &mtu);
1223             send_gatt_mtu_event(connection, handle, mtu);
1224             break;
1225         }
1226 #endif
1227     default:
1228             log_error("Error: command %u not implemented:", READ_CMD_OCF(packet));
1229             break;
1230     }
1231 
1232     return 0;
1233 }
1234 
1235 static int daemon_client_handler(connection_t *connection, uint16_t packet_type, uint16_t channel, uint8_t *data, uint16_t length){
1236 
1237     int err = 0;
1238     client_state_t * client;
1239 
1240     switch (packet_type){
1241         case HCI_COMMAND_DATA_PACKET:
1242             if (READ_CMD_OGF(data) != OGF_BTSTACK) {
1243                 // HCI Command
1244                 hci_send_cmd_packet(data, length);
1245             } else {
1246                 // BTstack command
1247                 btstack_command_handler(connection, data, length);
1248             }
1249             break;
1250         case L2CAP_DATA_PACKET:
1251             // process l2cap packet...
1252             err = l2cap_send_internal(channel, data, length);
1253             if (err == BTSTACK_ACL_BUFFERS_FULL) {
1254                 l2cap_block_new_credits(1);
1255             }
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     if (!socket_connection_has_parked_connections()){
1377         l2cap_block_new_credits(0);
1378     }
1379 
1380     // unlock mutex
1381     retry_mutex = 0;
1382 }
1383 
1384 #if 0
1385 
1386 Minimal Code for LE Peripheral
1387 
1388 enum {
1389     SET_ADVERTISEMENT_PARAMS = 1 << 0,
1390     SET_ADVERTISEMENT_DATA   = 1 << 1,
1391     ENABLE_ADVERTISEMENTS    = 1 << 2,
1392 };
1393 
1394 const uint8_t adv_data[] = {
1395     // Flags general discoverable
1396     0x02, 0x01, 0x02,
1397     // Name
1398     0x08, 0x09, 'B', 'T', 's', 't', 'a', 'c', 'k'
1399 };
1400 uint8_t adv_data_len = sizeof(adv_data);
1401 static uint16_t todos = 0;
1402 
1403 static void app_run(void){
1404 
1405     if (!hci_can_send_command_packet_now()) return;
1406 
1407     if (todos & SET_ADVERTISEMENT_DATA){
1408         log_info("app_run: set advertisement data\n");
1409         todos &= ~SET_ADVERTISEMENT_DATA;
1410         hci_send_cmd(&hci_le_set_advertising_data, adv_data_len, adv_data);
1411         return;
1412     }
1413 
1414     if (todos & SET_ADVERTISEMENT_PARAMS){
1415         todos &= ~SET_ADVERTISEMENT_PARAMS;
1416         uint8_t adv_type = 0;   // default
1417         bd_addr_t null_addr;
1418         memset(null_addr, 0, 6);
1419         uint16_t adv_int_min = 0x0030;
1420         uint16_t adv_int_max = 0x0030;
1421         hci_send_cmd(&hci_le_set_advertising_parameters, adv_int_min, adv_int_max, adv_type, 0, 0, &null_addr, 0x07, 0x00);
1422         return;
1423     }
1424 
1425     if (todos & ENABLE_ADVERTISEMENTS){
1426         log_info("app_run: enable advertisements\n");
1427         todos &= ~ENABLE_ADVERTISEMENTS;
1428         hci_send_cmd(&hci_le_set_advertise_enable, 1);
1429         return;
1430     }
1431 }
1432 #endif
1433 
1434 static void daemon_packet_handler(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1435     uint16_t cid;
1436     switch (packet_type) {
1437         case HCI_EVENT_PACKET:
1438             deamon_status_event_handler(packet, size);
1439             switch (packet[0]){
1440 
1441                 case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
1442                     // ACL buffer freed...
1443                     daemon_retry_parked();
1444                     // no need to tell clients
1445                     return;
1446                 case RFCOMM_EVENT_CREDITS:
1447                     // RFCOMM CREDITS received...
1448                     daemon_retry_parked();
1449                     break;
1450                  case RFCOMM_EVENT_OPEN_CHANNEL_COMPLETE:
1451                     cid = READ_BT_16(packet, 13);
1452                     connection = connection_for_rfcomm_cid(cid);
1453                     if (!connection) break;
1454                     if (packet[2]) {
1455                         daemon_remove_client_rfcomm_channel(connection, cid);
1456                     } else {
1457                         daemon_add_client_rfcomm_channel(connection, cid);
1458                     }
1459                     break;
1460                 case RFCOMM_EVENT_CHANNEL_CLOSED:
1461                     cid = READ_BT_16(packet, 2);
1462                     connection = connection_for_rfcomm_cid(cid);
1463                     if (!connection) break;
1464                     daemon_remove_client_rfcomm_channel(connection, cid);
1465                     break;
1466                 case RFCOMM_EVENT_SERVICE_REGISTERED:
1467                     if (packet[2]) break;
1468                     daemon_add_client_rfcomm_service(connection, packet[3]);
1469                     break;
1470                 case L2CAP_EVENT_CHANNEL_OPENED:
1471                     cid = READ_BT_16(packet, 13);
1472                     connection = connection_for_l2cap_cid(cid);
1473                     if (!connection) break;
1474                     if (packet[2]) {
1475                         daemon_remove_client_l2cap_channel(connection, cid);
1476                     } else {
1477                         daemon_add_client_l2cap_channel(connection, cid);
1478                     }
1479                     break;
1480                 case L2CAP_EVENT_CHANNEL_CLOSED:
1481                     cid = READ_BT_16(packet, 2);
1482                     connection = connection_for_l2cap_cid(cid);
1483                     if (!connection) break;
1484                     daemon_remove_client_l2cap_channel(connection, cid);
1485                     break;
1486 #if defined(HAVE_BLE) && defined(HAVE_MALLOC)
1487                 case HCI_EVENT_DISCONNECTION_COMPLETE:
1488                     log_info("daemon : ignore HCI_EVENT_DISCONNECTION_COMPLETE ingnoring.");
1489                     // note: moved to gatt_client_handler because it's received here prematurely
1490                     // daemon_remove_gatt_client_helper(READ_BT_16(packet, 3));
1491                     break;
1492 #endif
1493                 default:
1494                     break;
1495             }
1496         case DAEMON_EVENT_PACKET:
1497             switch (packet[0]){
1498                 case DAEMON_EVENT_NEW_RFCOMM_CREDITS:
1499                     daemon_retry_parked();
1500                     break;
1501                 default:
1502                     break;
1503             }
1504         case L2CAP_DATA_PACKET:
1505             connection = connection_for_l2cap_cid(channel);
1506             if (!connection) return;
1507             break;
1508         case RFCOMM_DATA_PACKET:
1509             connection = connection_for_l2cap_cid(channel);
1510             if (!connection) return;
1511             break;
1512         default:
1513             break;
1514     }
1515 
1516     if (connection) {
1517         socket_connection_send_packet(connection, packet_type, channel, packet, size);
1518     } else {
1519         socket_connection_send_packet_all(packet_type, channel, packet, size);
1520     }
1521 }
1522 
1523 static void l2cap_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){
1524     daemon_packet_handler(NULL, packet_type, channel, packet, size);
1525 }
1526 static void rfcomm_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){
1527     daemon_packet_handler(NULL, packet_type, channel, packet, size);
1528 }
1529 
1530 static void handle_sdp_rfcomm_service_result(sdp_query_event_t * rfcomm_event, void * context){
1531     switch (rfcomm_event->type){
1532         case SDP_QUERY_RFCOMM_SERVICE: {
1533             sdp_query_rfcomm_service_event_t * service_event = (sdp_query_rfcomm_service_event_t*) rfcomm_event;
1534             int name_len = (int)strlen((const char*)service_event->service_name);
1535             int event_len = 3 + name_len;
1536             uint8_t event[event_len];
1537             event[0] = rfcomm_event->type;
1538             event[1] = 1 + name_len;
1539             event[2] = service_event->channel_nr;
1540             memcpy(&event[3], service_event->service_name, name_len);
1541             hci_dump_packet(HCI_EVENT_PACKET, 0, event, event_len);
1542             socket_connection_send_packet(context, HCI_EVENT_PACKET, 0, event, event_len);
1543             break;
1544         }
1545         case SDP_QUERY_COMPLETE: {
1546             sdp_query_complete_event_t * complete_event = (sdp_query_complete_event_t*) rfcomm_event;
1547             uint8_t event[] = { rfcomm_event->type, 1, complete_event->status};
1548             hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
1549             socket_connection_send_packet(context, HCI_EVENT_PACKET, 0, event, sizeof(event));
1550             break;
1551         }
1552     }
1553 }
1554 
1555 static void sdp_client_assert_buffer(int size){
1556     if (size > attribute_value_buffer_size){
1557         log_error("SDP attribute value buffer size exceeded: available %d, required %d", attribute_value_buffer_size, size);
1558     }
1559 }
1560 
1561 // define new packet type SDP_CLIENT_PACKET
1562 static void handle_sdp_client_query_result(sdp_query_event_t * event){
1563     sdp_query_attribute_value_event_t * ve;
1564     sdp_query_complete_event_t * complete_event;
1565 
1566     switch (event->type){
1567         case SDP_QUERY_ATTRIBUTE_VALUE:
1568             ve = (sdp_query_attribute_value_event_t*) event;
1569 
1570             sdp_client_assert_buffer(ve->attribute_length);
1571 
1572             attribute_value[ve->data_offset] = ve->data;
1573 
1574             if ((uint16_t)(ve->data_offset+1) == ve->attribute_length){
1575                 hexdump(attribute_value, ve->attribute_length);
1576 
1577                 int event_len = 1 + 3 * 2 + ve->attribute_length;
1578                 uint8_t event[event_len];
1579                 event[0] = SDP_QUERY_ATTRIBUTE_VALUE;
1580                 bt_store_16(event, 1, (uint16_t)ve->record_id);
1581                 bt_store_16(event, 3, ve->attribute_id);
1582                 bt_store_16(event, 5, (uint16_t)ve->attribute_length);
1583                 memcpy(&event[7], attribute_value, ve->attribute_length);
1584                 hci_dump_packet(SDP_CLIENT_PACKET, 0, event, event_len);
1585                 socket_connection_send_packet(sdp_client_query_connection, SDP_CLIENT_PACKET, 0, event, event_len);
1586             }
1587 
1588             break;
1589         case SDP_QUERY_COMPLETE:
1590             complete_event = (sdp_query_complete_event_t*) event;
1591             uint8_t event[] = { SDP_QUERY_COMPLETE, 1, complete_event->status};
1592             hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
1593             socket_connection_send_packet(sdp_client_query_connection, HCI_EVENT_PACKET, 0, event, sizeof(event));
1594             break;
1595     }
1596 }
1597 
1598 static void power_notification_callback(POWER_NOTIFICATION_t notification){
1599     switch (notification) {
1600         case POWER_WILL_SLEEP:
1601             // let's sleep
1602             power_management_sleep = 1;
1603             hci_power_control(HCI_POWER_SLEEP);
1604             break;
1605         case POWER_WILL_WAKE_UP:
1606             // assume that all clients use Bluetooth -> if connection, start Bluetooth
1607             power_management_sleep = 0;
1608             if (clients_require_power_on()) {
1609                 hci_power_control(HCI_POWER_ON);
1610             }
1611             break;
1612         default:
1613             break;
1614     }
1615 }
1616 
1617 static void daemon_sigint_handler(int param){
1618 
1619 #ifdef USE_BLUETOOL
1620     // notify daemons
1621     notify_post("ch.ringwald.btstack.stopped");
1622 #endif
1623 
1624     log_info(" <= SIGINT received, shutting down..\n");
1625 
1626     hci_power_control( HCI_POWER_OFF);
1627     hci_close();
1628 
1629     log_info("Good bye, see you.\n");
1630 
1631     exit(0);
1632 }
1633 
1634 // MARK: manage power off timer
1635 
1636 #define USE_POWER_OFF_TIMER
1637 
1638 static void stop_power_off_timer(void){
1639 #ifdef USE_POWER_OFF_TIMER
1640     if (timeout_active) {
1641         run_loop_remove_timer(&timeout);
1642         timeout_active = 0;
1643     }
1644 #endif
1645 }
1646 
1647 static void start_power_off_timer(void){
1648 #ifdef USE_POWER_OFF_TIMER
1649     stop_power_off_timer();
1650     run_loop_set_timer(&timeout, DAEMON_NO_ACTIVE_CLIENT_TIMEOUT);
1651     run_loop_add_timer(&timeout);
1652     timeout_active = 1;
1653 #else
1654     hci_power_control(HCI_POWER_OFF);
1655 #endif
1656 }
1657 
1658 // MARK: manage list of clients
1659 
1660 
1661 static client_state_t * client_for_connection(connection_t *connection) {
1662     linked_item_t *it;
1663     for (it = (linked_item_t *) clients; it ; it = it->next){
1664         client_state_t * client_state = (client_state_t *) it;
1665         if (client_state->connection == connection) {
1666             return client_state;
1667         }
1668     }
1669     return NULL;
1670 }
1671 
1672 static void clients_clear_power_request(void){
1673     linked_item_t *it;
1674     for (it = (linked_item_t *) clients; it ; it = it->next){
1675         client_state_t * client_state = (client_state_t *) it;
1676         client_state->power_mode = HCI_POWER_OFF;
1677     }
1678 }
1679 
1680 static int clients_require_power_on(void){
1681 
1682     if (global_enable) return 1;
1683 
1684     linked_item_t *it;
1685     for (it = (linked_item_t *) clients; it ; it = it->next){
1686         client_state_t * client_state = (client_state_t *) it;
1687         if (client_state->power_mode == HCI_POWER_ON) {
1688             return 1;
1689         }
1690     }
1691     return 0;
1692 }
1693 
1694 static int clients_require_discoverable(void){
1695     linked_item_t *it;
1696     for (it = (linked_item_t *) clients; it ; it = it->next){
1697         client_state_t * client_state = (client_state_t *) it;
1698         if (client_state->discoverable) {
1699             return 1;
1700         }
1701     }
1702     return 0;
1703 }
1704 
1705 static void usage(const char * name) {
1706     printf("%s, BTstack background daemon\n", name);
1707     printf("usage: %s [--help] [--tcp port]\n", name);
1708     printf("    --help   display this usage\n");
1709     printf("    --tcp    use TCP server on port %u\n", BTSTACK_PORT);
1710     printf("Without the --tcp option, BTstack daemon is listening on unix domain socket %s\n\n", BTSTACK_UNIX);
1711 }
1712 
1713 #ifdef USE_BLUETOOL
1714 static void * run_loop_thread(void *context){
1715     run_loop_execute();
1716     return NULL;
1717 }
1718 #endif
1719 
1720 #ifdef HAVE_BLE
1721 
1722 static void handle_gatt_client_event(uint8_t packet_type, uint8_t * packet, uint16_t size){
1723 
1724     // hack: handle disconnection_complete_here instead of main hci event packet handler
1725     // we receive a HCI event packet in disguise
1726     if (packet[0] == HCI_EVENT_DISCONNECTION_COMPLETE){
1727         log_info("daemon hack: handle disconnection_complete in handle_gatt_client_event instead of main hci event packet handler");
1728         uint16_t handle = READ_BT_16(packet, 3);
1729         daemon_remove_gatt_client_helper(handle);
1730         return;
1731     }
1732 
1733     // only handle GATT Events
1734     switch(packet[0]){
1735         case GATT_SERVICE_QUERY_RESULT:
1736         case GATT_INCLUDED_SERVICE_QUERY_RESULT:
1737         case GATT_NOTIFICATION:
1738         case GATT_INDICATION:
1739         case GATT_CHARACTERISTIC_QUERY_RESULT:
1740         case GATT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
1741         case GATT_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
1742         case GATT_LONG_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
1743         case GATT_CHARACTERISTIC_VALUE_QUERY_RESULT:
1744         case GATT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT:
1745         case GATT_QUERY_COMPLETE:
1746            break;
1747         default:
1748             return;
1749     }
1750 
1751     uint16_t con_handle = READ_BT_16(packet, 2);
1752     linked_list_gatt_client_helper_t * gatt_client_helper = daemon_get_gatt_client_helper(con_handle);
1753     if (!gatt_client_helper){
1754         log_info("daemon handle_gatt_client_event: gc helper for handle 0x%2x is NULL.", con_handle);
1755         return;
1756     }
1757 
1758     connection_t *connection = NULL;
1759 
1760     // daemon doesn't track which connection subscribed to this particular handle, so we just notify all connections
1761     switch(packet[0]){
1762         case GATT_NOTIFICATION:
1763         case GATT_INDICATION:{
1764             hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size);
1765 
1766             linked_item_t *it;
1767             for (it = (linked_item_t *) clients; it ; it = it->next){
1768                 client_state_t * client_state = (client_state_t *) it;
1769                 socket_connection_send_packet(client_state->connection, HCI_EVENT_PACKET, 0, packet, size);
1770             }
1771             return;
1772         }
1773         default:
1774             break;
1775     }
1776 
1777     // otherwise, we have to have an active connection
1778     connection = gatt_client_helper->active_connection;
1779     uint16_t offset;
1780     uint16_t length;
1781 
1782     if (!connection) return;
1783 
1784     switch(packet[0]){
1785 
1786         case GATT_SERVICE_QUERY_RESULT:
1787         case GATT_INCLUDED_SERVICE_QUERY_RESULT:
1788         case GATT_CHARACTERISTIC_QUERY_RESULT:
1789         case GATT_CHARACTERISTIC_VALUE_QUERY_RESULT:
1790         case GATT_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
1791         case GATT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
1792             hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size);
1793             socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, packet, size);
1794             break;
1795 
1796         case GATT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT:
1797         case GATT_LONG_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
1798             offset = READ_BT_16(packet, 6);
1799             length = READ_BT_16(packet, 8);
1800             gatt_client_helper->characteristic_buffer[0] = packet[0];               // store type (characteristic/descriptor)
1801             gatt_client_helper->characteristic_handle    = READ_BT_16(packet, 4);   // store attribute handle
1802             gatt_client_helper->characteristic_length = offset + length;            // update length
1803             memcpy(&gatt_client_helper->characteristic_buffer[10 + offset], &packet[10], length);
1804             break;
1805 
1806         case GATT_QUERY_COMPLETE:{
1807             gatt_client_helper->active_connection = NULL;
1808             if (gatt_client_helper->characteristic_length){
1809                 // send re-combined long characteristic value or long characteristic descriptor value
1810                 uint8_t * event = gatt_client_helper->characteristic_buffer;
1811                 uint16_t event_size = 10 + gatt_client_helper->characteristic_length;
1812                 // event[0] == already set by previsous case
1813                 event[1] = 8 + gatt_client_helper->characteristic_length;
1814                 bt_store_16(event, 2, READ_BT_16(packet, 2));
1815                 bt_store_16(event, 4, gatt_client_helper->characteristic_handle);
1816                 bt_store_16(event, 6, 0);   // offset
1817                 bt_store_16(event, 8, gatt_client_helper->characteristic_length);
1818                 hci_dump_packet(HCI_EVENT_PACKET, 0, event, event_size);
1819                 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, event_size);
1820                 gatt_client_helper->characteristic_length = 0;
1821             }
1822             hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size);
1823             socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, packet, size);
1824             break;
1825         }
1826         default:
1827             break;
1828     }
1829 }
1830 #endif
1831 
1832 int main (int argc,  char * const * argv){
1833 
1834     static int tcp_flag = 0;
1835 
1836     while (1) {
1837         static struct option long_options[] = {
1838             { "tcp", no_argument, &tcp_flag, 1 },
1839             { "help", no_argument, 0, 0 },
1840             { 0,0,0,0 } // This is a filler for -1
1841         };
1842 
1843         int c;
1844         int option_index = -1;
1845 
1846         c = getopt_long(argc, argv, "h", long_options, &option_index);
1847 
1848         if (c == -1) break; // no more option
1849 
1850         // treat long parameter first
1851         if (option_index == -1) {
1852             switch (c) {
1853                 case '?':
1854                 case 'h':
1855                     usage(argv[0]);
1856                     return 0;
1857                     break;
1858             }
1859         } else {
1860             switch (option_index) {
1861                 case 1:
1862                     usage(argv[0]);
1863                     return 0;
1864                     break;
1865             }
1866         }
1867     }
1868 
1869     if (tcp_flag){
1870         printf("BTstack Daemon started on port %u\n", BTSTACK_PORT);
1871     } else {
1872         printf("BTstack Daemon started on socket %s\n", BTSTACK_UNIX);
1873     }
1874 
1875     // make stdout unbuffered
1876     setbuf(stdout, NULL);
1877 
1878     // handle CTRL-c
1879     signal(SIGINT, daemon_sigint_handler);
1880     // handle SIGTERM - suggested for launchd
1881     signal(SIGTERM, daemon_sigint_handler);
1882 
1883     // TODO: win32 variant
1884 #ifndef _WIN32
1885     // handle SIGPIPE
1886     struct sigaction act;
1887     act.sa_handler = SIG_IGN;
1888     sigemptyset (&act.sa_mask);
1889     act.sa_flags = 0;
1890     sigaction (SIGPIPE, &act, NULL);
1891 #endif
1892 
1893     bt_control_t * control = NULL;
1894 
1895 #ifdef HAVE_TRANSPORT_H4
1896     config.device_name   = UART_DEVICE;
1897     config.baudrate_init = UART_SPEED;
1898     config.baudrate_main = 0;
1899     config.flowcontrol = 1;
1900 #if defined(USE_BLUETOOL) && defined(USE_POWERMANAGEMENT)
1901     if (bt_control_iphone_power_management_supported()){
1902         // use default (max) UART baudrate over netraph interface
1903         config.baudrate_init = 0;
1904         transport = hci_transport_h4_iphone_instance();
1905     } else {
1906         transport = hci_transport_h4_instance();
1907     }
1908 #else
1909     transport = hci_transport_h4_instance();
1910 #endif
1911 #endif
1912 
1913 #ifdef HAVE_TRANSPORT_USB
1914     transport = hci_transport_usb_instance();
1915 #endif
1916 
1917 #ifdef USE_BLUETOOL
1918     control = &bt_control_iphone;
1919 #endif
1920 
1921 #if defined(USE_BLUETOOL) && defined(USE_POWERMANAGEMENT)
1922     if (bt_control_iphone_power_management_supported()){
1923         hci_transport_h4_iphone_set_enforce_wake_device("/dev/btwake");
1924     }
1925 #endif
1926 
1927 #ifdef USE_SPRINGBOARD
1928     bluetooth_status_handler = platform_iphone_status_handler;
1929     platform_iphone_register_window_manager_restart(update_ui_status);
1930     platform_iphone_register_preferences_changed(preferences_changed_callback);
1931 #endif
1932 
1933 #ifdef REMOTE_DEVICE_DB
1934     remote_device_db = &REMOTE_DEVICE_DB;
1935 #endif
1936 
1937     run_loop_init(RUN_LOOP_POSIX);
1938 
1939     // init power management notifications
1940     if (control && control->register_for_power_notifications){
1941         control->register_for_power_notifications(power_notification_callback);
1942     }
1943 
1944     // logging
1945     loggingEnabled = 0;
1946     int newLoggingEnabled = 1;
1947 #ifdef USE_BLUETOOL
1948     // iPhone has toggle in Preferences.app
1949     newLoggingEnabled = platform_iphone_logging_enabled();
1950 #endif
1951     daemon_set_logging_enabled(newLoggingEnabled);
1952 
1953     // dump version
1954     log_info("BTdaemon started\n");
1955     log_info("version %s, build %s", BTSTACK_VERSION, BTSTACK_DATE);
1956 
1957     // init HCI
1958     hci_init(transport, &config, control, remote_device_db);
1959 
1960 #ifdef USE_BLUETOOL
1961     // iPhone doesn't use SSP yet as there's no UI for it yet and auto accept is not an option
1962     hci_ssp_set_enable(0);
1963 #endif
1964     // init L2CAP
1965     l2cap_init();
1966     l2cap_register_packet_handler(&l2cap_packet_handler);
1967     timeout.process = daemon_no_connections_timeout;
1968 
1969 #ifdef HAVE_RFCOMM
1970     log_info("config.h: HAVE_RFCOMM\n");
1971     rfcomm_init();
1972     rfcomm_register_packet_handler(&rfcomm_packet_handler);
1973 #endif
1974 
1975 #ifdef HAVE_SDP
1976     sdp_init();
1977 #endif
1978 
1979 #ifdef HAVE_BLE
1980     // GATT Client
1981     gatt_client_init();
1982     gatt_client_id = gatt_client_register_packet_handler(&handle_gatt_client_event);
1983 
1984     // sm_init();
1985     // sm_set_io_capabilities(IO_CAPABILITY_DISPLAY_ONLY);
1986     // sm_set_authentication_requirements( SM_AUTHREQ_BONDING | SM_AUTHREQ_MITM_PROTECTION);
1987 
1988     // GATT Server - empty attribute database
1989     le_device_db_init();
1990     att_server_init(NULL, NULL, NULL);
1991 
1992 #endif
1993 
1994 #ifdef USE_LAUNCHD
1995     socket_connection_create_launchd();
1996 #else
1997     // create server
1998     if (tcp_flag) {
1999         socket_connection_create_tcp(BTSTACK_PORT);
2000     } else {
2001         socket_connection_create_unix(BTSTACK_UNIX);
2002     }
2003 #endif
2004     socket_connection_register_packet_callback(&daemon_client_handler);
2005 
2006 #ifdef USE_BLUETOOL
2007     // notify daemons
2008     notify_post("ch.ringwald.btstack.started");
2009 
2010     // spawn thread to have BTstack run loop on new thread, while main thread is used to keep CFRunLoop
2011     pthread_t run_loop;
2012     pthread_create(&run_loop, NULL, &run_loop_thread, NULL);
2013 
2014     // needed to receive notifications
2015     CFRunLoopRun();
2016 #endif
2017         // go!
2018     run_loop_execute();
2019     return 0;
2020 }
2021