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