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