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