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