]> The Tcpdump Group git mirrors - tcpdump/blob - tcpdump.c
Add bounds checking.
[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.238 2004-03-23 18:57:33 fenner 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 #ifndef HAVE_PCAP_IF_T
326 #undef HAVE_PCAP_FINDALLDEVS
327 #endif
328 #endif
329
330 #ifdef HAVE_PCAP_FINDALLDEVS
331 #define D_FLAG "D"
332 #else
333 #define D_FLAG
334 #endif
335
336 #ifdef HAVE_PCAP_DUMP_FLUSH
337 #define U_FLAG "U"
338 #else
339 #define U_FLAG
340 #endif
341
342 #ifndef WIN32
343 /* Drop root privileges and chroot if necessary */
344 static void
345 droproot(const char *username, const char *chroot_dir)
346 {
347 struct passwd *pw = NULL;
348
349 if (chroot_dir && !username) {
350 fprintf(stderr, "Chroot without dropping root is insecure\n");
351 exit(1);
352 }
353
354 pw = getpwnam(username);
355 if (pw) {
356 if (chroot_dir) {
357 if (chroot(chroot_dir) != 0 || chdir ("/") != 0) {
358 fprintf(stderr, "Couldn't chroot/chdir to '%.64s'\n", chroot_dir);
359 exit(1);
360 }
361 }
362 if (initgroups(pw->pw_name, pw->pw_gid) != 0 || setgid(pw->pw_gid) != 0 ||
363 setuid(pw->pw_uid) != 0) {
364 fprintf(stderr, "Couldn't change to '%.32s' uid=%d gid=%d\n", username,
365 pw->pw_uid, pw->pw_gid);
366 exit(1);
367 }
368 }
369 else {
370 fprintf(stderr, "Couldn't find user '%.32s'\n", username);
371 exit(1);
372 }
373 }
374 #endif /* WIN32 */
375
376 static int
377 getWflagChars(int x)
378 {
379 int c = 0;
380
381 x -= 1;
382 while (x > 0) {
383 c += 1;
384 x /= 10;
385 }
386
387 return c;
388 }
389
390
391 static void
392 MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
393 {
394 if (cnt == 0 && max_chars == 0)
395 strcpy(buffer, orig_name);
396 else
397 sprintf(buffer, "%s%0*d", orig_name, max_chars, cnt);
398 }
399
400 int
401 main(int argc, char **argv)
402 {
403 register int cnt, op, i;
404 bpf_u_int32 localnet, netmask;
405 register char *cp, *infile, *cmdbuf, *device, *RFileName, *WFileName, *WFileNameAlt;
406 pcap_handler callback;
407 int type;
408 struct bpf_program fcode;
409 #ifndef WIN32
410 RETSIGTYPE (*oldhandler)(int);
411 #endif
412 struct print_info printinfo;
413 struct dump_info dumpinfo;
414 u_char *pcap_userdata;
415 char ebuf[PCAP_ERRBUF_SIZE];
416 char *username = NULL;
417 char *chroot_dir = NULL;
418 #ifdef HAVE_PCAP_FINDALLDEVS
419 pcap_if_t *devpointer;
420 int devnum;
421 #endif
422 int status;
423 #ifdef WIN32
424 u_int UserBufferSize = 1000000;
425 if(wsockinit() != 0) return 1;
426 #endif /* WIN32 */
427
428 cnt = -1;
429 device = NULL;
430 infile = NULL;
431 RFileName = NULL;
432 WFileName = NULL;
433 if ((cp = strrchr(argv[0], '/')) != NULL)
434 program_name = cp + 1;
435 else
436 program_name = argv[0];
437
438 if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
439 error("%s", ebuf);
440
441 #ifdef LIBSMI
442 smiInit("tcpdump");
443 #endif
444
445 opterr = 0;
446 while (
447 (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)
448 switch (op) {
449
450 case 'a':
451 /* compatibility for old -a */
452 break;
453
454 case 'A':
455 ++xflag;
456 ++Xflag;
457 ++Aflag;
458 break;
459
460 #ifdef WIN32
461 case 'B':
462 UserBufferSize = atoi(optarg)*1024;
463 if (UserBufferSize < 0)
464 error("invalid packet buffer size %s", optarg);
465 break;
466 #endif /* WIN32 */
467
468 case 'c':
469 cnt = atoi(optarg);
470 if (cnt <= 0)
471 error("invalid packet count %s", optarg);
472 break;
473
474 case 'C':
475 Cflag = atoi(optarg) * 1000000;
476 if (Cflag < 0)
477 error("invalid file size %s", optarg);
478 break;
479
480 case 'd':
481 ++dflag;
482 break;
483
484 #ifdef HAVE_PCAP_FINDALLDEVS
485 case 'D':
486 if (pcap_findalldevs(&devpointer, ebuf) < 0)
487 error("%s", ebuf);
488 else {
489 for (i = 0; devpointer != 0; i++) {
490 printf("%d.%s", i+1, devpointer->name);
491 if (devpointer->description != NULL)
492 printf(" (%s)", devpointer->description);
493 printf("\n");
494 devpointer = devpointer->next;
495 }
496 }
497 return 0;
498 #endif /* HAVE_PCAP_FINDALLDEVS */
499
500 case 'L':
501 Lflag++;
502 break;
503
504 case 'e':
505 ++eflag;
506 break;
507
508 case 'E':
509 #ifndef HAVE_LIBCRYPTO
510 warning("crypto code not compiled in");
511 #endif
512 espsecret = optarg;
513 break;
514
515 case 'f':
516 ++fflag;
517 break;
518
519 case 'F':
520 infile = optarg;
521 break;
522
523 case 'i':
524 if (optarg[0] == '0' && optarg[1] == 0)
525 error("Invalid adapter index");
526
527 #ifdef HAVE_PCAP_FINDALLDEVS
528 /*
529 * If the argument is a number, treat it as
530 * an index into the list of adapters, as
531 * printed by "tcpdump -D".
532 *
533 * This should be OK on UNIX systems, as interfaces
534 * shouldn't have names that begin with digits.
535 * It can be useful on Windows, where more than
536 * one interface can have the same name.
537 */
538 if ((devnum = atoi(optarg)) != 0) {
539 if (devnum < 0)
540 error("Invalid adapter index");
541
542 if (pcap_findalldevs(&devpointer, ebuf) < 0)
543 error("%s", ebuf);
544 else {
545 for (i = 0; i < devnum-1; i++){
546 devpointer = devpointer->next;
547 if (devpointer == NULL)
548 error("Invalid adapter index");
549 }
550 }
551 device = devpointer->name;
552 break;
553 }
554 #endif /* HAVE_PCAP_FINDALLDEVS */
555 device = optarg;
556 break;
557
558 case 'l':
559 #ifdef WIN32
560 /*
561 * _IOLBF is the same as _IOFBF in Microsoft's C
562 * libraries; the only alternative they offer
563 * is _IONBF.
564 *
565 * XXX - this should really be checking for MSVC++,
566 * not WIN32, if, for example, MinGW has its own
567 * C library that is more UNIX-compatible.
568 */
569 setvbuf(stdout, NULL, _IONBF, 0);
570 #else /* WIN32 */
571 #ifdef HAVE_SETLINEBUF
572 setlinebuf(stdout);
573 #else
574 setvbuf(stdout, NULL, _IOLBF, 0);
575 #endif
576 #endif /* WIN32 */
577 break;
578
579 case 'n':
580 ++nflag;
581 break;
582
583 case 'N':
584 ++Nflag;
585 break;
586
587 case 'm':
588 #ifdef LIBSMI
589 if (smiLoadModule(optarg) == 0) {
590 error("could not load MIB module %s", optarg);
591 }
592 sflag = 1;
593 #else
594 (void)fprintf(stderr, "%s: ignoring option `-m %s' ",
595 program_name, optarg);
596 (void)fprintf(stderr, "(no libsmi support)\n");
597 #endif
598 break;
599
600 case 'M':
601 /* TCP-MD5 shared secret */
602 #ifndef HAVE_LIBCRYPTO
603 warning("crypto code not compiled in");
604 #endif
605 tcpmd5secret = optarg;
606 break;
607
608 case 'O':
609 Oflag = 0;
610 break;
611
612 case 'p':
613 ++pflag;
614 break;
615
616 case 'q':
617 ++qflag;
618 break;
619
620 case 'r':
621 RFileName = optarg;
622 break;
623
624 case 'R':
625 Rflag = 0;
626 break;
627
628 case 's': {
629 char *end;
630
631 snaplen = strtol(optarg, &end, 0);
632 if (optarg == end || *end != '\0'
633 || snaplen < 0 || snaplen > 65535)
634 error("invalid snaplen %s", optarg);
635 else if (snaplen == 0)
636 snaplen = 65535;
637 break;
638 }
639
640 case 'S':
641 ++Sflag;
642 break;
643
644 case 't':
645 --tflag;
646 break;
647
648 case 'T':
649 if (strcasecmp(optarg, "vat") == 0)
650 packettype = PT_VAT;
651 else if (strcasecmp(optarg, "wb") == 0)
652 packettype = PT_WB;
653 else if (strcasecmp(optarg, "rpc") == 0)
654 packettype = PT_RPC;
655 else if (strcasecmp(optarg, "rtp") == 0)
656 packettype = PT_RTP;
657 else if (strcasecmp(optarg, "rtcp") == 0)
658 packettype = PT_RTCP;
659 else if (strcasecmp(optarg, "snmp") == 0)
660 packettype = PT_SNMP;
661 else if (strcasecmp(optarg, "cnfp") == 0)
662 packettype = PT_CNFP;
663 else if (strcasecmp(optarg, "tftp") == 0)
664 packettype = PT_TFTP;
665 else if (strcasecmp(optarg, "aodv") == 0)
666 packettype = PT_AODV;
667 else
668 error("unknown packet type `%s'", optarg);
669 break;
670
671 case 'u':
672 ++uflag;
673 break;
674
675 #ifdef HAVE_PCAP_DUMP_FLUSH
676 case 'U':
677 ++Uflag;
678 break;
679 #endif
680
681 case 'v':
682 ++vflag;
683 break;
684
685 case 'w':
686 WFileName = optarg;
687 break;
688
689 case 'W':
690 Wflag = atoi(optarg);
691 if (Wflag < 0)
692 error("invalid number of output files %s", optarg);
693 WflagChars = getWflagChars(Wflag);
694 break;
695
696 case 'x':
697 ++xflag;
698 break;
699
700 case 'X':
701 ++xflag;
702 ++Xflag;
703 break;
704
705 case 'y':
706 dlt_name = optarg;
707 dlt = pcap_datalink_name_to_val(dlt_name);
708 if (dlt < 0)
709 error("invalid data link type %s", dlt_name);
710 break;
711
712 #if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
713 case 'Y':
714 {
715 /* Undocumented flag */
716 #ifdef HAVE_PCAP_DEBUG
717 extern int pcap_debug;
718 pcap_debug = 1;
719 #else
720 extern int yydebug;
721 yydebug = 1;
722 #endif
723 }
724 break;
725 #endif
726 case 'Z':
727 if (optarg) {
728 username = strdup(optarg);
729 }
730 else {
731 usage();
732 /* NOTREACHED */
733 }
734 break;
735
736 default:
737 usage();
738 /* NOTREACHED */
739 }
740
741 if (tflag > 0)
742 thiszone = gmt2local(0);
743
744 #ifdef WITH_CHROOT
745 /* if run as root, prepare for chrooting */
746 if (getuid() == 0 || geteuid() == 0) {
747 /* future extensibility for cmd-line arguments */
748 if (!chroot_dir)
749 chroot_dir = WITH_CHROOT;
750 }
751 #endif
752
753 #ifdef WITH_USER
754 /* if run as root, prepare for dropping root privileges */
755 if (getuid() == 0 || geteuid() == 0) {
756 /* Run with '-Z root' to restore old behaviour */
757 if (!username)
758 username = WITH_USER;
759 }
760 #endif
761
762 if (RFileName != NULL) {
763 int dlt;
764 const char *dlt_name;
765
766 #ifndef WIN32
767 /*
768 * We don't need network access, so relinquish any set-UID
769 * or set-GID privileges we have (if any).
770 *
771 * We do *not* want set-UID privileges when opening a
772 * trace file, as that might let the user read other
773 * people's trace files (especially if we're set-UID
774 * root).
775 */
776 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
777 fprintf(stderr, "Warning: setgid/setuid failed !\n");
778 #endif /* WIN32 */
779 pd = pcap_open_offline(RFileName, ebuf);
780 if (pd == NULL)
781 error("%s", ebuf);
782 dlt = pcap_datalink(pd);
783 dlt_name = pcap_datalink_val_to_name(dlt);
784 if (dlt_name == NULL) {
785 fprintf(stderr, "reading from file %s, link-type %u\n",
786 RFileName, dlt);
787 } else {
788 fprintf(stderr,
789 "reading from file %s, link-type %s (%s)\n",
790 RFileName, dlt_name,
791 pcap_datalink_val_to_description(dlt));
792 }
793 localnet = 0;
794 netmask = 0;
795 if (fflag != 0)
796 error("-f and -r options are incompatible");
797 } else {
798 if (device == NULL) {
799 device = pcap_lookupdev(ebuf);
800 if (device == NULL)
801 error("%s", ebuf);
802 }
803 #ifdef WIN32
804 if(IsTextUnicode(device,
805 wcslen((short*)device), // Device always ends with a double \0, so this way to determine its
806 // length should be always valid
807 NULL))
808 {
809 fprintf(stderr, "%s: listening on %ws\n", program_name, device);
810 }
811 else
812 {
813 fprintf(stderr, "%s: listening on %s\n", program_name, device);
814 }
815
816 fflush(stderr);
817 #endif /* WIN32 */
818 *ebuf = '\0';
819 pd = pcap_open_live(device, snaplen, !pflag, 1000, ebuf);
820 if (pd == NULL)
821 error("%s", ebuf);
822 else if (*ebuf)
823 warning("%s", ebuf);
824 /*
825 * Let user own process after socket has been opened.
826 */
827 #ifndef WIN32
828 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
829 fprintf(stderr, "Warning: setgid/setuid failed !\n");
830 #endif /* WIN32 */
831 #ifdef WIN32
832 if(UserBufferSize != 1000000)
833 if(pcap_setbuff(pd, UserBufferSize)==-1){
834 error("%s", pcap_geterr(pd));
835 }
836 #endif /* WIN32 */
837 if (Lflag)
838 show_dlts_and_exit(pd);
839 if (dlt >= 0) {
840 #ifdef HAVE_PCAP_SET_DATALINK
841 if (pcap_set_datalink(pd, dlt) < 0)
842 error("%s", pcap_geterr(pd));
843 #else
844 /*
845 * We don't actually support changing the
846 * data link type, so we only let them
847 * set it to what it already is.
848 */
849 if (dlt != pcap_datalink(pd)) {
850 error("%s is not one of the DLTs supported by this device\n",
851 dlt_name);
852 }
853 #endif
854 (void)fprintf(stderr, "%s: data link type %s\n",
855 program_name, dlt_name);
856 (void)fflush(stderr);
857 }
858 i = pcap_snapshot(pd);
859 if (snaplen < i) {
860 warning("snaplen raised from %d to %d", snaplen, i);
861 snaplen = i;
862 }
863 if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
864 localnet = 0;
865 netmask = 0;
866 warning("%s", ebuf);
867 }
868 }
869 if (infile)
870 cmdbuf = read_infile(infile);
871 else
872 cmdbuf = copy_argv(&argv[optind]);
873
874 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
875 error("%s", pcap_geterr(pd));
876 if (dflag) {
877 bpf_dump(&fcode, dflag);
878 pcap_close(pd);
879 exit(0);
880 }
881 init_addrtoname(localnet, netmask);
882
883 #ifndef WIN32
884 (void)setsignal(SIGPIPE, cleanup);
885 #endif /* WIN32 */
886 (void)setsignal(SIGTERM, cleanup);
887 (void)setsignal(SIGINT, cleanup);
888 /* Cooperate with nohup(1) */
889 #ifndef WIN32
890 if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
891 (void)setsignal(SIGHUP, oldhandler);
892 #endif /* WIN32 */
893
894 if (pcap_setfilter(pd, &fcode) < 0)
895 error("%s", pcap_geterr(pd));
896 if (WFileName) {
897 pcap_dumper_t *p;
898
899 WFileNameAlt = (char *)malloc(strlen(WFileName) + MAX_CFLAG_CHARS + 1);
900 if (WFileNameAlt == NULL)
901 error("malloc of WFileNameAlt");
902 MakeFilename(WFileNameAlt, WFileName, 0, WflagChars);
903 p = pcap_dump_open(pd, WFileNameAlt);
904 if (p == NULL)
905 error("%s", pcap_geterr(pd));
906 if (Cflag != 0) {
907 callback = dump_packet_and_trunc;
908 dumpinfo.WFileName = WFileName;
909 dumpinfo.pd = pd;
910 dumpinfo.p = p;
911 pcap_userdata = (u_char *)&dumpinfo;
912 } else {
913 callback = dump_packet;
914 pcap_userdata = (u_char *)p;
915 }
916 } else {
917 type = pcap_datalink(pd);
918 printinfo.printer = lookup_printer(type);
919 if (printinfo.printer == NULL) {
920 dlt_name = pcap_datalink_val_to_name(type);
921 if (dlt_name != NULL)
922 error("unsupported data link type %s", dlt_name);
923 else
924 error("unsupported data link type %d", type);
925 }
926 callback = print_packet;
927 pcap_userdata = (u_char *)&printinfo;
928 }
929 #ifndef WIN32
930 /*
931 * We cannot do this earlier, because we want to be able to open
932 * the file (if done) for writing before giving up permissions.
933 */
934 if (getuid() == 0 || geteuid() == 0) {
935 if (username || chroot_dir)
936 droproot(username, chroot_dir);
937 }
938 #endif /* WIN32 */
939 #ifdef SIGINFO
940 (void)setsignal(SIGINFO, requestinfo);
941 #endif
942
943 if (vflag > 0 && WFileName) {
944 /*
945 * When capturing to a file, "-v" means tcpdump should,
946 * every 10 secodns, "v"erbosely report the number of
947 * packets captured.
948 */
949 #ifdef USE_WIN32_MM_TIMER
950 /* call verbose_stats_dump() each 1000 +/-100msec */
951 timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
952 setvbuf(stderr, NULL, _IONBF, 0);
953 #elif defined(HAVE_ALARM)
954 (void)setsignal(SIGALRM, verbose_stats_dump);
955 alarm(1);
956 #endif
957 }
958
959 #ifndef WIN32
960 if (RFileName == NULL) {
961 int dlt;
962 const char *dlt_name;
963
964 if (!vflag && !WFileName) {
965 (void)fprintf(stderr,
966 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
967 program_name);
968 } else
969 (void)fprintf(stderr, "%s: ", program_name);
970 dlt = pcap_datalink(pd);
971 dlt_name = pcap_datalink_val_to_name(dlt);
972 if (dlt_name == NULL) {
973 (void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
974 device, dlt, snaplen);
975 } else {
976 (void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
977 device, dlt_name,
978 pcap_datalink_val_to_description(dlt), snaplen);
979 }
980 (void)fflush(stderr);
981 }
982 #endif /* WIN32 */
983 status = pcap_loop(pd, cnt, callback, pcap_userdata);
984 if (WFileName == NULL) {
985 /*
986 * We're printing packets. Flush the printed output,
987 * so it doesn't get intermingled with error output.
988 */
989 if (status == -2) {
990 /*
991 * We got interrupted, so perhaps we didn't
992 * manage to finish a line we were printing.
993 * Print an extra newline, just in case.
994 */
995 putchar('\n');
996 }
997 (void)fflush(stdout);
998 }
999 if (status == -1) {
1000 /*
1001 * Error. Report it.
1002 */
1003 (void)fprintf(stderr, "%s: pcap_loop: %s\n",
1004 program_name, pcap_geterr(pd));
1005 }
1006 if (RFileName == NULL) {
1007 /*
1008 * We're doing a live capture. Report the capture
1009 * statistics.
1010 */
1011 info(1);
1012 }
1013 pcap_close(pd);
1014 exit(status == -1 ? 1 : 0);
1015 }
1016
1017 /* make a clean exit on interrupts */
1018 static RETSIGTYPE
1019 cleanup(int signo _U_)
1020 {
1021 #ifdef USE_WIN32_MM_TIMER
1022 if (timer_id)
1023 timeKillEvent(timer_id);
1024 timer_id = 0;
1025 #elif defined(HAVE_ALARM)
1026 alarm(0);
1027 #endif
1028
1029 #ifdef HAVE_PCAP_BREAKLOOP
1030 /*
1031 * We have "pcap_breakloop()"; use it, so that we do as little
1032 * as possible in the signal handler (it's probably not safe
1033 * to do anything with standard I/O streams in a signal handler -
1034 * the ANSI C standard doesn't say it is).
1035 */
1036 pcap_breakloop(pd);
1037 #else
1038 /*
1039 * We don't have "pcap_breakloop()"; this isn't safe, but
1040 * it's the best we can do. Print the summary if we're
1041 * not reading from a savefile - i.e., if we're doing a
1042 * live capture - and exit.
1043 */
1044 if (pd != NULL && pcap_file(pd) == NULL) {
1045 /*
1046 * We got interrupted, so perhaps we didn't
1047 * manage to finish a line we were printing.
1048 * Print an extra newline, just in case.
1049 */
1050 putchar('\n');
1051 (void)fflush(stdout);
1052 info(1);
1053 }
1054 exit(0);
1055 #endif
1056 }
1057
1058 static void
1059 info(register int verbose)
1060 {
1061 struct pcap_stat stat;
1062
1063 if (pcap_stats(pd, &stat) < 0) {
1064 (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
1065 return;
1066 }
1067
1068 if (!verbose)
1069 fprintf(stderr, "%s: ", program_name);
1070
1071 (void)fprintf(stderr, "%u packets captured", packets_captured);
1072 if (!verbose)
1073 fputs(", ", stderr);
1074 else
1075 putc('\n', stderr);
1076 (void)fprintf(stderr, "%d packets received by filter", stat.ps_recv);
1077 if (!verbose)
1078 fputs(", ", stderr);
1079 else
1080 putc('\n', stderr);
1081 (void)fprintf(stderr, "%d packets dropped by kernel\n", stat.ps_drop);
1082 infoprint = 0;
1083 }
1084
1085 static void
1086 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1087 {
1088 struct dump_info *dump_info;
1089 char *name;
1090
1091 ++packets_captured;
1092
1093 ++infodelay;
1094
1095 dump_info = (struct dump_info *)user;
1096
1097 /*
1098 * XXX - this won't prevent capture files from getting
1099 * larger than Cflag - the last packet written to the
1100 * file could put it over Cflag.
1101 */
1102 if (ftell((FILE *)dump_info->p) > Cflag) {
1103 /*
1104 * Close the current file and open a new one.
1105 */
1106 pcap_dump_close(dump_info->p);
1107 Cflag_count++;
1108 if (Wflag > 0) {
1109 if (Cflag_count >= Wflag)
1110 Cflag_count = 0;
1111 } else {
1112 if (Cflag_count >= MAX_CFLAG)
1113 error("too many output files");
1114 }
1115 name = (char *)malloc(strlen(dump_info->WFileName) + MAX_CFLAG_CHARS + 1);
1116 if (name == NULL)
1117 error("dump_packet_and_trunc: malloc");
1118 MakeFilename(name, dump_info->WFileName, Cflag_count, WflagChars);
1119 dump_info->p = pcap_dump_open(dump_info->pd, name);
1120 free(name);
1121 if (dump_info->p == NULL)
1122 error("%s", pcap_geterr(pd));
1123 }
1124
1125 pcap_dump((u_char *)dump_info->p, h, sp);
1126 #ifdef HAVE_PCAP_DUMP_FLUSH
1127 if (Uflag)
1128 pcap_dump_flush(dump_info->p);
1129 #endif
1130
1131 --infodelay;
1132 if (infoprint)
1133 info(0);
1134 }
1135
1136 static void
1137 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1138 {
1139 ++packets_captured;
1140
1141 ++infodelay;
1142
1143 pcap_dump(user, h, sp);
1144 #ifdef HAVE_PCAP_DUMP_FLUSH
1145 if (Uflag)
1146 pcap_dump_flush((pcap_dumper_t *)user);
1147 #endif
1148
1149 --infodelay;
1150 if (infoprint)
1151 info(0);
1152 }
1153
1154 static void
1155 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1156 {
1157 struct print_info *print_info;
1158 u_int hdrlen;
1159
1160 ++packets_captured;
1161
1162 ++infodelay;
1163 ts_print(&h->ts);
1164
1165 print_info = (struct print_info *)user;
1166
1167 /*
1168 * Some printers want to check that they're not walking off the
1169 * end of the packet.
1170 * Rather than pass it all the way down, we set this global.
1171 */
1172 snapend = sp + h->caplen;
1173
1174 hdrlen = (*print_info->printer)(h, sp);
1175 if (xflag) {
1176 /*
1177 * Print the raw packet data.
1178 */
1179 if (xflag > 1) {
1180 /*
1181 * Include the link-layer header.
1182 */
1183 default_print(sp, h->caplen);
1184 } else {
1185 /*
1186 * Don't include the link-layer header - and if
1187 * we have nothing past the link-layer header,
1188 * print nothing.
1189 */
1190 if (h->caplen > hdrlen)
1191 default_print(sp + hdrlen,
1192 h->caplen - hdrlen);
1193 }
1194 }
1195
1196 putchar('\n');
1197
1198 --infodelay;
1199 if (infoprint)
1200 info(0);
1201 }
1202
1203 #ifdef WIN32
1204 /*
1205 * XXX - there should really be libpcap calls to get the version
1206 * number as a string (the string would be generated from #defines
1207 * at run time, so that it's not generated from string constants
1208 * in the library, as, on many UNIX systems, those constants would
1209 * be statically linked into the application executable image, and
1210 * would thus reflect the version of libpcap on the system on
1211 * which the application was *linked*, not the system on which it's
1212 * *running*.
1213 *
1214 * That routine should be documented, unlike the "version[]"
1215 * string, so that UNIX vendors providing their own libpcaps
1216 * don't omit it (as a couple of vendors have...).
1217 *
1218 * Packet.dll should perhaps also export a routine to return the
1219 * version number of the Packet.dll code, to supply the
1220 * "Wpcap_version" information on Windows.
1221 */
1222 char WDversion[]="current-cvs.tcpdump.org";
1223 #if !defined(HAVE_GENERATED_VERSION)
1224 char version[]="current-cvs.tcpdump.org";
1225 #endif
1226 char pcap_version[]="current-cvs.tcpdump.org";
1227 char Wpcap_version[]="3.0 alpha";
1228 #endif
1229
1230 /*
1231 * By default, print the specified data out in hex.
1232 */
1233 void
1234 default_print(register const u_char *bp, register u_int length)
1235 {
1236 ascii_print("\n\t", bp, length); /* pass on lf and identation string */
1237 }
1238
1239 #ifdef SIGINFO
1240 RETSIGTYPE requestinfo(int signo _U_)
1241 {
1242 if (infodelay)
1243 ++infoprint;
1244 else
1245 info(0);
1246 }
1247 #endif
1248
1249 /*
1250 * Called once each second in verbose mode while dumping to file
1251 */
1252 #ifdef USE_WIN32_MM_TIMER
1253 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
1254 DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
1255 {
1256 struct pcap_stat stat;
1257
1258 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
1259 fprintf(stderr, "Got %u\r", packets_captured);
1260 }
1261 #elif defined(HAVE_ALARM)
1262 static void verbose_stats_dump(int sig _U_)
1263 {
1264 struct pcap_stat stat;
1265
1266 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
1267 fprintf(stderr, "Got %u\r", packets_captured);
1268 alarm(1);
1269 }
1270 #endif
1271
1272 static void
1273 usage(void)
1274 {
1275 extern char version[];
1276 #ifndef HAVE_PCAP_LIB_VERSION
1277 #if defined(WIN32) || defined(HAVE_PCAP_VERSION)
1278 extern char pcap_version[];
1279 #else /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
1280 static char pcap_version[] = "unknown";
1281 #endif /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
1282 #endif /* HAVE_PCAP_LIB_VERSION */
1283
1284 #ifdef HAVE_PCAP_LIB_VERSION
1285 (void)fprintf(stderr, "%s version %s\n", program_name, version);
1286 (void)fprintf(stderr, "%s\n", pcap_lib_version());
1287 #else /* HAVE_PCAP_LIB_VERSION */
1288 #ifdef WIN32
1289 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
1290 (void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
1291 #else /* WIN32 */
1292 (void)fprintf(stderr, "%s version %s\n", program_name, version);
1293 (void)fprintf(stderr, "libpcap version %s\n", pcap_version);
1294 #endif /* WIN32 */
1295 #endif /* HAVE_PCAP_LIB_VERSION */
1296 (void)fprintf(stderr,
1297 "Usage: %s [-aAd" D_FLAG "eflLnNOpqRStu" U_FLAG "vxX]" B_FLAG_USAGE " [-c count] [ -C file_size ]\n", program_name);
1298 (void)fprintf(stderr,
1299 "\t\t[ -E algo:secret ] [ -F file ] [ -i interface ] [ -M secret ]\n");
1300 (void)fprintf(stderr,
1301 "\t\t[ -r file ] [ -s snaplen ] [ -T type ] [ -w file ] [ -W filecount ]\n");
1302 (void)fprintf(stderr,
1303 "\t\t[ -y datalinktype ] [ -Z user ]\n");
1304 (void)fprintf(stderr,
1305 "\t\t[ expression ]\n");
1306 exit(1);
1307 }