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