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