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