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