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