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