1/*
2 * Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000
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
22#ifndef lint
23static const char copyright[] =
24    "@(#) Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000\n\
25The Regents of the University of California.  All rights reserved.\n";
26#endif
27
28#include <pcap.h>
29#include <stdio.h>
30#include <stdlib.h>
31#include <string.h>
32#include <stdarg.h>
33#include <unistd.h>
34#include <errno.h>
35#include <sys/types.h>
36#include <sys/select.h>
37#include <poll.h>
38
39char *program_name;
40
41/* Forwards */
42static void countme(u_char *, const struct pcap_pkthdr *, const u_char *);
43static void usage(void) __attribute__((noreturn));
44static void error(const char *, ...);
45static void warning(const char *, ...);
46static char *copy_argv(char **);
47
48static pcap_t *pd;
49
50extern int optind;
51extern int opterr;
52extern char *optarg;
53
54int
55main(int argc, char **argv)
56{
57	register int op;
58	bpf_u_int32 localnet, netmask;
59	register char *cp, *cmdbuf, *device;
60	int doselect, dopoll, dotimeout, dononblock;
61	struct bpf_program fcode;
62	char ebuf[PCAP_ERRBUF_SIZE];
63	int selectable_fd;
64	int status;
65	int packet_count;
66
67	device = NULL;
68	doselect = 0;
69	dopoll = 0;
70	dotimeout = 0;
71	dononblock = 0;
72	if ((cp = strrchr(argv[0], '/')) != NULL)
73		program_name = cp + 1;
74	else
75		program_name = argv[0];
76
77	opterr = 0;
78	while ((op = getopt(argc, argv, "i:sptn")) != -1) {
79		switch (op) {
80
81		case 'i':
82			device = optarg;
83			break;
84
85		case 's':
86			doselect = 1;
87			break;
88
89		case 'p':
90			dopoll = 1;
91			break;
92
93		case 't':
94			dotimeout = 1;
95			break;
96
97		case 'n':
98			dononblock = 1;
99			break;
100
101		default:
102			usage();
103			/* NOTREACHED */
104		}
105	}
106
107	if (doselect && dopoll) {
108		fprintf(stderr, "selpolltest: choose select (-s) or poll (-p), but not both\n");
109		return 1;
110	}
111	if (dotimeout && !doselect && !dopoll) {
112		fprintf(stderr, "selpolltest: timeout (-t) requires select (-s) or poll (-p)\n");
113		return 1;
114	}
115	if (device == NULL) {
116		device = pcap_lookupdev(ebuf);
117		if (device == NULL)
118			error("%s", ebuf);
119	}
120	*ebuf = '\0';
121	pd = pcap_open_live(device, 65535, 0, 1000, ebuf);
122	if (pd == NULL)
123		error("%s", ebuf);
124	else if (*ebuf)
125		warning("%s", ebuf);
126	if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
127		localnet = 0;
128		netmask = 0;
129		warning("%s", ebuf);
130	}
131	cmdbuf = copy_argv(&argv[optind]);
132
133	if (pcap_compile(pd, &fcode, cmdbuf, 1, netmask) < 0)
134		error("%s", pcap_geterr(pd));
135
136	if (pcap_setfilter(pd, &fcode) < 0)
137		error("%s", pcap_geterr(pd));
138	if (pcap_get_selectable_fd(pd) == -1)
139		error("pcap_get_selectable_fd() fails");
140	if (dononblock) {
141		if (pcap_setnonblock(pd, 1, ebuf) == -1)
142			error("pcap_setnonblock failed: %s", ebuf);
143	}
144	selectable_fd = pcap_get_selectable_fd(pd);
145	printf("Listening on %s\n", device);
146	if (doselect) {
147		for (;;) {
148			fd_set setread, setexcept;
149			struct timeval seltimeout;
150
151			FD_ZERO(&setread);
152			FD_SET(selectable_fd, &setread);
153			FD_ZERO(&setexcept);
154			FD_SET(selectable_fd, &setexcept);
155			if (dotimeout) {
156				seltimeout.tv_sec = 0;
157				seltimeout.tv_usec = 1000;
158				status = select(selectable_fd + 1, &setread,
159				    NULL, &setexcept, &seltimeout);
160			} else {
161				status = select(selectable_fd + 1, &setread,
162				    NULL, &setexcept, NULL);
163			}
164			if (status == -1) {
165				printf("Select returns error (%s)\n",
166				    strerror(errno));
167			} else {
168				if (status == 0)
169					printf("Select timed out: ");
170				else
171					printf("Select returned a descriptor: ");
172				if (FD_ISSET(selectable_fd, &setread))
173					printf("readable, ");
174				else
175					printf("not readable, ");
176				if (FD_ISSET(selectable_fd, &setexcept))
177					printf("exceptional condition\n");
178				else
179					printf("no exceptional condition\n");
180				packet_count = 0;
181				status = pcap_dispatch(pd, -1, countme,
182				    (u_char *)&packet_count);
183				if (status < 0)
184					break;
185				printf("%d packets seen, %d packets counted after select returns\n",
186				    status, packet_count);
187			}
188		}
189	} else if (dopoll) {
190		for (;;) {
191			struct pollfd fd;
192			int polltimeout;
193
194			fd.fd = selectable_fd;
195			fd.events = POLLIN;
196			if (dotimeout)
197				polltimeout = 1;
198			else
199				polltimeout = -1;
200			status = poll(&fd, 1, polltimeout);
201			if (status == -1) {
202				printf("Poll returns error (%s)\n",
203				    strerror(errno));
204			} else {
205				if (status == 0)
206					printf("Poll timed out\n");
207				else {
208					printf("Poll returned a descriptor: ");
209					if (fd.revents & POLLIN)
210						printf("readable, ");
211					else
212						printf("not readable, ");
213					if (fd.revents & POLLERR)
214						printf("exceptional condition, ");
215					else
216						printf("no exceptional condition, ");
217					if (fd.revents & POLLHUP)
218						printf("disconnect, ");
219					else
220						printf("no disconnect, ");
221					if (fd.revents & POLLNVAL)
222						printf("invalid\n");
223					else
224						printf("not invalid\n");
225				}
226				packet_count = 0;
227				status = pcap_dispatch(pd, -1, countme,
228				    (u_char *)&packet_count);
229				if (status < 0)
230					break;
231				printf("%d packets seen, %d packets counted after poll returns\n",
232				    status, packet_count);
233			}
234		}
235	} else {
236		for (;;) {
237			packet_count = 0;
238			status = pcap_dispatch(pd, -1, countme,
239			    (u_char *)&packet_count);
240			if (status < 0)
241				break;
242			printf("%d packets seen, %d packets counted after pcap_dispatch returns\n",
243			    status, packet_count);
244		}
245	}
246	if (status == -2) {
247		/*
248		 * We got interrupted, so perhaps we didn't
249		 * manage to finish a line we were printing.
250		 * Print an extra newline, just in case.
251		 */
252		putchar('\n');
253	}
254	(void)fflush(stdout);
255	if (status == -1) {
256		/*
257		 * Error.  Report it.
258		 */
259		(void)fprintf(stderr, "%s: pcap_loop: %s\n",
260		    program_name, pcap_geterr(pd));
261	}
262	pcap_close(pd);
263	exit(status == -1 ? 1 : 0);
264}
265
266static void
267countme(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
268{
269	int *counterp = (int *)user;
270
271	(*counterp)++;
272}
273
274static void
275usage(void)
276{
277	(void)fprintf(stderr, "Usage: %s [ -sptn ] [ -i interface ] [expression]\n",
278	    program_name);
279	exit(1);
280}
281
282/* VARARGS */
283static void
284error(const char *fmt, ...)
285{
286	va_list ap;
287
288	(void)fprintf(stderr, "%s: ", program_name);
289	va_start(ap, fmt);
290	(void)vfprintf(stderr, fmt, ap);
291	va_end(ap);
292	if (*fmt) {
293		fmt += strlen(fmt);
294		if (fmt[-1] != '\n')
295			(void)fputc('\n', stderr);
296	}
297	exit(1);
298	/* NOTREACHED */
299}
300
301/* VARARGS */
302static void
303warning(const char *fmt, ...)
304{
305	va_list ap;
306
307	(void)fprintf(stderr, "%s: WARNING: ", program_name);
308	va_start(ap, fmt);
309	(void)vfprintf(stderr, fmt, ap);
310	va_end(ap);
311	if (*fmt) {
312		fmt += strlen(fmt);
313		if (fmt[-1] != '\n')
314			(void)fputc('\n', stderr);
315	}
316}
317
318/*
319 * Copy arg vector into a new buffer, concatenating arguments with spaces.
320 */
321static char *
322copy_argv(register char **argv)
323{
324	register char **p;
325	register u_int len = 0;
326	char *buf;
327	char *src, *dst;
328
329	p = argv;
330	if (*p == 0)
331		return 0;
332
333	while (*p)
334		len += strlen(*p++) + 1;
335
336	buf = (char *)malloc(len);
337	if (buf == NULL)
338		error("copy_argv: malloc");
339
340	p = argv;
341	dst = buf;
342	while ((src = *p++) != NULL) {
343		while ((*dst++ = *src++) != '\0')
344			;
345		dst[-1] = ' ';
346	}
347	dst[-1] = '\0';
348
349	return buf;
350}
351