1 /**********************************************************************
2  *
3  *  Copyright 2017 The Android Open Source Project
4  *  Copyright 2015 Intel Corporation
5  *
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at:
9  *
10  *  http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15  *  implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  *
19  **********************************************************************/
20 #include <base/bind.h>
21 #include <base/location.h>
22 #include <base/logging.h>
23 #include <base/threading/thread.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <poll.h>
27 #include <stdbool.h>
28 #include <stdint.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <algorithm>
32 
33 #include <sys/ioctl.h>
34 #include <sys/socket.h>
35 
36 #include "buffer_allocator.h"
37 #include "hci_internals.h"
38 #include "hci_layer.h"
39 #include "osi/include/compat.h"
40 #include "osi/include/log.h"
41 #include "osi/include/osi.h"
42 #include "osi/include/properties.h"
43 
44 using base::Thread;
45 
46 #define BTPROTO_HCI 1
47 #define HCI_CHANNEL_USER 1
48 #define HCI_CHANNEL_CONTROL 3
49 #define HCI_DEV_NONE 0xffff
50 
51 #define RFKILL_TYPE_BLUETOOTH 2
52 #define RFKILL_OP_CHANGE_ALL 3
53 
54 #define MGMT_OP_INDEX_LIST 0x0003
55 #define MGMT_EV_INDEX_ADDED 0x0004
56 #define MGMT_EV_COMMAND_COMP 0x0001
57 #define MGMT_EV_SIZE_MAX 1024
58 #define MGMT_EV_POLL_TIMEOUT 3000 /* 3000ms */
59 
60 struct sockaddr_hci {
61   sa_family_t hci_family;
62   unsigned short hci_dev;
63   unsigned short hci_channel;
64 };
65 
66 struct rfkill_event {
67   uint32_t idx;
68   uint8_t type;
69   uint8_t op;
70   uint8_t soft, hard;
71 } __attribute__((packed));
72 
73 struct mgmt_pkt {
74   uint16_t opcode;
75   uint16_t index;
76   uint16_t len;
77   uint8_t data[MGMT_EV_SIZE_MAX];
78 } __attribute__((packed));
79 
80 struct mgmt_event_read_index {
81   uint16_t cc_opcode;
82   uint8_t status;
83   uint16_t num_intf;
84   uint16_t index[0];
85 } __attribute__((packed));
86 
87 enum HciPacketType {
88   HCI_PACKET_TYPE_UNKNOWN = 0,
89   HCI_PACKET_TYPE_COMMAND = 1,
90   HCI_PACKET_TYPE_ACL_DATA = 2,
91   HCI_PACKET_TYPE_SCO_DATA = 3,
92   HCI_PACKET_TYPE_EVENT = 4
93 };
94 
95 extern void initialization_complete();
96 extern void hci_event_received(const base::Location& from_here, BT_HDR* packet);
97 extern void acl_event_received(BT_HDR* packet);
98 extern void sco_data_received(BT_HDR* packet);
99 
100 static int bt_vendor_fd = -1;
101 static int hci_interface;
102 static int rfkill_en;
103 static int wait_hcidev(void);
104 static int rfkill(int block);
105 
106 int reader_thread_ctrl_fd = -1;
107 Thread* reader_thread = NULL;
108 
monitor_socket(int ctrl_fd,int fd)109 void monitor_socket(int ctrl_fd, int fd) {
110   const allocator_t* buffer_allocator = buffer_allocator_get_interface();
111   const size_t buf_size = 2000;
112   uint8_t buf[buf_size];
113   ssize_t len = read(fd, buf, buf_size);
114 
115   while (len > 0) {
116     if (len == buf_size)
117       LOG(FATAL) << "This packet filled buffer, if it have continuation we "
118                     "don't know how to merge it, increase buffer size!";
119 
120     uint8_t type = buf[0];
121 
122     size_t packet_size = buf_size + BT_HDR_SIZE;
123     BT_HDR* packet =
124         reinterpret_cast<BT_HDR*>(buffer_allocator->alloc(packet_size));
125     packet->offset = 0;
126     packet->layer_specific = 0;
127     packet->len = len - 1;
128     memcpy(packet->data, buf + 1, len - 1);
129 
130     switch (type) {
131       case HCI_PACKET_TYPE_COMMAND:
132         packet->event = MSG_HC_TO_STACK_HCI_EVT;
133         hci_event_received(FROM_HERE, packet);
134         break;
135       case HCI_PACKET_TYPE_ACL_DATA:
136         packet->event = MSG_HC_TO_STACK_HCI_ACL;
137         acl_event_received(packet);
138         break;
139       case HCI_PACKET_TYPE_SCO_DATA:
140         packet->event = MSG_HC_TO_STACK_HCI_SCO;
141         sco_data_received(packet);
142         break;
143       case HCI_PACKET_TYPE_EVENT:
144         packet->event = MSG_HC_TO_STACK_HCI_EVT;
145         hci_event_received(FROM_HERE, packet);
146         break;
147       default:
148         LOG(FATAL) << "Unexpected event type: " << +type;
149         break;
150     }
151 
152     fd_set fds;
153     FD_ZERO(&fds);
154     FD_SET(ctrl_fd, &fds);
155     FD_SET(fd, &fds);
156     int res = select(std::max(fd, ctrl_fd) + 1, &fds, NULL, NULL, NULL);
157     if (res <= 0) LOG(INFO) << "Nothing more to read";
158 
159     if (FD_ISSET(ctrl_fd, &fds)) {
160       LOG(INFO) << "exitting";
161       return;
162     }
163 
164     len = read(fd, buf, buf_size);
165   }
166 }
167 
168 /* TODO: should thread the device waiting and return immedialty */
hci_initialize()169 void hci_initialize() {
170   LOG(INFO) << __func__;
171 
172   char prop_value[PROPERTY_VALUE_MAX];
173   osi_property_get("bluetooth.interface", prop_value, "0");
174 
175   errno = 0;
176   if (memcmp(prop_value, "hci", 3))
177     hci_interface = strtol(prop_value, NULL, 10);
178   else
179     hci_interface = strtol(prop_value + 3, NULL, 10);
180   if (errno) hci_interface = 0;
181 
182   LOG(INFO) << "Using interface hci" << +hci_interface;
183 
184   osi_property_get("bluetooth.rfkill", prop_value, "1");
185 
186   rfkill_en = atoi(prop_value);
187   if (rfkill_en) {
188     rfkill(0);
189   }
190 
191   int fd = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI);
192   CHECK(fd >= 0) << "socket create error" << strerror(errno);
193 
194   bt_vendor_fd = fd;
195 
196   if (wait_hcidev()) {
197     LOG(FATAL) << "HCI interface hci" << +hci_interface << " not found";
198   }
199 
200   struct sockaddr_hci addr;
201   memset(&addr, 0, sizeof(addr));
202   addr.hci_family = AF_BLUETOOTH;
203   addr.hci_dev = hci_interface;
204   addr.hci_channel = HCI_CHANNEL_USER;
205   if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
206     PLOG(FATAL) << "socket bind error";
207   }
208 
209   int sv[2];
210   if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) < 0) {
211     PLOG(FATAL) << "socketpair failed";
212   }
213 
214   reader_thread_ctrl_fd = sv[0];
215   reader_thread = new Thread("hci_sock_reader");
216   reader_thread->Start();
217   reader_thread->task_runner()->PostTask(
218       FROM_HERE, base::Bind(&monitor_socket, sv[1], bt_vendor_fd));
219 
220   LOG(INFO) << "HCI device ready";
221   initialization_complete();
222 }
223 
hci_close()224 void hci_close() {
225   LOG(INFO) << __func__;
226 
227   if (bt_vendor_fd != -1) {
228     close(bt_vendor_fd);
229     bt_vendor_fd = -1;
230   }
231 
232   if (reader_thread_ctrl_fd != -1) {
233     uint8_t msg[] = {1};
234     send(reader_thread_ctrl_fd, msg, sizeof(msg), 0);
235     reader_thread_ctrl_fd = -1;
236   }
237 
238   if (reader_thread != NULL) {
239     reader_thread->Stop();
240     delete reader_thread;
241     reader_thread = NULL;
242   }
243 
244   rfkill(1);
245 }
246 
hci_transmit(BT_HDR * packet)247 void hci_transmit(BT_HDR* packet) {
248   uint8_t type = 0;
249 
250   CHECK(bt_vendor_fd != -1);
251 
252   uint16_t event = packet->event & MSG_EVT_MASK;
253   switch (event & MSG_EVT_MASK) {
254     case MSG_STACK_TO_HC_HCI_CMD:
255       type = 1;
256       break;
257     case MSG_STACK_TO_HC_HCI_ACL:
258       type = 2;
259       break;
260     case MSG_STACK_TO_HC_HCI_SCO:
261       type = 3;
262       break;
263     default:
264       LOG(FATAL) << "Unknown packet type " << event;
265       break;
266   }
267 
268   uint8_t* addr = packet->data + packet->offset - 1;
269   uint8_t store = *addr;
270   *addr = type;
271   size_t ret = write(bt_vendor_fd, addr, packet->len + 1);
272 
273   *(addr) = store;
274 
275   if (ret != packet->len + 1) LOG(ERROR) << "Should have send whole packet";
276 
277   if (ret == -1) PLOG(FATAL) << "write failed";
278 }
279 
wait_hcidev(void)280 static int wait_hcidev(void) {
281   struct sockaddr_hci addr;
282   struct pollfd fds[1];
283   struct mgmt_pkt ev;
284   int fd;
285   int ret = 0;
286 
287   LOG(INFO) << __func__;
288 
289   fd = socket(PF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI);
290   if (fd < 0) {
291     PLOG(ERROR) << "Bluetooth socket error";
292     return -1;
293   }
294 
295   memset(&addr, 0, sizeof(addr));
296   addr.hci_family = AF_BLUETOOTH;
297   addr.hci_dev = HCI_DEV_NONE;
298   addr.hci_channel = HCI_CHANNEL_CONTROL;
299 
300   if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
301     PLOG(ERROR) << "HCI Channel Control";
302     close(fd);
303     return -1;
304   }
305 
306   fds[0].fd = fd;
307   fds[0].events = POLLIN;
308 
309   /* Read Controller Index List Command */
310   ev.opcode = MGMT_OP_INDEX_LIST;
311   ev.index = HCI_DEV_NONE;
312   ev.len = 0;
313 
314   ssize_t wrote;
315   OSI_NO_INTR(wrote = write(fd, &ev, 6));
316   if (wrote != 6) {
317     PLOG(ERROR) << "Unable to write mgmt command";
318     ret = -1;
319     goto end;
320   }
321 
322   while (1) {
323     int n;
324     OSI_NO_INTR(n = poll(fds, 1, MGMT_EV_POLL_TIMEOUT));
325     if (n == -1) {
326       PLOG(ERROR) << "Poll error";
327       ret = -1;
328       break;
329     } else if (n == 0) {
330       LOG(ERROR) << "Timeout, no HCI device detected";
331       ret = -1;
332       break;
333     }
334 
335     if (fds[0].revents & POLLIN) {
336       OSI_NO_INTR(n = read(fd, &ev, sizeof(struct mgmt_pkt)));
337       if (n < 0) {
338         PLOG(ERROR) << "Error reading control channel";
339         ret = -1;
340         break;
341       }
342 
343       if (ev.opcode == MGMT_EV_INDEX_ADDED && ev.index == hci_interface) {
344         goto end;
345       } else if (ev.opcode == MGMT_EV_COMMAND_COMP) {
346         struct mgmt_event_read_index* cc;
347         int i;
348 
349         cc = (struct mgmt_event_read_index*)ev.data;
350 
351         if (cc->cc_opcode != MGMT_OP_INDEX_LIST || cc->status != 0) continue;
352 
353         for (i = 0; i < cc->num_intf; i++) {
354           if (cc->index[i] == hci_interface) goto end;
355         }
356       }
357     }
358   }
359 
360 end:
361   close(fd);
362   return ret;
363 }
364 
rfkill(int block)365 static int rfkill(int block) {
366   struct rfkill_event event;
367   int fd;
368 
369   LOG(INFO) << __func__;
370 
371   fd = open("/dev/rfkill", O_WRONLY);
372   if (fd < 0) {
373     LOG(ERROR) << "Unable to open /dev/rfkill";
374     return -1;
375   }
376 
377   memset(&event, 0, sizeof(struct rfkill_event));
378   event.op = RFKILL_OP_CHANGE_ALL;
379   event.type = RFKILL_TYPE_BLUETOOTH;
380   event.hard = block;
381   event.soft = block;
382 
383   ssize_t len;
384   OSI_NO_INTR(len = write(fd, &event, sizeof(event)));
385   if (len < 0) {
386     LOG(ERROR) << "Failed to change rfkill state";
387     close(fd);
388     return 1;
389   }
390 
391   close(fd);
392   return 0;
393 }
394 
hci_open_firmware_log_file()395 int hci_open_firmware_log_file() { return INVALID_FD; }
396 
hci_close_firmware_log_file(int fd)397 void hci_close_firmware_log_file(int fd) {}
398 
hci_log_firmware_debug_packet(int fd,BT_HDR * packet)399 void hci_log_firmware_debug_packet(int fd, BT_HDR* packet) {}
400