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