]> The Tcpdump Group git mirrors - tcpdump/blob - tcpdump.c
updated version
[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 #ifndef lint
29 static const char copyright[] _U_ =
30 "@(#) Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000\n\
31 The Regents of the University of California. All rights reserved.\n";
32 #endif
33
34 /*
35 * tcpdump - dump traffic on a network
36 *
37 * First written in 1987 by Van Jacobson, Lawrence Berkeley Laboratory.
38 * Mercilessly hacked and occasionally improved since then via the
39 * combined efforts of Van, Steve McCanne and Craig Leres of LBL.
40 */
41
42 #ifdef HAVE_CONFIG_H
43 #include "config.h"
44 #endif
45
46 /*
47 * Mac OS X may ship pcap.h from libpcap 0.6 with a libpcap based on
48 * 0.8. That means it has pcap_findalldevs() but the header doesn't
49 * define pcap_if_t, meaning that we can't actually *use* pcap_findalldevs().
50 */
51 #ifdef HAVE_PCAP_FINDALLDEVS
52 #ifndef HAVE_PCAP_IF_T
53 #undef HAVE_PCAP_FINDALLDEVS
54 #endif
55 #endif
56
57 #include <netdissect-stdinc.h>
58
59 #ifdef USE_LIBSMI
60 #include <smi.h>
61 #endif
62
63 #ifdef HAVE_LIBCRYPTO
64 #include <openssl/crypto.h>
65 #endif
66
67 #ifdef HAVE_GETOPT_LONG
68 #include <getopt.h>
69 #else
70 #include "getopt_long.h"
71 #endif
72 /* Capsicum-specific code requires macros from <net/bpf.h>, which will fail
73 * to compile if <pcap.h> has already been included; including the headers
74 * in the opposite order works fine.
75 */
76 #ifdef HAVE_CAPSICUM
77 #include <sys/capability.h>
78 #include <sys/ioccom.h>
79 #include <net/bpf.h>
80 #include <fcntl.h>
81 #include <libgen.h>
82 #endif /* HAVE_CAPSICUM */
83 #include <pcap.h>
84 #include <signal.h>
85 #include <stdio.h>
86 #include <stdlib.h>
87 #include <string.h>
88 #include <limits.h>
89 #ifndef _WIN32
90 #include <sys/wait.h>
91 #include <sys/resource.h>
92 #include <pwd.h>
93 #include <grp.h>
94 #endif /* _WIN32 */
95
96 /* capabilities convenience library */
97 /* If a code depends on HAVE_LIBCAP_NG, it depends also on HAVE_CAP_NG_H.
98 * If HAVE_CAP_NG_H is not defined, undefine HAVE_LIBCAP_NG.
99 * Thus, the later tests are done only on HAVE_LIBCAP_NG.
100 */
101 #ifdef HAVE_LIBCAP_NG
102 #ifdef HAVE_CAP_NG_H
103 #include <cap-ng.h>
104 #else
105 #undef HAVE_LIBCAP_NG
106 #endif /* HAVE_CAP_NG_H */
107 #endif /* HAVE_LIBCAP_NG */
108
109 #include "netdissect.h"
110 #include "interface.h"
111 #include "addrtoname.h"
112 #include "machdep.h"
113 #include "setsignal.h"
114 #include "gmt2local.h"
115 #include "pcap-missing.h"
116 #include "ascii_strcasecmp.h"
117
118 #include "print.h"
119
120 #ifndef PATH_MAX
121 #define PATH_MAX 1024
122 #endif
123
124 #ifdef SIGINFO
125 #define SIGNAL_REQ_INFO SIGINFO
126 #elif SIGUSR1
127 #define SIGNAL_REQ_INFO SIGUSR1
128 #endif
129
130 static int Cflag; /* rotate dump files after this many bytes */
131 static int Cflag_count; /* Keep track of which file number we're writing */
132 static int Dflag; /* list available devices and exit */
133 /*
134 * This is exported because, in some versions of libpcap, if libpcap
135 * is built with optimizer debugging code (which is *NOT* the default
136 * configuration!), the library *imports*(!) a variable named dflag,
137 * under the expectation that tcpdump is exporting it, to govern
138 * how much debugging information to print when optimizing
139 * the generated BPF code.
140 *
141 * This is a horrible hack; newer versions of libpcap don't import
142 * dflag but, instead, *if* built with optimizer debugging code,
143 * *export* a routine to set that flag.
144 */
145 int dflag; /* print filter code */
146 static int Gflag; /* rotate dump files after this many seconds */
147 static int Gflag_count; /* number of files created with Gflag rotation */
148 static time_t Gflag_time; /* The last time_t the dump file was rotated. */
149 static int Lflag; /* list available data link types and exit */
150 static int Iflag; /* rfmon (monitor) mode */
151 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
152 static int Jflag; /* list available time stamp types */
153 #endif
154 #ifdef HAVE_PCAP_SETDIRECTION
155 int Qflag = -1; /* restrict captured packet by send/receive direction */
156 #endif
157 static int Uflag; /* "unbuffered" output of dump files */
158 static int Wflag; /* recycle output files after this number of files */
159 static int WflagChars;
160 static char *zflag = NULL; /* compress each savefile using a specified command (like gzip or bzip2) */
161
162 static int infodelay;
163 static int infoprint;
164
165 char *program_name;
166
167 /* Forwards */
168 static RETSIGTYPE cleanup(int);
169 static RETSIGTYPE child_cleanup(int);
170 static void print_version(void);
171 static void print_usage(void);
172 static void show_tstamp_types_and_exit(const char *device) __attribute__((noreturn));
173 static void show_dlts_and_exit(const char *device) __attribute__((noreturn));
174
175 static void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
176 static void dump_packet_and_trunc(u_char *, const struct pcap_pkthdr *, const u_char *);
177 static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
178 static void droproot(const char *, const char *);
179
180 #ifdef SIGNAL_REQ_INFO
181 RETSIGTYPE requestinfo(int);
182 #endif
183
184 #if defined(USE_WIN32_MM_TIMER)
185 #include <MMsystem.h>
186 static UINT timer_id;
187 static void CALLBACK verbose_stats_dump(UINT, UINT, DWORD_PTR, DWORD_PTR, DWORD_PTR);
188 #elif defined(HAVE_ALARM)
189 static void verbose_stats_dump(int sig);
190 #endif
191
192 static void info(int);
193 static u_int packets_captured;
194
195 static const struct tok status_flags[] = {
196 #ifdef PCAP_IF_UP
197 { PCAP_IF_UP, "Up" },
198 #endif
199 #ifdef PCAP_IF_RUNNING
200 { PCAP_IF_RUNNING, "Running" },
201 #endif
202 { PCAP_IF_LOOPBACK, "Loopback" },
203 { 0, NULL }
204 };
205
206 static pcap_t *pd;
207
208 static int supports_monitor_mode;
209
210 extern int optind;
211 extern int opterr;
212 extern char *optarg;
213
214 struct dump_info {
215 char *WFileName;
216 char *CurrentFileName;
217 pcap_t *pd;
218 pcap_dumper_t *p;
219 #ifdef HAVE_CAPSICUM
220 int dirfd;
221 #endif
222 };
223
224 #if defined(HAVE_PCAP_SET_PARSER_DEBUG)
225 /*
226 * We have pcap_set_parser_debug() in libpcap; declare it (it's not declared
227 * by any libpcap header, because it's a special hack, only available if
228 * libpcap was configured to include it, and only intended for use by
229 * libpcap developers trying to debug the parser for filter expressions).
230 */
231 #ifdef _WIN32
232 __declspec(dllimport)
233 #else /* _WIN32 */
234 extern
235 #endif /* _WIN32 */
236 void pcap_set_parser_debug(int);
237 #elif defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
238 /*
239 * We don't have pcap_set_parser_debug() in libpcap, but we do have
240 * pcap_debug or yydebug. Make a local version of pcap_set_parser_debug()
241 * to set the flag, and define HAVE_PCAP_SET_PARSER_DEBUG.
242 */
243 static void
244 pcap_set_parser_debug(int value)
245 {
246 #ifdef HAVE_PCAP_DEBUG
247 extern int pcap_debug;
248
249 pcap_debug = value;
250 #else /* HAVE_PCAP_DEBUG */
251 extern int yydebug;
252
253 yydebug = value;
254 #endif /* HAVE_PCAP_DEBUG */
255 }
256
257 #define HAVE_PCAP_SET_PARSER_DEBUG
258 #endif
259
260 #if defined(HAVE_PCAP_SET_OPTIMIZER_DEBUG)
261 /*
262 * We have pcap_set_optimizer_debug() in libpcap; declare it (it's not declared
263 * by any libpcap header, because it's a special hack, only available if
264 * libpcap was configured to include it, and only intended for use by
265 * libpcap developers trying to debug the optimizer for filter expressions).
266 */
267 #ifdef _WIN32
268 __declspec(dllimport)
269 #else /* _WIN32 */
270 extern
271 #endif /* _WIN32 */
272 void pcap_set_optimizer_debug(int);
273 #endif
274
275 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
276 static void
277 show_tstamp_types_and_exit(const char *device)
278 {
279 int n_tstamp_types;
280 int *tstamp_types = 0;
281 const char *tstamp_type_name;
282 int i;
283
284 n_tstamp_types = pcap_list_tstamp_types(pd, &tstamp_types);
285 if (n_tstamp_types < 0)
286 error("%s", pcap_geterr(pd));
287
288 if (n_tstamp_types == 0) {
289 fprintf(stderr, "Time stamp type cannot be set for %s\n",
290 device);
291 exit(0);
292 }
293 fprintf(stderr, "Time stamp types for %s (use option -j to set):\n",
294 device);
295 for (i = 0; i < n_tstamp_types; i++) {
296 tstamp_type_name = pcap_tstamp_type_val_to_name(tstamp_types[i]);
297 if (tstamp_type_name != NULL) {
298 (void) fprintf(stderr, " %s (%s)\n", tstamp_type_name,
299 pcap_tstamp_type_val_to_description(tstamp_types[i]));
300 } else {
301 (void) fprintf(stderr, " %d\n", tstamp_types[i]);
302 }
303 }
304 pcap_free_tstamp_types(tstamp_types);
305 exit(0);
306 }
307 #endif
308
309 static void
310 show_dlts_and_exit(const char *device)
311 {
312 int n_dlts, i;
313 int *dlts = 0;
314 const char *dlt_name;
315
316 n_dlts = pcap_list_datalinks(pd, &dlts);
317 if (n_dlts < 0)
318 error("%s", pcap_geterr(pd));
319 else if (n_dlts == 0 || !dlts)
320 error("No data link types.");
321
322 /*
323 * If the interface is known to support monitor mode, indicate
324 * whether these are the data link types available when not in
325 * monitor mode, if -I wasn't specified, or when in monitor mode,
326 * when -I was specified (the link-layer types available in
327 * monitor mode might be different from the ones available when
328 * not in monitor mode).
329 */
330 if (supports_monitor_mode)
331 (void) fprintf(stderr, "Data link types for %s %s (use option -y to set):\n",
332 device,
333 Iflag ? "when in monitor mode" : "when not in monitor mode");
334 else
335 (void) fprintf(stderr, "Data link types for %s (use option -y to set):\n",
336 device);
337
338 for (i = 0; i < n_dlts; i++) {
339 dlt_name = pcap_datalink_val_to_name(dlts[i]);
340 if (dlt_name != NULL) {
341 (void) fprintf(stderr, " %s (%s)", dlt_name,
342 pcap_datalink_val_to_description(dlts[i]));
343
344 /*
345 * OK, does tcpdump handle that type?
346 */
347 if (!has_printer(dlts[i]))
348 (void) fprintf(stderr, " (printing not supported)");
349 fprintf(stderr, "\n");
350 } else {
351 (void) fprintf(stderr, " DLT %d (printing not supported)\n",
352 dlts[i]);
353 }
354 }
355 #ifdef HAVE_PCAP_FREE_DATALINKS
356 pcap_free_datalinks(dlts);
357 #endif
358 exit(0);
359 }
360
361 #ifdef HAVE_PCAP_FINDALLDEVS
362 static void
363 show_devices_and_exit (void)
364 {
365 pcap_if_t *dev, *devlist;
366 char ebuf[PCAP_ERRBUF_SIZE];
367 int i;
368
369 if (pcap_findalldevs(&devlist, ebuf) < 0)
370 error("%s", ebuf);
371 for (i = 0, dev = devlist; dev != NULL; i++, dev = dev->next) {
372 printf("%d.%s", i+1, dev->name);
373 if (dev->description != NULL)
374 printf(" (%s)", dev->description);
375 if (dev->flags != 0)
376 printf(" [%s]", bittok2str(status_flags, "none", dev->flags));
377 printf("\n");
378 }
379 pcap_freealldevs(devlist);
380 exit(0);
381 }
382 #endif /* HAVE_PCAP_FINDALLDEVS */
383
384 /*
385 * Short options.
386 *
387 * Note that there we use all letters for short options except for g, k,
388 * o, and P, and those are used by other versions of tcpdump, and we should
389 * only use them for the same purposes that the other versions of tcpdump
390 * use them:
391 *
392 * OS X tcpdump uses -g to force non--v output for IP to be on one
393 * line, making it more "g"repable;
394 *
395 * OS X tcpdump uses -k tospecify that packet comments in pcap-ng files
396 * should be printed;
397 *
398 * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done
399 * for hosts sending TCP SYN packets;
400 *
401 * OS X tcpdump uses -P to indicate that -w should write pcap-ng rather
402 * than pcap files.
403 *
404 * OS X tcpdump also uses -Q to specify expressions that match packet
405 * metadata, including but not limited to the packet direction.
406 * The expression syntax is different from a simple "in|out|inout",
407 * and those expressions aren't accepted by OS X tcpdump, but the
408 * equivalents would be "in" = "dir=in", "out" = "dir=out", and
409 * "inout" = "dir=in or dir=out", and the parser could conceivably
410 * special-case "in", "out", and "inout" as expressions for backwards
411 * compatibility, so all is not (yet) lost.
412 */
413
414 /*
415 * Set up flags that might or might not be supported depending on the
416 * version of libpcap we're using.
417 */
418 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
419 #define B_FLAG "B:"
420 #define B_FLAG_USAGE " [ -B size ]"
421 #else /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
422 #define B_FLAG
423 #define B_FLAG_USAGE
424 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
425
426 #ifdef HAVE_PCAP_CREATE
427 #define I_FLAG "I"
428 #else /* HAVE_PCAP_CREATE */
429 #define I_FLAG
430 #endif /* HAVE_PCAP_CREATE */
431
432 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
433 #define j_FLAG "j:"
434 #define j_FLAG_USAGE " [ -j tstamptype ]"
435 #define J_FLAG "J"
436 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
437 #define j_FLAG
438 #define j_FLAG_USAGE
439 #define J_FLAG
440 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
441
442 #ifdef HAVE_PCAP_FINDALLDEVS
443 #define D_FLAG "D"
444 #else
445 #define D_FLAG
446 #endif
447
448 #ifdef HAVE_PCAP_DUMP_FLUSH
449 #define U_FLAG "U"
450 #else
451 #define U_FLAG
452 #endif
453
454 #ifdef HAVE_PCAP_SETDIRECTION
455 #define Q_FLAG "Q:"
456 #else
457 #define Q_FLAG
458 #endif
459
460 #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:#"
461
462 /*
463 * Long options.
464 *
465 * We do not currently have long options corresponding to all short
466 * options; we should probably pick appropriate option names for them.
467 *
468 * However, the short options where the number of times the option is
469 * specified matters, such as -v and -d and -t, should probably not
470 * just map to a long option, as saying
471 *
472 * tcpdump --verbose --verbose
473 *
474 * doesn't make sense; it should be --verbosity={N} or something such
475 * as that.
476 *
477 * For long options with no corresponding short options, we define values
478 * outside the range of ASCII graphic characters, make that the last
479 * component of the entry for the long option, and have a case for that
480 * option in the switch statement.
481 */
482 #define OPTION_VERSION 128
483 #define OPTION_TSTAMP_PRECISION 129
484 #define OPTION_IMMEDIATE_MODE 130
485
486 static const struct option longopts[] = {
487 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
488 { "buffer-size", required_argument, NULL, 'B' },
489 #endif
490 { "list-interfaces", no_argument, NULL, 'D' },
491 { "help", no_argument, NULL, 'h' },
492 { "interface", required_argument, NULL, 'i' },
493 #ifdef HAVE_PCAP_CREATE
494 { "monitor-mode", no_argument, NULL, 'I' },
495 #endif
496 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
497 { "time-stamp-type", required_argument, NULL, 'j' },
498 { "list-time-stamp-types", no_argument, NULL, 'J' },
499 #endif
500 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
501 { "time-stamp-precision", required_argument, NULL, OPTION_TSTAMP_PRECISION},
502 #endif
503 { "dont-verify-checksums", no_argument, NULL, 'K' },
504 { "list-data-link-types", no_argument, NULL, 'L' },
505 { "no-optimize", no_argument, NULL, 'O' },
506 { "no-promiscuous-mode", no_argument, NULL, 'p' },
507 #ifdef HAVE_PCAP_SETDIRECTION
508 { "direction", required_argument, NULL, 'Q' },
509 #endif
510 { "snapshot-length", required_argument, NULL, 's' },
511 { "absolute-tcp-sequence-numbers", no_argument, NULL, 'S' },
512 #ifdef HAVE_PCAP_DUMP_FLUSH
513 { "packet-buffered", no_argument, NULL, 'U' },
514 #endif
515 { "linktype", required_argument, NULL, 'y' },
516 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
517 { "immediate-mode", no_argument, NULL, OPTION_IMMEDIATE_MODE },
518 #endif
519 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
520 { "debug-filter-parser", no_argument, NULL, 'Y' },
521 #endif
522 { "relinquish-privileges", required_argument, NULL, 'Z' },
523 { "number", no_argument, NULL, '#' },
524 { "version", no_argument, NULL, OPTION_VERSION },
525 { NULL, 0, NULL, 0 }
526 };
527
528 #ifndef _WIN32
529 /* Drop root privileges and chroot if necessary */
530 static void
531 droproot(const char *username, const char *chroot_dir)
532 {
533 struct passwd *pw = NULL;
534
535 if (chroot_dir && !username) {
536 fprintf(stderr, "%s: Chroot without dropping root is insecure\n",
537 program_name);
538 exit(1);
539 }
540
541 pw = getpwnam(username);
542 if (pw) {
543 if (chroot_dir) {
544 if (chroot(chroot_dir) != 0 || chdir ("/") != 0) {
545 fprintf(stderr, "%s: Couldn't chroot/chdir to '%.64s': %s\n",
546 program_name, chroot_dir, pcap_strerror(errno));
547 exit(1);
548 }
549 }
550 #ifdef HAVE_LIBCAP_NG
551 {
552 int ret = capng_change_id(pw->pw_uid, pw->pw_gid, CAPNG_NO_FLAG);
553 if (ret < 0) {
554 fprintf(stderr, "error : ret %d\n", ret);
555 } else {
556 fprintf(stderr, "dropped privs to %s\n", username);
557 }
558 }
559 #else
560 if (initgroups(pw->pw_name, pw->pw_gid) != 0 ||
561 setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0) {
562 fprintf(stderr, "%s: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
563 program_name, username,
564 (unsigned long)pw->pw_uid,
565 (unsigned long)pw->pw_gid,
566 pcap_strerror(errno));
567 exit(1);
568 }
569 else {
570 fprintf(stderr, "dropped privs to %s\n", username);
571 }
572 #endif /* HAVE_LIBCAP_NG */
573 }
574 else {
575 fprintf(stderr, "%s: Couldn't find user '%.32s'\n",
576 program_name, username);
577 exit(1);
578 }
579 #ifdef HAVE_LIBCAP_NG
580 /* We don't need CAP_SETUID and CAP_SETGID any more. */
581 capng_updatev(
582 CAPNG_DROP,
583 CAPNG_EFFECTIVE | CAPNG_PERMITTED,
584 CAP_SETUID,
585 CAP_SETGID,
586 -1);
587 capng_apply(CAPNG_SELECT_BOTH);
588 #endif /* HAVE_LIBCAP_NG */
589
590 }
591 #endif /* _WIN32 */
592
593 static int
594 getWflagChars(int x)
595 {
596 int c = 0;
597
598 x -= 1;
599 while (x > 0) {
600 c += 1;
601 x /= 10;
602 }
603
604 return c;
605 }
606
607
608 static void
609 MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
610 {
611 char *filename = malloc(PATH_MAX + 1);
612 if (filename == NULL)
613 error("Makefilename: malloc");
614
615 /* Process with strftime if Gflag is set. */
616 if (Gflag != 0) {
617 struct tm *local_tm;
618
619 /* Convert Gflag_time to a usable format */
620 if ((local_tm = localtime(&Gflag_time)) == NULL) {
621 error("MakeTimedFilename: localtime");
622 }
623
624 /* There's no good way to detect an error in strftime since a return
625 * value of 0 isn't necessarily failure.
626 */
627 strftime(filename, PATH_MAX, orig_name, local_tm);
628 } else {
629 strncpy(filename, orig_name, PATH_MAX);
630 }
631
632 if (cnt == 0 && max_chars == 0)
633 strncpy(buffer, filename, PATH_MAX + 1);
634 else
635 if (snprintf(buffer, PATH_MAX + 1, "%s%0*d", filename, max_chars, cnt) > PATH_MAX)
636 /* Report an error if the filename is too large */
637 error("too many output files or filename is too long (> %d)", PATH_MAX);
638 free(filename);
639 }
640
641 static char *
642 get_next_file(FILE *VFile, char *ptr)
643 {
644 char *ret;
645
646 ret = fgets(ptr, PATH_MAX, VFile);
647 if (!ret)
648 return NULL;
649
650 if (ptr[strlen(ptr) - 1] == '\n')
651 ptr[strlen(ptr) - 1] = '\0';
652
653 return ret;
654 }
655
656 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
657 static int
658 tstamp_precision_from_string(const char *precision)
659 {
660 if (strncmp(precision, "nano", strlen("nano")) == 0)
661 return PCAP_TSTAMP_PRECISION_NANO;
662
663 if (strncmp(precision, "micro", strlen("micro")) == 0)
664 return PCAP_TSTAMP_PRECISION_MICRO;
665
666 return -EINVAL;
667 }
668
669 static const char *
670 tstamp_precision_to_string(int precision)
671 {
672 switch (precision) {
673
674 case PCAP_TSTAMP_PRECISION_MICRO:
675 return "micro";
676
677 case PCAP_TSTAMP_PRECISION_NANO:
678 return "nano";
679
680 default:
681 return "unknown";
682 }
683 }
684 #endif
685
686 #ifdef HAVE_CAPSICUM
687 /*
688 * Ensure that, on a dump file's descriptor, we have all the rights
689 * necessary to make the standard I/O library work with an fdopen()ed
690 * FILE * from that descriptor.
691 *
692 * A long time ago, in a galaxy far far away, AT&T decided that, instead
693 * of providing separate APIs for getting and setting the FD_ flags on a
694 * descriptor, getting and setting the O_ flags on a descriptor, and
695 * locking files, they'd throw them all into a kitchen-sink fcntl() call
696 * along the lines of ioctl(), the fact that ioctl() operations are
697 * largely specific to particular character devices but fcntl() operations
698 * are either generic to all descriptors or generic to all descriptors for
699 * regular files nonwithstanding.
700 *
701 * The Capsicum people decided that fine-grained control of descriptor
702 * operations was required, so that you need to grant permission for
703 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
704 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
705 * collection of things, so there are *individual* fcntls for which
706 * permission needs to be granted.
707 *
708 * The FreeBSD standard I/O people implemented some optimizations that
709 * requires that the standard I/O routines be able to determine whether
710 * the descriptor for the FILE * is open append-only or not; as that
711 * descriptor could have come from an open() rather than an fopen(),
712 * that requires that it be able to do an F_GETFL fcntl() to read
713 * the O_ flags.
714 *
715 * Tcpdump uses ftell() to determine how much data has been written
716 * to a file in order to, when used with -C, determine when it's time
717 * to rotate capture files. ftell() therefore needs to do an lseek()
718 * to find out the file offset and must, thanks to the aforementioned
719 * optimization, also know whether the descriptor is open append-only
720 * or not.
721 *
722 * The net result of all the above is that we need to grant CAP_SEEK,
723 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
724 *
725 * Perhaps this is the universe's way of saying that either
726 *
727 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
728 * using it, so that Capsicum-capable tcpdump wouldn't need to do
729 * an fdopen()
730 *
731 * or
732 *
733 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
734 * I/O library that knows what rights are needed by the standard
735 * I/O library, based on the open mode, and assigns them, perhaps
736 * with an additional argument indicating, for example, whether
737 * seeking should be allowed, so that tcpdump doesn't need to know
738 * what the standard I/O library happens to require this week.
739 */
740 static void
741 set_dumper_capsicum_rights(pcap_dumper_t *p)
742 {
743 int fd = fileno(pcap_dump_file(p));
744 cap_rights_t rights;
745
746 cap_rights_init(&rights, CAP_SEEK, CAP_WRITE, CAP_FCNTL);
747 if (cap_rights_limit(fd, &rights) < 0 && errno != ENOSYS) {
748 error("unable to limit dump descriptor");
749 }
750 if (cap_fcntls_limit(fd, CAP_FCNTL_GETFL) < 0 && errno != ENOSYS) {
751 error("unable to limit dump descriptor fcntls");
752 }
753 }
754 #endif
755
756 int
757 main(int argc, char **argv)
758 {
759 register int cnt, op, i;
760 bpf_u_int32 localnet =0 , netmask = 0;
761 int timezone_offset = 0;
762 register char *cp, *infile, *cmdbuf, *device, *RFileName, *VFileName, *WFileName;
763 pcap_handler callback;
764 int dlt;
765 const char *dlt_name;
766 struct bpf_program fcode;
767 #ifndef _WIN32
768 RETSIGTYPE (*oldhandler)(int);
769 #endif
770 struct dump_info dumpinfo;
771 u_char *pcap_userdata;
772 char ebuf[PCAP_ERRBUF_SIZE];
773 char VFileLine[PATH_MAX + 1];
774 char *username = NULL;
775 char *chroot_dir = NULL;
776 char *ret = NULL;
777 char *end;
778 #ifdef HAVE_PCAP_FINDALLDEVS
779 pcap_if_t *dev, *devlist;
780 int devnum;
781 #endif
782 int status;
783 FILE *VFile;
784 #ifdef HAVE_CAPSICUM
785 cap_rights_t rights;
786 int cansandbox;
787 #endif /* HAVE_CAPSICUM */
788 int Bflag = 0; /* buffer size */
789 int jflag = -1; /* packet time stamp source */
790 int Oflag = 1; /* run filter code optimizer */
791 int pflag = 0; /* don't go promiscuous */
792 int yflag_dlt = -1;
793 const char *yflag_dlt_name = NULL;
794
795 netdissect_options Ndo;
796 netdissect_options *ndo = &Ndo;
797 int immediate_mode = 0;
798
799 memset(ndo, 0, sizeof(*ndo));
800 ndo_set_function_pointers(ndo);
801 ndo->ndo_snaplen = DEFAULT_SNAPLEN;
802
803 cnt = -1;
804 device = NULL;
805 infile = NULL;
806 RFileName = NULL;
807 VFileName = NULL;
808 VFile = NULL;
809 WFileName = NULL;
810 dlt = -1;
811 if ((cp = strrchr(argv[0], '/')) != NULL)
812 ndo->program_name = program_name = cp + 1;
813 else
814 ndo->program_name = program_name = argv[0];
815
816 #ifdef _WIN32
817 if (pcap_wsockinit() != 0)
818 error("Attempting to initialize Winsock failed");
819 #endif /* _WIN32 */
820
821 /*
822 * On platforms where the CPU doesn't support unaligned loads,
823 * force unaligned accesses to abort with SIGBUS, rather than
824 * being fixed up (slowly) by the OS kernel; on those platforms,
825 * misaligned accesses are bugs, and we want tcpdump to crash so
826 * that the bugs are reported.
827 */
828 if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
829 error("%s", ebuf);
830
831 #ifdef USE_LIBSMI
832 smiInit("tcpdump");
833 #endif
834
835 while (
836 (op = getopt_long(argc, argv, SHORTOPTS, longopts, NULL)) != -1)
837 switch (op) {
838
839 case 'a':
840 /* compatibility for old -a */
841 break;
842
843 case 'A':
844 ++ndo->ndo_Aflag;
845 break;
846
847 case 'b':
848 ++ndo->ndo_bflag;
849 break;
850
851 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
852 case 'B':
853 Bflag = atoi(optarg)*1024;
854 if (Bflag <= 0)
855 error("invalid packet buffer size %s", optarg);
856 break;
857 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
858
859 case 'c':
860 cnt = atoi(optarg);
861 if (cnt <= 0)
862 error("invalid packet count %s", optarg);
863 break;
864
865 case 'C':
866 Cflag = atoi(optarg) * 1000000;
867 if (Cflag <= 0)
868 error("invalid file size %s", optarg);
869 break;
870
871 case 'd':
872 ++dflag;
873 break;
874
875 case 'D':
876 Dflag++;
877 break;
878
879 case 'L':
880 Lflag++;
881 break;
882
883 case 'e':
884 ++ndo->ndo_eflag;
885 break;
886
887 case 'E':
888 #ifndef HAVE_LIBCRYPTO
889 warning("crypto code not compiled in");
890 #endif
891 ndo->ndo_espsecret = optarg;
892 break;
893
894 case 'f':
895 ++ndo->ndo_fflag;
896 break;
897
898 case 'F':
899 infile = optarg;
900 break;
901
902 case 'G':
903 Gflag = atoi(optarg);
904 if (Gflag < 0)
905 error("invalid number of seconds %s", optarg);
906
907 /* We will create one file initially. */
908 Gflag_count = 0;
909
910 /* Grab the current time for rotation use. */
911 if ((Gflag_time = time(NULL)) == (time_t)-1) {
912 error("main: can't get current time: %s",
913 pcap_strerror(errno));
914 }
915 break;
916
917 case 'h':
918 print_usage();
919 exit(0);
920 break;
921
922 case 'H':
923 ++ndo->ndo_Hflag;
924 break;
925
926 case 'i':
927 if (optarg[0] == '0' && optarg[1] == 0)
928 error("Invalid adapter index");
929
930 #ifdef HAVE_PCAP_FINDALLDEVS
931 /*
932 * If the argument is a number, treat it as
933 * an index into the list of adapters, as
934 * printed by "tcpdump -D".
935 *
936 * This should be OK on UNIX systems, as interfaces
937 * shouldn't have names that begin with digits.
938 * It can be useful on Windows, where more than
939 * one interface can have the same name.
940 */
941 devnum = strtol(optarg, &end, 10);
942 if (optarg != end && *end == '\0') {
943 if (devnum < 0)
944 error("Invalid adapter index");
945
946 if (pcap_findalldevs(&devlist, ebuf) < 0)
947 error("%s", ebuf);
948 /*
949 * Look for the devnum-th entry in the
950 * list of devices (1-based).
951 */
952 for (i = 0, dev = devlist;
953 i < devnum-1 && dev != NULL;
954 i++, dev = dev->next)
955 ;
956 if (dev == NULL)
957 error("Invalid adapter index");
958 device = strdup(dev->name);
959 pcap_freealldevs(devlist);
960 break;
961 }
962 #endif /* HAVE_PCAP_FINDALLDEVS */
963 device = optarg;
964 break;
965
966 #ifdef HAVE_PCAP_CREATE
967 case 'I':
968 ++Iflag;
969 break;
970 #endif /* HAVE_PCAP_CREATE */
971
972 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
973 case 'j':
974 jflag = pcap_tstamp_type_name_to_val(optarg);
975 if (jflag < 0)
976 error("invalid time stamp type %s", optarg);
977 break;
978
979 case 'J':
980 Jflag++;
981 break;
982 #endif
983
984 case 'l':
985 #ifdef _WIN32
986 /*
987 * _IOLBF is the same as _IOFBF in Microsoft's C
988 * libraries; the only alternative they offer
989 * is _IONBF.
990 *
991 * XXX - this should really be checking for MSVC++,
992 * not _WIN32, if, for example, MinGW has its own
993 * C library that is more UNIX-compatible.
994 */
995 setvbuf(stdout, NULL, _IONBF, 0);
996 #else /* _WIN32 */
997 #ifdef HAVE_SETLINEBUF
998 setlinebuf(stdout);
999 #else
1000 setvbuf(stdout, NULL, _IOLBF, 0);
1001 #endif
1002 #endif /* _WIN32 */
1003 break;
1004
1005 case 'K':
1006 ++ndo->ndo_Kflag;
1007 break;
1008
1009 case 'm':
1010 #ifdef USE_LIBSMI
1011 if (smiLoadModule(optarg) == 0) {
1012 error("could not load MIB module %s", optarg);
1013 }
1014 ndo->ndo_mflag = 1;
1015 #else
1016 (void)fprintf(stderr, "%s: ignoring option `-m %s' ",
1017 program_name, optarg);
1018 (void)fprintf(stderr, "(no libsmi support)\n");
1019 #endif
1020 break;
1021
1022 case 'M':
1023 /* TCP-MD5 shared secret */
1024 #ifndef HAVE_LIBCRYPTO
1025 warning("crypto code not compiled in");
1026 #endif
1027 ndo->ndo_sigsecret = optarg;
1028 break;
1029
1030 case 'n':
1031 ++ndo->ndo_nflag;
1032 break;
1033
1034 case 'N':
1035 ++ndo->ndo_Nflag;
1036 break;
1037
1038 case 'O':
1039 Oflag = 0;
1040 break;
1041
1042 case 'p':
1043 ++pflag;
1044 break;
1045
1046 case 'q':
1047 ++ndo->ndo_qflag;
1048 ++ndo->ndo_suppress_default_print;
1049 break;
1050
1051 #ifdef HAVE_PCAP_SETDIRECTION
1052 case 'Q':
1053 if (ascii_strcasecmp(optarg, "in") == 0)
1054 Qflag = PCAP_D_IN;
1055 else if (ascii_strcasecmp(optarg, "out") == 0)
1056 Qflag = PCAP_D_OUT;
1057 else if (ascii_strcasecmp(optarg, "inout") == 0)
1058 Qflag = PCAP_D_INOUT;
1059 else
1060 error("unknown capture direction `%s'", optarg);
1061 break;
1062 #endif /* HAVE_PCAP_SETDIRECTION */
1063
1064 case 'r':
1065 RFileName = optarg;
1066 break;
1067
1068 case 's':
1069 ndo->ndo_snaplen = strtol(optarg, &end, 0);
1070 if (optarg == end || *end != '\0'
1071 || ndo->ndo_snaplen < 0 || ndo->ndo_snaplen > MAXIMUM_SNAPLEN)
1072 error("invalid snaplen %s", optarg);
1073 else if (ndo->ndo_snaplen == 0)
1074 ndo->ndo_snaplen = MAXIMUM_SNAPLEN;
1075 break;
1076
1077 case 'S':
1078 ++ndo->ndo_Sflag;
1079 break;
1080
1081 case 't':
1082 ++ndo->ndo_tflag;
1083 break;
1084
1085 case 'T':
1086 if (ascii_strcasecmp(optarg, "vat") == 0)
1087 ndo->ndo_packettype = PT_VAT;
1088 else if (ascii_strcasecmp(optarg, "wb") == 0)
1089 ndo->ndo_packettype = PT_WB;
1090 else if (ascii_strcasecmp(optarg, "rpc") == 0)
1091 ndo->ndo_packettype = PT_RPC;
1092 else if (ascii_strcasecmp(optarg, "rtp") == 0)
1093 ndo->ndo_packettype = PT_RTP;
1094 else if (ascii_strcasecmp(optarg, "rtcp") == 0)
1095 ndo->ndo_packettype = PT_RTCP;
1096 else if (ascii_strcasecmp(optarg, "snmp") == 0)
1097 ndo->ndo_packettype = PT_SNMP;
1098 else if (ascii_strcasecmp(optarg, "cnfp") == 0)
1099 ndo->ndo_packettype = PT_CNFP;
1100 else if (ascii_strcasecmp(optarg, "tftp") == 0)
1101 ndo->ndo_packettype = PT_TFTP;
1102 else if (ascii_strcasecmp(optarg, "aodv") == 0)
1103 ndo->ndo_packettype = PT_AODV;
1104 else if (ascii_strcasecmp(optarg, "carp") == 0)
1105 ndo->ndo_packettype = PT_CARP;
1106 else if (ascii_strcasecmp(optarg, "radius") == 0)
1107 ndo->ndo_packettype = PT_RADIUS;
1108 else if (ascii_strcasecmp(optarg, "zmtp1") == 0)
1109 ndo->ndo_packettype = PT_ZMTP1;
1110 else if (ascii_strcasecmp(optarg, "vxlan") == 0)
1111 ndo->ndo_packettype = PT_VXLAN;
1112 else if (ascii_strcasecmp(optarg, "pgm") == 0)
1113 ndo->ndo_packettype = PT_PGM;
1114 else if (ascii_strcasecmp(optarg, "pgm_zmtp1") == 0)
1115 ndo->ndo_packettype = PT_PGM_ZMTP1;
1116 else if (ascii_strcasecmp(optarg, "lmp") == 0)
1117 ndo->ndo_packettype = PT_LMP;
1118 else if (ascii_strcasecmp(optarg, "resp") == 0)
1119 ndo->ndo_packettype = PT_RESP;
1120 else
1121 error("unknown packet type `%s'", optarg);
1122 break;
1123
1124 case 'u':
1125 ++ndo->ndo_uflag;
1126 break;
1127
1128 #ifdef HAVE_PCAP_DUMP_FLUSH
1129 case 'U':
1130 ++Uflag;
1131 break;
1132 #endif
1133
1134 case 'v':
1135 ++ndo->ndo_vflag;
1136 break;
1137
1138 case 'V':
1139 VFileName = optarg;
1140 break;
1141
1142 case 'w':
1143 WFileName = optarg;
1144 break;
1145
1146 case 'W':
1147 Wflag = atoi(optarg);
1148 if (Wflag <= 0)
1149 error("invalid number of output files %s", optarg);
1150 WflagChars = getWflagChars(Wflag);
1151 break;
1152
1153 case 'x':
1154 ++ndo->ndo_xflag;
1155 ++ndo->ndo_suppress_default_print;
1156 break;
1157
1158 case 'X':
1159 ++ndo->ndo_Xflag;
1160 ++ndo->ndo_suppress_default_print;
1161 break;
1162
1163 case 'y':
1164 yflag_dlt_name = optarg;
1165 yflag_dlt =
1166 pcap_datalink_name_to_val(yflag_dlt_name);
1167 if (yflag_dlt < 0)
1168 error("invalid data link type %s", yflag_dlt_name);
1169 break;
1170
1171 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
1172 case 'Y':
1173 {
1174 /* Undocumented flag */
1175 pcap_set_parser_debug(1);
1176 }
1177 break;
1178 #endif
1179 case 'z':
1180 zflag = optarg;
1181 break;
1182
1183 case 'Z':
1184 username = optarg;
1185 break;
1186
1187 case '#':
1188 ndo->ndo_packet_number = 1;
1189 break;
1190
1191 case OPTION_VERSION:
1192 print_version();
1193 exit(0);
1194 break;
1195
1196 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1197 case OPTION_TSTAMP_PRECISION:
1198 ndo->ndo_tstamp_precision = tstamp_precision_from_string(optarg);
1199 if (ndo->ndo_tstamp_precision < 0)
1200 error("unsupported time stamp precision");
1201 break;
1202 #endif
1203
1204 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1205 case OPTION_IMMEDIATE_MODE:
1206 immediate_mode = 1;
1207 break;
1208 #endif
1209
1210 default:
1211 print_usage();
1212 exit(1);
1213 /* NOTREACHED */
1214 }
1215
1216 #ifdef HAVE_PCAP_FINDALLDEVS
1217 if (Dflag)
1218 show_devices_and_exit();
1219 #endif
1220
1221 switch (ndo->ndo_tflag) {
1222
1223 case 0: /* Default */
1224 case 4: /* Default + Date*/
1225 timezone_offset = gmt2local(0);
1226 break;
1227
1228 case 1: /* No time stamp */
1229 case 2: /* Unix timeval style */
1230 case 3: /* Microseconds since previous packet */
1231 case 5: /* Microseconds since first packet */
1232 break;
1233
1234 default: /* Not supported */
1235 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1236 break;
1237 }
1238
1239 if (ndo->ndo_fflag != 0 && (VFileName != NULL || RFileName != NULL))
1240 error("-f can not be used with -V or -r");
1241
1242 if (VFileName != NULL && RFileName != NULL)
1243 error("-V and -r are mutually exclusive.");
1244
1245 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1246 /*
1247 * If we're printing dissected packets to the standard output
1248 * rather than saving raw packets to a file, and the standard
1249 * output is a terminal, use immediate mode, as the user's
1250 * probably expecting to see packets pop up immediately.
1251 */
1252 if (WFileName == NULL && isatty(1))
1253 immediate_mode = 1;
1254 #endif
1255
1256 #ifdef WITH_CHROOT
1257 /* if run as root, prepare for chrooting */
1258 if (getuid() == 0 || geteuid() == 0) {
1259 /* future extensibility for cmd-line arguments */
1260 if (!chroot_dir)
1261 chroot_dir = WITH_CHROOT;
1262 }
1263 #endif
1264
1265 #ifdef WITH_USER
1266 /* if run as root, prepare for dropping root privileges */
1267 if (getuid() == 0 || geteuid() == 0) {
1268 /* Run with '-Z root' to restore old behaviour */
1269 if (!username)
1270 username = WITH_USER;
1271 }
1272 #endif
1273
1274 if (RFileName != NULL || VFileName != NULL) {
1275 /*
1276 * If RFileName is non-null, it's the pathname of a
1277 * savefile to read. If VFileName is non-null, it's
1278 * the pathname of a file containing a list of pathnames
1279 * (one per line) of savefiles to read.
1280 *
1281 * In either case, we're reading a savefile, not doing
1282 * a live capture.
1283 */
1284 #ifndef _WIN32
1285 /*
1286 * We don't need network access, so relinquish any set-UID
1287 * or set-GID privileges we have (if any).
1288 *
1289 * We do *not* want set-UID privileges when opening a
1290 * trace file, as that might let the user read other
1291 * people's trace files (especially if we're set-UID
1292 * root).
1293 */
1294 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1295 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1296 #endif /* _WIN32 */
1297 if (VFileName != NULL) {
1298 if (VFileName[0] == '-' && VFileName[1] == '\0')
1299 VFile = stdin;
1300 else
1301 VFile = fopen(VFileName, "r");
1302
1303 if (VFile == NULL)
1304 error("Unable to open file: %s\n", pcap_strerror(errno));
1305
1306 ret = get_next_file(VFile, VFileLine);
1307 if (!ret)
1308 error("Nothing in %s\n", VFileName);
1309 RFileName = VFileLine;
1310 }
1311
1312 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1313 pd = pcap_open_offline_with_tstamp_precision(RFileName,
1314 ndo->ndo_tstamp_precision, ebuf);
1315 #else
1316 pd = pcap_open_offline(RFileName, ebuf);
1317 #endif
1318
1319 if (pd == NULL)
1320 error("%s", ebuf);
1321 #ifdef HAVE_CAPSICUM
1322 cap_rights_init(&rights, CAP_READ);
1323 if (cap_rights_limit(fileno(pcap_file(pd)), &rights) < 0 &&
1324 errno != ENOSYS) {
1325 error("unable to limit pcap descriptor");
1326 }
1327 #endif
1328 dlt = pcap_datalink(pd);
1329 dlt_name = pcap_datalink_val_to_name(dlt);
1330 if (dlt_name == NULL) {
1331 fprintf(stderr, "reading from file %s, link-type %u\n",
1332 RFileName, dlt);
1333 } else {
1334 fprintf(stderr,
1335 "reading from file %s, link-type %s (%s)\n",
1336 RFileName, dlt_name,
1337 pcap_datalink_val_to_description(dlt));
1338 }
1339 } else {
1340 /*
1341 * We're doing a live capture.
1342 */
1343 if (device == NULL) {
1344 #ifdef HAVE_PCAP_FINDALLDEVS
1345 if (pcap_findalldevs(&devlist, ebuf) >= 0 &&
1346 devlist != NULL) {
1347 device = strdup(devlist->name);
1348 pcap_freealldevs(devlist);
1349 }
1350 #else /* HAVE_PCAP_FINDALLDEVS */
1351 device = pcap_lookupdev(ebuf);
1352 #endif
1353 if (device == NULL)
1354 error("%s", ebuf);
1355 }
1356 #ifdef _WIN32
1357 /*
1358 * Print a message to the standard error on Windows.
1359 * XXX - why do it here, with a different message?
1360 */
1361 if(strlen(device) == 1) /* we assume that an ASCII string is always longer than 1 char */
1362 { /* a Unicode string has a \0 as second byte (so strlen() is 1) */
1363 fprintf(stderr, "%s: listening on %ws\n", program_name, device);
1364 }
1365 else
1366 {
1367 fprintf(stderr, "%s: listening on %s\n", program_name, device);
1368 }
1369
1370 fflush(stderr);
1371 #endif /* _WIN32 */
1372 #ifdef HAVE_PCAP_CREATE
1373 pd = pcap_create(device, ebuf);
1374 if (pd == NULL)
1375 error("%s", ebuf);
1376 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1377 if (Jflag)
1378 show_tstamp_types_and_exit(device);
1379 #endif
1380 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1381 status = pcap_set_tstamp_precision(pd, ndo->ndo_tstamp_precision);
1382 if (status != 0)
1383 error("%s: Can't set %ssecond time stamp precision: %s",
1384 device,
1385 tstamp_precision_to_string(ndo->ndo_tstamp_precision),
1386 pcap_statustostr(status));
1387 #endif
1388
1389 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1390 if (immediate_mode) {
1391 status = pcap_set_immediate_mode(pd, 1);
1392 if (status != 0)
1393 error("%s: Can't set immediate mode: %s",
1394 device,
1395 pcap_statustostr(status));
1396 }
1397 #endif
1398 /*
1399 * Is this an interface that supports monitor mode?
1400 */
1401 if (pcap_can_set_rfmon(pd) == 1)
1402 supports_monitor_mode = 1;
1403 else
1404 supports_monitor_mode = 0;
1405 status = pcap_set_snaplen(pd, ndo->ndo_snaplen);
1406 if (status != 0)
1407 error("%s: Can't set snapshot length: %s",
1408 device, pcap_statustostr(status));
1409 status = pcap_set_promisc(pd, !pflag);
1410 if (status != 0)
1411 error("%s: Can't set promiscuous mode: %s",
1412 device, pcap_statustostr(status));
1413 if (Iflag) {
1414 status = pcap_set_rfmon(pd, 1);
1415 if (status != 0)
1416 error("%s: Can't set monitor mode: %s",
1417 device, pcap_statustostr(status));
1418 }
1419 status = pcap_set_timeout(pd, 1000);
1420 if (status != 0)
1421 error("%s: pcap_set_timeout failed: %s",
1422 device, pcap_statustostr(status));
1423 if (Bflag != 0) {
1424 status = pcap_set_buffer_size(pd, Bflag);
1425 if (status != 0)
1426 error("%s: Can't set buffer size: %s",
1427 device, pcap_statustostr(status));
1428 }
1429 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1430 if (jflag != -1) {
1431 status = pcap_set_tstamp_type(pd, jflag);
1432 if (status < 0)
1433 error("%s: Can't set time stamp type: %s",
1434 device, pcap_statustostr(status));
1435 }
1436 #endif
1437 status = pcap_activate(pd);
1438 if (status < 0) {
1439 /*
1440 * pcap_activate() failed.
1441 */
1442 cp = pcap_geterr(pd);
1443 if (status == PCAP_ERROR)
1444 error("%s", cp);
1445 else if ((status == PCAP_ERROR_NO_SUCH_DEVICE ||
1446 status == PCAP_ERROR_PERM_DENIED) &&
1447 *cp != '\0')
1448 error("%s: %s\n(%s)", device,
1449 pcap_statustostr(status), cp);
1450 else
1451 error("%s: %s", device,
1452 pcap_statustostr(status));
1453 } else if (status > 0) {
1454 /*
1455 * pcap_activate() succeeded, but it's warning us
1456 * of a problem it had.
1457 */
1458 cp = pcap_geterr(pd);
1459 if (status == PCAP_WARNING)
1460 warning("%s", cp);
1461 else if (status == PCAP_WARNING_PROMISC_NOTSUP &&
1462 *cp != '\0')
1463 warning("%s: %s\n(%s)", device,
1464 pcap_statustostr(status), cp);
1465 else
1466 warning("%s: %s", device,
1467 pcap_statustostr(status));
1468 }
1469 #ifdef HAVE_PCAP_SETDIRECTION
1470 if (Qflag != -1) {
1471 status = pcap_setdirection(pd, Qflag);
1472 if (status != 0)
1473 error("%s: pcap_setdirection() failed: %s",
1474 device, pcap_geterr(pd));
1475 }
1476 #endif /* HAVE_PCAP_SETDIRECTION */
1477 #else
1478 *ebuf = '\0';
1479 pd = pcap_open_live(device, ndo->ndo_snaplen, !pflag, 1000,
1480 ebuf);
1481 if (pd == NULL)
1482 error("%s", ebuf);
1483 else if (*ebuf)
1484 warning("%s", ebuf);
1485 #endif /* HAVE_PCAP_CREATE */
1486 /*
1487 * Let user own process after socket has been opened.
1488 */
1489 #ifndef _WIN32
1490 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1491 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1492 #endif /* _WIN32 */
1493 #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32)
1494 if(Bflag != 0)
1495 if(pcap_setbuff(pd, Bflag)==-1){
1496 error("%s", pcap_geterr(pd));
1497 }
1498 #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */
1499 if (Lflag)
1500 show_dlts_and_exit(device);
1501 if (yflag_dlt >= 0) {
1502 #ifdef HAVE_PCAP_SET_DATALINK
1503 if (pcap_set_datalink(pd, yflag_dlt) < 0)
1504 error("%s", pcap_geterr(pd));
1505 #else
1506 /*
1507 * We don't actually support changing the
1508 * data link type, so we only let them
1509 * set it to what it already is.
1510 */
1511 if (yflag_dlt != pcap_datalink(pd)) {
1512 error("%s is not one of the DLTs supported by this device\n",
1513 yflag_dlt_name);
1514 }
1515 #endif
1516 (void)fprintf(stderr, "%s: data link type %s\n",
1517 program_name, yflag_dlt_name);
1518 (void)fflush(stderr);
1519 }
1520 i = pcap_snapshot(pd);
1521 if (ndo->ndo_snaplen < i) {
1522 warning("snaplen raised from %d to %d", ndo->ndo_snaplen, i);
1523 ndo->ndo_snaplen = i;
1524 }
1525 if(ndo->ndo_fflag != 0) {
1526 if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
1527 warning("foreign (-f) flag used but: %s", ebuf);
1528 }
1529 }
1530
1531 }
1532 if (infile)
1533 cmdbuf = read_infile(infile);
1534 else
1535 cmdbuf = copy_argv(&argv[optind]);
1536
1537 #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
1538 pcap_set_optimizer_debug(dflag);
1539 #endif
1540 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1541 error("%s", pcap_geterr(pd));
1542 if (dflag) {
1543 bpf_dump(&fcode, dflag);
1544 pcap_close(pd);
1545 free(cmdbuf);
1546 pcap_freecode(&fcode);
1547 exit(0);
1548 }
1549 init_print(ndo, localnet, netmask, timezone_offset);
1550
1551 #ifndef _WIN32
1552 (void)setsignal(SIGPIPE, cleanup);
1553 (void)setsignal(SIGTERM, cleanup);
1554 (void)setsignal(SIGINT, cleanup);
1555 #endif /* _WIN32 */
1556 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1557 (void)setsignal(SIGCHLD, child_cleanup);
1558 #endif
1559 /* Cooperate with nohup(1) */
1560 #ifndef _WIN32
1561 if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
1562 (void)setsignal(SIGHUP, oldhandler);
1563 #endif /* _WIN32 */
1564
1565 #ifndef _WIN32
1566 /*
1567 * If a user name was specified with "-Z", attempt to switch to
1568 * that user's UID. This would probably be used with sudo,
1569 * to allow tcpdump to be run in a special restricted
1570 * account (if you just want to allow users to open capture
1571 * devices, and can't just give users that permission,
1572 * you'd make tcpdump set-UID or set-GID).
1573 *
1574 * Tcpdump doesn't necessarily write only to one savefile;
1575 * the general only way to allow a -Z instance to write to
1576 * savefiles as the user under whose UID it's run, rather
1577 * than as the user specified with -Z, would thus be to switch
1578 * to the original user ID before opening a capture file and
1579 * then switch back to the -Z user ID after opening the savefile.
1580 * Switching to the -Z user ID only after opening the first
1581 * savefile doesn't handle the general case.
1582 */
1583
1584 if (getuid() == 0 || geteuid() == 0) {
1585 #ifdef HAVE_LIBCAP_NG
1586 /* Initialize capng */
1587 capng_clear(CAPNG_SELECT_BOTH);
1588 if (username) {
1589 capng_updatev(
1590 CAPNG_ADD,
1591 CAPNG_PERMITTED | CAPNG_EFFECTIVE,
1592 CAP_SETUID,
1593 CAP_SETGID,
1594 -1);
1595 }
1596
1597 if (WFileName) {
1598 capng_update(
1599 CAPNG_ADD,
1600 CAPNG_PERMITTED | CAPNG_EFFECTIVE,
1601 CAP_DAC_OVERRIDE
1602 );
1603 }
1604 capng_apply(CAPNG_SELECT_BOTH);
1605 #endif /* HAVE_LIBCAP_NG */
1606 if (username || chroot_dir)
1607 droproot(username, chroot_dir);
1608
1609 }
1610 #endif /* _WIN32 */
1611
1612 if (pcap_setfilter(pd, &fcode) < 0)
1613 error("%s", pcap_geterr(pd));
1614 #ifdef HAVE_CAPSICUM
1615 if (RFileName == NULL && VFileName == NULL) {
1616 static const unsigned long cmds[] = { BIOCGSTATS, BIOCROTZBUF };
1617
1618 cap_rights_init(&rights, CAP_IOCTL, CAP_READ);
1619 if (cap_rights_limit(pcap_fileno(pd), &rights) < 0 &&
1620 errno != ENOSYS) {
1621 error("unable to limit pcap descriptor");
1622 }
1623 if (cap_ioctls_limit(pcap_fileno(pd), cmds,
1624 sizeof(cmds) / sizeof(cmds[0])) < 0 && errno != ENOSYS) {
1625 error("unable to limit ioctls on pcap descriptor");
1626 }
1627 }
1628 #endif
1629 if (WFileName) {
1630 pcap_dumper_t *p;
1631 /* Do not exceed the default PATH_MAX for files. */
1632 dumpinfo.CurrentFileName = (char *)malloc(PATH_MAX + 1);
1633
1634 if (dumpinfo.CurrentFileName == NULL)
1635 error("malloc of dumpinfo.CurrentFileName");
1636
1637 /* We do not need numbering for dumpfiles if Cflag isn't set. */
1638 if (Cflag != 0)
1639 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
1640 else
1641 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
1642
1643 p = pcap_dump_open(pd, dumpinfo.CurrentFileName);
1644 #ifdef HAVE_LIBCAP_NG
1645 /* Give up CAP_DAC_OVERRIDE capability.
1646 * Only allow it to be restored if the -C or -G flag have been
1647 * set since we may need to create more files later on.
1648 */
1649 capng_update(
1650 CAPNG_DROP,
1651 (Cflag || Gflag ? 0 : CAPNG_PERMITTED)
1652 | CAPNG_EFFECTIVE,
1653 CAP_DAC_OVERRIDE
1654 );
1655 capng_apply(CAPNG_SELECT_BOTH);
1656 #endif /* HAVE_LIBCAP_NG */
1657 if (p == NULL)
1658 error("%s", pcap_geterr(pd));
1659 #ifdef HAVE_CAPSICUM
1660 set_dumper_capsicum_rights(p);
1661 #endif
1662 if (Cflag != 0 || Gflag != 0) {
1663 #ifdef HAVE_CAPSICUM
1664 dumpinfo.WFileName = strdup(basename(WFileName));
1665 if (dumpinfo.WFileName == NULL) {
1666 error("Unable to allocate memory for file %s",
1667 WFileName);
1668 }
1669 dumpinfo.dirfd = open(dirname(WFileName),
1670 O_DIRECTORY | O_RDONLY);
1671 if (dumpinfo.dirfd < 0) {
1672 error("unable to open directory %s",
1673 dirname(WFileName));
1674 }
1675 cap_rights_init(&rights, CAP_CREATE, CAP_FCNTL,
1676 CAP_FTRUNCATE, CAP_LOOKUP, CAP_SEEK, CAP_WRITE);
1677 if (cap_rights_limit(dumpinfo.dirfd, &rights) < 0 &&
1678 errno != ENOSYS) {
1679 error("unable to limit directory rights");
1680 }
1681 if (cap_fcntls_limit(dumpinfo.dirfd, CAP_FCNTL_GETFL) < 0 &&
1682 errno != ENOSYS) {
1683 error("unable to limit dump descriptor fcntls");
1684 }
1685 #else /* !HAVE_CAPSICUM */
1686 dumpinfo.WFileName = WFileName;
1687 #endif
1688 callback = dump_packet_and_trunc;
1689 dumpinfo.pd = pd;
1690 dumpinfo.p = p;
1691 pcap_userdata = (u_char *)&dumpinfo;
1692 } else {
1693 callback = dump_packet;
1694 pcap_userdata = (u_char *)p;
1695 }
1696 #ifdef HAVE_PCAP_DUMP_FLUSH
1697 if (Uflag)
1698 pcap_dump_flush(p);
1699 #endif
1700 } else {
1701 dlt = pcap_datalink(pd);
1702 ndo->ndo_if_printer = get_if_printer(ndo, dlt);
1703 callback = print_packet;
1704 pcap_userdata = (u_char *)ndo;
1705 }
1706
1707 #ifdef SIGNAL_REQ_INFO
1708 /*
1709 * We can't get statistics when reading from a file rather
1710 * than capturing from a device.
1711 */
1712 if (RFileName == NULL)
1713 (void)setsignal(SIGNAL_REQ_INFO, requestinfo);
1714 #endif
1715
1716 if (ndo->ndo_vflag > 0 && WFileName) {
1717 /*
1718 * When capturing to a file, "-v" means tcpdump should,
1719 * every 10 seconds, "v"erbosely report the number of
1720 * packets captured.
1721 */
1722 #ifdef USE_WIN32_MM_TIMER
1723 /* call verbose_stats_dump() each 1000 +/-100msec */
1724 timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
1725 setvbuf(stderr, NULL, _IONBF, 0);
1726 #elif defined(HAVE_ALARM)
1727 (void)setsignal(SIGALRM, verbose_stats_dump);
1728 alarm(1);
1729 #endif
1730 }
1731
1732 #ifndef _WIN32
1733 if (RFileName == NULL) {
1734 /*
1735 * Live capture (if -V was specified, we set RFileName
1736 * to a file from the -V file). Print a message to
1737 * the standard error on UN*X.
1738 */
1739 if (!ndo->ndo_vflag && !WFileName) {
1740 (void)fprintf(stderr,
1741 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
1742 program_name);
1743 } else
1744 (void)fprintf(stderr, "%s: ", program_name);
1745 dlt = pcap_datalink(pd);
1746 dlt_name = pcap_datalink_val_to_name(dlt);
1747 if (dlt_name == NULL) {
1748 (void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
1749 device, dlt, ndo->ndo_snaplen);
1750 } else {
1751 (void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
1752 device, dlt_name,
1753 pcap_datalink_val_to_description(dlt), ndo->ndo_snaplen);
1754 }
1755 (void)fflush(stderr);
1756 }
1757 #endif /* _WIN32 */
1758
1759 #ifdef HAVE_CAPSICUM
1760 cansandbox = (ndo->ndo_nflag && VFileName == NULL && zflag == NULL);
1761 if (cansandbox && cap_enter() < 0 && errno != ENOSYS)
1762 error("unable to enter the capability mode");
1763 #endif /* HAVE_CAPSICUM */
1764
1765 do {
1766 status = pcap_loop(pd, cnt, callback, pcap_userdata);
1767 if (WFileName == NULL) {
1768 /*
1769 * We're printing packets. Flush the printed output,
1770 * so it doesn't get intermingled with error output.
1771 */
1772 if (status == -2) {
1773 /*
1774 * We got interrupted, so perhaps we didn't
1775 * manage to finish a line we were printing.
1776 * Print an extra newline, just in case.
1777 */
1778 putchar('\n');
1779 }
1780 (void)fflush(stdout);
1781 }
1782 if (status == -2) {
1783 /*
1784 * We got interrupted. If we are reading multiple
1785 * files (via -V) set these so that we stop.
1786 */
1787 VFileName = NULL;
1788 ret = NULL;
1789 }
1790 if (status == -1) {
1791 /*
1792 * Error. Report it.
1793 */
1794 (void)fprintf(stderr, "%s: pcap_loop: %s\n",
1795 program_name, pcap_geterr(pd));
1796 }
1797 if (RFileName == NULL) {
1798 /*
1799 * We're doing a live capture. Report the capture
1800 * statistics.
1801 */
1802 info(1);
1803 }
1804 pcap_close(pd);
1805 if (VFileName != NULL) {
1806 ret = get_next_file(VFile, VFileLine);
1807 if (ret) {
1808 int new_dlt;
1809
1810 RFileName = VFileLine;
1811 pd = pcap_open_offline(RFileName, ebuf);
1812 if (pd == NULL)
1813 error("%s", ebuf);
1814 #ifdef HAVE_CAPSICUM
1815 cap_rights_init(&rights, CAP_READ);
1816 if (cap_rights_limit(fileno(pcap_file(pd)),
1817 &rights) < 0 && errno != ENOSYS) {
1818 error("unable to limit pcap descriptor");
1819 }
1820 #endif
1821 new_dlt = pcap_datalink(pd);
1822 if (new_dlt != dlt) {
1823 /*
1824 * The new file has a different
1825 * link-layer header type from the
1826 * previous one.
1827 */
1828 if (WFileName != NULL) {
1829 /*
1830 * We're writing raw packets
1831 * that match the filter to
1832 * a pcap file. pcap files
1833 * don't support multiple
1834 * different link-layer
1835 * header types, so we fail
1836 * here.
1837 */
1838 error("%s: new dlt does not match original", RFileName);
1839 }
1840
1841 /*
1842 * We're printing the decoded packets;
1843 * switch to the new DLT.
1844 *
1845 * To do that, we need to change
1846 * the printer, change the DLT name,
1847 * and recompile the filter with
1848 * the new DLT.
1849 */
1850 dlt = new_dlt;
1851 ndo->ndo_if_printer = get_if_printer(ndo, dlt);
1852 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1853 error("%s", pcap_geterr(pd));
1854 }
1855
1856 /*
1857 * Set the filter on the new file.
1858 */
1859 if (pcap_setfilter(pd, &fcode) < 0)
1860 error("%s", pcap_geterr(pd));
1861
1862 /*
1863 * Report the new file.
1864 */
1865 dlt_name = pcap_datalink_val_to_name(dlt);
1866 if (dlt_name == NULL) {
1867 fprintf(stderr, "reading from file %s, link-type %u\n",
1868 RFileName, dlt);
1869 } else {
1870 fprintf(stderr,
1871 "reading from file %s, link-type %s (%s)\n",
1872 RFileName, dlt_name,
1873 pcap_datalink_val_to_description(dlt));
1874 }
1875 }
1876 }
1877 }
1878 while (ret != NULL);
1879
1880 free(cmdbuf);
1881 pcap_freecode(&fcode);
1882 exit(status == -1 ? 1 : 0);
1883 }
1884
1885 /* make a clean exit on interrupts */
1886 static RETSIGTYPE
1887 cleanup(int signo _U_)
1888 {
1889 #ifdef USE_WIN32_MM_TIMER
1890 if (timer_id)
1891 timeKillEvent(timer_id);
1892 timer_id = 0;
1893 #elif defined(HAVE_ALARM)
1894 alarm(0);
1895 #endif
1896
1897 #ifdef HAVE_PCAP_BREAKLOOP
1898 /*
1899 * We have "pcap_breakloop()"; use it, so that we do as little
1900 * as possible in the signal handler (it's probably not safe
1901 * to do anything with standard I/O streams in a signal handler -
1902 * the ANSI C standard doesn't say it is).
1903 */
1904 pcap_breakloop(pd);
1905 #else
1906 /*
1907 * We don't have "pcap_breakloop()"; this isn't safe, but
1908 * it's the best we can do. Print the summary if we're
1909 * not reading from a savefile - i.e., if we're doing a
1910 * live capture - and exit.
1911 */
1912 if (pd != NULL && pcap_file(pd) == NULL) {
1913 /*
1914 * We got interrupted, so perhaps we didn't
1915 * manage to finish a line we were printing.
1916 * Print an extra newline, just in case.
1917 */
1918 putchar('\n');
1919 (void)fflush(stdout);
1920 info(1);
1921 }
1922 exit(0);
1923 #endif
1924 }
1925
1926 /*
1927 On windows, we do not use a fork, so we do not care less about
1928 waiting a child processes to die
1929 */
1930 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1931 static RETSIGTYPE
1932 child_cleanup(int signo _U_)
1933 {
1934 wait(NULL);
1935 }
1936 #endif /* HAVE_FORK && HAVE_VFORK */
1937
1938 static void
1939 info(register int verbose)
1940 {
1941 struct pcap_stat stats;
1942
1943 /*
1944 * Older versions of libpcap didn't set ps_ifdrop on some
1945 * platforms; initialize it to 0 to handle that.
1946 */
1947 stats.ps_ifdrop = 0;
1948 if (pcap_stats(pd, &stats) < 0) {
1949 (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
1950 infoprint = 0;
1951 return;
1952 }
1953
1954 if (!verbose)
1955 fprintf(stderr, "%s: ", program_name);
1956
1957 (void)fprintf(stderr, "%u packet%s captured", packets_captured,
1958 PLURAL_SUFFIX(packets_captured));
1959 if (!verbose)
1960 fputs(", ", stderr);
1961 else
1962 putc('\n', stderr);
1963 (void)fprintf(stderr, "%u packet%s received by filter", stats.ps_recv,
1964 PLURAL_SUFFIX(stats.ps_recv));
1965 if (!verbose)
1966 fputs(", ", stderr);
1967 else
1968 putc('\n', stderr);
1969 (void)fprintf(stderr, "%u packet%s dropped by kernel", stats.ps_drop,
1970 PLURAL_SUFFIX(stats.ps_drop));
1971 if (stats.ps_ifdrop != 0) {
1972 if (!verbose)
1973 fputs(", ", stderr);
1974 else
1975 putc('\n', stderr);
1976 (void)fprintf(stderr, "%u packet%s dropped by interface\n",
1977 stats.ps_ifdrop, PLURAL_SUFFIX(stats.ps_ifdrop));
1978 } else
1979 putc('\n', stderr);
1980 infoprint = 0;
1981 }
1982
1983 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1984 #ifdef HAVE_FORK
1985 #define fork_subprocess() fork()
1986 #else
1987 #define fork_subprocess() vfork()
1988 #endif
1989 static void
1990 compress_savefile(const char *filename)
1991 {
1992 pid_t child;
1993
1994 child = fork_subprocess();
1995 if (child == -1) {
1996 fprintf(stderr,
1997 "compress_savefile: fork failed: %s\n",
1998 pcap_strerror(errno));
1999 return;
2000 }
2001 if (child != 0) {
2002 /* Parent process. */
2003 return;
2004 }
2005
2006 /*
2007 * Child process.
2008 * Set to lowest priority so that this doesn't disturb the capture.
2009 */
2010 #ifdef NZERO
2011 setpriority(PRIO_PROCESS, 0, NZERO - 1);
2012 #else
2013 setpriority(PRIO_PROCESS, 0, 19);
2014 #endif
2015 if (execlp(zflag, zflag, filename, (char *)NULL) == -1)
2016 fprintf(stderr,
2017 "compress_savefile: execlp(%s, %s) failed: %s\n",
2018 zflag,
2019 filename,
2020 pcap_strerror(errno));
2021 #ifdef HAVE_FORK
2022 exit(1);
2023 #else
2024 _exit(1);
2025 #endif
2026 }
2027 #else /* HAVE_FORK && HAVE_VFORK */
2028 static void
2029 compress_savefile(const char *filename)
2030 {
2031 fprintf(stderr,
2032 "compress_savefile failed. Functionality not implemented under your system\n");
2033 }
2034 #endif /* HAVE_FORK && HAVE_VFORK */
2035
2036 static void
2037 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2038 {
2039 struct dump_info *dump_info;
2040
2041 ++packets_captured;
2042
2043 ++infodelay;
2044
2045 dump_info = (struct dump_info *)user;
2046
2047 /*
2048 * XXX - this won't force the file to rotate on the specified time
2049 * boundary, but it will rotate on the first packet received after the
2050 * specified Gflag number of seconds. Note: if a Gflag time boundary
2051 * and a Cflag size boundary coincide, the time rotation will occur
2052 * first thereby cancelling the Cflag boundary (since the file should
2053 * be 0).
2054 */
2055 if (Gflag != 0) {
2056 /* Check if it is time to rotate */
2057 time_t t;
2058
2059 /* Get the current time */
2060 if ((t = time(NULL)) == (time_t)-1) {
2061 error("dump_and_trunc_packet: can't get current_time: %s",
2062 pcap_strerror(errno));
2063 }
2064
2065
2066 /* If the time is greater than the specified window, rotate */
2067 if (t - Gflag_time >= Gflag) {
2068 #ifdef HAVE_CAPSICUM
2069 FILE *fp;
2070 int fd;
2071 #endif
2072
2073 /* Update the Gflag_time */
2074 Gflag_time = t;
2075 /* Update Gflag_count */
2076 Gflag_count++;
2077 /*
2078 * Close the current file and open a new one.
2079 */
2080 pcap_dump_close(dump_info->p);
2081
2082 /*
2083 * Compress the file we just closed, if the user asked for it
2084 */
2085 if (zflag != NULL)
2086 compress_savefile(dump_info->CurrentFileName);
2087
2088 /*
2089 * Check to see if we've exceeded the Wflag (when
2090 * not using Cflag).
2091 */
2092 if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
2093 (void)fprintf(stderr, "Maximum file limit reached: %d\n",
2094 Wflag);
2095 exit(0);
2096 /* NOTREACHED */
2097 }
2098 if (dump_info->CurrentFileName != NULL)
2099 free(dump_info->CurrentFileName);
2100 /* Allocate space for max filename + \0. */
2101 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2102 if (dump_info->CurrentFileName == NULL)
2103 error("dump_packet_and_trunc: malloc");
2104 /*
2105 * Gflag was set otherwise we wouldn't be here. Reset the count
2106 * so multiple files would end with 1,2,3 in the filename.
2107 * The counting is handled with the -C flow after this.
2108 */
2109 Cflag_count = 0;
2110
2111 /*
2112 * This is always the first file in the Cflag
2113 * rotation: e.g. 0
2114 * We also don't need numbering if Cflag is not set.
2115 */
2116 if (Cflag != 0)
2117 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
2118 WflagChars);
2119 else
2120 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
2121
2122 #ifdef HAVE_LIBCAP_NG
2123 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2124 capng_apply(CAPNG_SELECT_BOTH);
2125 #endif /* HAVE_LIBCAP_NG */
2126 #ifdef HAVE_CAPSICUM
2127 fd = openat(dump_info->dirfd,
2128 dump_info->CurrentFileName,
2129 O_CREAT | O_WRONLY | O_TRUNC, 0644);
2130 if (fd < 0) {
2131 error("unable to open file %s",
2132 dump_info->CurrentFileName);
2133 }
2134 fp = fdopen(fd, "w");
2135 if (fp == NULL) {
2136 error("unable to fdopen file %s",
2137 dump_info->CurrentFileName);
2138 }
2139 dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2140 #else /* !HAVE_CAPSICUM */
2141 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2142 #endif
2143 #ifdef HAVE_LIBCAP_NG
2144 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2145 capng_apply(CAPNG_SELECT_BOTH);
2146 #endif /* HAVE_LIBCAP_NG */
2147 if (dump_info->p == NULL)
2148 error("%s", pcap_geterr(pd));
2149 #ifdef HAVE_CAPSICUM
2150 set_dumper_capsicum_rights(dump_info->p);
2151 #endif
2152 }
2153 }
2154
2155 /*
2156 * XXX - this won't prevent capture files from getting
2157 * larger than Cflag - the last packet written to the
2158 * file could put it over Cflag.
2159 */
2160 if (Cflag != 0) {
2161 long size = pcap_dump_ftell(dump_info->p);
2162
2163 if (size == -1)
2164 error("ftell fails on output file");
2165 if (size > Cflag) {
2166 #ifdef HAVE_CAPSICUM
2167 FILE *fp;
2168 int fd;
2169 #endif
2170
2171 /*
2172 * Close the current file and open a new one.
2173 */
2174 pcap_dump_close(dump_info->p);
2175
2176 /*
2177 * Compress the file we just closed, if the user
2178 * asked for it.
2179 */
2180 if (zflag != NULL)
2181 compress_savefile(dump_info->CurrentFileName);
2182
2183 Cflag_count++;
2184 if (Wflag > 0) {
2185 if (Cflag_count >= Wflag)
2186 Cflag_count = 0;
2187 }
2188 if (dump_info->CurrentFileName != NULL)
2189 free(dump_info->CurrentFileName);
2190 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2191 if (dump_info->CurrentFileName == NULL)
2192 error("dump_packet_and_trunc: malloc");
2193 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
2194 #ifdef HAVE_LIBCAP_NG
2195 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2196 capng_apply(CAPNG_SELECT_BOTH);
2197 #endif /* HAVE_LIBCAP_NG */
2198 #ifdef HAVE_CAPSICUM
2199 fd = openat(dump_info->dirfd, dump_info->CurrentFileName,
2200 O_CREAT | O_WRONLY | O_TRUNC, 0644);
2201 if (fd < 0) {
2202 error("unable to open file %s",
2203 dump_info->CurrentFileName);
2204 }
2205 fp = fdopen(fd, "w");
2206 if (fp == NULL) {
2207 error("unable to fdopen file %s",
2208 dump_info->CurrentFileName);
2209 }
2210 dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2211 #else /* !HAVE_CAPSICUM */
2212 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2213 #endif
2214 #ifdef HAVE_LIBCAP_NG
2215 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2216 capng_apply(CAPNG_SELECT_BOTH);
2217 #endif /* HAVE_LIBCAP_NG */
2218 if (dump_info->p == NULL)
2219 error("%s", pcap_geterr(pd));
2220 #ifdef HAVE_CAPSICUM
2221 set_dumper_capsicum_rights(dump_info->p);
2222 #endif
2223 }
2224 }
2225
2226 pcap_dump((u_char *)dump_info->p, h, sp);
2227 #ifdef HAVE_PCAP_DUMP_FLUSH
2228 if (Uflag)
2229 pcap_dump_flush(dump_info->p);
2230 #endif
2231
2232 --infodelay;
2233 if (infoprint)
2234 info(0);
2235 }
2236
2237 static void
2238 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2239 {
2240 ++packets_captured;
2241
2242 ++infodelay;
2243
2244 pcap_dump(user, h, sp);
2245 #ifdef HAVE_PCAP_DUMP_FLUSH
2246 if (Uflag)
2247 pcap_dump_flush((pcap_dumper_t *)user);
2248 #endif
2249
2250 --infodelay;
2251 if (infoprint)
2252 info(0);
2253 }
2254
2255 static void
2256 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2257 {
2258 ++packets_captured;
2259
2260 ++infodelay;
2261
2262 pretty_print_packet((netdissect_options *)user, h, sp, packets_captured);
2263
2264 --infodelay;
2265 if (infoprint)
2266 info(0);
2267 }
2268
2269 #ifdef _WIN32
2270 /*
2271 * XXX - there should really be libpcap calls to get the version
2272 * number as a string (the string would be generated from #defines
2273 * at run time, so that it's not generated from string constants
2274 * in the library, as, on many UNIX systems, those constants would
2275 * be statically linked into the application executable image, and
2276 * would thus reflect the version of libpcap on the system on
2277 * which the application was *linked*, not the system on which it's
2278 * *running*.
2279 *
2280 * That routine should be documented, unlike the "version[]"
2281 * string, so that UNIX vendors providing their own libpcaps
2282 * don't omit it (as a couple of vendors have...).
2283 *
2284 * Packet.dll should perhaps also export a routine to return the
2285 * version number of the Packet.dll code, to supply the
2286 * "Wpcap_version" information on Windows.
2287 */
2288 char WDversion[]="current-git.tcpdump.org";
2289 #if !defined(HAVE_GENERATED_VERSION)
2290 char version[]="current-git.tcpdump.org";
2291 #endif
2292 char pcap_version[]="current-git.tcpdump.org";
2293 char Wpcap_version[]="3.1";
2294 #endif
2295
2296 #ifdef SIGNAL_REQ_INFO
2297 RETSIGTYPE requestinfo(int signo _U_)
2298 {
2299 if (infodelay)
2300 ++infoprint;
2301 else
2302 info(0);
2303 }
2304 #endif
2305
2306 /*
2307 * Called once each second in verbose mode while dumping to file
2308 */
2309 #ifdef USE_WIN32_MM_TIMER
2310 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
2311 DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
2312 {
2313 if (infodelay == 0)
2314 fprintf(stderr, "Got %u\r", packets_captured);
2315 }
2316 #elif defined(HAVE_ALARM)
2317 static void verbose_stats_dump(int sig _U_)
2318 {
2319 if (infodelay == 0)
2320 fprintf(stderr, "Got %u\r", packets_captured);
2321 alarm(1);
2322 }
2323 #endif
2324
2325 USES_APPLE_DEPRECATED_API
2326 static void
2327 print_version(void)
2328 {
2329 extern char version[];
2330 #ifndef HAVE_PCAP_LIB_VERSION
2331 #if defined(_WIN32) || defined(HAVE_PCAP_VERSION)
2332 extern char pcap_version[];
2333 #else /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2334 static char pcap_version[] = "unknown";
2335 #endif /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2336 #endif /* HAVE_PCAP_LIB_VERSION */
2337
2338 #ifdef HAVE_PCAP_LIB_VERSION
2339 #ifdef _WIN32
2340 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2341 #else /* _WIN32 */
2342 (void)fprintf(stderr, "%s version %s\n", program_name, version);
2343 #endif /* _WIN32 */
2344 (void)fprintf(stderr, "%s\n",pcap_lib_version());
2345 #else /* HAVE_PCAP_LIB_VERSION */
2346 #ifdef _WIN32
2347 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2348 (void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
2349 #else /* _WIN32 */
2350 (void)fprintf(stderr, "%s version %s\n", program_name, version);
2351 (void)fprintf(stderr, "libpcap version %s\n", pcap_version);
2352 #endif /* _WIN32 */
2353 #endif /* HAVE_PCAP_LIB_VERSION */
2354
2355 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
2356 (void)fprintf (stderr, "%s\n", SSLeay_version(SSLEAY_VERSION));
2357 #endif
2358
2359 #ifdef USE_LIBSMI
2360 (void)fprintf (stderr, "SMI-library: %s\n", smi_version_string);
2361 #endif
2362 }
2363 USES_APPLE_RST
2364
2365 static void
2366 print_usage(void)
2367 {
2368 print_version();
2369 (void)fprintf(stderr,
2370 "Usage: %s [-aAbd" D_FLAG "efhH" I_FLAG J_FLAG "KlLnNOpqStu" U_FLAG "vxX#]" B_FLAG_USAGE " [ -c count ]\n", program_name);
2371 (void)fprintf(stderr,
2372 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
2373 (void)fprintf(stderr,
2374 "\t\t[ -i interface ]" j_FLAG_USAGE " [ -M secret ] [ --number ]\n");
2375 #ifdef HAVE_PCAP_SETDIRECTION
2376 (void)fprintf(stderr,
2377 "\t\t[ -Q in|out|inout ]\n");
2378 #endif
2379 (void)fprintf(stderr,
2380 "\t\t[ -r file ] [ -s snaplen ] ");
2381 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2382 (void)fprintf(stderr, "[ --time-stamp-precision precision ]\n");
2383 (void)fprintf(stderr,
2384 "\t\t");
2385 #endif
2386 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
2387 (void)fprintf(stderr, "[ --immediate-mode ] ");
2388 #endif
2389 (void)fprintf(stderr, "[ -T type ] [ --version ] [ -V file ]\n");
2390 (void)fprintf(stderr,
2391 "\t\t[ -w file ] [ -W filecount ] [ -y datalinktype ] [ -z postrotate-command ]\n");
2392 (void)fprintf(stderr,
2393 "\t\t[ -Z user ] [ expression ]\n");
2394 }
2395 /*
2396 * Local Variables:
2397 * c-style: whitesmith
2398 * c-basic-offset: 8
2399 * End:
2400 */