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