xref: /btstack/platform/daemon/src/daemon.c (revision 457b5cb16b95dcfdb3b5786e4195d8b5b211dd71)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 /*
39  *  daemon.c
40  *
41  *  Created by Matthias Ringwald on 7/1/09.
42  *
43  *  BTstack background daemon
44  *
45  */
46 
47 #include "btstack-config.h"
48 
49 #include <pthread.h>
50 #include <signal.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <strings.h>
54 #include <unistd.h>
55 
56 #include <getopt.h>
57 
58 #include "btstack.h"
59 #include "linked_list.h"
60 #include "run_loop.h"
61 #include "hci_cmds.h"
62 #include "version.h"
63 
64 #include "debug.h"
65 #include "hci.h"
66 #include "hci_dump.h"
67 #include "hci_transport.h"
68 #include "l2cap.h"
69 #include "classic/rfcomm.h"
70 #include "classic/sdp.h"
71 #include "classic/sdp_parser.h"
72 #include "classic/sdp_client.h"
73 #include "classic/sdp_query_util.h"
74 #include "classic/sdp_query_rfcomm.h"
75 #include "socket_connection.h"
76 
77 #ifdef HAVE_BLE
78 #include "ble/gatt_client.h"
79 #include "ble/att_server.h"
80 #include "ble/att.h"
81 #include "ble/le_device_db.h"
82 #include "ble/sm.h"
83 #endif
84 
85 #ifdef USE_BLUETOOL
86 #include <CoreFoundation/CoreFoundation.h>
87 #include "../port/ios/src/bt_control_iphone.h"
88 #include <notify.h>
89 #endif
90 
91 #ifdef USE_SPRINGBOARD
92 #include "../port/ios/src/platform_iphone.h"
93 #endif
94 
95 #ifndef BTSTACK_LOG_FILE
96 #define BTSTACK_LOG_FILE "/tmp/hci_dump.pklg"
97 #endif
98 
99 // use logger: format HCI_DUMP_PACKETLOGGER, HCI_DUMP_BLUEZ or HCI_DUMP_STDOUT
100 #ifndef BTSTACK_LOG_TYPE
101 #define BTSTACK_LOG_TYPE HCI_DUMP_PACKETLOGGER
102 #endif
103 
104 #define DAEMON_NO_ACTIVE_CLIENT_TIMEOUT 10000
105 
106 #define ATT_MAX_LONG_ATTRIBUTE_SIZE 512
107 
108 
109 #define SERVICE_LENGTH                      20
110 #define CHARACTERISTIC_LENGTH               24
111 #define CHARACTERISTIC_DESCRIPTOR_LENGTH    18
112 
113 // ATT_MTU - 1
114 #define ATT_MAX_ATTRIBUTE_SIZE 22
115 
116 typedef struct {
117     // linked list - assert: first field
118     linked_item_t    item;
119 
120     // connection
121     connection_t * connection;
122 
123     linked_list_t rfcomm_cids;
124     linked_list_t rfcomm_services;
125     linked_list_t l2cap_cids;
126     linked_list_t l2cap_psms;
127     linked_list_t sdp_record_handles;
128     linked_list_t gatt_con_handles;
129     // power mode
130     HCI_POWER_MODE power_mode;
131 
132     // discoverable
133     uint8_t        discoverable;
134 
135 } client_state_t;
136 
137 typedef struct linked_list_uint32 {
138     linked_item_t   item;
139     uint32_t        value;
140 } linked_list_uint32_t;
141 
142 typedef struct linked_list_connection {
143     linked_item_t   item;
144     connection_t  * connection;
145 } linked_list_connection_t;
146 
147 typedef struct linked_list_gatt_client_helper{
148     linked_item_t item;
149     uint16_t con_handle;
150     connection_t * active_connection;   // the one that started the current query
151     linked_list_t  all_connections;     // list of all connections that ever used this helper
152     uint16_t characteristic_length;
153     uint16_t characteristic_handle;
154     uint8_t  characteristic_buffer[10 + ATT_MAX_LONG_ATTRIBUTE_SIZE];   // header for sending event right away
155     uint8_t  long_query_type;
156 } linked_list_gatt_client_helper_t;
157 
158 // MARK: prototypes
159 static void handle_sdp_rfcomm_service_result(sdp_query_event_t * event, void * context);
160 static void handle_sdp_client_query_result(sdp_query_event_t * event);
161 static void dummy_bluetooth_status_handler(BLUETOOTH_STATE state);
162 static client_state_t * client_for_connection(connection_t *connection);
163 static int              clients_require_power_on(void);
164 static int              clients_require_discoverable(void);
165 static void              clients_clear_power_request(void);
166 static void start_power_off_timer(void);
167 static void stop_power_off_timer(void);
168 static client_state_t * client_for_connection(connection_t *connection);
169 
170 
171 // MARK: globals
172 static hci_transport_t * transport;
173 static hci_uart_config_t config;
174 static timer_source_t timeout;
175 static uint8_t timeout_active = 0;
176 static int power_management_sleep = 0;
177 static linked_list_t clients = NULL;        // list of connected clients `
178 #ifdef HAVE_BLE
179 static linked_list_t gatt_client_helpers = NULL;   // list of used gatt client (helpers)
180 static uint16_t gatt_client_id = 0;
181 #endif
182 
183 static void (*bluetooth_status_handler)(BLUETOOTH_STATE state) = dummy_bluetooth_status_handler;
184 
185 static int global_enable = 0;
186 
187 static remote_device_db_t const * remote_device_db = NULL;
188 static int rfcomm_channel_generator = 1;
189 
190 static uint8_t   attribute_value[1000];
191 static const int attribute_value_buffer_size = sizeof(attribute_value);
192 static uint8_t serviceSearchPattern[200];
193 static uint8_t attributeIDList[50];
194 static void * sdp_client_query_connection;
195 
196 static int loggingEnabled;
197 
198 static void dummy_bluetooth_status_handler(BLUETOOTH_STATE state){
199     log_info("Bluetooth status: %u\n", state);
200 };
201 
202 static void daemon_no_connections_timeout(struct timer *ts){
203     if (clients_require_power_on()) return;    // false alarm :)
204     log_info("No active client connection for %u seconds -> POWER OFF\n", DAEMON_NO_ACTIVE_CLIENT_TIMEOUT/1000);
205     hci_power_control(HCI_POWER_OFF);
206 }
207 
208 
209 static void add_uint32_to_list(linked_list_t *list, uint32_t value){
210     linked_list_iterator_t it;
211     linked_list_iterator_init(&it, list);
212     while (linked_list_iterator_has_next(&it)){
213         linked_list_uint32_t * item = (linked_list_uint32_t*) linked_list_iterator_next(&it);
214         if ( item->value == value) return; // already in list
215     }
216 
217     linked_list_uint32_t * item = malloc(sizeof(linked_list_uint32_t));
218     if (!item) return;
219     item->value = value;
220     linked_list_add(list, (linked_item_t *) item);
221 }
222 
223 static void remove_and_free_uint32_from_list(linked_list_t *list, uint32_t value){
224     linked_list_iterator_t it;
225     linked_list_iterator_init(&it, list);
226     while (linked_list_iterator_has_next(&it)){
227         linked_list_uint32_t * item = (linked_list_uint32_t*) linked_list_iterator_next(&it);
228         if ( item->value != value) continue;
229         linked_list_remove(list, (linked_item_t *) item);
230         free(item);
231     }
232 }
233 
234 static void daemon_add_client_rfcomm_service(connection_t * connection, uint16_t service_channel){
235     client_state_t * client_state = client_for_connection(connection);
236     if (!client_state) return;
237     add_uint32_to_list(&client_state->rfcomm_services, service_channel);
238 }
239 
240 static void daemon_remove_client_rfcomm_service(connection_t * connection, uint16_t service_channel){
241     client_state_t * client_state = client_for_connection(connection);
242     if (!client_state) return;
243     remove_and_free_uint32_from_list(&client_state->rfcomm_services, service_channel);
244 }
245 
246 static void daemon_add_client_rfcomm_channel(connection_t * connection, uint16_t cid){
247     client_state_t * client_state = client_for_connection(connection);
248     if (!client_state) return;
249     add_uint32_to_list(&client_state->rfcomm_cids, cid);
250 }
251 
252 static void daemon_remove_client_rfcomm_channel(connection_t * connection, uint16_t cid){
253     client_state_t * client_state = client_for_connection(connection);
254     if (!client_state) return;
255     remove_and_free_uint32_from_list(&client_state->rfcomm_cids, cid);
256 }
257 
258 static void daemon_add_client_l2cap_service(connection_t * connection, uint16_t psm){
259     client_state_t * client_state = client_for_connection(connection);
260     if (!client_state) return;
261     add_uint32_to_list(&client_state->l2cap_psms, psm);
262 }
263 
264 static void daemon_remove_client_l2cap_service(connection_t * connection, uint16_t psm){
265     client_state_t * client_state = client_for_connection(connection);
266     if (!client_state) return;
267     remove_and_free_uint32_from_list(&client_state->l2cap_psms, psm);
268 }
269 
270 static void daemon_add_client_l2cap_channel(connection_t * connection, uint16_t cid){
271     client_state_t * client_state = client_for_connection(connection);
272     if (!client_state) return;
273     add_uint32_to_list(&client_state->l2cap_cids, cid);
274 }
275 
276 static void daemon_remove_client_l2cap_channel(connection_t * connection, uint16_t cid){
277     client_state_t * client_state = client_for_connection(connection);
278     if (!client_state) return;
279     remove_and_free_uint32_from_list(&client_state->l2cap_cids, cid);
280 }
281 
282 static void daemon_add_client_sdp_service_record_handle(connection_t * connection, uint32_t handle){
283     client_state_t * client_state = client_for_connection(connection);
284     if (!client_state) return;
285     add_uint32_to_list(&client_state->sdp_record_handles, handle);
286 }
287 
288 static void daemon_remove_client_sdp_service_record_handle(connection_t * connection, uint32_t handle){
289     client_state_t * client_state = client_for_connection(connection);
290     if (!client_state) return;
291     remove_and_free_uint32_from_list(&client_state->sdp_record_handles, handle);
292 }
293 
294 #ifdef HAVE_BLE
295 static void daemon_add_gatt_client_handle(connection_t * connection, uint32_t handle){
296     client_state_t * client_state = client_for_connection(connection);
297     if (!client_state) return;
298 
299     // check if handle already exists in the gatt_con_handles list
300     linked_list_iterator_t it;
301     int handle_found = 0;
302     linked_list_iterator_init(&it, &client_state->gatt_con_handles);
303     while (linked_list_iterator_has_next(&it)){
304         linked_list_uint32_t * item = (linked_list_uint32_t*) linked_list_iterator_next(&it);
305         if (item->value == handle){
306             handle_found = 1;
307             break;
308         }
309     }
310     // if handle doesn't exist add it to gatt_con_handles
311     if (!handle_found){
312         add_uint32_to_list(&client_state->gatt_con_handles, handle);
313     }
314 
315     // check if there is a helper with given handle
316     linked_list_gatt_client_helper_t * gatt_helper = NULL;
317     linked_list_iterator_init(&it, &gatt_client_helpers);
318     while (linked_list_iterator_has_next(&it)){
319         linked_list_gatt_client_helper_t * item = (linked_list_gatt_client_helper_t*) linked_list_iterator_next(&it);
320         if (item->con_handle == handle){
321             gatt_helper = item;
322             break;
323         }
324     }
325 
326     // if gatt_helper doesn't exist, create it and add it to gatt_client_helpers list
327     if (!gatt_helper){
328         gatt_helper = malloc(sizeof(linked_list_gatt_client_helper_t));
329         if (!gatt_helper) return;
330         memset(gatt_helper, 0, sizeof(linked_list_gatt_client_helper_t));
331         gatt_helper->con_handle = handle;
332         linked_list_add(&gatt_client_helpers, (linked_item_t *) gatt_helper);
333     }
334 
335     // check if connection exists
336     int connection_found = 0;
337     linked_list_iterator_init(&it, &gatt_helper->all_connections);
338     while (linked_list_iterator_has_next(&it)){
339         linked_list_connection_t * item = (linked_list_connection_t*) linked_list_iterator_next(&it);
340         if (item->connection == connection){
341             connection_found = 1;
342             break;
343         }
344     }
345 
346     // if connection is not found, add it to the all_connections, and set it as active connection
347     if (!connection_found){
348         linked_list_connection_t * con = malloc(sizeof(linked_list_connection_t));
349         if (!con) return;
350         memset(con, 0, sizeof(linked_list_connection_t));
351         con->connection = connection;
352         linked_list_add(&gatt_helper->all_connections, (linked_item_t *)con);
353     }
354 }
355 
356 
357 static void daemon_remove_gatt_client_handle(connection_t * connection, uint32_t handle){
358     // PART 1 - uses connection & handle
359     // might be extracted or vanish totally
360     client_state_t * client_state = client_for_connection(connection);
361     if (!client_state) return;
362 
363     linked_list_iterator_t it;
364     // remove handle from gatt_con_handles list
365     linked_list_iterator_init(&it, &client_state->gatt_con_handles);
366     while (linked_list_iterator_has_next(&it)){
367         linked_list_uint32_t * item = (linked_list_uint32_t*) linked_list_iterator_next(&it);
368         if (item->value == handle){
369             linked_list_remove(&client_state->gatt_con_handles, (linked_item_t *) item);
370             free(item);
371         }
372     }
373 
374     // PART 2 - only uses handle
375 
376     // find helper with given handle
377     linked_list_gatt_client_helper_t * helper = NULL;
378     linked_list_iterator_init(&it, &gatt_client_helpers);
379     while (linked_list_iterator_has_next(&it)){
380         linked_list_gatt_client_helper_t * item = (linked_list_gatt_client_helper_t*) linked_list_iterator_next(&it);
381         if (item->con_handle == handle){
382             helper = item;
383             break;
384         }
385     }
386 
387     if (!helper) return;
388     // remove connection from helper
389     linked_list_iterator_init(&it, &helper->all_connections);
390     while (linked_list_iterator_has_next(&it)){
391         linked_list_connection_t * item = (linked_list_connection_t*) linked_list_iterator_next(&it);
392         if (item->connection == connection){
393             linked_list_remove(&helper->all_connections, (linked_item_t *) item);
394             free(item);
395             break;
396         }
397     }
398 
399     if (helper->active_connection == connection){
400         helper->active_connection = NULL;
401     }
402     // if helper has no more connections, call disconnect
403     if (helper->all_connections == NULL){
404         gap_disconnect((hci_con_handle_t) helper->con_handle);
405     }
406 }
407 
408 
409 static void daemon_remove_gatt_client_helper(uint32_t con_handle){
410     linked_list_iterator_t it, cl;
411     // find helper with given handle
412     linked_list_gatt_client_helper_t * helper = NULL;
413     linked_list_iterator_init(&it, &gatt_client_helpers);
414     while (linked_list_iterator_has_next(&it)){
415         linked_list_gatt_client_helper_t * item = (linked_list_gatt_client_helper_t*) linked_list_iterator_next(&it);
416         if (item->con_handle == con_handle){
417             helper = item;
418             break;
419         }
420     }
421 
422     if (!helper) return;
423 
424     // remove all connection from helper
425     linked_list_iterator_init(&it, &helper->all_connections);
426     while (linked_list_iterator_has_next(&it)){
427         linked_list_connection_t * item = (linked_list_connection_t*) linked_list_iterator_next(&it);
428         linked_list_remove(&helper->all_connections, (linked_item_t *) item);
429         free(item);
430     }
431 
432     linked_list_remove(&gatt_client_helpers, (linked_item_t *) helper);
433     free(helper);
434 
435     linked_list_iterator_init(&cl, &clients);
436     while (linked_list_iterator_has_next(&cl)){
437         client_state_t * client_state = (client_state_t *) linked_list_iterator_next(&cl);
438         linked_list_iterator_init(&it, &client_state->gatt_con_handles);
439         while (linked_list_iterator_has_next(&it)){
440             linked_list_uint32_t * item = (linked_list_uint32_t*) linked_list_iterator_next(&it);
441             if (item->value == con_handle){
442                 linked_list_remove(&client_state->gatt_con_handles, (linked_item_t *) item);
443                 free(item);
444             }
445         }
446     }
447 }
448 #endif
449 
450 static void daemon_rfcomm_close_connection(client_state_t * daemon_client){
451     linked_list_iterator_t it;
452     linked_list_t *rfcomm_services = &daemon_client->rfcomm_services;
453     linked_list_t *rfcomm_cids = &daemon_client->rfcomm_cids;
454 
455     linked_list_iterator_init(&it, rfcomm_services);
456     while (linked_list_iterator_has_next(&it)){
457         linked_list_uint32_t * item = (linked_list_uint32_t*) linked_list_iterator_next(&it);
458         rfcomm_unregister_service(item->value);
459         linked_list_remove(rfcomm_services, (linked_item_t *) item);
460         free(item);
461     }
462 
463     linked_list_iterator_init(&it, rfcomm_cids);
464     while (linked_list_iterator_has_next(&it)){
465         linked_list_uint32_t * item = (linked_list_uint32_t*) linked_list_iterator_next(&it);
466         rfcomm_disconnect_internal(item->value);
467         linked_list_remove(rfcomm_cids, (linked_item_t *) item);
468         free(item);
469     }
470 }
471 
472 
473 static void daemon_l2cap_close_connection(client_state_t * daemon_client){
474     linked_list_iterator_t it;
475     linked_list_t *l2cap_psms = &daemon_client->l2cap_psms;
476     linked_list_t *l2cap_cids = &daemon_client->l2cap_cids;
477 
478     linked_list_iterator_init(&it, l2cap_psms);
479     while (linked_list_iterator_has_next(&it)){
480         linked_list_uint32_t * item = (linked_list_uint32_t*) linked_list_iterator_next(&it);
481         l2cap_unregister_service(item->value);
482         linked_list_remove(l2cap_psms, (linked_item_t *) item);
483         free(item);
484     }
485 
486     linked_list_iterator_init(&it, l2cap_cids);
487     while (linked_list_iterator_has_next(&it)){
488         linked_list_uint32_t * item = (linked_list_uint32_t*) linked_list_iterator_next(&it);
489         l2cap_disconnect_internal(item->value, 0); // note: reason isn't used
490         linked_list_remove(l2cap_cids, (linked_item_t *) item);
491         free(item);
492     }
493 }
494 
495 static void daemon_sdp_close_connection(client_state_t * daemon_client){
496     linked_list_t * list = &daemon_client->sdp_record_handles;
497     linked_list_iterator_t it;
498     linked_list_iterator_init(&it, list);
499     while (linked_list_iterator_has_next(&it)){
500         linked_list_uint32_t * item = (linked_list_uint32_t*) linked_list_iterator_next(&it);
501         sdp_unregister_service_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 static 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 rfcomm_emit_service_registered(void *connection, uint8_t status, uint8_t channel){
651     log_info("RFCOMM_EVENT_SERVICE_REGISTERED status 0x%x channel #%u", status, channel);
652     uint8_t event[4];
653     event[0] = RFCOMM_EVENT_SERVICE_REGISTERED;
654     event[1] = sizeof(event) - 2;
655     event[2] = status;
656     event[3] = channel;
657     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
658     socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event));
659 }
660 
661 static void send_rfcomm_create_channel_failed(void * connection, bd_addr_t addr, uint8_t server_channel, uint8_t status){
662     // emit error - see rfcom.c:rfcomm_emit_channel_open_failed_outgoing_memory(..)
663     uint8_t event[16];
664     memset(event, 0, sizeof(event));
665     uint8_t pos = 0;
666     event[pos++] = RFCOMM_EVENT_OPEN_CHANNEL_COMPLETE;
667     event[pos++] = sizeof(event) - 2;
668     event[pos++] = status;
669     bt_flip_addr(&event[pos], addr); pos += 6;
670     bt_store_16(event,  pos, 0);   pos += 2;
671     event[pos++] = server_channel;
672     bt_store_16(event, pos, 0); pos += 2;   // channel ID
673     bt_store_16(event, pos, 0); pos += 2;   // max frame size
674     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
675     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
676     socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, sizeof(event));
677 }
678 
679 
680 linked_list_gatt_client_helper_t * daemon_setup_gatt_client_request(connection_t *connection, uint8_t *packet, int track_active_connection) {
681     hci_con_handle_t handle = READ_BT_16(packet, 3);
682     log_info("daemon_setup_gatt_client_request for handle 0x%02x", handle);
683     hci_connection_t * hci_con = hci_connection_for_handle(handle);
684     if ((hci_con == NULL) || (hci_con->state != OPEN)){
685         send_gatt_query_complete(connection, handle, GATT_CLIENT_NOT_CONNECTED);
686         return NULL;
687     }
688 
689     linked_list_gatt_client_helper_t * helper = daemon_get_gatt_client_helper(handle);
690 
691     if (!helper){
692         log_info("helper does not exist");
693         helper = malloc(sizeof(linked_list_gatt_client_helper_t));
694         if (!helper) return NULL;
695         memset(helper, 0, sizeof(linked_list_gatt_client_helper_t));
696         helper->con_handle = handle;
697         linked_list_add(&gatt_client_helpers, (linked_item_t *) helper);
698     }
699 
700     if (track_active_connection && helper->active_connection){
701         send_gatt_query_complete(connection, handle, GATT_CLIENT_BUSY);
702         return NULL;
703     }
704 
705     daemon_add_gatt_client_handle(connection, handle);
706 
707     if (track_active_connection){
708         // remember connection responsible for this request
709         helper->active_connection = connection;
710     }
711 
712     return helper;
713 }
714 
715 // (de)serialize structs from/to HCI commands/events
716 
717 void daemon_gatt_deserialize_service(uint8_t *packet, int offset, le_service_t *service){
718     service->start_group_handle = READ_BT_16(packet, offset);
719     service->end_group_handle = READ_BT_16(packet, offset + 2);
720     swap128(&packet[offset + 4], service->uuid128);
721 }
722 
723 void daemon_gatt_serialize_service(le_service_t * service, uint8_t * event, int offset){
724     bt_store_16(event, offset, service->start_group_handle);
725     bt_store_16(event, offset+2, service->end_group_handle);
726     swap128(service->uuid128, &event[offset + 4]);
727 }
728 
729 void daemon_gatt_deserialize_characteristic(uint8_t * packet, int offset, le_characteristic_t * characteristic){
730     characteristic->start_handle = READ_BT_16(packet, offset);
731     characteristic->value_handle = READ_BT_16(packet, offset + 2);
732     characteristic->end_handle = READ_BT_16(packet, offset + 4);
733     characteristic->properties = READ_BT_16(packet, offset + 6);
734     characteristic->uuid16 = READ_BT_16(packet, offset + 8);
735     swap128(&packet[offset+10], characteristic->uuid128);
736 }
737 
738 void daemon_gatt_serialize_characteristic(le_characteristic_t * characteristic, uint8_t * event, int offset){
739     bt_store_16(event, offset, characteristic->start_handle);
740     bt_store_16(event, offset+2, characteristic->value_handle);
741     bt_store_16(event, offset+4, characteristic->end_handle);
742     bt_store_16(event, offset+6, characteristic->properties);
743     swap128(characteristic->uuid128, &event[offset+8]);
744 }
745 
746 void daemon_gatt_deserialize_characteristic_descriptor(uint8_t * packet, int offset, le_characteristic_descriptor_t * descriptor){
747     descriptor->handle = READ_BT_16(packet, offset);
748     swap128(&packet[offset+2], descriptor->uuid128);
749 }
750 
751 void daemon_gatt_serialize_characteristic_descriptor(le_characteristic_descriptor_t * characteristic_descriptor, uint8_t * event, int offset){
752     bt_store_16(event, offset, characteristic_descriptor->handle);
753     swap128(characteristic_descriptor->uuid128, &event[offset+2]);
754 }
755 
756 #endif
757 
758 static int btstack_command_handler(connection_t *connection, uint8_t *packet, uint16_t size){
759 
760     bd_addr_t addr;
761     bd_addr_type_t addr_type;
762     hci_con_handle_t handle;
763     uint16_t cid;
764     uint16_t psm;
765     uint16_t service_channel;
766     uint16_t mtu;
767     uint8_t  reason;
768     uint8_t  rfcomm_channel;
769     uint8_t  rfcomm_credits;
770     uint32_t service_record_handle;
771     client_state_t *client;
772     uint8_t status;
773 
774 #if defined(HAVE_MALLOC) && defined(HAVE_BLE)
775     uint8_t uuid128[16];
776     le_service_t service;
777     le_characteristic_t characteristic;
778     le_characteristic_descriptor_t descriptor;
779     uint16_t data_length;
780     uint8_t  * data;
781     linked_list_gatt_client_helper_t * gatt_helper;
782 #endif
783 
784     uint16_t serviceSearchPatternLen;
785     uint16_t attributeIDListLen;
786 
787     // verbose log info before other info to allow for better tracking
788     hci_dump_packet( HCI_COMMAND_DATA_PACKET, 1, packet, size);
789 
790     // BTstack internal commands - 16 Bit OpCode, 8 Bit ParamLen, Params...
791     switch (READ_CMD_OCF(packet)){
792         case BTSTACK_GET_STATE:
793             log_info("BTSTACK_GET_STATE");
794             hci_emit_state();
795             break;
796         case BTSTACK_SET_POWER_MODE:
797             log_info("BTSTACK_SET_POWER_MODE %u", packet[3]);
798             // track client power requests
799             client = client_for_connection(connection);
800             if (!client) break;
801             client->power_mode = packet[3];
802             // handle merged state
803             if (!clients_require_power_on()){
804                 start_power_off_timer();
805             } else if (!power_management_sleep) {
806                 stop_power_off_timer();
807                 hci_power_control(HCI_POWER_ON);
808             }
809             break;
810         case BTSTACK_GET_VERSION:
811             log_info("BTSTACK_GET_VERSION");
812             hci_emit_btstack_version();
813             break;
814 #ifdef USE_BLUETOOL
815         case BTSTACK_SET_SYSTEM_BLUETOOTH_ENABLED:
816             log_info("BTSTACK_SET_SYSTEM_BLUETOOTH_ENABLED %u", packet[3]);
817             iphone_system_bt_set_enabled(packet[3]);
818             hci_emit_system_bluetooth_enabled(iphone_system_bt_enabled());
819             break;
820 
821         case BTSTACK_GET_SYSTEM_BLUETOOTH_ENABLED:
822             log_info("BTSTACK_GET_SYSTEM_BLUETOOTH_ENABLED");
823             hci_emit_system_bluetooth_enabled(iphone_system_bt_enabled());
824             break;
825 #else
826         case BTSTACK_SET_SYSTEM_BLUETOOTH_ENABLED:
827         case BTSTACK_GET_SYSTEM_BLUETOOTH_ENABLED:
828             hci_emit_system_bluetooth_enabled(0);
829             break;
830 #endif
831         case BTSTACK_SET_DISCOVERABLE:
832             log_info("BTSTACK_SET_DISCOVERABLE discoverable %u)", packet[3]);
833             // track client discoverable requests
834             client = client_for_connection(connection);
835             if (!client) break;
836             client->discoverable = packet[3];
837             // merge state
838             hci_discoverable_control(clients_require_discoverable());
839             break;
840         case BTSTACK_SET_BLUETOOTH_ENABLED:
841             log_info("BTSTACK_SET_BLUETOOTH_ENABLED: %u\n", packet[3]);
842             if (packet[3]) {
843                 // global enable
844                 global_enable = 1;
845                 hci_power_control(HCI_POWER_ON);
846             } else {
847                 global_enable = 0;
848                 clients_clear_power_request();
849                 hci_power_control(HCI_POWER_OFF);
850             }
851             break;
852         case L2CAP_CREATE_CHANNEL_MTU:
853             bt_flip_addr(addr, &packet[3]);
854             psm = READ_BT_16(packet, 9);
855             mtu = READ_BT_16(packet, 11);
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_CREATE_CHANNEL:
864             bt_flip_addr(addr, &packet[3]);
865             psm = READ_BT_16(packet, 9);
866             mtu = 150; // until r865
867             status = l2cap_create_channel(NULL, addr, psm, mtu, &cid);
868             if (status){
869                 send_l2cap_connection_open_failed(connection, addr, psm, status);
870             } else {
871                 daemon_add_client_l2cap_channel(connection, cid);
872             }
873             break;
874         case L2CAP_DISCONNECT:
875             cid = READ_BT_16(packet, 3);
876             reason = packet[5];
877             l2cap_disconnect_internal(cid, reason);
878             break;
879         case L2CAP_REGISTER_SERVICE:
880             psm = READ_BT_16(packet, 3);
881             mtu = READ_BT_16(packet, 5);
882             status = l2cap_register_service(NULL, psm, mtu, LEVEL_0);
883             daemon_add_client_l2cap_service(connection, READ_BT_16(packet, 3));
884             l2cap_emit_service_registered(connection, status, psm);
885             break;
886         case L2CAP_UNREGISTER_SERVICE:
887             psm = READ_BT_16(packet, 3);
888             daemon_remove_client_l2cap_service(connection, psm);
889             l2cap_unregister_service(psm);
890             break;
891         case L2CAP_ACCEPT_CONNECTION:
892             cid    = READ_BT_16(packet, 3);
893             l2cap_accept_connection_internal(cid);
894             break;
895         case L2CAP_DECLINE_CONNECTION:
896             cid    = READ_BT_16(packet, 3);
897             reason = packet[7];
898             l2cap_decline_connection_internal(cid, reason);
899             break;
900         case RFCOMM_CREATE_CHANNEL:
901             bt_flip_addr(addr, &packet[3]);
902             rfcomm_channel = packet[9];
903             status = rfcomm_create_channel(addr, rfcomm_channel, &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_CREATE_CHANNEL_WITH_CREDITS:
911             bt_flip_addr(addr, &packet[3]);
912             rfcomm_channel = packet[9];
913             rfcomm_credits = packet[10];
914             status = rfcomm_create_channel_with_initial_credits(addr, rfcomm_channel, rfcomm_credits, &cid );
915             if (status){
916                 send_rfcomm_create_channel_failed(connection, addr, rfcomm_channel, status);
917             } else {
918                 daemon_add_client_rfcomm_channel(connection, cid);
919             }
920             break;
921         case RFCOMM_DISCONNECT:
922             cid = READ_BT_16(packet, 3);
923             reason = packet[5];
924             rfcomm_disconnect_internal(cid);
925             break;
926         case RFCOMM_REGISTER_SERVICE:
927             rfcomm_channel = packet[3];
928             mtu = READ_BT_16(packet, 4);
929             status = rfcomm_register_service(rfcomm_channel, mtu);
930             rfcomm_emit_service_registered(connection, status, rfcomm_channel);
931             break;
932         case RFCOMM_REGISTER_SERVICE_WITH_CREDITS:
933             rfcomm_channel = packet[3];
934             mtu = READ_BT_16(packet, 4);
935             rfcomm_credits = packet[6];
936             status = rfcomm_register_service_with_initial_credits(rfcomm_channel, mtu, rfcomm_credits);
937             rfcomm_emit_service_registered(connection, status, rfcomm_channel);
938             break;
939         case RFCOMM_UNREGISTER_SERVICE:
940             service_channel = READ_BT_16(packet, 3);
941             daemon_remove_client_rfcomm_service(connection, service_channel);
942             rfcomm_unregister_service(service_channel);
943             break;
944         case RFCOMM_ACCEPT_CONNECTION:
945             cid    = READ_BT_16(packet, 3);
946             rfcomm_accept_connection_internal(cid);
947             break;
948         case RFCOMM_DECLINE_CONNECTION:
949             cid    = READ_BT_16(packet, 3);
950             reason = packet[7];
951             rfcomm_decline_connection_internal(cid);
952             break;
953         case RFCOMM_GRANT_CREDITS:
954             cid    = READ_BT_16(packet, 3);
955             rfcomm_credits = packet[5];
956             rfcomm_grant_credits(cid, rfcomm_credits);
957             break;
958         case RFCOMM_PERSISTENT_CHANNEL: {
959             if (remote_device_db) {
960                 // enforce \0
961                 packet[3+248] = 0;
962                 rfcomm_channel = remote_device_db->persistent_rfcomm_channel((char*)&packet[3]);
963             } else {
964                 // NOTE: hack for non-iOS platforms
965                 rfcomm_channel = rfcomm_channel_generator++;
966             }
967             log_info("RFCOMM_EVENT_PERSISTENT_CHANNEL %u", rfcomm_channel);
968             uint8_t event[4];
969             event[0] = RFCOMM_EVENT_PERSISTENT_CHANNEL;
970             event[1] = sizeof(event) - 2;
971             event[2] = 0;
972             event[3] = rfcomm_channel;
973             hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
974             socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, (uint8_t *) event, sizeof(event));
975             break;
976         }
977 
978         case SDP_REGISTER_SERVICE_RECORD:
979             log_info("SDP_REGISTER_SERVICE_RECORD size %u\n", size);
980             service_record_handle = sdp_register_service_internal(connection, &packet[3]);
981             daemon_add_client_sdp_service_record_handle(connection, service_record_handle);
982             break;
983         case SDP_UNREGISTER_SERVICE_RECORD:
984             service_record_handle = READ_BT_32(packet, 3);
985             log_info("SDP_UNREGISTER_SERVICE_RECORD handle 0x%x ", service_record_handle);
986             sdp_unregister_service_internal(connection, service_record_handle);
987             daemon_remove_client_sdp_service_record_handle(connection, service_record_handle);
988             break;
989         case SDP_CLIENT_QUERY_RFCOMM_SERVICES:
990             bt_flip_addr(addr, &packet[3]);
991 
992             serviceSearchPatternLen = de_get_len(&packet[9]);
993             memcpy(serviceSearchPattern, &packet[9], serviceSearchPatternLen);
994 
995             sdp_query_rfcomm_register_callback(handle_sdp_rfcomm_service_result, connection);
996             sdp_query_rfcomm_channel_and_name_for_search_pattern(addr, serviceSearchPattern);
997 
998             break;
999         case SDP_CLIENT_QUERY_SERVICES:
1000             bt_flip_addr(addr, &packet[3]);
1001             sdp_parser_init();
1002             sdp_client_query_connection = connection;
1003             sdp_parser_register_callback(handle_sdp_client_query_result);
1004 
1005             serviceSearchPatternLen = de_get_len(&packet[9]);
1006             memcpy(serviceSearchPattern, &packet[9], serviceSearchPatternLen);
1007 
1008             attributeIDListLen = de_get_len(&packet[9+serviceSearchPatternLen]);
1009             memcpy(attributeIDList, &packet[9+serviceSearchPatternLen], attributeIDListLen);
1010 
1011             sdp_client_query(addr, (uint8_t*)&serviceSearchPattern[0], (uint8_t*)&attributeIDList[0]);
1012 
1013             // sdp_general_query_for_uuid(addr, SDP_PublicBrowseGroup);
1014             break;
1015         case GAP_LE_SCAN_START:
1016             le_central_start_scan();
1017             break;
1018         case GAP_LE_SCAN_STOP:
1019             le_central_stop_scan();
1020             break;
1021         case GAP_LE_SET_SCAN_PARAMETERS:
1022             le_central_set_scan_parameters(packet[3], READ_BT_16(packet, 4), READ_BT_16(packet, 6));
1023             break;
1024         case GAP_LE_CONNECT:
1025             bt_flip_addr(addr, &packet[4]);
1026             addr_type = packet[3];
1027             le_central_connect(addr, addr_type);
1028             break;
1029         case GAP_LE_CONNECT_CANCEL:
1030             le_central_connect_cancel();
1031             break;
1032         case GAP_DISCONNECT:
1033             handle = READ_BT_16(packet, 3);
1034             gap_disconnect(handle);
1035             break;
1036 #if defined(HAVE_MALLOC) && defined(HAVE_BLE)
1037         case GATT_DISCOVER_ALL_PRIMARY_SERVICES:
1038             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1039             if (!gatt_helper) break;
1040             gatt_client_discover_primary_services(gatt_client_id, gatt_helper->con_handle);
1041             break;
1042         case GATT_DISCOVER_PRIMARY_SERVICES_BY_UUID16:
1043             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1044             if (!gatt_helper) break;
1045             gatt_client_discover_primary_services_by_uuid16(gatt_client_id, gatt_helper->con_handle, READ_BT_16(packet, 5));
1046             break;
1047         case GATT_DISCOVER_PRIMARY_SERVICES_BY_UUID128:
1048             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1049             if (!gatt_helper) break;
1050             swap128(&packet[5], uuid128);
1051             gatt_client_discover_primary_services_by_uuid128(gatt_client_id, gatt_helper->con_handle, uuid128);
1052             break;
1053         case GATT_FIND_INCLUDED_SERVICES_FOR_SERVICE:
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             gatt_client_find_included_services_for_service(gatt_client_id, gatt_helper->con_handle, &service);
1058             break;
1059 
1060         case GATT_DISCOVER_CHARACTERISTICS_FOR_SERVICE:
1061             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1062             if (!gatt_helper) break;
1063             daemon_gatt_deserialize_service(packet, 5, &service);
1064             gatt_client_discover_characteristics_for_service(gatt_client_id, gatt_helper->con_handle, &service);
1065             break;
1066         case GATT_DISCOVER_CHARACTERISTICS_FOR_SERVICE_BY_UUID128:
1067             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1068             if (!gatt_helper) break;
1069             daemon_gatt_deserialize_service(packet, 5, &service);
1070             swap128(&packet[5 + SERVICE_LENGTH], uuid128);
1071             gatt_client_discover_characteristics_for_service_by_uuid128(gatt_client_id, gatt_helper->con_handle, &service, uuid128);
1072             break;
1073         case GATT_DISCOVER_CHARACTERISTIC_DESCRIPTORS:
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_discover_characteristic_descriptors(gatt_client_id, gatt_helper->con_handle, &characteristic);
1078             break;
1079 
1080         case GATT_READ_VALUE_OF_CHARACTERISTIC:
1081             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1082             if (!gatt_helper) break;
1083             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
1084             gatt_client_read_value_of_characteristic(gatt_client_id, gatt_helper->con_handle, &characteristic);
1085             break;
1086         case GATT_READ_LONG_VALUE_OF_CHARACTERISTIC:
1087             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1088             if (!gatt_helper) break;
1089             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
1090             gatt_client_read_long_value_of_characteristic(gatt_client_id, gatt_helper->con_handle, &characteristic);
1091             break;
1092 
1093         case GATT_WRITE_VALUE_OF_CHARACTERISTIC_WITHOUT_RESPONSE:
1094             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 0);  // note: don't track active connection
1095             if (!gatt_helper) break;
1096             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
1097             data_length = READ_BT_16(packet, 5 + CHARACTERISTIC_LENGTH);
1098             data = gatt_helper->characteristic_buffer;
1099             memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length);
1100             gatt_client_write_value_of_characteristic_without_response(gatt_client_id, gatt_helper->con_handle, characteristic.value_handle, data_length, data);
1101             break;
1102         case GATT_WRITE_VALUE_OF_CHARACTERISTIC:
1103             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1104             if (!gatt_helper) break;
1105             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
1106             data_length = READ_BT_16(packet, 5 + CHARACTERISTIC_LENGTH);
1107             data = gatt_helper->characteristic_buffer;
1108             memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length);
1109             gatt_client_write_value_of_characteristic(gatt_client_id, gatt_helper->con_handle, characteristic.value_handle, data_length, data);
1110             break;
1111         case GATT_WRITE_LONG_VALUE_OF_CHARACTERISTIC:
1112             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1113             if (!gatt_helper) break;
1114             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
1115             data_length = READ_BT_16(packet, 5 + CHARACTERISTIC_LENGTH);
1116             data = gatt_helper->characteristic_buffer;
1117             memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length);
1118             gatt_client_write_long_value_of_characteristic(gatt_client_id, gatt_helper->con_handle, characteristic.value_handle, data_length, data);
1119             break;
1120         case GATT_RELIABLE_WRITE_LONG_VALUE_OF_CHARACTERISTIC:
1121             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1122             if (!gatt_helper) break;
1123             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
1124             data_length = READ_BT_16(packet, 5 + CHARACTERISTIC_LENGTH);
1125             data = gatt_helper->characteristic_buffer;
1126             memcpy(data, &packet[7 + CHARACTERISTIC_LENGTH], data_length);
1127             gatt_client_write_long_value_of_characteristic(gatt_client_id, gatt_helper->con_handle, characteristic.value_handle, data_length, data);
1128             break;
1129         case GATT_READ_CHARACTERISTIC_DESCRIPTOR:
1130             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1131             if (!gatt_helper) break;
1132             handle = READ_BT_16(packet, 3);
1133             daemon_gatt_deserialize_characteristic_descriptor(packet, 5, &descriptor);
1134             gatt_client_read_characteristic_descriptor(gatt_client_id, gatt_helper->con_handle, &descriptor);
1135             break;
1136         case GATT_READ_LONG_CHARACTERISTIC_DESCRIPTOR:
1137             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1138             if (!gatt_helper) break;
1139             daemon_gatt_deserialize_characteristic_descriptor(packet, 5, &descriptor);
1140             gatt_client_read_long_characteristic_descriptor(gatt_client_id, gatt_helper->con_handle, &descriptor);
1141             break;
1142 
1143         case GATT_WRITE_CHARACTERISTIC_DESCRIPTOR:
1144             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1145             if (!gatt_helper) break;
1146             daemon_gatt_deserialize_characteristic_descriptor(packet, 5, &descriptor);
1147             data = gatt_helper->characteristic_buffer;
1148             data_length = READ_BT_16(packet, 5 + CHARACTERISTIC_DESCRIPTOR_LENGTH);
1149             gatt_client_write_characteristic_descriptor(gatt_client_id, gatt_helper->con_handle, &descriptor, data_length, data);
1150             break;
1151         case GATT_WRITE_LONG_CHARACTERISTIC_DESCRIPTOR:
1152             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1153             if (!gatt_helper) break;
1154             daemon_gatt_deserialize_characteristic_descriptor(packet, 5, &descriptor);
1155             data = gatt_helper->characteristic_buffer;
1156             data_length = READ_BT_16(packet, 5 + CHARACTERISTIC_DESCRIPTOR_LENGTH);
1157             gatt_client_write_long_characteristic_descriptor(gatt_client_id, gatt_helper->con_handle, &descriptor, data_length, data);
1158             break;
1159         case GATT_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION:{
1160             uint16_t configuration = READ_BT_16(packet, 5 + CHARACTERISTIC_LENGTH);
1161             gatt_helper = daemon_setup_gatt_client_request(connection, packet, 1);
1162             if (!gatt_helper) break;
1163             data = gatt_helper->characteristic_buffer;
1164             daemon_gatt_deserialize_characteristic(packet, 5, &characteristic);
1165             gatt_client_write_client_characteristic_configuration(gatt_client_id, gatt_helper->con_handle, &characteristic, configuration);
1166             break;
1167         case GATT_GET_MTU:
1168             handle = READ_BT_16(packet, 3);
1169             gatt_client_get_mtu(handle, &mtu);
1170             send_gatt_mtu_event(connection, handle, mtu);
1171             break;
1172         }
1173 #endif
1174     default:
1175             log_error("Error: command %u not implemented:", READ_CMD_OCF(packet));
1176             break;
1177     }
1178 
1179     return 0;
1180 }
1181 
1182 static int daemon_client_handler(connection_t *connection, uint16_t packet_type, uint16_t channel, uint8_t *data, uint16_t length){
1183 
1184     int err = 0;
1185     client_state_t * client;
1186 
1187     switch (packet_type){
1188         case HCI_COMMAND_DATA_PACKET:
1189             if (READ_CMD_OGF(data) != OGF_BTSTACK) {
1190                 // HCI Command
1191                 hci_send_cmd_packet(data, length);
1192             } else {
1193                 // BTstack command
1194                 btstack_command_handler(connection, data, length);
1195             }
1196             break;
1197         case L2CAP_DATA_PACKET:
1198             // process l2cap packet...
1199             err = l2cap_send_internal(channel, data, length);
1200             if (err == BTSTACK_ACL_BUFFERS_FULL) {
1201                 l2cap_block_new_credits(1);
1202             }
1203             break;
1204         case RFCOMM_DATA_PACKET:
1205             // process l2cap packet...
1206             err = rfcomm_send_internal(channel, data, length);
1207             break;
1208         case DAEMON_EVENT_PACKET:
1209             switch (data[0]) {
1210                 case DAEMON_EVENT_CONNECTION_OPENED:
1211                     log_info("DAEMON_EVENT_CONNECTION_OPENED %p\n",connection);
1212 
1213                     client = malloc(sizeof(client_state_t));
1214                     if (!client) break; // fail
1215                     memset(client, 0, sizeof(client_state_t));
1216                     client->connection   = connection;
1217                     client->power_mode   = HCI_POWER_OFF;
1218                     client->discoverable = 0;
1219                     linked_list_add(&clients, (linked_item_t *) client);
1220                     break;
1221                 case DAEMON_EVENT_CONNECTION_CLOSED:
1222                     log_info("DAEMON_EVENT_CONNECTION_CLOSED %p\n",connection);
1223                     daemon_disconnect_client(connection);
1224                     sdp_query_rfcomm_deregister_callback();
1225                     // no clients -> no HCI connections
1226                     if (!clients){
1227                         hci_disconnect_all();
1228                     }
1229 
1230                     // update discoverable mode
1231                     hci_discoverable_control(clients_require_discoverable());
1232                     // start power off, if last active client
1233                     if (!clients_require_power_on()){
1234                         start_power_off_timer();
1235                     }
1236                     break;
1237                 case DAEMON_NR_CONNECTIONS_CHANGED:
1238                     log_info("Nr Connections changed, new %u\n",data[1]);
1239                     break;
1240                 default:
1241                     break;
1242             }
1243             break;
1244     }
1245     if (err) {
1246         log_info("Daemon Handler: err %d\n", err);
1247     }
1248     return err;
1249 }
1250 
1251 
1252 static void daemon_set_logging_enabled(int enabled){
1253     if (enabled && !loggingEnabled){
1254         hci_dump_open(BTSTACK_LOG_FILE, BTSTACK_LOG_TYPE);
1255     }
1256     if (!enabled && loggingEnabled){
1257         hci_dump_close();
1258     }
1259     loggingEnabled = enabled;
1260 }
1261 
1262 // local cache used to manage UI status
1263 static HCI_STATE hci_state = HCI_STATE_OFF;
1264 static int num_connections = 0;
1265 static void update_ui_status(void){
1266     if (hci_state != HCI_STATE_WORKING) {
1267         bluetooth_status_handler(BLUETOOTH_OFF);
1268     } else {
1269         if (num_connections) {
1270             bluetooth_status_handler(BLUETOOTH_ACTIVE);
1271         } else {
1272             bluetooth_status_handler(BLUETOOTH_ON);
1273         }
1274     }
1275 }
1276 
1277 #ifdef USE_SPRINGBOARD
1278 static void preferences_changed_callback(void){
1279     int logging = platform_iphone_logging_enabled();
1280     log_info("Logging enabled: %u\n", logging);
1281     daemon_set_logging_enabled(logging);
1282 }
1283 #endif
1284 
1285 static void deamon_status_event_handler(uint8_t *packet, uint16_t size){
1286 
1287     uint8_t update_status = 0;
1288 
1289     // handle state event
1290     switch (packet[0]) {
1291         case BTSTACK_EVENT_STATE:
1292             hci_state = packet[2];
1293             log_info("New state: %u\n", hci_state);
1294             update_status = 1;
1295             break;
1296         case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED:
1297             num_connections = packet[2];
1298             log_info("New nr connections: %u\n", num_connections);
1299             update_status = 1;
1300             break;
1301         default:
1302             break;
1303     }
1304 
1305     // choose full bluetooth state
1306     if (update_status) {
1307         update_ui_status();
1308     }
1309 }
1310 
1311 static void daemon_retry_parked(void){
1312 
1313     // socket_connection_retry_parked is not reentrant
1314     static int retry_mutex = 0;
1315 
1316     // lock mutex
1317     if (retry_mutex) return;
1318     retry_mutex = 1;
1319 
1320     // ... try sending again
1321     socket_connection_retry_parked();
1322 
1323     if (!socket_connection_has_parked_connections()){
1324         l2cap_block_new_credits(0);
1325     }
1326 
1327     // unlock mutex
1328     retry_mutex = 0;
1329 }
1330 
1331 #if 0
1332 
1333 Minimal Code for LE Peripheral
1334 
1335 enum {
1336     SET_ADVERTISEMENT_PARAMS = 1 << 0,
1337     SET_ADVERTISEMENT_DATA   = 1 << 1,
1338     ENABLE_ADVERTISEMENTS    = 1 << 2,
1339 };
1340 
1341 const uint8_t adv_data[] = {
1342     // Flags general discoverable
1343     0x02, 0x01, 0x02,
1344     // Name
1345     0x08, 0x09, 'B', 'T', 's', 't', 'a', 'c', 'k'
1346 };
1347 uint8_t adv_data_len = sizeof(adv_data);
1348 static uint16_t todos = 0;
1349 
1350 static void app_run(void){
1351 
1352     if (!hci_can_send_command_packet_now()) return;
1353 
1354     if (todos & SET_ADVERTISEMENT_DATA){
1355         log_info("app_run: set advertisement data\n");
1356         todos &= ~SET_ADVERTISEMENT_DATA;
1357         hci_send_cmd(&hci_le_set_advertising_data, adv_data_len, adv_data);
1358         return;
1359     }
1360 
1361     if (todos & SET_ADVERTISEMENT_PARAMS){
1362         todos &= ~SET_ADVERTISEMENT_PARAMS;
1363         uint8_t adv_type = 0;   // default
1364         bd_addr_t null_addr;
1365         memset(null_addr, 0, 6);
1366         uint16_t adv_int_min = 0x0030;
1367         uint16_t adv_int_max = 0x0030;
1368         hci_send_cmd(&hci_le_set_advertising_parameters, adv_int_min, adv_int_max, adv_type, 0, 0, &null_addr, 0x07, 0x00);
1369         return;
1370     }
1371 
1372     if (todos & ENABLE_ADVERTISEMENTS){
1373         log_info("app_run: enable advertisements\n");
1374         todos &= ~ENABLE_ADVERTISEMENTS;
1375         hci_send_cmd(&hci_le_set_advertise_enable, 1);
1376         return;
1377     }
1378 }
1379 #endif
1380 
1381 static void daemon_packet_handler(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1382     uint16_t cid;
1383     switch (packet_type) {
1384         case HCI_EVENT_PACKET:
1385             deamon_status_event_handler(packet, size);
1386             switch (packet[0]){
1387 
1388                 case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
1389                     // ACL buffer freed...
1390                     daemon_retry_parked();
1391                     // no need to tell clients
1392                     return;
1393                 case RFCOMM_EVENT_CREDITS:
1394                     // RFCOMM CREDITS received...
1395                     daemon_retry_parked();
1396                     break;
1397                  case RFCOMM_EVENT_OPEN_CHANNEL_COMPLETE:
1398                     cid = READ_BT_16(packet, 13);
1399                     connection = connection_for_rfcomm_cid(cid);
1400                     if (!connection) break;
1401                     if (packet[2]) {
1402                         daemon_remove_client_rfcomm_channel(connection, cid);
1403                     } else {
1404                         daemon_add_client_rfcomm_channel(connection, cid);
1405                     }
1406                     break;
1407                 case RFCOMM_EVENT_CHANNEL_CLOSED:
1408                     cid = READ_BT_16(packet, 2);
1409                     connection = connection_for_rfcomm_cid(cid);
1410                     if (!connection) break;
1411                     daemon_remove_client_rfcomm_channel(connection, cid);
1412                     break;
1413                 case RFCOMM_EVENT_SERVICE_REGISTERED:
1414                     if (packet[2]) break;
1415                     daemon_add_client_rfcomm_service(connection, packet[3]);
1416                     break;
1417                 case L2CAP_EVENT_CHANNEL_OPENED:
1418                     cid = READ_BT_16(packet, 13);
1419                     connection = connection_for_l2cap_cid(cid);
1420                     if (!connection) break;
1421                     if (packet[2]) {
1422                         daemon_remove_client_l2cap_channel(connection, cid);
1423                     } else {
1424                         daemon_add_client_l2cap_channel(connection, cid);
1425                     }
1426                     break;
1427                 case L2CAP_EVENT_CHANNEL_CLOSED:
1428                     cid = READ_BT_16(packet, 2);
1429                     connection = connection_for_l2cap_cid(cid);
1430                     if (!connection) break;
1431                     daemon_remove_client_l2cap_channel(connection, cid);
1432                     break;
1433 #if defined(HAVE_BLE) && defined(HAVE_MALLOC)
1434                 case HCI_EVENT_DISCONNECTION_COMPLETE:
1435                     log_info("daemon : ignore HCI_EVENT_DISCONNECTION_COMPLETE ingnoring.");
1436                     // note: moved to gatt_client_handler because it's received here prematurely
1437                     // daemon_remove_gatt_client_helper(READ_BT_16(packet, 3));
1438                     break;
1439 #endif
1440                 default:
1441                     break;
1442             }
1443         case DAEMON_EVENT_PACKET:
1444             switch (packet[0]){
1445                 case DAEMON_EVENT_NEW_RFCOMM_CREDITS:
1446                     daemon_retry_parked();
1447                     break;
1448                 default:
1449                     break;
1450             }
1451         default:
1452             break;
1453     }
1454     if (connection) {
1455         socket_connection_send_packet(connection, packet_type, channel, packet, size);
1456     } else {
1457         socket_connection_send_packet_all(packet_type, channel, packet, size);
1458     }
1459 }
1460 
1461 static void l2cap_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){
1462     daemon_packet_handler(NULL, packet_type, channel, packet, size);
1463 }
1464 
1465 static void handle_sdp_rfcomm_service_result(sdp_query_event_t * rfcomm_event, void * context){
1466     switch (rfcomm_event->type){
1467         case SDP_QUERY_RFCOMM_SERVICE: {
1468             sdp_query_rfcomm_service_event_t * service_event = (sdp_query_rfcomm_service_event_t*) rfcomm_event;
1469             int name_len = (int)strlen((const char*)service_event->service_name);
1470             int event_len = 3 + name_len;
1471             uint8_t event[event_len];
1472             event[0] = rfcomm_event->type;
1473             event[1] = 1 + name_len;
1474             event[2] = service_event->channel_nr;
1475             memcpy(&event[3], service_event->service_name, name_len);
1476             hci_dump_packet(HCI_EVENT_PACKET, 0, event, event_len);
1477             socket_connection_send_packet(context, HCI_EVENT_PACKET, 0, event, event_len);
1478             break;
1479         }
1480         case SDP_QUERY_COMPLETE: {
1481             sdp_query_complete_event_t * complete_event = (sdp_query_complete_event_t*) rfcomm_event;
1482             uint8_t event[] = { rfcomm_event->type, 1, complete_event->status};
1483             hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
1484             socket_connection_send_packet(context, HCI_EVENT_PACKET, 0, event, sizeof(event));
1485             break;
1486         }
1487     }
1488 }
1489 
1490 static void sdp_client_assert_buffer(int size){
1491     if (size > attribute_value_buffer_size){
1492         log_error("SDP attribute value buffer size exceeded: available %d, required %d", attribute_value_buffer_size, size);
1493     }
1494 }
1495 
1496 // define new packet type SDP_CLIENT_PACKET
1497 static void handle_sdp_client_query_result(sdp_query_event_t * event){
1498     sdp_query_attribute_value_event_t * ve;
1499     sdp_query_complete_event_t * complete_event;
1500 
1501     switch (event->type){
1502         case SDP_QUERY_ATTRIBUTE_VALUE:
1503             ve = (sdp_query_attribute_value_event_t*) event;
1504 
1505             sdp_client_assert_buffer(ve->attribute_length);
1506 
1507             attribute_value[ve->data_offset] = ve->data;
1508 
1509             if ((uint16_t)(ve->data_offset+1) == ve->attribute_length){
1510                 hexdump(attribute_value, ve->attribute_length);
1511 
1512                 int event_len = 1 + 3 * 2 + ve->attribute_length;
1513                 uint8_t event[event_len];
1514                 event[0] = SDP_QUERY_ATTRIBUTE_VALUE;
1515                 bt_store_16(event, 1, (uint16_t)ve->record_id);
1516                 bt_store_16(event, 3, ve->attribute_id);
1517                 bt_store_16(event, 5, (uint16_t)ve->attribute_length);
1518                 memcpy(&event[7], attribute_value, ve->attribute_length);
1519                 hci_dump_packet(SDP_CLIENT_PACKET, 0, event, event_len);
1520                 socket_connection_send_packet(sdp_client_query_connection, SDP_CLIENT_PACKET, 0, event, event_len);
1521             }
1522 
1523             break;
1524         case SDP_QUERY_COMPLETE:
1525             complete_event = (sdp_query_complete_event_t*) event;
1526             uint8_t event[] = { SDP_QUERY_COMPLETE, 1, complete_event->status};
1527             hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
1528             socket_connection_send_packet(sdp_client_query_connection, HCI_EVENT_PACKET, 0, event, sizeof(event));
1529             break;
1530     }
1531 }
1532 
1533 static void power_notification_callback(POWER_NOTIFICATION_t notification){
1534     switch (notification) {
1535         case POWER_WILL_SLEEP:
1536             // let's sleep
1537             power_management_sleep = 1;
1538             hci_power_control(HCI_POWER_SLEEP);
1539             break;
1540         case POWER_WILL_WAKE_UP:
1541             // assume that all clients use Bluetooth -> if connection, start Bluetooth
1542             power_management_sleep = 0;
1543             if (clients_require_power_on()) {
1544                 hci_power_control(HCI_POWER_ON);
1545             }
1546             break;
1547         default:
1548             break;
1549     }
1550 }
1551 
1552 static void daemon_sigint_handler(int param){
1553 
1554 #ifdef USE_BLUETOOL
1555     // notify daemons
1556     notify_post("ch.ringwald.btstack.stopped");
1557 #endif
1558 
1559     log_info(" <= SIGINT received, shutting down..\n");
1560 
1561     hci_power_control( HCI_POWER_OFF);
1562     hci_close();
1563 
1564     log_info("Good bye, see you.\n");
1565 
1566     exit(0);
1567 }
1568 
1569 // MARK: manage power off timer
1570 
1571 #define USE_POWER_OFF_TIMER
1572 
1573 static void stop_power_off_timer(void){
1574 #ifdef USE_POWER_OFF_TIMER
1575     if (timeout_active) {
1576         run_loop_remove_timer(&timeout);
1577         timeout_active = 0;
1578     }
1579 #endif
1580 }
1581 
1582 static void start_power_off_timer(void){
1583 #ifdef USE_POWER_OFF_TIMER
1584     stop_power_off_timer();
1585     run_loop_set_timer(&timeout, DAEMON_NO_ACTIVE_CLIENT_TIMEOUT);
1586     run_loop_add_timer(&timeout);
1587     timeout_active = 1;
1588 #else
1589     hci_power_control(HCI_POWER_OFF);
1590 #endif
1591 }
1592 
1593 // MARK: manage list of clients
1594 
1595 
1596 static client_state_t * client_for_connection(connection_t *connection) {
1597     linked_item_t *it;
1598     for (it = (linked_item_t *) clients; it ; it = it->next){
1599         client_state_t * client_state = (client_state_t *) it;
1600         if (client_state->connection == connection) {
1601             return client_state;
1602         }
1603     }
1604     return NULL;
1605 }
1606 
1607 static void clients_clear_power_request(void){
1608     linked_item_t *it;
1609     for (it = (linked_item_t *) clients; it ; it = it->next){
1610         client_state_t * client_state = (client_state_t *) it;
1611         client_state->power_mode = HCI_POWER_OFF;
1612     }
1613 }
1614 
1615 static int clients_require_power_on(void){
1616 
1617     if (global_enable) return 1;
1618 
1619     linked_item_t *it;
1620     for (it = (linked_item_t *) clients; it ; it = it->next){
1621         client_state_t * client_state = (client_state_t *) it;
1622         if (client_state->power_mode == HCI_POWER_ON) {
1623             return 1;
1624         }
1625     }
1626     return 0;
1627 }
1628 
1629 static int clients_require_discoverable(void){
1630     linked_item_t *it;
1631     for (it = (linked_item_t *) clients; it ; it = it->next){
1632         client_state_t * client_state = (client_state_t *) it;
1633         if (client_state->discoverable) {
1634             return 1;
1635         }
1636     }
1637     return 0;
1638 }
1639 
1640 static void usage(const char * name) {
1641     printf("%s, BTstack background daemon\n", name);
1642     printf("usage: %s [--help] [--tcp port]\n", name);
1643     printf("    --help   display this usage\n");
1644     printf("    --tcp    use TCP server on port %u\n", BTSTACK_PORT);
1645     printf("Without the --tcp option, BTstack daemon is listening on unix domain socket %s\n\n", BTSTACK_UNIX);
1646 }
1647 
1648 #ifdef USE_BLUETOOL
1649 static void * run_loop_thread(void *context){
1650     run_loop_execute();
1651     return NULL;
1652 }
1653 #endif
1654 
1655 #ifdef HAVE_BLE
1656 
1657 static void handle_gatt_client_event(uint8_t packet_type, uint8_t * packet, uint16_t size){
1658 
1659     // hack: handle disconnection_complete_here instead of main hci event packet handler
1660     // we receive a HCI event packet in disguise
1661     if (packet[0] == HCI_EVENT_DISCONNECTION_COMPLETE){
1662         log_info("daemon hack: handle disconnection_complete in handle_gatt_client_event instead of main hci event packet handler");
1663         uint16_t handle = READ_BT_16(packet, 3);
1664         daemon_remove_gatt_client_helper(handle);
1665         return;
1666     }
1667 
1668     // only handle GATT Events
1669     switch(packet[0]){
1670         case GATT_SERVICE_QUERY_RESULT:
1671         case GATT_INCLUDED_SERVICE_QUERY_RESULT:
1672         case GATT_NOTIFICATION:
1673         case GATT_INDICATION:
1674         case GATT_CHARACTERISTIC_QUERY_RESULT:
1675         case GATT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
1676         case GATT_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
1677         case GATT_LONG_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
1678         case GATT_CHARACTERISTIC_VALUE_QUERY_RESULT:
1679         case GATT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT:
1680         case GATT_QUERY_COMPLETE:
1681            break;
1682         default:
1683             return;
1684     }
1685 
1686     uint16_t con_handle = READ_BT_16(packet, 2);
1687     linked_list_gatt_client_helper_t * gatt_client_helper = daemon_get_gatt_client_helper(con_handle);
1688     if (!gatt_client_helper){
1689         log_info("daemon handle_gatt_client_event: gc helper for handle 0x%2x is NULL.", con_handle);
1690         return;
1691     }
1692 
1693     connection_t *connection = NULL;
1694 
1695     // daemon doesn't track which connection subscribed to this particular handle, so we just notify all connections
1696     switch(packet[0]){
1697         case GATT_NOTIFICATION:
1698         case GATT_INDICATION:{
1699             hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size);
1700 
1701             linked_item_t *it;
1702             for (it = (linked_item_t *) clients; it ; it = it->next){
1703                 client_state_t * client_state = (client_state_t *) it;
1704                 socket_connection_send_packet(client_state->connection, HCI_EVENT_PACKET, 0, packet, size);
1705             }
1706             return;
1707         }
1708         default:
1709             break;
1710     }
1711 
1712     // otherwise, we have to have an active connection
1713     connection = gatt_client_helper->active_connection;
1714     uint16_t offset;
1715     uint16_t length;
1716 
1717     if (!connection) return;
1718 
1719     switch(packet[0]){
1720 
1721         case GATT_SERVICE_QUERY_RESULT:
1722         case GATT_INCLUDED_SERVICE_QUERY_RESULT:
1723         case GATT_CHARACTERISTIC_QUERY_RESULT:
1724         case GATT_CHARACTERISTIC_VALUE_QUERY_RESULT:
1725         case GATT_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
1726         case GATT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
1727             hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size);
1728             socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, packet, size);
1729             break;
1730 
1731         case GATT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT:
1732         case GATT_LONG_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
1733             offset = READ_BT_16(packet, 6);
1734             length = READ_BT_16(packet, 8);
1735             gatt_client_helper->characteristic_buffer[0] = packet[0];               // store type (characteristic/descriptor)
1736             gatt_client_helper->characteristic_handle    = READ_BT_16(packet, 4);   // store attribute handle
1737             gatt_client_helper->characteristic_length = offset + length;            // update length
1738             memcpy(&gatt_client_helper->characteristic_buffer[10 + offset], &packet[10], length);
1739             break;
1740 
1741         case GATT_QUERY_COMPLETE:{
1742             gatt_client_helper->active_connection = NULL;
1743             if (gatt_client_helper->characteristic_length){
1744                 // send re-combined long characteristic value or long characteristic descriptor value
1745                 uint8_t * event = gatt_client_helper->characteristic_buffer;
1746                 uint16_t event_size = 10 + gatt_client_helper->characteristic_length;
1747                 // event[0] == already set by previsous case
1748                 event[1] = 8 + gatt_client_helper->characteristic_length;
1749                 bt_store_16(event, 2, READ_BT_16(packet, 2));
1750                 bt_store_16(event, 4, gatt_client_helper->characteristic_handle);
1751                 bt_store_16(event, 6, 0);   // offset
1752                 bt_store_16(event, 8, gatt_client_helper->characteristic_length);
1753                 hci_dump_packet(HCI_EVENT_PACKET, 0, event, event_size);
1754                 socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, event, event_size);
1755                 gatt_client_helper->characteristic_length = 0;
1756             }
1757             hci_dump_packet(HCI_EVENT_PACKET, 0, packet, size);
1758             socket_connection_send_packet(connection, HCI_EVENT_PACKET, 0, packet, size);
1759             break;
1760         }
1761         default:
1762             break;
1763     }
1764 }
1765 #endif
1766 
1767 int main (int argc,  char * const * argv){
1768 
1769     static int tcp_flag = 0;
1770 
1771     while (1) {
1772         static struct option long_options[] = {
1773             { "tcp", no_argument, &tcp_flag, 1 },
1774             { "help", no_argument, 0, 0 },
1775             { 0,0,0,0 } // This is a filler for -1
1776         };
1777 
1778         int c;
1779         int option_index = -1;
1780 
1781         c = getopt_long(argc, argv, "h", long_options, &option_index);
1782 
1783         if (c == -1) break; // no more option
1784 
1785         // treat long parameter first
1786         if (option_index == -1) {
1787             switch (c) {
1788                 case '?':
1789                 case 'h':
1790                     usage(argv[0]);
1791                     return 0;
1792                     break;
1793             }
1794         } else {
1795             switch (option_index) {
1796                 case 1:
1797                     usage(argv[0]);
1798                     return 0;
1799                     break;
1800             }
1801         }
1802     }
1803 
1804     if (tcp_flag){
1805         printf("BTstack Daemon started on port %u\n", BTSTACK_PORT);
1806     } else {
1807         printf("BTstack Daemon started on socket %s\n", BTSTACK_UNIX);
1808     }
1809 
1810     // make stdout unbuffered
1811     setbuf(stdout, NULL);
1812 
1813     // handle CTRL-c
1814     signal(SIGINT, daemon_sigint_handler);
1815     // handle SIGTERM - suggested for launchd
1816     signal(SIGTERM, daemon_sigint_handler);
1817 
1818     // TODO: win32 variant
1819 #ifndef _WIN32
1820     // handle SIGPIPE
1821     struct sigaction act;
1822     act.sa_handler = SIG_IGN;
1823     sigemptyset (&act.sa_mask);
1824     act.sa_flags = 0;
1825     sigaction (SIGPIPE, &act, NULL);
1826 #endif
1827 
1828     bt_control_t * control = NULL;
1829 
1830 #ifdef HAVE_TRANSPORT_H4
1831     config.device_name   = UART_DEVICE;
1832     config.baudrate_init = UART_SPEED;
1833     config.baudrate_main = 0;
1834     config.flowcontrol = 1;
1835 #if defined(USE_BLUETOOL) && defined(USE_POWERMANAGEMENT)
1836     if (bt_control_iphone_power_management_supported()){
1837         // use default (max) UART baudrate over netraph interface
1838         config.baudrate_init = 0;
1839         transport = hci_transport_h4_iphone_instance();
1840     } else {
1841         transport = hci_transport_h4_instance();
1842     }
1843 #else
1844     transport = hci_transport_h4_instance();
1845 #endif
1846 #endif
1847 
1848 #ifdef HAVE_TRANSPORT_USB
1849     transport = hci_transport_usb_instance();
1850 #endif
1851 
1852 #ifdef USE_BLUETOOL
1853     control = &bt_control_iphone;
1854 #endif
1855 
1856 #if defined(USE_BLUETOOL) && defined(USE_POWERMANAGEMENT)
1857     if (bt_control_iphone_power_management_supported()){
1858         hci_transport_h4_iphone_set_enforce_wake_device("/dev/btwake");
1859     }
1860 #endif
1861 
1862 #ifdef USE_SPRINGBOARD
1863     bluetooth_status_handler = platform_iphone_status_handler;
1864     platform_iphone_register_window_manager_restart(update_ui_status);
1865     platform_iphone_register_preferences_changed(preferences_changed_callback);
1866 #endif
1867 
1868 #ifdef REMOTE_DEVICE_DB
1869     remote_device_db = &REMOTE_DEVICE_DB;
1870 #endif
1871 
1872     run_loop_init(RUN_LOOP_POSIX);
1873 
1874     // init power management notifications
1875     if (control && control->register_for_power_notifications){
1876         control->register_for_power_notifications(power_notification_callback);
1877     }
1878 
1879     // logging
1880     loggingEnabled = 0;
1881     int newLoggingEnabled = 1;
1882 #ifdef USE_BLUETOOL
1883     // iPhone has toggle in Preferences.app
1884     newLoggingEnabled = platform_iphone_logging_enabled();
1885 #endif
1886     daemon_set_logging_enabled(newLoggingEnabled);
1887 
1888     // dump version
1889     log_info("BTdaemon started\n");
1890     log_info("version %s, build %s", BTSTACK_VERSION, BTSTACK_DATE);
1891 
1892     // init HCI
1893     hci_init(transport, &config, control, remote_device_db);
1894 
1895 #ifdef USE_BLUETOOL
1896     // iPhone doesn't use SSP yet as there's no UI for it yet and auto accept is not an option
1897     hci_ssp_set_enable(0);
1898 #endif
1899     // init L2CAP
1900     l2cap_init();
1901     l2cap_register_packet_handler(&l2cap_packet_handler);
1902     timeout.process = daemon_no_connections_timeout;
1903 
1904 #ifdef HAVE_RFCOMM
1905     log_info("config.h: HAVE_RFCOMM\n");
1906     rfcomm_init();
1907     rfcomm_register_packet_handler(&daemon_packet_handler);
1908 #endif
1909 
1910 #ifdef HAVE_SDP
1911     sdp_init();
1912     sdp_register_packet_handler(&daemon_packet_handler);
1913 #endif
1914 
1915 #ifdef HAVE_BLE
1916     // GATT Client
1917     gatt_client_init();
1918     gatt_client_id = gatt_client_register_packet_handler(&handle_gatt_client_event);
1919 
1920     // sm_init();
1921     // sm_set_io_capabilities(IO_CAPABILITY_DISPLAY_ONLY);
1922     // sm_set_authentication_requirements( SM_AUTHREQ_BONDING | SM_AUTHREQ_MITM_PROTECTION);
1923 
1924     // GATT Server - empty attribute database
1925     le_device_db_init();
1926     att_server_init(NULL, NULL, NULL);
1927 
1928 #endif
1929 
1930 #ifdef USE_LAUNCHD
1931     socket_connection_create_launchd();
1932 #else
1933     // create server
1934     if (tcp_flag) {
1935         socket_connection_create_tcp(BTSTACK_PORT);
1936     } else {
1937         socket_connection_create_unix(BTSTACK_UNIX);
1938     }
1939 #endif
1940     socket_connection_register_packet_callback(&daemon_client_handler);
1941 
1942 #ifdef USE_BLUETOOL
1943     // notify daemons
1944     notify_post("ch.ringwald.btstack.started");
1945 
1946     // spawn thread to have BTstack run loop on new thread, while main thread is used to keep CFRunLoop
1947     pthread_t run_loop;
1948     pthread_create(&run_loop, NULL, &run_loop_thread, NULL);
1949 
1950     // needed to receive notifications
1951     CFRunLoopRun();
1952 #endif
1953         // go!
1954     run_loop_execute();
1955     return 0;
1956 }
1957