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