xref: /btstack/platform/daemon/src/daemon.c (revision 02f83142d437cdf22e03c9e8be9c859cbc17c701)
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             l2cap_emit_service_registered(connection, status, psm);
839             break;
840         case L2CAP_UNREGISTER_SERVICE:
841             psm = READ_BT_16(packet, 3);
842             daemon_remove_client_l2cap_service(connection, psm);
843             l2cap_unregister_service(psm);
844             break;
845         case L2CAP_ACCEPT_CONNECTION:
846             cid    = READ_BT_16(packet, 3);
847             l2cap_accept_connection_internal(cid);
848             break;
849         case L2CAP_DECLINE_CONNECTION:
850             cid    = READ_BT_16(packet, 3);
851             reason = packet[7];
852             l2cap_decline_connection_internal(cid, reason);
853             break;
854         case RFCOMM_CREATE_CHANNEL:
855             bt_flip_addr(addr, &packet[3]);
856             rfcomm_channel = packet[9];
857             status = rfcomm_create_channel(addr, rfcomm_channel, &cid);
858             if (status){
859                 send_rfcomm_create_channel_failed(connection, addr, rfcomm_channel, status);
860             } else {
861                 daemon_add_client_rfcomm_channel(connection, cid);
862             }
863             break;
864         case RFCOMM_CREATE_CHANNEL_WITH_CREDITS:
865             bt_flip_addr(addr, &packet[3]);
866             rfcomm_channel = packet[9];
867             rfcomm_credits = packet[10];
868             status = rfcomm_create_channel_with_initial_credits(addr, rfcomm_channel, rfcomm_credits, &cid );
869             if (status){
870                 send_rfcomm_create_channel_failed(connection, addr, rfcomm_channel, status);
871             } else {
872                 daemon_add_client_rfcomm_channel(connection, cid);
873             }
874             break;
875         case RFCOMM_DISCONNECT:
876             cid = READ_BT_16(packet, 3);
877             reason = packet[5];
878             rfcomm_disconnect_internal(cid);
879             break;
880         case RFCOMM_REGISTER_SERVICE:
881             rfcomm_channel = packet[3];
882             mtu = READ_BT_16(packet, 4);
883             rfcomm_register_service_internal(connection, rfcomm_channel, mtu);
884             break;
885         case RFCOMM_REGISTER_SERVICE_WITH_CREDITS:
886             rfcomm_channel = packet[3];
887             mtu = READ_BT_16(packet, 4);
888             rfcomm_credits = packet[6];
889             rfcomm_register_service_with_initial_credits_internal(connection, rfcomm_channel, mtu, rfcomm_credits);
890             break;
891         case RFCOMM_UNREGISTER_SERVICE:
892             service_channel = READ_BT_16(packet, 3);
893             daemon_remove_client_rfcomm_service(connection, service_channel);
894             rfcomm_unregister_service_internal(service_channel);
895             break;
896         case RFCOMM_ACCEPT_CONNECTION:
897             cid    = READ_BT_16(packet, 3);
898             rfcomm_accept_connection_internal(cid);
899             break;
900         case RFCOMM_DECLINE_CONNECTION:
901             cid    = READ_BT_16(packet, 3);
902             reason = packet[7];
903             rfcomm_decline_connection_internal(cid);
904             break;
905         case RFCOMM_GRANT_CREDITS:
906             cid    = READ_BT_16(packet, 3);
907             rfcomm_credits = packet[5];
908             rfcomm_grant_credits(cid, rfcomm_credits);
909             break;
910         case RFCOMM_PERSISTENT_CHANNEL: {
911             if (remote_device_db) {
912                 // enforce \0
913                 packet[3+248] = 0;
914                 rfcomm_channel = remote_device_db->persistent_rfcomm_channel((char*)&packet[3]);
915             } else {
916                 // NOTE: hack for non-iOS platforms
917                 rfcomm_channel = rfcomm_channel_generator++;
918             }
919             log_info("RFCOMM_EVENT_PERSISTENT_CHANNEL %u", rfcomm_channel);
920             uint8_t event[4];
921             event[0] = RFCOMM_EVENT_PERSISTENT_CHANNEL;
922             event[1] = sizeof(event) - 2;
923             event[2] = 0;
924             event[3] = rfcomm_channel;
925             hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
926             socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, (uint8_t *) event, sizeof(event));
927             break;
928         }
929 
930         case SDP_REGISTER_SERVICE_RECORD:
931             log_info("SDP_REGISTER_SERVICE_RECORD size %u\n", size);
932             service_record_handle = sdp_register_service_internal(connection, &packet[3]);
933             daemon_add_client_sdp_service_record_handle(connection, service_record_handle);
934             break;
935         case SDP_UNREGISTER_SERVICE_RECORD:
936             service_record_handle = READ_BT_32(packet, 3);
937             log_info("SDP_UNREGISTER_SERVICE_RECORD handle 0x%x ", service_record_handle);
938             sdp_unregister_service_internal(connection, service_record_handle);
939             daemon_remove_client_sdp_service_record_handle(connection, service_record_handle);
940             break;
941         case SDP_CLIENT_QUERY_RFCOMM_SERVICES:
942             bt_flip_addr(addr, &packet[3]);
943 
944             serviceSearchPatternLen = de_get_len(&packet[9]);
945             memcpy(serviceSearchPattern, &packet[9], serviceSearchPatternLen);
946 
947             sdp_query_rfcomm_register_callback(handle_sdp_rfcomm_service_result, connection);
948             sdp_query_rfcomm_channel_and_name_for_search_pattern(addr, serviceSearchPattern);
949 
950             break;
951         case SDP_CLIENT_QUERY_SERVICES:
952             bt_flip_addr(addr, &packet[3]);
953             sdp_parser_init();
954             sdp_client_query_connection = connection;
955             sdp_parser_register_callback(handle_sdp_client_query_result);
956 
957             serviceSearchPatternLen = de_get_len(&packet[9]);
958             memcpy(serviceSearchPattern, &packet[9], serviceSearchPatternLen);
959 
960             attributeIDListLen = de_get_len(&packet[9+serviceSearchPatternLen]);
961             memcpy(attributeIDList, &packet[9+serviceSearchPatternLen], attributeIDListLen);
962 
963             sdp_client_query(addr, (uint8_t*)&serviceSearchPattern[0], (uint8_t*)&attributeIDList[0]);
964 
965             // sdp_general_query_for_uuid(addr, SDP_PublicBrowseGroup);
966             break;
967         case GAP_LE_SCAN_START:
968             le_central_start_scan();
969             break;
970         case GAP_LE_SCAN_STOP:
971             le_central_stop_scan();
972             break;
973         case GAP_LE_SET_SCAN_PARAMETERS:
974             le_central_set_scan_parameters(packet[3], READ_BT_16(packet, 4), READ_BT_16(packet, 6));
975             break;
976         case GAP_LE_CONNECT:
977             bt_flip_addr(addr, &packet[4]);
978             addr_type = packet[3];
979             le_central_connect(addr, addr_type);
980             break;
981         case GAP_LE_CONNECT_CANCEL:
982             le_central_connect_cancel();
983             break;
984         case GAP_DISCONNECT:
985             handle = READ_BT_16(packet, 3);
986             gap_disconnect(handle);
987             break;
988 #if defined(HAVE_MALLOC) && defined(HAVE_BLE)
989         case GATT_DISCOVER_ALL_PRIMARY_SERVICES:
990             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
991             if (!gatt_helper) break;
992             gatt_client_discover_primary_services(gatt_client_id, gatt_helper->con_handle);
993             break;
994         case GATT_DISCOVER_PRIMARY_SERVICES_BY_UUID16:
995             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
996             if (!gatt_helper) break;
997             gatt_client_discover_primary_services_by_uuid16(gatt_client_id, gatt_helper->con_handle, READ_BT_16(packet, 5));
998             break;
999         case GATT_DISCOVER_PRIMARY_SERVICES_BY_UUID128:
1000             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1001             if (!gatt_helper) break;
1002             swap128(&packet[5], uuid128);
1003             gatt_client_discover_primary_services_by_uuid128(gatt_client_id, gatt_helper->con_handle, uuid128);
1004             break;
1005         case GATT_FIND_INCLUDED_SERVICES_FOR_SERVICE:
1006             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1007             if (!gatt_helper) break;
1008             daemon_gatt_deserialize_service(packet, 5, &service);
1009             gatt_client_find_included_services_for_service(gatt_client_id, gatt_helper->con_handle, &service);
1010             break;
1011 
1012         case GATT_DISCOVER_CHARACTERISTICS_FOR_SERVICE:
1013             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1014             if (!gatt_helper) break;
1015             daemon_gatt_deserialize_service(packet, 5, &service);
1016             gatt_client_discover_characteristics_for_service(gatt_client_id, gatt_helper->con_handle, &service);
1017             break;
1018         case GATT_DISCOVER_CHARACTERISTICS_FOR_SERVICE_BY_UUID128:
1019             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1020             if (!gatt_helper) break;
1021             daemon_gatt_deserialize_service(packet, 5, &service);
1022             swap128(&packet[5 + SERVICE_LENGTH], uuid128);
1023             gatt_client_discover_characteristics_for_service_by_uuid128(gatt_client_id, gatt_helper->con_handle, &service, uuid128);
1024             break;
1025         case GATT_DISCOVER_CHARACTERISTIC_DESCRIPTORS:
1026             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1027             if (!gatt_helper) break;
1028             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
1029             gatt_client_discover_characteristic_descriptors(gatt_client_id, gatt_helper->con_handle, &characteristic);
1030             break;
1031 
1032         case GATT_READ_VALUE_OF_CHARACTERISTIC:
1033             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1034             if (!gatt_helper) break;
1035             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
1036             gatt_client_read_value_of_characteristic(gatt_client_id, gatt_helper->con_handle, &characteristic);
1037             break;
1038         case GATT_READ_LONG_VALUE_OF_CHARACTERISTIC:
1039             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1040             if (!gatt_helper) break;
1041             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
1042             gatt_client_read_long_value_of_characteristic(gatt_client_id, gatt_helper->con_handle, &characteristic);
1043             break;
1044 
1045         case GATT_WRITE_VALUE_OF_CHARACTERISTIC_WITHOUT_RESPONSE:
1046             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 0);  // note: don't track active connection
1047             if (!gatt_helper) break;
1048             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
1049             data_length = READ_BT_16(packet, 5 + CHARACTERISTIC_LENGTH);
1050             data = gatt_helper->characteristic_buffer;
1051             memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length);
1052             gatt_client_write_value_of_characteristic_without_response(gatt_client_id, gatt_helper->con_handle, characteristic.value_handle, data_length, data);
1053             break;
1054         case GATT_WRITE_VALUE_OF_CHARACTERISTIC:
1055             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1056             if (!gatt_helper) break;
1057             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
1058             data_length = READ_BT_16(packet, 5 + CHARACTERISTIC_LENGTH);
1059             data = gatt_helper->characteristic_buffer;
1060             memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length);
1061             gatt_client_write_value_of_characteristic(gatt_client_id, gatt_helper->con_handle, characteristic.value_handle, data_length, data);
1062             break;
1063         case GATT_WRITE_LONG_VALUE_OF_CHARACTERISTIC:
1064             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1065             if (!gatt_helper) break;
1066             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
1067             data_length = READ_BT_16(packet, 5 + CHARACTERISTIC_LENGTH);
1068             data = gatt_helper->characteristic_buffer;
1069             memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length);
1070             gatt_client_write_long_value_of_characteristic(gatt_client_id, gatt_helper->con_handle, characteristic.value_handle, data_length, data);
1071             break;
1072         case GATT_RELIABLE_WRITE_LONG_VALUE_OF_CHARACTERISTIC:
1073             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1074             if (!gatt_helper) break;
1075             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
1076             data_length = READ_BT_16(packet, 5 + CHARACTERISTIC_LENGTH);
1077             data = gatt_helper->characteristic_buffer;
1078             memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length);
1079             gatt_client_write_long_value_of_characteristic(gatt_client_id, gatt_helper->con_handle, characteristic.value_handle, data_length, data);
1080             break;
1081         case GATT_READ_CHARACTERISTIC_DESCRIPTOR:
1082             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1083             if (!gatt_helper) break;
1084             handle = READ_BT_16(packet, 3);
1085             daemon_gatt_deserialize_characteristic_descriptor(packet, 5, &descriptor);
1086             gatt_client_read_characteristic_descriptor(gatt_client_id, gatt_helper->con_handle, &descriptor);
1087             break;
1088         case GATT_READ_LONG_CHARACTERISTIC_DESCRIPTOR:
1089             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1090             if (!gatt_helper) break;
1091             daemon_gatt_deserialize_characteristic_descriptor(packet, 5, &descriptor);
1092             gatt_client_read_long_characteristic_descriptor(gatt_client_id, gatt_helper->con_handle, &descriptor);
1093             break;
1094 
1095         case GATT_WRITE_CHARACTERISTIC_DESCRIPTOR:
1096             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1097             if (!gatt_helper) break;
1098             daemon_gatt_deserialize_characteristic_descriptor(packet, 5, &descriptor);
1099             data = gatt_helper->characteristic_buffer;
1100             data_length = READ_BT_16(packet, 5 + CHARACTERISTIC_DESCRIPTOR_LENGTH);
1101             gatt_client_write_characteristic_descriptor(gatt_client_id, gatt_helper->con_handle, &descriptor, data_length, data);
1102             break;
1103         case GATT_WRITE_LONG_CHARACTERISTIC_DESCRIPTOR:
1104             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1105             if (!gatt_helper) break;
1106             daemon_gatt_deserialize_characteristic_descriptor(packet, 5, &descriptor);
1107             data = gatt_helper->characteristic_buffer;
1108             data_length = READ_BT_16(packet, 5 + CHARACTERISTIC_DESCRIPTOR_LENGTH);
1109             gatt_client_write_long_characteristic_descriptor(gatt_client_id, gatt_helper->con_handle, &descriptor, data_length, data);
1110             break;
1111         case GATT_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION:{
1112             uint16_t configuration = READ_BT_16(packet, 5 + CHARACTERISTIC_LENGTH);
1113             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1114             if (!gatt_helper) break;
1115             data = gatt_helper->characteristic_buffer;
1116             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
1117             gatt_client_write_client_characteristic_configuration(gatt_client_id, gatt_helper->con_handle, &characteristic, configuration);
1118             break;
1119         case GATT_GET_MTU:
1120             handle = READ_BT_16(packet, 3);
1121             gatt_client_get_mtu(handle, &mtu);
1122             send_gatt_mtu_event(connection, handle, mtu);
1123             break;
1124         }
1125 #endif
1126     default:
1127             log_error("Error: command %u not implemented:", READ_CMD_OCF(packet));
1128             break;
1129     }
1130 
1131     return 0;
1132 }
1133 
1134 static int daemon_client_handler(connection_t *connection, uint16_t packet_type, uint16_t channel, uint8_t *data, uint16_t length){
1135 
1136     int err = 0;
1137     client_state_t * client;
1138 
1139     switch (packet_type){
1140         case HCI_COMMAND_DATA_PACKET:
1141             if (READ_CMD_OGF(data) != OGF_BTSTACK) {
1142                 // HCI Command
1143                 hci_send_cmd_packet(data, length);
1144             } else {
1145                 // BTstack command
1146                 btstack_command_handler(connection, data, length);
1147             }
1148             break;
1149         case L2CAP_DATA_PACKET:
1150             // process l2cap packet...
1151             err = l2cap_send_internal(channel, data, length);
1152             if (err == BTSTACK_ACL_BUFFERS_FULL) {
1153                 l2cap_block_new_credits(1);
1154             }
1155             break;
1156         case RFCOMM_DATA_PACKET:
1157             // process l2cap packet...
1158             err = rfcomm_send_internal(channel, data, length);
1159             break;
1160         case DAEMON_EVENT_PACKET:
1161             switch (data[0]) {
1162                 case DAEMON_EVENT_CONNECTION_OPENED:
1163                     log_info("DAEMON_EVENT_CONNECTION_OPENED %p\n",connection);
1164 
1165                     client = malloc(sizeof(client_state_t));
1166                     if (!client) break; // fail
1167                     memset(client, 0, sizeof(client_state_t));
1168                     client->connection   = connection;
1169                     client->power_mode   = HCI_POWER_OFF;
1170                     client->discoverable = 0;
1171                     linked_list_add(&clients, (linked_item_t *) client);
1172                     break;
1173                 case DAEMON_EVENT_CONNECTION_CLOSED:
1174                     log_info("DAEMON_EVENT_CONNECTION_CLOSED %p\n",connection);
1175                     daemon_disconnect_client(connection);
1176                     sdp_query_rfcomm_deregister_callback();
1177                     // no clients -> no HCI connections
1178                     if (!clients){
1179                         hci_disconnect_all();
1180                     }
1181 
1182                     // update discoverable mode
1183                     hci_discoverable_control(clients_require_discoverable());
1184                     // start power off, if last active client
1185                     if (!clients_require_power_on()){
1186                         start_power_off_timer();
1187                     }
1188                     break;
1189                 case DAEMON_NR_CONNECTIONS_CHANGED:
1190                     log_info("Nr Connections changed, new %u\n",data[1]);
1191                     break;
1192                 default:
1193                     break;
1194             }
1195             break;
1196     }
1197     if (err) {
1198         log_info("Daemon Handler: err %d\n", err);
1199     }
1200     return err;
1201 }
1202 
1203 
1204 static void daemon_set_logging_enabled(int enabled){
1205     if (enabled && !loggingEnabled){
1206         hci_dump_open(BTSTACK_LOG_FILE, BTSTACK_LOG_TYPE);
1207     }
1208     if (!enabled && loggingEnabled){
1209         hci_dump_close();
1210     }
1211     loggingEnabled = enabled;
1212 }
1213 
1214 // local cache used to manage UI status
1215 static HCI_STATE hci_state = HCI_STATE_OFF;
1216 static int num_connections = 0;
1217 static void update_ui_status(void){
1218     if (hci_state != HCI_STATE_WORKING) {
1219         bluetooth_status_handler(BLUETOOTH_OFF);
1220     } else {
1221         if (num_connections) {
1222             bluetooth_status_handler(BLUETOOTH_ACTIVE);
1223         } else {
1224             bluetooth_status_handler(BLUETOOTH_ON);
1225         }
1226     }
1227 }
1228 
1229 #ifdef USE_SPRINGBOARD
1230 static void preferences_changed_callback(void){
1231     int logging = platform_iphone_logging_enabled();
1232     log_info("Logging enabled: %u\n", logging);
1233     daemon_set_logging_enabled(logging);
1234 }
1235 #endif
1236 
1237 static void deamon_status_event_handler(uint8_t *packet, uint16_t size){
1238 
1239     uint8_t update_status = 0;
1240 
1241     // handle state event
1242     switch (packet[0]) {
1243         case BTSTACK_EVENT_STATE:
1244             hci_state = packet[2];
1245             log_info("New state: %u\n", hci_state);
1246             update_status = 1;
1247             break;
1248         case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED:
1249             num_connections = packet[2];
1250             log_info("New nr connections: %u\n", num_connections);
1251             update_status = 1;
1252             break;
1253         default:
1254             break;
1255     }
1256 
1257     // choose full bluetooth state
1258     if (update_status) {
1259         update_ui_status();
1260     }
1261 }
1262 
1263 static void daemon_retry_parked(void){
1264 
1265     // socket_connection_retry_parked is not reentrant
1266     static int retry_mutex = 0;
1267 
1268     // lock mutex
1269     if (retry_mutex) return;
1270     retry_mutex = 1;
1271 
1272     // ... try sending again
1273     socket_connection_retry_parked();
1274 
1275     if (!socket_connection_has_parked_connections()){
1276         l2cap_block_new_credits(0);
1277     }
1278 
1279     // unlock mutex
1280     retry_mutex = 0;
1281 }
1282 
1283 #if 0
1284 
1285 Minimal Code for LE Peripheral
1286 
1287 enum {
1288     SET_ADVERTISEMENT_PARAMS = 1 << 0,
1289     SET_ADVERTISEMENT_DATA   = 1 << 1,
1290     ENABLE_ADVERTISEMENTS    = 1 << 2,
1291 };
1292 
1293 const uint8_t adv_data[] = {
1294     // Flags general discoverable
1295     0x02, 0x01, 0x02,
1296     // Name
1297     0x08, 0x09, 'B', 'T', 's', 't', 'a', 'c', 'k'
1298 };
1299 uint8_t adv_data_len = sizeof(adv_data);
1300 static uint16_t todos = 0;
1301 
1302 static void app_run(void){
1303 
1304     if (!hci_can_send_command_packet_now()) return;
1305 
1306     if (todos & SET_ADVERTISEMENT_DATA){
1307         log_info("app_run: set advertisement data\n");
1308         todos &= ~SET_ADVERTISEMENT_DATA;
1309         hci_send_cmd(&hci_le_set_advertising_data, adv_data_len, adv_data);
1310         return;
1311     }
1312 
1313     if (todos & SET_ADVERTISEMENT_PARAMS){
1314         todos &= ~SET_ADVERTISEMENT_PARAMS;
1315         uint8_t adv_type = 0;   // default
1316         bd_addr_t null_addr;
1317         memset(null_addr, 0, 6);
1318         uint16_t adv_int_min = 0x0030;
1319         uint16_t adv_int_max = 0x0030;
1320         hci_send_cmd(&hci_le_set_advertising_parameters, adv_int_min, adv_int_max, adv_type, 0, 0, &null_addr, 0x07, 0x00);
1321         return;
1322     }
1323 
1324     if (todos & ENABLE_ADVERTISEMENTS){
1325         log_info("app_run: enable advertisements\n");
1326         todos &= ~ENABLE_ADVERTISEMENTS;
1327         hci_send_cmd(&hci_le_set_advertise_enable, 1);
1328         return;
1329     }
1330 }
1331 #endif
1332 
1333 static void daemon_packet_handler(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1334 
1335     switch (packet_type) {
1336         case HCI_EVENT_PACKET:
1337             deamon_status_event_handler(packet, size);
1338             switch (packet[0]){
1339 
1340                 case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
1341                     // ACL buffer freed...
1342                     daemon_retry_parked();
1343                     // no need to tell clients
1344                     return;
1345                 case RFCOMM_EVENT_CREDITS:
1346                     // RFCOMM CREDITS received...
1347                     daemon_retry_parked();
1348                     break;
1349                  case RFCOMM_EVENT_OPEN_CHANNEL_COMPLETE:
1350                     if (packet[2]) {
1351                         daemon_remove_client_rfcomm_channel(connection, READ_BT_16(packet, 13));
1352                     } else {
1353                         daemon_add_client_rfcomm_channel(connection, READ_BT_16(packet, 13));
1354                     }
1355                     break;
1356                 case RFCOMM_EVENT_CHANNEL_CLOSED:
1357                     daemon_remove_client_rfcomm_channel(connection, READ_BT_16(packet, 2));
1358                     break;
1359                 case RFCOMM_EVENT_SERVICE_REGISTERED:
1360                     if (packet[2]) break;
1361                     daemon_add_client_rfcomm_service(connection, packet[3]);
1362                     break;
1363                 case L2CAP_EVENT_CHANNEL_OPENED:
1364                     if (packet[2]) {
1365                         daemon_remove_client_l2cap_channel(connection, READ_BT_16(packet, 13));
1366                     } else {
1367                         daemon_add_client_l2cap_channel(connection, READ_BT_16(packet, 13));
1368                     }
1369                     break;
1370                 case L2CAP_EVENT_CHANNEL_CLOSED:
1371                     daemon_remove_client_l2cap_channel(connection, READ_BT_16(packet, 2));
1372                     break;
1373                 case L2CAP_EVENT_SERVICE_REGISTERED:
1374                     if (packet[2]) break;
1375                     daemon_add_client_l2cap_service(connection, READ_BT_16(packet, 3));
1376                     break;
1377 #if defined(HAVE_BLE) && defined(HAVE_MALLOC)
1378                 case HCI_EVENT_DISCONNECTION_COMPLETE:
1379                     log_info("daemon : ignore HCI_EVENT_DISCONNECTION_COMPLETE ingnoring.");
1380                     // note: moved to gatt_client_handler because it's received here prematurely
1381                     // daemon_remove_gatt_client_helper(READ_BT_16(packet, 3));
1382                     break;
1383 #endif
1384                 default:
1385                     break;
1386             }
1387         case DAEMON_EVENT_PACKET:
1388             switch (packet[0]){
1389                 case DAEMON_EVENT_NEW_RFCOMM_CREDITS:
1390                     daemon_retry_parked();
1391                     break;
1392                 default:
1393                     break;
1394             }
1395         default:
1396             break;
1397     }
1398     if (connection) {
1399         socket_connection_send_packet(connection, packet_type, channel, packet, size);
1400     } else {
1401         socket_connection_send_packet_all(packet_type, channel, packet, size);
1402     }
1403 }
1404 
1405 static void handle_sdp_rfcomm_service_result(sdp_query_event_t * rfcomm_event, void * context){
1406     switch (rfcomm_event->type){
1407         case SDP_QUERY_RFCOMM_SERVICE: {
1408             sdp_query_rfcomm_service_event_t * service_event = (sdp_query_rfcomm_service_event_t*) rfcomm_event;
1409             int name_len = (int)strlen((const char*)service_event->service_name);
1410             int event_len = 3 + name_len;
1411             uint8_t event[event_len];
1412             event[0] = rfcomm_event->type;
1413             event[1] = 1 + name_len;
1414             event[2] = service_event->channel_nr;
1415             memcpy(&event[3], service_event->service_name, name_len);
1416             hci_dump_packet(HCI_EVENT_PACKET, 0, event, event_len);
1417             socket_connection_send_packet(context, HCI_EVENT_PACKET, 0, event, event_len);
1418             break;
1419         }
1420         case SDP_QUERY_COMPLETE: {
1421             sdp_query_complete_event_t * complete_event = (sdp_query_complete_event_t*) rfcomm_event;
1422             uint8_t event[] = { rfcomm_event->type, 1, complete_event->status};
1423             hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
1424             socket_connection_send_packet(context, HCI_EVENT_PACKET, 0, event, sizeof(event));
1425             break;
1426         }
1427     }
1428 }
1429 
1430 static void sdp_client_assert_buffer(int size){
1431     if (size > attribute_value_buffer_size){
1432         log_error("SDP attribute value buffer size exceeded: available %d, required %d", attribute_value_buffer_size, size);
1433     }
1434 }
1435 
1436 // define new packet type SDP_CLIENT_PACKET
1437 static void handle_sdp_client_query_result(sdp_query_event_t * event){
1438     sdp_query_attribute_value_event_t * ve;
1439     sdp_query_complete_event_t * complete_event;
1440 
1441     switch (event->type){
1442         case SDP_QUERY_ATTRIBUTE_VALUE:
1443             ve = (sdp_query_attribute_value_event_t*) event;
1444 
1445             sdp_client_assert_buffer(ve->attribute_length);
1446 
1447             attribute_value[ve->data_offset] = ve->data;
1448 
1449             if ((uint16_t)(ve->data_offset+1) == ve->attribute_length){
1450                 hexdump(attribute_value, ve->attribute_length);
1451 
1452                 int event_len = 1 + 3 * 2 + ve->attribute_length;
1453                 uint8_t event[event_len];
1454                 event[0] = SDP_QUERY_ATTRIBUTE_VALUE;
1455                 bt_store_16(event, 1, (uint16_t)ve->record_id);
1456                 bt_store_16(event, 3, ve->attribute_id);
1457                 bt_store_16(event, 5, (uint16_t)ve->attribute_length);
1458                 memcpy(&event[7], attribute_value, ve->attribute_length);
1459                 hci_dump_packet(SDP_CLIENT_PACKET, 0, event, event_len);
1460                 socket_connection_send_packet(sdp_client_query_connection, SDP_CLIENT_PACKET, 0, event, event_len);
1461             }
1462 
1463             break;
1464         case SDP_QUERY_COMPLETE:
1465             complete_event = (sdp_query_complete_event_t*) event;
1466             uint8_t event[] = { SDP_QUERY_COMPLETE, 1, complete_event->status};
1467             hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
1468             socket_connection_send_packet(sdp_client_query_connection, HCI_EVENT_PACKET, 0, event, sizeof(event));
1469             break;
1470     }
1471 }
1472 
1473 static void power_notification_callback(POWER_NOTIFICATION_t notification){
1474     switch (notification) {
1475         case POWER_WILL_SLEEP:
1476             // let's sleep
1477             power_management_sleep = 1;
1478             hci_power_control(HCI_POWER_SLEEP);
1479             break;
1480         case POWER_WILL_WAKE_UP:
1481             // assume that all clients use Bluetooth -> if connection, start Bluetooth
1482             power_management_sleep = 0;
1483             if (clients_require_power_on()) {
1484                 hci_power_control(HCI_POWER_ON);
1485             }
1486             break;
1487         default:
1488             break;
1489     }
1490 }
1491 
1492 static void daemon_sigint_handler(int param){
1493 
1494 #ifdef USE_BLUETOOL
1495     // notify daemons
1496     notify_post("ch.ringwald.btstack.stopped");
1497 #endif
1498 
1499     log_info(" <= SIGINT received, shutting down..\n");
1500 
1501     hci_power_control( HCI_POWER_OFF);
1502     hci_close();
1503 
1504     log_info("Good bye, see you.\n");
1505 
1506     exit(0);
1507 }
1508 
1509 // MARK: manage power off timer
1510 
1511 #define USE_POWER_OFF_TIMER
1512 
1513 static void stop_power_off_timer(void){
1514 #ifdef USE_POWER_OFF_TIMER
1515     if (timeout_active) {
1516         run_loop_remove_timer(&timeout);
1517         timeout_active = 0;
1518     }
1519 #endif
1520 }
1521 
1522 static void start_power_off_timer(void){
1523 #ifdef USE_POWER_OFF_TIMER
1524     stop_power_off_timer();
1525     run_loop_set_timer(&timeout, DAEMON_NO_ACTIVE_CLIENT_TIMEOUT);
1526     run_loop_add_timer(&timeout);
1527     timeout_active = 1;
1528 #else
1529     hci_power_control(HCI_POWER_OFF);
1530 #endif
1531 }
1532 
1533 // MARK: manage list of clients
1534 
1535 
1536 static client_state_t * client_for_connection(connection_t *connection) {
1537     linked_item_t *it;
1538     for (it = (linked_item_t *) clients; it ; it = it->next){
1539         client_state_t * client_state = (client_state_t *) it;
1540         if (client_state->connection == connection) {
1541             return client_state;
1542         }
1543     }
1544     return NULL;
1545 }
1546 
1547 static void clients_clear_power_request(void){
1548     linked_item_t *it;
1549     for (it = (linked_item_t *) clients; it ; it = it->next){
1550         client_state_t * client_state = (client_state_t *) it;
1551         client_state->power_mode = HCI_POWER_OFF;
1552     }
1553 }
1554 
1555 static int clients_require_power_on(void){
1556 
1557     if (global_enable) return 1;
1558 
1559     linked_item_t *it;
1560     for (it = (linked_item_t *) clients; it ; it = it->next){
1561         client_state_t * client_state = (client_state_t *) it;
1562         if (client_state->power_mode == HCI_POWER_ON) {
1563             return 1;
1564         }
1565     }
1566     return 0;
1567 }
1568 
1569 static int clients_require_discoverable(void){
1570     linked_item_t *it;
1571     for (it = (linked_item_t *) clients; it ; it = it->next){
1572         client_state_t * client_state = (client_state_t *) it;
1573         if (client_state->discoverable) {
1574             return 1;
1575         }
1576     }
1577     return 0;
1578 }
1579 
1580 static void usage(const char * name) {
1581     printf("%s, BTstack background daemon\n", name);
1582     printf("usage: %s [--help] [--tcp port]\n", name);
1583     printf("    --help   display this usage\n");
1584     printf("    --tcp    use TCP server on port %u\n", BTSTACK_PORT);
1585     printf("Without the --tcp option, BTstack daemon is listening on unix domain socket %s\n\n", BTSTACK_UNIX);
1586 }
1587 
1588 #ifdef USE_BLUETOOL
1589 static void * run_loop_thread(void *context){
1590     run_loop_execute();
1591     return NULL;
1592 }
1593 #endif
1594 
1595 #ifdef HAVE_BLE
1596 
1597 static void handle_gatt_client_event(uint8_t packet_type, uint8_t * packet, uint16_t size){
1598 
1599     // hack: handle disconnection_complete_here instead of main hci event packet handler
1600     // we receive a HCI event packet in disguise
1601     if (packet[0] == HCI_EVENT_DISCONNECTION_COMPLETE){
1602         log_info("daemon hack: handle disconnection_complete in handle_gatt_client_event instead of main hci event packet handler");
1603         uint16_t handle = READ_BT_16(packet, 3);
1604         daemon_remove_gatt_client_helper(handle);
1605         return;
1606     }
1607 
1608     // only handle GATT Events
1609     switch(packet[0]){
1610         case GATT_SERVICE_QUERY_RESULT:
1611         case GATT_INCLUDED_SERVICE_QUERY_RESULT:
1612         case GATT_NOTIFICATION:
1613         case GATT_INDICATION:
1614         case GATT_CHARACTERISTIC_QUERY_RESULT:
1615         case GATT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
1616         case GATT_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
1617         case GATT_LONG_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
1618         case GATT_CHARACTERISTIC_VALUE_QUERY_RESULT:
1619         case GATT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT:
1620         case GATT_QUERY_COMPLETE:
1621            break;
1622         default:
1623             return;
1624     }
1625 
1626     uint16_t con_handle = READ_BT_16(packet, 2);
1627     linked_list_gatt_client_helper_t * gatt_client_helper = daemon_get_gatt_client_helper(con_handle);
1628     if (!gatt_client_helper){
1629         log_info("daemon handle_gatt_client_event: gc helper for handle 0x%2x is NULL.", con_handle);
1630         return;
1631     }
1632 
1633     connection_t *connection = NULL;
1634 
1635     // daemon doesn't track which connection subscribed to this particular handle, so we just notify all connections
1636     switch(packet[0]){
1637         case GATT_NOTIFICATION:
1638         case GATT_INDICATION:{
1639             hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size);
1640 
1641             linked_item_t *it;
1642             for (it = (linked_item_t *) clients; it ; it = it->next){
1643                 client_state_t * client_state = (client_state_t *) it;
1644                 socket_connection_send_packet(client_state->connection, HCI_EVENT_PACKET, 0, packet, size);
1645             }
1646             return;
1647         }
1648         default:
1649             break;
1650     }
1651 
1652     // otherwise, we have to have an active connection
1653     connection = gatt_client_helper->active_connection;
1654     uint16_t offset;
1655     uint16_t length;
1656 
1657     if (!connection) return;
1658 
1659     switch(packet[0]){
1660 
1661         case GATT_SERVICE_QUERY_RESULT:
1662         case GATT_INCLUDED_SERVICE_QUERY_RESULT:
1663         case GATT_CHARACTERISTIC_QUERY_RESULT:
1664         case GATT_CHARACTERISTIC_VALUE_QUERY_RESULT:
1665         case GATT_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
1666         case GATT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
1667             hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size);
1668             socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, packet, size);
1669             break;
1670 
1671         case GATT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT:
1672         case GATT_LONG_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
1673             offset = READ_BT_16(packet, 6);
1674             length = READ_BT_16(packet, 8);
1675             gatt_client_helper->characteristic_buffer[0] = packet[0];               // store type (characteristic/descriptor)
1676             gatt_client_helper->characteristic_handle    = READ_BT_16(packet, 4);   // store attribute handle
1677             gatt_client_helper->characteristic_length = offset + length;            // update length
1678             memcpy(&gatt_client_helper->characteristic_buffer[10 + offset], &packet[10], length);
1679             break;
1680 
1681         case GATT_QUERY_COMPLETE:{
1682             gatt_client_helper->active_connection = NULL;
1683             if (gatt_client_helper->characteristic_length){
1684                 // send re-combined long characteristic value or long characteristic descriptor value
1685                 uint8_t * event = gatt_client_helper->characteristic_buffer;
1686                 uint16_t event_size = 10 + gatt_client_helper->characteristic_length;
1687                 // event[0] == already set by previsous case
1688                 event[1] = 8 + gatt_client_helper->characteristic_length;
1689                 bt_store_16(event, 2, READ_BT_16(packet, 2));
1690                 bt_store_16(event, 4, gatt_client_helper->characteristic_handle);
1691                 bt_store_16(event, 6, 0);   // offset
1692                 bt_store_16(event, 8, gatt_client_helper->characteristic_length);
1693                 hci_dump_packet(HCI_EVENT_PACKET, 0, event, event_size);
1694                 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, event_size);
1695                 gatt_client_helper->characteristic_length = 0;
1696             }
1697             hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size);
1698             socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, packet, size);
1699             break;
1700         }
1701         default:
1702             break;
1703     }
1704 }
1705 #endif
1706 
1707 int main (int argc,  char * const * argv){
1708 
1709     static int tcp_flag = 0;
1710 
1711     while (1) {
1712         static struct option long_options[] = {
1713             { "tcp", no_argument, &tcp_flag, 1 },
1714             { "help", no_argument, 0, 0 },
1715             { 0,0,0,0 } // This is a filler for -1
1716         };
1717 
1718         int c;
1719         int option_index = -1;
1720 
1721         c = getopt_long(argc, argv, "h", long_options, &option_index);
1722 
1723         if (c == -1) break; // no more option
1724 
1725         // treat long parameter first
1726         if (option_index == -1) {
1727             switch (c) {
1728                 case '?':
1729                 case 'h':
1730                     usage(argv[0]);
1731                     return 0;
1732                     break;
1733             }
1734         } else {
1735             switch (option_index) {
1736                 case 1:
1737                     usage(argv[0]);
1738                     return 0;
1739                     break;
1740             }
1741         }
1742     }
1743 
1744     if (tcp_flag){
1745         printf("BTstack Daemon started on port %u\n", BTSTACK_PORT);
1746     } else {
1747         printf("BTstack Daemon started on socket %s\n", BTSTACK_UNIX);
1748     }
1749 
1750     // make stdout unbuffered
1751     setbuf(stdout, NULL);
1752 
1753     // handle CTRL-c
1754     signal(SIGINT, daemon_sigint_handler);
1755     // handle SIGTERM - suggested for launchd
1756     signal(SIGTERM, daemon_sigint_handler);
1757 
1758     // TODO: win32 variant
1759 #ifndef _WIN32
1760     // handle SIGPIPE
1761     struct sigaction act;
1762     act.sa_handler = SIG_IGN;
1763     sigemptyset (&act.sa_mask);
1764     act.sa_flags = 0;
1765     sigaction (SIGPIPE, &act, NULL);
1766 #endif
1767 
1768     bt_control_t * control = NULL;
1769 
1770 #ifdef HAVE_TRANSPORT_H4
1771     config.device_name   = UART_DEVICE;
1772     config.baudrate_init = UART_SPEED;
1773     config.baudrate_main = 0;
1774     config.flowcontrol = 1;
1775 #if defined(USE_BLUETOOL) && defined(USE_POWERMANAGEMENT)
1776     if (bt_control_iphone_power_management_supported()){
1777         // use default (max) UART baudrate over netraph interface
1778         config.baudrate_init = 0;
1779         transport = hci_transport_h4_iphone_instance();
1780     } else {
1781         transport = hci_transport_h4_instance();
1782     }
1783 #else
1784     transport = hci_transport_h4_instance();
1785 #endif
1786 #endif
1787 
1788 #ifdef HAVE_TRANSPORT_USB
1789     transport = hci_transport_usb_instance();
1790 #endif
1791 
1792 #ifdef USE_BLUETOOL
1793     control = &bt_control_iphone;
1794 #endif
1795 
1796 #if defined(USE_BLUETOOL) && defined(USE_POWERMANAGEMENT)
1797     if (bt_control_iphone_power_management_supported()){
1798         hci_transport_h4_iphone_set_enforce_wake_device("/dev/btwake");
1799     }
1800 #endif
1801 
1802 #ifdef USE_SPRINGBOARD
1803     bluetooth_status_handler = platform_iphone_status_handler;
1804     platform_iphone_register_window_manager_restart(update_ui_status);
1805     platform_iphone_register_preferences_changed(preferences_changed_callback);
1806 #endif
1807 
1808 #ifdef REMOTE_DEVICE_DB
1809     remote_device_db = &REMOTE_DEVICE_DB;
1810 #endif
1811 
1812     run_loop_init(RUN_LOOP_POSIX);
1813 
1814     // init power management notifications
1815     if (control && control->register_for_power_notifications){
1816         control->register_for_power_notifications(power_notification_callback);
1817     }
1818 
1819     // logging
1820     loggingEnabled = 0;
1821     int newLoggingEnabled = 1;
1822 #ifdef USE_BLUETOOL
1823     // iPhone has toggle in Preferences.app
1824     newLoggingEnabled = platform_iphone_logging_enabled();
1825 #endif
1826     daemon_set_logging_enabled(newLoggingEnabled);
1827 
1828     // dump version
1829     log_info("BTdaemon started\n");
1830     log_info("version %s, build %s", BTSTACK_VERSION, BTSTACK_DATE);
1831 
1832     // init HCI
1833     hci_init(transport, &config, control, remote_device_db);
1834 
1835 #ifdef USE_BLUETOOL
1836     // iPhone doesn't use SSP yet as there's no UI for it yet and auto accept is not an option
1837     hci_ssp_set_enable(0);
1838 #endif
1839     // init L2CAP
1840     l2cap_init();
1841     l2cap_register_packet_handler(&daemon_packet_handler);
1842     timeout.process = daemon_no_connections_timeout;
1843 
1844 #ifdef HAVE_RFCOMM
1845     log_info("config.h: HAVE_RFCOMM\n");
1846     rfcomm_init();
1847     rfcomm_register_packet_handler(&daemon_packet_handler);
1848 #endif
1849 
1850 #ifdef HAVE_SDP
1851     sdp_init();
1852     sdp_register_packet_handler(&daemon_packet_handler);
1853 #endif
1854 
1855 #ifdef HAVE_BLE
1856     // GATT Client
1857     gatt_client_init();
1858     gatt_client_id = gatt_client_register_packet_handler(&handle_gatt_client_event);
1859 
1860     // sm_init();
1861     // sm_set_io_capabilities(IO_CAPABILITY_DISPLAY_ONLY);
1862     // sm_set_authentication_requirements( SM_AUTHREQ_BONDING | SM_AUTHREQ_MITM_PROTECTION);
1863 
1864     // GATT Server - empty attribute database
1865     le_device_db_init();
1866     att_server_init(NULL, NULL, NULL);
1867 
1868 #endif
1869 
1870 #ifdef USE_LAUNCHD
1871     socket_connection_create_launchd();
1872 #else
1873     // create server
1874     if (tcp_flag) {
1875         socket_connection_create_tcp(BTSTACK_PORT);
1876     } else {
1877         socket_connection_create_unix(BTSTACK_UNIX);
1878     }
1879 #endif
1880     socket_connection_register_packet_callback(&daemon_client_handler);
1881 
1882 #ifdef USE_BLUETOOL
1883     // notify daemons
1884     notify_post("ch.ringwald.btstack.started");
1885 
1886     // spawn thread to have BTstack run loop on new thread, while main thread is used to keep CFRunLoop
1887     pthread_t run_loop;
1888     pthread_create(&run_loop, NULL, &run_loop_thread, NULL);
1889 
1890     // needed to receive notifications
1891     CFRunLoopRun();
1892 #endif
1893         // go!
1894     run_loop_execute();
1895     return 0;
1896 }
1897