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