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