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