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