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