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