xref: /freebsd/contrib/libpcap/pcap-bpf.c (revision 6780ab54325a71e7e70112b11657973edde8655e)
1 /*
2  * Copyright (c) 1993, 1994, 1995, 1996, 1998
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that: (1) source code distributions
7  * retain the above copyright notice and this paragraph in its entirety, (2)
8  * distributions including binary code include the above copyright notice and
9  * this paragraph in its entirety in the documentation or other materials
10  * provided with the distribution, and (3) all advertising materials mentioning
11  * features or use of this software display the following acknowledgement:
12  * ``This product includes software developed by the University of California,
13  * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
14  * the University nor the names of its contributors may be used to endorse
15  * or promote products derived from this software without specific prior
16  * written permission.
17  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
18  * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
19  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
20  */
21 #ifndef lint
22 static const char rcsid[] =
23     "@(#) $Header: /tcpdump/master/libpcap/pcap-bpf.c,v 1.48 2001/12/10 07:14:14 guy Exp $ (LBL)";
24 #endif
25 
26 #ifdef HAVE_CONFIG_H
27 #include "config.h"
28 #endif
29 
30 #include <sys/param.h>			/* optionally get BSD define */
31 #include <sys/time.h>
32 #include <sys/timeb.h>
33 #include <sys/socket.h>
34 #include <sys/file.h>
35 #include <sys/ioctl.h>
36 
37 #include <net/if.h>
38 #ifdef _AIX
39 /*
40  * XXX - I'm guessing here AIX defines IFT_ values in <net/if_types.h>,
41  * as BSD does.  If not, this code won't compile, but, if not, you
42  * want to send us a bug report and fall back on using DLPI.
43  * It's not as if BPF used to work right on AIX before this change;
44  * this change attempts to fix the fact that it didn't....
45  */
46 #include <net/if_types.h>		/* for IFT_ values */
47 #endif
48 
49 #include <ctype.h>
50 #include <errno.h>
51 #include <netdb.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <unistd.h>
56 
57 #include "pcap-int.h"
58 
59 #ifdef HAVE_OS_PROTO_H
60 #include "os-proto.h"
61 #endif
62 
63 #include "gencode.h"
64 
65 int
66 pcap_stats(pcap_t *p, struct pcap_stat *ps)
67 {
68 	struct bpf_stat s;
69 
70 	/*
71 	 * "ps_recv" counts packets handed to the filter, not packets
72 	 * that passed the filter.  This includes packets later dropped
73 	 * because we ran out of buffer space.
74 	 *
75 	 * "ps_drop" counts packets dropped inside the BPF device
76 	 * because we ran out of buffer space.  It doesn't count
77 	 * packets dropped by the interface driver.  It counts
78 	 * only packets that passed the filter.
79 	 *
80 	 * Both statistics include packets not yet read from the kernel
81 	 * by libpcap, and thus not yet seen by the application.
82 	 */
83 	if (ioctl(p->fd, BIOCGSTATS, (caddr_t)&s) < 0) {
84 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGSTATS: %s",
85 		    pcap_strerror(errno));
86 		return (-1);
87 	}
88 
89 	ps->ps_recv = s.bs_recv;
90 	ps->ps_drop = s.bs_drop;
91 	return (0);
92 }
93 
94 int
95 pcap_read(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
96 {
97 	int cc;
98 	int n = 0;
99 	register u_char *bp, *ep;
100 
101  again:
102 	cc = p->cc;
103 	if (p->cc == 0) {
104 		cc = read(p->fd, (char *)p->buffer, p->bufsize);
105 		if (cc < 0) {
106 			/* Don't choke when we get ptraced */
107 			switch (errno) {
108 
109 			case EINTR:
110 				goto again;
111 
112 			case EWOULDBLOCK:
113 				return (0);
114 #if defined(sun) && !defined(BSD)
115 			/*
116 			 * Due to a SunOS bug, after 2^31 bytes, the kernel
117 			 * file offset overflows and read fails with EINVAL.
118 			 * The lseek() to 0 will fix things.
119 			 */
120 			case EINVAL:
121 				if (lseek(p->fd, 0L, SEEK_CUR) +
122 				    p->bufsize < 0) {
123 					(void)lseek(p->fd, 0L, SEEK_SET);
124 					goto again;
125 				}
126 				/* fall through */
127 #endif
128 			}
129 			snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read: %s",
130 			    pcap_strerror(errno));
131 			return (-1);
132 		}
133 		bp = p->buffer;
134 	} else
135 		bp = p->bp;
136 
137 	/*
138 	 * Loop through each packet.
139 	 */
140 #define bhp ((struct bpf_hdr *)bp)
141 	ep = bp + cc;
142 	while (bp < ep) {
143 		register int caplen, hdrlen;
144 		caplen = bhp->bh_caplen;
145 		hdrlen = bhp->bh_hdrlen;
146 		/*
147 		 * XXX A bpf_hdr matches a pcap_pkthdr.
148 		 */
149 #ifdef _AIX
150 		/*
151 		 * AIX's BPF returns seconds/nanoseconds time stamps, not
152 		 * seconds/microseconds time stamps.
153 		 *
154 		 * XXX - I'm guessing here that it's a "struct timestamp";
155 		 * if not, this code won't compile, but, if not, you
156 		 * want to send us a bug report and fall back on using
157 		 * DLPI.  It's not as if BPF used to work right on
158 		 * AIX before this change; this change attempts to fix
159 		 * the fact that it didn't....
160 		 */
161 		bhp->bh_tstamp.tv_usec = bhp->bh_tstamp.tv_usec/1000;
162 #endif
163 		(*callback)(user, (struct pcap_pkthdr*)bp, bp + hdrlen);
164 		bp += BPF_WORDALIGN(caplen + hdrlen);
165 		if (++n >= cnt && cnt > 0) {
166 			p->bp = bp;
167 			p->cc = ep - bp;
168 			return (n);
169 		}
170 	}
171 #undef bhp
172 	p->cc = 0;
173 	return (n);
174 }
175 
176 static inline int
177 bpf_open(pcap_t *p, char *errbuf)
178 {
179 	int fd;
180 	int n = 0;
181 	char device[sizeof "/dev/bpf0000000000"];
182 
183 	/*
184 	 * Go through all the minors and find one that isn't in use.
185 	 */
186 	do {
187 		(void)snprintf(device, sizeof(device), "/dev/bpf%d", n++);
188 		fd = open(device, O_RDONLY);
189 	} while (fd < 0 && errno == EBUSY);
190 
191 	/*
192 	 * XXX better message for all minors used
193 	 */
194 	if (fd < 0)
195 		snprintf(errbuf, PCAP_ERRBUF_SIZE, "(no devices found) %s: %s",
196 		    device, pcap_strerror(errno));
197 
198 	return (fd);
199 }
200 
201 pcap_t *
202 pcap_open_live(char *device, int snaplen, int promisc, int to_ms, char *ebuf)
203 {
204 	int fd;
205 	struct ifreq ifr;
206 	struct bpf_version bv;
207 	struct bpf_dltlist bdl;
208 	u_int v;
209 	pcap_t *p;
210 
211 	bzero(&bdl, sizeof(bdl));
212 
213 	p = (pcap_t *)malloc(sizeof(*p));
214 	if (p == NULL) {
215 		snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
216 		    pcap_strerror(errno));
217 		return (NULL);
218 	}
219 	memset(p, 0, sizeof(*p));
220 	fd = bpf_open(p, ebuf);
221 	if (fd < 0)
222 		goto bad;
223 
224 	p->fd = fd;
225 	p->snapshot = snaplen;
226 
227 	if (ioctl(fd, BIOCVERSION, (caddr_t)&bv) < 0) {
228 		snprintf(ebuf, PCAP_ERRBUF_SIZE, "BIOCVERSION: %s",
229 		    pcap_strerror(errno));
230 		goto bad;
231 	}
232 	if (bv.bv_major != BPF_MAJOR_VERSION ||
233 	    bv.bv_minor < BPF_MINOR_VERSION) {
234 		snprintf(ebuf, PCAP_ERRBUF_SIZE,
235 		    "kernel bpf filter out of date");
236 		goto bad;
237 	}
238 
239 	/*
240 	 * Try finding a good size for the buffer; 32768 may be too
241 	 * big, so keep cutting it in half until we find a size
242 	 * that works, or run out of sizes to try.
243 	 *
244 	 * XXX - there should be a user-accessible hook to set the
245 	 * initial buffer size.
246 	 */
247 	for (v = 32768; v != 0; v >>= 1) {
248 		/* Ignore the return value - this is because the call fails
249 		 * on BPF systems that don't have kernel malloc.  And if
250 		 * the call fails, it's no big deal, we just continue to
251 		 * use the standard buffer size.
252 		 */
253 		(void) ioctl(fd, BIOCSBLEN, (caddr_t)&v);
254 
255 		(void)strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
256 		if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) >= 0)
257 			break;	/* that size worked; we're done */
258 
259 		if (errno != ENOBUFS) {
260 			snprintf(ebuf, PCAP_ERRBUF_SIZE, "BIOCSETIF: %s: %s",
261 			    device, pcap_strerror(errno));
262 			goto bad;
263 		}
264 	}
265 
266 	if (v == 0) {
267 		snprintf(ebuf, PCAP_ERRBUF_SIZE,
268 			 "BIOCSBLEN: %s: No buffer size worked", device);
269 		goto bad;
270 	}
271 
272 	/* Get the data link layer type. */
273 	if (ioctl(fd, BIOCGDLT, (caddr_t)&v) < 0) {
274 		snprintf(ebuf, PCAP_ERRBUF_SIZE, "BIOCGDLT: %s",
275 		    pcap_strerror(errno));
276 		goto bad;
277 	}
278 #ifdef _AIX
279 	/*
280 	 * AIX's BPF returns IFF_ types, not DLT_ types, in BIOCGDLT.
281 	 */
282 	switch (v) {
283 
284 	case IFT_ETHER:
285 	case IFT_ISO88023:
286 		v = DLT_EN10MB;
287 		break;
288 
289 	case IFT_FDDI:
290 		v = DLT_FDDI;
291 		break;
292 
293 	case IFT_ISO88025:
294 		v = DLT_IEEE802;
295 		break;
296 
297 	default:
298 		/*
299 		 * We don't know what to map this to yet.
300 		 */
301 		snprintf(ebuf, PCAP_ERRBUF_SIZE, "unknown interface type %lu",
302 		    v);
303 		goto bad;
304 	}
305 #endif
306 #if _BSDI_VERSION - 0 >= 199510
307 	/* The SLIP and PPP link layer header changed in BSD/OS 2.1 */
308 	switch (v) {
309 
310 	case DLT_SLIP:
311 		v = DLT_SLIP_BSDOS;
312 		break;
313 
314 	case DLT_PPP:
315 		v = DLT_PPP_BSDOS;
316 		break;
317 
318 	case 11:	/*DLT_FR*/
319 		v = DLT_RAW;	/*XXX*/
320 		break;
321 
322 	case 12:	/*DLT_C_HDLC*/
323 		v = DLT_CHDLC;
324 		break;
325 	}
326 #endif
327 	p->linktype = v;
328 
329 	/*
330 	 * We know the default link type -- now determine any additional
331 	 * DLTs this interface supports.  If this fails, it's not fatal;
332 	 * we just don't get to use the feature later.
333 	 */
334 	if (ioctl(fd, BIOCGDLTLIST, (caddr_t) &bdl) == 0) {
335 		bdl.bfl_list = (u_int *) malloc(sizeof(u_int) * bdl.bfl_len);
336 		if (bdl.bfl_list == NULL) {
337 			(void)snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
338 			    pcap_strerror(errno));
339 			goto bad;
340 		}
341 
342 		if (ioctl(fd, BIOCGDLTLIST, (caddr_t) &bdl) < 0) {
343 			(void)snprintf(ebuf, PCAP_ERRBUF_SIZE,
344 			    "BIOCGDLTLIST: %s", pcap_strerror(errno));
345 			free(bdl.bfl_list);
346 			goto bad;
347 		}
348 
349 		p->dlt_count = bdl.bfl_len;
350 		p->dlt_list = bdl.bfl_list;
351 	}
352 
353 	/* set timeout */
354 	if (to_ms != 0) {
355 		struct timeval to;
356 		to.tv_sec = to_ms / 1000;
357 		to.tv_usec = (to_ms * 1000) % 1000000;
358 		if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&to) < 0) {
359 			snprintf(ebuf, PCAP_ERRBUF_SIZE, "BIOCSRTIMEOUT: %s",
360 			    pcap_strerror(errno));
361 			goto bad;
362 		}
363 	}
364 
365 #ifdef _AIX
366 #ifdef	BIOCIMMEDIATE
367 	/*
368 	 * Darren Reed notes that
369 	 *
370 	 *	On AIX (4.2 at least), if BIOCIMMEDIATE is not set, the
371 	 *	timeout appears to be ignored and it waits until the buffer
372 	 *	is filled before returning.  The result of not having it
373 	 *	set is almost worse than useless if your BPF filter
374 	 *	is reducing things to only a few packets (i.e. one every
375 	 *	second or so).
376 	 *
377 	 * so we turn BIOCIMMEDIATE mode on if this is AIX.
378 	 *
379 	 * We don't turn it on for other platforms, as that means we
380 	 * get woken up for every packet, which may not be what we want;
381 	 * in the Winter 1993 USENIX paper on BPF, they say:
382 	 *
383 	 *	Since a process might want to look at every packet on a
384 	 *	network and the time between packets can be only a few
385 	 *	microseconds, it is not possible to do a read system call
386 	 *	per packet and BPF must collect the data from several
387 	 *	packets and return it as a unit when the monitoring
388 	 *	application does a read.
389 	 *
390 	 * which I infer is the reason for the timeout - it means we
391 	 * wait that amount of time, in the hopes that more packets
392 	 * will arrive and we'll get them all with one read.
393 	 *
394 	 * Setting BIOCIMMEDIATE mode on FreeBSD (and probably other
395 	 * BSDs) causes the timeout to be ignored.
396 	 *
397 	 * On the other hand, some platforms (e.g., Linux) don't support
398 	 * timeouts, they just hand stuff to you as soon as it arrives;
399 	 * if that doesn't cause a problem on those platforms, it may
400 	 * be OK to have BIOCIMMEDIATE mode on BSD as well.
401 	 *
402 	 * (Note, though, that applications may depend on the read
403 	 * completing, even if no packets have arrived, when the timeout
404 	 * expires, e.g. GUI applications that have to check for input
405 	 * while waiting for packets to arrive; a non-zero timeout
406 	 * prevents "select()" from working right on FreeBSD and
407 	 * possibly other BSDs, as the timer doesn't start until a
408 	 * "read()" is done, so the timer isn't in effect if the
409 	 * application is blocked on a "select()", and the "select()"
410 	 * doesn't get woken up for a BPF device until the buffer
411 	 * fills up.)
412 	 */
413 	v = 1;
414 	if (ioctl(p->fd, BIOCIMMEDIATE, &v) < 0) {
415 		snprintf(ebuf, PCAP_ERRBUF_SIZE, "BIOCIMMEDIATE: %s",
416 		    pcap_strerror(errno));
417 		goto bad;
418 	}
419 #endif	/* BIOCIMMEDIATE */
420 #endif	/* _AIX */
421 
422 	if (promisc) {
423 		/* set promiscuous mode, okay if it fails */
424 		if (ioctl(p->fd, BIOCPROMISC, NULL) < 0) {
425 			snprintf(ebuf, PCAP_ERRBUF_SIZE, "BIOCPROMISC: %s",
426 			    pcap_strerror(errno));
427 		}
428 	}
429 
430 	if (ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) {
431 		snprintf(ebuf, PCAP_ERRBUF_SIZE, "BIOCGBLEN: %s",
432 		    pcap_strerror(errno));
433 		goto bad;
434 	}
435 	p->bufsize = v;
436 	p->buffer = (u_char *)malloc(p->bufsize);
437 	if (p->buffer == NULL) {
438 		snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
439 		    pcap_strerror(errno));
440 		goto bad;
441 	}
442 
443 	return (p);
444  bad:
445 	(void)close(fd);
446 	if (bdl.bfl_list != NULL)
447 		free(bdl.bfl_list);
448 	free(p);
449 	return (NULL);
450 }
451 
452 int
453 pcap_setfilter(pcap_t *p, struct bpf_program *fp)
454 {
455 	/*
456 	 * It looks that BPF code generated by gen_protochain() is not
457 	 * compatible with some of kernel BPF code (for example BSD/OS 3.1).
458 	 * Take a safer side for now.
459 	 */
460 	if (no_optimize) {
461 		if (install_bpf_program(p, fp) < 0)
462 			return (-1);
463 	} else if (p->sf.rfile != NULL) {
464 		if (install_bpf_program(p, fp) < 0)
465 			return (-1);
466 	} else if (ioctl(p->fd, BIOCSETF, (caddr_t)fp) < 0) {
467 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETF: %s",
468 		    pcap_strerror(errno));
469 		return (-1);
470 	}
471 	return (0);
472 }
473 
474 int
475 pcap_set_datalink(pcap_t *p, int dlt)
476 {
477 	int i;
478 
479 	for (i = 0; i < p->dlt_count; i++)
480 		if (p->dlt_list[i] == dlt)
481 			break;
482 	if (i >= p->dlt_count) {
483 		(void) snprintf(p->errbuf, sizeof(p->errbuf),
484 		    "No such DLT as %d", dlt);
485 		return -1;
486 	}
487 	if (ioctl(p->fd, BIOCSDLT, &dlt) == -1) {
488 		(void) snprintf(p->errbuf, sizeof(p->errbuf),
489 		    "Cannot set DLT %d: %s", dlt, strerror(errno));
490 		return -1;
491 	}
492 	p->linktype = dlt;
493 	return 0;
494 }
495