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