xref: /freebsd/contrib/libpcap/pcap-snit.c (revision 54521a2ff93ae06c95c31f79f89dc23c9b51c20b)
1 /*
2  * Copyright (c) 1990, 1991, 1992, 1993, 1994, 1995, 1996
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  * Modifications made to accommodate the new SunOS4.0 NIT facility by
22  * Micky Liu, micky@cunixc.cc.columbia.edu, Columbia University in May, 1989.
23  * This module now handles the STREAMS based NIT.
24  */
25 
26 #include <config.h>
27 
28 #include <sys/types.h>
29 #include <sys/time.h>
30 #include <sys/timeb.h>
31 #include <sys/dir.h>
32 #include <sys/fcntlcom.h>
33 #include <sys/file.h>
34 #include <sys/ioctl.h>
35 #include <sys/socket.h>
36 #include <sys/stropts.h>
37 
38 #include <net/if.h>
39 #include <net/nit.h>
40 #include <net/nit_if.h>
41 #include <net/nit_pf.h>
42 #include <net/nit_buf.h>
43 
44 #include <netinet/in.h>
45 #include <netinet/in_systm.h>
46 #include <netinet/ip.h>
47 #include <netinet/if_ether.h>
48 #include <netinet/ip_var.h>
49 #include <netinet/udp.h>
50 #include <netinet/udp_var.h>
51 #include <netinet/tcp.h>
52 #include <netinet/tcpip.h>
53 
54 #include <errno.h>
55 #include <stdio.h>
56 #include <string.h>
57 #include <unistd.h>
58 
59 #include "pcap-int.h"
60 
61 #ifdef HAVE_OS_PROTO_H
62 #include "os-proto.h"
63 #endif
64 
65 /*
66  * The chunk size for NIT.  This is the amount of buffering
67  * done for read calls.
68  */
69 #define CHUNKSIZE (2*1024)
70 
71 /*
72  * The total buffer space used by NIT.
73  */
74 #define BUFSPACE (4*CHUNKSIZE)
75 
76 /* Forwards */
77 static int nit_setflags(int, int, int, char *);
78 
79 /*
80  * Private data for capturing on STREAMS NIT devices.
81  */
82 struct pcap_snit {
83 	struct pcap_stat stat;
84 };
85 
86 static int
87 pcap_stats_snit(pcap_t *p, struct pcap_stat *ps)
88 {
89 	struct pcap_snit *psn = p->priv;
90 
91 	/*
92 	 * "ps_recv" counts packets handed to the filter, not packets
93 	 * that passed the filter.  As filtering is done in userland,
94 	 * this does not include packets dropped because we ran out
95 	 * of buffer space.
96 	 *
97 	 * "ps_drop" counts packets dropped inside the "/dev/nit"
98 	 * device because of flow control requirements or resource
99 	 * exhaustion; it doesn't count packets dropped by the
100 	 * interface driver, or packets dropped upstream.  As filtering
101 	 * is done in userland, it counts packets regardless of whether
102 	 * they would've passed the filter.
103 	 *
104 	 * These statistics don't include packets not yet read from the
105 	 * kernel by libpcap or packets not yet read from libpcap by the
106 	 * application.
107 	 */
108 	*ps = psn->stat;
109 	return (0);
110 }
111 
112 static int
113 pcap_read_snit(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
114 {
115 	struct pcap_snit *psn = p->priv;
116 	register int cc, n;
117 	register u_char *bp, *cp, *ep;
118 	register struct nit_bufhdr *hdrp;
119 	register struct nit_iftime *ntp;
120 	register struct nit_iflen *nlp;
121 	register struct nit_ifdrops *ndp;
122 	register int caplen;
123 
124 	cc = p->cc;
125 	if (cc == 0) {
126 		cc = read(p->fd, (char *)p->buffer, p->bufsize);
127 		if (cc < 0) {
128 			if (errno == EWOULDBLOCK)
129 				return (0);
130 			pcapint_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf),
131 			    errno, "pcap_read");
132 			return (-1);
133 		}
134 		bp = (u_char *)p->buffer;
135 	} else
136 		bp = p->bp;
137 
138 	/*
139 	 * loop through each snapshot in the chunk
140 	 *
141 	 * This assumes that a single buffer of packets will have
142 	 * <= INT_MAX packets, so the packet count doesn't overflow.
143 	 */
144 	n = 0;
145 	ep = bp + cc;
146 	while (bp < ep) {
147 		/*
148 		 * Has "pcap_breakloop()" been called?
149 		 * If so, return immediately - if we haven't read any
150 		 * packets, clear the flag and return -2 to indicate
151 		 * that we were told to break out of the loop, otherwise
152 		 * leave the flag set, so that the *next* call will break
153 		 * out of the loop without having read any packets, and
154 		 * return the number of packets we've processed so far.
155 		 */
156 		if (p->break_loop) {
157 			if (n == 0) {
158 				p->break_loop = 0;
159 				return (-2);
160 			} else {
161 				p->bp = bp;
162 				p->cc = ep - bp;
163 				return (n);
164 			}
165 		}
166 
167 		++psn->stat.ps_recv;
168 		cp = bp;
169 
170 		/* get past NIT buffer  */
171 		hdrp = (struct nit_bufhdr *)cp;
172 		cp += sizeof(*hdrp);
173 
174 		/* get past NIT timer   */
175 		ntp = (struct nit_iftime *)cp;
176 		cp += sizeof(*ntp);
177 
178 		ndp = (struct nit_ifdrops *)cp;
179 		psn->stat.ps_drop = ndp->nh_drops;
180 		cp += sizeof *ndp;
181 
182 		/* get past packet len  */
183 		nlp = (struct nit_iflen *)cp;
184 		cp += sizeof(*nlp);
185 
186 		/* next snapshot        */
187 		bp += hdrp->nhb_totlen;
188 
189 		caplen = nlp->nh_pktlen;
190 		if (caplen > p->snapshot)
191 			caplen = p->snapshot;
192 
193 		if (pcapint_filter(p->fcode.bf_insns, cp, nlp->nh_pktlen, caplen)) {
194 			struct pcap_pkthdr h;
195 			h.ts = ntp->nh_timestamp;
196 			h.len = nlp->nh_pktlen;
197 			h.caplen = caplen;
198 			(*callback)(user, &h, cp);
199 			if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt)) {
200 				p->cc = ep - bp;
201 				p->bp = bp;
202 				return (n);
203 			}
204 		}
205 	}
206 	p->cc = 0;
207 	return (n);
208 }
209 
210 static int
211 pcap_inject_snit(pcap_t *p, const void *buf, int size)
212 {
213 	struct strbuf ctl, data;
214 
215 	/*
216 	 * XXX - can we just do
217 	 *
218 	ret = write(pd->f, buf, size);
219 	 */
220 	ctl.len = sizeof(*sa);	/* XXX - what was this? */
221 	ctl.buf = (char *)sa;
222 	data.buf = buf;
223 	data.len = size;
224 	ret = putmsg(p->fd, &ctl, &data);
225 	if (ret == -1) {
226 		pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
227 		    errno, "send");
228 		return (-1);
229 	}
230 	return (ret);
231 }
232 
233 static int
234 nit_setflags(pcap_t *p)
235 {
236 	bpf_u_int32 flags;
237 	struct strioctl si;
238 	u_int zero = 0;
239 	struct timeval timeout;
240 
241 	if (p->opt.immediate) {
242 		/*
243 		 * Set the chunk size to zero, so that chunks get sent
244 		 * up immediately.
245 		 */
246 		si.ic_cmd = NIOCSCHUNK;
247 		si.ic_len = sizeof(zero);
248 		si.ic_dp = (char *)&zero;
249 		if (ioctl(p->fd, I_STR, (char *)&si) < 0) {
250 			pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
251 			    errno, "NIOCSCHUNK");
252 			return (-1);
253 		}
254 	}
255 	si.ic_timout = INFTIM;
256 	if (p->opt.timeout != 0) {
257 		timeout.tv_sec = p->opt.timeout / 1000;
258 		timeout.tv_usec = (p->opt.timeout * 1000) % 1000000;
259 		si.ic_cmd = NIOCSTIME;
260 		si.ic_len = sizeof(timeout);
261 		si.ic_dp = (char *)&timeout;
262 		if (ioctl(p->fd, I_STR, (char *)&si) < 0) {
263 			pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
264 			    errno, "NIOCSTIME");
265 			return (-1);
266 		}
267 	}
268 	flags = NI_TIMESTAMP | NI_LEN | NI_DROPS;
269 	if (p->opt.promisc)
270 		flags |= NI_PROMISC;
271 	si.ic_cmd = NIOCSFLAGS;
272 	si.ic_len = sizeof(flags);
273 	si.ic_dp = (char *)&flags;
274 	if (ioctl(p->fd, I_STR, (char *)&si) < 0) {
275 		pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
276 		    errno, "NIOCSFLAGS");
277 		return (-1);
278 	}
279 	return (0);
280 }
281 
282 static int
283 pcap_activate_snit(pcap_t *p)
284 {
285 	struct strioctl si;		/* struct for ioctl() */
286 	struct ifreq ifr;		/* interface request struct */
287 	int chunksize = CHUNKSIZE;
288 	int fd;
289 	static const char dev[] = "/dev/nit";
290 	int err;
291 
292 	if (p->opt.rfmon) {
293 		/*
294 		 * No monitor mode on SunOS 4.x (no Wi-Fi devices on
295 		 * hardware supported by SunOS 4.x).
296 		 */
297 		return (PCAP_ERROR_RFMON_NOTSUP);
298 	}
299 
300 	/*
301 	 * Turn a negative snapshot value (invalid), a snapshot value of
302 	 * 0 (unspecified), or a value bigger than the normal maximum
303 	 * value, into the maximum allowed value.
304 	 *
305 	 * If some application really *needs* a bigger snapshot
306 	 * length, we should just increase MAXIMUM_SNAPLEN.
307 	 */
308 	if (p->snapshot <= 0 || p->snapshot > MAXIMUM_SNAPLEN)
309 		p->snapshot = MAXIMUM_SNAPLEN;
310 
311 	if (p->snapshot < 96)
312 		/*
313 		 * NIT requires a snapshot length of at least 96.
314 		 */
315 		p->snapshot = 96;
316 
317 	/*
318 	 * Initially try a read/write open (to allow the inject
319 	 * method to work).  If that fails due to permission
320 	 * issues, fall back to read-only.  This allows a
321 	 * non-root user to be granted specific access to pcap
322 	 * capabilities via file permissions.
323 	 *
324 	 * XXX - we should have an API that has a flag that
325 	 * controls whether to open read-only or read-write,
326 	 * so that denial of permission to send (or inability
327 	 * to send, if sending packets isn't supported on
328 	 * the device in question) can be indicated at open
329 	 * time.
330 	 */
331 	p->fd = fd = open(dev, O_RDWR);
332 	if (fd < 0 && errno == EACCES)
333 		p->fd = fd = open(dev, O_RDONLY);
334 	if (fd < 0) {
335 		if (errno == EACCES) {
336 			err = PCAP_ERROR_PERM_DENIED;
337 			snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
338 			    "Attempt to open %s failed with EACCES - root privileges may be required",
339 			    dev);
340 		} else {
341 			err = PCAP_ERROR;
342 			pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
343 			    errno, "%s", dev);
344 		}
345 		goto bad;
346 	}
347 
348 	/* arrange to get discrete messages from the STREAM and use NIT_BUF */
349 	if (ioctl(fd, I_SRDOPT, (char *)RMSGD) < 0) {
350 		pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
351 		    errno, "I_SRDOPT");
352 		err = PCAP_ERROR;
353 		goto bad;
354 	}
355 	if (ioctl(fd, I_PUSH, "nbuf") < 0) {
356 		pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
357 		    errno, "push nbuf");
358 		err = PCAP_ERROR;
359 		goto bad;
360 	}
361 	/* set the chunksize */
362 	si.ic_cmd = NIOCSCHUNK;
363 	si.ic_timout = INFTIM;
364 	si.ic_len = sizeof(chunksize);
365 	si.ic_dp = (char *)&chunksize;
366 	if (ioctl(fd, I_STR, (char *)&si) < 0) {
367 		pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
368 		    errno, "NIOCSCHUNK");
369 		err = PCAP_ERROR;
370 		goto bad;
371 	}
372 
373 	/* request the interface */
374 	strncpy(ifr.ifr_name, p->opt.device, sizeof(ifr.ifr_name));
375 	ifr.ifr_name[sizeof(ifr.ifr_name) - 1] = '\0';
376 	si.ic_cmd = NIOCBIND;
377 	si.ic_len = sizeof(ifr);
378 	si.ic_dp = (char *)&ifr;
379 	if (ioctl(fd, I_STR, (char *)&si) < 0) {
380 		/*
381 		 * XXX - is there an error that means "no such device"?
382 		 * Is there one that means "that device doesn't support
383 		 * STREAMS NIT"?
384 		 */
385 		pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
386 		    errno, "NIOCBIND: %s", ifr.ifr_name);
387 		err = PCAP_ERROR;
388 		goto bad;
389 	}
390 
391 	/* set the snapshot length */
392 	si.ic_cmd = NIOCSSNAP;
393 	si.ic_len = sizeof(p->snapshot);
394 	si.ic_dp = (char *)&p->snapshot;
395 	if (ioctl(fd, I_STR, (char *)&si) < 0) {
396 		pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
397 		    errno, "NIOCSSNAP");
398 		err = PCAP_ERROR;
399 		goto bad;
400 	}
401 	if (nit_setflags(p) < 0) {
402 		err = PCAP_ERROR;
403 		goto bad;
404 	}
405 
406 	(void)ioctl(fd, I_FLUSH, (char *)FLUSHR);
407 	/*
408 	 * NIT supports only ethernets.
409 	 */
410 	p->linktype = DLT_EN10MB;
411 
412 	p->bufsize = BUFSPACE;
413 	p->buffer = malloc(p->bufsize);
414 	if (p->buffer == NULL) {
415 		pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
416 		    errno, "malloc");
417 		err = PCAP_ERROR;
418 		goto bad;
419 	}
420 
421 	/*
422 	 * "p->fd" is an FD for a STREAMS device, so "select()" and
423 	 * "poll()" should work on it.
424 	 */
425 	p->selectable_fd = p->fd;
426 
427 	/*
428 	 * This is (presumably) a real Ethernet capture; give it a
429 	 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
430 	 * that an application can let you choose it, in case you're
431 	 * capturing DOCSIS traffic that a Cisco Cable Modem
432 	 * Termination System is putting out onto an Ethernet (it
433 	 * doesn't put an Ethernet header onto the wire, it puts raw
434 	 * DOCSIS frames out on the wire inside the low-level
435 	 * Ethernet framing).
436 	 */
437 	p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
438 	if (p->dlt_list == NULL) {
439 		pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
440 		    errno, "malloc");
441 		err = PCAP_ERROR;
442 		goto bad;
443 	}
444 	p->dlt_list[0] = DLT_EN10MB;
445 	p->dlt_list[1] = DLT_DOCSIS;
446 	p->dlt_count = 2;
447 
448 	p->read_op = pcap_read_snit;
449 	p->inject_op = pcap_inject_snit;
450 	p->setfilter_op = pcapint_install_bpf_program;	/* no kernel filtering */
451 	p->setdirection_op = NULL;	/* Not implemented. */
452 	p->set_datalink_op = NULL;	/* can't change data link type */
453 	p->getnonblock_op = pcapint_getnonblock_fd;
454 	p->setnonblock_op = pcapint_setnonblock_fd;
455 	p->stats_op = pcap_stats_snit;
456 
457 	return (0);
458  bad:
459 	pcapint_cleanup_live_common(p);
460 	return (err);
461 }
462 
463 pcap_t *
464 pcapint_create_interface(const char *device _U_, char *ebuf)
465 {
466 	pcap_t *p;
467 
468 	p = PCAP_CREATE_COMMON(ebuf, struct pcap_snit);
469 	if (p == NULL)
470 		return (NULL);
471 
472 	p->activate_op = pcap_activate_snit;
473 	return (p);
474 }
475 
476 /*
477  * XXX - there's probably a NIOCBIND error that means "that device
478  * doesn't support NIT"; if so, we should try an NIOCBIND and use that.
479  */
480 static int
481 can_be_bound(const char *name _U_)
482 {
483 	return (1);
484 }
485 
486 static int
487 get_if_flags(const char *name _U_, bpf_u_int32 *flags _U_, char *errbuf _U_)
488 {
489 	/*
490 	 * Nothing we can do.
491 	 * XXX - is there a way to find out whether an adapter has
492 	 * something plugged into it?
493 	 */
494 	return (0);
495 }
496 
497 int
498 pcapint_platform_finddevs(pcap_if_list_t *devlistp, char *errbuf)
499 {
500 	return (pcapint_findalldevs_interfaces(devlistp, errbuf, can_be_bound,
501 	    get_if_flags));
502 }
503 
504 /*
505  * Libpcap version string.
506  */
507 const char *
508 pcap_lib_version(void)
509 {
510 	return (PCAP_VERSION_STRING);
511 }
512