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