xref: /freebsd/contrib/libpcap/pcap-bt-linux.c (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1 /*
2  * Copyright (c) 2006 Paolo Abeni (Italy)
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  * notice, this list of conditions and the following disclaimer in the
13  * documentation and/or other materials provided with the distribution.
14  * 3. The name of the author may not be used to endorse or promote
15  * products derived from this software without specific prior written
16  * permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  *
30  * Bluetooth sniffing API implementation for Linux platform
31  * By Paolo Abeni <paolo.abeni@email.it>
32  *
33  */
34 
35 #include <config.h>
36 
37 #include "pcap-int.h"
38 #include "pcap-bt-linux.h"
39 #include "pcap/bluetooth.h"
40 #include "diag-control.h"
41 
42 #include <errno.h>
43 #include <stdlib.h>
44 #include <unistd.h>
45 #include <fcntl.h>
46 #include <string.h>
47 #include <sys/ioctl.h>
48 #include <sys/socket.h>
49 #include <arpa/inet.h>
50 
51 #include <bluetooth/bluetooth.h>
52 #include <bluetooth/hci.h>
53 
54 #define BT_IFACE "bluetooth"
55 #define BT_CTRL_SIZE 128
56 
57 /* forward declaration */
58 static int bt_activate(pcap_t *);
59 static int bt_read_linux(pcap_t *, int , pcap_handler , u_char *);
60 static int bt_inject_linux(pcap_t *, const void *, int);
61 static int bt_setdirection_linux(pcap_t *, pcap_direction_t);
62 static int bt_stats_linux(pcap_t *, struct pcap_stat *);
63 
64 /*
65  * Private data for capturing on Linux Bluetooth devices.
66  */
67 struct pcap_bt {
68 	int dev_id;		/* device ID of device we're bound to */
69 };
70 
71 int
72 bt_findalldevs(pcap_if_list_t *devlistp, char *err_str)
73 {
74 	struct hci_dev_list_req *dev_list;
75 	struct hci_dev_req *dev_req;
76 	int sock;
77 	unsigned i;
78 	int ret = 0;
79 
80 	sock  = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI);
81 	if (sock < 0)
82 	{
83 		/* if bluetooth is not supported this is not fatal*/
84 		if (errno == EAFNOSUPPORT)
85 			return 0;
86 		pcapint_fmt_errmsg_for_errno(err_str, PCAP_ERRBUF_SIZE,
87 		    errno, "Can't open raw Bluetooth socket");
88 		return PCAP_ERROR;
89 	}
90 
91 	dev_list = malloc(HCI_MAX_DEV * sizeof(*dev_req) + sizeof(*dev_list));
92 	if (!dev_list)
93 	{
94 		snprintf(err_str, PCAP_ERRBUF_SIZE, "Can't allocate %zu bytes for Bluetooth device list",
95 			HCI_MAX_DEV * sizeof(*dev_req) + sizeof(*dev_list));
96 		ret = PCAP_ERROR;
97 		goto done;
98 	}
99 
100 	/*
101 	 * Zero the complete header, which is larger than dev_num because of tail
102 	 * padding, to silence Valgrind, which overshoots validating that dev_num
103 	 * has been set.
104 	 * https://github.com/the-tcpdump-group/libpcap/issues/1083
105 	 * https://bugs.kde.org/show_bug.cgi?id=448464
106 	 */
107 	memset(dev_list, 0, sizeof(*dev_list));
108 	dev_list->dev_num = HCI_MAX_DEV;
109 
110 	if (ioctl(sock, HCIGETDEVLIST, (void *) dev_list) < 0)
111 	{
112 		pcapint_fmt_errmsg_for_errno(err_str, PCAP_ERRBUF_SIZE,
113 		    errno, "Can't get Bluetooth device list via ioctl");
114 		ret = PCAP_ERROR;
115 		goto free;
116 	}
117 
118 	dev_req = dev_list->dev_req;
119 	for (i = 0; i < dev_list->dev_num; i++, dev_req++) {
120 		char dev_name[20], dev_descr[40];
121 
122 		snprintf(dev_name, sizeof(dev_name), BT_IFACE"%u", dev_req->dev_id);
123 		snprintf(dev_descr, sizeof(dev_descr), "Bluetooth adapter number %u", i);
124 
125 		/*
126 		 * Bluetooth is a wireless technology.
127 		 * XXX - if there's the notion of associating with a
128 		 * network, and we can determine whether the interface
129 		 * is associated with a network, check that and set
130 		 * the status to PCAP_IF_CONNECTION_STATUS_CONNECTED
131 		 * or PCAP_IF_CONNECTION_STATUS_DISCONNECTED.
132 		 */
133 		if (pcapint_add_dev(devlistp, dev_name, PCAP_IF_WIRELESS, dev_descr, err_str)  == NULL)
134 		{
135 			ret = PCAP_ERROR;
136 			break;
137 		}
138 	}
139 
140 free:
141 	free(dev_list);
142 
143 done:
144 	close(sock);
145 	return ret;
146 }
147 
148 pcap_t *
149 bt_create(const char *device, char *ebuf, int *is_ours)
150 {
151 	const char *cp;
152 	char *cpend;
153 	long devnum;
154 	pcap_t *p;
155 
156 	/* Does this look like a Bluetooth device? */
157 	cp = strrchr(device, '/');
158 	if (cp == NULL)
159 		cp = device;
160 	/* Does it begin with BT_IFACE? */
161 	if (strncmp(cp, BT_IFACE, sizeof BT_IFACE - 1) != 0) {
162 		/* Nope, doesn't begin with BT_IFACE */
163 		*is_ours = 0;
164 		return NULL;
165 	}
166 	/* Yes - is BT_IFACE followed by a number? */
167 	cp += sizeof BT_IFACE - 1;
168 	devnum = strtol(cp, &cpend, 10);
169 	if (cpend == cp || *cpend != '\0') {
170 		/* Not followed by a number. */
171 		*is_ours = 0;
172 		return NULL;
173 	}
174 	if (devnum < 0) {
175 		/* Followed by a non-valid number. */
176 		*is_ours = 0;
177 		return NULL;
178 	}
179 
180 	/* OK, it's probably ours. */
181 	*is_ours = 1;
182 
183 	p = PCAP_CREATE_COMMON(ebuf, struct pcap_bt);
184 	if (p == NULL)
185 		return (NULL);
186 
187 	p->activate_op = bt_activate;
188 	return (p);
189 }
190 
191 static int
192 bt_activate(pcap_t* handle)
193 {
194 	struct pcap_bt *handlep = handle->priv;
195 	struct sockaddr_hci addr;
196 	int opt;
197 	int		dev_id;
198 	struct hci_filter	flt;
199 	int err = PCAP_ERROR;
200 
201 	/* get bt interface id */
202 	if (sscanf(handle->opt.device, BT_IFACE"%d", &dev_id) != 1)
203 	{
204 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
205 			"Can't get Bluetooth device index from %s",
206 			 handle->opt.device);
207 		return PCAP_ERROR;
208 	}
209 
210 	/*
211 	 * Turn a negative snapshot value (invalid), a snapshot value of
212 	 * 0 (unspecified), or a value bigger than the normal maximum
213 	 * value, into the maximum allowed value.
214 	 *
215 	 * If some application really *needs* a bigger snapshot
216 	 * length, we should just increase MAXIMUM_SNAPLEN.
217 	 */
218 	if (handle->snapshot <= 0 || handle->snapshot > MAXIMUM_SNAPLEN)
219 		handle->snapshot = MAXIMUM_SNAPLEN;
220 
221 	/* Initialize some components of the pcap structure. */
222 	handle->bufsize = BT_CTRL_SIZE+sizeof(pcap_bluetooth_h4_header)+handle->snapshot;
223 	handle->linktype = DLT_BLUETOOTH_HCI_H4_WITH_PHDR;
224 
225 	handle->read_op = bt_read_linux;
226 	handle->inject_op = bt_inject_linux;
227 	handle->setfilter_op = pcapint_install_bpf_program; /* no kernel filtering */
228 	handle->setdirection_op = bt_setdirection_linux;
229 	handle->set_datalink_op = NULL;	/* can't change data link type */
230 	handle->getnonblock_op = pcapint_getnonblock_fd;
231 	handle->setnonblock_op = pcapint_setnonblock_fd;
232 	handle->stats_op = bt_stats_linux;
233 	handlep->dev_id = dev_id;
234 
235 	/* Create HCI socket */
236 	handle->fd = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI);
237 	if (handle->fd < 0) {
238 		pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
239 		    errno, "Can't create raw socket");
240 		return PCAP_ERROR;
241 	}
242 
243 	handle->buffer = malloc(handle->bufsize);
244 	if (!handle->buffer) {
245 		pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
246 		    errno, "Can't allocate dump buffer");
247 		goto close_fail;
248 	}
249 
250 	opt = 1;
251 	if (setsockopt(handle->fd, SOL_HCI, HCI_DATA_DIR, &opt, sizeof(opt)) < 0) {
252 		pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
253 		    errno, "Can't enable data direction info");
254 		goto close_fail;
255 	}
256 
257 	opt = 1;
258 	if (setsockopt(handle->fd, SOL_HCI, HCI_TIME_STAMP, &opt, sizeof(opt)) < 0) {
259 		pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
260 		    errno, "Can't enable time stamp");
261 		goto close_fail;
262 	}
263 
264 	/* Setup filter, do not call hci function to avoid dependence on
265 	 * external libs	*/
266 	memset(&flt, 0, sizeof(flt));
267 	memset((void *) &flt.type_mask, 0xff, sizeof(flt.type_mask));
268 	memset((void *) &flt.event_mask, 0xff, sizeof(flt.event_mask));
269 	if (setsockopt(handle->fd, SOL_HCI, HCI_FILTER, &flt, sizeof(flt)) < 0) {
270 		pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
271 		    errno, "Can't set filter");
272 		goto close_fail;
273 	}
274 
275 
276 	/* Bind socket to the HCI device */
277 	addr.hci_family = AF_BLUETOOTH;
278 	addr.hci_dev = handlep->dev_id;
279 #ifdef HAVE_STRUCT_SOCKADDR_HCI_HCI_CHANNEL
280 	addr.hci_channel = HCI_CHANNEL_RAW;
281 #endif
282 	if (bind(handle->fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
283 		pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
284 		    errno, "Can't attach to device %d", handlep->dev_id);
285 		goto close_fail;
286 	}
287 
288 	if (handle->opt.rfmon) {
289 		/*
290 		 * Monitor mode doesn't apply to Bluetooth devices.
291 		 */
292 		err = PCAP_ERROR_RFMON_NOTSUP;
293 		goto close_fail;
294 	}
295 
296 	if (handle->opt.buffer_size != 0) {
297 		/*
298 		 * Set the socket buffer size to the specified value.
299 		 */
300 		if (setsockopt(handle->fd, SOL_SOCKET, SO_RCVBUF,
301 		    &handle->opt.buffer_size,
302 		    sizeof(handle->opt.buffer_size)) == -1) {
303 			pcapint_fmt_errmsg_for_errno(handle->errbuf,
304 			    errno, PCAP_ERRBUF_SIZE, "SO_RCVBUF");
305 			goto close_fail;
306 		}
307 	}
308 
309 	handle->selectable_fd = handle->fd;
310 	return 0;
311 
312 close_fail:
313 	pcapint_cleanup_live_common(handle);
314 	return err;
315 }
316 
317 static int
318 bt_read_linux(pcap_t *handle, int max_packets _U_, pcap_handler callback, u_char *user)
319 {
320 	struct cmsghdr *cmsg;
321 	struct msghdr msg;
322 	struct iovec  iv;
323 	ssize_t ret;
324 	struct pcap_pkthdr pkth;
325 	pcap_bluetooth_h4_header* bthdr;
326 	u_char *pktd;
327 	int in = 0;
328 
329 	pktd = (u_char *)handle->buffer + BT_CTRL_SIZE;
330 	bthdr = (pcap_bluetooth_h4_header*)(void *)pktd;
331 	iv.iov_base = pktd + sizeof(pcap_bluetooth_h4_header);
332 	iv.iov_len  = handle->snapshot;
333 
334 	memset(&msg, 0, sizeof(msg));
335 	msg.msg_iov = &iv;
336 	msg.msg_iovlen = 1;
337 	msg.msg_control = handle->buffer;
338 	msg.msg_controllen = BT_CTRL_SIZE;
339 
340 	/* ignore interrupt system call error */
341 	do {
342 		if (handle->break_loop)
343 		{
344 			handle->break_loop = 0;
345 			return PCAP_ERROR_BREAK;
346 		}
347 		ret = recvmsg(handle->fd, &msg, 0);
348 	} while ((ret == -1) && (errno == EINTR));
349 
350 	if (ret < 0) {
351 		if (errno == EAGAIN || errno == EWOULDBLOCK) {
352 			/* Nonblocking mode, no data */
353 			return 0;
354 		}
355 		pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
356 		    errno, "Can't receive packet");
357 		return PCAP_ERROR;
358 	}
359 
360 	pkth.caplen = (bpf_u_int32)ret;
361 
362 	/* get direction and timestamp*/
363 	cmsg = CMSG_FIRSTHDR(&msg);
364 	while (cmsg) {
365 		switch (cmsg->cmsg_type) {
366 			case HCI_CMSG_DIR:
367 				memcpy(&in, CMSG_DATA(cmsg), sizeof in);
368 				break;
369 			case HCI_CMSG_TSTAMP:
370 				memcpy(&pkth.ts, CMSG_DATA(cmsg),
371 					sizeof pkth.ts);
372 				break;
373 		}
374 		// for musl libc CMSG_NXTHDR()
375 DIAG_OFF_SIGN_COMPARE
376 		cmsg = CMSG_NXTHDR(&msg, cmsg);
377 DIAG_ON_SIGN_COMPARE
378 	}
379 	switch (handle->direction) {
380 
381 	case PCAP_D_IN:
382 		if (!in)
383 			return 0;
384 		break;
385 
386 	case PCAP_D_OUT:
387 		if (in)
388 			return 0;
389 		break;
390 
391 	default:
392 		break;
393 	}
394 
395 	bthdr->direction = htonl(in != 0);
396 	pkth.caplen+=sizeof(pcap_bluetooth_h4_header);
397 	pkth.len = pkth.caplen;
398 	if (handle->fcode.bf_insns == NULL ||
399 	    pcapint_filter(handle->fcode.bf_insns, pktd, pkth.len, pkth.caplen)) {
400 		callback(user, &pkth, pktd);
401 		return 1;
402 	}
403 	return 0;	/* didn't pass filter */
404 }
405 
406 static int
407 bt_inject_linux(pcap_t *handle, const void *buf _U_, int size _U_)
408 {
409 	snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
410 	    "Packet injection is not supported on Bluetooth devices");
411 	return (-1);
412 }
413 
414 
415 static int
416 bt_stats_linux(pcap_t *handle, struct pcap_stat *stats)
417 {
418 	struct pcap_bt *handlep = handle->priv;
419 	int ret;
420 	struct hci_dev_info dev_info;
421 	struct hci_dev_stats * s = &dev_info.stat;
422 	dev_info.dev_id = handlep->dev_id;
423 
424 	/* ignore eintr */
425 	do {
426 		ret = ioctl(handle->fd, HCIGETDEVINFO, (void *)&dev_info);
427 	} while ((ret == -1) && (errno == EINTR));
428 
429 	if (ret < 0) {
430 		pcapint_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
431 		    errno, "Can't get stats via ioctl");
432 		return (-1);
433 
434 	}
435 
436 	/* we receive both rx and tx frames, so cumulate all stats */
437 	stats->ps_recv = s->evt_rx + s->acl_rx + s->sco_rx + s->cmd_tx +
438 		s->acl_tx +s->sco_tx;
439 	stats->ps_drop = s->err_rx + s->err_tx;
440 	stats->ps_ifdrop = 0;
441 	return 0;
442 }
443 
444 static int
445 bt_setdirection_linux(pcap_t *p, pcap_direction_t d)
446 {
447 	/*
448 	 * It's guaranteed, at this point, that d is a valid
449 	 * direction value.
450 	 */
451 	p->direction = d;
452 	return 0;
453 }
454