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