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