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