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