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