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 static const char rcsid[] _U_ =
33 "@(#) $Header: /tcpdump/master/tcpdump/tcpdump.c,v 1.283 2008-09-25 21:45:50 guy Exp $ (LBL)";
34 #endif
35
36 /* $FreeBSD: stable/10/contrib/tcpdump/tcpdump.c 314560 2017-03-02 17:17:06Z emaste $ */
37
38 /*
39 * tcpdump - monitor tcp/ip traffic on an ethernet.
40 *
41 * First written in 1987 by Van Jacobson, Lawrence Berkeley Laboratory.
42 * Mercilessly hacked and occasionally improved since then via the
43 * combined efforts of Van, Steve McCanne and Craig Leres of LBL.
44 */
45
46 #ifdef HAVE_CONFIG_H
47 #include "config.h"
48 #endif
49
50 #include <tcpdump-stdinc.h>
51
52 #ifdef WIN32
53 #include "getopt.h"
54 #include "w32_fzs.h"
55 extern int strcasecmp (const char *__s1, const char *__s2);
56 extern int SIZE_BUF;
57 #define off_t long
58 #define uint UINT
59 #endif /* WIN32 */
60
61 #ifdef HAVE_SMI_H
62 #include <smi.h>
63 #endif
64
65 #include <pcap.h>
66 #include <signal.h>
67 #include <stdio.h>
68 #include <stdlib.h>
69 #include <string.h>
70 #include <limits.h>
71 #ifdef __FreeBSD__
72 #include <sys/capsicum.h>
73 #include <sys/ioccom.h>
74 #include <sys/types.h>
75 #include <sys/sysctl.h>
76 #include <net/bpf.h>
77 #include <fcntl.h>
78 #include <libgen.h>
79 #endif /* __FreeBSD__ */
80 #ifndef WIN32
81 #include <sys/wait.h>
82 #include <sys/resource.h>
83 #include <pwd.h>
84 #include <grp.h>
85 #include <errno.h>
86 #endif /* WIN32 */
87
88 /* capabilities convinience library */
89 #ifdef HAVE_CAP_NG_H
90 #include <cap-ng.h>
91 #endif /* HAVE_CAP_NG_H */
92
93 #include "netdissect.h"
94 #include "interface.h"
95 #include "addrtoname.h"
96 #include "machdep.h"
97 #include "setsignal.h"
98 #include "gmt2local.h"
99 #include "pcap-missing.h"
100
101 #ifndef PATH_MAX
102 #define PATH_MAX 1024
103 #endif
104
105 #ifdef SIGINFO
106 #define SIGNAL_REQ_INFO SIGINFO
107 #elif SIGUSR1
108 #define SIGNAL_REQ_INFO SIGUSR1
109 #endif
110
111 netdissect_options Gndo;
112 netdissect_options *gndo = &Gndo;
113
114 static int dflag; /* print filter code */
115 static int Lflag; /* list available data link types and exit */
116 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
117 static int Jflag; /* list available time stamp types */
118 #endif
119 static char *zflag = NULL; /* compress each savefile using a specified command (like gzip or bzip2) */
120
121 static int infodelay;
122 static int infoprint;
123
124 char *program_name;
125
126 int32_t thiszone; /* seconds offset from gmt to local time */
127
128 /* Forwards */
129 static RETSIGTYPE cleanup(int);
130 static RETSIGTYPE child_cleanup(int);
131 static void usage(void) __attribute__((noreturn));
132 static void show_dlts_and_exit(const char *device, pcap_t *pd) __attribute__((noreturn));
133
134 static void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
135 static void ndo_default_print(netdissect_options *, const u_char *, u_int);
136 static void dump_packet_and_trunc(u_char *, const struct pcap_pkthdr *, const u_char *);
137 static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
138 static void droproot(const char *, const char *);
139 static void ndo_error(netdissect_options *ndo, const char *fmt, ...)
140 __attribute__ ((noreturn, format (printf, 2, 3)));
141 static void ndo_warning(netdissect_options *ndo, const char *fmt, ...);
142
143 #ifdef SIGNAL_REQ_INFO
144 RETSIGTYPE requestinfo(int);
145 #endif
146
147 #if defined(USE_WIN32_MM_TIMER)
148 #include <MMsystem.h>
149 static UINT timer_id;
150 static void CALLBACK verbose_stats_dump(UINT, UINT, DWORD_PTR, DWORD_PTR, DWORD_PTR);
151 #elif defined(HAVE_ALARM)
152 static void verbose_stats_dump(int sig);
153 #endif
154
155 static void info(int);
156 static u_int packets_captured;
157
158 struct printer {
159 if_printer f;
160 int type;
161 };
162
163
164 struct ndo_printer {
165 if_ndo_printer f;
166 int type;
167 };
168
169
170 static struct printer printers[] = {
171 { arcnet_if_print, DLT_ARCNET },
172 #ifdef DLT_ARCNET_LINUX
173 { arcnet_linux_if_print, DLT_ARCNET_LINUX },
174 #endif
175 { token_if_print, DLT_IEEE802 },
176 #ifdef DLT_LANE8023
177 { lane_if_print, DLT_LANE8023 },
178 #endif
179 #ifdef DLT_CIP
180 { cip_if_print, DLT_CIP },
181 #endif
182 #ifdef DLT_ATM_CLIP
183 { cip_if_print, DLT_ATM_CLIP },
184 #endif
185 { sl_if_print, DLT_SLIP },
186 #ifdef DLT_SLIP_BSDOS
187 { sl_bsdos_if_print, DLT_SLIP_BSDOS },
188 #endif
189 { ppp_if_print, DLT_PPP },
190 #ifdef DLT_PPP_WITHDIRECTION
191 { ppp_if_print, DLT_PPP_WITHDIRECTION },
192 #endif
193 #ifdef DLT_PPP_BSDOS
194 { ppp_bsdos_if_print, DLT_PPP_BSDOS },
195 #endif
196 { fddi_if_print, DLT_FDDI },
197 { null_if_print, DLT_NULL },
198 #ifdef DLT_LOOP
199 { null_if_print, DLT_LOOP },
200 #endif
201 { raw_if_print, DLT_RAW },
202 { atm_if_print, DLT_ATM_RFC1483 },
203 #ifdef DLT_C_HDLC
204 { chdlc_if_print, DLT_C_HDLC },
205 #endif
206 #ifdef DLT_HDLC
207 { chdlc_if_print, DLT_HDLC },
208 #endif
209 #ifdef DLT_PPP_SERIAL
210 { ppp_hdlc_if_print, DLT_PPP_SERIAL },
211 #endif
212 #ifdef DLT_PPP_ETHER
213 { pppoe_if_print, DLT_PPP_ETHER },
214 #endif
215 #ifdef DLT_LINUX_SLL
216 { sll_if_print, DLT_LINUX_SLL },
217 #endif
218 #ifdef DLT_IEEE802_11
219 { ieee802_11_if_print, DLT_IEEE802_11},
220 #endif
221 #ifdef DLT_LTALK
222 { ltalk_if_print, DLT_LTALK },
223 #endif
224 #if defined(DLT_PFLOG) && defined(HAVE_NET_PFVAR_H)
225 { pflog_if_print, DLT_PFLOG },
226 #endif
227 #ifdef DLT_FR
228 { fr_if_print, DLT_FR },
229 #endif
230 #ifdef DLT_FRELAY
231 { fr_if_print, DLT_FRELAY },
232 #endif
233 #ifdef DLT_SUNATM
234 { sunatm_if_print, DLT_SUNATM },
235 #endif
236 #ifdef DLT_IP_OVER_FC
237 { ipfc_if_print, DLT_IP_OVER_FC },
238 #endif
239 #ifdef DLT_PRISM_HEADER
240 { prism_if_print, DLT_PRISM_HEADER },
241 #endif
242 #ifdef DLT_IEEE802_11_RADIO
243 { ieee802_11_radio_if_print, DLT_IEEE802_11_RADIO },
244 #endif
245 #ifdef DLT_ENC
246 { enc_if_print, DLT_ENC },
247 #endif
248 #ifdef DLT_SYMANTEC_FIREWALL
249 { symantec_if_print, DLT_SYMANTEC_FIREWALL },
250 #endif
251 #ifdef DLT_APPLE_IP_OVER_IEEE1394
252 { ap1394_if_print, DLT_APPLE_IP_OVER_IEEE1394 },
253 #endif
254 #ifdef DLT_IEEE802_11_RADIO_AVS
255 { ieee802_11_radio_avs_if_print, DLT_IEEE802_11_RADIO_AVS },
256 #endif
257 #ifdef DLT_JUNIPER_ATM1
258 { juniper_atm1_print, DLT_JUNIPER_ATM1 },
259 #endif
260 #ifdef DLT_JUNIPER_ATM2
261 { juniper_atm2_print, DLT_JUNIPER_ATM2 },
262 #endif
263 #ifdef DLT_JUNIPER_MFR
264 { juniper_mfr_print, DLT_JUNIPER_MFR },
265 #endif
266 #ifdef DLT_JUNIPER_MLFR
267 { juniper_mlfr_print, DLT_JUNIPER_MLFR },
268 #endif
269 #ifdef DLT_JUNIPER_MLPPP
270 { juniper_mlppp_print, DLT_JUNIPER_MLPPP },
271 #endif
272 #ifdef DLT_JUNIPER_PPPOE
273 { juniper_pppoe_print, DLT_JUNIPER_PPPOE },
274 #endif
275 #ifdef DLT_JUNIPER_PPPOE_ATM
276 { juniper_pppoe_atm_print, DLT_JUNIPER_PPPOE_ATM },
277 #endif
278 #ifdef DLT_JUNIPER_GGSN
279 { juniper_ggsn_print, DLT_JUNIPER_GGSN },
280 #endif
281 #ifdef DLT_JUNIPER_ES
282 { juniper_es_print, DLT_JUNIPER_ES },
283 #endif
284 #ifdef DLT_JUNIPER_MONITOR
285 { juniper_monitor_print, DLT_JUNIPER_MONITOR },
286 #endif
287 #ifdef DLT_JUNIPER_SERVICES
288 { juniper_services_print, DLT_JUNIPER_SERVICES },
289 #endif
290 #ifdef DLT_JUNIPER_ETHER
291 { juniper_ether_print, DLT_JUNIPER_ETHER },
292 #endif
293 #ifdef DLT_JUNIPER_PPP
294 { juniper_ppp_print, DLT_JUNIPER_PPP },
295 #endif
296 #ifdef DLT_JUNIPER_FRELAY
297 { juniper_frelay_print, DLT_JUNIPER_FRELAY },
298 #endif
299 #ifdef DLT_JUNIPER_CHDLC
300 { juniper_chdlc_print, DLT_JUNIPER_CHDLC },
301 #endif
302 #ifdef DLT_MFR
303 { mfr_if_print, DLT_MFR },
304 #endif
305 #if defined(DLT_BLUETOOTH_HCI_H4_WITH_PHDR) && defined(HAVE_PCAP_BLUETOOTH_H)
306 { bt_if_print, DLT_BLUETOOTH_HCI_H4_WITH_PHDR},
307 #endif
308 #ifdef HAVE_PCAP_USB_H
309 #ifdef DLT_USB_LINUX
310 { usb_linux_48_byte_print, DLT_USB_LINUX},
311 #endif /* DLT_USB_LINUX */
312 #ifdef DLT_USB_LINUX_MMAPPED
313 { usb_linux_64_byte_print, DLT_USB_LINUX_MMAPPED},
314 #endif /* DLT_USB_LINUX_MMAPPED */
315 #endif /* HAVE_PCAP_USB_H */
316 #ifdef DLT_IPV4
317 { raw_if_print, DLT_IPV4 },
318 #endif
319 #ifdef DLT_IPV6
320 { raw_if_print, DLT_IPV6 },
321 #endif
322 { NULL, 0 },
323 };
324
325 static struct ndo_printer ndo_printers[] = {
326 { ether_if_print, DLT_EN10MB },
327 #ifdef DLT_IPNET
328 { ipnet_if_print, DLT_IPNET },
329 #endif
330 #ifdef DLT_IEEE802_15_4
331 { ieee802_15_4_if_print, DLT_IEEE802_15_4 },
332 #endif
333 #ifdef DLT_IEEE802_15_4_NOFCS
334 { ieee802_15_4_if_print, DLT_IEEE802_15_4_NOFCS },
335 #endif
336 #ifdef DLT_PPI
337 { ppi_if_print, DLT_PPI },
338 #endif
339 #ifdef DLT_NETANALYZER
340 { netanalyzer_if_print, DLT_NETANALYZER },
341 #endif
342 #ifdef DLT_NETANALYZER_TRANSPARENT
343 { netanalyzer_transparent_if_print, DLT_NETANALYZER_TRANSPARENT },
344 #endif
345 { NULL, 0 },
346 };
347
348 if_printer
lookup_printer(int type)349 lookup_printer(int type)
350 {
351 struct printer *p;
352
353 for (p = printers; p->f; ++p)
354 if (type == p->type)
355 return p->f;
356
357 return NULL;
358 /* NOTREACHED */
359 }
360
361 if_ndo_printer
lookup_ndo_printer(int type)362 lookup_ndo_printer(int type)
363 {
364 struct ndo_printer *p;
365
366 for (p = ndo_printers; p->f; ++p)
367 if (type == p->type)
368 return p->f;
369
370 return NULL;
371 /* NOTREACHED */
372 }
373
374 static pcap_t *pd;
375
376 static int supports_monitor_mode;
377
378 extern int optind;
379 extern int opterr;
380 extern char *optarg;
381
382 struct print_info {
383 netdissect_options *ndo;
384 union {
385 if_printer printer;
386 if_ndo_printer ndo_printer;
387 } p;
388 int ndo_type;
389 };
390
391 struct dump_info {
392 char *WFileName;
393 char *CurrentFileName;
394 pcap_t *pd;
395 pcap_dumper_t *p;
396 #ifdef __FreeBSD__
397 int dirfd;
398 #endif
399 };
400
401 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
402 static void
show_tstamp_types_and_exit(const char * device,pcap_t * pd)403 show_tstamp_types_and_exit(const char *device, pcap_t *pd)
404 {
405 int n_tstamp_types;
406 int *tstamp_types = 0;
407 const char *tstamp_type_name;
408 int i;
409
410 n_tstamp_types = pcap_list_tstamp_types(pd, &tstamp_types);
411 if (n_tstamp_types < 0)
412 error("%s", pcap_geterr(pd));
413
414 if (n_tstamp_types == 0) {
415 fprintf(stderr, "Time stamp type cannot be set for %s\n",
416 device);
417 exit(0);
418 }
419 fprintf(stderr, "Time stamp types for %s (use option -j to set):\n",
420 device);
421 for (i = 0; i < n_tstamp_types; i++) {
422 tstamp_type_name = pcap_tstamp_type_val_to_name(tstamp_types[i]);
423 if (tstamp_type_name != NULL) {
424 (void) fprintf(stderr, " %s (%s)\n", tstamp_type_name,
425 pcap_tstamp_type_val_to_description(tstamp_types[i]));
426 } else {
427 (void) fprintf(stderr, " %d\n", tstamp_types[i]);
428 }
429 }
430 pcap_free_tstamp_types(tstamp_types);
431 exit(0);
432 }
433 #endif
434
435 static void
show_dlts_and_exit(const char * device,pcap_t * pd)436 show_dlts_and_exit(const char *device, pcap_t *pd)
437 {
438 int n_dlts;
439 int *dlts = 0;
440 const char *dlt_name;
441
442 n_dlts = pcap_list_datalinks(pd, &dlts);
443 if (n_dlts < 0)
444 error("%s", pcap_geterr(pd));
445 else if (n_dlts == 0 || !dlts)
446 error("No data link types.");
447
448 /*
449 * If the interface is known to support monitor mode, indicate
450 * whether these are the data link types available when not in
451 * monitor mode, if -I wasn't specified, or when in monitor mode,
452 * when -I was specified (the link-layer types available in
453 * monitor mode might be different from the ones available when
454 * not in monitor mode).
455 */
456 if (supports_monitor_mode)
457 (void) fprintf(stderr, "Data link types for %s %s (use option -y to set):\n",
458 device,
459 Iflag ? "when in monitor mode" : "when not in monitor mode");
460 else
461 (void) fprintf(stderr, "Data link types for %s (use option -y to set):\n",
462 device);
463
464 while (--n_dlts >= 0) {
465 dlt_name = pcap_datalink_val_to_name(dlts[n_dlts]);
466 if (dlt_name != NULL) {
467 (void) fprintf(stderr, " %s (%s)", dlt_name,
468 pcap_datalink_val_to_description(dlts[n_dlts]));
469
470 /*
471 * OK, does tcpdump handle that type?
472 */
473 if (lookup_printer(dlts[n_dlts]) == NULL
474 && lookup_ndo_printer(dlts[n_dlts]) == NULL)
475 (void) fprintf(stderr, " (printing not supported)");
476 fprintf(stderr, "\n");
477 } else {
478 (void) fprintf(stderr, " DLT %d (printing not supported)\n",
479 dlts[n_dlts]);
480 }
481 }
482 #ifdef HAVE_PCAP_FREE_DATALINKS
483 pcap_free_datalinks(dlts);
484 #endif
485 exit(0);
486 }
487
488 /*
489 * Set up flags that might or might not be supported depending on the
490 * version of libpcap we're using.
491 */
492 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
493 #define B_FLAG "B:"
494 #define B_FLAG_USAGE " [ -B size ]"
495 #else /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
496 #define B_FLAG
497 #define B_FLAG_USAGE
498 #endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
499
500 #ifdef HAVE_PCAP_CREATE
501 #define I_FLAG "I"
502 #else /* HAVE_PCAP_CREATE */
503 #define I_FLAG
504 #endif /* HAVE_PCAP_CREATE */
505
506 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
507 #define j_FLAG "j:"
508 #define j_FLAG_USAGE " [ -j tstamptype ]"
509 #define J_FLAG "J"
510 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
511 #define j_FLAG
512 #define j_FLAG_USAGE
513 #define J_FLAG
514 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
515
516 #ifdef HAVE_PCAP_FINDALLDEVS
517 #ifndef HAVE_PCAP_IF_T
518 #undef HAVE_PCAP_FINDALLDEVS
519 #endif
520 #endif
521
522 #ifdef HAVE_PCAP_FINDALLDEVS
523 #define D_FLAG "D"
524 #else
525 #define D_FLAG
526 #endif
527
528 #ifdef HAVE_PCAP_DUMP_FLUSH
529 #define U_FLAG "U"
530 #else
531 #define U_FLAG
532 #endif
533
534 #ifndef WIN32
535 /* Drop root privileges and chroot if necessary */
536 static void
droproot(const char * username,const char * chroot_dir)537 droproot(const char *username, const char *chroot_dir)
538 {
539 struct passwd *pw = NULL;
540
541 if (chroot_dir && !username) {
542 fprintf(stderr, "tcpdump: Chroot without dropping root is insecure\n");
543 exit(1);
544 }
545
546 pw = getpwnam(username);
547 if (pw) {
548 if (chroot_dir) {
549 if (chroot(chroot_dir) != 0 || chdir ("/") != 0) {
550 fprintf(stderr, "tcpdump: Couldn't chroot/chdir to '%.64s': %s\n",
551 chroot_dir, pcap_strerror(errno));
552 exit(1);
553 }
554 }
555 #ifdef HAVE_CAP_NG_H
556 int ret = capng_change_id(pw->pw_uid, pw->pw_gid, CAPNG_NO_FLAG);
557 if (ret < 0) {
558 printf("error : ret %d\n", ret);
559 }
560 /* We don't need CAP_SETUID and CAP_SETGID */
561 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_SETUID);
562 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_SETUID);
563 capng_update(CAPNG_DROP, CAPNG_PERMITTED, CAP_SETUID);
564 capng_update(CAPNG_DROP, CAPNG_PERMITTED, CAP_SETUID);
565 capng_apply(CAPNG_SELECT_BOTH);
566
567 #else
568 if (initgroups(pw->pw_name, pw->pw_gid) != 0 ||
569 setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0) {
570 fprintf(stderr, "tcpdump: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
571 username,
572 (unsigned long)pw->pw_uid,
573 (unsigned long)pw->pw_gid,
574 pcap_strerror(errno));
575 exit(1);
576 }
577 #endif /* HAVE_CAP_NG_H */
578 }
579 else {
580 fprintf(stderr, "tcpdump: Couldn't find user '%.32s'\n",
581 username);
582 exit(1);
583 }
584 }
585 #endif /* WIN32 */
586
587 static int
getWflagChars(int x)588 getWflagChars(int x)
589 {
590 int c = 0;
591
592 x -= 1;
593 while (x > 0) {
594 c += 1;
595 x /= 10;
596 }
597
598 return c;
599 }
600
601
602 static void
MakeFilename(char * buffer,char * orig_name,int cnt,int max_chars)603 MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
604 {
605 char *filename = malloc(PATH_MAX + 1);
606 if (filename == NULL)
607 error("Makefilename: malloc");
608
609 /* Process with strftime if Gflag is set. */
610 if (Gflag != 0) {
611 struct tm *local_tm;
612
613 /* Convert Gflag_time to a usable format */
614 if ((local_tm = localtime(&Gflag_time)) == NULL) {
615 error("MakeTimedFilename: localtime");
616 }
617
618 /* There's no good way to detect an error in strftime since a return
619 * value of 0 isn't necessarily failure.
620 */
621 strftime(filename, PATH_MAX, orig_name, local_tm);
622 } else {
623 strncpy(filename, orig_name, PATH_MAX);
624 }
625
626 if (cnt == 0 && max_chars == 0)
627 strncpy(buffer, filename, PATH_MAX + 1);
628 else
629 if (snprintf(buffer, PATH_MAX + 1, "%s%0*d", filename, max_chars, cnt) > PATH_MAX)
630 /* Report an error if the filename is too large */
631 error("too many output files or filename is too long (> %d)", PATH_MAX);
632 free(filename);
633 }
634
tcpdump_printf(netdissect_options * ndo _U_,const char * fmt,...)635 static int tcpdump_printf(netdissect_options *ndo _U_,
636 const char *fmt, ...)
637 {
638
639 va_list args;
640 int ret;
641
642 va_start(args, fmt);
643 ret=vfprintf(stdout, fmt, args);
644 va_end(args);
645
646 return ret;
647 }
648
649 static struct print_info
get_print_info(int type)650 get_print_info(int type)
651 {
652 struct print_info printinfo;
653
654 printinfo.ndo_type = 1;
655 printinfo.ndo = gndo;
656 printinfo.p.ndo_printer = lookup_ndo_printer(type);
657 if (printinfo.p.ndo_printer == NULL) {
658 printinfo.p.printer = lookup_printer(type);
659 printinfo.ndo_type = 0;
660 if (printinfo.p.printer == NULL) {
661 gndo->ndo_dltname = pcap_datalink_val_to_name(type);
662 if (gndo->ndo_dltname != NULL)
663 error("packet printing is not supported for link type %s: use -w",
664 gndo->ndo_dltname);
665 else
666 error("packet printing is not supported for link type %d: use -w", type);
667 }
668 }
669 return (printinfo);
670 }
671
672 static char *
get_next_file(FILE * VFile,char * ptr)673 get_next_file(FILE *VFile, char *ptr)
674 {
675 char *ret;
676
677 ret = fgets(ptr, PATH_MAX, VFile);
678 if (!ret)
679 return NULL;
680
681 if (ptr[strlen(ptr) - 1] == '\n')
682 ptr[strlen(ptr) - 1] = '\0';
683
684 return ret;
685 }
686
687 #ifdef __FreeBSD__
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
set_dumper_capsicum_rights(pcap_dumper_t * p)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
main(int argc,char ** argv)758 main(int argc, char **argv)
759 {
760 register int cnt, op, i;
761 bpf_u_int32 localnet, netmask;
762 register char *cp, *infile, *cmdbuf, *device, *RFileName, *VFileName, *WFileName;
763 pcap_handler callback;
764 int type;
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 print_info printinfo;
773 struct dump_info dumpinfo;
774 u_char *pcap_userdata;
775 char ebuf[PCAP_ERRBUF_SIZE];
776 char VFileLine[PATH_MAX + 1];
777 char *username = NULL;
778 char *chroot_dir = NULL;
779 char *ret = NULL;
780 char *end;
781 #ifdef HAVE_PCAP_FINDALLDEVS
782 pcap_if_t *devpointer;
783 int devnum;
784 #endif
785 int status;
786 FILE *VFile;
787 #ifdef __FreeBSD__
788 cap_rights_t rights;
789 int cansandbox;
790 #endif /* __FreeBSD__ */
791
792 #ifdef WIN32
793 if(wsockinit() != 0) return 1;
794 #endif /* WIN32 */
795
796 jflag=-1; /* not set */
797 gndo->ndo_Oflag=1;
798 gndo->ndo_Rflag=1;
799 gndo->ndo_dlt=-1;
800 gndo->ndo_default_print=ndo_default_print;
801 gndo->ndo_printf=tcpdump_printf;
802 gndo->ndo_error=ndo_error;
803 gndo->ndo_warning=ndo_warning;
804 gndo->ndo_snaplen = DEFAULT_SNAPLEN;
805
806 cnt = -1;
807 device = NULL;
808 infile = NULL;
809 RFileName = NULL;
810 VFileName = NULL;
811 VFile = NULL;
812 WFileName = NULL;
813 dlt = -1;
814 if ((cp = strrchr(argv[0], '/')) != NULL)
815 program_name = cp + 1;
816 else
817 program_name = argv[0];
818
819 if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
820 error("%s", ebuf);
821
822 #ifdef LIBSMI
823 smiInit("tcpdump");
824 #endif
825
826 while (
827 (op = getopt(argc, argv, "aAb" B_FLAG "c:C:d" D_FLAG "eE:fF:G:hHi:" I_FLAG j_FLAG J_FLAG "KlLm:M:nNOpqr:Rs:StT:u" U_FLAG "V:vw:W:xXy:Yz:Z:")) != -1)
828 switch (op) {
829
830 case 'a':
831 /* compatibility for old -a */
832 break;
833
834 case 'A':
835 ++Aflag;
836 break;
837
838 case 'b':
839 ++bflag;
840 break;
841
842 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
843 case 'B':
844 Bflag = atoi(optarg)*1024;
845 if (Bflag <= 0)
846 error("invalid packet buffer size %s", optarg);
847 break;
848 #endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
849
850 case 'c':
851 cnt = atoi(optarg);
852 if (cnt <= 0)
853 error("invalid packet count %s", optarg);
854 break;
855
856 case 'C':
857 Cflag = atoi(optarg) * 1000000;
858 if (Cflag < 0)
859 error("invalid file size %s", optarg);
860 break;
861
862 case 'd':
863 ++dflag;
864 break;
865
866 #ifdef HAVE_PCAP_FINDALLDEVS
867 case 'D':
868 if (pcap_findalldevs(&devpointer, ebuf) < 0)
869 error("%s", ebuf);
870 else {
871 for (i = 0; devpointer != 0; i++) {
872 printf("%d.%s", i+1, devpointer->name);
873 if (devpointer->description != NULL)
874 printf(" (%s)", devpointer->description);
875 printf("\n");
876 devpointer = devpointer->next;
877 }
878 }
879 return 0;
880 #endif /* HAVE_PCAP_FINDALLDEVS */
881
882 case 'L':
883 Lflag++;
884 break;
885
886 case 'e':
887 ++eflag;
888 break;
889
890 case 'E':
891 #ifndef HAVE_LIBCRYPTO
892 warning("crypto code not compiled in");
893 #endif
894 gndo->ndo_espsecret = optarg;
895 break;
896
897 case 'f':
898 ++fflag;
899 break;
900
901 case 'F':
902 infile = optarg;
903 break;
904
905 case 'G':
906 Gflag = atoi(optarg);
907 if (Gflag < 0)
908 error("invalid number of seconds %s", optarg);
909
910 /* We will create one file initially. */
911 Gflag_count = 0;
912
913 /* Grab the current time for rotation use. */
914 if ((Gflag_time = time(NULL)) == (time_t)-1) {
915 error("main: can't get current time: %s",
916 pcap_strerror(errno));
917 }
918 break;
919
920 case 'h':
921 usage();
922 break;
923
924 case 'H':
925 ++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(&devpointer, ebuf) < 0)
949 error("%s", ebuf);
950 else {
951 /*
952 * Look for the devnum-th entry
953 * in the list of devices
954 * (1-based).
955 */
956 for (i = 0;
957 i < devnum-1 && devpointer != NULL;
958 i++, devpointer = devpointer->next)
959 ;
960 if (devpointer == NULL)
961 error("Invalid adapter index");
962 }
963 device = devpointer->name;
964 break;
965 }
966 #endif /* HAVE_PCAP_FINDALLDEVS */
967 device = optarg;
968 break;
969
970 #ifdef HAVE_PCAP_CREATE
971 case 'I':
972 ++Iflag;
973 break;
974 #endif /* HAVE_PCAP_CREATE */
975
976 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
977 case 'j':
978 jflag = pcap_tstamp_type_name_to_val(optarg);
979 if (jflag < 0)
980 error("invalid time stamp type %s", optarg);
981 break;
982
983 case 'J':
984 Jflag++;
985 break;
986 #endif
987
988 case 'l':
989 #ifdef WIN32
990 /*
991 * _IOLBF is the same as _IOFBF in Microsoft's C
992 * libraries; the only alternative they offer
993 * is _IONBF.
994 *
995 * XXX - this should really be checking for MSVC++,
996 * not WIN32, if, for example, MinGW has its own
997 * C library that is more UNIX-compatible.
998 */
999 setvbuf(stdout, NULL, _IONBF, 0);
1000 #else /* WIN32 */
1001 #ifdef HAVE_SETLINEBUF
1002 setlinebuf(stdout);
1003 #else
1004 setvbuf(stdout, NULL, _IOLBF, 0);
1005 #endif
1006 #endif /* WIN32 */
1007 break;
1008
1009 case 'K':
1010 ++Kflag;
1011 break;
1012
1013 case 'm':
1014 #ifdef LIBSMI
1015 if (smiLoadModule(optarg) == 0) {
1016 error("could not load MIB module %s", optarg);
1017 }
1018 sflag = 1;
1019 #else
1020 (void)fprintf(stderr, "%s: ignoring option `-m %s' ",
1021 program_name, optarg);
1022 (void)fprintf(stderr, "(no libsmi support)\n");
1023 #endif
1024 break;
1025
1026 case 'M':
1027 /* TCP-MD5 shared secret */
1028 #ifndef HAVE_LIBCRYPTO
1029 warning("crypto code not compiled in");
1030 #endif
1031 sigsecret = optarg;
1032 break;
1033
1034 case 'n':
1035 ++nflag;
1036 break;
1037
1038 case 'N':
1039 ++Nflag;
1040 break;
1041
1042 case 'O':
1043 Oflag = 0;
1044 break;
1045
1046 case 'p':
1047 ++pflag;
1048 break;
1049
1050 case 'q':
1051 ++qflag;
1052 ++suppress_default_print;
1053 break;
1054
1055 case 'r':
1056 RFileName = optarg;
1057 break;
1058
1059 case 'R':
1060 Rflag = 0;
1061 break;
1062
1063 case 's':
1064 snaplen = strtol(optarg, &end, 0);
1065 if (optarg == end || *end != '\0'
1066 || snaplen < 0 || snaplen > MAXIMUM_SNAPLEN)
1067 error("invalid snaplen %s", optarg);
1068 else if (snaplen == 0)
1069 snaplen = MAXIMUM_SNAPLEN;
1070 break;
1071
1072 case 'S':
1073 ++Sflag;
1074 break;
1075
1076 case 't':
1077 ++tflag;
1078 break;
1079
1080 case 'T':
1081 if (strcasecmp(optarg, "vat") == 0)
1082 packettype = PT_VAT;
1083 else if (strcasecmp(optarg, "wb") == 0)
1084 packettype = PT_WB;
1085 else if (strcasecmp(optarg, "rpc") == 0)
1086 packettype = PT_RPC;
1087 else if (strcasecmp(optarg, "rtp") == 0)
1088 packettype = PT_RTP;
1089 else if (strcasecmp(optarg, "rtcp") == 0)
1090 packettype = PT_RTCP;
1091 else if (strcasecmp(optarg, "snmp") == 0)
1092 packettype = PT_SNMP;
1093 else if (strcasecmp(optarg, "cnfp") == 0)
1094 packettype = PT_CNFP;
1095 else if (strcasecmp(optarg, "tftp") == 0)
1096 packettype = PT_TFTP;
1097 else if (strcasecmp(optarg, "aodv") == 0)
1098 packettype = PT_AODV;
1099 else if (strcasecmp(optarg, "carp") == 0)
1100 packettype = PT_CARP;
1101 else if (strcasecmp(optarg, "radius") == 0)
1102 packettype = PT_RADIUS;
1103 else if (strcasecmp(optarg, "zmtp1") == 0)
1104 packettype = PT_ZMTP1;
1105 else if (strcasecmp(optarg, "vxlan") == 0)
1106 packettype = PT_VXLAN;
1107 else
1108 error("unknown packet type `%s'", optarg);
1109 break;
1110
1111 case 'u':
1112 ++uflag;
1113 break;
1114
1115 #ifdef HAVE_PCAP_DUMP_FLUSH
1116 case 'U':
1117 ++Uflag;
1118 break;
1119 #endif
1120
1121 case 'v':
1122 ++vflag;
1123 break;
1124
1125 case 'V':
1126 VFileName = optarg;
1127 break;
1128
1129 case 'w':
1130 WFileName = optarg;
1131 break;
1132
1133 case 'W':
1134 Wflag = atoi(optarg);
1135 if (Wflag < 0)
1136 error("invalid number of output files %s", optarg);
1137 WflagChars = getWflagChars(Wflag);
1138 break;
1139
1140 case 'x':
1141 ++xflag;
1142 ++suppress_default_print;
1143 break;
1144
1145 case 'X':
1146 ++Xflag;
1147 ++suppress_default_print;
1148 break;
1149
1150 case 'y':
1151 gndo->ndo_dltname = optarg;
1152 gndo->ndo_dlt =
1153 pcap_datalink_name_to_val(gndo->ndo_dltname);
1154 if (gndo->ndo_dlt < 0)
1155 error("invalid data link type %s", gndo->ndo_dltname);
1156 break;
1157
1158 #if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
1159 case 'Y':
1160 {
1161 /* Undocumented flag */
1162 #ifdef HAVE_PCAP_DEBUG
1163 extern int pcap_debug;
1164 pcap_debug = 1;
1165 #else
1166 extern int yydebug;
1167 yydebug = 1;
1168 #endif
1169 }
1170 break;
1171 #endif
1172 case 'z':
1173 if (optarg) {
1174 zflag = strdup(optarg);
1175 } else {
1176 usage();
1177 /* NOTREACHED */
1178 }
1179 break;
1180
1181 case 'Z':
1182 if (optarg) {
1183 username = strdup(optarg);
1184 }
1185 else {
1186 usage();
1187 /* NOTREACHED */
1188 }
1189 break;
1190
1191 default:
1192 usage();
1193 /* NOTREACHED */
1194 }
1195
1196 switch (tflag) {
1197
1198 case 0: /* Default */
1199 case 4: /* Default + Date*/
1200 thiszone = gmt2local(0);
1201 break;
1202
1203 case 1: /* No time stamp */
1204 case 2: /* Unix timeval style */
1205 case 3: /* Microseconds since previous packet */
1206 case 5: /* Microseconds since first packet */
1207 break;
1208
1209 default: /* Not supported */
1210 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1211 break;
1212 }
1213
1214 if (fflag != 0 && (VFileName != NULL || RFileName != NULL))
1215 error("-f can not be used with -V or -r");
1216
1217 if (VFileName != NULL && RFileName != NULL)
1218 error("-V and -r are mutually exclusive.");
1219
1220 #ifdef WITH_CHROOT
1221 /* if run as root, prepare for chrooting */
1222 if (getuid() == 0 || geteuid() == 0) {
1223 /* future extensibility for cmd-line arguments */
1224 if (!chroot_dir)
1225 chroot_dir = WITH_CHROOT;
1226 }
1227 #endif
1228
1229 #ifdef WITH_USER
1230 /* if run as root, prepare for dropping root privileges */
1231 if (getuid() == 0 || geteuid() == 0) {
1232 /* Run with '-Z root' to restore old behaviour */
1233 if (!username)
1234 username = WITH_USER;
1235 }
1236 #endif
1237
1238 if (RFileName != NULL || VFileName != NULL) {
1239 /*
1240 * If RFileName is non-null, it's the pathname of a
1241 * savefile to read. If VFileName is non-null, it's
1242 * the pathname of a file containing a list of pathnames
1243 * (one per line) of savefiles to read.
1244 *
1245 * In either case, we're reading a savefile, not doing
1246 * a live capture.
1247 */
1248 #ifndef WIN32
1249 /*
1250 * We don't need network access, so relinquish any set-UID
1251 * or set-GID privileges we have (if any).
1252 *
1253 * We do *not* want set-UID privileges when opening a
1254 * trace file, as that might let the user read other
1255 * people's trace files (especially if we're set-UID
1256 * root).
1257 */
1258 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1259 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1260 #endif /* WIN32 */
1261 if (VFileName != NULL) {
1262 if (VFileName[0] == '-' && VFileName[1] == '\0')
1263 VFile = stdin;
1264 else
1265 VFile = fopen(VFileName, "r");
1266
1267 if (VFile == NULL)
1268 error("Unable to open file: %s\n", strerror(errno));
1269
1270 ret = get_next_file(VFile, VFileLine);
1271 if (!ret)
1272 error("Nothing in %s\n", VFileName);
1273 RFileName = VFileLine;
1274 }
1275
1276 pd = pcap_open_offline(RFileName, ebuf);
1277 if (pd == NULL)
1278 error("%s", ebuf);
1279 #ifdef __FreeBSD__
1280 cap_rights_init(&rights, CAP_READ);
1281 if (cap_rights_limit(fileno(pcap_file(pd)), &rights) < 0 &&
1282 errno != ENOSYS) {
1283 error("unable to limit pcap descriptor");
1284 }
1285 #endif
1286 dlt = pcap_datalink(pd);
1287 dlt_name = pcap_datalink_val_to_name(dlt);
1288 if (dlt_name == NULL) {
1289 fprintf(stderr, "reading from file %s, link-type %u\n",
1290 RFileName, dlt);
1291 } else {
1292 fprintf(stderr,
1293 "reading from file %s, link-type %s (%s)\n",
1294 RFileName, dlt_name,
1295 pcap_datalink_val_to_description(dlt));
1296 }
1297 localnet = 0;
1298 netmask = 0;
1299 } else {
1300 /*
1301 * We're doing a live capture.
1302 */
1303 if (device == NULL) {
1304 device = pcap_lookupdev(ebuf);
1305 if (device == NULL)
1306 error("%s", ebuf);
1307 }
1308 #ifdef WIN32
1309 /*
1310 * Print a message to the standard error on Windows.
1311 * XXX - why do it here, with a different message?
1312 */
1313 if(strlen(device) == 1) //we assume that an ASCII string is always longer than 1 char
1314 { //a Unicode string has a \0 as second byte (so strlen() is 1)
1315 fprintf(stderr, "%s: listening on %ws\n", program_name, device);
1316 }
1317 else
1318 {
1319 fprintf(stderr, "%s: listening on %s\n", program_name, device);
1320 }
1321
1322 fflush(stderr);
1323 #endif /* WIN32 */
1324 #ifdef HAVE_PCAP_CREATE
1325 pd = pcap_create(device, ebuf);
1326 if (pd == NULL)
1327 error("%s", ebuf);
1328 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1329 if (Jflag)
1330 show_tstamp_types_and_exit(device, pd);
1331 #endif
1332 /*
1333 * Is this an interface that supports monitor mode?
1334 */
1335 if (pcap_can_set_rfmon(pd) == 1)
1336 supports_monitor_mode = 1;
1337 else
1338 supports_monitor_mode = 0;
1339 status = pcap_set_snaplen(pd, snaplen);
1340 if (status != 0)
1341 error("%s: Can't set snapshot length: %s",
1342 device, pcap_statustostr(status));
1343 status = pcap_set_promisc(pd, !pflag);
1344 if (status != 0)
1345 error("%s: Can't set promiscuous mode: %s",
1346 device, pcap_statustostr(status));
1347 if (Iflag) {
1348 status = pcap_set_rfmon(pd, 1);
1349 if (status != 0)
1350 error("%s: Can't set monitor mode: %s",
1351 device, pcap_statustostr(status));
1352 }
1353 status = pcap_set_timeout(pd, 1000);
1354 if (status != 0)
1355 error("%s: pcap_set_timeout failed: %s",
1356 device, pcap_statustostr(status));
1357 if (Bflag != 0) {
1358 status = pcap_set_buffer_size(pd, Bflag);
1359 if (status != 0)
1360 error("%s: Can't set buffer size: %s",
1361 device, pcap_statustostr(status));
1362 }
1363 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1364 if (jflag != -1) {
1365 status = pcap_set_tstamp_type(pd, jflag);
1366 if (status < 0)
1367 error("%s: Can't set time stamp type: %s",
1368 device, pcap_statustostr(status));
1369 }
1370 #endif
1371 status = pcap_activate(pd);
1372 if (status < 0) {
1373 /*
1374 * pcap_activate() failed.
1375 */
1376 cp = pcap_geterr(pd);
1377 if (status == PCAP_ERROR)
1378 error("%s", cp);
1379 else if ((status == PCAP_ERROR_NO_SUCH_DEVICE ||
1380 status == PCAP_ERROR_PERM_DENIED) &&
1381 *cp != '\0')
1382 error("%s: %s\n(%s)", device,
1383 pcap_statustostr(status), cp);
1384 #ifdef __FreeBSD__
1385 else if (status == PCAP_ERROR_RFMON_NOTSUP &&
1386 strncmp(device, "wlan", 4) == 0) {
1387 char parent[8], newdev[8];
1388 char sysctl[32];
1389 size_t s = sizeof(parent);
1390
1391 snprintf(sysctl, sizeof(sysctl),
1392 "net.wlan.%d.%%parent", atoi(device + 4));
1393 sysctlbyname(sysctl, parent, &s, NULL, 0);
1394 strlcpy(newdev, device, sizeof(newdev));
1395 /* Suggest a new wlan device. */
1396 newdev[strlen(newdev)-1]++;
1397 error("%s is not a monitor mode VAP\n"
1398 "To create a new monitor mode VAP use:\n"
1399 " ifconfig %s create wlandev %s wlanmode "
1400 "monitor\nand use %s as the tcpdump "
1401 "interface", device, newdev, parent,
1402 newdev);
1403 }
1404 #endif
1405 else
1406 error("%s: %s", device,
1407 pcap_statustostr(status));
1408 } else if (status > 0) {
1409 /*
1410 * pcap_activate() succeeded, but it's warning us
1411 * of a problem it had.
1412 */
1413 cp = pcap_geterr(pd);
1414 if (status == PCAP_WARNING)
1415 warning("%s", cp);
1416 else if (status == PCAP_WARNING_PROMISC_NOTSUP &&
1417 *cp != '\0')
1418 warning("%s: %s\n(%s)", device,
1419 pcap_statustostr(status), cp);
1420 else
1421 warning("%s: %s", device,
1422 pcap_statustostr(status));
1423 }
1424 #else
1425 *ebuf = '\0';
1426 pd = pcap_open_live(device, snaplen, !pflag, 1000, ebuf);
1427 if (pd == NULL)
1428 error("%s", ebuf);
1429 else if (*ebuf)
1430 warning("%s", ebuf);
1431 #endif /* HAVE_PCAP_CREATE */
1432 /*
1433 * Let user own process after socket has been opened.
1434 */
1435 #ifndef WIN32
1436 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1437 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1438 #endif /* WIN32 */
1439 #if !defined(HAVE_PCAP_CREATE) && defined(WIN32)
1440 if(Bflag != 0)
1441 if(pcap_setbuff(pd, Bflag)==-1){
1442 error("%s", pcap_geterr(pd));
1443 }
1444 #endif /* !defined(HAVE_PCAP_CREATE) && defined(WIN32) */
1445 if (Lflag)
1446 show_dlts_and_exit(device, pd);
1447 if (gndo->ndo_dlt >= 0) {
1448 #ifdef HAVE_PCAP_SET_DATALINK
1449 if (pcap_set_datalink(pd, gndo->ndo_dlt) < 0)
1450 error("%s", pcap_geterr(pd));
1451 #else
1452 /*
1453 * We don't actually support changing the
1454 * data link type, so we only let them
1455 * set it to what it already is.
1456 */
1457 if (gndo->ndo_dlt != pcap_datalink(pd)) {
1458 error("%s is not one of the DLTs supported by this device\n",
1459 gndo->ndo_dltname);
1460 }
1461 #endif
1462 (void)fprintf(stderr, "%s: data link type %s\n",
1463 program_name, gndo->ndo_dltname);
1464 (void)fflush(stderr);
1465 }
1466 i = pcap_snapshot(pd);
1467 if (snaplen < i) {
1468 warning("snaplen raised from %d to %d", snaplen, i);
1469 snaplen = i;
1470 }
1471 if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
1472 localnet = 0;
1473 netmask = 0;
1474 warning("%s", ebuf);
1475 }
1476 }
1477 if (infile)
1478 cmdbuf = read_infile(infile);
1479 else
1480 cmdbuf = copy_argv(&argv[optind]);
1481
1482 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1483 error("%s", pcap_geterr(pd));
1484 if (dflag) {
1485 bpf_dump(&fcode, dflag);
1486 pcap_close(pd);
1487 free(cmdbuf);
1488 exit(0);
1489 }
1490 init_addrtoname(localnet, netmask);
1491 init_checksum();
1492
1493 #ifndef WIN32
1494 (void)setsignal(SIGPIPE, cleanup);
1495 (void)setsignal(SIGTERM, cleanup);
1496 (void)setsignal(SIGINT, cleanup);
1497 #endif /* WIN32 */
1498 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1499 (void)setsignal(SIGCHLD, child_cleanup);
1500 #endif
1501 /* Cooperate with nohup(1) */
1502 #ifndef WIN32
1503 if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
1504 (void)setsignal(SIGHUP, oldhandler);
1505 #endif /* WIN32 */
1506
1507 #ifndef WIN32
1508 /*
1509 * If a user name was specified with "-Z", attempt to switch to
1510 * that user's UID. This would probably be used with sudo,
1511 * to allow tcpdump to be run in a special restricted
1512 * account (if you just want to allow users to open capture
1513 * devices, and can't just give users that permission,
1514 * you'd make tcpdump set-UID or set-GID).
1515 *
1516 * Tcpdump doesn't necessarily write only to one savefile;
1517 * the general only way to allow a -Z instance to write to
1518 * savefiles as the user under whose UID it's run, rather
1519 * than as the user specified with -Z, would thus be to switch
1520 * to the original user ID before opening a capture file and
1521 * then switch back to the -Z user ID after opening the savefile.
1522 * Switching to the -Z user ID only after opening the first
1523 * savefile doesn't handle the general case.
1524 */
1525
1526 #ifdef HAVE_CAP_NG_H
1527 /* We are running as root and we will be writing to savefile */
1528 if ((getuid() == 0 || geteuid() == 0) && WFileName) {
1529 if (username) {
1530 /* Drop all capabilities from effective set */
1531 capng_clear(CAPNG_EFFECTIVE);
1532 /* Add capabilities we will need*/
1533 capng_update(CAPNG_ADD, CAPNG_PERMITTED, CAP_SETUID);
1534 capng_update(CAPNG_ADD, CAPNG_PERMITTED, CAP_SETGID);
1535 capng_update(CAPNG_ADD, CAPNG_PERMITTED, CAP_DAC_OVERRIDE);
1536
1537 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_SETUID);
1538 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_SETGID);
1539 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
1540
1541 capng_apply(CAPNG_SELECT_BOTH);
1542 }
1543 }
1544 #endif /* HAVE_CAP_NG_H */
1545
1546 if (getuid() == 0 || geteuid() == 0) {
1547 if (username || chroot_dir)
1548 droproot(username, chroot_dir);
1549
1550 }
1551 #endif /* WIN32 */
1552
1553 if (pcap_setfilter(pd, &fcode) < 0)
1554 error("%s", pcap_geterr(pd));
1555 #ifdef __FreeBSD__
1556 if (RFileName == NULL && VFileName == NULL) {
1557 static const unsigned long cmds[] = { BIOCGSTATS, BIOCROTZBUF };
1558
1559 /*
1560 * The various libpcap devices use a combination of
1561 * read (bpf), ioctl (bpf, netmap), poll (netmap).
1562 * Grant the relevant access rights, sorted by name.
1563 */
1564 cap_rights_init(&rights, CAP_EVENT, CAP_IOCTL, CAP_READ);
1565 if (cap_rights_limit(pcap_fileno(pd), &rights) < 0 &&
1566 errno != ENOSYS) {
1567 error("unable to limit pcap descriptor");
1568 }
1569 if (cap_ioctls_limit(pcap_fileno(pd), cmds,
1570 sizeof(cmds) / sizeof(cmds[0])) < 0 && errno != ENOSYS) {
1571 error("unable to limit ioctls on pcap descriptor");
1572 }
1573 }
1574 #endif
1575 if (WFileName) {
1576 pcap_dumper_t *p;
1577 /* Do not exceed the default PATH_MAX for files. */
1578 dumpinfo.CurrentFileName = (char *)malloc(PATH_MAX + 1);
1579
1580 if (dumpinfo.CurrentFileName == NULL)
1581 error("malloc of dumpinfo.CurrentFileName");
1582
1583 /* We do not need numbering for dumpfiles if Cflag isn't set. */
1584 if (Cflag != 0)
1585 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
1586 else
1587 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
1588
1589 p = pcap_dump_open(pd, dumpinfo.CurrentFileName);
1590 #ifdef HAVE_CAP_NG_H
1591 /* Give up capabilities, clear Effective set */
1592 capng_clear(CAPNG_EFFECTIVE);
1593 #endif
1594 if (p == NULL)
1595 error("%s", pcap_geterr(pd));
1596 #ifdef __FreeBSD__
1597 set_dumper_capsicum_rights(p);
1598 #endif
1599 if (Cflag != 0 || Gflag != 0) {
1600 #ifdef __FreeBSD__
1601 dumpinfo.WFileName = strdup(basename(WFileName));
1602 dumpinfo.dirfd = open(dirname(WFileName),
1603 O_DIRECTORY | O_RDONLY);
1604 if (dumpinfo.dirfd < 0) {
1605 error("unable to open directory %s",
1606 dirname(WFileName));
1607 }
1608 cap_rights_init(&rights, CAP_CREATE, CAP_FCNTL,
1609 CAP_FTRUNCATE, CAP_LOOKUP, CAP_SEEK, CAP_WRITE);
1610 if (cap_rights_limit(dumpinfo.dirfd, &rights) < 0 &&
1611 errno != ENOSYS) {
1612 error("unable to limit directory rights");
1613 }
1614 if (cap_fcntls_limit(fileno(pcap_dump_file(p)), CAP_FCNTL_GETFL) < 0 &&
1615 errno != ENOSYS) {
1616 error("unable to limit dump descriptor fcntls");
1617 }
1618 #else /* !__FreeBSD__ */
1619 dumpinfo.WFileName = WFileName;
1620 #endif
1621 callback = dump_packet_and_trunc;
1622 dumpinfo.pd = pd;
1623 dumpinfo.p = p;
1624 pcap_userdata = (u_char *)&dumpinfo;
1625 } else {
1626 callback = dump_packet;
1627 pcap_userdata = (u_char *)p;
1628 }
1629 #ifdef HAVE_PCAP_DUMP_FLUSH
1630 if (Uflag)
1631 pcap_dump_flush(p);
1632 #endif
1633 } else {
1634 type = pcap_datalink(pd);
1635 printinfo = get_print_info(type);
1636 callback = print_packet;
1637 pcap_userdata = (u_char *)&printinfo;
1638 }
1639
1640 #ifdef SIGNAL_REQ_INFO
1641 /*
1642 * We can't get statistics when reading from a file rather
1643 * than capturing from a device.
1644 */
1645 if (RFileName == NULL)
1646 (void)setsignal(SIGNAL_REQ_INFO, requestinfo);
1647 #endif
1648
1649 if (vflag > 0 && WFileName) {
1650 /*
1651 * When capturing to a file, "-v" means tcpdump should,
1652 * every 10 secodns, "v"erbosely report the number of
1653 * packets captured.
1654 */
1655 #ifdef USE_WIN32_MM_TIMER
1656 /* call verbose_stats_dump() each 1000 +/-100msec */
1657 timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
1658 setvbuf(stderr, NULL, _IONBF, 0);
1659 #elif defined(HAVE_ALARM)
1660 (void)setsignal(SIGALRM, verbose_stats_dump);
1661 alarm(1);
1662 #endif
1663 }
1664
1665 #ifndef WIN32
1666 if (RFileName == NULL) {
1667 /*
1668 * Live capture (if -V was specified, we set RFileName
1669 * to a file from the -V file). Print a message to
1670 * the standard error on UN*X.
1671 */
1672 if (!vflag && !WFileName) {
1673 (void)fprintf(stderr,
1674 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
1675 program_name);
1676 } else
1677 (void)fprintf(stderr, "%s: ", program_name);
1678 dlt = pcap_datalink(pd);
1679 dlt_name = pcap_datalink_val_to_name(dlt);
1680 if (dlt_name == NULL) {
1681 (void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
1682 device, dlt, snaplen);
1683 } else {
1684 (void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
1685 device, dlt_name,
1686 pcap_datalink_val_to_description(dlt), snaplen);
1687 }
1688 (void)fflush(stderr);
1689 }
1690 #endif /* WIN32 */
1691
1692 #ifdef __FreeBSD__
1693 cansandbox = (nflag && VFileName == NULL && zflag == NULL);
1694 if (cansandbox && cap_enter() < 0 && errno != ENOSYS)
1695 error("unable to enter the capability mode");
1696 #endif /* __FreeBSD__ */
1697
1698 do {
1699 status = pcap_loop(pd, cnt, callback, pcap_userdata);
1700 if (WFileName == NULL) {
1701 /*
1702 * We're printing packets. Flush the printed output,
1703 * so it doesn't get intermingled with error output.
1704 */
1705 if (status == -2) {
1706 /*
1707 * We got interrupted, so perhaps we didn't
1708 * manage to finish a line we were printing.
1709 * Print an extra newline, just in case.
1710 */
1711 putchar('\n');
1712 }
1713 (void)fflush(stdout);
1714 }
1715 if (status == -1) {
1716 /*
1717 * Error. Report it.
1718 */
1719 (void)fprintf(stderr, "%s: pcap_loop: %s\n",
1720 program_name, pcap_geterr(pd));
1721 }
1722 if (RFileName == NULL) {
1723 /*
1724 * We're doing a live capture. Report the capture
1725 * statistics.
1726 */
1727 info(1);
1728 }
1729 pcap_close(pd);
1730 if (VFileName != NULL) {
1731 ret = get_next_file(VFile, VFileLine);
1732 if (ret) {
1733 RFileName = VFileLine;
1734 pd = pcap_open_offline(RFileName, ebuf);
1735 if (pd == NULL)
1736 error("%s", ebuf);
1737 #ifdef __FreeBSD__
1738 cap_rights_init(&rights, CAP_READ);
1739 if (cap_rights_limit(fileno(pcap_file(pd)),
1740 &rights) < 0 && errno != ENOSYS) {
1741 error("unable to limit pcap descriptor");
1742 }
1743 #endif
1744 new_dlt = pcap_datalink(pd);
1745 if (WFileName && new_dlt != dlt)
1746 error("%s: new dlt does not match original", RFileName);
1747 printinfo = get_print_info(new_dlt);
1748 dlt_name = pcap_datalink_val_to_name(new_dlt);
1749 if (dlt_name == NULL) {
1750 fprintf(stderr, "reading from file %s, link-type %u\n",
1751 RFileName, new_dlt);
1752 } else {
1753 fprintf(stderr,
1754 "reading from file %s, link-type %s (%s)\n",
1755 RFileName, dlt_name,
1756 pcap_datalink_val_to_description(new_dlt));
1757 }
1758 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1759 error("%s", pcap_geterr(pd));
1760 if (pcap_setfilter(pd, &fcode) < 0)
1761 error("%s", pcap_geterr(pd));
1762 }
1763 }
1764 }
1765 while (ret != NULL);
1766
1767 free(cmdbuf);
1768 exit(status == -1 ? 1 : 0);
1769 }
1770
1771 /* make a clean exit on interrupts */
1772 static RETSIGTYPE
cleanup(int signo _U_)1773 cleanup(int signo _U_)
1774 {
1775 #ifdef USE_WIN32_MM_TIMER
1776 if (timer_id)
1777 timeKillEvent(timer_id);
1778 timer_id = 0;
1779 #elif defined(HAVE_ALARM)
1780 alarm(0);
1781 #endif
1782
1783 #ifdef HAVE_PCAP_BREAKLOOP
1784 /*
1785 * We have "pcap_breakloop()"; use it, so that we do as little
1786 * as possible in the signal handler (it's probably not safe
1787 * to do anything with standard I/O streams in a signal handler -
1788 * the ANSI C standard doesn't say it is).
1789 */
1790 pcap_breakloop(pd);
1791 #else
1792 /*
1793 * We don't have "pcap_breakloop()"; this isn't safe, but
1794 * it's the best we can do. Print the summary if we're
1795 * not reading from a savefile - i.e., if we're doing a
1796 * live capture - and exit.
1797 */
1798 if (pd != NULL && pcap_file(pd) == NULL) {
1799 /*
1800 * We got interrupted, so perhaps we didn't
1801 * manage to finish a line we were printing.
1802 * Print an extra newline, just in case.
1803 */
1804 putchar('\n');
1805 (void)fflush(stdout);
1806 info(1);
1807 }
1808 exit(0);
1809 #endif
1810 }
1811
1812 /*
1813 On windows, we do not use a fork, so we do not care less about
1814 waiting a child processes to die
1815 */
1816 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1817 static RETSIGTYPE
child_cleanup(int signo _U_)1818 child_cleanup(int signo _U_)
1819 {
1820 wait(NULL);
1821 }
1822 #endif /* HAVE_FORK && HAVE_VFORK */
1823
1824 static void
info(register int verbose)1825 info(register int verbose)
1826 {
1827 struct pcap_stat stat;
1828
1829 /*
1830 * Older versions of libpcap didn't set ps_ifdrop on some
1831 * platforms; initialize it to 0 to handle that.
1832 */
1833 stat.ps_ifdrop = 0;
1834 if (pcap_stats(pd, &stat) < 0) {
1835 (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
1836 infoprint = 0;
1837 return;
1838 }
1839
1840 if (!verbose)
1841 fprintf(stderr, "%s: ", program_name);
1842
1843 (void)fprintf(stderr, "%u packet%s captured", packets_captured,
1844 PLURAL_SUFFIX(packets_captured));
1845 if (!verbose)
1846 fputs(", ", stderr);
1847 else
1848 putc('\n', stderr);
1849 (void)fprintf(stderr, "%u packet%s received by filter", stat.ps_recv,
1850 PLURAL_SUFFIX(stat.ps_recv));
1851 if (!verbose)
1852 fputs(", ", stderr);
1853 else
1854 putc('\n', stderr);
1855 (void)fprintf(stderr, "%u packet%s dropped by kernel", stat.ps_drop,
1856 PLURAL_SUFFIX(stat.ps_drop));
1857 if (stat.ps_ifdrop != 0) {
1858 if (!verbose)
1859 fputs(", ", stderr);
1860 else
1861 putc('\n', stderr);
1862 (void)fprintf(stderr, "%u packet%s dropped by interface\n",
1863 stat.ps_ifdrop, PLURAL_SUFFIX(stat.ps_ifdrop));
1864 } else
1865 putc('\n', stderr);
1866 infoprint = 0;
1867 }
1868
1869 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1870 static void
compress_savefile(const char * filename)1871 compress_savefile(const char *filename)
1872 {
1873 # ifdef HAVE_FORK
1874 if (fork())
1875 # else
1876 if (vfork())
1877 # endif
1878 return;
1879 /*
1880 * Set to lowest priority so that this doesn't disturb the capture
1881 */
1882 #ifdef NZERO
1883 setpriority(PRIO_PROCESS, 0, NZERO - 1);
1884 #else
1885 setpriority(PRIO_PROCESS, 0, 19);
1886 #endif
1887 if (execlp(zflag, zflag, filename, (char *)NULL) == -1)
1888 fprintf(stderr,
1889 "compress_savefile:execlp(%s, %s): %s\n",
1890 zflag,
1891 filename,
1892 strerror(errno));
1893 # ifdef HAVE_FORK
1894 exit(1);
1895 # else
1896 _exit(1);
1897 # endif
1898 }
1899 #else /* HAVE_FORK && HAVE_VFORK */
1900 static void
compress_savefile(const char * filename)1901 compress_savefile(const char *filename)
1902 {
1903 fprintf(stderr,
1904 "compress_savefile failed. Functionality not implemented under your system\n");
1905 }
1906 #endif /* HAVE_FORK && HAVE_VFORK */
1907
1908 static void
dump_packet_and_trunc(u_char * user,const struct pcap_pkthdr * h,const u_char * sp)1909 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1910 {
1911 struct dump_info *dump_info;
1912
1913 ++packets_captured;
1914
1915 ++infodelay;
1916
1917 dump_info = (struct dump_info *)user;
1918
1919 /*
1920 * XXX - this won't force the file to rotate on the specified time
1921 * boundary, but it will rotate on the first packet received after the
1922 * specified Gflag number of seconds. Note: if a Gflag time boundary
1923 * and a Cflag size boundary coincide, the time rotation will occur
1924 * first thereby cancelling the Cflag boundary (since the file should
1925 * be 0).
1926 */
1927 if (Gflag != 0) {
1928 /* Check if it is time to rotate */
1929 time_t t;
1930
1931 /* Get the current time */
1932 if ((t = time(NULL)) == (time_t)-1) {
1933 error("dump_and_trunc_packet: can't get current_time: %s",
1934 pcap_strerror(errno));
1935 }
1936
1937
1938 /* If the time is greater than the specified window, rotate */
1939 if (t - Gflag_time >= Gflag) {
1940 #ifdef __FreeBSD__
1941 FILE *fp;
1942 int fd;
1943 #endif
1944
1945 /* Update the Gflag_time */
1946 Gflag_time = t;
1947 /* Update Gflag_count */
1948 Gflag_count++;
1949 /*
1950 * Close the current file and open a new one.
1951 */
1952 pcap_dump_close(dump_info->p);
1953
1954 /*
1955 * Compress the file we just closed, if the user asked for it
1956 */
1957 if (zflag != NULL)
1958 compress_savefile(dump_info->CurrentFileName);
1959
1960 /*
1961 * Check to see if we've exceeded the Wflag (when
1962 * not using Cflag).
1963 */
1964 if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
1965 (void)fprintf(stderr, "Maximum file limit reached: %d\n",
1966 Wflag);
1967 exit(0);
1968 /* NOTREACHED */
1969 }
1970 if (dump_info->CurrentFileName != NULL)
1971 free(dump_info->CurrentFileName);
1972 /* Allocate space for max filename + \0. */
1973 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
1974 if (dump_info->CurrentFileName == NULL)
1975 error("dump_packet_and_trunc: malloc");
1976 /*
1977 * This is always the first file in the Cflag
1978 * rotation: e.g. 0
1979 * We also don't need numbering if Cflag is not set.
1980 */
1981 if (Cflag != 0)
1982 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
1983 WflagChars);
1984 else
1985 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
1986
1987 #ifdef HAVE_CAP_NG_H
1988 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
1989 capng_apply(CAPNG_EFFECTIVE);
1990 #endif /* HAVE_CAP_NG_H */
1991 #ifdef __FreeBSD__
1992 fd = openat(dump_info->dirfd,
1993 dump_info->CurrentFileName,
1994 O_CREAT | O_WRONLY | O_TRUNC, 0644);
1995 if (fd < 0) {
1996 error("unable to open file %s",
1997 dump_info->CurrentFileName);
1998 }
1999 fp = fdopen(fd, "w");
2000 if (fp == NULL) {
2001 error("unable to fdopen file %s",
2002 dump_info->CurrentFileName);
2003 }
2004 dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2005 #else /* !__FreeBSD__ */
2006 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2007 #endif
2008 #ifdef HAVE_CAP_NG_H
2009 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2010 capng_apply(CAPNG_EFFECTIVE);
2011 #endif /* HAVE_CAP_NG_H */
2012 if (dump_info->p == NULL)
2013 error("%s", pcap_geterr(pd));
2014 #ifdef __FreeBSD__
2015 set_dumper_capsicum_rights(dump_info->p);
2016 #endif
2017 }
2018 }
2019
2020 /*
2021 * XXX - this won't prevent capture files from getting
2022 * larger than Cflag - the last packet written to the
2023 * file could put it over Cflag.
2024 */
2025 if (Cflag != 0 && pcap_dump_ftell(dump_info->p) > Cflag) {
2026 #ifdef __FreeBSD__
2027 FILE *fp;
2028 int fd;
2029 #endif
2030
2031 /*
2032 * Close the current file and open a new one.
2033 */
2034 pcap_dump_close(dump_info->p);
2035
2036 /*
2037 * Compress the file we just closed, if the user asked for it
2038 */
2039 if (zflag != NULL)
2040 compress_savefile(dump_info->CurrentFileName);
2041
2042 Cflag_count++;
2043 if (Wflag > 0) {
2044 if (Cflag_count >= Wflag)
2045 Cflag_count = 0;
2046 }
2047 if (dump_info->CurrentFileName != NULL)
2048 free(dump_info->CurrentFileName);
2049 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2050 if (dump_info->CurrentFileName == NULL)
2051 error("dump_packet_and_trunc: malloc");
2052 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
2053 #ifdef __FreeBSD__
2054 fd = openat(dump_info->dirfd, dump_info->CurrentFileName,
2055 O_CREAT | O_WRONLY | O_TRUNC, 0644);
2056 if (fd < 0) {
2057 error("unable to open file %s",
2058 dump_info->CurrentFileName);
2059 }
2060 fp = fdopen(fd, "w");
2061 if (fp == NULL) {
2062 error("unable to fdopen file %s",
2063 dump_info->CurrentFileName);
2064 }
2065 dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2066 #else /* !__FreeBSD__ */
2067 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2068 #endif
2069 if (dump_info->p == NULL)
2070 error("%s", pcap_geterr(pd));
2071 #ifdef __FreeBSD__
2072 set_dumper_capsicum_rights(dump_info->p);
2073 #endif
2074 }
2075
2076 pcap_dump((u_char *)dump_info->p, h, sp);
2077 #ifdef HAVE_PCAP_DUMP_FLUSH
2078 if (Uflag)
2079 pcap_dump_flush(dump_info->p);
2080 #endif
2081
2082 --infodelay;
2083 if (infoprint)
2084 info(0);
2085 }
2086
2087 static void
dump_packet(u_char * user,const struct pcap_pkthdr * h,const u_char * sp)2088 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2089 {
2090 ++packets_captured;
2091
2092 ++infodelay;
2093
2094 pcap_dump(user, h, sp);
2095 #ifdef HAVE_PCAP_DUMP_FLUSH
2096 if (Uflag)
2097 pcap_dump_flush((pcap_dumper_t *)user);
2098 #endif
2099
2100 --infodelay;
2101 if (infoprint)
2102 info(0);
2103 }
2104
2105 static void
print_packet(u_char * user,const struct pcap_pkthdr * h,const u_char * sp)2106 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2107 {
2108 struct print_info *print_info;
2109 u_int hdrlen;
2110
2111 ++packets_captured;
2112
2113 ++infodelay;
2114 ts_print(&h->ts);
2115
2116 print_info = (struct print_info *)user;
2117
2118 /*
2119 * Some printers want to check that they're not walking off the
2120 * end of the packet.
2121 * Rather than pass it all the way down, we set this global.
2122 */
2123 snapend = sp + h->caplen;
2124
2125 if(print_info->ndo_type) {
2126 hdrlen = (*print_info->p.ndo_printer)(print_info->ndo, h, sp);
2127 } else {
2128 hdrlen = (*print_info->p.printer)(h, sp);
2129 }
2130
2131 if (Xflag) {
2132 /*
2133 * Print the raw packet data in hex and ASCII.
2134 */
2135 if (Xflag > 1) {
2136 /*
2137 * Include the link-layer header.
2138 */
2139 hex_and_ascii_print("\n\t", sp, h->caplen);
2140 } else {
2141 /*
2142 * Don't include the link-layer header - and if
2143 * we have nothing past the link-layer header,
2144 * print nothing.
2145 */
2146 if (h->caplen > hdrlen)
2147 hex_and_ascii_print("\n\t", sp + hdrlen,
2148 h->caplen - hdrlen);
2149 }
2150 } else if (xflag) {
2151 /*
2152 * Print the raw packet data in hex.
2153 */
2154 if (xflag > 1) {
2155 /*
2156 * Include the link-layer header.
2157 */
2158 hex_print("\n\t", sp, h->caplen);
2159 } else {
2160 /*
2161 * Don't include the link-layer header - and if
2162 * we have nothing past the link-layer header,
2163 * print nothing.
2164 */
2165 if (h->caplen > hdrlen)
2166 hex_print("\n\t", sp + hdrlen,
2167 h->caplen - hdrlen);
2168 }
2169 } else if (Aflag) {
2170 /*
2171 * Print the raw packet data in ASCII.
2172 */
2173 if (Aflag > 1) {
2174 /*
2175 * Include the link-layer header.
2176 */
2177 ascii_print(sp, h->caplen);
2178 } else {
2179 /*
2180 * Don't include the link-layer header - and if
2181 * we have nothing past the link-layer header,
2182 * print nothing.
2183 */
2184 if (h->caplen > hdrlen)
2185 ascii_print(sp + hdrlen, h->caplen - hdrlen);
2186 }
2187 }
2188
2189 putchar('\n');
2190
2191 --infodelay;
2192 if (infoprint)
2193 info(0);
2194 }
2195
2196 #ifdef WIN32
2197 /*
2198 * XXX - there should really be libpcap calls to get the version
2199 * number as a string (the string would be generated from #defines
2200 * at run time, so that it's not generated from string constants
2201 * in the library, as, on many UNIX systems, those constants would
2202 * be statically linked into the application executable image, and
2203 * would thus reflect the version of libpcap on the system on
2204 * which the application was *linked*, not the system on which it's
2205 * *running*.
2206 *
2207 * That routine should be documented, unlike the "version[]"
2208 * string, so that UNIX vendors providing their own libpcaps
2209 * don't omit it (as a couple of vendors have...).
2210 *
2211 * Packet.dll should perhaps also export a routine to return the
2212 * version number of the Packet.dll code, to supply the
2213 * "Wpcap_version" information on Windows.
2214 */
2215 char WDversion[]="current-cvs.tcpdump.org";
2216 #if !defined(HAVE_GENERATED_VERSION)
2217 char version[]="current-cvs.tcpdump.org";
2218 #endif
2219 char pcap_version[]="current-cvs.tcpdump.org";
2220 char Wpcap_version[]="3.1";
2221 #endif
2222
2223 /*
2224 * By default, print the specified data out in hex and ASCII.
2225 */
2226 static void
ndo_default_print(netdissect_options * ndo _U_,const u_char * bp,u_int length)2227 ndo_default_print(netdissect_options *ndo _U_, const u_char *bp, u_int length)
2228 {
2229 hex_and_ascii_print("\n\t", bp, length); /* pass on lf and identation string */
2230 }
2231
2232 void
default_print(const u_char * bp,u_int length)2233 default_print(const u_char *bp, u_int length)
2234 {
2235 ndo_default_print(gndo, bp, length);
2236 }
2237
2238 #ifdef SIGNAL_REQ_INFO
requestinfo(int signo _U_)2239 RETSIGTYPE requestinfo(int signo _U_)
2240 {
2241 if (infodelay)
2242 ++infoprint;
2243 else
2244 info(0);
2245 }
2246 #endif
2247
2248 /*
2249 * Called once each second in verbose mode while dumping to file
2250 */
2251 #ifdef USE_WIN32_MM_TIMER
verbose_stats_dump(UINT timer_id _U_,UINT msg _U_,DWORD_PTR arg _U_,DWORD_PTR dw1 _U_,DWORD_PTR dw2 _U_)2252 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
2253 DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
2254 {
2255 struct pcap_stat stat;
2256
2257 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
2258 fprintf(stderr, "Got %u\r", packets_captured);
2259 }
2260 #elif defined(HAVE_ALARM)
verbose_stats_dump(int sig _U_)2261 static void verbose_stats_dump(int sig _U_)
2262 {
2263 struct pcap_stat stat;
2264
2265 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
2266 fprintf(stderr, "Got %u\r", packets_captured);
2267 alarm(1);
2268 }
2269 #endif
2270
2271 static void
usage(void)2272 usage(void)
2273 {
2274 extern char version[];
2275 #ifndef HAVE_PCAP_LIB_VERSION
2276 #if defined(WIN32) || defined(HAVE_PCAP_VERSION)
2277 extern char pcap_version[];
2278 #else /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
2279 static char pcap_version[] = "unknown";
2280 #endif /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
2281 #endif /* HAVE_PCAP_LIB_VERSION */
2282
2283 #ifdef HAVE_PCAP_LIB_VERSION
2284 #ifdef WIN32
2285 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2286 #else /* WIN32 */
2287 (void)fprintf(stderr, "%s version %s\n", program_name, version);
2288 #endif /* WIN32 */
2289 (void)fprintf(stderr, "%s\n",pcap_lib_version());
2290 #else /* HAVE_PCAP_LIB_VERSION */
2291 #ifdef WIN32
2292 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2293 (void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
2294 #else /* WIN32 */
2295 (void)fprintf(stderr, "%s version %s\n", program_name, version);
2296 (void)fprintf(stderr, "libpcap version %s\n", pcap_version);
2297 #endif /* WIN32 */
2298 #endif /* HAVE_PCAP_LIB_VERSION */
2299 (void)fprintf(stderr,
2300 "Usage: %s [-aAbd" D_FLAG "efhH" I_FLAG J_FLAG "KlLnNOpqRStu" U_FLAG "vxX]" B_FLAG_USAGE " [ -c count ]\n", program_name);
2301 (void)fprintf(stderr,
2302 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
2303 (void)fprintf(stderr,
2304 "\t\t[ -i interface ]" j_FLAG_USAGE " [ -M secret ]\n");
2305 (void)fprintf(stderr,
2306 "\t\t[ -r file ] [ -s snaplen ] [ -T type ] [ -V file ] [ -w file ]\n");
2307 (void)fprintf(stderr,
2308 "\t\t[ -W filecount ] [ -y datalinktype ] [ -z command ]\n");
2309 (void)fprintf(stderr,
2310 "\t\t[ -Z user ] [ expression ]\n");
2311 exit(1);
2312 }
2313
2314
2315
2316 /* VARARGS */
2317 static void
ndo_error(netdissect_options * ndo _U_,const char * fmt,...)2318 ndo_error(netdissect_options *ndo _U_, const char *fmt, ...)
2319 {
2320 va_list ap;
2321
2322 (void)fprintf(stderr, "%s: ", program_name);
2323 va_start(ap, fmt);
2324 (void)vfprintf(stderr, fmt, ap);
2325 va_end(ap);
2326 if (*fmt) {
2327 fmt += strlen(fmt);
2328 if (fmt[-1] != '\n')
2329 (void)fputc('\n', stderr);
2330 }
2331 exit(1);
2332 /* NOTREACHED */
2333 }
2334
2335 /* VARARGS */
2336 static void
ndo_warning(netdissect_options * ndo _U_,const char * fmt,...)2337 ndo_warning(netdissect_options *ndo _U_, const char *fmt, ...)
2338 {
2339 va_list ap;
2340
2341 (void)fprintf(stderr, "%s: WARNING: ", program_name);
2342 va_start(ap, fmt);
2343 (void)vfprintf(stderr, fmt, ap);
2344 va_end(ap);
2345 if (*fmt) {
2346 fmt += strlen(fmt);
2347 if (fmt[-1] != '\n')
2348 (void)fputc('\n', stderr);
2349 }
2350 }
2351