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