xref: /freebsd/contrib/libpcap/testprogs/selpolltest.c (revision 9f23cbd6cae82fd77edfad7173432fa8dccd0a95)
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 #include "varattrs.h"
23 
24 #ifndef lint
25 static const char copyright[] _U_ =
26     "@(#) Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000\n\
27 The Regents of the University of California.  All rights reserved.\n";
28 #endif
29 
30 /*
31  * Tests how select() and poll() behave on the selectable file descriptor
32  * for a pcap_t.
33  *
34  * This would be significantly different on Windows, as it'd test
35  * how WaitForMultipleObjects() would work on the event handle for a
36  * pcap_t.
37  */
38 #include <pcap.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <stdarg.h>
43 #include <unistd.h>
44 #include <errno.h>
45 #include <sys/types.h>
46 #ifdef HAVE_SYS_SELECT_H
47 #include <sys/select.h>
48 #else
49 #include <sys/time.h>	/* older UN*Xes */
50 #endif
51 #include <poll.h>
52 
53 #include "pcap/funcattrs.h"
54 
55 static char *program_name;
56 
57 /* Forwards */
58 static void countme(u_char *, const struct pcap_pkthdr *, const u_char *);
59 static void PCAP_NORETURN usage(void);
60 static void PCAP_NORETURN error(const char *, ...) PCAP_PRINTFLIKE(1, 2);
61 static void warning(const char *, ...) PCAP_PRINTFLIKE(1, 2);
62 static char *copy_argv(char **);
63 
64 static pcap_t *pd;
65 
66 int
67 main(int argc, char **argv)
68 {
69 	register int op;
70 	bpf_u_int32 localnet, netmask;
71 	register char *cp, *cmdbuf, *device;
72 	int doselect, dopoll, dotimeout, dononblock, quiet;
73 	const char *mechanism;
74 	struct bpf_program fcode;
75 	char ebuf[PCAP_ERRBUF_SIZE];
76 	pcap_if_t *devlist;
77 	int selectable_fd = -1;
78 	const struct timeval *required_timeout;
79 	int status;
80 	int packet_count;
81 
82 	device = NULL;
83 	doselect = 0;
84 	dopoll = 0;
85 	mechanism = NULL;
86 	dotimeout = 0;
87 	dononblock = 0;
88 	quiet = 0;
89 	if ((cp = strrchr(argv[0], '/')) != NULL)
90 		program_name = cp + 1;
91 	else
92 		program_name = argv[0];
93 
94 	opterr = 0;
95 	while ((op = getopt(argc, argv, "i:sptnq")) != -1) {
96 		switch (op) {
97 
98 		case 'i':
99 			device = optarg;
100 			break;
101 
102 		case 's':
103 			doselect = 1;
104 			mechanism = "select() and pcap_dispatch()";
105 			break;
106 
107 		case 'p':
108 			dopoll = 1;
109 			mechanism = "poll() and pcap_dispatch()";
110 			break;
111 
112 		case 't':
113 			dotimeout = 1;
114 			break;
115 
116 		case 'n':
117 			dononblock = 1;
118 			break;
119 
120 		case 'q':
121 			quiet = 1;
122 			break;
123 
124 		default:
125 			usage();
126 			/* NOTREACHED */
127 		}
128 	}
129 
130 	if (doselect && dopoll) {
131 		fprintf(stderr, "selpolltest: choose select (-s) or poll (-p), but not both\n");
132 		return 1;
133 	}
134 	if (dotimeout && !doselect && !dopoll) {
135 		fprintf(stderr, "selpolltest: timeout (-t) requires select (-s) or poll (-p)\n");
136 		return 1;
137 	}
138 	if (device == NULL) {
139 		if (pcap_findalldevs(&devlist, ebuf) == -1)
140 			error("%s", ebuf);
141 		if (devlist == NULL)
142 			error("no interfaces available for capture");
143 		device = strdup(devlist->name);
144 		pcap_freealldevs(devlist);
145 	}
146 	*ebuf = '\0';
147 	pd = pcap_open_live(device, 65535, 0, 1000, ebuf);
148 	if (pd == NULL)
149 		error("%s", ebuf);
150 	else if (*ebuf)
151 		warning("%s", ebuf);
152 	if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
153 		localnet = 0;
154 		netmask = 0;
155 		warning("%s", ebuf);
156 	}
157 	cmdbuf = copy_argv(&argv[optind]);
158 
159 	if (pcap_compile(pd, &fcode, cmdbuf, 1, netmask) < 0)
160 		error("%s", pcap_geterr(pd));
161 	if (pcap_setfilter(pd, &fcode) < 0)
162 		error("%s", pcap_geterr(pd));
163 
164 	if (doselect || dopoll) {
165 		/*
166 		 * We need either an FD on which to do select()/poll()
167 		 * or, if there isn't one, a timeout to use in select()/
168 		 * poll().
169 		 */
170 		selectable_fd = pcap_get_selectable_fd(pd);
171 		if (selectable_fd == -1) {
172 			printf("Listening on %s, using %s, with a timeout\n",
173 			    device, mechanism);
174 			required_timeout = pcap_get_required_select_timeout(pd);
175 			if (required_timeout == NULL)
176 				error("select()/poll() isn't supported on %s, even with a timeout",
177 				    device);
178 
179 			/*
180 			 * As we won't be notified by select() or poll()
181 			 * that a read can be done, we'll have to periodically
182 			 * try reading from the device every time the required
183 			 * timeout expires, and we don't want those attempts
184 			 * to block if nothing has arrived in that interval,
185 			 * so we want to force non-blocking mode.
186 			 */
187 			dononblock = 1;
188 		} else {
189 			printf("Listening on %s, using %s\n", device,
190 			    mechanism);
191 			required_timeout = NULL;
192 		}
193 	} else
194 		printf("Listening on %s, using pcap_dispatch()\n", device);
195 
196 	if (dononblock) {
197 		if (pcap_setnonblock(pd, 1, ebuf) == -1)
198 			error("pcap_setnonblock failed: %s", ebuf);
199 	}
200 	if (doselect) {
201 		for (;;) {
202 			fd_set setread, setexcept;
203 			struct timeval seltimeout;
204 			struct timeval *timeoutp;
205 
206 			FD_ZERO(&setread);
207 			if (selectable_fd != -1) {
208 				FD_SET(selectable_fd, &setread);
209 				FD_ZERO(&setexcept);
210 				FD_SET(selectable_fd, &setexcept);
211 			}
212 			required_timeout = pcap_get_required_select_timeout(pd);
213 			if (dotimeout) {
214 				seltimeout.tv_sec = 0;
215 				if (required_timeout != NULL &&
216 				    required_timeout->tv_usec < 1000)
217 					seltimeout.tv_usec = required_timeout->tv_usec;
218 				else
219 					seltimeout.tv_usec = 1000;
220 				timeoutp = &seltimeout;
221 			} else if (required_timeout != NULL) {
222 				seltimeout = *required_timeout;
223 				timeoutp = &seltimeout;
224 			} else {
225 				timeoutp = NULL;
226 			}
227 			status = select((selectable_fd == -1) ?
228 			    0 : selectable_fd + 1, &setread, NULL, &setexcept,
229 			    timeoutp);
230 			if (status == -1) {
231 				printf("Select returns error (%s)\n",
232 				    strerror(errno));
233 			} else {
234 				if (!quiet) {
235 					if (status == 0)
236 						printf("Select timed out: ");
237 					else{
238 						printf("Select returned a descriptor: ");
239 						if (FD_ISSET(selectable_fd, &setread))
240 							printf("readable, ");
241 						else
242 							printf("not readable, ");
243 						if (FD_ISSET(selectable_fd, &setexcept))
244 							printf("exceptional condition\n");
245 						else
246 							printf("no exceptional condition\n");
247 					}
248 				}
249 				packet_count = 0;
250 				status = pcap_dispatch(pd, -1, countme,
251 				    (u_char *)&packet_count);
252 				if (status < 0)
253 					break;
254 				/*
255 				 * Don't report this if we're using a
256 				 * required timeout and we got no packets,
257 				 * because that could be a very short timeout,
258 				 * and we don't want to spam the user with
259 				 * a ton of "no packets" reports.
260 				 */
261 				if (status != 0 || packet_count != 0 ||
262 				    required_timeout != NULL) {
263 					printf("%d packets seen, %d packets counted after select returns\n",
264 					    status, packet_count);
265 				}
266 			}
267 		}
268 	} else if (dopoll) {
269 		for (;;) {
270 			struct pollfd fd;
271 			int polltimeout;
272 
273 			fd.fd = selectable_fd;
274 			fd.events = POLLIN;
275 			required_timeout = pcap_get_required_select_timeout(pd);
276 			if (dotimeout)
277 				polltimeout = 1;
278 			else if (required_timeout != NULL &&
279 			    required_timeout->tv_usec >= 1000)
280 				polltimeout = (int)(required_timeout->tv_usec/1000);
281 			else
282 				polltimeout = -1;
283 			status = poll(&fd, (selectable_fd == -1) ? 0 : 1, polltimeout);
284 			if (status == -1) {
285 				printf("Poll returns error (%s)\n",
286 				    strerror(errno));
287 			} else {
288 				if (!quiet) {
289 					if (status == 0)
290 						printf("Poll timed out\n");
291 					else {
292 						printf("Poll returned a descriptor: ");
293 						if (fd.revents & POLLIN)
294 							printf("readable, ");
295 						else
296 							printf("not readable, ");
297 						if (fd.revents & POLLERR)
298 							printf("exceptional condition, ");
299 						else
300 							printf("no exceptional condition, ");
301 						if (fd.revents & POLLHUP)
302 							printf("disconnect, ");
303 						else
304 							printf("no disconnect, ");
305 						if (fd.revents & POLLNVAL)
306 							printf("invalid\n");
307 						else
308 							printf("not invalid\n");
309 					}
310 				}
311 				packet_count = 0;
312 				status = pcap_dispatch(pd, -1, countme,
313 				    (u_char *)&packet_count);
314 				if (status < 0)
315 					break;
316 				/*
317 				 * Don't report this if we're using a
318 				 * required timeout and we got no packets,
319 				 * because that could be a very short timeout,
320 				 * and we don't want to spam the user with
321 				 * a ton of "no packets" reports.
322 				 */
323 				if (status != 0 || packet_count != 0 ||
324 				    required_timeout != NULL) {
325 					printf("%d packets seen, %d packets counted after poll returns\n",
326 					    status, packet_count);
327 				}
328 			}
329 		}
330 	} else {
331 		for (;;) {
332 			packet_count = 0;
333 			status = pcap_dispatch(pd, -1, countme,
334 			    (u_char *)&packet_count);
335 			if (status < 0)
336 				break;
337 			printf("%d packets seen, %d packets counted after pcap_dispatch returns\n",
338 			    status, packet_count);
339 		}
340 	}
341 	if (status == -2) {
342 		/*
343 		 * We got interrupted, so perhaps we didn't
344 		 * manage to finish a line we were printing.
345 		 * Print an extra newline, just in case.
346 		 */
347 		putchar('\n');
348 	}
349 	(void)fflush(stdout);
350 	if (status == -1) {
351 		/*
352 		 * Error.  Report it.
353 		 */
354 		(void)fprintf(stderr, "%s: pcap_dispatch: %s\n",
355 		    program_name, pcap_geterr(pd));
356 	}
357 	pcap_close(pd);
358 	exit(status == -1 ? 1 : 0);
359 }
360 
361 static void
362 countme(u_char *user, const struct pcap_pkthdr *h _U_, const u_char *sp _U_)
363 {
364 	int *counterp = (int *)user;
365 
366 	(*counterp)++;
367 }
368 
369 static void
370 usage(void)
371 {
372 	(void)fprintf(stderr, "Usage: %s [ -sptnq ] [ -i interface ] [expression]\n",
373 	    program_name);
374 	exit(1);
375 }
376 
377 /* VARARGS */
378 static void
379 error(const char *fmt, ...)
380 {
381 	va_list ap;
382 
383 	(void)fprintf(stderr, "%s: ", program_name);
384 	va_start(ap, fmt);
385 	(void)vfprintf(stderr, fmt, ap);
386 	va_end(ap);
387 	if (*fmt) {
388 		fmt += strlen(fmt);
389 		if (fmt[-1] != '\n')
390 			(void)fputc('\n', stderr);
391 	}
392 	exit(1);
393 	/* NOTREACHED */
394 }
395 
396 /* VARARGS */
397 static void
398 warning(const char *fmt, ...)
399 {
400 	va_list ap;
401 
402 	(void)fprintf(stderr, "%s: WARNING: ", program_name);
403 	va_start(ap, fmt);
404 	(void)vfprintf(stderr, fmt, ap);
405 	va_end(ap);
406 	if (*fmt) {
407 		fmt += strlen(fmt);
408 		if (fmt[-1] != '\n')
409 			(void)fputc('\n', stderr);
410 	}
411 }
412 
413 /*
414  * Copy arg vector into a new buffer, concatenating arguments with spaces.
415  */
416 static char *
417 copy_argv(register char **argv)
418 {
419 	register char **p;
420 	register size_t len = 0;
421 	char *buf;
422 	char *src, *dst;
423 
424 	p = argv;
425 	if (*p == 0)
426 		return 0;
427 
428 	while (*p)
429 		len += strlen(*p++) + 1;
430 
431 	buf = (char *)malloc(len);
432 	if (buf == NULL)
433 		error("copy_argv: malloc");
434 
435 	p = argv;
436 	dst = buf;
437 	while ((src = *p++) != NULL) {
438 		while ((*dst++ = *src++) != '\0')
439 			;
440 		dst[-1] = ' ';
441 	}
442 	dst[-1] = '\0';
443 
444 	return buf;
445 }
446