]> The Tcpdump Group git mirrors - tcpdump/blob - tcpdump.c
We have to set the filter on every new file.
[tcpdump] / tcpdump.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 * Support for splitting captures into multiple files with a maximum
22 * file size:
23 *
24 * Copyright (c) 2001
25 * Seth Webster <swebster@sst.ll.mit.edu>
26 */
27
28 #ifndef lint
29 static const char copyright[] _U_ =
30 "@(#) Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000\n\
31 The Regents of the University of California. All rights reserved.\n";
32 #endif
33
34 /*
35 * tcpdump - dump traffic on a network
36 *
37 * First written in 1987 by Van Jacobson, Lawrence Berkeley Laboratory.
38 * Mercilessly hacked and occasionally improved since then via the
39 * combined efforts of Van, Steve McCanne and Craig Leres of LBL.
40 */
41
42 #ifdef HAVE_CONFIG_H
43 #include "config.h"
44 #endif
45
46 /*
47 * Mac OS X may ship pcap.h from libpcap 0.6 with a libpcap based on
48 * 0.8. That means it has pcap_findalldevs() but the header doesn't
49 * define pcap_if_t, meaning that we can't actually *use* pcap_findalldevs().
50 */
51 #ifdef HAVE_PCAP_FINDALLDEVS
52 #ifndef HAVE_PCAP_IF_T
53 #undef HAVE_PCAP_FINDALLDEVS
54 #endif
55 #endif
56
57 #include <netdissect-stdinc.h>
58
59 #ifdef USE_LIBSMI
60 #include <smi.h>
61 #endif
62
63 #ifdef HAVE_LIBCRYPTO
64 #include <openssl/crypto.h>
65 #endif
66
67 #ifdef HAVE_GETOPT_LONG
68 #include <getopt.h>
69 #else
70 #include "getopt_long.h"
71 #endif
72 /* Capsicum-specific code requires macros from <net/bpf.h>, which will fail
73 * to compile if <pcap.h> has already been included; including the headers
74 * in the opposite order works fine.
75 */
76 #ifdef HAVE_CAPSICUM
77 #include <sys/capability.h>
78 #include <sys/ioccom.h>
79 #include <net/bpf.h>
80 #include <fcntl.h>
81 #include <libgen.h>
82 #endif /* HAVE_CAPSICUM */
83 #include <pcap.h>
84 #include <signal.h>
85 #include <stdio.h>
86 #include <stdlib.h>
87 #include <string.h>
88 #include <limits.h>
89 #ifndef _WIN32
90 #include <sys/wait.h>
91 #include <sys/resource.h>
92 #include <pwd.h>
93 #include <grp.h>
94 #endif /* _WIN32 */
95
96 /* capabilities convenience library */
97 /* If a code depends on HAVE_LIBCAP_NG, it depends also on HAVE_CAP_NG_H.
98 * If HAVE_CAP_NG_H is not defined, undefine HAVE_LIBCAP_NG.
99 * Thus, the later tests are done only on HAVE_LIBCAP_NG.
100 */
101 #ifdef HAVE_LIBCAP_NG
102 #ifdef HAVE_CAP_NG_H
103 #include <cap-ng.h>
104 #else
105 #undef HAVE_LIBCAP_NG
106 #endif /* HAVE_CAP_NG_H */
107 #endif /* HAVE_LIBCAP_NG */
108
109 #include "netdissect.h"
110 #include "interface.h"
111 #include "addrtoname.h"
112 #include "machdep.h"
113 #include "setsignal.h"
114 #include "gmt2local.h"
115 #include "pcap-missing.h"
116 #include "ascii_strcasecmp.h"
117
118 #include "print.h"
119
120 #ifndef PATH_MAX
121 #define PATH_MAX 1024
122 #endif
123
124 #ifdef SIGINFO
125 #define SIGNAL_REQ_INFO SIGINFO
126 #elif SIGUSR1
127 #define SIGNAL_REQ_INFO SIGUSR1
128 #endif
129
130 static int Cflag; /* rotate dump files after this many bytes */
131 static int Cflag_count; /* Keep track of which file number we're writing */
132 static int Dflag; /* list available devices and exit */
133 /*
134 * This is exported because, in some versions of libpcap, if libpcap
135 * is built with optimizer debugging code (which is *NOT* the default
136 * configuration!), the library *imports*(!) a variable named dflag,
137 * under the expectation that tcpdump is exporting it, to govern
138 * how much debugging information to print when optimizing
139 * the generated BPF code.
140 *
141 * This is a horrible hack; newer versions of libpcap don't import
142 * dflag but, instead, *if* built with optimizer debugging code,
143 * *export* a routine to set that flag.
144 */
145 int dflag; /* print filter code */
146 static int Gflag; /* rotate dump files after this many seconds */
147 static int Gflag_count; /* number of files created with Gflag rotation */
148 static time_t Gflag_time; /* The last time_t the dump file was rotated. */
149 static int Lflag; /* list available data link types and exit */
150 static int Iflag; /* rfmon (monitor) mode */
151 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
152 static int Jflag; /* list available time stamp types */
153 #endif
154 #ifdef HAVE_PCAP_SETDIRECTION
155 int Qflag = -1; /* restrict captured packet by send/receive direction */
156 #endif
157 static int Uflag; /* "unbuffered" output of dump files */
158 static int Wflag; /* recycle output files after this number of files */
159 static int WflagChars;
160 static char *zflag = NULL; /* compress each savefile using a specified command (like gzip or bzip2) */
161
162 static int infodelay;
163 static int infoprint;
164
165 char *program_name;
166
167 /* Forwards */
168 static RETSIGTYPE cleanup(int);
169 static RETSIGTYPE child_cleanup(int);
170 static void print_version(void);
171 static void print_usage(void);
172 static void show_tstamp_types_and_exit(const char *device) __attribute__((noreturn));
173 static void show_dlts_and_exit(const char *device) __attribute__((noreturn));
174
175 static void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
176 static void dump_packet_and_trunc(u_char *, const struct pcap_pkthdr *, const u_char *);
177 static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
178 static void droproot(const char *, const char *);
179
180 #ifdef SIGNAL_REQ_INFO
181 RETSIGTYPE requestinfo(int);
182 #endif
183
184 #if defined(USE_WIN32_MM_TIMER)
185 #include <MMsystem.h>
186 static UINT timer_id;
187 static void CALLBACK verbose_stats_dump(UINT, UINT, DWORD_PTR, DWORD_PTR, DWORD_PTR);
188 #elif defined(HAVE_ALARM)
189 static void verbose_stats_dump(int sig);
190 #endif
191
192 static void info(int);
193 static u_int packets_captured;
194
195 static const struct tok status_flags[] = {
196 #ifdef PCAP_IF_UP
197 { PCAP_IF_UP, "Up" },
198 #endif
199 #ifdef PCAP_IF_RUNNING
200 { PCAP_IF_RUNNING, "Running" },
201 #endif
202 { PCAP_IF_LOOPBACK, "Loopback" },
203 { 0, NULL }
204 };
205
206 static pcap_t *pd;
207
208 static int supports_monitor_mode;
209
210 extern int optind;
211 extern int opterr;
212 extern char *optarg;
213
214 struct dump_info {
215 char *WFileName;
216 char *CurrentFileName;
217 pcap_t *pd;
218 pcap_dumper_t *p;
219 #ifdef HAVE_CAPSICUM
220 int dirfd;
221 #endif
222 };
223
224 #if defined(HAVE_PCAP_SET_PARSER_DEBUG)
225 /*
226 * We have pcap_set_parser_debug() in libpcap; declare it (it's not declared
227 * by any libpcap header, because it's a special hack, only available if
228 * libpcap was configured to include it, and only intended for use by
229 * libpcap developers trying to debug the parser for filter expressions).
230 */
231 #ifdef _WIN32
232 __declspec(dllimport)
233 #else /* _WIN32 */
234 extern
235 #endif /* _WIN32 */
236 void pcap_set_parser_debug(int);
237 #elif defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
238 /*
239 * We don't have pcap_set_parser_debug() in libpcap, but we do have
240 * pcap_debug or yydebug. Make a local version of pcap_set_parser_debug()
241 * to set the flag, and define HAVE_PCAP_SET_PARSER_DEBUG.
242 */
243 static void
244 pcap_set_parser_debug(int value)
245 {
246 #ifdef HAVE_PCAP_DEBUG
247 extern int pcap_debug;
248
249 pcap_debug = value;
250 #else /* HAVE_PCAP_DEBUG */
251 extern int yydebug;
252
253 yydebug = value;
254 #endif /* HAVE_PCAP_DEBUG */
255 }
256
257 #define HAVE_PCAP_SET_PARSER_DEBUG
258 #endif
259
260 #if defined(HAVE_PCAP_SET_OPTIMIZER_DEBUG)
261 /*
262 * We have pcap_set_optimizer_debug() in libpcap; declare it (it's not declared
263 * by any libpcap header, because it's a special hack, only available if
264 * libpcap was configured to include it, and only intended for use by
265 * libpcap developers trying to debug the optimizer for filter expressions).
266 */
267 #ifdef _WIN32
268 __declspec(dllimport)
269 #else /* _WIN32 */
270 extern
271 #endif /* _WIN32 */
272 void pcap_set_optimizer_debug(int);
273 #endif
274
275 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
276 static void
277 show_tstamp_types_and_exit(const char *device)
278 {
279 int n_tstamp_types;
280 int *tstamp_types = 0;
281 const char *tstamp_type_name;
282 int i;
283
284 n_tstamp_types = pcap_list_tstamp_types(pd, &tstamp_types);
285 if (n_tstamp_types < 0)
286 error("%s", pcap_geterr(pd));
287
288 if (n_tstamp_types == 0) {
289 fprintf(stderr, "Time stamp type cannot be set for %s\n",
290 device);
291 exit(0);
292 }
293 fprintf(stderr, "Time stamp types for %s (use option -j to set):\n",
294 device);
295 for (i = 0; i < n_tstamp_types; i++) {
296 tstamp_type_name = pcap_tstamp_type_val_to_name(tstamp_types[i]);
297 if (tstamp_type_name != NULL) {
298 (void) fprintf(stderr, " %s (%s)\n", tstamp_type_name,
299 pcap_tstamp_type_val_to_description(tstamp_types[i]));
300 } else {
301 (void) fprintf(stderr, " %d\n", tstamp_types[i]);
302 }
303 }
304 pcap_free_tstamp_types(tstamp_types);
305 exit(0);
306 }
307 #endif
308
309 static void
310 show_dlts_and_exit(const char *device)
311 {
312 int n_dlts, i;
313 int *dlts = 0;
314 const char *dlt_name;
315
316 n_dlts = pcap_list_datalinks(pd, &dlts);
317 if (n_dlts < 0)
318 error("%s", pcap_geterr(pd));
319 else if (n_dlts == 0 || !dlts)
320 error("No data link types.");
321
322 /*
323 * If the interface is known to support monitor mode, indicate
324 * whether these are the data link types available when not in
325 * monitor mode, if -I wasn't specified, or when in monitor mode,
326 * when -I was specified (the link-layer types available in
327 * monitor mode might be different from the ones available when
328 * not in monitor mode).
329 */
330 if (supports_monitor_mode)
331 (void) fprintf(stderr, "Data link types for %s %s (use option -y to set):\n",
332 device,
333 Iflag ? "when in monitor mode" : "when not in monitor mode");
334 else
335 (void) fprintf(stderr, "Data link types for %s (use option -y to set):\n",
336 device);
337
338 for (i = 0; i < n_dlts; i++) {
339 dlt_name = pcap_datalink_val_to_name(dlts[i]);
340 if (dlt_name != NULL) {
341 (void) fprintf(stderr, " %s (%s)", dlt_name,
342 pcap_datalink_val_to_description(dlts[i]));
343
344 /*
345 * OK, does tcpdump handle that type?
346 */
347 if (!has_printer(dlts[i]))
348 (void) fprintf(stderr, " (printing not supported)");
349 fprintf(stderr, "\n");
350 } else {
351 (void) fprintf(stderr, " DLT %d (printing not supported)\n",
352 dlts[i]);
353 }
354 }
355 #ifdef HAVE_PCAP_FREE_DATALINKS
356 pcap_free_datalinks(dlts);
357 #endif
358 exit(0);
359 }
360
361 #ifdef HAVE_PCAP_FINDALLDEVS
362 static void
363 show_devices_and_exit (void)
364 {
365 pcap_if_t *dev, *devlist;
366 char ebuf[PCAP_ERRBUF_SIZE];
367 int i;
368
369 if (pcap_findalldevs(&devlist, ebuf) < 0)
370 error("%s", ebuf);
371 for (i = 0, dev = devlist; dev != NULL; i++, dev = dev->next) {
372 printf("%d.%s", i+1, dev->name);
373 if (dev->description != NULL)
374 printf(" (%s)", dev->description);
375 if (dev->flags != 0)
376 printf(" [%s]", bittok2str(status_flags, "none", dev->flags));
377 printf("\n");
378 }
379 pcap_freealldevs(devlist);
380 exit(0);
381 }
382 #endif /* HAVE_PCAP_FINDALLDEVS */
383
384 /*
385 * Short options.
386 *
387 * Note that there we use all letters for short options except for g, k,
388 * o, and P, and those are used by other versions of tcpdump, and we should
389 * only use them for the same purposes that the other versions of tcpdump
390 * use them:
391 *
392 * OS X tcpdump uses -g to force non--v output for IP to be on one
393 * line, making it more "g"repable;
394 *
395 * OS X tcpdump uses -k tospecify that packet comments in pcap-ng files
396 * should be printed;
397 *
398 * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done
399 * for hosts sending TCP SYN packets;
400 *
401 * OS X tcpdump uses -P to indicate that -w should write pcap-ng rather
402 * than pcap files.
403 *
404 * OS X tcpdump also uses -Q to specify expressions that match packet
405 * metadata, including but not limited to the packet direction.
406 * The expression syntax is different from a simple "in|out|inout",
407 * and those expressions aren't accepted by OS X tcpdump, but the
408 * equivalents would be "in" = "dir=in", "out" = "dir=out", and
409 * "inout" = "dir=in or dir=out", and the parser could conceivably
410 * special-case "in", "out", and "inout" as expressions for backwards
411 * compatibility, so all is not (yet) lost.
412 */
413
414 /*
415 * Set up flags that might or might not be supported depending on the
416 * version of libpcap we're using.
417 */
418 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
419 #define B_FLAG "B:"
420 #define B_FLAG_USAGE " [ -B size ]"
421 #else /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
422 #define B_FLAG
423 #define B_FLAG_USAGE
424 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
425
426 #ifdef HAVE_PCAP_CREATE
427 #define I_FLAG "I"
428 #else /* HAVE_PCAP_CREATE */
429 #define I_FLAG
430 #endif /* HAVE_PCAP_CREATE */
431
432 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
433 #define j_FLAG "j:"
434 #define j_FLAG_USAGE " [ -j tstamptype ]"
435 #define J_FLAG "J"
436 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
437 #define j_FLAG
438 #define j_FLAG_USAGE
439 #define J_FLAG
440 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
441
442 #ifdef HAVE_PCAP_FINDALLDEVS
443 #define D_FLAG "D"
444 #else
445 #define D_FLAG
446 #endif
447
448 #ifdef HAVE_PCAP_DUMP_FLUSH
449 #define U_FLAG "U"
450 #else
451 #define U_FLAG
452 #endif
453
454 #ifdef HAVE_PCAP_SETDIRECTION
455 #define Q_FLAG "Q:"
456 #else
457 #define Q_FLAG
458 #endif
459
460 #define SHORTOPTS "aAb" B_FLAG "c:C:d" D_FLAG "eE:fF:G:hHi:" I_FLAG j_FLAG J_FLAG "KlLm:M:nNOpq" Q_FLAG "r:s:StT:u" U_FLAG "vV:w:W:xXy:Yz:Z:#"
461
462 /*
463 * Long options.
464 *
465 * We do not currently have long options corresponding to all short
466 * options; we should probably pick appropriate option names for them.
467 *
468 * However, the short options where the number of times the option is
469 * specified matters, such as -v and -d and -t, should probably not
470 * just map to a long option, as saying
471 *
472 * tcpdump --verbose --verbose
473 *
474 * doesn't make sense; it should be --verbosity={N} or something such
475 * as that.
476 *
477 * For long options with no corresponding short options, we define values
478 * outside the range of ASCII graphic characters, make that the last
479 * component of the entry for the long option, and have a case for that
480 * option in the switch statement.
481 */
482 #define OPTION_VERSION 128
483 #define OPTION_TSTAMP_PRECISION 129
484 #define OPTION_IMMEDIATE_MODE 130
485
486 static const struct option longopts[] = {
487 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
488 { "buffer-size", required_argument, NULL, 'B' },
489 #endif
490 { "list-interfaces", no_argument, NULL, 'D' },
491 { "help", no_argument, NULL, 'h' },
492 { "interface", required_argument, NULL, 'i' },
493 #ifdef HAVE_PCAP_CREATE
494 { "monitor-mode", no_argument, NULL, 'I' },
495 #endif
496 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
497 { "time-stamp-type", required_argument, NULL, 'j' },
498 { "list-time-stamp-types", no_argument, NULL, 'J' },
499 #endif
500 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
501 { "time-stamp-precision", required_argument, NULL, OPTION_TSTAMP_PRECISION},
502 #endif
503 { "dont-verify-checksums", no_argument, NULL, 'K' },
504 { "list-data-link-types", no_argument, NULL, 'L' },
505 { "no-optimize", no_argument, NULL, 'O' },
506 { "no-promiscuous-mode", no_argument, NULL, 'p' },
507 #ifdef HAVE_PCAP_SETDIRECTION
508 { "direction", required_argument, NULL, 'Q' },
509 #endif
510 { "snapshot-length", required_argument, NULL, 's' },
511 { "absolute-tcp-sequence-numbers", no_argument, NULL, 'S' },
512 #ifdef HAVE_PCAP_DUMP_FLUSH
513 { "packet-buffered", no_argument, NULL, 'U' },
514 #endif
515 { "linktype", required_argument, NULL, 'y' },
516 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
517 { "immediate-mode", no_argument, NULL, OPTION_IMMEDIATE_MODE },
518 #endif
519 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
520 { "debug-filter-parser", no_argument, NULL, 'Y' },
521 #endif
522 { "relinquish-privileges", required_argument, NULL, 'Z' },
523 { "number", no_argument, NULL, '#' },
524 { "version", no_argument, NULL, OPTION_VERSION },
525 { NULL, 0, NULL, 0 }
526 };
527
528 #ifndef _WIN32
529 /* Drop root privileges and chroot if necessary */
530 static void
531 droproot(const char *username, const char *chroot_dir)
532 {
533 struct passwd *pw = NULL;
534
535 if (chroot_dir && !username) {
536 fprintf(stderr, "%s: Chroot without dropping root is insecure\n",
537 program_name);
538 exit(1);
539 }
540
541 pw = getpwnam(username);
542 if (pw) {
543 if (chroot_dir) {
544 if (chroot(chroot_dir) != 0 || chdir ("/") != 0) {
545 fprintf(stderr, "%s: Couldn't chroot/chdir to '%.64s': %s\n",
546 program_name, chroot_dir, pcap_strerror(errno));
547 exit(1);
548 }
549 }
550 #ifdef HAVE_LIBCAP_NG
551 {
552 int ret = capng_change_id(pw->pw_uid, pw->pw_gid, CAPNG_NO_FLAG);
553 if (ret < 0) {
554 fprintf(stderr, "error : ret %d\n", ret);
555 } else {
556 fprintf(stderr, "dropped privs to %s\n", username);
557 }
558 }
559 #else
560 if (initgroups(pw->pw_name, pw->pw_gid) != 0 ||
561 setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0) {
562 fprintf(stderr, "%s: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
563 program_name, username,
564 (unsigned long)pw->pw_uid,
565 (unsigned long)pw->pw_gid,
566 pcap_strerror(errno));
567 exit(1);
568 }
569 else {
570 fprintf(stderr, "dropped privs to %s\n", username);
571 }
572 #endif /* HAVE_LIBCAP_NG */
573 }
574 else {
575 fprintf(stderr, "%s: Couldn't find user '%.32s'\n",
576 program_name, username);
577 exit(1);
578 }
579 #ifdef HAVE_LIBCAP_NG
580 /* We don't need CAP_SETUID and CAP_SETGID any more. */
581 capng_updatev(
582 CAPNG_DROP,
583 CAPNG_EFFECTIVE | CAPNG_PERMITTED,
584 CAP_SETUID,
585 CAP_SETGID,
586 -1);
587 capng_apply(CAPNG_SELECT_BOTH);
588 #endif /* HAVE_LIBCAP_NG */
589
590 }
591 #endif /* _WIN32 */
592
593 static int
594 getWflagChars(int x)
595 {
596 int c = 0;
597
598 x -= 1;
599 while (x > 0) {
600 c += 1;
601 x /= 10;
602 }
603
604 return c;
605 }
606
607
608 static void
609 MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
610 {
611 char *filename = malloc(PATH_MAX + 1);
612 if (filename == NULL)
613 error("Makefilename: malloc");
614
615 /* Process with strftime if Gflag is set. */
616 if (Gflag != 0) {
617 struct tm *local_tm;
618
619 /* Convert Gflag_time to a usable format */
620 if ((local_tm = localtime(&Gflag_time)) == NULL) {
621 error("MakeTimedFilename: localtime");
622 }
623
624 /* There's no good way to detect an error in strftime since a return
625 * value of 0 isn't necessarily failure.
626 */
627 strftime(filename, PATH_MAX, orig_name, local_tm);
628 } else {
629 strncpy(filename, orig_name, PATH_MAX);
630 }
631
632 if (cnt == 0 && max_chars == 0)
633 strncpy(buffer, filename, PATH_MAX + 1);
634 else
635 if (snprintf(buffer, PATH_MAX + 1, "%s%0*d", filename, max_chars, cnt) > PATH_MAX)
636 /* Report an error if the filename is too large */
637 error("too many output files or filename is too long (> %d)", PATH_MAX);
638 free(filename);
639 }
640
641 static char *
642 get_next_file(FILE *VFile, char *ptr)
643 {
644 char *ret;
645
646 ret = fgets(ptr, PATH_MAX, VFile);
647 if (!ret)
648 return NULL;
649
650 if (ptr[strlen(ptr) - 1] == '\n')
651 ptr[strlen(ptr) - 1] = '\0';
652
653 return ret;
654 }
655
656 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
657 static int
658 tstamp_precision_from_string(const char *precision)
659 {
660 if (strncmp(precision, "nano", strlen("nano")) == 0)
661 return PCAP_TSTAMP_PRECISION_NANO;
662
663 if (strncmp(precision, "micro", strlen("micro")) == 0)
664 return PCAP_TSTAMP_PRECISION_MICRO;
665
666 return -EINVAL;
667 }
668
669 static const char *
670 tstamp_precision_to_string(int precision)
671 {
672 switch (precision) {
673
674 case PCAP_TSTAMP_PRECISION_MICRO:
675 return "micro";
676
677 case PCAP_TSTAMP_PRECISION_NANO:
678 return "nano";
679
680 default:
681 return "unknown";
682 }
683 }
684 #endif
685
686 #ifdef HAVE_CAPSICUM
687 /*
688 * Ensure that, on a dump file's descriptor, we have all the rights
689 * necessary to make the standard I/O library work with an fdopen()ed
690 * FILE * from that descriptor.
691 *
692 * A long time ago, in a galaxy far far away, AT&T decided that, instead
693 * of providing separate APIs for getting and setting the FD_ flags on a
694 * descriptor, getting and setting the O_ flags on a descriptor, and
695 * locking files, they'd throw them all into a kitchen-sink fcntl() call
696 * along the lines of ioctl(), the fact that ioctl() operations are
697 * largely specific to particular character devices but fcntl() operations
698 * are either generic to all descriptors or generic to all descriptors for
699 * regular files nonwithstanding.
700 *
701 * The Capsicum people decided that fine-grained control of descriptor
702 * operations was required, so that you need to grant permission for
703 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
704 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
705 * collection of things, so there are *individual* fcntls for which
706 * permission needs to be granted.
707 *
708 * The FreeBSD standard I/O people implemented some optimizations that
709 * requires that the standard I/O routines be able to determine whether
710 * the descriptor for the FILE * is open append-only or not; as that
711 * descriptor could have come from an open() rather than an fopen(),
712 * that requires that it be able to do an F_GETFL fcntl() to read
713 * the O_ flags.
714 *
715 * Tcpdump uses ftell() to determine how much data has been written
716 * to a file in order to, when used with -C, determine when it's time
717 * to rotate capture files. ftell() therefore needs to do an lseek()
718 * to find out the file offset and must, thanks to the aforementioned
719 * optimization, also know whether the descriptor is open append-only
720 * or not.
721 *
722 * The net result of all the above is that we need to grant CAP_SEEK,
723 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
724 *
725 * Perhaps this is the universe's way of saying that either
726 *
727 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
728 * using it, so that Capsicum-capable tcpdump wouldn't need to do
729 * an fdopen()
730 *
731 * or
732 *
733 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
734 * I/O library that knows what rights are needed by the standard
735 * I/O library, based on the open mode, and assigns them, perhaps
736 * with an additional argument indicating, for example, whether
737 * seeking should be allowed, so that tcpdump doesn't need to know
738 * what the standard I/O library happens to require this week.
739 */
740 static void
741 set_dumper_capsicum_rights(pcap_dumper_t *p)
742 {
743 int fd = fileno(pcap_dump_file(p));
744 cap_rights_t rights;
745
746 cap_rights_init(&rights, CAP_SEEK, CAP_WRITE, CAP_FCNTL);
747 if (cap_rights_limit(fd, &rights) < 0 && errno != ENOSYS) {
748 error("unable to limit dump descriptor");
749 }
750 if (cap_fcntls_limit(fd, CAP_FCNTL_GETFL) < 0 && errno != ENOSYS) {
751 error("unable to limit dump descriptor fcntls");
752 }
753 }
754 #endif
755
756 int
757 main(int argc, char **argv)
758 {
759 register int cnt, op, i;
760 bpf_u_int32 localnet =0 , netmask = 0;
761 int timezone_offset = 0;
762 register char *cp, *infile, *cmdbuf, *device, *RFileName, *VFileName, *WFileName;
763 pcap_handler callback;
764 int dlt;
765 const char *dlt_name;
766 struct bpf_program fcode;
767 #ifndef _WIN32
768 RETSIGTYPE (*oldhandler)(int);
769 #endif
770 struct dump_info dumpinfo;
771 u_char *pcap_userdata;
772 char ebuf[PCAP_ERRBUF_SIZE];
773 char VFileLine[PATH_MAX + 1];
774 char *username = NULL;
775 char *chroot_dir = NULL;
776 char *ret = NULL;
777 char *end;
778 #ifdef HAVE_PCAP_FINDALLDEVS
779 pcap_if_t *dev, *devlist;
780 int devnum;
781 #endif
782 int status;
783 FILE *VFile;
784 #ifdef HAVE_CAPSICUM
785 cap_rights_t rights;
786 int cansandbox;
787 #endif /* HAVE_CAPSICUM */
788 int Bflag = 0; /* buffer size */
789 int jflag = -1; /* packet time stamp source */
790 int Oflag = 1; /* run filter code optimizer */
791 int pflag = 0; /* don't go promiscuous */
792 int yflag_dlt = -1;
793 const char *yflag_dlt_name = NULL;
794
795 netdissect_options Ndo;
796 netdissect_options *ndo = &Ndo;
797 int immediate_mode = 0;
798
799 memset(ndo, 0, sizeof(*ndo));
800 ndo_set_function_pointers(ndo);
801 ndo->ndo_snaplen = DEFAULT_SNAPLEN;
802
803 cnt = -1;
804 device = NULL;
805 infile = NULL;
806 RFileName = NULL;
807 VFileName = NULL;
808 VFile = NULL;
809 WFileName = NULL;
810 dlt = -1;
811 if ((cp = strrchr(argv[0], '/')) != NULL)
812 ndo->program_name = program_name = cp + 1;
813 else
814 ndo->program_name = program_name = argv[0];
815
816 #ifdef _WIN32
817 if (pcap_wsockinit() != 0)
818 error("Attempting to initialize Winsock failed");
819 #endif /* _WIN32 */
820
821 /*
822 * On platforms where the CPU doesn't support unaligned loads,
823 * force unaligned accesses to abort with SIGBUS, rather than
824 * being fixed up (slowly) by the OS kernel; on those platforms,
825 * misaligned accesses are bugs, and we want tcpdump to crash so
826 * that the bugs are reported.
827 */
828 if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
829 error("%s", ebuf);
830
831 #ifdef USE_LIBSMI
832 smiInit("tcpdump");
833 #endif
834
835 while (
836 (op = getopt_long(argc, argv, SHORTOPTS, longopts, NULL)) != -1)
837 switch (op) {
838
839 case 'a':
840 /* compatibility for old -a */
841 break;
842
843 case 'A':
844 ++ndo->ndo_Aflag;
845 break;
846
847 case 'b':
848 ++ndo->ndo_bflag;
849 break;
850
851 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
852 case 'B':
853 Bflag = atoi(optarg)*1024;
854 if (Bflag <= 0)
855 error("invalid packet buffer size %s", optarg);
856 break;
857 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
858
859 case 'c':
860 cnt = atoi(optarg);
861 if (cnt <= 0)
862 error("invalid packet count %s", optarg);
863 break;
864
865 case 'C':
866 Cflag = atoi(optarg) * 1000000;
867 if (Cflag < 0)
868 error("invalid file size %s", optarg);
869 break;
870
871 case 'd':
872 ++dflag;
873 break;
874
875 case 'D':
876 Dflag++;
877 break;
878
879 case 'L':
880 Lflag++;
881 break;
882
883 case 'e':
884 ++ndo->ndo_eflag;
885 break;
886
887 case 'E':
888 #ifndef HAVE_LIBCRYPTO
889 warning("crypto code not compiled in");
890 #endif
891 ndo->ndo_espsecret = optarg;
892 break;
893
894 case 'f':
895 ++ndo->ndo_fflag;
896 break;
897
898 case 'F':
899 infile = optarg;
900 break;
901
902 case 'G':
903 Gflag = atoi(optarg);
904 if (Gflag < 0)
905 error("invalid number of seconds %s", optarg);
906
907 /* We will create one file initially. */
908 Gflag_count = 0;
909
910 /* Grab the current time for rotation use. */
911 if ((Gflag_time = time(NULL)) == (time_t)-1) {
912 error("main: can't get current time: %s",
913 pcap_strerror(errno));
914 }
915 break;
916
917 case 'h':
918 print_usage();
919 exit(0);
920 break;
921
922 case 'H':
923 ++ndo->ndo_Hflag;
924 break;
925
926 case 'i':
927 if (optarg[0] == '0' && optarg[1] == 0)
928 error("Invalid adapter index");
929
930 #ifdef HAVE_PCAP_FINDALLDEVS
931 /*
932 * If the argument is a number, treat it as
933 * an index into the list of adapters, as
934 * printed by "tcpdump -D".
935 *
936 * This should be OK on UNIX systems, as interfaces
937 * shouldn't have names that begin with digits.
938 * It can be useful on Windows, where more than
939 * one interface can have the same name.
940 */
941 devnum = strtol(optarg, &end, 10);
942 if (optarg != end && *end == '\0') {
943 if (devnum < 0)
944 error("Invalid adapter index");
945
946 if (pcap_findalldevs(&devlist, ebuf) < 0)
947 error("%s", ebuf);
948 /*
949 * Look for the devnum-th entry in the
950 * list of devices (1-based).
951 */
952 for (i = 0, dev = devlist;
953 i < devnum-1 && dev != NULL;
954 i++, dev = dev->next)
955 ;
956 if (dev == NULL)
957 error("Invalid adapter index");
958 device = strdup(dev->name);
959 pcap_freealldevs(devlist);
960 break;
961 }
962 #endif /* HAVE_PCAP_FINDALLDEVS */
963 device = optarg;
964 break;
965
966 #ifdef HAVE_PCAP_CREATE
967 case 'I':
968 ++Iflag;
969 break;
970 #endif /* HAVE_PCAP_CREATE */
971
972 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
973 case 'j':
974 jflag = pcap_tstamp_type_name_to_val(optarg);
975 if (jflag < 0)
976 error("invalid time stamp type %s", optarg);
977 break;
978
979 case 'J':
980 Jflag++;
981 break;
982 #endif
983
984 case 'l':
985 #ifdef _WIN32
986 /*
987 * _IOLBF is the same as _IOFBF in Microsoft's C
988 * libraries; the only alternative they offer
989 * is _IONBF.
990 *
991 * XXX - this should really be checking for MSVC++,
992 * not _WIN32, if, for example, MinGW has its own
993 * C library that is more UNIX-compatible.
994 */
995 setvbuf(stdout, NULL, _IONBF, 0);
996 #else /* _WIN32 */
997 #ifdef HAVE_SETLINEBUF
998 setlinebuf(stdout);
999 #else
1000 setvbuf(stdout, NULL, _IOLBF, 0);
1001 #endif
1002 #endif /* _WIN32 */
1003 break;
1004
1005 case 'K':
1006 ++ndo->ndo_Kflag;
1007 break;
1008
1009 case 'm':
1010 #ifdef USE_LIBSMI
1011 if (smiLoadModule(optarg) == 0) {
1012 error("could not load MIB module %s", optarg);
1013 }
1014 ndo->ndo_mflag = 1;
1015 #else
1016 (void)fprintf(stderr, "%s: ignoring option `-m %s' ",
1017 program_name, optarg);
1018 (void)fprintf(stderr, "(no libsmi support)\n");
1019 #endif
1020 break;
1021
1022 case 'M':
1023 /* TCP-MD5 shared secret */
1024 #ifndef HAVE_LIBCRYPTO
1025 warning("crypto code not compiled in");
1026 #endif
1027 ndo->ndo_sigsecret = optarg;
1028 break;
1029
1030 case 'n':
1031 ++ndo->ndo_nflag;
1032 break;
1033
1034 case 'N':
1035 ++ndo->ndo_Nflag;
1036 break;
1037
1038 case 'O':
1039 Oflag = 0;
1040 break;
1041
1042 case 'p':
1043 ++pflag;
1044 break;
1045
1046 case 'q':
1047 ++ndo->ndo_qflag;
1048 ++ndo->ndo_suppress_default_print;
1049 break;
1050
1051 #ifdef HAVE_PCAP_SETDIRECTION
1052 case 'Q':
1053 if (ascii_strcasecmp(optarg, "in") == 0)
1054 Qflag = PCAP_D_IN;
1055 else if (ascii_strcasecmp(optarg, "out") == 0)
1056 Qflag = PCAP_D_OUT;
1057 else if (ascii_strcasecmp(optarg, "inout") == 0)
1058 Qflag = PCAP_D_INOUT;
1059 else
1060 error("unknown capture direction `%s'", optarg);
1061 break;
1062 #endif /* HAVE_PCAP_SETDIRECTION */
1063
1064 case 'r':
1065 RFileName = optarg;
1066 break;
1067
1068 case 's':
1069 ndo->ndo_snaplen = strtol(optarg, &end, 0);
1070 if (optarg == end || *end != '\0'
1071 || ndo->ndo_snaplen < 0 || ndo->ndo_snaplen > MAXIMUM_SNAPLEN)
1072 error("invalid snaplen %s", optarg);
1073 else if (ndo->ndo_snaplen == 0)
1074 ndo->ndo_snaplen = MAXIMUM_SNAPLEN;
1075 break;
1076
1077 case 'S':
1078 ++ndo->ndo_Sflag;
1079 break;
1080
1081 case 't':
1082 ++ndo->ndo_tflag;
1083 break;
1084
1085 case 'T':
1086 if (ascii_strcasecmp(optarg, "vat") == 0)
1087 ndo->ndo_packettype = PT_VAT;
1088 else if (ascii_strcasecmp(optarg, "wb") == 0)
1089 ndo->ndo_packettype = PT_WB;
1090 else if (ascii_strcasecmp(optarg, "rpc") == 0)
1091 ndo->ndo_packettype = PT_RPC;
1092 else if (ascii_strcasecmp(optarg, "rtp") == 0)
1093 ndo->ndo_packettype = PT_RTP;
1094 else if (ascii_strcasecmp(optarg, "rtcp") == 0)
1095 ndo->ndo_packettype = PT_RTCP;
1096 else if (ascii_strcasecmp(optarg, "snmp") == 0)
1097 ndo->ndo_packettype = PT_SNMP;
1098 else if (ascii_strcasecmp(optarg, "cnfp") == 0)
1099 ndo->ndo_packettype = PT_CNFP;
1100 else if (ascii_strcasecmp(optarg, "tftp") == 0)
1101 ndo->ndo_packettype = PT_TFTP;
1102 else if (ascii_strcasecmp(optarg, "aodv") == 0)
1103 ndo->ndo_packettype = PT_AODV;
1104 else if (ascii_strcasecmp(optarg, "carp") == 0)
1105 ndo->ndo_packettype = PT_CARP;
1106 else if (ascii_strcasecmp(optarg, "radius") == 0)
1107 ndo->ndo_packettype = PT_RADIUS;
1108 else if (ascii_strcasecmp(optarg, "zmtp1") == 0)
1109 ndo->ndo_packettype = PT_ZMTP1;
1110 else if (ascii_strcasecmp(optarg, "vxlan") == 0)
1111 ndo->ndo_packettype = PT_VXLAN;
1112 else if (ascii_strcasecmp(optarg, "pgm") == 0)
1113 ndo->ndo_packettype = PT_PGM;
1114 else if (ascii_strcasecmp(optarg, "pgm_zmtp1") == 0)
1115 ndo->ndo_packettype = PT_PGM_ZMTP1;
1116 else if (ascii_strcasecmp(optarg, "lmp") == 0)
1117 ndo->ndo_packettype = PT_LMP;
1118 else
1119 error("unknown packet type `%s'", optarg);
1120 break;
1121
1122 case 'u':
1123 ++ndo->ndo_uflag;
1124 break;
1125
1126 #ifdef HAVE_PCAP_DUMP_FLUSH
1127 case 'U':
1128 ++Uflag;
1129 break;
1130 #endif
1131
1132 case 'v':
1133 ++ndo->ndo_vflag;
1134 break;
1135
1136 case 'V':
1137 VFileName = optarg;
1138 break;
1139
1140 case 'w':
1141 WFileName = optarg;
1142 break;
1143
1144 case 'W':
1145 Wflag = atoi(optarg);
1146 if (Wflag < 0)
1147 error("invalid number of output files %s", optarg);
1148 WflagChars = getWflagChars(Wflag);
1149 break;
1150
1151 case 'x':
1152 ++ndo->ndo_xflag;
1153 ++ndo->ndo_suppress_default_print;
1154 break;
1155
1156 case 'X':
1157 ++ndo->ndo_Xflag;
1158 ++ndo->ndo_suppress_default_print;
1159 break;
1160
1161 case 'y':
1162 yflag_dlt_name = optarg;
1163 yflag_dlt =
1164 pcap_datalink_name_to_val(yflag_dlt_name);
1165 if (yflag_dlt < 0)
1166 error("invalid data link type %s", yflag_dlt_name);
1167 break;
1168
1169 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
1170 case 'Y':
1171 {
1172 /* Undocumented flag */
1173 pcap_set_parser_debug(1);
1174 }
1175 break;
1176 #endif
1177 case 'z':
1178 zflag = optarg;
1179 break;
1180
1181 case 'Z':
1182 username = optarg;
1183 break;
1184
1185 case '#':
1186 ndo->ndo_packet_number = 1;
1187 break;
1188
1189 case OPTION_VERSION:
1190 print_version();
1191 exit(0);
1192 break;
1193
1194 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1195 case OPTION_TSTAMP_PRECISION:
1196 ndo->ndo_tstamp_precision = tstamp_precision_from_string(optarg);
1197 if (ndo->ndo_tstamp_precision < 0)
1198 error("unsupported time stamp precision");
1199 break;
1200 #endif
1201
1202 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1203 case OPTION_IMMEDIATE_MODE:
1204 immediate_mode = 1;
1205 break;
1206 #endif
1207
1208 default:
1209 print_usage();
1210 exit(1);
1211 /* NOTREACHED */
1212 }
1213
1214 #ifdef HAVE_PCAP_FINDALLDEVS
1215 if (Dflag)
1216 show_devices_and_exit();
1217 #endif
1218
1219 switch (ndo->ndo_tflag) {
1220
1221 case 0: /* Default */
1222 case 4: /* Default + Date*/
1223 timezone_offset = gmt2local(0);
1224 break;
1225
1226 case 1: /* No time stamp */
1227 case 2: /* Unix timeval style */
1228 case 3: /* Microseconds since previous packet */
1229 case 5: /* Microseconds since first packet */
1230 break;
1231
1232 default: /* Not supported */
1233 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1234 break;
1235 }
1236
1237 if (ndo->ndo_fflag != 0 && (VFileName != NULL || RFileName != NULL))
1238 error("-f can not be used with -V or -r");
1239
1240 if (VFileName != NULL && RFileName != NULL)
1241 error("-V and -r are mutually exclusive.");
1242
1243 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1244 /*
1245 * If we're printing dissected packets to the standard output
1246 * rather than saving raw packets to a file, and the standard
1247 * output is a terminal, use immediate mode, as the user's
1248 * probably expecting to see packets pop up immediately.
1249 */
1250 if (WFileName == NULL && isatty(1))
1251 immediate_mode = 1;
1252 #endif
1253
1254 #ifdef WITH_CHROOT
1255 /* if run as root, prepare for chrooting */
1256 if (getuid() == 0 || geteuid() == 0) {
1257 /* future extensibility for cmd-line arguments */
1258 if (!chroot_dir)
1259 chroot_dir = WITH_CHROOT;
1260 }
1261 #endif
1262
1263 #ifdef WITH_USER
1264 /* if run as root, prepare for dropping root privileges */
1265 if (getuid() == 0 || geteuid() == 0) {
1266 /* Run with '-Z root' to restore old behaviour */
1267 if (!username)
1268 username = WITH_USER;
1269 }
1270 #endif
1271
1272 if (RFileName != NULL || VFileName != NULL) {
1273 /*
1274 * If RFileName is non-null, it's the pathname of a
1275 * savefile to read. If VFileName is non-null, it's
1276 * the pathname of a file containing a list of pathnames
1277 * (one per line) of savefiles to read.
1278 *
1279 * In either case, we're reading a savefile, not doing
1280 * a live capture.
1281 */
1282 #ifndef _WIN32
1283 /*
1284 * We don't need network access, so relinquish any set-UID
1285 * or set-GID privileges we have (if any).
1286 *
1287 * We do *not* want set-UID privileges when opening a
1288 * trace file, as that might let the user read other
1289 * people's trace files (especially if we're set-UID
1290 * root).
1291 */
1292 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1293 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1294 #endif /* _WIN32 */
1295 if (VFileName != NULL) {
1296 if (VFileName[0] == '-' && VFileName[1] == '\0')
1297 VFile = stdin;
1298 else
1299 VFile = fopen(VFileName, "r");
1300
1301 if (VFile == NULL)
1302 error("Unable to open file: %s\n", pcap_strerror(errno));
1303
1304 ret = get_next_file(VFile, VFileLine);
1305 if (!ret)
1306 error("Nothing in %s\n", VFileName);
1307 RFileName = VFileLine;
1308 }
1309
1310 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1311 pd = pcap_open_offline_with_tstamp_precision(RFileName,
1312 ndo->ndo_tstamp_precision, ebuf);
1313 #else
1314 pd = pcap_open_offline(RFileName, ebuf);
1315 #endif
1316
1317 if (pd == NULL)
1318 error("%s", ebuf);
1319 #ifdef HAVE_CAPSICUM
1320 cap_rights_init(&rights, CAP_READ);
1321 if (cap_rights_limit(fileno(pcap_file(pd)), &rights) < 0 &&
1322 errno != ENOSYS) {
1323 error("unable to limit pcap descriptor");
1324 }
1325 #endif
1326 dlt = pcap_datalink(pd);
1327 dlt_name = pcap_datalink_val_to_name(dlt);
1328 if (dlt_name == NULL) {
1329 fprintf(stderr, "reading from file %s, link-type %u\n",
1330 RFileName, dlt);
1331 } else {
1332 fprintf(stderr,
1333 "reading from file %s, link-type %s (%s)\n",
1334 RFileName, dlt_name,
1335 pcap_datalink_val_to_description(dlt));
1336 }
1337 } else {
1338 /*
1339 * We're doing a live capture.
1340 */
1341 if (device == NULL) {
1342 #ifdef HAVE_PCAP_FINDALLDEVS
1343 if (pcap_findalldevs(&devlist, ebuf) >= 0 &&
1344 devlist != NULL) {
1345 device = strdup(devlist->name);
1346 pcap_freealldevs(devlist);
1347 }
1348 #else /* HAVE_PCAP_FINDALLDEVS */
1349 device = pcap_lookupdev(ebuf);
1350 #endif
1351 if (device == NULL)
1352 error("%s", ebuf);
1353 }
1354 #ifdef _WIN32
1355 /*
1356 * Print a message to the standard error on Windows.
1357 * XXX - why do it here, with a different message?
1358 */
1359 if(strlen(device) == 1) /* we assume that an ASCII string is always longer than 1 char */
1360 { /* a Unicode string has a \0 as second byte (so strlen() is 1) */
1361 fprintf(stderr, "%s: listening on %ws\n", program_name, device);
1362 }
1363 else
1364 {
1365 fprintf(stderr, "%s: listening on %s\n", program_name, device);
1366 }
1367
1368 fflush(stderr);
1369 #endif /* _WIN32 */
1370 #ifdef HAVE_PCAP_CREATE
1371 pd = pcap_create(device, ebuf);
1372 if (pd == NULL)
1373 error("%s", ebuf);
1374 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1375 if (Jflag)
1376 show_tstamp_types_and_exit(device);
1377 #endif
1378 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1379 status = pcap_set_tstamp_precision(pd, ndo->ndo_tstamp_precision);
1380 if (status != 0)
1381 error("%s: Can't set %ssecond time stamp precision: %s",
1382 device,
1383 tstamp_precision_to_string(ndo->ndo_tstamp_precision),
1384 pcap_statustostr(status));
1385 #endif
1386
1387 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1388 if (immediate_mode) {
1389 status = pcap_set_immediate_mode(pd, 1);
1390 if (status != 0)
1391 error("%s: Can't set immediate mode: %s",
1392 device,
1393 pcap_statustostr(status));
1394 }
1395 #endif
1396 /*
1397 * Is this an interface that supports monitor mode?
1398 */
1399 if (pcap_can_set_rfmon(pd) == 1)
1400 supports_monitor_mode = 1;
1401 else
1402 supports_monitor_mode = 0;
1403 status = pcap_set_snaplen(pd, ndo->ndo_snaplen);
1404 if (status != 0)
1405 error("%s: Can't set snapshot length: %s",
1406 device, pcap_statustostr(status));
1407 status = pcap_set_promisc(pd, !pflag);
1408 if (status != 0)
1409 error("%s: Can't set promiscuous mode: %s",
1410 device, pcap_statustostr(status));
1411 if (Iflag) {
1412 status = pcap_set_rfmon(pd, 1);
1413 if (status != 0)
1414 error("%s: Can't set monitor mode: %s",
1415 device, pcap_statustostr(status));
1416 }
1417 status = pcap_set_timeout(pd, 1000);
1418 if (status != 0)
1419 error("%s: pcap_set_timeout failed: %s",
1420 device, pcap_statustostr(status));
1421 if (Bflag != 0) {
1422 status = pcap_set_buffer_size(pd, Bflag);
1423 if (status != 0)
1424 error("%s: Can't set buffer size: %s",
1425 device, pcap_statustostr(status));
1426 }
1427 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1428 if (jflag != -1) {
1429 status = pcap_set_tstamp_type(pd, jflag);
1430 if (status < 0)
1431 error("%s: Can't set time stamp type: %s",
1432 device, pcap_statustostr(status));
1433 }
1434 #endif
1435 status = pcap_activate(pd);
1436 if (status < 0) {
1437 /*
1438 * pcap_activate() failed.
1439 */
1440 cp = pcap_geterr(pd);
1441 if (status == PCAP_ERROR)
1442 error("%s", cp);
1443 else if ((status == PCAP_ERROR_NO_SUCH_DEVICE ||
1444 status == PCAP_ERROR_PERM_DENIED) &&
1445 *cp != '\0')
1446 error("%s: %s\n(%s)", device,
1447 pcap_statustostr(status), cp);
1448 else
1449 error("%s: %s", device,
1450 pcap_statustostr(status));
1451 } else if (status > 0) {
1452 /*
1453 * pcap_activate() succeeded, but it's warning us
1454 * of a problem it had.
1455 */
1456 cp = pcap_geterr(pd);
1457 if (status == PCAP_WARNING)
1458 warning("%s", cp);
1459 else if (status == PCAP_WARNING_PROMISC_NOTSUP &&
1460 *cp != '\0')
1461 warning("%s: %s\n(%s)", device,
1462 pcap_statustostr(status), cp);
1463 else
1464 warning("%s: %s", device,
1465 pcap_statustostr(status));
1466 }
1467 #ifdef HAVE_PCAP_SETDIRECTION
1468 if (Qflag != -1) {
1469 status = pcap_setdirection(pd, Qflag);
1470 if (status != 0)
1471 error("%s: pcap_setdirection() failed: %s",
1472 device, pcap_geterr(pd));
1473 }
1474 #endif /* HAVE_PCAP_SETDIRECTION */
1475 #else
1476 *ebuf = '\0';
1477 pd = pcap_open_live(device, ndo->ndo_snaplen, !pflag, 1000,
1478 ebuf);
1479 if (pd == NULL)
1480 error("%s", ebuf);
1481 else if (*ebuf)
1482 warning("%s", ebuf);
1483 #endif /* HAVE_PCAP_CREATE */
1484 /*
1485 * Let user own process after socket has been opened.
1486 */
1487 #ifndef _WIN32
1488 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1489 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1490 #endif /* _WIN32 */
1491 #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32)
1492 if(Bflag != 0)
1493 if(pcap_setbuff(pd, Bflag)==-1){
1494 error("%s", pcap_geterr(pd));
1495 }
1496 #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */
1497 if (Lflag)
1498 show_dlts_and_exit(device);
1499 if (yflag_dlt >= 0) {
1500 #ifdef HAVE_PCAP_SET_DATALINK
1501 if (pcap_set_datalink(pd, yflag_dlt) < 0)
1502 error("%s", pcap_geterr(pd));
1503 #else
1504 /*
1505 * We don't actually support changing the
1506 * data link type, so we only let them
1507 * set it to what it already is.
1508 */
1509 if (yflag_dlt != pcap_datalink(pd)) {
1510 error("%s is not one of the DLTs supported by this device\n",
1511 yflag_dlt_name);
1512 }
1513 #endif
1514 (void)fprintf(stderr, "%s: data link type %s\n",
1515 program_name, yflag_dlt_name);
1516 (void)fflush(stderr);
1517 }
1518 i = pcap_snapshot(pd);
1519 if (ndo->ndo_snaplen < i) {
1520 warning("snaplen raised from %d to %d", ndo->ndo_snaplen, i);
1521 ndo->ndo_snaplen = i;
1522 }
1523 if(ndo->ndo_fflag != 0) {
1524 if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
1525 warning("foreign (-f) flag used but: %s", ebuf);
1526 }
1527 }
1528
1529 }
1530 if (infile)
1531 cmdbuf = read_infile(infile);
1532 else
1533 cmdbuf = copy_argv(&argv[optind]);
1534
1535 #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
1536 pcap_set_optimizer_debug(dflag);
1537 #endif
1538 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1539 error("%s", pcap_geterr(pd));
1540 if (dflag) {
1541 bpf_dump(&fcode, dflag);
1542 pcap_close(pd);
1543 free(cmdbuf);
1544 pcap_freecode(&fcode);
1545 exit(0);
1546 }
1547 init_print(ndo, localnet, netmask, timezone_offset);
1548
1549 #ifndef _WIN32
1550 (void)setsignal(SIGPIPE, cleanup);
1551 (void)setsignal(SIGTERM, cleanup);
1552 (void)setsignal(SIGINT, cleanup);
1553 #endif /* _WIN32 */
1554 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1555 (void)setsignal(SIGCHLD, child_cleanup);
1556 #endif
1557 /* Cooperate with nohup(1) */
1558 #ifndef _WIN32
1559 if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
1560 (void)setsignal(SIGHUP, oldhandler);
1561 #endif /* _WIN32 */
1562
1563 #ifndef _WIN32
1564 /*
1565 * If a user name was specified with "-Z", attempt to switch to
1566 * that user's UID. This would probably be used with sudo,
1567 * to allow tcpdump to be run in a special restricted
1568 * account (if you just want to allow users to open capture
1569 * devices, and can't just give users that permission,
1570 * you'd make tcpdump set-UID or set-GID).
1571 *
1572 * Tcpdump doesn't necessarily write only to one savefile;
1573 * the general only way to allow a -Z instance to write to
1574 * savefiles as the user under whose UID it's run, rather
1575 * than as the user specified with -Z, would thus be to switch
1576 * to the original user ID before opening a capture file and
1577 * then switch back to the -Z user ID after opening the savefile.
1578 * Switching to the -Z user ID only after opening the first
1579 * savefile doesn't handle the general case.
1580 */
1581
1582 if (getuid() == 0 || geteuid() == 0) {
1583 #ifdef HAVE_LIBCAP_NG
1584 /* Initialize capng */
1585 capng_clear(CAPNG_SELECT_BOTH);
1586 if (username) {
1587 capng_updatev(
1588 CAPNG_ADD,
1589 CAPNG_PERMITTED | CAPNG_EFFECTIVE,
1590 CAP_SETUID,
1591 CAP_SETGID,
1592 -1);
1593 }
1594
1595 if (WFileName) {
1596 capng_update(
1597 CAPNG_ADD,
1598 CAPNG_PERMITTED | CAPNG_EFFECTIVE,
1599 CAP_DAC_OVERRIDE
1600 );
1601 }
1602 capng_apply(CAPNG_SELECT_BOTH);
1603 #endif /* HAVE_LIBCAP_NG */
1604 if (username || chroot_dir)
1605 droproot(username, chroot_dir);
1606
1607 }
1608 #endif /* _WIN32 */
1609
1610 if (pcap_setfilter(pd, &fcode) < 0)
1611 error("%s", pcap_geterr(pd));
1612 #ifdef HAVE_CAPSICUM
1613 if (RFileName == NULL && VFileName == NULL) {
1614 static const unsigned long cmds[] = { BIOCGSTATS, BIOCROTZBUF };
1615
1616 cap_rights_init(&rights, CAP_IOCTL, CAP_READ);
1617 if (cap_rights_limit(pcap_fileno(pd), &rights) < 0 &&
1618 errno != ENOSYS) {
1619 error("unable to limit pcap descriptor");
1620 }
1621 if (cap_ioctls_limit(pcap_fileno(pd), cmds,
1622 sizeof(cmds) / sizeof(cmds[0])) < 0 && errno != ENOSYS) {
1623 error("unable to limit ioctls on pcap descriptor");
1624 }
1625 }
1626 #endif
1627 if (WFileName) {
1628 pcap_dumper_t *p;
1629 /* Do not exceed the default PATH_MAX for files. */
1630 dumpinfo.CurrentFileName = (char *)malloc(PATH_MAX + 1);
1631
1632 if (dumpinfo.CurrentFileName == NULL)
1633 error("malloc of dumpinfo.CurrentFileName");
1634
1635 /* We do not need numbering for dumpfiles if Cflag isn't set. */
1636 if (Cflag != 0)
1637 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
1638 else
1639 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
1640
1641 p = pcap_dump_open(pd, dumpinfo.CurrentFileName);
1642 #ifdef HAVE_LIBCAP_NG
1643 /* Give up CAP_DAC_OVERRIDE capability.
1644 * Only allow it to be restored if the -C or -G flag have been
1645 * set since we may need to create more files later on.
1646 */
1647 capng_update(
1648 CAPNG_DROP,
1649 (Cflag || Gflag ? 0 : CAPNG_PERMITTED)
1650 | CAPNG_EFFECTIVE,
1651 CAP_DAC_OVERRIDE
1652 );
1653 capng_apply(CAPNG_SELECT_BOTH);
1654 #endif /* HAVE_LIBCAP_NG */
1655 if (p == NULL)
1656 error("%s", pcap_geterr(pd));
1657 #ifdef HAVE_CAPSICUM
1658 set_dumper_capsicum_rights(p);
1659 #endif
1660 if (Cflag != 0 || Gflag != 0) {
1661 #ifdef HAVE_CAPSICUM
1662 dumpinfo.WFileName = strdup(basename(WFileName));
1663 if (dumpinfo.WFileName == NULL) {
1664 error("Unable to allocate memory for file %s",
1665 WFileName);
1666 }
1667 dumpinfo.dirfd = open(dirname(WFileName),
1668 O_DIRECTORY | O_RDONLY);
1669 if (dumpinfo.dirfd < 0) {
1670 error("unable to open directory %s",
1671 dirname(WFileName));
1672 }
1673 cap_rights_init(&rights, CAP_CREATE, CAP_FCNTL,
1674 CAP_FTRUNCATE, CAP_LOOKUP, CAP_SEEK, CAP_WRITE);
1675 if (cap_rights_limit(dumpinfo.dirfd, &rights) < 0 &&
1676 errno != ENOSYS) {
1677 error("unable to limit directory rights");
1678 }
1679 if (cap_fcntls_limit(dumpinfo.dirfd, CAP_FCNTL_GETFL) < 0 &&
1680 errno != ENOSYS) {
1681 error("unable to limit dump descriptor fcntls");
1682 }
1683 #else /* !HAVE_CAPSICUM */
1684 dumpinfo.WFileName = WFileName;
1685 #endif
1686 callback = dump_packet_and_trunc;
1687 dumpinfo.pd = pd;
1688 dumpinfo.p = p;
1689 pcap_userdata = (u_char *)&dumpinfo;
1690 } else {
1691 callback = dump_packet;
1692 pcap_userdata = (u_char *)p;
1693 }
1694 #ifdef HAVE_PCAP_DUMP_FLUSH
1695 if (Uflag)
1696 pcap_dump_flush(p);
1697 #endif
1698 } else {
1699 dlt = pcap_datalink(pd);
1700 ndo->ndo_if_printer = get_if_printer(ndo, dlt);
1701 callback = print_packet;
1702 pcap_userdata = (u_char *)ndo;
1703 }
1704
1705 #ifdef SIGNAL_REQ_INFO
1706 /*
1707 * We can't get statistics when reading from a file rather
1708 * than capturing from a device.
1709 */
1710 if (RFileName == NULL)
1711 (void)setsignal(SIGNAL_REQ_INFO, requestinfo);
1712 #endif
1713
1714 if (ndo->ndo_vflag > 0 && WFileName) {
1715 /*
1716 * When capturing to a file, "-v" means tcpdump should,
1717 * every 10 seconds, "v"erbosely report the number of
1718 * packets captured.
1719 */
1720 #ifdef USE_WIN32_MM_TIMER
1721 /* call verbose_stats_dump() each 1000 +/-100msec */
1722 timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
1723 setvbuf(stderr, NULL, _IONBF, 0);
1724 #elif defined(HAVE_ALARM)
1725 (void)setsignal(SIGALRM, verbose_stats_dump);
1726 alarm(1);
1727 #endif
1728 }
1729
1730 #ifndef _WIN32
1731 if (RFileName == NULL) {
1732 /*
1733 * Live capture (if -V was specified, we set RFileName
1734 * to a file from the -V file). Print a message to
1735 * the standard error on UN*X.
1736 */
1737 if (!ndo->ndo_vflag && !WFileName) {
1738 (void)fprintf(stderr,
1739 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
1740 program_name);
1741 } else
1742 (void)fprintf(stderr, "%s: ", program_name);
1743 dlt = pcap_datalink(pd);
1744 dlt_name = pcap_datalink_val_to_name(dlt);
1745 if (dlt_name == NULL) {
1746 (void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
1747 device, dlt, ndo->ndo_snaplen);
1748 } else {
1749 (void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
1750 device, dlt_name,
1751 pcap_datalink_val_to_description(dlt), ndo->ndo_snaplen);
1752 }
1753 (void)fflush(stderr);
1754 }
1755 #endif /* _WIN32 */
1756
1757 #ifdef HAVE_CAPSICUM
1758 cansandbox = (ndo->ndo_nflag && VFileName == NULL && zflag == NULL);
1759 if (cansandbox && cap_enter() < 0 && errno != ENOSYS)
1760 error("unable to enter the capability mode");
1761 #endif /* HAVE_CAPSICUM */
1762
1763 do {
1764 status = pcap_loop(pd, cnt, callback, pcap_userdata);
1765 if (WFileName == NULL) {
1766 /*
1767 * We're printing packets. Flush the printed output,
1768 * so it doesn't get intermingled with error output.
1769 */
1770 if (status == -2) {
1771 /*
1772 * We got interrupted, so perhaps we didn't
1773 * manage to finish a line we were printing.
1774 * Print an extra newline, just in case.
1775 */
1776 putchar('\n');
1777 }
1778 (void)fflush(stdout);
1779 }
1780 if (status == -2) {
1781 /*
1782 * We got interrupted. If we are reading multiple
1783 * files (via -V) set these so that we stop.
1784 */
1785 VFileName = NULL;
1786 ret = NULL;
1787 }
1788 if (status == -1) {
1789 /*
1790 * Error. Report it.
1791 */
1792 (void)fprintf(stderr, "%s: pcap_loop: %s\n",
1793 program_name, pcap_geterr(pd));
1794 }
1795 if (RFileName == NULL) {
1796 /*
1797 * We're doing a live capture. Report the capture
1798 * statistics.
1799 */
1800 info(1);
1801 }
1802 pcap_close(pd);
1803 if (VFileName != NULL) {
1804 ret = get_next_file(VFile, VFileLine);
1805 if (ret) {
1806 int new_dlt;
1807
1808 RFileName = VFileLine;
1809 pd = pcap_open_offline(RFileName, ebuf);
1810 if (pd == NULL)
1811 error("%s", ebuf);
1812 #ifdef HAVE_CAPSICUM
1813 cap_rights_init(&rights, CAP_READ);
1814 if (cap_rights_limit(fileno(pcap_file(pd)),
1815 &rights) < 0 && errno != ENOSYS) {
1816 error("unable to limit pcap descriptor");
1817 }
1818 #endif
1819 new_dlt = pcap_datalink(pd);
1820 if (new_dlt != dlt) {
1821 /*
1822 * The new file has a different
1823 * link-layer header type from the
1824 * previous one.
1825 */
1826 if (WFileName != NULL) {
1827 /*
1828 * We're writing raw packets
1829 * that match the filter to
1830 * a pcap file. pcap files
1831 * don't support multiple
1832 * different link-layer
1833 * header types, so we fail
1834 * here.
1835 */
1836 error("%s: new dlt does not match original", RFileName);
1837 }
1838
1839 /*
1840 * We're printing the decoded packets;
1841 * switch to the new DLT.
1842 *
1843 * To do that, we need to change
1844 * the printer, change the DLT name,
1845 * and recompile the filter with
1846 * the new DLT.
1847 */
1848 dlt = new_dlt;
1849 ndo->ndo_if_printer = get_if_printer(ndo, dlt);
1850 dlt_name = pcap_datalink_val_to_name(dlt);
1851 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1852 error("%s", pcap_geterr(pd));
1853 }
1854
1855 /*
1856 * Set the filter on the new file.
1857 */
1858 if (pcap_setfilter(pd, &fcode) < 0)
1859 error("%s", pcap_geterr(pd));
1860
1861 /*
1862 * Report the new file.
1863 */
1864 if (dlt_name == NULL) {
1865 fprintf(stderr, "reading from file %s, link-type %u\n",
1866 RFileName, dlt);
1867 } else {
1868 fprintf(stderr,
1869 "reading from file %s, link-type %s (%s)\n",
1870 RFileName, dlt_name,
1871 pcap_datalink_val_to_description(dlt));
1872 }
1873 }
1874 }
1875 }
1876 while (ret != NULL);
1877
1878 free(cmdbuf);
1879 pcap_freecode(&fcode);
1880 exit(status == -1 ? 1 : 0);
1881 }
1882
1883 /* make a clean exit on interrupts */
1884 static RETSIGTYPE
1885 cleanup(int signo _U_)
1886 {
1887 #ifdef USE_WIN32_MM_TIMER
1888 if (timer_id)
1889 timeKillEvent(timer_id);
1890 timer_id = 0;
1891 #elif defined(HAVE_ALARM)
1892 alarm(0);
1893 #endif
1894
1895 #ifdef HAVE_PCAP_BREAKLOOP
1896 /*
1897 * We have "pcap_breakloop()"; use it, so that we do as little
1898 * as possible in the signal handler (it's probably not safe
1899 * to do anything with standard I/O streams in a signal handler -
1900 * the ANSI C standard doesn't say it is).
1901 */
1902 pcap_breakloop(pd);
1903 #else
1904 /*
1905 * We don't have "pcap_breakloop()"; this isn't safe, but
1906 * it's the best we can do. Print the summary if we're
1907 * not reading from a savefile - i.e., if we're doing a
1908 * live capture - and exit.
1909 */
1910 if (pd != NULL && pcap_file(pd) == NULL) {
1911 /*
1912 * We got interrupted, so perhaps we didn't
1913 * manage to finish a line we were printing.
1914 * Print an extra newline, just in case.
1915 */
1916 putchar('\n');
1917 (void)fflush(stdout);
1918 info(1);
1919 }
1920 exit(0);
1921 #endif
1922 }
1923
1924 /*
1925 On windows, we do not use a fork, so we do not care less about
1926 waiting a child processes to die
1927 */
1928 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1929 static RETSIGTYPE
1930 child_cleanup(int signo _U_)
1931 {
1932 wait(NULL);
1933 }
1934 #endif /* HAVE_FORK && HAVE_VFORK */
1935
1936 static void
1937 info(register int verbose)
1938 {
1939 struct pcap_stat stats;
1940
1941 /*
1942 * Older versions of libpcap didn't set ps_ifdrop on some
1943 * platforms; initialize it to 0 to handle that.
1944 */
1945 stats.ps_ifdrop = 0;
1946 if (pcap_stats(pd, &stats) < 0) {
1947 (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
1948 infoprint = 0;
1949 return;
1950 }
1951
1952 if (!verbose)
1953 fprintf(stderr, "%s: ", program_name);
1954
1955 (void)fprintf(stderr, "%u packet%s captured", packets_captured,
1956 PLURAL_SUFFIX(packets_captured));
1957 if (!verbose)
1958 fputs(", ", stderr);
1959 else
1960 putc('\n', stderr);
1961 (void)fprintf(stderr, "%u packet%s received by filter", stats.ps_recv,
1962 PLURAL_SUFFIX(stats.ps_recv));
1963 if (!verbose)
1964 fputs(", ", stderr);
1965 else
1966 putc('\n', stderr);
1967 (void)fprintf(stderr, "%u packet%s dropped by kernel", stats.ps_drop,
1968 PLURAL_SUFFIX(stats.ps_drop));
1969 if (stats.ps_ifdrop != 0) {
1970 if (!verbose)
1971 fputs(", ", stderr);
1972 else
1973 putc('\n', stderr);
1974 (void)fprintf(stderr, "%u packet%s dropped by interface\n",
1975 stats.ps_ifdrop, PLURAL_SUFFIX(stats.ps_ifdrop));
1976 } else
1977 putc('\n', stderr);
1978 infoprint = 0;
1979 }
1980
1981 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1982 #ifdef HAVE_FORK
1983 #define fork_subprocess() fork()
1984 #else
1985 #define fork_subprocess() vfork()
1986 #endif
1987 static void
1988 compress_savefile(const char *filename)
1989 {
1990 pid_t child;
1991
1992 child = fork_subprocess();
1993 if (child == -1) {
1994 fprintf(stderr,
1995 "compress_savefile: fork failed: %s\n",
1996 pcap_strerror(errno));
1997 return;
1998 }
1999 if (child != 0) {
2000 /* Parent process. */
2001 return;
2002 }
2003
2004 /*
2005 * Child process.
2006 * Set to lowest priority so that this doesn't disturb the capture.
2007 */
2008 #ifdef NZERO
2009 setpriority(PRIO_PROCESS, 0, NZERO - 1);
2010 #else
2011 setpriority(PRIO_PROCESS, 0, 19);
2012 #endif
2013 if (execlp(zflag, zflag, filename, (char *)NULL) == -1)
2014 fprintf(stderr,
2015 "compress_savefile: execlp(%s, %s) failed: %s\n",
2016 zflag,
2017 filename,
2018 pcap_strerror(errno));
2019 #ifdef HAVE_FORK
2020 exit(1);
2021 #else
2022 _exit(1);
2023 #endif
2024 }
2025 #else /* HAVE_FORK && HAVE_VFORK */
2026 static void
2027 compress_savefile(const char *filename)
2028 {
2029 fprintf(stderr,
2030 "compress_savefile failed. Functionality not implemented under your system\n");
2031 }
2032 #endif /* HAVE_FORK && HAVE_VFORK */
2033
2034 static void
2035 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2036 {
2037 struct dump_info *dump_info;
2038
2039 ++packets_captured;
2040
2041 ++infodelay;
2042
2043 dump_info = (struct dump_info *)user;
2044
2045 /*
2046 * XXX - this won't force the file to rotate on the specified time
2047 * boundary, but it will rotate on the first packet received after the
2048 * specified Gflag number of seconds. Note: if a Gflag time boundary
2049 * and a Cflag size boundary coincide, the time rotation will occur
2050 * first thereby cancelling the Cflag boundary (since the file should
2051 * be 0).
2052 */
2053 if (Gflag != 0) {
2054 /* Check if it is time to rotate */
2055 time_t t;
2056
2057 /* Get the current time */
2058 if ((t = time(NULL)) == (time_t)-1) {
2059 error("dump_and_trunc_packet: can't get current_time: %s",
2060 pcap_strerror(errno));
2061 }
2062
2063
2064 /* If the time is greater than the specified window, rotate */
2065 if (t - Gflag_time >= Gflag) {
2066 #ifdef HAVE_CAPSICUM
2067 FILE *fp;
2068 int fd;
2069 #endif
2070
2071 /* Update the Gflag_time */
2072 Gflag_time = t;
2073 /* Update Gflag_count */
2074 Gflag_count++;
2075 /*
2076 * Close the current file and open a new one.
2077 */
2078 pcap_dump_close(dump_info->p);
2079
2080 /*
2081 * Compress the file we just closed, if the user asked for it
2082 */
2083 if (zflag != NULL)
2084 compress_savefile(dump_info->CurrentFileName);
2085
2086 /*
2087 * Check to see if we've exceeded the Wflag (when
2088 * not using Cflag).
2089 */
2090 if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
2091 (void)fprintf(stderr, "Maximum file limit reached: %d\n",
2092 Wflag);
2093 exit(0);
2094 /* NOTREACHED */
2095 }
2096 if (dump_info->CurrentFileName != NULL)
2097 free(dump_info->CurrentFileName);
2098 /* Allocate space for max filename + \0. */
2099 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2100 if (dump_info->CurrentFileName == NULL)
2101 error("dump_packet_and_trunc: malloc");
2102 /*
2103 * Gflag was set otherwise we wouldn't be here. Reset the count
2104 * so multiple files would end with 1,2,3 in the filename.
2105 * The counting is handled with the -C flow after this.
2106 */
2107 Cflag_count = 0;
2108
2109 /*
2110 * This is always the first file in the Cflag
2111 * rotation: e.g. 0
2112 * We also don't need numbering if Cflag is not set.
2113 */
2114 if (Cflag != 0)
2115 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
2116 WflagChars);
2117 else
2118 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
2119
2120 #ifdef HAVE_LIBCAP_NG
2121 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2122 capng_apply(CAPNG_SELECT_BOTH);
2123 #endif /* HAVE_LIBCAP_NG */
2124 #ifdef HAVE_CAPSICUM
2125 fd = openat(dump_info->dirfd,
2126 dump_info->CurrentFileName,
2127 O_CREAT | O_WRONLY | O_TRUNC, 0644);
2128 if (fd < 0) {
2129 error("unable to open file %s",
2130 dump_info->CurrentFileName);
2131 }
2132 fp = fdopen(fd, "w");
2133 if (fp == NULL) {
2134 error("unable to fdopen file %s",
2135 dump_info->CurrentFileName);
2136 }
2137 dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2138 #else /* !HAVE_CAPSICUM */
2139 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2140 #endif
2141 #ifdef HAVE_LIBCAP_NG
2142 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2143 capng_apply(CAPNG_SELECT_BOTH);
2144 #endif /* HAVE_LIBCAP_NG */
2145 if (dump_info->p == NULL)
2146 error("%s", pcap_geterr(pd));
2147 #ifdef HAVE_CAPSICUM
2148 set_dumper_capsicum_rights(dump_info->p);
2149 #endif
2150 }
2151 }
2152
2153 /*
2154 * XXX - this won't prevent capture files from getting
2155 * larger than Cflag - the last packet written to the
2156 * file could put it over Cflag.
2157 */
2158 if (Cflag != 0) {
2159 long size = pcap_dump_ftell(dump_info->p);
2160
2161 if (size == -1)
2162 error("ftell fails on output file");
2163 if (size > Cflag) {
2164 #ifdef HAVE_CAPSICUM
2165 FILE *fp;
2166 int fd;
2167 #endif
2168
2169 /*
2170 * Close the current file and open a new one.
2171 */
2172 pcap_dump_close(dump_info->p);
2173
2174 /*
2175 * Compress the file we just closed, if the user
2176 * asked for it.
2177 */
2178 if (zflag != NULL)
2179 compress_savefile(dump_info->CurrentFileName);
2180
2181 Cflag_count++;
2182 if (Wflag > 0) {
2183 if (Cflag_count >= Wflag)
2184 Cflag_count = 0;
2185 }
2186 if (dump_info->CurrentFileName != NULL)
2187 free(dump_info->CurrentFileName);
2188 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2189 if (dump_info->CurrentFileName == NULL)
2190 error("dump_packet_and_trunc: malloc");
2191 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
2192 #ifdef HAVE_LIBCAP_NG
2193 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2194 capng_apply(CAPNG_SELECT_BOTH);
2195 #endif /* HAVE_LIBCAP_NG */
2196 #ifdef HAVE_CAPSICUM
2197 fd = openat(dump_info->dirfd, dump_info->CurrentFileName,
2198 O_CREAT | O_WRONLY | O_TRUNC, 0644);
2199 if (fd < 0) {
2200 error("unable to open file %s",
2201 dump_info->CurrentFileName);
2202 }
2203 fp = fdopen(fd, "w");
2204 if (fp == NULL) {
2205 error("unable to fdopen file %s",
2206 dump_info->CurrentFileName);
2207 }
2208 dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2209 #else /* !HAVE_CAPSICUM */
2210 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2211 #endif
2212 #ifdef HAVE_LIBCAP_NG
2213 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2214 capng_apply(CAPNG_SELECT_BOTH);
2215 #endif /* HAVE_LIBCAP_NG */
2216 if (dump_info->p == NULL)
2217 error("%s", pcap_geterr(pd));
2218 #ifdef HAVE_CAPSICUM
2219 set_dumper_capsicum_rights(dump_info->p);
2220 #endif
2221 }
2222 }
2223
2224 pcap_dump((u_char *)dump_info->p, h, sp);
2225 #ifdef HAVE_PCAP_DUMP_FLUSH
2226 if (Uflag)
2227 pcap_dump_flush(dump_info->p);
2228 #endif
2229
2230 --infodelay;
2231 if (infoprint)
2232 info(0);
2233 }
2234
2235 static void
2236 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2237 {
2238 ++packets_captured;
2239
2240 ++infodelay;
2241
2242 pcap_dump(user, h, sp);
2243 #ifdef HAVE_PCAP_DUMP_FLUSH
2244 if (Uflag)
2245 pcap_dump_flush((pcap_dumper_t *)user);
2246 #endif
2247
2248 --infodelay;
2249 if (infoprint)
2250 info(0);
2251 }
2252
2253 static void
2254 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2255 {
2256 ++packets_captured;
2257
2258 ++infodelay;
2259
2260 pretty_print_packet((netdissect_options *)user, h, sp, packets_captured);
2261
2262 --infodelay;
2263 if (infoprint)
2264 info(0);
2265 }
2266
2267 #ifdef _WIN32
2268 /*
2269 * XXX - there should really be libpcap calls to get the version
2270 * number as a string (the string would be generated from #defines
2271 * at run time, so that it's not generated from string constants
2272 * in the library, as, on many UNIX systems, those constants would
2273 * be statically linked into the application executable image, and
2274 * would thus reflect the version of libpcap on the system on
2275 * which the application was *linked*, not the system on which it's
2276 * *running*.
2277 *
2278 * That routine should be documented, unlike the "version[]"
2279 * string, so that UNIX vendors providing their own libpcaps
2280 * don't omit it (as a couple of vendors have...).
2281 *
2282 * Packet.dll should perhaps also export a routine to return the
2283 * version number of the Packet.dll code, to supply the
2284 * "Wpcap_version" information on Windows.
2285 */
2286 char WDversion[]="current-git.tcpdump.org";
2287 #if !defined(HAVE_GENERATED_VERSION)
2288 char version[]="current-git.tcpdump.org";
2289 #endif
2290 char pcap_version[]="current-git.tcpdump.org";
2291 char Wpcap_version[]="3.1";
2292 #endif
2293
2294 #ifdef SIGNAL_REQ_INFO
2295 RETSIGTYPE requestinfo(int signo _U_)
2296 {
2297 if (infodelay)
2298 ++infoprint;
2299 else
2300 info(0);
2301 }
2302 #endif
2303
2304 /*
2305 * Called once each second in verbose mode while dumping to file
2306 */
2307 #ifdef USE_WIN32_MM_TIMER
2308 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
2309 DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
2310 {
2311 if (infodelay == 0)
2312 fprintf(stderr, "Got %u\r", packets_captured);
2313 }
2314 #elif defined(HAVE_ALARM)
2315 static void verbose_stats_dump(int sig _U_)
2316 {
2317 if (infodelay == 0)
2318 fprintf(stderr, "Got %u\r", packets_captured);
2319 alarm(1);
2320 }
2321 #endif
2322
2323 USES_APPLE_DEPRECATED_API
2324 static void
2325 print_version(void)
2326 {
2327 extern char version[];
2328 #ifndef HAVE_PCAP_LIB_VERSION
2329 #if defined(_WIN32) || defined(HAVE_PCAP_VERSION)
2330 extern char pcap_version[];
2331 #else /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2332 static char pcap_version[] = "unknown";
2333 #endif /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2334 #endif /* HAVE_PCAP_LIB_VERSION */
2335
2336 #ifdef HAVE_PCAP_LIB_VERSION
2337 #ifdef _WIN32
2338 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2339 #else /* _WIN32 */
2340 (void)fprintf(stderr, "%s version %s\n", program_name, version);
2341 #endif /* _WIN32 */
2342 (void)fprintf(stderr, "%s\n",pcap_lib_version());
2343 #else /* HAVE_PCAP_LIB_VERSION */
2344 #ifdef _WIN32
2345 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2346 (void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
2347 #else /* _WIN32 */
2348 (void)fprintf(stderr, "%s version %s\n", program_name, version);
2349 (void)fprintf(stderr, "libpcap version %s\n", pcap_version);
2350 #endif /* _WIN32 */
2351 #endif /* HAVE_PCAP_LIB_VERSION */
2352
2353 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
2354 (void)fprintf (stderr, "%s\n", SSLeay_version(SSLEAY_VERSION));
2355 #endif
2356
2357 #ifdef USE_LIBSMI
2358 (void)fprintf (stderr, "SMI-library: %s\n", smi_version_string);
2359 #endif
2360 }
2361 USES_APPLE_RST
2362
2363 static void
2364 print_usage(void)
2365 {
2366 print_version();
2367 (void)fprintf(stderr,
2368 "Usage: %s [-aAbd" D_FLAG "efhH" I_FLAG J_FLAG "KlLnNOpqStu" U_FLAG "vxX#]" B_FLAG_USAGE " [ -c count ]\n", program_name);
2369 (void)fprintf(stderr,
2370 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
2371 (void)fprintf(stderr,
2372 "\t\t[ -i interface ]" j_FLAG_USAGE " [ -M secret ] [ --number ]\n");
2373 #ifdef HAVE_PCAP_SETDIRECTION
2374 (void)fprintf(stderr,
2375 "\t\t[ -Q in|out|inout ]\n");
2376 #endif
2377 (void)fprintf(stderr,
2378 "\t\t[ -r file ] [ -s snaplen ] ");
2379 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2380 (void)fprintf(stderr, "[ --time-stamp-precision precision ]\n");
2381 (void)fprintf(stderr,
2382 "\t\t");
2383 #endif
2384 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
2385 (void)fprintf(stderr, "[ --immediate-mode ] ");
2386 #endif
2387 (void)fprintf(stderr, "[ -T type ] [ --version ] [ -V file ]\n");
2388 (void)fprintf(stderr,
2389 "\t\t[ -w file ] [ -W filecount ] [ -y datalinktype ] [ -z command ]\n");
2390 (void)fprintf(stderr,
2391 "\t\t[ -Z user ] [ expression ]\n");
2392 }
2393 /*
2394 * Local Variables:
2395 * c-style: whitesmith
2396 * c-basic-offset: 8
2397 * End:
2398 */