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