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