xref: /freebsd/contrib/libpcap/pcap-bpf.c (revision a3e8fd0b7f663db7eafff527d5c3ca3bcfa8a537)
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 	u_int v;
208 	pcap_t *p;
209 
210 	p = (pcap_t *)malloc(sizeof(*p));
211 	if (p == NULL) {
212 		snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
213 		    pcap_strerror(errno));
214 		return (NULL);
215 	}
216 	memset(p, 0, sizeof(*p));
217 	fd = bpf_open(p, ebuf);
218 	if (fd < 0)
219 		goto bad;
220 
221 	p->fd = fd;
222 	p->snapshot = snaplen;
223 
224 	if (ioctl(fd, BIOCVERSION, (caddr_t)&bv) < 0) {
225 		snprintf(ebuf, PCAP_ERRBUF_SIZE, "BIOCVERSION: %s",
226 		    pcap_strerror(errno));
227 		goto bad;
228 	}
229 	if (bv.bv_major != BPF_MAJOR_VERSION ||
230 	    bv.bv_minor < BPF_MINOR_VERSION) {
231 		snprintf(ebuf, PCAP_ERRBUF_SIZE,
232 		    "kernel bpf filter out of date");
233 		goto bad;
234 	}
235 
236 	/*
237 	 * Try finding a good size for the buffer; 32768 may be too
238 	 * big, so keep cutting it in half until we find a size
239 	 * that works, or run out of sizes to try.
240 	 *
241 	 * XXX - there should be a user-accessible hook to set the
242 	 * initial buffer size.
243 	 */
244 	for (v = 32768; v != 0; v >>= 1) {
245 		/* Ignore the return value - this is because the call fails
246 		 * on BPF systems that don't have kernel malloc.  And if
247 		 * the call fails, it's no big deal, we just continue to
248 		 * use the standard buffer size.
249 		 */
250 		(void) ioctl(fd, BIOCSBLEN, (caddr_t)&v);
251 
252 		(void)strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
253 		if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) >= 0)
254 			break;	/* that size worked; we're done */
255 
256 		if (errno != ENOBUFS) {
257 			snprintf(ebuf, PCAP_ERRBUF_SIZE, "BIOCSETIF: %s: %s",
258 			    device, pcap_strerror(errno));
259 			goto bad;
260 		}
261 	}
262 
263 	if (v == 0) {
264 		snprintf(ebuf, PCAP_ERRBUF_SIZE,
265 			 "BIOCSBLEN: %s: No buffer size worked", device);
266 		goto bad;
267 	}
268 
269 	/* Get the data link layer type. */
270 	if (ioctl(fd, BIOCGDLT, (caddr_t)&v) < 0) {
271 		snprintf(ebuf, PCAP_ERRBUF_SIZE, "BIOCGDLT: %s",
272 		    pcap_strerror(errno));
273 		goto bad;
274 	}
275 #ifdef _AIX
276 	/*
277 	 * AIX's BPF returns IFF_ types, not DLT_ types, in BIOCGDLT.
278 	 */
279 	switch (v) {
280 
281 	case IFT_ETHER:
282 	case IFT_ISO88023:
283 		v = DLT_EN10MB;
284 		break;
285 
286 	case IFT_FDDI:
287 		v = DLT_FDDI;
288 		break;
289 
290 	case IFT_ISO88025:
291 		v = DLT_IEEE802;
292 		break;
293 
294 	default:
295 		/*
296 		 * We don't know what to map this to yet.
297 		 */
298 		snprintf(ebuf, PCAP_ERRBUF_SIZE, "unknown interface type %lu",
299 		    v);
300 		goto bad;
301 	}
302 #endif
303 #if _BSDI_VERSION - 0 >= 199510
304 	/* The SLIP and PPP link layer header changed in BSD/OS 2.1 */
305 	switch (v) {
306 
307 	case DLT_SLIP:
308 		v = DLT_SLIP_BSDOS;
309 		break;
310 
311 	case DLT_PPP:
312 		v = DLT_PPP_BSDOS;
313 		break;
314 
315 	case 11:	/*DLT_FR*/
316 		v = DLT_RAW;	/*XXX*/
317 		break;
318 
319 	case 12:	/*DLT_C_HDLC*/
320 		v = DLT_CHDLC;
321 		break;
322 	}
323 #endif
324 	p->linktype = v;
325 
326 	/* set timeout */
327 	if (to_ms != 0) {
328 		struct timeval to;
329 		to.tv_sec = to_ms / 1000;
330 		to.tv_usec = (to_ms * 1000) % 1000000;
331 		if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&to) < 0) {
332 			snprintf(ebuf, PCAP_ERRBUF_SIZE, "BIOCSRTIMEOUT: %s",
333 			    pcap_strerror(errno));
334 			goto bad;
335 		}
336 	}
337 
338 #ifdef _AIX
339 #ifdef	BIOCIMMEDIATE
340 	/*
341 	 * Darren Reed notes that
342 	 *
343 	 *	On AIX (4.2 at least), if BIOCIMMEDIATE is not set, the
344 	 *	timeout appears to be ignored and it waits until the buffer
345 	 *	is filled before returning.  The result of not having it
346 	 *	set is almost worse than useless if your BPF filter
347 	 *	is reducing things to only a few packets (i.e. one every
348 	 *	second or so).
349 	 *
350 	 * so we turn BIOCIMMEDIATE mode on if this is AIX.
351 	 *
352 	 * We don't turn it on for other platforms, as that means we
353 	 * get woken up for every packet, which may not be what we want;
354 	 * in the Winter 1993 USENIX paper on BPF, they say:
355 	 *
356 	 *	Since a process might want to look at every packet on a
357 	 *	network and the time between packets can be only a few
358 	 *	microseconds, it is not possible to do a read system call
359 	 *	per packet and BPF must collect the data from several
360 	 *	packets and return it as a unit when the monitoring
361 	 *	application does a read.
362 	 *
363 	 * which I infer is the reason for the timeout - it means we
364 	 * wait that amount of time, in the hopes that more packets
365 	 * will arrive and we'll get them all with one read.
366 	 *
367 	 * Setting BIOCIMMEDIATE mode on FreeBSD (and probably other
368 	 * BSDs) causes the timeout to be ignored.
369 	 *
370 	 * On the other hand, some platforms (e.g., Linux) don't support
371 	 * timeouts, they just hand stuff to you as soon as it arrives;
372 	 * if that doesn't cause a problem on those platforms, it may
373 	 * be OK to have BIOCIMMEDIATE mode on BSD as well.
374 	 *
375 	 * (Note, though, that applications may depend on the read
376 	 * completing, even if no packets have arrived, when the timeout
377 	 * expires, e.g. GUI applications that have to check for input
378 	 * while waiting for packets to arrive; a non-zero timeout
379 	 * prevents "select()" from working right on FreeBSD and
380 	 * possibly other BSDs, as the timer doesn't start until a
381 	 * "read()" is done, so the timer isn't in effect if the
382 	 * application is blocked on a "select()", and the "select()"
383 	 * doesn't get woken up for a BPF device until the buffer
384 	 * fills up.)
385 	 */
386 	v = 1;
387 	if (ioctl(p->fd, BIOCIMMEDIATE, &v) < 0) {
388 		snprintf(ebuf, PCAP_ERRBUF_SIZE, "BIOCIMMEDIATE: %s",
389 		    pcap_strerror(errno));
390 		goto bad;
391 	}
392 #endif	/* BIOCIMMEDIATE */
393 #endif	/* _AIX */
394 
395 	if (promisc) {
396 		/* set promiscuous mode, okay if it fails */
397 		if (ioctl(p->fd, BIOCPROMISC, NULL) < 0) {
398 			snprintf(ebuf, PCAP_ERRBUF_SIZE, "BIOCPROMISC: %s",
399 			    pcap_strerror(errno));
400 		}
401 	}
402 
403 	if (ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) {
404 		snprintf(ebuf, PCAP_ERRBUF_SIZE, "BIOCGBLEN: %s",
405 		    pcap_strerror(errno));
406 		goto bad;
407 	}
408 	p->bufsize = v;
409 	p->buffer = (u_char *)malloc(p->bufsize);
410 	if (p->buffer == NULL) {
411 		snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
412 		    pcap_strerror(errno));
413 		goto bad;
414 	}
415 
416 	return (p);
417  bad:
418 	(void)close(fd);
419 	free(p);
420 	return (NULL);
421 }
422 
423 int
424 pcap_setfilter(pcap_t *p, struct bpf_program *fp)
425 {
426 	/*
427 	 * It looks that BPF code generated by gen_protochain() is not
428 	 * compatible with some of kernel BPF code (for example BSD/OS 3.1).
429 	 * Take a safer side for now.
430 	 */
431 	if (no_optimize) {
432 		if (install_bpf_program(p, fp) < 0)
433 			return (-1);
434 	} else if (p->sf.rfile != NULL) {
435 		if (install_bpf_program(p, fp) < 0)
436 			return (-1);
437 	} else if (ioctl(p->fd, BIOCSETF, (caddr_t)fp) < 0) {
438 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETF: %s",
439 		    pcap_strerror(errno));
440 		return (-1);
441 	}
442 	return (0);
443 }
444