]> The Tcpdump Group git mirrors - tcpdump/blob - tcpdump.c
Add support for Apple's IP-over-IEEE 1394 encapsulation.
[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.235 2004-03-17 19:40:42 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 <pwd.h>
69 #include <grp.h>
70
71 #include "interface.h"
72 #include "addrtoname.h"
73 #include "machdep.h"
74 #include "setsignal.h"
75 #include "gmt2local.h"
76 #include "pcap-missing.h"
77
78 int dflag; /* print filter code */
79 int eflag; /* print ethernet header */
80 int fflag; /* don't translate "foreign" IP address */
81 static int Lflag; /* list available data link types and exit */
82 int nflag; /* leave addresses as numbers */
83 int Nflag; /* remove domains from printed host names */
84 static int Oflag = 1; /* run filter code optimizer */
85 static int pflag; /* don't go promiscuous */
86 int qflag; /* quick (shorter) output */
87 int Rflag = 1; /* print sequence # field in AH/ESP*/
88 int sflag = 0; /* use the libsmi to translate OIDs */
89 int Sflag; /* print raw TCP sequence numbers */
90 int tflag = 1; /* print packet arrival time */
91 int Uflag = 0; /* "unbuffered" output of dump files */
92 int uflag = 0; /* Print undecoded NFS handles */
93 int vflag; /* verbose */
94 int xflag; /* print packet in hex */
95 int Xflag; /* print packet in ascii as well as hex */
96 static off_t Cflag = 0; /* rotate dump files after this many bytes */
97 int Aflag = 0; /* print packet only in ascii observing LF, CR, TAB, SPACE */
98 static int dlt = -1; /* if != -1, ask libpcap for the DLT it names */
99 static int Cflag_count = 0; /* Keep track of which file number we're writing */
100 static int Wflag = 0; /* recycle output files after this number of files */
101 static int WflagChars = 0;
102
103 /*
104 * Define the maximum number of files for the -C flag, and how many
105 * characters can be added to a filename for the -C flag (which
106 * should be enough to handle MAX_CFLAG - 1).
107 */
108 #define MAX_CFLAG 1000000
109 #define MAX_CFLAG_CHARS 6
110
111 const char *dlt_name = NULL;
112
113 char *espsecret = NULL; /* ESP secret key */
114
115 int packettype;
116
117 static int infodelay;
118 static int infoprint;
119
120 char *program_name;
121
122 int32_t thiszone; /* seconds offset from gmt to local time */
123
124 /* Forwards */
125 static RETSIGTYPE cleanup(int);
126 static void usage(void) __attribute__((noreturn));
127 static void show_dlts_and_exit(pcap_t *pd) __attribute__((noreturn));
128
129 static void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
130 static void dump_packet_and_trunc(u_char *, const struct pcap_pkthdr *, const u_char *);
131 static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
132 static void droproot(const char *, const char *);
133
134 #ifdef SIGINFO
135 RETSIGTYPE requestinfo(int);
136 #endif
137
138 #if defined(USE_WIN32_MM_TIMER)
139 #include <MMsystem.h>
140 static UINT timer_id;
141 static void CALLBACK verbose_stats_dump(UINT, UINT, DWORD_PTR, DWORD_PTR, DWORD_PTR);
142 #elif defined(HAVE_ALARM)
143 static void verbose_stats_dump(int sig);
144 #endif
145
146 static void info(int);
147 static u_int packets_captured;
148
149 /* Length of saved portion of packet. */
150 int snaplen = DEFAULT_SNAPLEN;
151
152 typedef u_int (*if_printer)(const struct pcap_pkthdr *, const u_char *);
153
154 struct printer {
155 if_printer f;
156 int type;
157 };
158
159 static struct printer printers[] = {
160 { arcnet_if_print, DLT_ARCNET },
161 #ifdef DLT_ARCNET_LINUX
162 { arcnet_linux_if_print, DLT_ARCNET_LINUX },
163 #endif
164 { ether_if_print, DLT_EN10MB },
165 { token_if_print, DLT_IEEE802 },
166 #ifdef DLT_LANE8023
167 { lane_if_print, DLT_LANE8023 },
168 #endif
169 #ifdef DLT_CIP
170 { cip_if_print, DLT_CIP },
171 #endif
172 #ifdef DLT_ATM_CLIP
173 { cip_if_print, DLT_ATM_CLIP },
174 #endif
175 { sl_if_print, DLT_SLIP },
176 #ifdef DLT_SLIP_BSDOS
177 { sl_bsdos_if_print, DLT_SLIP_BSDOS },
178 #endif
179 { ppp_if_print, DLT_PPP },
180 #ifdef DLT_PPP_BSDOS
181 { ppp_bsdos_if_print, DLT_PPP_BSDOS },
182 #endif
183 { fddi_if_print, DLT_FDDI },
184 { null_if_print, DLT_NULL },
185 #ifdef DLT_LOOP
186 { null_if_print, DLT_LOOP },
187 #endif
188 { raw_if_print, DLT_RAW },
189 { atm_if_print, DLT_ATM_RFC1483 },
190 #ifdef DLT_C_HDLC
191 { chdlc_if_print, DLT_C_HDLC },
192 #endif
193 #ifdef DLT_HDLC
194 { chdlc_if_print, DLT_HDLC },
195 #endif
196 #ifdef DLT_PPP_SERIAL
197 { ppp_hdlc_if_print, DLT_PPP_SERIAL },
198 #endif
199 #ifdef DLT_PPP_ETHER
200 { pppoe_if_print, DLT_PPP_ETHER },
201 #endif
202 #ifdef DLT_LINUX_SLL
203 { sll_if_print, DLT_LINUX_SLL },
204 #endif
205 #ifdef DLT_IEEE802_11
206 { ieee802_11_if_print, DLT_IEEE802_11},
207 #endif
208 #ifdef DLT_LTALK
209 { ltalk_if_print, DLT_LTALK },
210 #endif
211 #ifdef DLT_PFLOG
212 { pflog_if_print, DLT_PFLOG },
213 #endif
214 #ifdef DLT_FR
215 { fr_if_print, DLT_FR },
216 #endif
217 #ifdef DLT_FRELAY
218 { fr_if_print, DLT_FRELAY },
219 #endif
220 #ifdef DLT_SUNATM
221 { sunatm_if_print, DLT_SUNATM },
222 #endif
223 #ifdef DLT_IP_OVER_FC
224 { ipfc_if_print, DLT_IP_OVER_FC },
225 #endif
226 #ifdef DLT_PRISM_HEADER
227 { prism_if_print, DLT_PRISM_HEADER },
228 #endif
229 #ifdef DLT_IEEE802_11_RADIO
230 { ieee802_11_radio_if_print, DLT_IEEE802_11_RADIO },
231 #endif
232 #ifdef DLT_ENC
233 { enc_if_print, DLT_ENC },
234 #endif
235 #ifdef DLT_SYMANTEC_FIREWALL
236 { symantec_if_print, DLT_SYMANTEC_FIREWALL },
237 #endif
238 #ifdef DLT_APPLE_IP_OVER_IEEE1394
239 { ap1394_if_print, DLT_APPLE_IP_OVER_IEEE1394 },
240 #endif
241 { NULL, 0 },
242 };
243
244 static if_printer
245 lookup_printer(int type)
246 {
247 struct printer *p;
248
249 for (p = printers; p->f; ++p)
250 if (type == p->type)
251 return p->f;
252
253 return NULL;
254 /* NOTREACHED */
255 }
256
257 static pcap_t *pd;
258
259 extern int optind;
260 extern int opterr;
261 extern char *optarg;
262
263 struct print_info {
264 if_printer printer;
265 };
266
267 struct dump_info {
268 char *WFileName;
269 pcap_t *pd;
270 pcap_dumper_t *p;
271 };
272
273 static void
274 show_dlts_and_exit(pcap_t *pd)
275 {
276 int n_dlts;
277 int *dlts = 0;
278 const char *dlt_name;
279
280 n_dlts = pcap_list_datalinks(pd, &dlts);
281 if (n_dlts < 0)
282 error("%s", pcap_geterr(pd));
283 else if (n_dlts == 0 || !dlts)
284 error("No data link types.");
285
286 (void) fprintf(stderr, "Data link types (use option -y to set):\n");
287
288 while (--n_dlts >= 0) {
289 dlt_name = pcap_datalink_val_to_name(dlts[n_dlts]);
290 if (dlt_name != NULL) {
291 (void) fprintf(stderr, " %s (%s)", dlt_name,
292 pcap_datalink_val_to_description(dlts[n_dlts]));
293
294 /*
295 * OK, does tcpdump handle that type?
296 */
297 if (lookup_printer(dlts[n_dlts]) == NULL)
298 (void) fprintf(stderr, " (not supported)");
299 putchar('\n');
300 } else {
301 (void) fprintf(stderr, " DLT %d (not supported)\n",
302 dlts[n_dlts]);
303 }
304 }
305 free(dlts);
306 exit(0);
307 }
308
309 /*
310 * Set up flags that might or might not be supported depending on the
311 * version of libpcap we're using.
312 */
313 #ifdef WIN32
314 #define B_FLAG "B:"
315 #define B_FLAG_USAGE " [ -B size ]"
316 #else /* WIN32 */
317 #define B_FLAG
318 #define B_FLAG_USAGE
319 #endif /* WIN32 */
320
321 #ifdef HAVE_PCAP_FINDALLDEVS
322 #define D_FLAG "D"
323 #else
324 #define D_FLAG
325 #endif
326
327 #ifdef HAVE_PCAP_DUMP_FLUSH
328 #define U_FLAG "U"
329 #else
330 #define U_FLAG
331 #endif
332
333 /* Drop root privileges and chroot if necessary */
334 static void
335 droproot(const char *username, const char *chroot_dir)
336 {
337 struct passwd *pw = NULL;
338
339 if (chroot_dir && !username) {
340 fprintf(stderr, "Chroot without dropping root is insecure\n");
341 exit(1);
342 }
343
344 pw = getpwnam(username);
345 if (pw) {
346 if (chroot_dir) {
347 if (chroot(chroot_dir) != 0 || chdir ("/") != 0) {
348 fprintf(stderr, "Couldn't chroot/chdir to '%.64s'\n", chroot_dir);
349 exit(1);
350 }
351 }
352 if (initgroups(pw->pw_name, pw->pw_gid) != 0 || setgid(pw->pw_gid) != 0 ||
353 setuid(pw->pw_uid) != 0) {
354 fprintf(stderr, "Couldn't change to '%.32s' uid=%d gid=%d\n", username,
355 pw->pw_uid, pw->pw_gid);
356 exit(1);
357 }
358 }
359 else {
360 fprintf(stderr, "Couldn't find user '%.32s'\n", username);
361 exit(1);
362 }
363 }
364
365 static int
366 getWflagChars(int x)
367 {
368 int c = 0;
369
370 x -= 1;
371 while (x > 0) {
372 c += 1;
373 x /= 10;
374 }
375
376 return c;
377 }
378
379
380 static void
381 MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
382 {
383 if (cnt == 0 && max_chars == 0)
384 strcpy(buffer, orig_name);
385 else
386 sprintf(buffer, "%s%0*d", orig_name, max_chars, cnt);
387 }
388
389 int
390 main(int argc, char **argv)
391 {
392 register int cnt, op, i;
393 bpf_u_int32 localnet, netmask;
394 register char *cp, *infile, *cmdbuf, *device, *RFileName, *WFileName, *WFileNameAlt;
395 pcap_handler callback;
396 int type;
397 struct bpf_program fcode;
398 #ifndef WIN32
399 RETSIGTYPE (*oldhandler)(int);
400 #endif
401 struct print_info printinfo;
402 struct dump_info dumpinfo;
403 u_char *pcap_userdata;
404 char ebuf[PCAP_ERRBUF_SIZE];
405 char *username = NULL;
406 char *chroot_dir = NULL;
407 #ifdef HAVE_PCAP_FINDALLDEVS
408 pcap_if_t *devpointer;
409 int devnum;
410 #endif
411 int status;
412 #ifdef WIN32
413 u_int UserBufferSize = 1000000;
414 if(wsockinit() != 0) return 1;
415 #endif /* WIN32 */
416
417 cnt = -1;
418 device = NULL;
419 infile = NULL;
420 RFileName = NULL;
421 WFileName = NULL;
422 if ((cp = strrchr(argv[0], '/')) != NULL)
423 program_name = cp + 1;
424 else
425 program_name = argv[0];
426
427 if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
428 error("%s", ebuf);
429
430 #ifdef LIBSMI
431 smiInit("tcpdump");
432 #endif
433
434 opterr = 0;
435 while (
436 (op = getopt(argc, argv, "aA" B_FLAG "c:C:d" D_FLAG "eE:fF:i:lLm:nNOpqr:Rs:StT:u" U_FLAG "vw:W:xXy:YZ:")) != -1)
437 switch (op) {
438
439 case 'a':
440 /* compatibility for old -a */
441 break;
442
443 case 'A':
444 ++xflag;
445 ++Xflag;
446 ++Aflag;
447 break;
448
449 #ifdef WIN32
450 case 'B':
451 UserBufferSize = atoi(optarg)*1024;
452 if (UserBufferSize < 0)
453 error("invalid packet buffer size %s", optarg);
454 break;
455 #endif /* WIN32 */
456
457 case 'c':
458 cnt = atoi(optarg);
459 if (cnt <= 0)
460 error("invalid packet count %s", optarg);
461 break;
462
463 case 'C':
464 Cflag = atoi(optarg) * 1000000;
465 if (Cflag < 0)
466 error("invalid file size %s", optarg);
467 break;
468
469 case 'd':
470 ++dflag;
471 break;
472
473 #ifdef HAVE_PCAP_FINDALLDEVS
474 case 'D':
475 if (pcap_findalldevs(&devpointer, ebuf) < 0)
476 error("%s", ebuf);
477 else {
478 for (i = 0; devpointer != 0; i++) {
479 printf("%d.%s", i+1, devpointer->name);
480 if (devpointer->description != NULL)
481 printf(" (%s)", devpointer->description);
482 printf("\n");
483 devpointer = devpointer->next;
484 }
485 }
486 return 0;
487 #endif /* HAVE_PCAP_FINDALLDEVS */
488
489 case 'L':
490 Lflag++;
491 break;
492
493 case 'e':
494 ++eflag;
495 break;
496
497 case 'E':
498 #ifndef HAVE_LIBCRYPTO
499 warning("crypto code not compiled in");
500 #endif
501 espsecret = optarg;
502 break;
503
504 case 'f':
505 ++fflag;
506 break;
507
508 case 'F':
509 infile = optarg;
510 break;
511
512 case 'i':
513 if (optarg[0] == '0' && optarg[1] == 0)
514 error("Invalid adapter index");
515
516 #ifdef HAVE_PCAP_FINDALLDEVS
517 /*
518 * If the argument is a number, treat it as
519 * an index into the list of adapters, as
520 * printed by "tcpdump -D".
521 *
522 * This should be OK on UNIX systems, as interfaces
523 * shouldn't have names that begin with digits.
524 * It can be useful on Windows, where more than
525 * one interface can have the same name.
526 */
527 if ((devnum = atoi(optarg)) != 0) {
528 if (devnum < 0)
529 error("Invalid adapter index");
530
531 if (pcap_findalldevs(&devpointer, ebuf) < 0)
532 error("%s", ebuf);
533 else {
534 for (i = 0; i < devnum-1; i++){
535 devpointer = devpointer->next;
536 if (devpointer == NULL)
537 error("Invalid adapter index");
538 }
539 }
540 device = devpointer->name;
541 break;
542 }
543 #endif /* HAVE_PCAP_FINDALLDEVS */
544 device = optarg;
545 break;
546
547 case 'l':
548 #ifdef WIN32
549 /*
550 * _IOLBF is the same as _IOFBF in Microsoft's C
551 * libraries; the only alternative they offer
552 * is _IONBF.
553 *
554 * XXX - this should really be checking for MSVC++,
555 * not WIN32, if, for example, MinGW has its own
556 * C library that is more UNIX-compatible.
557 */
558 setvbuf(stdout, NULL, _IONBF, 0);
559 #else /* WIN32 */
560 #ifdef HAVE_SETLINEBUF
561 setlinebuf(stdout);
562 #else
563 setvbuf(stdout, NULL, _IOLBF, 0);
564 #endif
565 #endif /* WIN32 */
566 break;
567
568 case 'n':
569 ++nflag;
570 break;
571
572 case 'N':
573 ++Nflag;
574 break;
575
576 case 'm':
577 #ifdef LIBSMI
578 if (smiLoadModule(optarg) == 0) {
579 error("could not load MIB module %s", optarg);
580 }
581 sflag = 1;
582 #else
583 (void)fprintf(stderr, "%s: ignoring option `-m %s' ",
584 program_name, optarg);
585 (void)fprintf(stderr, "(no libsmi support)\n");
586 #endif
587 break;
588
589 case 'O':
590 Oflag = 0;
591 break;
592
593 case 'p':
594 ++pflag;
595 break;
596
597 case 'q':
598 ++qflag;
599 break;
600
601 case 'r':
602 RFileName = optarg;
603 break;
604
605 case 'R':
606 Rflag = 0;
607 break;
608
609 case 's': {
610 char *end;
611
612 snaplen = strtol(optarg, &end, 0);
613 if (optarg == end || *end != '\0'
614 || snaplen < 0 || snaplen > 65535)
615 error("invalid snaplen %s", optarg);
616 else if (snaplen == 0)
617 snaplen = 65535;
618 break;
619 }
620
621 case 'S':
622 ++Sflag;
623 break;
624
625 case 't':
626 --tflag;
627 break;
628
629 case 'T':
630 if (strcasecmp(optarg, "vat") == 0)
631 packettype = PT_VAT;
632 else if (strcasecmp(optarg, "wb") == 0)
633 packettype = PT_WB;
634 else if (strcasecmp(optarg, "rpc") == 0)
635 packettype = PT_RPC;
636 else if (strcasecmp(optarg, "rtp") == 0)
637 packettype = PT_RTP;
638 else if (strcasecmp(optarg, "rtcp") == 0)
639 packettype = PT_RTCP;
640 else if (strcasecmp(optarg, "snmp") == 0)
641 packettype = PT_SNMP;
642 else if (strcasecmp(optarg, "cnfp") == 0)
643 packettype = PT_CNFP;
644 else if (strcasecmp(optarg, "tftp") == 0)
645 packettype = PT_TFTP;
646 else if (strcasecmp(optarg, "aodv") == 0)
647 packettype = PT_AODV;
648 else
649 error("unknown packet type `%s'", optarg);
650 break;
651
652 case 'u':
653 ++uflag;
654 break;
655
656 #ifdef HAVE_PCAP_DUMP_FLUSH
657 case 'U':
658 ++Uflag;
659 break;
660 #endif
661
662 case 'v':
663 ++vflag;
664 break;
665
666 case 'w':
667 WFileName = optarg;
668 break;
669
670 case 'W':
671 Wflag = atoi(optarg);
672 if (Wflag < 0)
673 error("invalid number of output files %s", optarg);
674 WflagChars = getWflagChars(Wflag);
675 break;
676
677 case 'x':
678 ++xflag;
679 break;
680
681 case 'X':
682 ++xflag;
683 ++Xflag;
684 break;
685
686 case 'y':
687 dlt_name = optarg;
688 dlt = pcap_datalink_name_to_val(dlt_name);
689 if (dlt < 0)
690 error("invalid data link type %s", dlt_name);
691 break;
692
693 #if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
694 case 'Y':
695 {
696 /* Undocumented flag */
697 #ifdef HAVE_PCAP_DEBUG
698 extern int pcap_debug;
699 pcap_debug = 1;
700 #else
701 extern int yydebug;
702 yydebug = 1;
703 #endif
704 }
705 break;
706 #endif
707 case 'Z':
708 if (optarg) {
709 username = strdup(optarg);
710 }
711 else {
712 usage();
713 /* NOTREACHED */
714 }
715 break;
716
717 default:
718 usage();
719 /* NOTREACHED */
720 }
721
722 if (tflag > 0)
723 thiszone = gmt2local(0);
724
725 #ifdef WITH_CHROOT
726 /* if run as root, prepare for chrooting */
727 if (getuid() == 0 || geteuid() == 0) {
728 /* future extensibility for cmd-line arguments */
729 if (!chroot_dir)
730 chroot_dir = WITH_CHROOT;
731 }
732 #endif
733
734 #ifdef WITH_USER
735 /* if run as root, prepare for dropping root privileges */
736 if (getuid() == 0 || geteuid() == 0) {
737 /* Run with '-Z root' to restore old behaviour */
738 if (!username)
739 username = WITH_USER;
740 }
741 #endif
742
743 if (RFileName != NULL) {
744 int dlt;
745 const char *dlt_name;
746
747 #ifndef WIN32
748 /*
749 * We don't need network access, so relinquish any set-UID
750 * or set-GID privileges we have (if any).
751 *
752 * We do *not* want set-UID privileges when opening a
753 * trace file, as that might let the user read other
754 * people's trace files (especially if we're set-UID
755 * root).
756 */
757 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
758 fprintf(stderr, "Warning: setgid/setuid failed !\n");
759 #endif /* WIN32 */
760 pd = pcap_open_offline(RFileName, ebuf);
761 if (pd == NULL)
762 error("%s", ebuf);
763 dlt = pcap_datalink(pd);
764 dlt_name = pcap_datalink_val_to_name(dlt);
765 if (dlt_name == NULL) {
766 fprintf(stderr, "reading from file %s, link-type %u\n",
767 RFileName, dlt);
768 } else {
769 fprintf(stderr,
770 "reading from file %s, link-type %s (%s)\n",
771 RFileName, dlt_name,
772 pcap_datalink_val_to_description(dlt));
773 }
774 localnet = 0;
775 netmask = 0;
776 if (fflag != 0)
777 error("-f and -r options are incompatible");
778 } else {
779 if (device == NULL) {
780 device = pcap_lookupdev(ebuf);
781 if (device == NULL)
782 error("%s", ebuf);
783 }
784 #ifdef WIN32
785 if(IsTextUnicode(device,
786 wcslen((short*)device), // Device always ends with a double \0, so this way to determine its
787 // length should be always valid
788 NULL))
789 {
790 fprintf(stderr, "%s: listening on %ws\n", program_name, device);
791 }
792 else
793 {
794 fprintf(stderr, "%s: listening on %s\n", program_name, device);
795 }
796
797 fflush(stderr);
798 #endif /* WIN32 */
799 *ebuf = '\0';
800 pd = pcap_open_live(device, snaplen, !pflag, 1000, ebuf);
801 if (pd == NULL)
802 error("%s", ebuf);
803 else if (*ebuf)
804 warning("%s", ebuf);
805 /*
806 * Let user own process after socket has been opened.
807 */
808 #ifndef WIN32
809 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
810 fprintf(stderr, "Warning: setgid/setuid failed !\n");
811 #endif /* WIN32 */
812 #ifdef WIN32
813 if(UserBufferSize != 1000000)
814 if(pcap_setbuff(pd, UserBufferSize)==-1){
815 error("%s", pcap_geterr(pd));
816 }
817 #endif /* WIN32 */
818 if (Lflag)
819 show_dlts_and_exit(pd);
820 if (dlt >= 0) {
821 #ifdef HAVE_PCAP_SET_DATALINK
822 if (pcap_set_datalink(pd, dlt) < 0)
823 error("%s", pcap_geterr(pd));
824 #else
825 /*
826 * We don't actually support changing the
827 * data link type, so we only let them
828 * set it to what it already is.
829 */
830 if (dlt != pcap_datalink(pd)) {
831 error("%s is not one of the DLTs supported by this device\n",
832 dlt_name);
833 }
834 #endif
835 (void)fprintf(stderr, "%s: data link type %s\n",
836 program_name, dlt_name);
837 (void)fflush(stderr);
838 }
839 i = pcap_snapshot(pd);
840 if (snaplen < i) {
841 warning("snaplen raised from %d to %d", snaplen, i);
842 snaplen = i;
843 }
844 if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
845 localnet = 0;
846 netmask = 0;
847 warning("%s", ebuf);
848 }
849 }
850 if (infile)
851 cmdbuf = read_infile(infile);
852 else
853 cmdbuf = copy_argv(&argv[optind]);
854
855 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
856 error("%s", pcap_geterr(pd));
857 if (dflag) {
858 bpf_dump(&fcode, dflag);
859 pcap_close(pd);
860 exit(0);
861 }
862 init_addrtoname(localnet, netmask);
863
864 #ifndef WIN32
865 (void)setsignal(SIGPIPE, cleanup);
866 #endif /* WIN32 */
867 (void)setsignal(SIGTERM, cleanup);
868 (void)setsignal(SIGINT, cleanup);
869 /* Cooperate with nohup(1) */
870 #ifndef WIN32
871 if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
872 (void)setsignal(SIGHUP, oldhandler);
873 #endif /* WIN32 */
874
875 if (pcap_setfilter(pd, &fcode) < 0)
876 error("%s", pcap_geterr(pd));
877 if (WFileName) {
878 pcap_dumper_t *p;
879
880 WFileNameAlt = (char *)malloc(strlen(WFileName) + MAX_CFLAG_CHARS + 1);
881 if (WFileNameAlt == NULL)
882 error("malloc of WFileNameAlt");
883 MakeFilename(WFileNameAlt, WFileName, 0, WflagChars);
884 p = pcap_dump_open(pd, WFileNameAlt);
885 if (p == NULL)
886 error("%s", pcap_geterr(pd));
887 if (Cflag != 0) {
888 callback = dump_packet_and_trunc;
889 dumpinfo.WFileName = WFileName;
890 dumpinfo.pd = pd;
891 dumpinfo.p = p;
892 pcap_userdata = (u_char *)&dumpinfo;
893 } else {
894 callback = dump_packet;
895 pcap_userdata = (u_char *)p;
896 }
897 } else {
898 type = pcap_datalink(pd);
899 printinfo.printer = lookup_printer(type);
900 if (printinfo.printer == NULL) {
901 dlt_name = pcap_datalink_val_to_name(type);
902 if (dlt_name != NULL)
903 error("unsupported data link type %s", dlt_name);
904 else
905 error("unsupported data link type %d", type);
906 }
907 callback = print_packet;
908 pcap_userdata = (u_char *)&printinfo;
909 }
910 #ifndef WIN32
911 /*
912 * We cannot do this earlier, because we want to be able to open
913 * the file (if done) for writing before giving up permissions.
914 */
915 if (getuid() == 0 || geteuid() == 0) {
916 if (username || chroot_dir)
917 droproot(username, chroot_dir);
918 }
919 #endif /* WIN32 */
920 #ifdef SIGINFO
921 (void)setsignal(SIGINFO, requestinfo);
922 #endif
923
924 if (vflag > 0 && WFileName) {
925 /*
926 * When capturing to a file, "-v" means tcpdump should,
927 * every 10 secodns, "v"erbosely report the number of
928 * packets captured.
929 */
930 #ifdef USE_WIN32_MM_TIMER
931 /* call verbose_stats_dump() each 1000 +/-100msec */
932 timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
933 setvbuf(stderr, NULL, _IONBF, 0);
934 #elif defined(HAVE_ALARM)
935 (void)setsignal(SIGALRM, verbose_stats_dump);
936 alarm(1);
937 #endif
938 }
939
940 #ifndef WIN32
941 if (RFileName == NULL) {
942 int dlt;
943 const char *dlt_name;
944
945 if (!vflag && !WFileName) {
946 (void)fprintf(stderr,
947 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
948 program_name);
949 } else
950 (void)fprintf(stderr, "%s: ", program_name);
951 dlt = pcap_datalink(pd);
952 dlt_name = pcap_datalink_val_to_name(dlt);
953 if (dlt_name == NULL) {
954 (void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
955 device, dlt, snaplen);
956 } else {
957 (void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
958 device, dlt_name,
959 pcap_datalink_val_to_description(dlt), snaplen);
960 }
961 (void)fflush(stderr);
962 }
963 #endif /* WIN32 */
964 status = pcap_loop(pd, cnt, callback, pcap_userdata);
965 if (WFileName == NULL) {
966 /*
967 * We're printing packets. Flush the printed output,
968 * so it doesn't get intermingled with error output.
969 */
970 if (status == -2) {
971 /*
972 * We got interrupted, so perhaps we didn't
973 * manage to finish a line we were printing.
974 * Print an extra newline, just in case.
975 */
976 putchar('\n');
977 }
978 (void)fflush(stdout);
979 }
980 if (status == -1) {
981 /*
982 * Error. Report it.
983 */
984 (void)fprintf(stderr, "%s: pcap_loop: %s\n",
985 program_name, pcap_geterr(pd));
986 }
987 if (RFileName == NULL) {
988 /*
989 * We're doing a live capture. Report the capture
990 * statistics.
991 */
992 info(1);
993 }
994 pcap_close(pd);
995 exit(status == -1 ? 1 : 0);
996 }
997
998 /* make a clean exit on interrupts */
999 static RETSIGTYPE
1000 cleanup(int signo _U_)
1001 {
1002 #ifdef USE_WIN32_MM_TIMER
1003 if (timer_id)
1004 timeKillEvent(timer_id);
1005 timer_id = 0;
1006 #elif defined(HAVE_ALARM)
1007 alarm(0);
1008 #endif
1009
1010 #ifdef HAVE_PCAP_BREAKLOOP
1011 /*
1012 * We have "pcap_breakloop()"; use it, so that we do as little
1013 * as possible in the signal handler (it's probably not safe
1014 * to do anything with standard I/O streams in a signal handler -
1015 * the ANSI C standard doesn't say it is).
1016 */
1017 pcap_breakloop(pd);
1018 #else
1019 /*
1020 * We don't have "pcap_breakloop()"; this isn't safe, but
1021 * it's the best we can do. Print the summary if we're
1022 * not reading from a savefile - i.e., if we're doing a
1023 * live capture - and exit.
1024 */
1025 if (pd != NULL && pcap_file(pd) == NULL) {
1026 /*
1027 * We got interrupted, so perhaps we didn't
1028 * manage to finish a line we were printing.
1029 * Print an extra newline, just in case.
1030 */
1031 putchar('\n');
1032 (void)fflush(stdout);
1033 info(1);
1034 }
1035 exit(0);
1036 #endif
1037 }
1038
1039 static void
1040 info(register int verbose)
1041 {
1042 struct pcap_stat stat;
1043
1044 if (pcap_stats(pd, &stat) < 0) {
1045 (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
1046 return;
1047 }
1048
1049 if (!verbose)
1050 fprintf(stderr, "%s: ", program_name);
1051
1052 (void)fprintf(stderr, "%u packets captured", packets_captured);
1053 if (!verbose)
1054 fputs(", ", stderr);
1055 else
1056 putc('\n', stderr);
1057 (void)fprintf(stderr, "%d packets received by filter", stat.ps_recv);
1058 if (!verbose)
1059 fputs(", ", stderr);
1060 else
1061 putc('\n', stderr);
1062 (void)fprintf(stderr, "%d packets dropped by kernel\n", stat.ps_drop);
1063 infoprint = 0;
1064 }
1065
1066 static void
1067 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1068 {
1069 struct dump_info *dump_info;
1070 char *name;
1071
1072 ++packets_captured;
1073
1074 ++infodelay;
1075
1076 dump_info = (struct dump_info *)user;
1077
1078 /*
1079 * XXX - this won't prevent capture files from getting
1080 * larger than Cflag - the last packet written to the
1081 * file could put it over Cflag.
1082 */
1083 if (ftell((FILE *)dump_info->p) > Cflag) {
1084 /*
1085 * Close the current file and open a new one.
1086 */
1087 pcap_dump_close(dump_info->p);
1088 Cflag_count++;
1089 if (Wflag > 0) {
1090 if (Cflag_count >= Wflag)
1091 Cflag_count = 0;
1092 } else {
1093 if (Cflag_count >= MAX_CFLAG)
1094 error("too many output files");
1095 }
1096 name = (char *)malloc(strlen(dump_info->WFileName) + MAX_CFLAG_CHARS + 1);
1097 if (name == NULL)
1098 error("dump_packet_and_trunc: malloc");
1099 MakeFilename(name, dump_info->WFileName, Cflag_count, WflagChars);
1100 dump_info->p = pcap_dump_open(dump_info->pd, name);
1101 free(name);
1102 if (dump_info->p == NULL)
1103 error("%s", pcap_geterr(pd));
1104 }
1105
1106 pcap_dump((u_char *)dump_info->p, h, sp);
1107 #ifdef HAVE_PCAP_DUMP_FLUSH
1108 if (Uflag)
1109 pcap_dump_flush(dump_info->p);
1110 #endif
1111
1112 --infodelay;
1113 if (infoprint)
1114 info(0);
1115 }
1116
1117 static void
1118 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1119 {
1120 ++packets_captured;
1121
1122 ++infodelay;
1123
1124 pcap_dump(user, h, sp);
1125 #ifdef HAVE_PCAP_DUMP_FLUSH
1126 if (Uflag)
1127 pcap_dump_flush((pcap_dumper_t *)user);
1128 #endif
1129
1130 --infodelay;
1131 if (infoprint)
1132 info(0);
1133 }
1134
1135 static void
1136 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1137 {
1138 struct print_info *print_info;
1139 u_int hdrlen;
1140
1141 ++packets_captured;
1142
1143 ++infodelay;
1144 ts_print(&h->ts);
1145
1146 print_info = (struct print_info *)user;
1147
1148 /*
1149 * Some printers want to check that they're not walking off the
1150 * end of the packet.
1151 * Rather than pass it all the way down, we set this global.
1152 */
1153 snapend = sp + h->caplen;
1154
1155 hdrlen = (*print_info->printer)(h, sp);
1156 if (xflag) {
1157 /*
1158 * Print the raw packet data.
1159 */
1160 if (xflag > 1) {
1161 /*
1162 * Include the link-layer header.
1163 */
1164 default_print(sp, h->caplen);
1165 } else {
1166 /*
1167 * Don't include the link-layer header - and if
1168 * we have nothing past the link-layer header,
1169 * print nothing.
1170 */
1171 if (h->caplen > hdrlen)
1172 default_print(sp + hdrlen,
1173 h->caplen - hdrlen);
1174 }
1175 }
1176
1177 putchar('\n');
1178
1179 --infodelay;
1180 if (infoprint)
1181 info(0);
1182 }
1183
1184 #ifdef WIN32
1185 /*
1186 * XXX - there should really be libpcap calls to get the version
1187 * number as a string (the string would be generated from #defines
1188 * at run time, so that it's not generated from string constants
1189 * in the library, as, on many UNIX systems, those constants would
1190 * be statically linked into the application executable image, and
1191 * would thus reflect the version of libpcap on the system on
1192 * which the application was *linked*, not the system on which it's
1193 * *running*.
1194 *
1195 * That routine should be documented, unlike the "version[]"
1196 * string, so that UNIX vendors providing their own libpcaps
1197 * don't omit it (as a couple of vendors have...).
1198 *
1199 * Packet.dll should perhaps also export a routine to return the
1200 * version number of the Packet.dll code, to supply the
1201 * "Wpcap_version" information on Windows.
1202 */
1203 char WDversion[]="current-cvs.tcpdump.org";
1204 #if !defined(HAVE_GENERATED_VERSION)
1205 char version[]="current-cvs.tcpdump.org";
1206 #endif
1207 char pcap_version[]="current-cvs.tcpdump.org";
1208 char Wpcap_version[]="3.0 alpha";
1209 #endif
1210
1211 /*
1212 * By default, print the specified data out in hex.
1213 */
1214 void
1215 default_print(register const u_char *bp, register u_int length)
1216 {
1217 ascii_print("\n\t", bp, length); /* pass on lf and identation string */
1218 }
1219
1220 #ifdef SIGINFO
1221 RETSIGTYPE requestinfo(int signo _U_)
1222 {
1223 if (infodelay)
1224 ++infoprint;
1225 else
1226 info(0);
1227 }
1228 #endif
1229
1230 /*
1231 * Called once each second in verbose mode while dumping to file
1232 */
1233 #ifdef USE_WIN32_MM_TIMER
1234 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
1235 DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
1236 {
1237 struct pcap_stat stat;
1238
1239 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
1240 fprintf(stderr, "Got %u\r", packets_captured);
1241 }
1242 #elif defined(HAVE_ALARM)
1243 static void verbose_stats_dump(int sig _U_)
1244 {
1245 struct pcap_stat stat;
1246
1247 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
1248 fprintf(stderr, "Got %u\r", packets_captured);
1249 alarm(1);
1250 }
1251 #endif
1252
1253 static void
1254 usage(void)
1255 {
1256 extern char version[];
1257 #ifndef HAVE_PCAP_LIB_VERSION
1258 #if defined(WIN32) || defined(HAVE_PCAP_VERSION)
1259 extern char pcap_version[];
1260 #else /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
1261 static char pcap_version[] = "unknown";
1262 #endif /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
1263 #endif /* HAVE_PCAP_LIB_VERSION */
1264
1265 #ifdef HAVE_PCAP_LIB_VERSION
1266 (void)fprintf(stderr, "%s version %s\n", program_name, version);
1267 (void)fprintf(stderr, "%s\n", pcap_lib_version());
1268 #else /* HAVE_PCAP_LIB_VERSION */
1269 #ifdef WIN32
1270 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
1271 (void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
1272 #else /* WIN32 */
1273 (void)fprintf(stderr, "%s version %s\n", program_name, version);
1274 (void)fprintf(stderr, "libpcap version %s\n", pcap_version);
1275 #endif /* WIN32 */
1276 #endif /* HAVE_PCAP_LIB_VERSION */
1277 (void)fprintf(stderr,
1278 "Usage: %s [-aAd" D_FLAG "eflLnNOpqRStu" U_FLAG "vxX]" B_FLAG_USAGE " [-c count] [ -C file_size ]\n", program_name);
1279 (void)fprintf(stderr,
1280 "\t\t[ -E algo:secret ] [ -F file ] [ -i interface ] [ -r file ]\n");
1281 (void)fprintf(stderr,
1282 "\t\t[ -s snaplen ] [ -T type ] [ -w file ] [ -W filecount ]\n");
1283 (void)fprintf(stderr,
1284 "\t\t[ -y datalinktype ] [ -Z user ]\n");
1285 (void)fprintf(stderr,
1286 "\t\t[ expression ]\n");
1287 exit(1);
1288 }