]> The Tcpdump Group git mirrors - libpcap/blob - tests/threadsignaltest.c
Sleep different on Windows.
[libpcap] / tests / threadsignaltest.c
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
23 static const char copyright[] _U_ =
24 "@(#) Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000\n\
25 The Regents of the University of California. All rights reserved.\n";
26 #endif
27
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <stdarg.h>
32 #include <limits.h>
33 #ifdef _WIN32
34 #include <winsock2.h>
35 #include <windows.h>
36
37 #define THREAD_HANDLE HANDLE
38 #define THREAD_FUNC_RETURN_TYPE int
39
40 #include "getopt.h"
41 #else
42 #include <pthread.h>
43 #include <signal.h>
44 #include <unistd.h>
45
46 #define THREAD_HANDLE pthread_t
47 #define THREAD_FUNC_RETURN_TYPE void *
48 #endif
49 #include <errno.h>
50 #include <sys/types.h>
51
52 #include <pcap.h>
53
54 #include "pcap/funcattrs.h"
55
56 #ifdef _WIN32
57 #include "portability.h"
58 #endif
59
60 static char *program_name;
61
62 /* Forwards */
63 static void countme(u_char *, const struct pcap_pkthdr *, const u_char *);
64 static void PCAP_NORETURN usage(void);
65 static void PCAP_NORETURN error(const char *, ...) PCAP_PRINTFLIKE(1, 2);
66 static void warning(const char *, ...) PCAP_PRINTFLIKE(1, 2);
67 static char *copy_argv(char **);
68
69 static pcap_t *pd;
70
71 #ifdef _WIN32
72 /*
73 * Generate a string for a Win32-specific error (i.e. an error generated when
74 * calling a Win32 API).
75 * For errors occurred during standard C calls, we still use pcap_strerror()
76 */
77 #define ERRBUF_SIZE 1024
78 static const char *
79 win32_strerror(DWORD error)
80 {
81 static char errbuf[ERRBUF_SIZE+1];
82 size_t errlen;
83
84 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, errbuf,
85 ERRBUF_SIZE, NULL);
86
87 /*
88 * "FormatMessage()" "helpfully" sticks CR/LF at the end of the
89 * message. Get rid of it.
90 */
91 errlen = strlen(errbuf);
92 if (errlen >= 2) {
93 errbuf[errlen - 1] = '\0';
94 errbuf[errlen - 2] = '\0';
95 errlen -= 2;
96 }
97 return errbuf;
98 }
99 #else
100 static void
101 catch_sigusr1(int sig _U_)
102 {
103 printf("Got SIGUSR1\n");
104 }
105 #endif
106
107 static void
108 sleep_secs(int secs)
109 {
110 #ifdef _WIN32
111 Sleep(secs*1000);
112 #else
113 unsigned secs_remaining;
114
115 if (secs <= 0)
116 return;
117 secs_remaining = secs;
118 while (secs_remaining != 0)
119 secs_remaining = sleep(secs_remaining);
120 #endif
121 }
122
123 static THREAD_FUNC_RETURN_TYPE
124 capture_thread_func(void *arg)
125 {
126 char *device = arg;
127 int packet_count;
128 int status;
129 #ifndef _WIN32
130 struct sigaction action;
131 sigset_t mask;
132 #endif
133
134 #ifndef _WIN32
135 sigemptyset(&mask);
136 action.sa_handler = catch_sigusr1;
137 action.sa_mask = mask;
138 action.sa_flags = 0;
139 if (sigaction(SIGUSR1, &action, NULL) == -1)
140 error("Can't catch SIGUSR1: %s", strerror(errno));
141 #endif
142
143 printf("Listening on %s\n", device);
144 for (;;) {
145 packet_count = 0;
146 status = pcap_dispatch(pd, -1, countme,
147 (u_char *)&packet_count);
148 if (status < 0)
149 break;
150 if (status != 0) {
151 printf("%d packets seen, %d packets counted after pcap_dispatch returns\n",
152 status, packet_count);
153 }
154 }
155 if (status == -2) {
156 /*
157 * We got interrupted, so perhaps we didn't
158 * manage to finish a line we were printing.
159 * Print an extra newline, just in case.
160 */
161 putchar('\n');
162 printf("Loop got broken\n");
163 }
164 (void)fflush(stdout);
165 if (status == -1) {
166 /*
167 * Error. Report it.
168 */
169 (void)fprintf(stderr, "%s: pcap_loop: %s\n",
170 program_name, pcap_geterr(pd));
171 }
172 return 0;
173 }
174
175 int
176 main(int argc, char **argv)
177 {
178 register int op;
179 register char *cp, *cmdbuf, *device;
180 int immediate = 0;
181 pcap_if_t *devlist;
182 bpf_u_int32 localnet, netmask;
183 struct bpf_program fcode;
184 char ebuf[PCAP_ERRBUF_SIZE];
185 int status;
186 THREAD_HANDLE capture_thread;
187 void *retval;
188
189 device = NULL;
190 if ((cp = strrchr(argv[0], '/')) != NULL)
191 program_name = cp + 1;
192 else
193 program_name = argv[0];
194
195 opterr = 0;
196 while ((op = getopt(argc, argv, "i:")) != -1) {
197 switch (op) {
198
199 case 'i':
200 device = optarg;
201 break;
202
203 default:
204 usage();
205 /* NOTREACHED */
206 }
207 }
208
209 if (device == NULL) {
210 if (pcap_findalldevs(&devlist, ebuf) == -1)
211 error("%s", ebuf);
212 if (devlist == NULL)
213 error("no interfaces available for capture");
214 device = strdup(devlist->name);
215 pcap_freealldevs(devlist);
216 }
217 *ebuf = '\0';
218 pd = pcap_create(device, ebuf);
219 if (pd == NULL)
220 error("%s", ebuf);
221 status = pcap_set_snaplen(pd, 65535);
222 if (status != 0)
223 error("%s: pcap_set_snaplen failed: %s",
224 device, pcap_statustostr(status));
225 if (immediate) {
226 status = pcap_set_immediate_mode(pd, 1);
227 if (status != 0)
228 error("%s: pcap_set_immediate_mode failed: %s",
229 device, pcap_statustostr(status));
230 }
231 status = pcap_set_timeout(pd, 5*60*1000);
232 if (status != 0)
233 error("%s: pcap_set_timeout failed: %s",
234 device, pcap_statustostr(status));
235 status = pcap_activate(pd);
236 if (status < 0) {
237 /*
238 * pcap_activate() failed.
239 */
240 error("%s: %s\n(%s)", device,
241 pcap_statustostr(status), pcap_geterr(pd));
242 } else if (status > 0) {
243 /*
244 * pcap_activate() succeeded, but it's warning us
245 * of a problem it had.
246 */
247 warning("%s: %s\n(%s)", device,
248 pcap_statustostr(status), pcap_geterr(pd));
249 }
250 if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
251 localnet = 0;
252 netmask = 0;
253 warning("%s", ebuf);
254 }
255 cmdbuf = copy_argv(&argv[optind]);
256
257 if (pcap_compile(pd, &fcode, cmdbuf, 1, netmask) < 0)
258 error("%s", pcap_geterr(pd));
259
260 if (pcap_setfilter(pd, &fcode) < 0)
261 error("%s", pcap_geterr(pd));
262
263 #ifdef _WIN32
264 capture_thread = CreateThread(NULL, 0, capture_thread_func, device,
265 0, NULL);
266 if (capture_thread == NULL)
267 error("Can't create capture thread: %s",
268 win32_strerror(GetLastError()));
269 #else
270 status = pthread_create(&capture_thread, NULL, capture_thread_func,
271 device);
272 if (status != 0)
273 error("Can't create capture thread: %s", strerror(status));
274 #endif
275 sleep_secs(60);
276 pcap_breakloop(pd);
277 #ifdef _WIN32
278 printf("Setting event\n");
279 if (!SetEvent(pcap_getevent(pd)))
280 error("Can't set event for pcap_t: %s",
281 win32_strerror(GetLastError()));
282 if (WaitForSingleObject(capture_thread, INFINITE) == WAIT_FAILED)
283 error("Wait for thread termination failed: %s",
284 win32_strerror(GetLastError()));
285 CloseHandle(capture_thread);
286 #else
287 printf("Sending SIGUSR1\n");
288 status = pthread_kill(capture_thread, SIGUSR1);
289 if (status != 0)
290 warning("Can't interrupt capture thread: %s", strerror(status));
291 status = pthread_join(capture_thread, &retval);
292 if (status != 0)
293 error("Wait for thread termination failed: %s",
294 strerror(status));
295 #endif
296
297 pcap_close(pd);
298 pcap_freecode(&fcode);
299 exit(status == -1 ? 1 : 0);
300 }
301
302 static void
303 countme(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
304 {
305 int *counterp = (int *)user;
306
307 (*counterp)++;
308 }
309
310 static void
311 usage(void)
312 {
313 (void)fprintf(stderr, "Usage: %s [ -m ] [ -i interface ] [ -t timeout] [expression]\n",
314 program_name);
315 exit(1);
316 }
317
318 /* VARARGS */
319 static void
320 error(const char *fmt, ...)
321 {
322 va_list ap;
323
324 (void)fprintf(stderr, "%s: ", program_name);
325 va_start(ap, fmt);
326 (void)vfprintf(stderr, fmt, ap);
327 va_end(ap);
328 if (*fmt) {
329 fmt += strlen(fmt);
330 if (fmt[-1] != '\n')
331 (void)fputc('\n', stderr);
332 }
333 exit(1);
334 /* NOTREACHED */
335 }
336
337 /* VARARGS */
338 static void
339 warning(const char *fmt, ...)
340 {
341 va_list ap;
342
343 (void)fprintf(stderr, "%s: WARNING: ", program_name);
344 va_start(ap, fmt);
345 (void)vfprintf(stderr, fmt, ap);
346 va_end(ap);
347 if (*fmt) {
348 fmt += strlen(fmt);
349 if (fmt[-1] != '\n')
350 (void)fputc('\n', stderr);
351 }
352 }
353
354 /*
355 * Copy arg vector into a new buffer, concatenating arguments with spaces.
356 */
357 static char *
358 copy_argv(register char **argv)
359 {
360 register char **p;
361 register u_int len = 0;
362 char *buf;
363 char *src, *dst;
364
365 p = argv;
366 if (*p == 0)
367 return 0;
368
369 while (*p)
370 len += strlen(*p++) + 1;
371
372 buf = (char *)malloc(len);
373 if (buf == NULL)
374 error("copy_argv: malloc");
375
376 p = argv;
377 dst = buf;
378 while ((src = *p++) != NULL) {
379 while ((*dst++ = *src++) != '\0')
380 ;
381 dst[-1] = ' ';
382 }
383 dst[-1] = '\0';
384
385 return buf;
386 }