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