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