xref: /btstack/platform/daemon/src/daemon.c (revision 616edd56bcd31feb1a533261862afdeab6d85517)
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             if (err == BTSTACK_ACL_BUFFERS_FULL) {
1255                 l2cap_block_new_credits(1);
1256             }
1257             break;
1258         case RFCOMM_DATA_PACKET:
1259             // process l2cap packet...
1260             err = rfcomm_send_internal(channel, data, length);
1261             break;
1262         case DAEMON_EVENT_PACKET:
1263             switch (data[0]) {
1264                 case DAEMON_EVENT_CONNECTION_OPENED:
1265                     log_info("DAEMON_EVENT_CONNECTION_OPENED %p\n",connection);
1266 
1267                     client = malloc(sizeof(client_state_t));
1268                     if (!client) break; // fail
1269                     memset(client, 0, sizeof(client_state_t));
1270                     client->connection   = connection;
1271                     client->power_mode   = HCI_POWER_OFF;
1272                     client->discoverable = 0;
1273                     linked_list_add(&clients, (linked_item_t *) client);
1274                     break;
1275                 case DAEMON_EVENT_CONNECTION_CLOSED:
1276                     log_info("DAEMON_EVENT_CONNECTION_CLOSED %p\n",connection);
1277                     daemon_disconnect_client(connection);
1278                     sdp_query_rfcomm_deregister_callback();
1279                     // no clients -> no HCI connections
1280                     if (!clients){
1281                         hci_disconnect_all();
1282                     }
1283 
1284                     // update discoverable mode
1285                     hci_discoverable_control(clients_require_discoverable());
1286                     // start power off, if last active client
1287                     if (!clients_require_power_on()){
1288                         start_power_off_timer();
1289                     }
1290                     break;
1291                 case DAEMON_NR_CONNECTIONS_CHANGED:
1292                     log_info("Nr Connections changed, new %u\n",data[1]);
1293                     break;
1294                 default:
1295                     break;
1296             }
1297             break;
1298     }
1299     if (err) {
1300         log_info("Daemon Handler: err %d\n", err);
1301     }
1302     return err;
1303 }
1304 
1305 
1306 static void daemon_set_logging_enabled(int enabled){
1307     if (enabled && !loggingEnabled){
1308         hci_dump_open(BTSTACK_LOG_FILE, BTSTACK_LOG_TYPE);
1309     }
1310     if (!enabled && loggingEnabled){
1311         hci_dump_close();
1312     }
1313     loggingEnabled = enabled;
1314 }
1315 
1316 // local cache used to manage UI status
1317 static HCI_STATE hci_state = HCI_STATE_OFF;
1318 static int num_connections = 0;
1319 static void update_ui_status(void){
1320     if (hci_state != HCI_STATE_WORKING) {
1321         bluetooth_status_handler(BLUETOOTH_OFF);
1322     } else {
1323         if (num_connections) {
1324             bluetooth_status_handler(BLUETOOTH_ACTIVE);
1325         } else {
1326             bluetooth_status_handler(BLUETOOTH_ON);
1327         }
1328     }
1329 }
1330 
1331 #ifdef USE_SPRINGBOARD
1332 static void preferences_changed_callback(void){
1333     int logging = platform_iphone_logging_enabled();
1334     log_info("Logging enabled: %u\n", logging);
1335     daemon_set_logging_enabled(logging);
1336 }
1337 #endif
1338 
1339 static void deamon_status_event_handler(uint8_t *packet, uint16_t size){
1340 
1341     uint8_t update_status = 0;
1342 
1343     // handle state event
1344     switch (packet[0]) {
1345         case BTSTACK_EVENT_STATE:
1346             hci_state = packet[2];
1347             log_info("New state: %u\n", hci_state);
1348             update_status = 1;
1349             break;
1350         case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED:
1351             num_connections = packet[2];
1352             log_info("New nr connections: %u\n", num_connections);
1353             update_status = 1;
1354             break;
1355         default:
1356             break;
1357     }
1358 
1359     // choose full bluetooth state
1360     if (update_status) {
1361         update_ui_status();
1362     }
1363 }
1364 
1365 static void daemon_retry_parked(void){
1366 
1367     // socket_connection_retry_parked is not reentrant
1368     static int retry_mutex = 0;
1369 
1370     // lock mutex
1371     if (retry_mutex) return;
1372     retry_mutex = 1;
1373 
1374     // ... try sending again
1375     socket_connection_retry_parked();
1376 
1377     if (!socket_connection_has_parked_connections()){
1378         l2cap_block_new_credits(0);
1379     }
1380 
1381     // unlock mutex
1382     retry_mutex = 0;
1383 }
1384 
1385 #if 0
1386 
1387 Minimal Code for LE Peripheral
1388 
1389 enum {
1390     SET_ADVERTISEMENT_PARAMS = 1 << 0,
1391     SET_ADVERTISEMENT_DATA   = 1 << 1,
1392     ENABLE_ADVERTISEMENTS    = 1 << 2,
1393 };
1394 
1395 const uint8_t adv_data[] = {
1396     // Flags general discoverable
1397     0x02, 0x01, 0x02,
1398     // Name
1399     0x08, 0x09, 'B', 'T', 's', 't', 'a', 'c', 'k'
1400 };
1401 uint8_t adv_data_len = sizeof(adv_data);
1402 static uint16_t todos = 0;
1403 
1404 static void app_run(void){
1405 
1406     if (!hci_can_send_command_packet_now()) return;
1407 
1408     if (todos & SET_ADVERTISEMENT_DATA){
1409         log_info("app_run: set advertisement data\n");
1410         todos &= ~SET_ADVERTISEMENT_DATA;
1411         hci_send_cmd(&hci_le_set_advertising_data, adv_data_len, adv_data);
1412         return;
1413     }
1414 
1415     if (todos & SET_ADVERTISEMENT_PARAMS){
1416         todos &= ~SET_ADVERTISEMENT_PARAMS;
1417         uint8_t adv_type = 0;   // default
1418         bd_addr_t null_addr;
1419         memset(null_addr, 0, 6);
1420         uint16_t adv_int_min = 0x0030;
1421         uint16_t adv_int_max = 0x0030;
1422         hci_send_cmd(&hci_le_set_advertising_parameters, adv_int_min, adv_int_max, adv_type, 0, 0, &null_addr, 0x07, 0x00);
1423         return;
1424     }
1425 
1426     if (todos & ENABLE_ADVERTISEMENTS){
1427         log_info("app_run: enable advertisements\n");
1428         todos &= ~ENABLE_ADVERTISEMENTS;
1429         hci_send_cmd(&hci_le_set_advertise_enable, 1);
1430         return;
1431     }
1432 }
1433 #endif
1434 
1435 static void daemon_packet_handler(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1436     uint16_t cid;
1437     switch (packet_type) {
1438         case HCI_EVENT_PACKET:
1439             deamon_status_event_handler(packet, size);
1440             switch (packet[0]){
1441 
1442                 case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
1443                     // ACL buffer freed...
1444                     daemon_retry_parked();
1445                     // no need to tell clients
1446                     return;
1447                 case RFCOMM_EVENT_CREDITS:
1448                     // RFCOMM CREDITS received...
1449                     daemon_retry_parked();
1450                     break;
1451                  case RFCOMM_EVENT_OPEN_CHANNEL_COMPLETE:
1452                     cid = READ_BT_16(packet, 13);
1453                     connection = connection_for_rfcomm_cid(cid);
1454                     if (!connection) break;
1455                     if (packet[2]) {
1456                         daemon_remove_client_rfcomm_channel(connection, cid);
1457                     } else {
1458                         daemon_add_client_rfcomm_channel(connection, cid);
1459                     }
1460                     break;
1461                 case RFCOMM_EVENT_CHANNEL_CLOSED:
1462                     cid = READ_BT_16(packet, 2);
1463                     connection = connection_for_rfcomm_cid(cid);
1464                     if (!connection) break;
1465                     daemon_remove_client_rfcomm_channel(connection, cid);
1466                     break;
1467                 case RFCOMM_EVENT_SERVICE_REGISTERED:
1468                     if (packet[2]) break;
1469                     daemon_add_client_rfcomm_service(connection, packet[3]);
1470                     break;
1471                 case L2CAP_EVENT_CHANNEL_OPENED:
1472                     cid = READ_BT_16(packet, 13);
1473                     connection = connection_for_l2cap_cid(cid);
1474                     if (!connection) break;
1475                     if (packet[2]) {
1476                         daemon_remove_client_l2cap_channel(connection, cid);
1477                     } else {
1478                         daemon_add_client_l2cap_channel(connection, cid);
1479                     }
1480                     break;
1481                 case L2CAP_EVENT_CHANNEL_CLOSED:
1482                     cid = READ_BT_16(packet, 2);
1483                     connection = connection_for_l2cap_cid(cid);
1484                     if (!connection) break;
1485                     daemon_remove_client_l2cap_channel(connection, cid);
1486                     break;
1487 #if defined(HAVE_BLE) && defined(HAVE_MALLOC)
1488                 case HCI_EVENT_DISCONNECTION_COMPLETE:
1489                     log_info("daemon : ignore HCI_EVENT_DISCONNECTION_COMPLETE ingnoring.");
1490                     // note: moved to gatt_client_handler because it's received here prematurely
1491                     // daemon_remove_gatt_client_helper(READ_BT_16(packet, 3));
1492                     break;
1493 #endif
1494                 default:
1495                     break;
1496             }
1497         case DAEMON_EVENT_PACKET:
1498             switch (packet[0]){
1499                 case DAEMON_EVENT_NEW_RFCOMM_CREDITS:
1500                     daemon_retry_parked();
1501                     break;
1502                 default:
1503                     break;
1504             }
1505         case L2CAP_DATA_PACKET:
1506             connection = connection_for_l2cap_cid(channel);
1507             if (!connection) return;
1508             break;
1509         case RFCOMM_DATA_PACKET:
1510             connection = connection_for_l2cap_cid(channel);
1511             if (!connection) return;
1512             break;
1513         default:
1514             break;
1515     }
1516 
1517     if (connection) {
1518         socket_connection_send_packet(connection, packet_type, channel, packet, size);
1519     } else {
1520         socket_connection_send_packet_all(packet_type, channel, packet, size);
1521     }
1522 }
1523 
1524 static void l2cap_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){
1525     daemon_packet_handler(NULL, packet_type, channel, packet, size);
1526 }
1527 static void rfcomm_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){
1528     daemon_packet_handler(NULL, packet_type, channel, packet, size);
1529 }
1530 
1531 static void handle_sdp_rfcomm_service_result(sdp_query_event_t * rfcomm_event, void * context){
1532     switch (rfcomm_event->type){
1533         case SDP_QUERY_RFCOMM_SERVICE: {
1534             sdp_query_rfcomm_service_event_t * service_event = (sdp_query_rfcomm_service_event_t*) rfcomm_event;
1535             int name_len = (int)strlen((const char*)service_event->service_name);
1536             int event_len = 3 + name_len;
1537             uint8_t event[event_len];
1538             event[0] = rfcomm_event->type;
1539             event[1] = 1 + name_len;
1540             event[2] = service_event->channel_nr;
1541             memcpy(&event[3], service_event->service_name, name_len);
1542             hci_dump_packet(HCI_EVENT_PACKET, 0, event, event_len);
1543             socket_connection_send_packet(context, HCI_EVENT_PACKET, 0, event, event_len);
1544             break;
1545         }
1546         case SDP_QUERY_COMPLETE: {
1547             sdp_query_complete_event_t * complete_event = (sdp_query_complete_event_t*) rfcomm_event;
1548             uint8_t event[] = { rfcomm_event->type, 1, complete_event->status};
1549             hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
1550             socket_connection_send_packet(context, HCI_EVENT_PACKET, 0, event, sizeof(event));
1551             break;
1552         }
1553     }
1554 }
1555 
1556 static void sdp_client_assert_buffer(int size){
1557     if (size > attribute_value_buffer_size){
1558         log_error("SDP attribute value buffer size exceeded: available %d, required %d", attribute_value_buffer_size, size);
1559     }
1560 }
1561 
1562 // define new packet type SDP_CLIENT_PACKET
1563 static void handle_sdp_client_query_result(sdp_query_event_t * event){
1564     sdp_query_attribute_value_event_t * ve;
1565     sdp_query_complete_event_t * complete_event;
1566 
1567     switch (event->type){
1568         case SDP_QUERY_ATTRIBUTE_VALUE:
1569             ve = (sdp_query_attribute_value_event_t*) event;
1570 
1571             sdp_client_assert_buffer(ve->attribute_length);
1572 
1573             attribute_value[ve->data_offset] = ve->data;
1574 
1575             if ((uint16_t)(ve->data_offset+1) == ve->attribute_length){
1576                 hexdump(attribute_value, ve->attribute_length);
1577 
1578                 int event_len = 1 + 3 * 2 + ve->attribute_length;
1579                 uint8_t event[event_len];
1580                 event[0] = SDP_QUERY_ATTRIBUTE_VALUE;
1581                 bt_store_16(event, 1, (uint16_t)ve->record_id);
1582                 bt_store_16(event, 3, ve->attribute_id);
1583                 bt_store_16(event, 5, (uint16_t)ve->attribute_length);
1584                 memcpy(&event[7], attribute_value, ve->attribute_length);
1585                 hci_dump_packet(SDP_CLIENT_PACKET, 0, event, event_len);
1586                 socket_connection_send_packet(sdp_client_query_connection, SDP_CLIENT_PACKET, 0, event, event_len);
1587             }
1588 
1589             break;
1590         case SDP_QUERY_COMPLETE:
1591             complete_event = (sdp_query_complete_event_t*) event;
1592             uint8_t event[] = { SDP_QUERY_COMPLETE, 1, complete_event->status};
1593             hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
1594             socket_connection_send_packet(sdp_client_query_connection, HCI_EVENT_PACKET, 0, event, sizeof(event));
1595             break;
1596     }
1597 }
1598 
1599 static void power_notification_callback(POWER_NOTIFICATION_t notification){
1600     switch (notification) {
1601         case POWER_WILL_SLEEP:
1602             // let's sleep
1603             power_management_sleep = 1;
1604             hci_power_control(HCI_POWER_SLEEP);
1605             break;
1606         case POWER_WILL_WAKE_UP:
1607             // assume that all clients use Bluetooth -> if connection, start Bluetooth
1608             power_management_sleep = 0;
1609             if (clients_require_power_on()) {
1610                 hci_power_control(HCI_POWER_ON);
1611             }
1612             break;
1613         default:
1614             break;
1615     }
1616 }
1617 
1618 static void daemon_sigint_handler(int param){
1619 
1620 #ifdef USE_BLUETOOL
1621     // notify daemons
1622     notify_post("ch.ringwald.btstack.stopped");
1623 #endif
1624 
1625     log_info(" <= SIGINT received, shutting down..\n");
1626 
1627     hci_power_control( HCI_POWER_OFF);
1628     hci_close();
1629 
1630     log_info("Good bye, see you.\n");
1631 
1632     exit(0);
1633 }
1634 
1635 // MARK: manage power off timer
1636 
1637 #define USE_POWER_OFF_TIMER
1638 
1639 static void stop_power_off_timer(void){
1640 #ifdef USE_POWER_OFF_TIMER
1641     if (timeout_active) {
1642         run_loop_remove_timer(&timeout);
1643         timeout_active = 0;
1644     }
1645 #endif
1646 }
1647 
1648 static void start_power_off_timer(void){
1649 #ifdef USE_POWER_OFF_TIMER
1650     stop_power_off_timer();
1651     run_loop_set_timer(&timeout, DAEMON_NO_ACTIVE_CLIENT_TIMEOUT);
1652     run_loop_add_timer(&timeout);
1653     timeout_active = 1;
1654 #else
1655     hci_power_control(HCI_POWER_OFF);
1656 #endif
1657 }
1658 
1659 // MARK: manage list of clients
1660 
1661 
1662 static client_state_t * client_for_connection(connection_t *connection) {
1663     linked_item_t *it;
1664     for (it = (linked_item_t *) clients; it ; it = it->next){
1665         client_state_t * client_state = (client_state_t *) it;
1666         if (client_state->connection == connection) {
1667             return client_state;
1668         }
1669     }
1670     return NULL;
1671 }
1672 
1673 static void clients_clear_power_request(void){
1674     linked_item_t *it;
1675     for (it = (linked_item_t *) clients; it ; it = it->next){
1676         client_state_t * client_state = (client_state_t *) it;
1677         client_state->power_mode = HCI_POWER_OFF;
1678     }
1679 }
1680 
1681 static int clients_require_power_on(void){
1682 
1683     if (global_enable) return 1;
1684 
1685     linked_item_t *it;
1686     for (it = (linked_item_t *) clients; it ; it = it->next){
1687         client_state_t * client_state = (client_state_t *) it;
1688         if (client_state->power_mode == HCI_POWER_ON) {
1689             return 1;
1690         }
1691     }
1692     return 0;
1693 }
1694 
1695 static int clients_require_discoverable(void){
1696     linked_item_t *it;
1697     for (it = (linked_item_t *) clients; it ; it = it->next){
1698         client_state_t * client_state = (client_state_t *) it;
1699         if (client_state->discoverable) {
1700             return 1;
1701         }
1702     }
1703     return 0;
1704 }
1705 
1706 static void usage(const char * name) {
1707     printf("%s, BTstack background daemon\n", name);
1708     printf("usage: %s [--help] [--tcp port]\n", name);
1709     printf("    --help   display this usage\n");
1710     printf("    --tcp    use TCP server on port %u\n", BTSTACK_PORT);
1711     printf("Without the --tcp option, BTstack daemon is listening on unix domain socket %s\n\n", BTSTACK_UNIX);
1712 }
1713 
1714 #ifdef USE_BLUETOOL
1715 static void * run_loop_thread(void *context){
1716     run_loop_execute();
1717     return NULL;
1718 }
1719 #endif
1720 
1721 #ifdef HAVE_BLE
1722 
1723 static void handle_gatt_client_event(uint8_t packet_type, uint8_t * packet, uint16_t size){
1724 
1725     // hack: handle disconnection_complete_here instead of main hci event packet handler
1726     // we receive a HCI event packet in disguise
1727     if (packet[0] == HCI_EVENT_DISCONNECTION_COMPLETE){
1728         log_info("daemon hack: handle disconnection_complete in handle_gatt_client_event instead of main hci event packet handler");
1729         uint16_t handle = READ_BT_16(packet, 3);
1730         daemon_remove_gatt_client_helper(handle);
1731         return;
1732     }
1733 
1734     // only handle GATT Events
1735     switch(packet[0]){
1736         case GATT_SERVICE_QUERY_RESULT:
1737         case GATT_INCLUDED_SERVICE_QUERY_RESULT:
1738         case GATT_NOTIFICATION:
1739         case GATT_INDICATION:
1740         case GATT_CHARACTERISTIC_QUERY_RESULT:
1741         case GATT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
1742         case GATT_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
1743         case GATT_LONG_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
1744         case GATT_CHARACTERISTIC_VALUE_QUERY_RESULT:
1745         case GATT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT:
1746         case GATT_QUERY_COMPLETE:
1747            break;
1748         default:
1749             return;
1750     }
1751 
1752     uint16_t con_handle = READ_BT_16(packet, 2);
1753     linked_list_gatt_client_helper_t * gatt_client_helper = daemon_get_gatt_client_helper(con_handle);
1754     if (!gatt_client_helper){
1755         log_info("daemon handle_gatt_client_event: gc helper for handle 0x%2x is NULL.", con_handle);
1756         return;
1757     }
1758 
1759     connection_t *connection = NULL;
1760 
1761     // daemon doesn't track which connection subscribed to this particular handle, so we just notify all connections
1762     switch(packet[0]){
1763         case GATT_NOTIFICATION:
1764         case GATT_INDICATION:{
1765             hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size);
1766 
1767             linked_item_t *it;
1768             for (it = (linked_item_t *) clients; it ; it = it->next){
1769                 client_state_t * client_state = (client_state_t *) it;
1770                 socket_connection_send_packet(client_state->connection, HCI_EVENT_PACKET, 0, packet, size);
1771             }
1772             return;
1773         }
1774         default:
1775             break;
1776     }
1777 
1778     // otherwise, we have to have an active connection
1779     connection = gatt_client_helper->active_connection;
1780     uint16_t offset;
1781     uint16_t length;
1782 
1783     if (!connection) return;
1784 
1785     switch(packet[0]){
1786 
1787         case GATT_SERVICE_QUERY_RESULT:
1788         case GATT_INCLUDED_SERVICE_QUERY_RESULT:
1789         case GATT_CHARACTERISTIC_QUERY_RESULT:
1790         case GATT_CHARACTERISTIC_VALUE_QUERY_RESULT:
1791         case GATT_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
1792         case GATT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
1793             hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size);
1794             socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, packet, size);
1795             break;
1796 
1797         case GATT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT:
1798         case GATT_LONG_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
1799             offset = READ_BT_16(packet, 6);
1800             length = READ_BT_16(packet, 8);
1801             gatt_client_helper->characteristic_buffer[0] = packet[0];               // store type (characteristic/descriptor)
1802             gatt_client_helper->characteristic_handle    = READ_BT_16(packet, 4);   // store attribute handle
1803             gatt_client_helper->characteristic_length = offset + length;            // update length
1804             memcpy(&gatt_client_helper->characteristic_buffer[10 + offset], &packet[10], length);
1805             break;
1806 
1807         case GATT_QUERY_COMPLETE:{
1808             gatt_client_helper->active_connection = NULL;
1809             if (gatt_client_helper->characteristic_length){
1810                 // send re-combined long characteristic value or long characteristic descriptor value
1811                 uint8_t * event = gatt_client_helper->characteristic_buffer;
1812                 uint16_t event_size = 10 + gatt_client_helper->characteristic_length;
1813                 // event[0] == already set by previsous case
1814                 event[1] = 8 + gatt_client_helper->characteristic_length;
1815                 bt_store_16(event, 2, READ_BT_16(packet, 2));
1816                 bt_store_16(event, 4, gatt_client_helper->characteristic_handle);
1817                 bt_store_16(event, 6, 0);   // offset
1818                 bt_store_16(event, 8, gatt_client_helper->characteristic_length);
1819                 hci_dump_packet(HCI_EVENT_PACKET, 0, event, event_size);
1820                 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, event_size);
1821                 gatt_client_helper->characteristic_length = 0;
1822             }
1823             hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size);
1824             socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, packet, size);
1825             break;
1826         }
1827         default:
1828             break;
1829     }
1830 }
1831 #endif
1832 
1833 int main (int argc,  char * const * argv){
1834 
1835     static int tcp_flag = 0;
1836 
1837     while (1) {
1838         static struct option long_options[] = {
1839             { "tcp", no_argument, &tcp_flag, 1 },
1840             { "help", no_argument, 0, 0 },
1841             { 0,0,0,0 } // This is a filler for -1
1842         };
1843 
1844         int c;
1845         int option_index = -1;
1846 
1847         c = getopt_long(argc, argv, "h", long_options, &option_index);
1848 
1849         if (c == -1) break; // no more option
1850 
1851         // treat long parameter first
1852         if (option_index == -1) {
1853             switch (c) {
1854                 case '?':
1855                 case 'h':
1856                     usage(argv[0]);
1857                     return 0;
1858                     break;
1859             }
1860         } else {
1861             switch (option_index) {
1862                 case 1:
1863                     usage(argv[0]);
1864                     return 0;
1865                     break;
1866             }
1867         }
1868     }
1869 
1870     if (tcp_flag){
1871         printf("BTstack Daemon started on port %u\n", BTSTACK_PORT);
1872     } else {
1873         printf("BTstack Daemon started on socket %s\n", BTSTACK_UNIX);
1874     }
1875 
1876     // make stdout unbuffered
1877     setbuf(stdout, NULL);
1878 
1879     // handle CTRL-c
1880     signal(SIGINT, daemon_sigint_handler);
1881     // handle SIGTERM - suggested for launchd
1882     signal(SIGTERM, daemon_sigint_handler);
1883 
1884     // TODO: win32 variant
1885 #ifndef _WIN32
1886     // handle SIGPIPE
1887     struct sigaction act;
1888     act.sa_handler = SIG_IGN;
1889     sigemptyset (&act.sa_mask);
1890     act.sa_flags = 0;
1891     sigaction (SIGPIPE, &act, NULL);
1892 #endif
1893 
1894     bt_control_t * control = NULL;
1895 
1896 #ifdef HAVE_TRANSPORT_H4
1897     config.device_name   = UART_DEVICE;
1898     config.baudrate_init = UART_SPEED;
1899     config.baudrate_main = 0;
1900     config.flowcontrol = 1;
1901 #if defined(USE_BLUETOOL) && defined(USE_POWERMANAGEMENT)
1902     if (bt_control_iphone_power_management_supported()){
1903         // use default (max) UART baudrate over netraph interface
1904         config.baudrate_init = 0;
1905         transport = hci_transport_h4_iphone_instance();
1906     } else {
1907         transport = hci_transport_h4_instance();
1908     }
1909 #else
1910     transport = hci_transport_h4_instance();
1911 #endif
1912 #endif
1913 
1914 #ifdef HAVE_TRANSPORT_USB
1915     transport = hci_transport_usb_instance();
1916 #endif
1917 
1918 #ifdef USE_BLUETOOL
1919     control = &bt_control_iphone;
1920 #endif
1921 
1922 #if defined(USE_BLUETOOL) && defined(USE_POWERMANAGEMENT)
1923     if (bt_control_iphone_power_management_supported()){
1924         hci_transport_h4_iphone_set_enforce_wake_device("/dev/btwake");
1925     }
1926 #endif
1927 
1928 #ifdef USE_SPRINGBOARD
1929     bluetooth_status_handler = platform_iphone_status_handler;
1930     platform_iphone_register_window_manager_restart(update_ui_status);
1931     platform_iphone_register_preferences_changed(preferences_changed_callback);
1932 #endif
1933 
1934 #ifdef REMOTE_DEVICE_DB
1935     remote_device_db = &REMOTE_DEVICE_DB;
1936 #endif
1937 
1938     run_loop_init(RUN_LOOP_POSIX);
1939 
1940     // init power management notifications
1941     if (control && control->register_for_power_notifications){
1942         control->register_for_power_notifications(power_notification_callback);
1943     }
1944 
1945     // logging
1946     loggingEnabled = 0;
1947     int newLoggingEnabled = 1;
1948 #ifdef USE_BLUETOOL
1949     // iPhone has toggle in Preferences.app
1950     newLoggingEnabled = platform_iphone_logging_enabled();
1951 #endif
1952     daemon_set_logging_enabled(newLoggingEnabled);
1953 
1954     // dump version
1955     log_info("BTdaemon started\n");
1956     log_info("version %s, build %s", BTSTACK_VERSION, BTSTACK_DATE);
1957 
1958     // init HCI
1959     hci_init(transport, &config, control, remote_device_db);
1960 
1961 #ifdef USE_BLUETOOL
1962     // iPhone doesn't use SSP yet as there's no UI for it yet and auto accept is not an option
1963     hci_ssp_set_enable(0);
1964 #endif
1965     // init L2CAP
1966     l2cap_init();
1967     l2cap_register_packet_handler(&l2cap_packet_handler);
1968     timeout.process = daemon_no_connections_timeout;
1969 
1970 #ifdef HAVE_RFCOMM
1971     log_info("config.h: HAVE_RFCOMM\n");
1972     rfcomm_init();
1973     rfcomm_register_packet_handler(&rfcomm_packet_handler);
1974 #endif
1975 
1976 #ifdef HAVE_SDP
1977     sdp_init();
1978 #endif
1979 
1980 #ifdef HAVE_BLE
1981     // GATT Client
1982     gatt_client_init();
1983     gatt_client_id = gatt_client_register_packet_handler(&handle_gatt_client_event);
1984 
1985     // sm_init();
1986     // sm_set_io_capabilities(IO_CAPABILITY_DISPLAY_ONLY);
1987     // sm_set_authentication_requirements( SM_AUTHREQ_BONDING | SM_AUTHREQ_MITM_PROTECTION);
1988 
1989     // GATT Server - empty attribute database
1990     le_device_db_init();
1991     att_server_init(NULL, NULL, NULL);
1992 
1993 #endif
1994 
1995 #ifdef USE_LAUNCHD
1996     socket_connection_create_launchd();
1997 #else
1998     // create server
1999     if (tcp_flag) {
2000         socket_connection_create_tcp(BTSTACK_PORT);
2001     } else {
2002         socket_connection_create_unix(BTSTACK_UNIX);
2003     }
2004 #endif
2005     socket_connection_register_packet_callback(&daemon_client_handler);
2006 
2007 #ifdef USE_BLUETOOL
2008     // notify daemons
2009     notify_post("ch.ringwald.btstack.started");
2010 
2011     // spawn thread to have BTstack run loop on new thread, while main thread is used to keep CFRunLoop
2012     pthread_t run_loop;
2013     pthread_create(&run_loop, NULL, &run_loop_thread, NULL);
2014 
2015     // needed to receive notifications
2016     CFRunLoopRun();
2017 #endif
2018         // go!
2019     run_loop_execute();
2020     return 0;
2021 }
2022