1 /* userchan.c - HCI User Channel based Bluetooth driver */
2 
3 /*
4  * Copyright (c) 2018 Intel Corporation
5  * Copyright (c) 2023 Victor Chavez
6  * SPDX-License-Identifier: Apache-2.0
7  */
8 
9 #include <zephyr/kernel.h>
10 #include <zephyr/device.h>
11 #include <zephyr/init.h>
12 #include <zephyr/sys/util.h>
13 
14 #include <errno.h>
15 #include <stddef.h>
16 #include <stdlib.h>
17 #include <poll.h>
18 #include <errno.h>
19 #include <sys/socket.h>
20 #include <string.h>
21 #include <unistd.h>
22 #include <stdio.h>
23 #include <limits.h>
24 #include <netinet/in.h>
25 #include <arpa/inet.h>
26 #include <zephyr/sys/byteorder.h>
27 
28 #include "soc.h"
29 #include "cmdline.h" /* native_posix command line options header */
30 
31 #include <zephyr/bluetooth/bluetooth.h>
32 #include <zephyr/bluetooth/hci.h>
33 #include <zephyr/drivers/bluetooth.h>
34 
35 #define LOG_LEVEL CONFIG_BT_HCI_DRIVER_LOG_LEVEL
36 #include <zephyr/logging/log.h>
37 LOG_MODULE_REGISTER(bt_driver);
38 
39 #define DT_DRV_COMPAT zephyr_bt_hci_userchan
40 
41 struct uc_data {
42 	int           fd;
43 	bt_hci_recv_t recv;
44 
45 };
46 
47 #define BTPROTO_HCI      1
48 struct sockaddr_hci {
49 	sa_family_t     hci_family;
50 	unsigned short  hci_dev;
51 	unsigned short  hci_channel;
52 };
53 #define HCI_CHANNEL_USER 1
54 
55 #define SOL_HCI          0
56 
57 static K_KERNEL_STACK_DEFINE(rx_thread_stack,
58 			     CONFIG_ARCH_POSIX_RECOMMENDED_STACK_SIZE);
59 static struct k_thread rx_thread_data;
60 
61 static unsigned short bt_dev_index;
62 
63 #define TCP_ADDR_BUFF_SIZE 16
64 static bool hci_socket;
65 static char ip_addr[TCP_ADDR_BUFF_SIZE];
66 static unsigned int port;
67 static bool arg_found;
68 
get_rx(const uint8_t * buf)69 static struct net_buf *get_rx(const uint8_t *buf)
70 {
71 	bool discardable = false;
72 	k_timeout_t timeout = K_FOREVER;
73 
74 	switch (buf[0]) {
75 	case BT_HCI_H4_EVT:
76 		if (buf[1] == BT_HCI_EVT_LE_META_EVENT &&
77 		    (buf[3] == BT_HCI_EVT_LE_ADVERTISING_REPORT)) {
78 			discardable = true;
79 			timeout = K_NO_WAIT;
80 		}
81 
82 		return bt_buf_get_evt(buf[1], discardable, timeout);
83 	case BT_HCI_H4_ACL:
84 		return bt_buf_get_rx(BT_BUF_ACL_IN, K_FOREVER);
85 	case BT_HCI_H4_ISO:
86 		if (IS_ENABLED(CONFIG_BT_ISO)) {
87 			return bt_buf_get_rx(BT_BUF_ISO_IN, K_FOREVER);
88 		}
89 		__fallthrough;
90 	default:
91 		LOG_ERR("Unknown packet type: %u", buf[0]);
92 	}
93 
94 	return NULL;
95 }
96 
97 /**
98  * @brief Decode the length of an HCI H4 packet and check it's complete
99  * @details Decodes packet length according to Bluetooth spec v5.4 Vol 4 Part E
100  * @param buf	Pointer to a HCI packet buffer
101  * @param buf_len	Bytes available in the buffer
102  * @return Length of the complete HCI packet in bytes, -1 if cannot find an HCI
103  *         packet, 0 if more data required.
104  */
hci_packet_complete(const uint8_t * buf,uint16_t buf_len)105 static int32_t hci_packet_complete(const uint8_t *buf, uint16_t buf_len)
106 {
107 	uint16_t payload_len = 0;
108 	const uint8_t type = buf[0];
109 	uint8_t header_len = sizeof(type);
110 	const uint8_t *hdr = &buf[sizeof(type)];
111 
112 	switch (type) {
113 	case BT_HCI_H4_CMD: {
114 		const struct bt_hci_cmd_hdr *cmd = (const struct bt_hci_cmd_hdr *)hdr;
115 
116 		/* Parameter Total Length */
117 		payload_len = cmd->param_len;
118 		header_len += BT_HCI_CMD_HDR_SIZE;
119 		break;
120 	}
121 	case BT_HCI_H4_ACL: {
122 		const struct bt_hci_acl_hdr *acl = (const struct bt_hci_acl_hdr *)hdr;
123 
124 		/* Data Total Length */
125 		payload_len = sys_le16_to_cpu(acl->len);
126 		header_len += BT_HCI_ACL_HDR_SIZE;
127 		break;
128 	}
129 	case BT_HCI_H4_SCO: {
130 		const struct bt_hci_sco_hdr *sco = (const struct bt_hci_sco_hdr *)hdr;
131 
132 		/* Data_Total_Length */
133 		payload_len = sco->len;
134 		header_len += BT_HCI_SCO_HDR_SIZE;
135 		break;
136 	}
137 	case BT_HCI_H4_EVT: {
138 		const struct bt_hci_evt_hdr *evt = (const struct bt_hci_evt_hdr *)hdr;
139 
140 		/* Parameter Total Length */
141 		payload_len = evt->len;
142 		header_len += BT_HCI_EVT_HDR_SIZE;
143 		break;
144 	}
145 	case BT_HCI_H4_ISO: {
146 		const struct bt_hci_iso_hdr *iso = (const struct bt_hci_iso_hdr *)hdr;
147 
148 		/* ISO_Data_Load_Length parameter */
149 		payload_len =  bt_iso_hdr_len(sys_le16_to_cpu(iso->len));
150 		header_len += BT_HCI_ISO_HDR_SIZE;
151 		break;
152 	}
153 	/* If no valid packet type found */
154 	default:
155 		LOG_WRN("Unknown packet type 0x%02x", type);
156 		return -1;
157 	}
158 
159 	/* Request more data */
160 	if (buf_len < header_len || buf_len - header_len < payload_len) {
161 		return 0;
162 	}
163 
164 	return (int32_t)header_len + payload_len;
165 }
166 
uc_ready(int fd)167 static bool uc_ready(int fd)
168 {
169 	struct pollfd pollfd = { .fd = fd, .events = POLLIN };
170 
171 	return (poll(&pollfd, 1, 0) == 1);
172 }
173 
rx_thread(void * p1,void * p2,void * p3)174 static void rx_thread(void *p1, void *p2, void *p3)
175 {
176 	const struct device *dev = p1;
177 	struct uc_data *uc = dev->data;
178 
179 	ARG_UNUSED(p2);
180 	ARG_UNUSED(p3);
181 
182 	LOG_DBG("started");
183 
184 	uint16_t frame_size = 0;
185 
186 	while (1) {
187 		static uint8_t frame[512];
188 		struct net_buf *buf;
189 		size_t buf_tailroom;
190 		size_t buf_add_len;
191 		ssize_t len;
192 		const uint8_t *frame_start = frame;
193 
194 		if (!uc_ready(uc->fd)) {
195 			k_sleep(K_MSEC(1));
196 			continue;
197 		}
198 
199 		LOG_DBG("calling read()");
200 
201 		len = read(uc->fd, frame + frame_size, sizeof(frame) - frame_size);
202 		if (len < 0) {
203 			if (errno == EINTR) {
204 				k_yield();
205 				continue;
206 			}
207 
208 			LOG_ERR("Reading socket failed, errno %d", errno);
209 			close(uc->fd);
210 			uc->fd = -1;
211 			return;
212 		}
213 
214 		frame_size += len;
215 
216 		while (frame_size > 0) {
217 			const uint8_t *buf_add;
218 			const uint8_t packet_type = frame_start[0];
219 			const int32_t decoded_len = hci_packet_complete(frame_start, frame_size);
220 
221 			if (decoded_len == -1) {
222 				LOG_ERR("HCI Packet type is invalid, length could not be decoded");
223 				frame_size = 0; /* Drop buffer */
224 				break;
225 			}
226 
227 			if (decoded_len == 0) {
228 				if (frame_size == sizeof(frame)) {
229 					LOG_ERR("HCI Packet (%d bytes) is too big for frame (%d "
230 						"bytes)",
231 						decoded_len, sizeof(frame));
232 					frame_size = 0; /* Drop buffer */
233 					break;
234 				}
235 				if (frame_start != frame) {
236 					memmove(frame, frame_start, frame_size);
237 				}
238 				/* Read more */
239 				break;
240 			}
241 
242 			buf_add = frame_start + sizeof(packet_type);
243 			buf_add_len = decoded_len - sizeof(packet_type);
244 
245 			buf = get_rx(frame_start);
246 
247 			frame_size -= decoded_len;
248 			frame_start += decoded_len;
249 
250 			if (!buf) {
251 				LOG_DBG("Discard adv report due to insufficient buf");
252 				continue;
253 			}
254 
255 			buf_tailroom = net_buf_tailroom(buf);
256 			if (buf_tailroom < buf_add_len) {
257 				LOG_ERR("Not enough space in buffer %zu/%zu",
258 					buf_add_len, buf_tailroom);
259 				net_buf_unref(buf);
260 				continue;
261 			}
262 
263 			net_buf_add_mem(buf, buf_add, buf_add_len);
264 
265 			LOG_DBG("Calling bt_recv(%p)", buf);
266 
267 			uc->recv(dev, buf);
268 		}
269 
270 		k_yield();
271 	}
272 }
273 
uc_send(const struct device * dev,struct net_buf * buf)274 static int uc_send(const struct device *dev, struct net_buf *buf)
275 {
276 	struct uc_data *uc = dev->data;
277 
278 	LOG_DBG("buf %p type %u len %u", buf, bt_buf_get_type(buf), buf->len);
279 
280 	if (uc->fd < 0) {
281 		LOG_ERR("User channel not open");
282 		return -EIO;
283 	}
284 
285 	switch (bt_buf_get_type(buf)) {
286 	case BT_BUF_ACL_OUT:
287 		net_buf_push_u8(buf, BT_HCI_H4_ACL);
288 		break;
289 	case BT_BUF_CMD:
290 		net_buf_push_u8(buf, BT_HCI_H4_CMD);
291 		break;
292 	case BT_BUF_ISO_OUT:
293 		if (IS_ENABLED(CONFIG_BT_ISO)) {
294 			net_buf_push_u8(buf, BT_HCI_H4_ISO);
295 			break;
296 		}
297 		__fallthrough;
298 	default:
299 		LOG_ERR("Unknown buffer type");
300 		return -EINVAL;
301 	}
302 
303 	if (write(uc->fd, buf->data, buf->len) < 0) {
304 		return -errno;
305 	}
306 
307 	net_buf_unref(buf);
308 	return 0;
309 }
310 
user_chan_open(void)311 static int user_chan_open(void)
312 {
313 	int fd;
314 
315 	if (hci_socket) {
316 		struct sockaddr_hci addr;
317 
318 		fd = socket(PF_BLUETOOTH, SOCK_RAW | SOCK_CLOEXEC | SOCK_NONBLOCK,
319 			    BTPROTO_HCI);
320 		if (fd < 0) {
321 			return -errno;
322 		}
323 
324 		(void)memset(&addr, 0, sizeof(addr));
325 		addr.hci_family = AF_BLUETOOTH;
326 		addr.hci_dev = bt_dev_index;
327 		addr.hci_channel = HCI_CHANNEL_USER;
328 
329 		if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
330 			int err = -errno;
331 
332 			close(fd);
333 			return err;
334 		}
335 	} else {
336 		struct sockaddr_in addr;
337 
338 		fd = socket(AF_INET, SOCK_STREAM, 0);
339 		if (fd < 0) {
340 			return -errno;
341 		}
342 
343 		addr.sin_family = AF_INET;
344 		addr.sin_port = htons(port);
345 		if (inet_pton(AF_INET, ip_addr, &(addr.sin_addr)) <= 0) {
346 			int err = -errno;
347 
348 			close(fd);
349 			return err;
350 		}
351 
352 		if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
353 			int err = -errno;
354 
355 			close(fd);
356 			return err;
357 		}
358 	}
359 
360 	return fd;
361 }
362 
uc_open(const struct device * dev,bt_hci_recv_t recv)363 static int uc_open(const struct device *dev, bt_hci_recv_t recv)
364 {
365 	struct uc_data *uc = dev->data;
366 
367 	if (hci_socket) {
368 		LOG_DBG("hci%d", bt_dev_index);
369 	} else {
370 		LOG_DBG("hci %s:%d", ip_addr, port);
371 	}
372 
373 	uc->fd = user_chan_open();
374 	if (uc->fd < 0) {
375 		return uc->fd;
376 	}
377 
378 	uc->recv = recv;
379 
380 	LOG_DBG("User Channel opened as fd %d", uc->fd);
381 
382 	k_thread_create(&rx_thread_data, rx_thread_stack,
383 			K_KERNEL_STACK_SIZEOF(rx_thread_stack),
384 			rx_thread, (void *)dev, NULL, NULL,
385 			K_PRIO_COOP(CONFIG_BT_DRIVER_RX_HIGH_PRIO),
386 			0, K_NO_WAIT);
387 
388 	LOG_DBG("returning");
389 
390 	return 0;
391 }
392 
393 static const struct bt_hci_driver_api uc_drv_api = {
394 	.open = uc_open,
395 	.send = uc_send,
396 };
397 
uc_init(const struct device * dev)398 static int uc_init(const struct device *dev)
399 {
400 	if (!arg_found) {
401 		posix_print_warning("Warning: Bluetooth device missing.\n"
402 				    "Specify either a local hci interface --bt-dev=hciN\n"
403 				    "or a valid hci tcp server --bt-dev=ip_address:port\n");
404 		return -ENODEV;
405 	}
406 
407 	return 0;
408 }
409 
410 #define UC_DEVICE_INIT(inst) \
411 	static struct uc_data uc_data_##inst = { \
412 		.fd = -1, \
413 	}; \
414 	DEVICE_DT_INST_DEFINE(inst, uc_init, NULL, &uc_data_##inst, NULL, \
415 			      POST_KERNEL, CONFIG_KERNEL_INIT_PRIORITY_DEVICE, &uc_drv_api)
416 
DT_INST_FOREACH_STATUS_OKAY(UC_DEVICE_INIT)417 DT_INST_FOREACH_STATUS_OKAY(UC_DEVICE_INIT)
418 
419 static void cmd_bt_dev_found(char *argv, int offset)
420 {
421 	arg_found = true;
422 	if (strncmp(&argv[offset], "hci", 3) == 0 && strlen(&argv[offset]) >= 4) {
423 		long arg_hci_idx = strtol(&argv[offset + 3], NULL, 10);
424 
425 		if (arg_hci_idx >= 0 && arg_hci_idx <= USHRT_MAX) {
426 			bt_dev_index = arg_hci_idx;
427 			hci_socket = true;
428 		} else {
429 			posix_print_error_and_exit("Invalid argument value for --bt-dev. "
430 						  "hci idx must be within range 0 to 65536.\n");
431 		}
432 	} else if (sscanf(&argv[offset], "%15[^:]:%d", ip_addr, &port) == 2) {
433 		if (port > USHRT_MAX) {
434 			posix_print_error_and_exit("Error: IP port for bluetooth "
435 						   "hci tcp server is out of range.\n");
436 		}
437 		struct in_addr addr;
438 
439 		if (inet_pton(AF_INET, ip_addr, &addr) != 1) {
440 			posix_print_error_and_exit("Error: IP address for bluetooth "
441 						   "hci tcp server is incorrect.\n");
442 		}
443 	} else {
444 		posix_print_error_and_exit("Invalid option %s for --bt-dev. "
445 					   "An hci interface or hci tcp server is expected.\n",
446 					   &argv[offset]);
447 	}
448 }
449 
add_btuserchan_arg(void)450 static void add_btuserchan_arg(void)
451 {
452 	static struct args_struct_t btuserchan_args[] = {
453 		/*
454 		 * Fields:
455 		 * manual, mandatory, switch,
456 		 * option_name, var_name ,type,
457 		 * destination, callback,
458 		 * description
459 		 */
460 		{ false, true, false,
461 		"bt-dev", "hciX", 's',
462 		NULL, cmd_bt_dev_found,
463 		"A local HCI device to be used for Bluetooth (e.g. hci0) "
464 		"or an HCI TCP Server (e.g. 127.0.0.1:9000)"},
465 		ARG_TABLE_ENDMARKER
466 	};
467 
468 	native_add_command_line_opts(btuserchan_args);
469 }
470 
471 NATIVE_TASK(add_btuserchan_arg, PRE_BOOT_1, 10);
472