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