threadsignaltest.c 9.0 KB

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