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