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