]> The Tcpdump Group git mirrors - tcpdump/blob - tcpdump.c
Don't drop CAP_SYS_CHROOT before chrooting.
[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, CAP_SETGID and CAP_SYS_CHROOT any more. */
581 capng_updatev(
582 CAPNG_DROP,
583 CAPNG_EFFECTIVE | CAPNG_PERMITTED,
584 CAP_SETUID,
585 CAP_SETGID,
586 CAP_SYS_CHROOT,
587 -1);
588 capng_apply(CAPNG_SELECT_BOTH);
589 #endif /* HAVE_LIBCAP_NG */
590
591 }
592 #endif /* _WIN32 */
593
594 static int
595 getWflagChars(int x)
596 {
597 int c = 0;
598
599 x -= 1;
600 while (x > 0) {
601 c += 1;
602 x /= 10;
603 }
604
605 return c;
606 }
607
608
609 static void
610 MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
611 {
612 char *filename = malloc(PATH_MAX + 1);
613 if (filename == NULL)
614 error("Makefilename: malloc");
615
616 /* Process with strftime if Gflag is set. */
617 if (Gflag != 0) {
618 struct tm *local_tm;
619
620 /* Convert Gflag_time to a usable format */
621 if ((local_tm = localtime(&Gflag_time)) == NULL) {
622 error("MakeTimedFilename: localtime");
623 }
624
625 /* There's no good way to detect an error in strftime since a return
626 * value of 0 isn't necessarily failure.
627 */
628 strftime(filename, PATH_MAX, orig_name, local_tm);
629 } else {
630 strncpy(filename, orig_name, PATH_MAX);
631 }
632
633 if (cnt == 0 && max_chars == 0)
634 strncpy(buffer, filename, PATH_MAX + 1);
635 else
636 if (snprintf(buffer, PATH_MAX + 1, "%s%0*d", filename, max_chars, cnt) > PATH_MAX)
637 /* Report an error if the filename is too large */
638 error("too many output files or filename is too long (> %d)", PATH_MAX);
639 free(filename);
640 }
641
642 static char *
643 get_next_file(FILE *VFile, char *ptr)
644 {
645 char *ret;
646
647 ret = fgets(ptr, PATH_MAX, VFile);
648 if (!ret)
649 return NULL;
650
651 if (ptr[strlen(ptr) - 1] == '\n')
652 ptr[strlen(ptr) - 1] = '\0';
653
654 return ret;
655 }
656
657 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
658 static int
659 tstamp_precision_from_string(const char *precision)
660 {
661 if (strncmp(precision, "nano", strlen("nano")) == 0)
662 return PCAP_TSTAMP_PRECISION_NANO;
663
664 if (strncmp(precision, "micro", strlen("micro")) == 0)
665 return PCAP_TSTAMP_PRECISION_MICRO;
666
667 return -EINVAL;
668 }
669
670 static const char *
671 tstamp_precision_to_string(int precision)
672 {
673 switch (precision) {
674
675 case PCAP_TSTAMP_PRECISION_MICRO:
676 return "micro";
677
678 case PCAP_TSTAMP_PRECISION_NANO:
679 return "nano";
680
681 default:
682 return "unknown";
683 }
684 }
685 #endif
686
687 #ifdef HAVE_CAPSICUM
688 /*
689 * Ensure that, on a dump file's descriptor, we have all the rights
690 * necessary to make the standard I/O library work with an fdopen()ed
691 * FILE * from that descriptor.
692 *
693 * A long time ago, in a galaxy far far away, AT&T decided that, instead
694 * of providing separate APIs for getting and setting the FD_ flags on a
695 * descriptor, getting and setting the O_ flags on a descriptor, and
696 * locking files, they'd throw them all into a kitchen-sink fcntl() call
697 * along the lines of ioctl(), the fact that ioctl() operations are
698 * largely specific to particular character devices but fcntl() operations
699 * are either generic to all descriptors or generic to all descriptors for
700 * regular files nonwithstanding.
701 *
702 * The Capsicum people decided that fine-grained control of descriptor
703 * operations was required, so that you need to grant permission for
704 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
705 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
706 * collection of things, so there are *individual* fcntls for which
707 * permission needs to be granted.
708 *
709 * The FreeBSD standard I/O people implemented some optimizations that
710 * requires that the standard I/O routines be able to determine whether
711 * the descriptor for the FILE * is open append-only or not; as that
712 * descriptor could have come from an open() rather than an fopen(),
713 * that requires that it be able to do an F_GETFL fcntl() to read
714 * the O_ flags.
715 *
716 * Tcpdump uses ftell() to determine how much data has been written
717 * to a file in order to, when used with -C, determine when it's time
718 * to rotate capture files. ftell() therefore needs to do an lseek()
719 * to find out the file offset and must, thanks to the aforementioned
720 * optimization, also know whether the descriptor is open append-only
721 * or not.
722 *
723 * The net result of all the above is that we need to grant CAP_SEEK,
724 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
725 *
726 * Perhaps this is the universe's way of saying that either
727 *
728 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
729 * using it, so that Capsicum-capable tcpdump wouldn't need to do
730 * an fdopen()
731 *
732 * or
733 *
734 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
735 * I/O library that knows what rights are needed by the standard
736 * I/O library, based on the open mode, and assigns them, perhaps
737 * with an additional argument indicating, for example, whether
738 * seeking should be allowed, so that tcpdump doesn't need to know
739 * what the standard I/O library happens to require this week.
740 */
741 static void
742 set_dumper_capsicum_rights(pcap_dumper_t *p)
743 {
744 int fd = fileno(pcap_dump_file(p));
745 cap_rights_t rights;
746
747 cap_rights_init(&rights, CAP_SEEK, CAP_WRITE, CAP_FCNTL);
748 if (cap_rights_limit(fd, &rights) < 0 && errno != ENOSYS) {
749 error("unable to limit dump descriptor");
750 }
751 if (cap_fcntls_limit(fd, CAP_FCNTL_GETFL) < 0 && errno != ENOSYS) {
752 error("unable to limit dump descriptor fcntls");
753 }
754 }
755 #endif
756
757 int
758 main(int argc, char **argv)
759 {
760 register int cnt, op, i;
761 bpf_u_int32 localnet =0 , netmask = 0;
762 int timezone_offset = 0;
763 register char *cp, *infile, *cmdbuf, *device, *RFileName, *VFileName, *WFileName;
764 pcap_handler callback;
765 int dlt;
766 int new_dlt;
767 const char *dlt_name;
768 struct bpf_program fcode;
769 #ifndef _WIN32
770 RETSIGTYPE (*oldhandler)(int);
771 #endif
772 struct dump_info dumpinfo;
773 u_char *pcap_userdata;
774 char ebuf[PCAP_ERRBUF_SIZE];
775 char VFileLine[PATH_MAX + 1];
776 char *username = NULL;
777 char *chroot_dir = NULL;
778 char *ret = NULL;
779 char *end;
780 #ifdef HAVE_PCAP_FINDALLDEVS
781 pcap_if_t *dev, *devlist;
782 int devnum;
783 #endif
784 int status;
785 FILE *VFile;
786 #ifdef HAVE_CAPSICUM
787 cap_rights_t rights;
788 int cansandbox;
789 #endif /* HAVE_CAPSICUM */
790 int Bflag = 0; /* buffer size */
791 int jflag = -1; /* packet time stamp source */
792 int Oflag = 1; /* run filter code optimizer */
793 int pflag = 0; /* don't go promiscuous */
794 int yflag_dlt = -1;
795 const char *yflag_dlt_name = NULL;
796
797 netdissect_options Ndo;
798 netdissect_options *ndo = &Ndo;
799 int immediate_mode = 0;
800
801 memset(ndo, 0, sizeof(*ndo));
802 ndo_set_function_pointers(ndo);
803 ndo->ndo_snaplen = DEFAULT_SNAPLEN;
804
805 cnt = -1;
806 device = NULL;
807 infile = NULL;
808 RFileName = NULL;
809 VFileName = NULL;
810 VFile = NULL;
811 WFileName = NULL;
812 dlt = -1;
813 if ((cp = strrchr(argv[0], '/')) != NULL)
814 ndo->program_name = program_name = cp + 1;
815 else
816 ndo->program_name = program_name = argv[0];
817
818 #ifdef _WIN32
819 if (pcap_wsockinit() != 0)
820 error("Attempting to initialize Winsock failed");
821 #endif /* _WIN32 */
822
823 /*
824 * On platforms where the CPU doesn't support unaligned loads,
825 * force unaligned accesses to abort with SIGBUS, rather than
826 * being fixed up (slowly) by the OS kernel; on those platforms,
827 * misaligned accesses are bugs, and we want tcpdump to crash so
828 * that the bugs are reported.
829 */
830 if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
831 error("%s", ebuf);
832
833 #ifdef USE_LIBSMI
834 smiInit("tcpdump");
835 #endif
836
837 while (
838 (op = getopt_long(argc, argv, SHORTOPTS, longopts, NULL)) != -1)
839 switch (op) {
840
841 case 'a':
842 /* compatibility for old -a */
843 break;
844
845 case 'A':
846 ++ndo->ndo_Aflag;
847 break;
848
849 case 'b':
850 ++ndo->ndo_bflag;
851 break;
852
853 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
854 case 'B':
855 Bflag = atoi(optarg)*1024;
856 if (Bflag <= 0)
857 error("invalid packet buffer size %s", optarg);
858 break;
859 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
860
861 case 'c':
862 cnt = atoi(optarg);
863 if (cnt <= 0)
864 error("invalid packet count %s", optarg);
865 break;
866
867 case 'C':
868 Cflag = atoi(optarg) * 1000000;
869 if (Cflag < 0)
870 error("invalid file size %s", optarg);
871 break;
872
873 case 'd':
874 ++dflag;
875 break;
876
877 case 'D':
878 Dflag++;
879 break;
880
881 case 'L':
882 Lflag++;
883 break;
884
885 case 'e':
886 ++ndo->ndo_eflag;
887 break;
888
889 case 'E':
890 #ifndef HAVE_LIBCRYPTO
891 warning("crypto code not compiled in");
892 #endif
893 ndo->ndo_espsecret = optarg;
894 break;
895
896 case 'f':
897 ++ndo->ndo_fflag;
898 break;
899
900 case 'F':
901 infile = optarg;
902 break;
903
904 case 'G':
905 Gflag = atoi(optarg);
906 if (Gflag < 0)
907 error("invalid number of seconds %s", optarg);
908
909 /* We will create one file initially. */
910 Gflag_count = 0;
911
912 /* Grab the current time for rotation use. */
913 if ((Gflag_time = time(NULL)) == (time_t)-1) {
914 error("main: can't get current time: %s",
915 pcap_strerror(errno));
916 }
917 break;
918
919 case 'h':
920 print_usage();
921 exit(0);
922 break;
923
924 case 'H':
925 ++ndo->ndo_Hflag;
926 break;
927
928 case 'i':
929 if (optarg[0] == '0' && optarg[1] == 0)
930 error("Invalid adapter index");
931
932 #ifdef HAVE_PCAP_FINDALLDEVS
933 /*
934 * If the argument is a number, treat it as
935 * an index into the list of adapters, as
936 * printed by "tcpdump -D".
937 *
938 * This should be OK on UNIX systems, as interfaces
939 * shouldn't have names that begin with digits.
940 * It can be useful on Windows, where more than
941 * one interface can have the same name.
942 */
943 devnum = strtol(optarg, &end, 10);
944 if (optarg != end && *end == '\0') {
945 if (devnum < 0)
946 error("Invalid adapter index");
947
948 if (pcap_findalldevs(&devlist, ebuf) < 0)
949 error("%s", ebuf);
950 /*
951 * Look for the devnum-th entry in the
952 * list of devices (1-based).
953 */
954 for (i = 0, dev = devlist;
955 i < devnum-1 && dev != NULL;
956 i++, dev = dev->next)
957 ;
958 if (dev == NULL)
959 error("Invalid adapter index");
960 device = strdup(dev->name);
961 pcap_freealldevs(devlist);
962 break;
963 }
964 #endif /* HAVE_PCAP_FINDALLDEVS */
965 device = optarg;
966 break;
967
968 #ifdef HAVE_PCAP_CREATE
969 case 'I':
970 ++Iflag;
971 break;
972 #endif /* HAVE_PCAP_CREATE */
973
974 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
975 case 'j':
976 jflag = pcap_tstamp_type_name_to_val(optarg);
977 if (jflag < 0)
978 error("invalid time stamp type %s", optarg);
979 break;
980
981 case 'J':
982 Jflag++;
983 break;
984 #endif
985
986 case 'l':
987 #ifdef _WIN32
988 /*
989 * _IOLBF is the same as _IOFBF in Microsoft's C
990 * libraries; the only alternative they offer
991 * is _IONBF.
992 *
993 * XXX - this should really be checking for MSVC++,
994 * not _WIN32, if, for example, MinGW has its own
995 * C library that is more UNIX-compatible.
996 */
997 setvbuf(stdout, NULL, _IONBF, 0);
998 #else /* _WIN32 */
999 #ifdef HAVE_SETLINEBUF
1000 setlinebuf(stdout);
1001 #else
1002 setvbuf(stdout, NULL, _IOLBF, 0);
1003 #endif
1004 #endif /* _WIN32 */
1005 break;
1006
1007 case 'K':
1008 ++ndo->ndo_Kflag;
1009 break;
1010
1011 case 'm':
1012 #ifdef USE_LIBSMI
1013 if (smiLoadModule(optarg) == 0) {
1014 error("could not load MIB module %s", optarg);
1015 }
1016 ndo->ndo_mflag = 1;
1017 #else
1018 (void)fprintf(stderr, "%s: ignoring option `-m %s' ",
1019 program_name, optarg);
1020 (void)fprintf(stderr, "(no libsmi support)\n");
1021 #endif
1022 break;
1023
1024 case 'M':
1025 /* TCP-MD5 shared secret */
1026 #ifndef HAVE_LIBCRYPTO
1027 warning("crypto code not compiled in");
1028 #endif
1029 ndo->ndo_sigsecret = optarg;
1030 break;
1031
1032 case 'n':
1033 ++ndo->ndo_nflag;
1034 break;
1035
1036 case 'N':
1037 ++ndo->ndo_Nflag;
1038 break;
1039
1040 case 'O':
1041 Oflag = 0;
1042 break;
1043
1044 case 'p':
1045 ++pflag;
1046 break;
1047
1048 case 'q':
1049 ++ndo->ndo_qflag;
1050 ++ndo->ndo_suppress_default_print;
1051 break;
1052
1053 #ifdef HAVE_PCAP_SETDIRECTION
1054 case 'Q':
1055 if (ascii_strcasecmp(optarg, "in") == 0)
1056 Qflag = PCAP_D_IN;
1057 else if (ascii_strcasecmp(optarg, "out") == 0)
1058 Qflag = PCAP_D_OUT;
1059 else if (ascii_strcasecmp(optarg, "inout") == 0)
1060 Qflag = PCAP_D_INOUT;
1061 else
1062 error("unknown capture direction `%s'", optarg);
1063 break;
1064 #endif /* HAVE_PCAP_SETDIRECTION */
1065
1066 case 'r':
1067 RFileName = optarg;
1068 break;
1069
1070 case 's':
1071 ndo->ndo_snaplen = strtol(optarg, &end, 0);
1072 if (optarg == end || *end != '\0'
1073 || ndo->ndo_snaplen < 0 || ndo->ndo_snaplen > MAXIMUM_SNAPLEN)
1074 error("invalid snaplen %s", optarg);
1075 else if (ndo->ndo_snaplen == 0)
1076 ndo->ndo_snaplen = MAXIMUM_SNAPLEN;
1077 break;
1078
1079 case 'S':
1080 ++ndo->ndo_Sflag;
1081 break;
1082
1083 case 't':
1084 ++ndo->ndo_tflag;
1085 break;
1086
1087 case 'T':
1088 if (ascii_strcasecmp(optarg, "vat") == 0)
1089 ndo->ndo_packettype = PT_VAT;
1090 else if (ascii_strcasecmp(optarg, "wb") == 0)
1091 ndo->ndo_packettype = PT_WB;
1092 else if (ascii_strcasecmp(optarg, "rpc") == 0)
1093 ndo->ndo_packettype = PT_RPC;
1094 else if (ascii_strcasecmp(optarg, "rtp") == 0)
1095 ndo->ndo_packettype = PT_RTP;
1096 else if (ascii_strcasecmp(optarg, "rtcp") == 0)
1097 ndo->ndo_packettype = PT_RTCP;
1098 else if (ascii_strcasecmp(optarg, "snmp") == 0)
1099 ndo->ndo_packettype = PT_SNMP;
1100 else if (ascii_strcasecmp(optarg, "cnfp") == 0)
1101 ndo->ndo_packettype = PT_CNFP;
1102 else if (ascii_strcasecmp(optarg, "tftp") == 0)
1103 ndo->ndo_packettype = PT_TFTP;
1104 else if (ascii_strcasecmp(optarg, "aodv") == 0)
1105 ndo->ndo_packettype = PT_AODV;
1106 else if (ascii_strcasecmp(optarg, "carp") == 0)
1107 ndo->ndo_packettype = PT_CARP;
1108 else if (ascii_strcasecmp(optarg, "radius") == 0)
1109 ndo->ndo_packettype = PT_RADIUS;
1110 else if (ascii_strcasecmp(optarg, "zmtp1") == 0)
1111 ndo->ndo_packettype = PT_ZMTP1;
1112 else if (ascii_strcasecmp(optarg, "vxlan") == 0)
1113 ndo->ndo_packettype = PT_VXLAN;
1114 else if (ascii_strcasecmp(optarg, "pgm") == 0)
1115 ndo->ndo_packettype = PT_PGM;
1116 else if (ascii_strcasecmp(optarg, "pgm_zmtp1") == 0)
1117 ndo->ndo_packettype = PT_PGM_ZMTP1;
1118 else if (ascii_strcasecmp(optarg, "lmp") == 0)
1119 ndo->ndo_packettype = PT_LMP;
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 if (chroot_dir) {
1597 capng_update(
1598 CAPNG_ADD,
1599 CAPNG_PERMITTED | CAPNG_EFFECTIVE,
1600 CAP_SYS_CHROOT
1601 );
1602 }
1603
1604 if (WFileName) {
1605 capng_update(
1606 CAPNG_ADD,
1607 CAPNG_PERMITTED | CAPNG_EFFECTIVE,
1608 CAP_DAC_OVERRIDE
1609 );
1610 }
1611 capng_apply(CAPNG_SELECT_BOTH);
1612 #endif /* HAVE_LIBCAP_NG */
1613 if (username || chroot_dir)
1614 droproot(username, chroot_dir);
1615
1616 }
1617 #endif /* _WIN32 */
1618
1619 if (pcap_setfilter(pd, &fcode) < 0)
1620 error("%s", pcap_geterr(pd));
1621 #ifdef HAVE_CAPSICUM
1622 if (RFileName == NULL && VFileName == NULL) {
1623 static const unsigned long cmds[] = { BIOCGSTATS, BIOCROTZBUF };
1624
1625 cap_rights_init(&rights, CAP_IOCTL, CAP_READ);
1626 if (cap_rights_limit(pcap_fileno(pd), &rights) < 0 &&
1627 errno != ENOSYS) {
1628 error("unable to limit pcap descriptor");
1629 }
1630 if (cap_ioctls_limit(pcap_fileno(pd), cmds,
1631 sizeof(cmds) / sizeof(cmds[0])) < 0 && errno != ENOSYS) {
1632 error("unable to limit ioctls on pcap descriptor");
1633 }
1634 }
1635 #endif
1636 if (WFileName) {
1637 pcap_dumper_t *p;
1638 /* Do not exceed the default PATH_MAX for files. */
1639 dumpinfo.CurrentFileName = (char *)malloc(PATH_MAX + 1);
1640
1641 if (dumpinfo.CurrentFileName == NULL)
1642 error("malloc of dumpinfo.CurrentFileName");
1643
1644 /* We do not need numbering for dumpfiles if Cflag isn't set. */
1645 if (Cflag != 0)
1646 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
1647 else
1648 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
1649
1650 p = pcap_dump_open(pd, dumpinfo.CurrentFileName);
1651 #ifdef HAVE_LIBCAP_NG
1652 /* Give up CAP_DAC_OVERRIDE capability.
1653 * Only allow it to be restored if the -C or -G flag have been
1654 * set since we may need to create more files later on.
1655 */
1656 capng_update(
1657 CAPNG_DROP,
1658 (Cflag || Gflag ? 0 : CAPNG_PERMITTED)
1659 | CAPNG_EFFECTIVE,
1660 CAP_DAC_OVERRIDE
1661 );
1662 capng_apply(CAPNG_SELECT_BOTH);
1663 #endif /* HAVE_LIBCAP_NG */
1664 if (p == NULL)
1665 error("%s", pcap_geterr(pd));
1666 #ifdef HAVE_CAPSICUM
1667 set_dumper_capsicum_rights(p);
1668 #endif
1669 if (Cflag != 0 || Gflag != 0) {
1670 #ifdef HAVE_CAPSICUM
1671 dumpinfo.WFileName = strdup(basename(WFileName));
1672 if (dumpinfo.WFileName == NULL) {
1673 error("Unable to allocate memory for file %s",
1674 WFileName);
1675 }
1676 dumpinfo.dirfd = open(dirname(WFileName),
1677 O_DIRECTORY | O_RDONLY);
1678 if (dumpinfo.dirfd < 0) {
1679 error("unable to open directory %s",
1680 dirname(WFileName));
1681 }
1682 cap_rights_init(&rights, CAP_CREATE, CAP_FCNTL,
1683 CAP_FTRUNCATE, CAP_LOOKUP, CAP_SEEK, CAP_WRITE);
1684 if (cap_rights_limit(dumpinfo.dirfd, &rights) < 0 &&
1685 errno != ENOSYS) {
1686 error("unable to limit directory rights");
1687 }
1688 if (cap_fcntls_limit(dumpinfo.dirfd, CAP_FCNTL_GETFL) < 0 &&
1689 errno != ENOSYS) {
1690 error("unable to limit dump descriptor fcntls");
1691 }
1692 #else /* !HAVE_CAPSICUM */
1693 dumpinfo.WFileName = WFileName;
1694 #endif
1695 callback = dump_packet_and_trunc;
1696 dumpinfo.pd = pd;
1697 dumpinfo.p = p;
1698 pcap_userdata = (u_char *)&dumpinfo;
1699 } else {
1700 callback = dump_packet;
1701 pcap_userdata = (u_char *)p;
1702 }
1703 #ifdef HAVE_PCAP_DUMP_FLUSH
1704 if (Uflag)
1705 pcap_dump_flush(p);
1706 #endif
1707 } else {
1708 dlt = pcap_datalink(pd);
1709 ndo->ndo_if_printer = get_if_printer(ndo, dlt);
1710 callback = print_packet;
1711 pcap_userdata = (u_char *)ndo;
1712 }
1713
1714 #ifdef SIGNAL_REQ_INFO
1715 /*
1716 * We can't get statistics when reading from a file rather
1717 * than capturing from a device.
1718 */
1719 if (RFileName == NULL)
1720 (void)setsignal(SIGNAL_REQ_INFO, requestinfo);
1721 #endif
1722
1723 if (ndo->ndo_vflag > 0 && WFileName) {
1724 /*
1725 * When capturing to a file, "-v" means tcpdump should,
1726 * every 10 seconds, "v"erbosely report the number of
1727 * packets captured.
1728 */
1729 #ifdef USE_WIN32_MM_TIMER
1730 /* call verbose_stats_dump() each 1000 +/-100msec */
1731 timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
1732 setvbuf(stderr, NULL, _IONBF, 0);
1733 #elif defined(HAVE_ALARM)
1734 (void)setsignal(SIGALRM, verbose_stats_dump);
1735 alarm(1);
1736 #endif
1737 }
1738
1739 #ifndef _WIN32
1740 if (RFileName == NULL) {
1741 /*
1742 * Live capture (if -V was specified, we set RFileName
1743 * to a file from the -V file). Print a message to
1744 * the standard error on UN*X.
1745 */
1746 if (!ndo->ndo_vflag && !WFileName) {
1747 (void)fprintf(stderr,
1748 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
1749 program_name);
1750 } else
1751 (void)fprintf(stderr, "%s: ", program_name);
1752 dlt = pcap_datalink(pd);
1753 dlt_name = pcap_datalink_val_to_name(dlt);
1754 if (dlt_name == NULL) {
1755 (void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
1756 device, dlt, ndo->ndo_snaplen);
1757 } else {
1758 (void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
1759 device, dlt_name,
1760 pcap_datalink_val_to_description(dlt), ndo->ndo_snaplen);
1761 }
1762 (void)fflush(stderr);
1763 }
1764 #endif /* _WIN32 */
1765
1766 #ifdef HAVE_CAPSICUM
1767 cansandbox = (ndo->ndo_nflag && VFileName == NULL && zflag == NULL);
1768 if (cansandbox && cap_enter() < 0 && errno != ENOSYS)
1769 error("unable to enter the capability mode");
1770 #endif /* HAVE_CAPSICUM */
1771
1772 do {
1773 status = pcap_loop(pd, cnt, callback, pcap_userdata);
1774 if (WFileName == NULL) {
1775 /*
1776 * We're printing packets. Flush the printed output,
1777 * so it doesn't get intermingled with error output.
1778 */
1779 if (status == -2) {
1780 /*
1781 * We got interrupted, so perhaps we didn't
1782 * manage to finish a line we were printing.
1783 * Print an extra newline, just in case.
1784 */
1785 putchar('\n');
1786 }
1787 (void)fflush(stdout);
1788 }
1789 if (status == -2) {
1790 /*
1791 * We got interrupted. If we are reading multiple
1792 * files (via -V) set these so that we stop.
1793 */
1794 VFileName = NULL;
1795 ret = NULL;
1796 }
1797 if (status == -1) {
1798 /*
1799 * Error. Report it.
1800 */
1801 (void)fprintf(stderr, "%s: pcap_loop: %s\n",
1802 program_name, pcap_geterr(pd));
1803 }
1804 if (RFileName == NULL) {
1805 /*
1806 * We're doing a live capture. Report the capture
1807 * statistics.
1808 */
1809 info(1);
1810 }
1811 pcap_close(pd);
1812 if (VFileName != NULL) {
1813 ret = get_next_file(VFile, VFileLine);
1814 if (ret) {
1815 RFileName = VFileLine;
1816 pd = pcap_open_offline(RFileName, ebuf);
1817 if (pd == NULL)
1818 error("%s", ebuf);
1819 #ifdef HAVE_CAPSICUM
1820 cap_rights_init(&rights, CAP_READ);
1821 if (cap_rights_limit(fileno(pcap_file(pd)),
1822 &rights) < 0 && errno != ENOSYS) {
1823 error("unable to limit pcap descriptor");
1824 }
1825 #endif
1826 new_dlt = pcap_datalink(pd);
1827 if (WFileName && new_dlt != dlt)
1828 error("%s: new dlt does not match original", RFileName);
1829 ndo->ndo_if_printer = get_if_printer(ndo, new_dlt);
1830 dlt_name = pcap_datalink_val_to_name(new_dlt);
1831 if (dlt_name == NULL) {
1832 fprintf(stderr, "reading from file %s, link-type %u\n",
1833 RFileName, new_dlt);
1834 } else {
1835 fprintf(stderr,
1836 "reading from file %s, link-type %s (%s)\n",
1837 RFileName, dlt_name,
1838 pcap_datalink_val_to_description(new_dlt));
1839 }
1840 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1841 error("%s", pcap_geterr(pd));
1842 if (pcap_setfilter(pd, &fcode) < 0)
1843 error("%s", pcap_geterr(pd));
1844 }
1845 }
1846 }
1847 while (ret != NULL);
1848
1849 free(cmdbuf);
1850 pcap_freecode(&fcode);
1851 exit(status == -1 ? 1 : 0);
1852 }
1853
1854 /* make a clean exit on interrupts */
1855 static RETSIGTYPE
1856 cleanup(int signo _U_)
1857 {
1858 #ifdef USE_WIN32_MM_TIMER
1859 if (timer_id)
1860 timeKillEvent(timer_id);
1861 timer_id = 0;
1862 #elif defined(HAVE_ALARM)
1863 alarm(0);
1864 #endif
1865
1866 #ifdef HAVE_PCAP_BREAKLOOP
1867 /*
1868 * We have "pcap_breakloop()"; use it, so that we do as little
1869 * as possible in the signal handler (it's probably not safe
1870 * to do anything with standard I/O streams in a signal handler -
1871 * the ANSI C standard doesn't say it is).
1872 */
1873 pcap_breakloop(pd);
1874 #else
1875 /*
1876 * We don't have "pcap_breakloop()"; this isn't safe, but
1877 * it's the best we can do. Print the summary if we're
1878 * not reading from a savefile - i.e., if we're doing a
1879 * live capture - and exit.
1880 */
1881 if (pd != NULL && pcap_file(pd) == NULL) {
1882 /*
1883 * We got interrupted, so perhaps we didn't
1884 * manage to finish a line we were printing.
1885 * Print an extra newline, just in case.
1886 */
1887 putchar('\n');
1888 (void)fflush(stdout);
1889 info(1);
1890 }
1891 exit(0);
1892 #endif
1893 }
1894
1895 /*
1896 On windows, we do not use a fork, so we do not care less about
1897 waiting a child processes to die
1898 */
1899 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1900 static RETSIGTYPE
1901 child_cleanup(int signo _U_)
1902 {
1903 wait(NULL);
1904 }
1905 #endif /* HAVE_FORK && HAVE_VFORK */
1906
1907 static void
1908 info(register int verbose)
1909 {
1910 struct pcap_stat stats;
1911
1912 /*
1913 * Older versions of libpcap didn't set ps_ifdrop on some
1914 * platforms; initialize it to 0 to handle that.
1915 */
1916 stats.ps_ifdrop = 0;
1917 if (pcap_stats(pd, &stats) < 0) {
1918 (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
1919 infoprint = 0;
1920 return;
1921 }
1922
1923 if (!verbose)
1924 fprintf(stderr, "%s: ", program_name);
1925
1926 (void)fprintf(stderr, "%u packet%s captured", packets_captured,
1927 PLURAL_SUFFIX(packets_captured));
1928 if (!verbose)
1929 fputs(", ", stderr);
1930 else
1931 putc('\n', stderr);
1932 (void)fprintf(stderr, "%u packet%s received by filter", stats.ps_recv,
1933 PLURAL_SUFFIX(stats.ps_recv));
1934 if (!verbose)
1935 fputs(", ", stderr);
1936 else
1937 putc('\n', stderr);
1938 (void)fprintf(stderr, "%u packet%s dropped by kernel", stats.ps_drop,
1939 PLURAL_SUFFIX(stats.ps_drop));
1940 if (stats.ps_ifdrop != 0) {
1941 if (!verbose)
1942 fputs(", ", stderr);
1943 else
1944 putc('\n', stderr);
1945 (void)fprintf(stderr, "%u packet%s dropped by interface\n",
1946 stats.ps_ifdrop, PLURAL_SUFFIX(stats.ps_ifdrop));
1947 } else
1948 putc('\n', stderr);
1949 infoprint = 0;
1950 }
1951
1952 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1953 #ifdef HAVE_FORK
1954 #define fork_subprocess() fork()
1955 #else
1956 #define fork_subprocess() vfork()
1957 #endif
1958 static void
1959 compress_savefile(const char *filename)
1960 {
1961 pid_t child;
1962
1963 child = fork_subprocess();
1964 if (child == -1) {
1965 fprintf(stderr,
1966 "compress_savefile: fork failed: %s\n",
1967 pcap_strerror(errno));
1968 return;
1969 }
1970 if (child != 0) {
1971 /* Parent process. */
1972 return;
1973 }
1974
1975 /*
1976 * Child process.
1977 * Set to lowest priority so that this doesn't disturb the capture.
1978 */
1979 #ifdef NZERO
1980 setpriority(PRIO_PROCESS, 0, NZERO - 1);
1981 #else
1982 setpriority(PRIO_PROCESS, 0, 19);
1983 #endif
1984 if (execlp(zflag, zflag, filename, (char *)NULL) == -1)
1985 fprintf(stderr,
1986 "compress_savefile: execlp(%s, %s) failed: %s\n",
1987 zflag,
1988 filename,
1989 pcap_strerror(errno));
1990 #ifdef HAVE_FORK
1991 exit(1);
1992 #else
1993 _exit(1);
1994 #endif
1995 }
1996 #else /* HAVE_FORK && HAVE_VFORK */
1997 static void
1998 compress_savefile(const char *filename)
1999 {
2000 fprintf(stderr,
2001 "compress_savefile failed. Functionality not implemented under your system\n");
2002 }
2003 #endif /* HAVE_FORK && HAVE_VFORK */
2004
2005 static void
2006 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2007 {
2008 struct dump_info *dump_info;
2009
2010 ++packets_captured;
2011
2012 ++infodelay;
2013
2014 dump_info = (struct dump_info *)user;
2015
2016 /*
2017 * XXX - this won't force the file to rotate on the specified time
2018 * boundary, but it will rotate on the first packet received after the
2019 * specified Gflag number of seconds. Note: if a Gflag time boundary
2020 * and a Cflag size boundary coincide, the time rotation will occur
2021 * first thereby cancelling the Cflag boundary (since the file should
2022 * be 0).
2023 */
2024 if (Gflag != 0) {
2025 /* Check if it is time to rotate */
2026 time_t t;
2027
2028 /* Get the current time */
2029 if ((t = time(NULL)) == (time_t)-1) {
2030 error("dump_and_trunc_packet: can't get current_time: %s",
2031 pcap_strerror(errno));
2032 }
2033
2034
2035 /* If the time is greater than the specified window, rotate */
2036 if (t - Gflag_time >= Gflag) {
2037 #ifdef HAVE_CAPSICUM
2038 FILE *fp;
2039 int fd;
2040 #endif
2041
2042 /* Update the Gflag_time */
2043 Gflag_time = t;
2044 /* Update Gflag_count */
2045 Gflag_count++;
2046 /*
2047 * Close the current file and open a new one.
2048 */
2049 pcap_dump_close(dump_info->p);
2050
2051 /*
2052 * Compress the file we just closed, if the user asked for it
2053 */
2054 if (zflag != NULL)
2055 compress_savefile(dump_info->CurrentFileName);
2056
2057 /*
2058 * Check to see if we've exceeded the Wflag (when
2059 * not using Cflag).
2060 */
2061 if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
2062 (void)fprintf(stderr, "Maximum file limit reached: %d\n",
2063 Wflag);
2064 exit(0);
2065 /* NOTREACHED */
2066 }
2067 if (dump_info->CurrentFileName != NULL)
2068 free(dump_info->CurrentFileName);
2069 /* Allocate space for max filename + \0. */
2070 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2071 if (dump_info->CurrentFileName == NULL)
2072 error("dump_packet_and_trunc: malloc");
2073 /*
2074 * Gflag was set otherwise we wouldn't be here. Reset the count
2075 * so multiple files would end with 1,2,3 in the filename.
2076 * The counting is handled with the -C flow after this.
2077 */
2078 Cflag_count = 0;
2079
2080 /*
2081 * This is always the first file in the Cflag
2082 * rotation: e.g. 0
2083 * We also don't need numbering if Cflag is not set.
2084 */
2085 if (Cflag != 0)
2086 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
2087 WflagChars);
2088 else
2089 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
2090
2091 #ifdef HAVE_LIBCAP_NG
2092 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2093 capng_apply(CAPNG_SELECT_BOTH);
2094 #endif /* HAVE_LIBCAP_NG */
2095 #ifdef HAVE_CAPSICUM
2096 fd = openat(dump_info->dirfd,
2097 dump_info->CurrentFileName,
2098 O_CREAT | O_WRONLY | O_TRUNC, 0644);
2099 if (fd < 0) {
2100 error("unable to open file %s",
2101 dump_info->CurrentFileName);
2102 }
2103 fp = fdopen(fd, "w");
2104 if (fp == NULL) {
2105 error("unable to fdopen file %s",
2106 dump_info->CurrentFileName);
2107 }
2108 dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2109 #else /* !HAVE_CAPSICUM */
2110 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2111 #endif
2112 #ifdef HAVE_LIBCAP_NG
2113 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2114 capng_apply(CAPNG_SELECT_BOTH);
2115 #endif /* HAVE_LIBCAP_NG */
2116 if (dump_info->p == NULL)
2117 error("%s", pcap_geterr(pd));
2118 #ifdef HAVE_CAPSICUM
2119 set_dumper_capsicum_rights(dump_info->p);
2120 #endif
2121 }
2122 }
2123
2124 /*
2125 * XXX - this won't prevent capture files from getting
2126 * larger than Cflag - the last packet written to the
2127 * file could put it over Cflag.
2128 */
2129 if (Cflag != 0) {
2130 long size = pcap_dump_ftell(dump_info->p);
2131
2132 if (size == -1)
2133 error("ftell fails on output file");
2134 if (size > Cflag) {
2135 #ifdef HAVE_CAPSICUM
2136 FILE *fp;
2137 int fd;
2138 #endif
2139
2140 /*
2141 * Close the current file and open a new one.
2142 */
2143 pcap_dump_close(dump_info->p);
2144
2145 /*
2146 * Compress the file we just closed, if the user
2147 * asked for it.
2148 */
2149 if (zflag != NULL)
2150 compress_savefile(dump_info->CurrentFileName);
2151
2152 Cflag_count++;
2153 if (Wflag > 0) {
2154 if (Cflag_count >= Wflag)
2155 Cflag_count = 0;
2156 }
2157 if (dump_info->CurrentFileName != NULL)
2158 free(dump_info->CurrentFileName);
2159 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2160 if (dump_info->CurrentFileName == NULL)
2161 error("dump_packet_and_trunc: malloc");
2162 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
2163 #ifdef HAVE_LIBCAP_NG
2164 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2165 capng_apply(CAPNG_SELECT_BOTH);
2166 #endif /* HAVE_LIBCAP_NG */
2167 #ifdef HAVE_CAPSICUM
2168 fd = openat(dump_info->dirfd, dump_info->CurrentFileName,
2169 O_CREAT | O_WRONLY | O_TRUNC, 0644);
2170 if (fd < 0) {
2171 error("unable to open file %s",
2172 dump_info->CurrentFileName);
2173 }
2174 fp = fdopen(fd, "w");
2175 if (fp == NULL) {
2176 error("unable to fdopen file %s",
2177 dump_info->CurrentFileName);
2178 }
2179 dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2180 #else /* !HAVE_CAPSICUM */
2181 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2182 #endif
2183 #ifdef HAVE_LIBCAP_NG
2184 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2185 capng_apply(CAPNG_SELECT_BOTH);
2186 #endif /* HAVE_LIBCAP_NG */
2187 if (dump_info->p == NULL)
2188 error("%s", pcap_geterr(pd));
2189 #ifdef HAVE_CAPSICUM
2190 set_dumper_capsicum_rights(dump_info->p);
2191 #endif
2192 }
2193 }
2194
2195 pcap_dump((u_char *)dump_info->p, h, sp);
2196 #ifdef HAVE_PCAP_DUMP_FLUSH
2197 if (Uflag)
2198 pcap_dump_flush(dump_info->p);
2199 #endif
2200
2201 --infodelay;
2202 if (infoprint)
2203 info(0);
2204 }
2205
2206 static void
2207 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2208 {
2209 ++packets_captured;
2210
2211 ++infodelay;
2212
2213 pcap_dump(user, h, sp);
2214 #ifdef HAVE_PCAP_DUMP_FLUSH
2215 if (Uflag)
2216 pcap_dump_flush((pcap_dumper_t *)user);
2217 #endif
2218
2219 --infodelay;
2220 if (infoprint)
2221 info(0);
2222 }
2223
2224 static void
2225 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2226 {
2227 ++packets_captured;
2228
2229 ++infodelay;
2230
2231 pretty_print_packet((netdissect_options *)user, h, sp, packets_captured);
2232
2233 --infodelay;
2234 if (infoprint)
2235 info(0);
2236 }
2237
2238 #ifdef _WIN32
2239 /*
2240 * XXX - there should really be libpcap calls to get the version
2241 * number as a string (the string would be generated from #defines
2242 * at run time, so that it's not generated from string constants
2243 * in the library, as, on many UNIX systems, those constants would
2244 * be statically linked into the application executable image, and
2245 * would thus reflect the version of libpcap on the system on
2246 * which the application was *linked*, not the system on which it's
2247 * *running*.
2248 *
2249 * That routine should be documented, unlike the "version[]"
2250 * string, so that UNIX vendors providing their own libpcaps
2251 * don't omit it (as a couple of vendors have...).
2252 *
2253 * Packet.dll should perhaps also export a routine to return the
2254 * version number of the Packet.dll code, to supply the
2255 * "Wpcap_version" information on Windows.
2256 */
2257 char WDversion[]="current-git.tcpdump.org";
2258 #if !defined(HAVE_GENERATED_VERSION)
2259 char version[]="current-git.tcpdump.org";
2260 #endif
2261 char pcap_version[]="current-git.tcpdump.org";
2262 char Wpcap_version[]="3.1";
2263 #endif
2264
2265 #ifdef SIGNAL_REQ_INFO
2266 RETSIGTYPE requestinfo(int signo _U_)
2267 {
2268 if (infodelay)
2269 ++infoprint;
2270 else
2271 info(0);
2272 }
2273 #endif
2274
2275 /*
2276 * Called once each second in verbose mode while dumping to file
2277 */
2278 #ifdef USE_WIN32_MM_TIMER
2279 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
2280 DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
2281 {
2282 if (infodelay == 0)
2283 fprintf(stderr, "Got %u\r", packets_captured);
2284 }
2285 #elif defined(HAVE_ALARM)
2286 static void verbose_stats_dump(int sig _U_)
2287 {
2288 if (infodelay == 0)
2289 fprintf(stderr, "Got %u\r", packets_captured);
2290 alarm(1);
2291 }
2292 #endif
2293
2294 USES_APPLE_DEPRECATED_API
2295 static void
2296 print_version(void)
2297 {
2298 extern char version[];
2299 #ifndef HAVE_PCAP_LIB_VERSION
2300 #if defined(_WIN32) || defined(HAVE_PCAP_VERSION)
2301 extern char pcap_version[];
2302 #else /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2303 static char pcap_version[] = "unknown";
2304 #endif /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2305 #endif /* HAVE_PCAP_LIB_VERSION */
2306
2307 #ifdef HAVE_PCAP_LIB_VERSION
2308 #ifdef _WIN32
2309 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2310 #else /* _WIN32 */
2311 (void)fprintf(stderr, "%s version %s\n", program_name, version);
2312 #endif /* _WIN32 */
2313 (void)fprintf(stderr, "%s\n",pcap_lib_version());
2314 #else /* HAVE_PCAP_LIB_VERSION */
2315 #ifdef _WIN32
2316 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2317 (void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
2318 #else /* _WIN32 */
2319 (void)fprintf(stderr, "%s version %s\n", program_name, version);
2320 (void)fprintf(stderr, "libpcap version %s\n", pcap_version);
2321 #endif /* _WIN32 */
2322 #endif /* HAVE_PCAP_LIB_VERSION */
2323
2324 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
2325 (void)fprintf (stderr, "%s\n", SSLeay_version(SSLEAY_VERSION));
2326 #endif
2327
2328 #ifdef USE_LIBSMI
2329 (void)fprintf (stderr, "SMI-library: %s\n", smi_version_string);
2330 #endif
2331 }
2332 USES_APPLE_RST
2333
2334 static void
2335 print_usage(void)
2336 {
2337 print_version();
2338 (void)fprintf(stderr,
2339 "Usage: %s [-aAbd" D_FLAG "efhH" I_FLAG J_FLAG "KlLnNOpqStu" U_FLAG "vxX#]" B_FLAG_USAGE " [ -c count ]\n", program_name);
2340 (void)fprintf(stderr,
2341 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
2342 (void)fprintf(stderr,
2343 "\t\t[ -i interface ]" j_FLAG_USAGE " [ -M secret ] [ --number ]\n");
2344 #ifdef HAVE_PCAP_SETDIRECTION
2345 (void)fprintf(stderr,
2346 "\t\t[ -Q in|out|inout ]\n");
2347 #endif
2348 (void)fprintf(stderr,
2349 "\t\t[ -r file ] [ -s snaplen ] ");
2350 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2351 (void)fprintf(stderr, "[ --time-stamp-precision precision ]\n");
2352 (void)fprintf(stderr,
2353 "\t\t");
2354 #endif
2355 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
2356 (void)fprintf(stderr, "[ --immediate-mode ] ");
2357 #endif
2358 (void)fprintf(stderr, "[ -T type ] [ --version ] [ -V file ]\n");
2359 (void)fprintf(stderr,
2360 "\t\t[ -w file ] [ -W filecount ] [ -y datalinktype ] [ -z command ]\n");
2361 (void)fprintf(stderr,
2362 "\t\t[ -Z user ] [ expression ]\n");
2363 }
2364 /*
2365 * Local Variables:
2366 * c-style: whitesmith
2367 * c-basic-offset: 8
2368 * End:
2369 */