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