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