]> The Tcpdump Group git mirrors - tcpdump/blob - tcpdump.c
We can catch SIGINT on Windows as well.
[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 #if defined(USE_WIN32_MM_TIMER)
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 #elif defined(HAVE_ALARM)
231 static void verbose_stats_dump(int sig);
232 #endif
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 capng_updatev(
720 CAPNG_DROP,
721 CAPNG_EFFECTIVE | CAPNG_PERMITTED,
722 CAP_SETUID,
723 CAP_SETGID,
724 CAP_SYS_CHROOT,
725 -1);
726 capng_apply(CAPNG_SELECT_BOTH);
727 #endif /* HAVE_LIBCAP_NG */
728
729 }
730 #endif /* _WIN32 */
731
732 static int
733 getWflagChars(int x)
734 {
735 int c = 0;
736
737 x -= 1;
738 while (x > 0) {
739 c += 1;
740 x /= 10;
741 }
742
743 return c;
744 }
745
746
747 static void
748 MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
749 {
750 char *filename = malloc(PATH_MAX + 1);
751 if (filename == NULL)
752 error("Makefilename: malloc");
753
754 /* Process with strftime if Gflag is set. */
755 if (Gflag != 0) {
756 struct tm *local_tm;
757
758 /* Convert Gflag_time to a usable format */
759 if ((local_tm = localtime(&Gflag_time)) == NULL) {
760 error("MakeTimedFilename: localtime");
761 }
762
763 /* There's no good way to detect an error in strftime since a return
764 * value of 0 isn't necessarily failure.
765 */
766 strftime(filename, PATH_MAX, orig_name, local_tm);
767 } else {
768 strncpy(filename, orig_name, PATH_MAX);
769 }
770
771 if (cnt == 0 && max_chars == 0)
772 strncpy(buffer, filename, PATH_MAX + 1);
773 else
774 if (snprintf(buffer, PATH_MAX + 1, "%s%0*d", filename, max_chars, cnt) > PATH_MAX)
775 /* Report an error if the filename is too large */
776 error("too many output files or filename is too long (> %d)", PATH_MAX);
777 free(filename);
778 }
779
780 static char *
781 get_next_file(FILE *VFile, char *ptr)
782 {
783 char *ret;
784
785 ret = fgets(ptr, PATH_MAX, VFile);
786 if (!ret)
787 return NULL;
788
789 if (ptr[strlen(ptr) - 1] == '\n')
790 ptr[strlen(ptr) - 1] = '\0';
791
792 return ret;
793 }
794
795 #ifdef HAVE_CASPER
796 static cap_channel_t *
797 capdns_setup(void)
798 {
799 cap_channel_t *capcas, *capdnsloc;
800 const char *types[1];
801 int families[2];
802
803 capcas = cap_init();
804 if (capcas == NULL)
805 error("unable to create casper process");
806 capdnsloc = cap_service_open(capcas, "system.dns");
807 /* Casper capability no longer needed. */
808 cap_close(capcas);
809 if (capdnsloc == NULL)
810 error("unable to open system.dns service");
811 /* Limit system.dns to reverse DNS lookups. */
812 types[0] = "ADDR";
813 if (cap_dns_type_limit(capdnsloc, types, 1) < 0)
814 error("unable to limit access to system.dns service");
815 families[0] = AF_INET;
816 families[1] = AF_INET6;
817 if (cap_dns_family_limit(capdnsloc, families, 2) < 0)
818 error("unable to limit access to system.dns service");
819
820 return (capdnsloc);
821 }
822 #endif /* HAVE_CASPER */
823
824 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
825 static int
826 tstamp_precision_from_string(const char *precision)
827 {
828 if (strncmp(precision, "nano", strlen("nano")) == 0)
829 return PCAP_TSTAMP_PRECISION_NANO;
830
831 if (strncmp(precision, "micro", strlen("micro")) == 0)
832 return PCAP_TSTAMP_PRECISION_MICRO;
833
834 return -EINVAL;
835 }
836
837 static const char *
838 tstamp_precision_to_string(int precision)
839 {
840 switch (precision) {
841
842 case PCAP_TSTAMP_PRECISION_MICRO:
843 return "micro";
844
845 case PCAP_TSTAMP_PRECISION_NANO:
846 return "nano";
847
848 default:
849 return "unknown";
850 }
851 }
852 #endif
853
854 #ifdef HAVE_CAPSICUM
855 /*
856 * Ensure that, on a dump file's descriptor, we have all the rights
857 * necessary to make the standard I/O library work with an fdopen()ed
858 * FILE * from that descriptor.
859 *
860 * A long time ago, in a galaxy far far away, AT&T decided that, instead
861 * of providing separate APIs for getting and setting the FD_ flags on a
862 * descriptor, getting and setting the O_ flags on a descriptor, and
863 * locking files, they'd throw them all into a kitchen-sink fcntl() call
864 * along the lines of ioctl(), the fact that ioctl() operations are
865 * largely specific to particular character devices but fcntl() operations
866 * are either generic to all descriptors or generic to all descriptors for
867 * regular files nonwithstanding.
868 *
869 * The Capsicum people decided that fine-grained control of descriptor
870 * operations was required, so that you need to grant permission for
871 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
872 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
873 * collection of things, so there are *individual* fcntls for which
874 * permission needs to be granted.
875 *
876 * The FreeBSD standard I/O people implemented some optimizations that
877 * requires that the standard I/O routines be able to determine whether
878 * the descriptor for the FILE * is open append-only or not; as that
879 * descriptor could have come from an open() rather than an fopen(),
880 * that requires that it be able to do an F_GETFL fcntl() to read
881 * the O_ flags.
882 *
883 * Tcpdump uses ftell() to determine how much data has been written
884 * to a file in order to, when used with -C, determine when it's time
885 * to rotate capture files. ftell() therefore needs to do an lseek()
886 * to find out the file offset and must, thanks to the aforementioned
887 * optimization, also know whether the descriptor is open append-only
888 * or not.
889 *
890 * The net result of all the above is that we need to grant CAP_SEEK,
891 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
892 *
893 * Perhaps this is the universe's way of saying that either
894 *
895 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
896 * using it, so that Capsicum-capable tcpdump wouldn't need to do
897 * an fdopen()
898 *
899 * or
900 *
901 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
902 * I/O library that knows what rights are needed by the standard
903 * I/O library, based on the open mode, and assigns them, perhaps
904 * with an additional argument indicating, for example, whether
905 * seeking should be allowed, so that tcpdump doesn't need to know
906 * what the standard I/O library happens to require this week.
907 */
908 static void
909 set_dumper_capsicum_rights(pcap_dumper_t *p)
910 {
911 int fd = fileno(pcap_dump_file(p));
912 cap_rights_t rights;
913
914 cap_rights_init(&rights, CAP_SEEK, CAP_WRITE, CAP_FCNTL);
915 if (cap_rights_limit(fd, &rights) < 0 && errno != ENOSYS) {
916 error("unable to limit dump descriptor");
917 }
918 if (cap_fcntls_limit(fd, CAP_FCNTL_GETFL) < 0 && errno != ENOSYS) {
919 error("unable to limit dump descriptor fcntls");
920 }
921 }
922 #endif
923
924 /*
925 * Copy arg vector into a new buffer, concatenating arguments with spaces.
926 */
927 static char *
928 copy_argv(register char **argv)
929 {
930 register char **p;
931 register u_int len = 0;
932 char *buf;
933 char *src, *dst;
934
935 p = argv;
936 if (*p == NULL)
937 return 0;
938
939 while (*p)
940 len += strlen(*p++) + 1;
941
942 buf = (char *)malloc(len);
943 if (buf == NULL)
944 error("copy_argv: malloc");
945
946 p = argv;
947 dst = buf;
948 while ((src = *p++) != NULL) {
949 while ((*dst++ = *src++) != '\0')
950 ;
951 dst[-1] = ' ';
952 }
953 dst[-1] = '\0';
954
955 return buf;
956 }
957
958 /*
959 * On Windows, we need to open the file in binary mode, so that
960 * we get all the bytes specified by the size we get from "fstat()".
961 * On UNIX, that's not necessary. O_BINARY is defined on Windows;
962 * we define it as 0 if it's not defined, so it does nothing.
963 */
964 #ifndef O_BINARY
965 #define O_BINARY 0
966 #endif
967
968 static char *
969 read_infile(char *fname)
970 {
971 register int i, fd, cc;
972 register char *cp;
973 struct stat buf;
974
975 fd = open(fname, O_RDONLY|O_BINARY);
976 if (fd < 0)
977 error("can't open %s: %s", fname, pcap_strerror(errno));
978
979 if (fstat(fd, &buf) < 0)
980 error("can't stat %s: %s", fname, pcap_strerror(errno));
981
982 cp = malloc((u_int)buf.st_size + 1);
983 if (cp == NULL)
984 error("malloc(%d) for %s: %s", (u_int)buf.st_size + 1,
985 fname, pcap_strerror(errno));
986 cc = read(fd, cp, (u_int)buf.st_size);
987 if (cc < 0)
988 error("read %s: %s", fname, pcap_strerror(errno));
989 if (cc != buf.st_size)
990 error("short read %s (%d != %d)", fname, cc, (int)buf.st_size);
991
992 close(fd);
993 /* replace "# comment" with spaces */
994 for (i = 0; i < cc; i++) {
995 if (cp[i] == '#')
996 while (i < cc && cp[i] != '\n')
997 cp[i++] = ' ';
998 }
999 cp[cc] = '\0';
1000 return (cp);
1001 }
1002
1003 #ifdef HAVE_PCAP_FINDALLDEVS
1004 static long
1005 parse_interface_number(const char *device)
1006 {
1007 long devnum;
1008 char *end;
1009
1010 devnum = strtol(device, &end, 10);
1011 if (device != end && *end == '\0') {
1012 /*
1013 * It's all-numeric, but is it a valid number?
1014 */
1015 if (devnum <= 0) {
1016 /*
1017 * No, it's not an ordinal.
1018 */
1019 error("Invalid adapter index");
1020 }
1021 return (devnum);
1022 } else {
1023 /*
1024 * It's not all-numeric; return -1, so our caller
1025 * knows that.
1026 */
1027 return (-1);
1028 }
1029 }
1030
1031 static char *
1032 find_interface_by_number(long devnum)
1033 {
1034 pcap_if_t *dev, *devlist;
1035 long i;
1036 char ebuf[PCAP_ERRBUF_SIZE];
1037 char *device;
1038
1039 if (pcap_findalldevs(&devlist, ebuf) < 0)
1040 error("%s", ebuf);
1041 /*
1042 * Look for the devnum-th entry in the list of devices (1-based).
1043 */
1044 for (i = 0, dev = devlist; i < devnum-1 && dev != NULL;
1045 i++, dev = dev->next)
1046 ;
1047 if (dev == NULL)
1048 error("Invalid adapter index");
1049 device = strdup(dev->name);
1050 pcap_freealldevs(devlist);
1051 return (device);
1052 }
1053 #endif
1054
1055 #ifdef HAVE_PCAP_OPEN
1056 /*
1057 * Prefix for rpcap URLs.
1058 */
1059 static char rpcap_prefix[] = "rpcap://";
1060 #endif
1061
1062 static pcap_t *
1063 open_interface(const char *device, netdissect_options *ndo, char *ebuf)
1064 {
1065 pcap_t *pc;
1066 #ifdef HAVE_PCAP_CREATE
1067 int status;
1068 char *cp;
1069 #endif
1070
1071 #ifdef HAVE_PCAP_OPEN
1072 /*
1073 * Is this an rpcap URL?
1074 */
1075 if (strncmp(device, rpcap_prefix, sizeof(rpcap_prefix) - 1) == 0) {
1076 /*
1077 * Yes. Open it with pcap_open().
1078 */
1079 *ebuf = '\0';
1080 fprintf(stderr, "Opening %s\n", device);
1081 pc = pcap_open(device, ndo->ndo_snaplen,
1082 pflag ? 0 : PCAP_OPENFLAG_PROMISCUOUS, 1000, NULL,
1083 ebuf);
1084 if (pc == NULL) {
1085 /*
1086 * If this failed with "No such device", that means
1087 * the interface doesn't exist; return NULL, so that
1088 * the caller can see whether the device name is
1089 * actually an interface index.
1090 */
1091 if (strstr(ebuf, "No such device") != NULL)
1092 return (NULL);
1093 error("%s", ebuf);
1094 }
1095 if (*ebuf)
1096 warning("%s", ebuf);
1097 return (pc);
1098 }
1099 #endif /* HAVE_PCAP_OPEN */
1100
1101 #ifdef HAVE_PCAP_CREATE
1102 pc = pcap_create(device, ebuf);
1103 if (pc == NULL) {
1104 /*
1105 * If this failed with "No such device", that means
1106 * the interface doesn't exist; return NULL, so that
1107 * the caller can see whether the device name is
1108 * actually an interface index.
1109 */
1110 if (strstr(ebuf, "No such device") != NULL)
1111 return (NULL);
1112 error("%s", ebuf);
1113 }
1114 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1115 if (Jflag)
1116 show_tstamp_types_and_exit(pc, device);
1117 #endif
1118 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1119 status = pcap_set_tstamp_precision(pc, ndo->ndo_tstamp_precision);
1120 if (status != 0)
1121 error("%s: Can't set %ssecond time stamp precision: %s",
1122 device,
1123 tstamp_precision_to_string(ndo->ndo_tstamp_precision),
1124 pcap_statustostr(status));
1125 #endif
1126
1127 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1128 if (immediate_mode) {
1129 status = pcap_set_immediate_mode(pc, 1);
1130 if (status != 0)
1131 error("%s: Can't set immediate mode: %s",
1132 device,
1133 pcap_statustostr(status));
1134 }
1135 #endif
1136 /*
1137 * Is this an interface that supports monitor mode?
1138 */
1139 if (pcap_can_set_rfmon(pc) == 1)
1140 supports_monitor_mode = 1;
1141 else
1142 supports_monitor_mode = 0;
1143 if (ndo->ndo_snaplen != 0) {
1144 /*
1145 * A snapshot length was explicitly specified;
1146 * use it.
1147 */
1148 status = pcap_set_snaplen(pc, ndo->ndo_snaplen);
1149 if (status != 0)
1150 error("%s: Can't set snapshot length: %s",
1151 device, pcap_statustostr(status));
1152 }
1153 status = pcap_set_promisc(pc, !pflag);
1154 if (status != 0)
1155 error("%s: Can't set promiscuous mode: %s",
1156 device, pcap_statustostr(status));
1157 if (Iflag) {
1158 status = pcap_set_rfmon(pc, 1);
1159 if (status != 0)
1160 error("%s: Can't set monitor mode: %s",
1161 device, pcap_statustostr(status));
1162 }
1163 status = pcap_set_timeout(pc, 1000);
1164 if (status != 0)
1165 error("%s: pcap_set_timeout failed: %s",
1166 device, pcap_statustostr(status));
1167 if (Bflag != 0) {
1168 status = pcap_set_buffer_size(pc, Bflag);
1169 if (status != 0)
1170 error("%s: Can't set buffer size: %s",
1171 device, pcap_statustostr(status));
1172 }
1173 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1174 if (jflag != -1) {
1175 status = pcap_set_tstamp_type(pc, jflag);
1176 if (status < 0)
1177 error("%s: Can't set time stamp type: %s",
1178 device, pcap_statustostr(status));
1179 }
1180 #endif
1181 status = pcap_activate(pc);
1182 if (status < 0) {
1183 /*
1184 * pcap_activate() failed.
1185 */
1186 cp = pcap_geterr(pc);
1187 if (status == PCAP_ERROR)
1188 error("%s", cp);
1189 else if (status == PCAP_ERROR_NO_SUCH_DEVICE) {
1190 /*
1191 * Return an error for our caller to handle.
1192 */
1193 snprintf(ebuf, PCAP_ERRBUF_SIZE, "%s: %s\n(%s)",
1194 device, pcap_statustostr(status), cp);
1195 pcap_close(pc);
1196 return (NULL);
1197 } else if (status == PCAP_ERROR_PERM_DENIED && *cp != '\0')
1198 error("%s: %s\n(%s)", device,
1199 pcap_statustostr(status), cp);
1200 #ifdef __FreeBSD__
1201 else if (status == PCAP_ERROR_RFMON_NOTSUP &&
1202 strncmp(device, "wlan", 4) == 0) {
1203 char parent[8], newdev[8];
1204 char sysctl[32];
1205 size_t s = sizeof(parent);
1206
1207 snprintf(sysctl, sizeof(sysctl),
1208 "net.wlan.%d.%%parent", atoi(device + 4));
1209 sysctlbyname(sysctl, parent, &s, NULL, 0);
1210 strlcpy(newdev, device, sizeof(newdev));
1211 /* Suggest a new wlan device. */
1212 /* FIXME: incrementing the index this way is not going to work well
1213 * when the index is 9 or greater but the only consequence in this
1214 * specific case would be an error message that looks a bit odd.
1215 */
1216 newdev[strlen(newdev)-1]++;
1217 error("%s is not a monitor mode VAP\n"
1218 "To create a new monitor mode VAP use:\n"
1219 " ifconfig %s create wlandev %s wlanmode monitor\n"
1220 "and use %s as the tcpdump interface",
1221 device, newdev, parent, newdev);
1222 }
1223 #endif
1224 else
1225 error("%s: %s", device,
1226 pcap_statustostr(status));
1227 } else if (status > 0) {
1228 /*
1229 * pcap_activate() succeeded, but it's warning us
1230 * of a problem it had.
1231 */
1232 cp = pcap_geterr(pc);
1233 if (status == PCAP_WARNING)
1234 warning("%s", cp);
1235 else if (status == PCAP_WARNING_PROMISC_NOTSUP &&
1236 *cp != '\0')
1237 warning("%s: %s\n(%s)", device,
1238 pcap_statustostr(status), cp);
1239 else
1240 warning("%s: %s", device,
1241 pcap_statustostr(status));
1242 }
1243 #ifdef HAVE_PCAP_SETDIRECTION
1244 if (Qflag != -1) {
1245 status = pcap_setdirection(pc, Qflag);
1246 if (status != 0)
1247 error("%s: pcap_setdirection() failed: %s",
1248 device, pcap_geterr(pc));
1249 }
1250 #endif /* HAVE_PCAP_SETDIRECTION */
1251 #else /* HAVE_PCAP_CREATE */
1252 *ebuf = '\0';
1253 /*
1254 * If no snapshot length was specified, or a length of 0 was
1255 * specified, default to 256KB.
1256 */
1257 if (ndo->ndo_snaplen == 0)
1258 ndo->ndo_snaplen = 262144;
1259 pc = pcap_open_live(device, ndo->ndo_snaplen, !pflag, 1000, ebuf);
1260 if (pc == NULL) {
1261 /*
1262 * If this failed with "No such device", that means
1263 * the interface doesn't exist; return NULL, so that
1264 * the caller can see whether the device name is
1265 * actually an interface index.
1266 */
1267 if (strstr(ebuf, "No such device") != NULL)
1268 return (NULL);
1269 error("%s", ebuf);
1270 }
1271 if (*ebuf)
1272 warning("%s", ebuf);
1273 #endif /* HAVE_PCAP_CREATE */
1274
1275 return (pc);
1276 }
1277
1278 int
1279 main(int argc, char **argv)
1280 {
1281 register int cnt, op, i;
1282 bpf_u_int32 localnet = 0, netmask = 0;
1283 int timezone_offset = 0;
1284 register char *cp, *infile, *cmdbuf, *device, *RFileName, *VFileName, *WFileName;
1285 char *endp;
1286 pcap_handler callback;
1287 int dlt;
1288 const char *dlt_name;
1289 struct bpf_program fcode;
1290 #ifndef _WIN32
1291 void (*oldhandler)(int);
1292 #endif
1293 struct dump_info dumpinfo;
1294 u_char *pcap_userdata;
1295 char ebuf[PCAP_ERRBUF_SIZE];
1296 char VFileLine[PATH_MAX + 1];
1297 char *username = NULL;
1298 char *chroot_dir = NULL;
1299 char *ret = NULL;
1300 char *end;
1301 #ifdef HAVE_PCAP_FINDALLDEVS
1302 pcap_if_t *devlist;
1303 long devnum;
1304 #endif
1305 int status;
1306 FILE *VFile;
1307 #ifdef HAVE_CAPSICUM
1308 cap_rights_t rights;
1309 int cansandbox;
1310 #endif /* HAVE_CAPSICUM */
1311 int Oflag = 1; /* run filter code optimizer */
1312 int yflag_dlt = -1;
1313 const char *yflag_dlt_name = NULL;
1314 int print = 0;
1315
1316 netdissect_options Ndo;
1317 netdissect_options *ndo = &Ndo;
1318
1319 /*
1320 * Initialize the netdissect code.
1321 */
1322 if (nd_init(ebuf, sizeof ebuf) == -1)
1323 error("%s", ebuf);
1324
1325 memset(ndo, 0, sizeof(*ndo));
1326 ndo_set_function_pointers(ndo);
1327
1328 cnt = -1;
1329 device = NULL;
1330 infile = NULL;
1331 RFileName = NULL;
1332 VFileName = NULL;
1333 VFile = NULL;
1334 WFileName = NULL;
1335 dlt = -1;
1336 if ((cp = strrchr(argv[0], '/')) != NULL)
1337 ndo->program_name = program_name = cp + 1;
1338 else
1339 ndo->program_name = program_name = argv[0];
1340
1341 #ifdef _WIN32
1342 if (pcap_wsockinit() != 0)
1343 error("Attempting to initialize Winsock failed");
1344 #endif /* _WIN32 */
1345
1346 /*
1347 * On platforms where the CPU doesn't support unaligned loads,
1348 * force unaligned accesses to abort with SIGBUS, rather than
1349 * being fixed up (slowly) by the OS kernel; on those platforms,
1350 * misaligned accesses are bugs, and we want tcpdump to crash so
1351 * that the bugs are reported.
1352 */
1353 if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
1354 error("%s", ebuf);
1355
1356 while (
1357 (op = getopt_long(argc, argv, SHORTOPTS, longopts, NULL)) != -1)
1358 switch (op) {
1359
1360 case 'a':
1361 /* compatibility for old -a */
1362 break;
1363
1364 case 'A':
1365 ++ndo->ndo_Aflag;
1366 break;
1367
1368 case 'b':
1369 ++ndo->ndo_bflag;
1370 break;
1371
1372 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
1373 case 'B':
1374 Bflag = atoi(optarg)*1024;
1375 if (Bflag <= 0)
1376 error("invalid packet buffer size %s", optarg);
1377 break;
1378 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
1379
1380 case 'c':
1381 cnt = atoi(optarg);
1382 if (cnt <= 0)
1383 error("invalid packet count %s", optarg);
1384 break;
1385
1386 case 'C':
1387 errno = 0;
1388 #ifdef HAVE_PCAP_DUMP_FTELL64
1389 Cflag = strtoint64_t(optarg, &endp, 10);
1390 #else
1391 Cflag = strtol(optarg, &endp, 10);
1392 #endif
1393 if (endp == optarg || *endp != '\0' || errno != 0
1394 || Cflag <= 0)
1395 error("invalid file size %s", optarg);
1396 /*
1397 * Will multiplying it by 1000000 overflow?
1398 */
1399 #ifdef HAVE_PCAP_DUMP_FTELL64
1400 if (Cflag > INT64_T_CONSTANT(0x7fffffffffffffff) / 1000000)
1401 #else
1402 if (Cflag > LONG_MAX / 1000000)
1403 #endif
1404 error("file size %s is too large", optarg);
1405 Cflag *= 1000000;
1406 break;
1407
1408 case 'd':
1409 ++dflag;
1410 break;
1411
1412 #ifdef HAVE_PCAP_FINDALLDEVS
1413 case 'D':
1414 Dflag++;
1415 break;
1416 #endif
1417
1418 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1419 case OPTION_LIST_REMOTE_INTERFACES:
1420 remote_interfaces_source = optarg;
1421 break;
1422 #endif
1423
1424 case 'L':
1425 Lflag++;
1426 break;
1427
1428 case 'e':
1429 ++ndo->ndo_eflag;
1430 break;
1431
1432 case 'E':
1433 #ifndef HAVE_LIBCRYPTO
1434 warning("crypto code not compiled in");
1435 #endif
1436 ndo->ndo_espsecret = optarg;
1437 break;
1438
1439 case 'f':
1440 ++ndo->ndo_fflag;
1441 break;
1442
1443 case 'F':
1444 infile = optarg;
1445 break;
1446
1447 case 'G':
1448 Gflag = atoi(optarg);
1449 if (Gflag < 0)
1450 error("invalid number of seconds %s", optarg);
1451
1452 /* We will create one file initially. */
1453 Gflag_count = 0;
1454
1455 /* Grab the current time for rotation use. */
1456 if ((Gflag_time = time(NULL)) == (time_t)-1) {
1457 error("main: can't get current time: %s",
1458 pcap_strerror(errno));
1459 }
1460 break;
1461
1462 case 'h':
1463 print_usage();
1464 exit_tcpdump(0);
1465 break;
1466
1467 case 'H':
1468 ++ndo->ndo_Hflag;
1469 break;
1470
1471 case 'i':
1472 device = optarg;
1473 break;
1474
1475 #ifdef HAVE_PCAP_CREATE
1476 case 'I':
1477 ++Iflag;
1478 break;
1479 #endif /* HAVE_PCAP_CREATE */
1480
1481 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1482 case 'j':
1483 jflag = pcap_tstamp_type_name_to_val(optarg);
1484 if (jflag < 0)
1485 error("invalid time stamp type %s", optarg);
1486 break;
1487
1488 case 'J':
1489 Jflag++;
1490 break;
1491 #endif
1492
1493 case 'l':
1494 #ifdef _WIN32
1495 /*
1496 * _IOLBF is the same as _IOFBF in Microsoft's C
1497 * libraries; the only alternative they offer
1498 * is _IONBF.
1499 *
1500 * XXX - this should really be checking for MSVC++,
1501 * not _WIN32, if, for example, MinGW has its own
1502 * C library that is more UNIX-compatible.
1503 */
1504 setvbuf(stdout, NULL, _IONBF, 0);
1505 #else /* _WIN32 */
1506 #ifdef HAVE_SETLINEBUF
1507 setlinebuf(stdout);
1508 #else
1509 setvbuf(stdout, NULL, _IOLBF, 0);
1510 #endif
1511 #endif /* _WIN32 */
1512 break;
1513
1514 case 'K':
1515 ++ndo->ndo_Kflag;
1516 break;
1517
1518 case 'm':
1519 if (nd_have_smi_support()) {
1520 if (nd_load_smi_module(optarg, ebuf, sizeof ebuf) == -1)
1521 error("%s", ebuf);
1522 } else {
1523 (void)fprintf(stderr, "%s: ignoring option `-m %s' ",
1524 program_name, optarg);
1525 (void)fprintf(stderr, "(no libsmi support)\n");
1526 }
1527 break;
1528
1529 case 'M':
1530 /* TCP-MD5 shared secret */
1531 #ifndef HAVE_LIBCRYPTO
1532 warning("crypto code not compiled in");
1533 #endif
1534 ndo->ndo_sigsecret = optarg;
1535 break;
1536
1537 case 'n':
1538 ++ndo->ndo_nflag;
1539 break;
1540
1541 case 'N':
1542 ++ndo->ndo_Nflag;
1543 break;
1544
1545 case 'O':
1546 Oflag = 0;
1547 break;
1548
1549 case 'p':
1550 ++pflag;
1551 break;
1552
1553 case 'q':
1554 ++ndo->ndo_qflag;
1555 ++ndo->ndo_suppress_default_print;
1556 break;
1557
1558 #ifdef HAVE_PCAP_SETDIRECTION
1559 case 'Q':
1560 if (ascii_strcasecmp(optarg, "in") == 0)
1561 Qflag = PCAP_D_IN;
1562 else if (ascii_strcasecmp(optarg, "out") == 0)
1563 Qflag = PCAP_D_OUT;
1564 else if (ascii_strcasecmp(optarg, "inout") == 0)
1565 Qflag = PCAP_D_INOUT;
1566 else
1567 error("unknown capture direction `%s'", optarg);
1568 break;
1569 #endif /* HAVE_PCAP_SETDIRECTION */
1570
1571 case 'r':
1572 RFileName = optarg;
1573 break;
1574
1575 case 's':
1576 ndo->ndo_snaplen = strtol(optarg, &end, 0);
1577 if (optarg == end || *end != '\0'
1578 || ndo->ndo_snaplen < 0 || ndo->ndo_snaplen > MAXIMUM_SNAPLEN)
1579 error("invalid snaplen %s", optarg);
1580 break;
1581
1582 case 'S':
1583 ++ndo->ndo_Sflag;
1584 break;
1585
1586 case 't':
1587 ++ndo->ndo_tflag;
1588 break;
1589
1590 case 'T':
1591 if (ascii_strcasecmp(optarg, "vat") == 0)
1592 ndo->ndo_packettype = PT_VAT;
1593 else if (ascii_strcasecmp(optarg, "wb") == 0)
1594 ndo->ndo_packettype = PT_WB;
1595 else if (ascii_strcasecmp(optarg, "rpc") == 0)
1596 ndo->ndo_packettype = PT_RPC;
1597 else if (ascii_strcasecmp(optarg, "rtp") == 0)
1598 ndo->ndo_packettype = PT_RTP;
1599 else if (ascii_strcasecmp(optarg, "rtcp") == 0)
1600 ndo->ndo_packettype = PT_RTCP;
1601 else if (ascii_strcasecmp(optarg, "snmp") == 0)
1602 ndo->ndo_packettype = PT_SNMP;
1603 else if (ascii_strcasecmp(optarg, "cnfp") == 0)
1604 ndo->ndo_packettype = PT_CNFP;
1605 else if (ascii_strcasecmp(optarg, "tftp") == 0)
1606 ndo->ndo_packettype = PT_TFTP;
1607 else if (ascii_strcasecmp(optarg, "aodv") == 0)
1608 ndo->ndo_packettype = PT_AODV;
1609 else if (ascii_strcasecmp(optarg, "carp") == 0)
1610 ndo->ndo_packettype = PT_CARP;
1611 else if (ascii_strcasecmp(optarg, "radius") == 0)
1612 ndo->ndo_packettype = PT_RADIUS;
1613 else if (ascii_strcasecmp(optarg, "zmtp1") == 0)
1614 ndo->ndo_packettype = PT_ZMTP1;
1615 else if (ascii_strcasecmp(optarg, "vxlan") == 0)
1616 ndo->ndo_packettype = PT_VXLAN;
1617 else if (ascii_strcasecmp(optarg, "pgm") == 0)
1618 ndo->ndo_packettype = PT_PGM;
1619 else if (ascii_strcasecmp(optarg, "pgm_zmtp1") == 0)
1620 ndo->ndo_packettype = PT_PGM_ZMTP1;
1621 else if (ascii_strcasecmp(optarg, "lmp") == 0)
1622 ndo->ndo_packettype = PT_LMP;
1623 else if (ascii_strcasecmp(optarg, "resp") == 0)
1624 ndo->ndo_packettype = PT_RESP;
1625 else
1626 error("unknown packet type `%s'", optarg);
1627 break;
1628
1629 case 'u':
1630 ++ndo->ndo_uflag;
1631 break;
1632
1633 #ifdef HAVE_PCAP_DUMP_FLUSH
1634 case 'U':
1635 ++Uflag;
1636 break;
1637 #endif
1638
1639 case 'v':
1640 ++ndo->ndo_vflag;
1641 break;
1642
1643 case 'V':
1644 VFileName = optarg;
1645 break;
1646
1647 case 'w':
1648 WFileName = optarg;
1649 break;
1650
1651 case 'W':
1652 Wflag = atoi(optarg);
1653 if (Wflag <= 0)
1654 error("invalid number of output files %s", optarg);
1655 WflagChars = getWflagChars(Wflag);
1656 break;
1657
1658 case 'x':
1659 ++ndo->ndo_xflag;
1660 ++ndo->ndo_suppress_default_print;
1661 break;
1662
1663 case 'X':
1664 ++ndo->ndo_Xflag;
1665 ++ndo->ndo_suppress_default_print;
1666 break;
1667
1668 case 'y':
1669 yflag_dlt_name = optarg;
1670 yflag_dlt =
1671 pcap_datalink_name_to_val(yflag_dlt_name);
1672 if (yflag_dlt < 0)
1673 error("invalid data link type %s", yflag_dlt_name);
1674 break;
1675
1676 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
1677 case 'Y':
1678 {
1679 /* Undocumented flag */
1680 pcap_set_parser_debug(1);
1681 }
1682 break;
1683 #endif
1684 case 'z':
1685 zflag = optarg;
1686 break;
1687
1688 case 'Z':
1689 username = optarg;
1690 break;
1691
1692 case '#':
1693 ndo->ndo_packet_number = 1;
1694 break;
1695
1696 case OPTION_VERSION:
1697 print_version();
1698 exit_tcpdump(0);
1699 break;
1700
1701 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1702 case OPTION_TSTAMP_PRECISION:
1703 ndo->ndo_tstamp_precision = tstamp_precision_from_string(optarg);
1704 if (ndo->ndo_tstamp_precision < 0)
1705 error("unsupported time stamp precision");
1706 break;
1707 #endif
1708
1709 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1710 case OPTION_IMMEDIATE_MODE:
1711 immediate_mode = 1;
1712 break;
1713 #endif
1714
1715 case OPTION_PRINT:
1716 print = 1;
1717 break;
1718
1719 default:
1720 print_usage();
1721 exit_tcpdump(1);
1722 /* NOTREACHED */
1723 }
1724
1725 #ifdef HAVE_PCAP_FINDALLDEVS
1726 if (Dflag)
1727 show_devices_and_exit();
1728 #endif
1729 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1730 if (remote_interfaces_source != NULL)
1731 show_remote_devices_and_exit();
1732 #endif
1733
1734 switch (ndo->ndo_tflag) {
1735
1736 case 0: /* Default */
1737 case 4: /* Default + Date*/
1738 timezone_offset = gmt2local(0);
1739 break;
1740
1741 case 1: /* No time stamp */
1742 case 2: /* Unix timeval style */
1743 case 3: /* Microseconds since previous packet */
1744 case 5: /* Microseconds since first packet */
1745 break;
1746
1747 default: /* Not supported */
1748 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1749 break;
1750 }
1751
1752 if (ndo->ndo_fflag != 0 && (VFileName != NULL || RFileName != NULL))
1753 error("-f can not be used with -V or -r");
1754
1755 if (VFileName != NULL && RFileName != NULL)
1756 error("-V and -r are mutually exclusive.");
1757
1758 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1759 /*
1760 * If we're printing dissected packets to the standard output
1761 * and the standard output is a terminal, use immediate mode,
1762 * as the user's probably expecting to see packets pop up
1763 * immediately.
1764 *
1765 * XXX - set the timeout to a lower value, instead? If so,
1766 * what value would be appropriate?
1767 */
1768 if ((WFileName == NULL || print) && isatty(1))
1769 immediate_mode = 1;
1770 #endif
1771
1772 #ifdef WITH_CHROOT
1773 /* if run as root, prepare for chrooting */
1774 if (getuid() == 0 || geteuid() == 0) {
1775 /* future extensibility for cmd-line arguments */
1776 if (!chroot_dir)
1777 chroot_dir = WITH_CHROOT;
1778 }
1779 #endif
1780
1781 #ifdef WITH_USER
1782 /* if run as root, prepare for dropping root privileges */
1783 if (getuid() == 0 || geteuid() == 0) {
1784 /* Run with '-Z root' to restore old behaviour */
1785 if (!username)
1786 username = WITH_USER;
1787 }
1788 #endif
1789
1790 if (RFileName != NULL || VFileName != NULL) {
1791 /*
1792 * If RFileName is non-null, it's the pathname of a
1793 * savefile to read. If VFileName is non-null, it's
1794 * the pathname of a file containing a list of pathnames
1795 * (one per line) of savefiles to read.
1796 *
1797 * In either case, we're reading a savefile, not doing
1798 * a live capture.
1799 */
1800 #ifndef _WIN32
1801 /*
1802 * We don't need network access, so relinquish any set-UID
1803 * or set-GID privileges we have (if any).
1804 *
1805 * We do *not* want set-UID privileges when opening a
1806 * trace file, as that might let the user read other
1807 * people's trace files (especially if we're set-UID
1808 * root).
1809 */
1810 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1811 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1812 #endif /* _WIN32 */
1813 if (VFileName != NULL) {
1814 if (VFileName[0] == '-' && VFileName[1] == '\0')
1815 VFile = stdin;
1816 else
1817 VFile = fopen(VFileName, "r");
1818
1819 if (VFile == NULL)
1820 error("Unable to open file: %s\n", pcap_strerror(errno));
1821
1822 ret = get_next_file(VFile, VFileLine);
1823 if (!ret)
1824 error("Nothing in %s\n", VFileName);
1825 RFileName = VFileLine;
1826 }
1827
1828 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1829 pd = pcap_open_offline_with_tstamp_precision(RFileName,
1830 ndo->ndo_tstamp_precision, ebuf);
1831 #else
1832 pd = pcap_open_offline(RFileName, ebuf);
1833 #endif
1834
1835 if (pd == NULL)
1836 error("%s", ebuf);
1837 #ifdef HAVE_CAPSICUM
1838 cap_rights_init(&rights, CAP_READ);
1839 if (cap_rights_limit(fileno(pcap_file(pd)), &rights) < 0 &&
1840 errno != ENOSYS) {
1841 error("unable to limit pcap descriptor");
1842 }
1843 #endif
1844 dlt = pcap_datalink(pd);
1845 dlt_name = pcap_datalink_val_to_name(dlt);
1846 if (dlt_name == NULL) {
1847 fprintf(stderr, "reading from file %s, link-type %u\n",
1848 RFileName, dlt);
1849 } else {
1850 fprintf(stderr,
1851 "reading from file %s, link-type %s (%s)\n",
1852 RFileName, dlt_name,
1853 pcap_datalink_val_to_description(dlt));
1854 }
1855 } else {
1856 /*
1857 * We're doing a live capture.
1858 */
1859 if (device == NULL) {
1860 /*
1861 * No interface was specified. Pick one.
1862 */
1863 #ifdef HAVE_PCAP_FINDALLDEVS
1864 /*
1865 * Find the list of interfaces, and pick
1866 * the first interface.
1867 */
1868 if (pcap_findalldevs(&devlist, ebuf) == -1)
1869 error("%s", ebuf);
1870 if (devlist == NULL)
1871 error("no interfaces available for capture");
1872 device = strdup(devlist->name);
1873 pcap_freealldevs(devlist);
1874 #else /* HAVE_PCAP_FINDALLDEVS */
1875 /*
1876 * Use whatever interface pcap_lookupdev()
1877 * chooses.
1878 */
1879 device = pcap_lookupdev(ebuf);
1880 if (device == NULL)
1881 error("%s", ebuf);
1882 #endif
1883 }
1884
1885 /*
1886 * Try to open the interface with the specified name.
1887 */
1888 pd = open_interface(device, ndo, ebuf);
1889 if (pd == NULL) {
1890 /*
1891 * That failed. If we can get a list of
1892 * interfaces, and the interface name
1893 * is purely numeric, try to use it as
1894 * a 1-based index in the list of
1895 * interfaces.
1896 */
1897 #ifdef HAVE_PCAP_FINDALLDEVS
1898 devnum = parse_interface_number(device);
1899 if (devnum == -1) {
1900 /*
1901 * It's not a number; just report
1902 * the open error and fail.
1903 */
1904 error("%s", ebuf);
1905 }
1906
1907 /*
1908 * OK, it's a number; try to find the
1909 * interface with that index, and try
1910 * to open it.
1911 *
1912 * find_interface_by_number() exits if it
1913 * couldn't be found.
1914 */
1915 device = find_interface_by_number(devnum);
1916 pd = open_interface(device, ndo, ebuf);
1917 if (pd == NULL)
1918 error("%s", ebuf);
1919 #else /* HAVE_PCAP_FINDALLDEVS */
1920 /*
1921 * We can't get a list of interfaces; just
1922 * fail.
1923 */
1924 error("%s", ebuf);
1925 #endif /* HAVE_PCAP_FINDALLDEVS */
1926 }
1927
1928 /*
1929 * Let user own process after capture device has
1930 * been opened.
1931 */
1932 #ifndef _WIN32
1933 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1934 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1935 #endif /* _WIN32 */
1936 #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32)
1937 if(Bflag != 0)
1938 if(pcap_setbuff(pd, Bflag)==-1){
1939 error("%s", pcap_geterr(pd));
1940 }
1941 #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */
1942 if (Lflag)
1943 show_dlts_and_exit(pd, device);
1944 if (yflag_dlt >= 0) {
1945 #ifdef HAVE_PCAP_SET_DATALINK
1946 if (pcap_set_datalink(pd, yflag_dlt) < 0)
1947 error("%s", pcap_geterr(pd));
1948 #else
1949 /*
1950 * We don't actually support changing the
1951 * data link type, so we only let them
1952 * set it to what it already is.
1953 */
1954 if (yflag_dlt != pcap_datalink(pd)) {
1955 error("%s is not one of the DLTs supported by this device\n",
1956 yflag_dlt_name);
1957 }
1958 #endif
1959 (void)fprintf(stderr, "%s: data link type %s\n",
1960 program_name, yflag_dlt_name);
1961 (void)fflush(stderr);
1962 }
1963 i = pcap_snapshot(pd);
1964 if (ndo->ndo_snaplen < i) {
1965 if (ndo->ndo_snaplen != 0)
1966 warning("snaplen raised from %d to %d", ndo->ndo_snaplen, i);
1967 ndo->ndo_snaplen = i;
1968 } else if (ndo->ndo_snaplen > i) {
1969 warning("snaplen lowered from %d to %d", ndo->ndo_snaplen, i);
1970 ndo->ndo_snaplen = i;
1971 }
1972 if(ndo->ndo_fflag != 0) {
1973 if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
1974 warning("foreign (-f) flag used but: %s", ebuf);
1975 }
1976 }
1977
1978 }
1979 if (infile)
1980 cmdbuf = read_infile(infile);
1981 else
1982 cmdbuf = copy_argv(&argv[optind]);
1983
1984 #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
1985 pcap_set_optimizer_debug(dflag);
1986 #endif
1987 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1988 error("%s", pcap_geterr(pd));
1989 if (dflag) {
1990 bpf_dump(&fcode, dflag);
1991 pcap_close(pd);
1992 free(cmdbuf);
1993 pcap_freecode(&fcode);
1994 exit_tcpdump(0);
1995 }
1996
1997 #ifdef HAVE_CASPER
1998 if (!ndo->ndo_nflag)
1999 capdns = capdns_setup();
2000 #endif /* HAVE_CASPER */
2001
2002 init_print(ndo, localnet, netmask, timezone_offset);
2003
2004 #ifndef _WIN32
2005 (void)setsignal(SIGPIPE, cleanup);
2006 (void)setsignal(SIGTERM, cleanup);
2007 #endif /* _WIN32 */
2008 (void)setsignal(SIGINT, cleanup);
2009 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2010 (void)setsignal(SIGCHLD, child_cleanup);
2011 #endif
2012 /* Cooperate with nohup(1) */
2013 #ifndef _WIN32
2014 if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
2015 (void)setsignal(SIGHUP, oldhandler);
2016 #endif /* _WIN32 */
2017
2018 #ifndef _WIN32
2019 /*
2020 * If a user name was specified with "-Z", attempt to switch to
2021 * that user's UID. This would probably be used with sudo,
2022 * to allow tcpdump to be run in a special restricted
2023 * account (if you just want to allow users to open capture
2024 * devices, and can't just give users that permission,
2025 * you'd make tcpdump set-UID or set-GID).
2026 *
2027 * Tcpdump doesn't necessarily write only to one savefile;
2028 * the general only way to allow a -Z instance to write to
2029 * savefiles as the user under whose UID it's run, rather
2030 * than as the user specified with -Z, would thus be to switch
2031 * to the original user ID before opening a capture file and
2032 * then switch back to the -Z user ID after opening the savefile.
2033 * Switching to the -Z user ID only after opening the first
2034 * savefile doesn't handle the general case.
2035 */
2036
2037 if (getuid() == 0 || geteuid() == 0) {
2038 #ifdef HAVE_LIBCAP_NG
2039 /* Initialize capng */
2040 capng_clear(CAPNG_SELECT_BOTH);
2041 if (username) {
2042 capng_updatev(
2043 CAPNG_ADD,
2044 CAPNG_PERMITTED | CAPNG_EFFECTIVE,
2045 CAP_SETUID,
2046 CAP_SETGID,
2047 -1);
2048 }
2049 if (chroot_dir) {
2050 capng_update(
2051 CAPNG_ADD,
2052 CAPNG_PERMITTED | CAPNG_EFFECTIVE,
2053 CAP_SYS_CHROOT
2054 );
2055 }
2056
2057 if (WFileName) {
2058 capng_update(
2059 CAPNG_ADD,
2060 CAPNG_PERMITTED | CAPNG_EFFECTIVE,
2061 CAP_DAC_OVERRIDE
2062 );
2063 }
2064 capng_apply(CAPNG_SELECT_BOTH);
2065 #endif /* HAVE_LIBCAP_NG */
2066 if (username || chroot_dir)
2067 droproot(username, chroot_dir);
2068
2069 }
2070 #endif /* _WIN32 */
2071
2072 if (pcap_setfilter(pd, &fcode) < 0)
2073 error("%s", pcap_geterr(pd));
2074 #ifdef HAVE_CAPSICUM
2075 if (RFileName == NULL && VFileName == NULL) {
2076 static const unsigned long cmds[] = { BIOCGSTATS, BIOCROTZBUF };
2077
2078 /*
2079 * The various libpcap devices use a combination of
2080 * read (bpf), ioctl (bpf, netmap), poll (netmap)
2081 * so we add the relevant access rights.
2082 */
2083 cap_rights_init(&rights, CAP_IOCTL, CAP_READ, CAP_EVENT);
2084 if (cap_rights_limit(pcap_fileno(pd), &rights) < 0 &&
2085 errno != ENOSYS) {
2086 error("unable to limit pcap descriptor");
2087 }
2088 if (cap_ioctls_limit(pcap_fileno(pd), cmds,
2089 sizeof(cmds) / sizeof(cmds[0])) < 0 && errno != ENOSYS) {
2090 error("unable to limit ioctls on pcap descriptor");
2091 }
2092 }
2093 #endif
2094 if (WFileName) {
2095 pcap_dumper_t *p;
2096 /* Do not exceed the default PATH_MAX for files. */
2097 dumpinfo.CurrentFileName = (char *)malloc(PATH_MAX + 1);
2098
2099 if (dumpinfo.CurrentFileName == NULL)
2100 error("malloc of dumpinfo.CurrentFileName");
2101
2102 /* We do not need numbering for dumpfiles if Cflag isn't set. */
2103 if (Cflag != 0)
2104 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
2105 else
2106 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
2107
2108 p = pcap_dump_open(pd, dumpinfo.CurrentFileName);
2109 #ifdef HAVE_LIBCAP_NG
2110 /* Give up CAP_DAC_OVERRIDE capability.
2111 * Only allow it to be restored if the -C or -G flag have been
2112 * set since we may need to create more files later on.
2113 */
2114 capng_update(
2115 CAPNG_DROP,
2116 (Cflag || Gflag ? 0 : CAPNG_PERMITTED)
2117 | CAPNG_EFFECTIVE,
2118 CAP_DAC_OVERRIDE
2119 );
2120 capng_apply(CAPNG_SELECT_BOTH);
2121 #endif /* HAVE_LIBCAP_NG */
2122 if (p == NULL)
2123 error("%s", pcap_geterr(pd));
2124 #ifdef HAVE_CAPSICUM
2125 set_dumper_capsicum_rights(p);
2126 #endif
2127 if (Cflag != 0 || Gflag != 0) {
2128 #ifdef HAVE_CAPSICUM
2129 dumpinfo.WFileName = strdup(basename(WFileName));
2130 if (dumpinfo.WFileName == NULL) {
2131 error("Unable to allocate memory for file %s",
2132 WFileName);
2133 }
2134 dumpinfo.dirfd = open(dirname(WFileName),
2135 O_DIRECTORY | O_RDONLY);
2136 if (dumpinfo.dirfd < 0) {
2137 error("unable to open directory %s",
2138 dirname(WFileName));
2139 }
2140 cap_rights_init(&rights, CAP_CREATE, CAP_FCNTL,
2141 CAP_FTRUNCATE, CAP_LOOKUP, CAP_SEEK, CAP_WRITE);
2142 if (cap_rights_limit(dumpinfo.dirfd, &rights) < 0 &&
2143 errno != ENOSYS) {
2144 error("unable to limit directory rights");
2145 }
2146 if (cap_fcntls_limit(dumpinfo.dirfd, CAP_FCNTL_GETFL) < 0 &&
2147 errno != ENOSYS) {
2148 error("unable to limit dump descriptor fcntls");
2149 }
2150 #else /* !HAVE_CAPSICUM */
2151 dumpinfo.WFileName = WFileName;
2152 #endif
2153 callback = dump_packet_and_trunc;
2154 dumpinfo.pd = pd;
2155 dumpinfo.p = p;
2156 pcap_userdata = (u_char *)&dumpinfo;
2157 } else {
2158 callback = dump_packet;
2159 dumpinfo.WFileName = WFileName;
2160 dumpinfo.pd = pd;
2161 dumpinfo.p = p;
2162 pcap_userdata = (u_char *)&dumpinfo;
2163 }
2164 if (print) {
2165 dlt = pcap_datalink(pd);
2166 ndo->ndo_if_printer = get_if_printer(ndo, dlt);
2167 dumpinfo.ndo = ndo;
2168 } else
2169 dumpinfo.ndo = NULL;
2170
2171 #ifdef HAVE_PCAP_DUMP_FLUSH
2172 if (Uflag)
2173 pcap_dump_flush(p);
2174 #endif
2175 } else {
2176 dlt = pcap_datalink(pd);
2177 ndo->ndo_if_printer = get_if_printer(ndo, dlt);
2178 callback = print_packet;
2179 pcap_userdata = (u_char *)ndo;
2180 }
2181
2182 #ifdef SIGNAL_REQ_INFO
2183 /*
2184 * We can't get statistics when reading from a file rather
2185 * than capturing from a device.
2186 */
2187 if (RFileName == NULL)
2188 (void)setsignal(SIGNAL_REQ_INFO, requestinfo);
2189 #endif
2190
2191 if (ndo->ndo_vflag > 0 && WFileName && !print) {
2192 /*
2193 * When capturing to a file, if "--print" wasn't specified,
2194 *"-v" means tcpdump should, once per second,
2195 * "v"erbosely report the number of packets captured.
2196 */
2197 #ifdef USE_WIN32_MM_TIMER
2198 /* call verbose_stats_dump() each 1000 +/-100msec */
2199 timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
2200 setvbuf(stderr, NULL, _IONBF, 0);
2201 #elif defined(HAVE_ALARM)
2202 (void)setsignal(SIGALRM, verbose_stats_dump);
2203 alarm(1);
2204 #endif
2205 }
2206
2207 if (RFileName == NULL) {
2208 /*
2209 * Live capture (if -V was specified, we set RFileName
2210 * to a file from the -V file). Print a message to
2211 * the standard error on UN*X.
2212 */
2213 if (!ndo->ndo_vflag && !WFileName) {
2214 (void)fprintf(stderr,
2215 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
2216 program_name);
2217 } else
2218 (void)fprintf(stderr, "%s: ", program_name);
2219 dlt = pcap_datalink(pd);
2220 dlt_name = pcap_datalink_val_to_name(dlt);
2221 if (dlt_name == NULL) {
2222 (void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
2223 device, dlt, ndo->ndo_snaplen);
2224 } else {
2225 (void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
2226 device, dlt_name,
2227 pcap_datalink_val_to_description(dlt), ndo->ndo_snaplen);
2228 }
2229 (void)fflush(stderr);
2230 }
2231
2232 #ifdef HAVE_CAPSICUM
2233 cansandbox = (VFileName == NULL && zflag == NULL);
2234 #ifdef HAVE_CASPER
2235 cansandbox = (cansandbox && (ndo->ndo_nflag || capdns != NULL));
2236 #else
2237 cansandbox = (cansandbox && ndo->ndo_nflag);
2238 #endif /* HAVE_CASPER */
2239 if (cansandbox && cap_enter() < 0 && errno != ENOSYS)
2240 error("unable to enter the capability mode");
2241 #endif /* HAVE_CAPSICUM */
2242
2243 do {
2244 status = pcap_loop(pd, cnt, callback, pcap_userdata);
2245 if (WFileName == NULL) {
2246 /*
2247 * We're printing packets. Flush the printed output,
2248 * so it doesn't get intermingled with error output.
2249 */
2250 if (status == -2) {
2251 /*
2252 * We got interrupted, so perhaps we didn't
2253 * manage to finish a line we were printing.
2254 * Print an extra newline, just in case.
2255 */
2256 putchar('\n');
2257 }
2258 (void)fflush(stdout);
2259 }
2260 if (status == -2) {
2261 /*
2262 * We got interrupted. If we are reading multiple
2263 * files (via -V) set these so that we stop.
2264 */
2265 VFileName = NULL;
2266 ret = NULL;
2267 }
2268 if (status == -1) {
2269 /*
2270 * Error. Report it.
2271 */
2272 (void)fprintf(stderr, "%s: pcap_loop: %s\n",
2273 program_name, pcap_geterr(pd));
2274 }
2275 if (RFileName == NULL) {
2276 /*
2277 * We're doing a live capture. Report the capture
2278 * statistics.
2279 */
2280 info(1);
2281 }
2282 pcap_close(pd);
2283 if (VFileName != NULL) {
2284 ret = get_next_file(VFile, VFileLine);
2285 if (ret) {
2286 int new_dlt;
2287
2288 RFileName = VFileLine;
2289 pd = pcap_open_offline(RFileName, ebuf);
2290 if (pd == NULL)
2291 error("%s", ebuf);
2292 #ifdef HAVE_CAPSICUM
2293 cap_rights_init(&rights, CAP_READ);
2294 if (cap_rights_limit(fileno(pcap_file(pd)),
2295 &rights) < 0 && errno != ENOSYS) {
2296 error("unable to limit pcap descriptor");
2297 }
2298 #endif
2299 new_dlt = pcap_datalink(pd);
2300 if (new_dlt != dlt) {
2301 /*
2302 * The new file has a different
2303 * link-layer header type from the
2304 * previous one.
2305 */
2306 if (WFileName != NULL) {
2307 /*
2308 * We're writing raw packets
2309 * that match the filter to
2310 * a pcap file. pcap files
2311 * don't support multiple
2312 * different link-layer
2313 * header types, so we fail
2314 * here.
2315 */
2316 error("%s: new dlt does not match original", RFileName);
2317 }
2318
2319 /*
2320 * We're printing the decoded packets;
2321 * switch to the new DLT.
2322 *
2323 * To do that, we need to change
2324 * the printer, change the DLT name,
2325 * and recompile the filter with
2326 * the new DLT.
2327 */
2328 dlt = new_dlt;
2329 ndo->ndo_if_printer = get_if_printer(ndo, dlt);
2330 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
2331 error("%s", pcap_geterr(pd));
2332 }
2333
2334 /*
2335 * Set the filter on the new file.
2336 */
2337 if (pcap_setfilter(pd, &fcode) < 0)
2338 error("%s", pcap_geterr(pd));
2339
2340 /*
2341 * Report the new file.
2342 */
2343 dlt_name = pcap_datalink_val_to_name(dlt);
2344 if (dlt_name == NULL) {
2345 fprintf(stderr, "reading from file %s, link-type %u\n",
2346 RFileName, dlt);
2347 } else {
2348 fprintf(stderr,
2349 "reading from file %s, link-type %s (%s)\n",
2350 RFileName, dlt_name,
2351 pcap_datalink_val_to_description(dlt));
2352 }
2353 }
2354 }
2355 }
2356 while (ret != NULL);
2357
2358 free(cmdbuf);
2359 pcap_freecode(&fcode);
2360 exit_tcpdump(status == -1 ? 1 : 0);
2361 }
2362
2363 /*
2364 * Catch a signal.
2365 */
2366 static void
2367 (*setsignal (int sig, void (*func)(int)))(int)
2368 {
2369 #ifdef _WIN32
2370 return (signal(sig, func));
2371 #else
2372 struct sigaction old, new;
2373
2374 memset(&new, 0, sizeof(new));
2375 new.sa_handler = func;
2376 if (sig == SIGCHLD)
2377 new.sa_flags = SA_RESTART;
2378 if (sigaction(sig, &new, &old) < 0)
2379 return (SIG_ERR);
2380 return (old.sa_handler);
2381 #endif
2382 }
2383
2384 /* make a clean exit on interrupts */
2385 static void
2386 cleanup(int signo _U_)
2387 {
2388 #ifdef USE_WIN32_MM_TIMER
2389 if (timer_id)
2390 timeKillEvent(timer_id);
2391 timer_id = 0;
2392 #elif defined(HAVE_ALARM)
2393 alarm(0);
2394 #endif
2395
2396 #ifdef HAVE_PCAP_BREAKLOOP
2397 /*
2398 * We have "pcap_breakloop()"; use it, so that we do as little
2399 * as possible in the signal handler (it's probably not safe
2400 * to do anything with standard I/O streams in a signal handler -
2401 * the ANSI C standard doesn't say it is).
2402 */
2403 pcap_breakloop(pd);
2404 #else
2405 /*
2406 * We don't have "pcap_breakloop()"; this isn't safe, but
2407 * it's the best we can do. Print the summary if we're
2408 * not reading from a savefile - i.e., if we're doing a
2409 * live capture - and exit.
2410 */
2411 if (pd != NULL && pcap_file(pd) == NULL) {
2412 /*
2413 * We got interrupted, so perhaps we didn't
2414 * manage to finish a line we were printing.
2415 * Print an extra newline, just in case.
2416 */
2417 putchar('\n');
2418 (void)fflush(stdout);
2419 info(1);
2420 }
2421 exit_tcpdump(0);
2422 #endif
2423 }
2424
2425 /*
2426 On windows, we do not use a fork, so we do not care less about
2427 waiting a child processes to die
2428 */
2429 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2430 static void
2431 child_cleanup(int signo _U_)
2432 {
2433 wait(NULL);
2434 }
2435 #endif /* HAVE_FORK && HAVE_VFORK */
2436
2437 static void
2438 info(register int verbose)
2439 {
2440 struct pcap_stat stats;
2441
2442 /*
2443 * Older versions of libpcap didn't set ps_ifdrop on some
2444 * platforms; initialize it to 0 to handle that.
2445 */
2446 stats.ps_ifdrop = 0;
2447 if (pcap_stats(pd, &stats) < 0) {
2448 (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
2449 infoprint = 0;
2450 return;
2451 }
2452
2453 if (!verbose)
2454 fprintf(stderr, "%s: ", program_name);
2455
2456 (void)fprintf(stderr, "%u packet%s captured", packets_captured,
2457 PLURAL_SUFFIX(packets_captured));
2458 if (!verbose)
2459 fputs(", ", stderr);
2460 else
2461 putc('\n', stderr);
2462 (void)fprintf(stderr, "%u packet%s received by filter", stats.ps_recv,
2463 PLURAL_SUFFIX(stats.ps_recv));
2464 if (!verbose)
2465 fputs(", ", stderr);
2466 else
2467 putc('\n', stderr);
2468 (void)fprintf(stderr, "%u packet%s dropped by kernel", stats.ps_drop,
2469 PLURAL_SUFFIX(stats.ps_drop));
2470 if (stats.ps_ifdrop != 0) {
2471 if (!verbose)
2472 fputs(", ", stderr);
2473 else
2474 putc('\n', stderr);
2475 (void)fprintf(stderr, "%u packet%s dropped by interface\n",
2476 stats.ps_ifdrop, PLURAL_SUFFIX(stats.ps_ifdrop));
2477 } else
2478 putc('\n', stderr);
2479 infoprint = 0;
2480 }
2481
2482 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2483 #ifdef HAVE_FORK
2484 #define fork_subprocess() fork()
2485 #else
2486 #define fork_subprocess() vfork()
2487 #endif
2488 static void
2489 compress_savefile(const char *filename)
2490 {
2491 pid_t child;
2492
2493 child = fork_subprocess();
2494 if (child == -1) {
2495 fprintf(stderr,
2496 "compress_savefile: fork failed: %s\n",
2497 pcap_strerror(errno));
2498 return;
2499 }
2500 if (child != 0) {
2501 /* Parent process. */
2502 return;
2503 }
2504
2505 /*
2506 * Child process.
2507 * Set to lowest priority so that this doesn't disturb the capture.
2508 */
2509 #ifdef NZERO
2510 setpriority(PRIO_PROCESS, 0, NZERO - 1);
2511 #else
2512 setpriority(PRIO_PROCESS, 0, 19);
2513 #endif
2514 if (execlp(zflag, zflag, filename, (char *)NULL) == -1)
2515 fprintf(stderr,
2516 "compress_savefile: execlp(%s, %s) failed: %s\n",
2517 zflag,
2518 filename,
2519 pcap_strerror(errno));
2520 #ifdef HAVE_FORK
2521 exit(1);
2522 #else
2523 _exit(1);
2524 #endif
2525 }
2526 #else /* HAVE_FORK && HAVE_VFORK */
2527 static void
2528 compress_savefile(const char *filename)
2529 {
2530 fprintf(stderr,
2531 "compress_savefile failed. Functionality not implemented under your system\n");
2532 }
2533 #endif /* HAVE_FORK && HAVE_VFORK */
2534
2535 static void
2536 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2537 {
2538 struct dump_info *dump_info;
2539
2540 ++packets_captured;
2541
2542 ++infodelay;
2543
2544 dump_info = (struct dump_info *)user;
2545
2546 /*
2547 * XXX - this won't force the file to rotate on the specified time
2548 * boundary, but it will rotate on the first packet received after the
2549 * specified Gflag number of seconds. Note: if a Gflag time boundary
2550 * and a Cflag size boundary coincide, the time rotation will occur
2551 * first thereby cancelling the Cflag boundary (since the file should
2552 * be 0).
2553 */
2554 if (Gflag != 0) {
2555 /* Check if it is time to rotate */
2556 time_t t;
2557
2558 /* Get the current time */
2559 if ((t = time(NULL)) == (time_t)-1) {
2560 error("dump_and_trunc_packet: can't get current_time: %s",
2561 pcap_strerror(errno));
2562 }
2563
2564
2565 /* If the time is greater than the specified window, rotate */
2566 if (t - Gflag_time >= Gflag) {
2567 #ifdef HAVE_CAPSICUM
2568 FILE *fp;
2569 int fd;
2570 #endif
2571
2572 /* Update the Gflag_time */
2573 Gflag_time = t;
2574 /* Update Gflag_count */
2575 Gflag_count++;
2576 /*
2577 * Close the current file and open a new one.
2578 */
2579 pcap_dump_close(dump_info->p);
2580
2581 /*
2582 * Compress the file we just closed, if the user asked for it
2583 */
2584 if (zflag != NULL)
2585 compress_savefile(dump_info->CurrentFileName);
2586
2587 /*
2588 * Check to see if we've exceeded the Wflag (when
2589 * not using Cflag).
2590 */
2591 if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
2592 (void)fprintf(stderr, "Maximum file limit reached: %d\n",
2593 Wflag);
2594 info(1);
2595 exit_tcpdump(0);
2596 /* NOTREACHED */
2597 }
2598 if (dump_info->CurrentFileName != NULL)
2599 free(dump_info->CurrentFileName);
2600 /* Allocate space for max filename + \0. */
2601 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2602 if (dump_info->CurrentFileName == NULL)
2603 error("dump_packet_and_trunc: malloc");
2604 /*
2605 * Gflag was set otherwise we wouldn't be here. Reset the count
2606 * so multiple files would end with 1,2,3 in the filename.
2607 * The counting is handled with the -C flow after this.
2608 */
2609 Cflag_count = 0;
2610
2611 /*
2612 * This is always the first file in the Cflag
2613 * rotation: e.g. 0
2614 * We also don't need numbering if Cflag is not set.
2615 */
2616 if (Cflag != 0)
2617 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
2618 WflagChars);
2619 else
2620 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
2621
2622 #ifdef HAVE_LIBCAP_NG
2623 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2624 capng_apply(CAPNG_SELECT_BOTH);
2625 #endif /* HAVE_LIBCAP_NG */
2626 #ifdef HAVE_CAPSICUM
2627 fd = openat(dump_info->dirfd,
2628 dump_info->CurrentFileName,
2629 O_CREAT | O_WRONLY | O_TRUNC, 0644);
2630 if (fd < 0) {
2631 error("unable to open file %s",
2632 dump_info->CurrentFileName);
2633 }
2634 fp = fdopen(fd, "w");
2635 if (fp == NULL) {
2636 error("unable to fdopen file %s",
2637 dump_info->CurrentFileName);
2638 }
2639 dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2640 #else /* !HAVE_CAPSICUM */
2641 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2642 #endif
2643 #ifdef HAVE_LIBCAP_NG
2644 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2645 capng_apply(CAPNG_SELECT_BOTH);
2646 #endif /* HAVE_LIBCAP_NG */
2647 if (dump_info->p == NULL)
2648 error("%s", pcap_geterr(pd));
2649 #ifdef HAVE_CAPSICUM
2650 set_dumper_capsicum_rights(dump_info->p);
2651 #endif
2652 }
2653 }
2654
2655 /*
2656 * XXX - this won't prevent capture files from getting
2657 * larger than Cflag - the last packet written to the
2658 * file could put it over Cflag.
2659 */
2660 if (Cflag != 0) {
2661 #ifdef HAVE_PCAP_DUMP_FTELL64
2662 int64_t size = pcap_dump_ftell64(dump_info->p);
2663 #else
2664 /*
2665 * XXX - this only handles a Cflag value > 2^31-1 on
2666 * LP64 platforms; to handle ILP32 (32-bit UN*X and
2667 * Windows) or LLP64 (64-bit Windows) would require
2668 * a version of libpcap with pcap_dump_ftell64().
2669 */
2670 long size = pcap_dump_ftell(dump_info->p);
2671 #endif
2672
2673 if (size == -1)
2674 error("ftell fails on output file");
2675 if (size > Cflag) {
2676 #ifdef HAVE_CAPSICUM
2677 FILE *fp;
2678 int fd;
2679 #endif
2680
2681 /*
2682 * Close the current file and open a new one.
2683 */
2684 pcap_dump_close(dump_info->p);
2685
2686 /*
2687 * Compress the file we just closed, if the user
2688 * asked for it.
2689 */
2690 if (zflag != NULL)
2691 compress_savefile(dump_info->CurrentFileName);
2692
2693 Cflag_count++;
2694 if (Wflag > 0) {
2695 if (Cflag_count >= Wflag)
2696 Cflag_count = 0;
2697 }
2698 if (dump_info->CurrentFileName != NULL)
2699 free(dump_info->CurrentFileName);
2700 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2701 if (dump_info->CurrentFileName == NULL)
2702 error("dump_packet_and_trunc: malloc");
2703 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
2704 #ifdef HAVE_LIBCAP_NG
2705 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2706 capng_apply(CAPNG_SELECT_BOTH);
2707 #endif /* HAVE_LIBCAP_NG */
2708 #ifdef HAVE_CAPSICUM
2709 fd = openat(dump_info->dirfd, dump_info->CurrentFileName,
2710 O_CREAT | O_WRONLY | O_TRUNC, 0644);
2711 if (fd < 0) {
2712 error("unable to open file %s",
2713 dump_info->CurrentFileName);
2714 }
2715 fp = fdopen(fd, "w");
2716 if (fp == NULL) {
2717 error("unable to fdopen file %s",
2718 dump_info->CurrentFileName);
2719 }
2720 dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2721 #else /* !HAVE_CAPSICUM */
2722 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2723 #endif
2724 #ifdef HAVE_LIBCAP_NG
2725 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2726 capng_apply(CAPNG_SELECT_BOTH);
2727 #endif /* HAVE_LIBCAP_NG */
2728 if (dump_info->p == NULL)
2729 error("%s", pcap_geterr(pd));
2730 #ifdef HAVE_CAPSICUM
2731 set_dumper_capsicum_rights(dump_info->p);
2732 #endif
2733 }
2734 }
2735
2736 pcap_dump((u_char *)dump_info->p, h, sp);
2737 #ifdef HAVE_PCAP_DUMP_FLUSH
2738 if (Uflag)
2739 pcap_dump_flush(dump_info->p);
2740 #endif
2741
2742 if (dump_info->ndo != NULL)
2743 pretty_print_packet(dump_info->ndo, h, sp, packets_captured);
2744
2745 --infodelay;
2746 if (infoprint)
2747 info(0);
2748 }
2749
2750 static void
2751 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2752 {
2753 struct dump_info *dump_info;
2754
2755 ++packets_captured;
2756
2757 ++infodelay;
2758
2759 dump_info = (struct dump_info *)user;
2760
2761 pcap_dump((u_char *)dump_info->p, h, sp);
2762 #ifdef HAVE_PCAP_DUMP_FLUSH
2763 if (Uflag)
2764 pcap_dump_flush(dump_info->p);
2765 #endif
2766
2767 if (dump_info->ndo != NULL)
2768 pretty_print_packet(dump_info->ndo, h, sp, packets_captured);
2769
2770 --infodelay;
2771 if (infoprint)
2772 info(0);
2773 }
2774
2775 static void
2776 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2777 {
2778 ++packets_captured;
2779
2780 ++infodelay;
2781
2782 pretty_print_packet((netdissect_options *)user, h, sp, packets_captured);
2783
2784 --infodelay;
2785 if (infoprint)
2786 info(0);
2787 }
2788
2789 #ifdef _WIN32
2790 /*
2791 * XXX - there should really be libpcap calls to get the version
2792 * number as a string (the string would be generated from #defines
2793 * at run time, so that it's not generated from string constants
2794 * in the library, as, on many UNIX systems, those constants would
2795 * be statically linked into the application executable image, and
2796 * would thus reflect the version of libpcap on the system on
2797 * which the application was *linked*, not the system on which it's
2798 * *running*.
2799 *
2800 * That routine should be documented, unlike the "version[]"
2801 * string, so that UNIX vendors providing their own libpcaps
2802 * don't omit it (as a couple of vendors have...).
2803 *
2804 * Packet.dll should perhaps also export a routine to return the
2805 * version number of the Packet.dll code, to supply the
2806 * "Wpcap_version" information on Windows.
2807 */
2808 char WDversion[]="current-git.tcpdump.org";
2809 #if !defined(HAVE_GENERATED_VERSION)
2810 char version[]="current-git.tcpdump.org";
2811 #endif
2812 char pcap_version[]="current-git.tcpdump.org";
2813 char Wpcap_version[]="3.1";
2814 #endif
2815
2816 #ifdef SIGNAL_REQ_INFO
2817 void requestinfo(int signo _U_)
2818 {
2819 if (infodelay)
2820 ++infoprint;
2821 else
2822 info(0);
2823 }
2824 #endif
2825
2826 static void
2827 print_packets_captured (void)
2828 {
2829 static u_int prev_packets_captured, first = 1;
2830
2831 if (infodelay == 0 && (first || packets_captured != prev_packets_captured)) {
2832 fprintf(stderr, "Got %u\r", packets_captured);
2833 first = 0;
2834 prev_packets_captured = packets_captured;
2835 }
2836 }
2837
2838 /*
2839 * Called once each second in verbose mode while dumping to file
2840 */
2841 #ifdef USE_WIN32_MM_TIMER
2842 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
2843 DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
2844 {
2845 print_packets_captured();
2846 }
2847 #elif defined(HAVE_ALARM)
2848 static void verbose_stats_dump(int sig _U_)
2849 {
2850 print_packets_captured();
2851 alarm(1);
2852 }
2853 #endif
2854
2855 USES_APPLE_DEPRECATED_API
2856 static void
2857 print_version(void)
2858 {
2859 #ifndef HAVE_PCAP_LIB_VERSION
2860 #if defined(_WIN32) || defined(HAVE_PCAP_VERSION)
2861 extern char pcap_version[];
2862 #else /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2863 static char pcap_version[] = "unknown";
2864 #endif /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2865 #endif /* HAVE_PCAP_LIB_VERSION */
2866 const char *smi_version_string;
2867
2868 (void)fprintf(stderr, "%s version " PACKAGE_VERSION "\n", program_name);
2869 #ifdef HAVE_PCAP_LIB_VERSION
2870 (void)fprintf(stderr, "%s\n",pcap_lib_version());
2871 #else /* HAVE_PCAP_LIB_VERSION */
2872 (void)fprintf(stderr, "libpcap version %s\n", pcap_version);
2873 #endif /* HAVE_PCAP_LIB_VERSION */
2874
2875 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
2876 (void)fprintf (stderr, "%s\n", SSLeay_version(SSLEAY_VERSION));
2877 #endif
2878
2879 smi_version_string = nd_smi_version_string();
2880 if (smi_version_string != NULL)
2881 (void)fprintf (stderr, "SMI-library: %s\n", smi_version_string);
2882 #ifdef HAVE_DNET_HTOA
2883 (void)fprintf(stderr, "libdnet unknown version\n");
2884 #endif
2885
2886 #if defined(__SANITIZE_ADDRESS__)
2887 (void)fprintf (stderr, "Compiled with AddressSanitizer/GCC.\n");
2888 #elif defined(__has_feature)
2889 # if __has_feature(address_sanitizer)
2890 (void)fprintf (stderr, "Compiled with AddressSanitizer/CLang.\n");
2891 # endif
2892 #endif /* __SANITIZE_ADDRESS__ or __has_feature */
2893 }
2894 USES_APPLE_RST
2895
2896 static void
2897 print_usage(void)
2898 {
2899 print_version();
2900 (void)fprintf(stderr,
2901 "Usage: %s [-aAbd" D_FLAG "efhH" I_FLAG J_FLAG "KlLnNOpqStu" U_FLAG "vxX#]" B_FLAG_USAGE " [ -c count ]\n", program_name);
2902 (void)fprintf(stderr,
2903 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
2904 (void)fprintf(stderr,
2905 "\t\t[ -i interface ]" IMMEDIATE_MODE_USAGE j_FLAG_USAGE "\n");
2906 #ifdef HAVE_PCAP_FINDALLDEVS_EX
2907 (void)fprintf(stderr,
2908 "\t\t" LIST_REMOTE_INTERFACES_USAGE "\n");
2909 #endif
2910 (void)fprintf(stderr,
2911 "\t\t[ -M secret ] [ --number ] [ --print ]" Q_FLAG_USAGE "\n");
2912 (void)fprintf(stderr,
2913 "\t\t[ -r file ] [ -s snaplen ]" TIME_STAMP_PRECISION_USAGE "\n");
2914 (void)fprintf(stderr,
2915 "\t\t[ -T type ] [ --version ] [ -V file ] [ -w file ]\n");
2916 (void)fprintf(stderr,
2917 "\t\t[ -W filecount ] [ -y datalinktype ]\n");
2918 (void)fprintf(stderr,
2919 "\t\t[ -z postrotate-command ] [ -Z user ] [ expression ]\n");
2920 }
2921 /*
2922 * Local Variables:
2923 * c-style: whitesmith
2924 * c-basic-offset: 8
2925 * End:
2926 */