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