]> The Tcpdump Group git mirrors - tcpdump/blob - tcpdump.c
7f751f0e95d5ca19e342781a5680896c28575e9d
[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.231 2004-02-24 08:12:18 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 #include <pwd.h>
69 #include <grp.h>
70
71 #include "interface.h"
72 #include "addrtoname.h"
73 #include "machdep.h"
74 #include "setsignal.h"
75 #include "gmt2local.h"
76 #include "pcap-missing.h"
77
78 int dflag; /* print filter code */
79 int eflag; /* print ethernet header */
80 int fflag; /* don't translate "foreign" IP address */
81 static int Lflag; /* list available data link types and exit */
82 int nflag; /* leave addresses as numbers */
83 int Nflag; /* remove domains from printed host names */
84 static int Oflag = 1; /* run filter code optimizer */
85 static int pflag; /* don't go promiscuous */
86 int qflag; /* quick (shorter) output */
87 int Rflag = 1; /* print sequence # field in AH/ESP*/
88 int sflag = 0; /* use the libsmi to translate OIDs */
89 int Sflag; /* print raw TCP sequence numbers */
90 int tflag = 1; /* print packet arrival time */
91 int Uflag = 0; /* "unbuffered" output of dump files */
92 int uflag = 0; /* Print undecoded NFS handles */
93 int vflag; /* verbose */
94 int xflag; /* print packet in hex */
95 int Xflag; /* print packet in ascii as well as hex */
96 static off_t Cflag = 0; /* rotate dump files after this many bytes */
97 int Aflag = 0; /* print packet only in ascii observing LF, CR, TAB, SPACE */
98 static int dlt = -1; /* if != -1, ask libpcap for the DLT it names */
99 static int Cflag_count = 0; /* Keep track of which file number we're writing */
100 static int Wflag = 0; /* recycle output files after this number of files */
101 static int WflagChars = 0;
102
103 /*
104 * Define the maximum number of files for the -C flag, and how many
105 * characters can be added to a filename for the -C flag (which
106 * should be enough to handle MAX_CFLAG - 1).
107 */
108 #define MAX_CFLAG 1000000
109 #define MAX_CFLAG_CHARS 6
110
111 const char *dlt_name = NULL;
112
113 char *espsecret = NULL; /* ESP secret key */
114
115 int packettype;
116
117 static int infodelay;
118 static int infoprint;
119
120 char *program_name;
121
122 int32_t thiszone; /* seconds offset from gmt to local time */
123
124 /* Forwards */
125 static RETSIGTYPE cleanup(int);
126 static void usage(void) __attribute__((noreturn));
127 static void show_dlts_and_exit(pcap_t *pd) __attribute__((noreturn));
128
129 static void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
130 static void dump_packet_and_trunc(u_char *, const struct pcap_pkthdr *, const u_char *);
131 static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
132 static void droproot(const char *);
133
134 #ifdef SIGINFO
135 RETSIGTYPE requestinfo(int);
136 #endif
137
138 #if defined(USE_WIN32_MM_TIMER)
139 #include <MMsystem.h>
140 static UINT timer_id;
141 static void CALLBACK verbose_stats_dump(UINT, UINT, DWORD_PTR, DWORD_PTR, DWORD_PTR);
142 #elif defined(HAVE_ALARM)
143 static void verbose_stats_dump(int sig);
144 #endif
145
146 static void info(int);
147 static u_int packets_captured;
148
149 /* Length of saved portion of packet. */
150 int snaplen = DEFAULT_SNAPLEN;
151
152 typedef u_int (*if_printer)(const struct pcap_pkthdr *, const u_char *);
153
154 struct printer {
155 if_printer f;
156 int type;
157 };
158
159 static struct printer printers[] = {
160 { arcnet_if_print, DLT_ARCNET },
161 #ifdef DLT_ARCNET_LINUX
162 { arcnet_linux_if_print, DLT_ARCNET_LINUX },
163 #endif
164 { ether_if_print, DLT_EN10MB },
165 { token_if_print, DLT_IEEE802 },
166 #ifdef DLT_LANE8023
167 { lane_if_print, DLT_LANE8023 },
168 #endif
169 #ifdef DLT_CIP
170 { cip_if_print, DLT_CIP },
171 #endif
172 #ifdef DLT_ATM_CLIP
173 { cip_if_print, DLT_ATM_CLIP },
174 #endif
175 { sl_if_print, DLT_SLIP },
176 #ifdef DLT_SLIP_BSDOS
177 { sl_bsdos_if_print, DLT_SLIP_BSDOS },
178 #endif
179 { ppp_if_print, DLT_PPP },
180 #ifdef DLT_PPP_BSDOS
181 { ppp_bsdos_if_print, DLT_PPP_BSDOS },
182 #endif
183 { fddi_if_print, DLT_FDDI },
184 { null_if_print, DLT_NULL },
185 #ifdef DLT_LOOP
186 { null_if_print, DLT_LOOP },
187 #endif
188 { raw_if_print, DLT_RAW },
189 { atm_if_print, DLT_ATM_RFC1483 },
190 #ifdef DLT_C_HDLC
191 { chdlc_if_print, DLT_C_HDLC },
192 #endif
193 #ifdef DLT_HDLC
194 { chdlc_if_print, DLT_HDLC },
195 #endif
196 #ifdef DLT_PPP_SERIAL
197 { ppp_hdlc_if_print, DLT_PPP_SERIAL },
198 #endif
199 #ifdef DLT_PPP_ETHER
200 { pppoe_if_print, DLT_PPP_ETHER },
201 #endif
202 #ifdef DLT_LINUX_SLL
203 { sll_if_print, DLT_LINUX_SLL },
204 #endif
205 #ifdef DLT_IEEE802_11
206 { ieee802_11_if_print, DLT_IEEE802_11},
207 #endif
208 #ifdef DLT_LTALK
209 { ltalk_if_print, DLT_LTALK },
210 #endif
211 #ifdef DLT_PFLOG
212 { pflog_if_print, DLT_PFLOG },
213 #endif
214 #ifdef DLT_FR
215 { fr_if_print, DLT_FR },
216 #endif
217 #ifdef DLT_FRELAY
218 { fr_if_print, DLT_FRELAY },
219 #endif
220 #ifdef DLT_SUNATM
221 { sunatm_if_print, DLT_SUNATM },
222 #endif
223 #ifdef DLT_IP_OVER_FC
224 { ipfc_if_print, DLT_IP_OVER_FC },
225 #endif
226 #ifdef DLT_PRISM_HEADER
227 { prism_if_print, DLT_PRISM_HEADER },
228 #endif
229 #ifdef DLT_IEEE802_11_RADIO
230 { ieee802_11_radio_if_print, DLT_IEEE802_11_RADIO },
231 #endif
232 #ifdef DLT_ENC
233 { enc_if_print, DLT_ENC },
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 #define D_FLAG "D"
317 #else
318 #define D_FLAG
319 #endif
320
321 #ifdef HAVE_PCAP_DUMP_FLUSH
322 #define U_FLAG "U"
323 #else
324 #define U_FLAG
325 #endif
326
327 /* Drop root privileges */
328 static void
329 droproot(const char *username)
330 {
331 struct passwd *pw = NULL;
332
333 pw = getpwnam(username);
334 if (pw) {
335 if (initgroups(pw->pw_name, 0) != 0 || setgid(pw->pw_gid) != 0 ||
336 setuid(pw->pw_uid) != 0) {
337 fprintf(stderr, "Couldn't change to '%.32s' uid=%d gid=%d\n", username,
338 pw->pw_uid, pw->pw_gid);
339 exit(1);
340 }
341 }
342 else {
343 fprintf(stderr, "Couldn't find user '%.32s'\n", username);
344 exit(1);
345 }
346 }
347
348 static int
349 getWflagChars(int x)
350 {
351 int c = 0;
352
353 x -= 1;
354 while (x > 0) {
355 c += 1;
356 x /= 10;
357 }
358
359 return c;
360 }
361
362
363 static void
364 MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
365 {
366 if (cnt == 0 && max_chars == 0)
367 strcpy(buffer, orig_name);
368 else
369 sprintf(buffer, "%s%0*d", orig_name, max_chars, cnt);
370 }
371
372 int
373 main(int argc, char **argv)
374 {
375 register int cnt, op, i;
376 bpf_u_int32 localnet, netmask;
377 register char *cp, *infile, *cmdbuf, *device, *RFileName, *WFileName, *WFileNameAlt;
378 pcap_handler callback;
379 int type;
380 struct bpf_program fcode;
381 #ifndef WIN32
382 RETSIGTYPE (*oldhandler)(int);
383 #endif
384 struct print_info printinfo;
385 struct dump_info dumpinfo;
386 u_char *pcap_userdata;
387 char ebuf[PCAP_ERRBUF_SIZE];
388 char *username = NULL;
389 #ifdef HAVE_PCAP_FINDALLDEVS
390 pcap_if_t *devpointer;
391 int devnum;
392 #endif
393 int status;
394 #ifdef WIN32
395 u_int UserBufferSize = 1000000;
396 if(wsockinit() != 0) return 1;
397 #endif /* WIN32 */
398
399 cnt = -1;
400 device = NULL;
401 infile = NULL;
402 RFileName = NULL;
403 WFileName = NULL;
404 if ((cp = strrchr(argv[0], '/')) != NULL)
405 program_name = cp + 1;
406 else
407 program_name = argv[0];
408
409 if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
410 error("%s", ebuf);
411
412 #ifdef LIBSMI
413 smiInit("tcpdump");
414 #endif
415
416 opterr = 0;
417 while (
418 (op = getopt(argc, argv, "aA" B_FLAG "c:C:d" D_FLAG "eE:fF:i:lLm:nNOpqr:Rs:StT:u" U_FLAG "vw:W:xXy:YZ:")) != -1)
419 switch (op) {
420
421 case 'a':
422 /* compatibility for old -a */
423 break;
424
425 case 'A':
426 ++xflag;
427 ++Xflag;
428 ++Aflag;
429 break;
430
431 #ifdef WIN32
432 case 'B':
433 UserBufferSize = atoi(optarg)*1024;
434 if (UserBufferSize < 0)
435 error("invalid packet buffer size %s", optarg);
436 break;
437 #endif /* WIN32 */
438
439 case 'c':
440 cnt = atoi(optarg);
441 if (cnt <= 0)
442 error("invalid packet count %s", optarg);
443 break;
444
445 case 'C':
446 Cflag = atoi(optarg) * 1000000;
447 if (Cflag < 0)
448 error("invalid file size %s", optarg);
449 break;
450
451 case 'd':
452 ++dflag;
453 break;
454
455 #ifdef HAVE_PCAP_FINDALLDEVS
456 case 'D':
457 if (pcap_findalldevs(&devpointer, ebuf) < 0)
458 error("%s", ebuf);
459 else {
460 for (i = 0; devpointer != 0; i++) {
461 printf("%d.%s", i+1, devpointer->name);
462 if (devpointer->description != NULL)
463 printf(" (%s)", devpointer->description);
464 printf("\n");
465 devpointer = devpointer->next;
466 }
467 }
468 return 0;
469 #endif /* HAVE_PCAP_FINDALLDEVS */
470
471 case 'L':
472 Lflag++;
473 break;
474
475 case 'e':
476 ++eflag;
477 break;
478
479 case 'E':
480 #ifndef HAVE_LIBCRYPTO
481 warning("crypto code not compiled in");
482 #endif
483 espsecret = optarg;
484 break;
485
486 case 'f':
487 ++fflag;
488 break;
489
490 case 'F':
491 infile = optarg;
492 break;
493
494 case 'i':
495 if (optarg[0] == '0' && optarg[1] == 0)
496 error("Invalid adapter index");
497
498 #ifdef HAVE_PCAP_FINDALLDEVS
499 /*
500 * If the argument is a number, treat it as
501 * an index into the list of adapters, as
502 * printed by "tcpdump -D".
503 *
504 * This should be OK on UNIX systems, as interfaces
505 * shouldn't have names that begin with digits.
506 * It can be useful on Windows, where more than
507 * one interface can have the same name.
508 */
509 if ((devnum = atoi(optarg)) != 0) {
510 if (devnum < 0)
511 error("Invalid adapter index");
512
513 if (pcap_findalldevs(&devpointer, ebuf) < 0)
514 error("%s", ebuf);
515 else {
516 for (i = 0; i < devnum-1; i++){
517 devpointer = devpointer->next;
518 if (devpointer == NULL)
519 error("Invalid adapter index");
520 }
521 }
522 device = devpointer->name;
523 break;
524 }
525 #endif /* HAVE_PCAP_FINDALLDEVS */
526 device = optarg;
527 break;
528
529 case 'l':
530 #ifdef WIN32
531 /*
532 * _IOLBF is the same as _IOFBF in Microsoft's C
533 * libraries; the only alternative they offer
534 * is _IONBF.
535 *
536 * XXX - this should really be checking for MSVC++,
537 * not WIN32, if, for example, MinGW has its own
538 * C library that is more UNIX-compatible.
539 */
540 setvbuf(stdout, NULL, _IONBF, 0);
541 #else /* WIN32 */
542 #ifdef HAVE_SETLINEBUF
543 setlinebuf(stdout);
544 #else
545 setvbuf(stdout, NULL, _IOLBF, 0);
546 #endif
547 #endif /* WIN32 */
548 break;
549
550 case 'n':
551 ++nflag;
552 break;
553
554 case 'N':
555 ++Nflag;
556 break;
557
558 case 'm':
559 #ifdef LIBSMI
560 if (smiLoadModule(optarg) == 0) {
561 error("could not load MIB module %s", optarg);
562 }
563 sflag = 1;
564 #else
565 (void)fprintf(stderr, "%s: ignoring option `-m %s' ",
566 program_name, optarg);
567 (void)fprintf(stderr, "(no libsmi support)\n");
568 #endif
569 break;
570
571 case 'O':
572 Oflag = 0;
573 break;
574
575 case 'p':
576 ++pflag;
577 break;
578
579 case 'q':
580 ++qflag;
581 break;
582
583 case 'r':
584 RFileName = optarg;
585 break;
586
587 case 'R':
588 Rflag = 0;
589 break;
590
591 case 's': {
592 char *end;
593
594 snaplen = strtol(optarg, &end, 0);
595 if (optarg == end || *end != '\0'
596 || snaplen < 0 || snaplen > 65535)
597 error("invalid snaplen %s", optarg);
598 else if (snaplen == 0)
599 snaplen = 65535;
600 break;
601 }
602
603 case 'S':
604 ++Sflag;
605 break;
606
607 case 't':
608 --tflag;
609 break;
610
611 case 'T':
612 if (strcasecmp(optarg, "vat") == 0)
613 packettype = PT_VAT;
614 else if (strcasecmp(optarg, "wb") == 0)
615 packettype = PT_WB;
616 else if (strcasecmp(optarg, "rpc") == 0)
617 packettype = PT_RPC;
618 else if (strcasecmp(optarg, "rtp") == 0)
619 packettype = PT_RTP;
620 else if (strcasecmp(optarg, "rtcp") == 0)
621 packettype = PT_RTCP;
622 else if (strcasecmp(optarg, "snmp") == 0)
623 packettype = PT_SNMP;
624 else if (strcasecmp(optarg, "cnfp") == 0)
625 packettype = PT_CNFP;
626 else if (strcasecmp(optarg, "tftp") == 0)
627 packettype = PT_TFTP;
628 else if (strcasecmp(optarg, "aodv") == 0)
629 packettype = PT_AODV;
630 else
631 error("unknown packet type `%s'", optarg);
632 break;
633
634 case 'u':
635 ++uflag;
636 break;
637
638 #ifdef HAVE_PCAP_DUMP_FLUSH
639 case 'U':
640 ++Uflag;
641 break;
642 #endif
643
644 case 'v':
645 ++vflag;
646 break;
647
648 case 'w':
649 WFileName = optarg;
650 break;
651
652 case 'W':
653 Wflag = atoi(optarg);
654 if (Wflag < 0)
655 error("invalid number of output files %s", optarg);
656 WflagChars = getWflagChars(Wflag);
657 break;
658
659 case 'x':
660 ++xflag;
661 break;
662
663 case 'X':
664 ++xflag;
665 ++Xflag;
666 break;
667
668 case 'y':
669 dlt_name = optarg;
670 dlt = pcap_datalink_name_to_val(dlt_name);
671 if (dlt < 0)
672 error("invalid data link type %s", dlt_name);
673 break;
674
675 #if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
676 case 'Y':
677 {
678 /* Undocumented flag */
679 #ifdef HAVE_PCAP_DEBUG
680 extern int pcap_debug;
681 pcap_debug = 1;
682 #else
683 extern int yydebug;
684 yydebug = 1;
685 #endif
686 }
687 break;
688 #endif
689 case 'Z':
690 if (optarg) {
691 username = strdup(optarg);
692 }
693 else {
694 usage();
695 /* NOTREACHED */
696 }
697 break;
698
699 default:
700 usage();
701 /* NOTREACHED */
702 }
703
704 if (tflag > 0)
705 thiszone = gmt2local(0);
706
707 #ifdef WITH_USER
708 /* if run as root, prepare for dropping root privileges */
709 if (getuid() == 0 || geteuid() == 0) {
710 /* Run with '-Z root' to restore old behaviour */
711 if (!username)
712 username = WITH_USER;
713 }
714 #endif
715
716 if (RFileName != NULL) {
717 int dlt;
718 const char *dlt_name;
719
720 #ifndef WIN32
721 /*
722 * We don't need network access, so relinquish any set-UID
723 * or set-GID privileges we have (if any).
724 *
725 * We do *not* want set-UID privileges when opening a
726 * trace file, as that might let the user read other
727 * people's trace files (especially if we're set-UID
728 * root).
729 */
730 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
731 fprintf(stderr, "Warning: setgid/setuid failed !\n");
732 #endif /* WIN32 */
733 pd = pcap_open_offline(RFileName, ebuf);
734 if (pd == NULL)
735 error("%s", ebuf);
736 dlt = pcap_datalink(pd);
737 dlt_name = pcap_datalink_val_to_name(dlt);
738 if (dlt_name == NULL) {
739 fprintf(stderr, "reading from file %s, link-type %u\n",
740 RFileName, dlt);
741 } else {
742 fprintf(stderr,
743 "reading from file %s, link-type %s (%s)\n",
744 RFileName, dlt_name,
745 pcap_datalink_val_to_description(dlt));
746 }
747 localnet = 0;
748 netmask = 0;
749 if (fflag != 0)
750 error("-f and -r options are incompatible");
751 } else {
752 if (device == NULL) {
753 device = pcap_lookupdev(ebuf);
754 if (device == NULL)
755 error("%s", ebuf);
756 }
757 #ifdef WIN32
758 if(IsTextUnicode(device,
759 wcslen((short*)device), // Device always ends with a double \0, so this way to determine its
760 // length should be always valid
761 NULL))
762 {
763 fprintf(stderr, "%s: listening on %ws\n", program_name, device);
764 }
765 else
766 {
767 fprintf(stderr, "%s: listening on %s\n", program_name, device);
768 }
769
770 fflush(stderr);
771 #endif /* WIN32 */
772 *ebuf = '\0';
773 pd = pcap_open_live(device, snaplen, !pflag, 1000, ebuf);
774 if (pd == NULL)
775 error("%s", ebuf);
776 else if (*ebuf)
777 warning("%s", ebuf);
778 /*
779 * Let user own process after socket has been opened.
780 */
781 #ifndef WIN32
782 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
783 fprintf(stderr, "Warning: setgid/setuid failed !\n");
784 #endif /* WIN32 */
785 #ifdef WIN32
786 if(UserBufferSize != 1000000)
787 if(pcap_setbuff(pd, UserBufferSize)==-1){
788 error("%s", pcap_geterr(pd));
789 }
790 #endif /* WIN32 */
791 if (Lflag)
792 show_dlts_and_exit(pd);
793 if (dlt >= 0) {
794 #ifdef HAVE_PCAP_SET_DATALINK
795 if (pcap_set_datalink(pd, dlt) < 0)
796 error("%s", pcap_geterr(pd));
797 #else
798 /*
799 * We don't actually support changing the
800 * data link type, so we only let them
801 * set it to what it already is.
802 */
803 if (dlt != pcap_datalink(pd)) {
804 error("%s is not one of the DLTs supported by this device\n",
805 dlt_name);
806 }
807 #endif
808 (void)fprintf(stderr, "%s: data link type %s\n",
809 program_name, dlt_name);
810 (void)fflush(stderr);
811 }
812 i = pcap_snapshot(pd);
813 if (snaplen < i) {
814 warning("snaplen raised from %d to %d", snaplen, i);
815 snaplen = i;
816 }
817 if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
818 localnet = 0;
819 netmask = 0;
820 warning("%s", ebuf);
821 }
822 }
823 if (infile)
824 cmdbuf = read_infile(infile);
825 else
826 cmdbuf = copy_argv(&argv[optind]);
827
828 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
829 error("%s", pcap_geterr(pd));
830 if (dflag) {
831 bpf_dump(&fcode, dflag);
832 pcap_close(pd);
833 exit(0);
834 }
835 init_addrtoname(localnet, netmask);
836
837 #ifndef WIN32
838 (void)setsignal(SIGPIPE, cleanup);
839 #endif /* WIN32 */
840 (void)setsignal(SIGTERM, cleanup);
841 (void)setsignal(SIGINT, cleanup);
842 /* Cooperate with nohup(1) */
843 #ifndef WIN32
844 if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
845 (void)setsignal(SIGHUP, oldhandler);
846 #endif /* WIN32 */
847
848 if (pcap_setfilter(pd, &fcode) < 0)
849 error("%s", pcap_geterr(pd));
850 if (WFileName) {
851 pcap_dumper_t *p;
852
853 WFileNameAlt = (char *)malloc(strlen(WFileName) + MAX_CFLAG_CHARS + 1);
854 if (WFileNameAlt == NULL)
855 error("malloc of WFileNameAlt");
856 MakeFilename(WFileNameAlt, WFileName, 0, WflagChars);
857 p = pcap_dump_open(pd, WFileNameAlt);
858 if (p == NULL)
859 error("%s", pcap_geterr(pd));
860 if (Cflag != 0) {
861 callback = dump_packet_and_trunc;
862 dumpinfo.WFileName = WFileName;
863 dumpinfo.pd = pd;
864 dumpinfo.p = p;
865 pcap_userdata = (u_char *)&dumpinfo;
866 } else {
867 callback = dump_packet;
868 pcap_userdata = (u_char *)p;
869 }
870 } else {
871 type = pcap_datalink(pd);
872 printinfo.printer = lookup_printer(type);
873 if (printinfo.printer == NULL) {
874 dlt_name = pcap_datalink_val_to_name(type);
875 if (dlt_name != NULL)
876 error("unsupported data link type %s", dlt_name);
877 else
878 error("unsupported data link type %d", type);
879 }
880 callback = print_packet;
881 pcap_userdata = (u_char *)&printinfo;
882 }
883 #ifndef WIN32
884 /*
885 * We cannot do this earlier, because we want to be able to open
886 * the file (if done) for writing before giving up permissions.
887 */
888 if (username) {
889 droproot(username);
890 }
891 #endif /* WIN32 */
892 #ifdef SIGINFO
893 (void)setsignal(SIGINFO, requestinfo);
894 #endif
895
896 if (vflag > 0 && WFileName) {
897 /*
898 * When capturing to a file, "-v" means tcpdump should,
899 * every 10 secodns, "v"erbosely report the number of
900 * packets captured.
901 */
902 #ifdef USE_WIN32_MM_TIMER
903 /* call verbose_stats_dump() each 1000 +/-100msec */
904 timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
905 setvbuf(stderr, NULL, _IONBF, 0);
906 #elif defined(HAVE_ALARM)
907 (void)setsignal(SIGALRM, verbose_stats_dump);
908 alarm(1);
909 #endif
910 }
911
912 #ifndef WIN32
913 if (RFileName == NULL) {
914 int dlt;
915 const char *dlt_name;
916
917 if (!vflag && !WFileName) {
918 (void)fprintf(stderr,
919 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
920 program_name);
921 } else
922 (void)fprintf(stderr, "%s: ", program_name);
923 dlt = pcap_datalink(pd);
924 dlt_name = pcap_datalink_val_to_name(dlt);
925 if (dlt_name == NULL) {
926 (void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
927 device, dlt, snaplen);
928 } else {
929 (void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
930 device, dlt_name,
931 pcap_datalink_val_to_description(dlt), snaplen);
932 }
933 (void)fflush(stderr);
934 }
935 #endif /* WIN32 */
936 status = pcap_loop(pd, cnt, callback, pcap_userdata);
937 if (WFileName == NULL) {
938 /*
939 * We're printing packets. Flush the printed output,
940 * so it doesn't get intermingled with error output.
941 */
942 if (status == -2) {
943 /*
944 * We got interrupted, so perhaps we didn't
945 * manage to finish a line we were printing.
946 * Print an extra newline, just in case.
947 */
948 putchar('\n');
949 }
950 (void)fflush(stdout);
951 }
952 if (status == -1) {
953 /*
954 * Error. Report it.
955 */
956 (void)fprintf(stderr, "%s: pcap_loop: %s\n",
957 program_name, pcap_geterr(pd));
958 }
959 if (RFileName == NULL) {
960 /*
961 * We're doing a live capture. Report the capture
962 * statistics.
963 */
964 info(1);
965 }
966 pcap_close(pd);
967 exit(status == -1 ? 1 : 0);
968 }
969
970 /* make a clean exit on interrupts */
971 static RETSIGTYPE
972 cleanup(int signo _U_)
973 {
974 #ifdef USE_WIN32_MM_TIMER
975 if (timer_id)
976 timeKillEvent(timer_id);
977 timer_id = 0;
978 #elif defined(HAVE_ALARM)
979 alarm(0);
980 #endif
981
982 #ifdef HAVE_PCAP_BREAKLOOP
983 /*
984 * We have "pcap_breakloop()"; use it, so that we do as little
985 * as possible in the signal handler (it's probably not safe
986 * to do anything with standard I/O streams in a signal handler -
987 * the ANSI C standard doesn't say it is).
988 */
989 pcap_breakloop(pd);
990 #else
991 /*
992 * We don't have "pcap_breakloop()"; this isn't safe, but
993 * it's the best we can do. Print the summary if we're
994 * not reading from a savefile - i.e., if we're doing a
995 * live capture - and exit.
996 */
997 if (pd != NULL && pcap_file(pd) == NULL) {
998 /*
999 * We got interrupted, so perhaps we didn't
1000 * manage to finish a line we were printing.
1001 * Print an extra newline, just in case.
1002 */
1003 putchar('\n');
1004 (void)fflush(stdout);
1005 info(1);
1006 }
1007 exit(0);
1008 #endif
1009 }
1010
1011 static void
1012 info(register int verbose)
1013 {
1014 struct pcap_stat stat;
1015
1016 if (pcap_stats(pd, &stat) < 0) {
1017 (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
1018 return;
1019 }
1020
1021 if (!verbose)
1022 fprintf(stderr, "%s: ", program_name);
1023
1024 (void)fprintf(stderr, "%u packets captured", packets_captured);
1025 if (!verbose)
1026 fputs(", ", stderr);
1027 else
1028 putc('\n', stderr);
1029 (void)fprintf(stderr, "%d packets received by filter", stat.ps_recv);
1030 if (!verbose)
1031 fputs(", ", stderr);
1032 else
1033 putc('\n', stderr);
1034 (void)fprintf(stderr, "%d packets dropped by kernel\n", stat.ps_drop);
1035 infoprint = 0;
1036 }
1037
1038 static void
1039 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1040 {
1041 struct dump_info *dump_info;
1042 char *name;
1043
1044 ++packets_captured;
1045
1046 ++infodelay;
1047
1048 dump_info = (struct dump_info *)user;
1049
1050 /*
1051 * XXX - this won't prevent capture files from getting
1052 * larger than Cflag - the last packet written to the
1053 * file could put it over Cflag.
1054 */
1055 if (ftell((FILE *)dump_info->p) > Cflag) {
1056 /*
1057 * Close the current file and open a new one.
1058 */
1059 pcap_dump_close(dump_info->p);
1060 Cflag_count++;
1061 if (Wflag > 0) {
1062 if (Cflag_count >= Wflag)
1063 Cflag_count = 0;
1064 } else {
1065 if (Cflag_count >= MAX_CFLAG)
1066 error("too many output files");
1067 }
1068 name = (char *)malloc(strlen(dump_info->WFileName) + MAX_CFLAG_CHARS + 1);
1069 if (name == NULL)
1070 error("dump_packet_and_trunc: malloc");
1071 MakeFilename(name, dump_info->WFileName, Cflag_count, WflagChars);
1072 dump_info->p = pcap_dump_open(dump_info->pd, name);
1073 free(name);
1074 if (dump_info->p == NULL)
1075 error("%s", pcap_geterr(pd));
1076 }
1077
1078 pcap_dump((u_char *)dump_info->p, h, sp);
1079 #ifdef HAVE_PCAP_DUMP_FLUSH
1080 if (Uflag)
1081 pcap_dump_flush(dump_info->p);
1082 #endif
1083
1084 --infodelay;
1085 if (infoprint)
1086 info(0);
1087 }
1088
1089 static void
1090 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1091 {
1092 ++packets_captured;
1093
1094 ++infodelay;
1095
1096 pcap_dump(user, h, sp);
1097 #ifdef HAVE_PCAP_DUMP_FLUSH
1098 if (Uflag)
1099 pcap_dump_flush((pcap_dumper_t *)user);
1100 #endif
1101
1102 --infodelay;
1103 if (infoprint)
1104 info(0);
1105 }
1106
1107 static void
1108 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1109 {
1110 struct print_info *print_info;
1111 u_int hdrlen;
1112
1113 ++packets_captured;
1114
1115 ++infodelay;
1116 ts_print(&h->ts);
1117
1118 print_info = (struct print_info *)user;
1119
1120 /*
1121 * Some printers want to check that they're not walking off the
1122 * end of the packet.
1123 * Rather than pass it all the way down, we set this global.
1124 */
1125 snapend = sp + h->caplen;
1126
1127 hdrlen = (*print_info->printer)(h, sp);
1128 if (xflag) {
1129 /*
1130 * Print the raw packet data.
1131 */
1132 if (xflag > 1) {
1133 /*
1134 * Include the link-layer header.
1135 */
1136 default_print(sp, h->caplen);
1137 } else {
1138 /*
1139 * Don't include the link-layer header - and if
1140 * we have nothing past the link-layer header,
1141 * print nothing.
1142 */
1143 if (h->caplen > hdrlen)
1144 default_print(sp + hdrlen,
1145 h->caplen - hdrlen);
1146 }
1147 }
1148
1149 putchar('\n');
1150
1151 --infodelay;
1152 if (infoprint)
1153 info(0);
1154 }
1155
1156 #ifdef WIN32
1157 /*
1158 * XXX - there should really be libpcap calls to get the version
1159 * number as a string (the string would be generated from #defines
1160 * at run time, so that it's not generated from string constants
1161 * in the library, as, on many UNIX systems, those constants would
1162 * be statically linked into the application executable image, and
1163 * would thus reflect the version of libpcap on the system on
1164 * which the application was *linked*, not the system on which it's
1165 * *running*.
1166 *
1167 * That routine should be documented, unlike the "version[]"
1168 * string, so that UNIX vendors providing their own libpcaps
1169 * don't omit it (as a couple of vendors have...).
1170 *
1171 * Packet.dll should perhaps also export a routine to return the
1172 * version number of the Packet.dll code, to supply the
1173 * "Wpcap_version" information on Windows.
1174 */
1175 char WDversion[]="current-cvs.tcpdump.org";
1176 #if !defined(HAVE_GENERATED_VERSION)
1177 char version[]="current-cvs.tcpdump.org";
1178 #endif
1179 char pcap_version[]="current-cvs.tcpdump.org";
1180 char Wpcap_version[]="3.0 alpha";
1181 #endif
1182
1183 /*
1184 * By default, print the specified data out in hex.
1185 */
1186 void
1187 default_print(register const u_char *bp, register u_int length)
1188 {
1189 ascii_print("\n\t", bp, length); /* pass on lf and identation string */
1190 }
1191
1192 #ifdef SIGINFO
1193 RETSIGTYPE requestinfo(int signo _U_)
1194 {
1195 if (infodelay)
1196 ++infoprint;
1197 else
1198 info(0);
1199 }
1200 #endif
1201
1202 /*
1203 * Called once each second in verbose mode while dumping to file
1204 */
1205 #ifdef USE_WIN32_MM_TIMER
1206 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
1207 DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
1208 {
1209 struct pcap_stat stat;
1210
1211 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
1212 fprintf(stderr, "Got %u\r", packets_captured);
1213 }
1214 #elif defined(HAVE_ALARM)
1215 static void verbose_stats_dump(int sig _U_)
1216 {
1217 struct pcap_stat stat;
1218
1219 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
1220 fprintf(stderr, "Got %u\r", packets_captured);
1221 alarm(1);
1222 }
1223 #endif
1224
1225 static void
1226 usage(void)
1227 {
1228 extern char version[];
1229 #ifndef HAVE_PCAP_LIB_VERSION
1230 #if defined(WIN32) || defined(HAVE_PCAP_VERSION)
1231 extern char pcap_version[];
1232 #else /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
1233 static char pcap_version[] = "unknown";
1234 #endif /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
1235 #endif /* HAVE_PCAP_LIB_VERSION */
1236
1237 #ifdef HAVE_PCAP_LIB_VERSION
1238 (void)fprintf(stderr, "%s version %s\n", program_name, version);
1239 (void)fprintf(stderr, "%s\n", pcap_lib_version());
1240 #else /* HAVE_PCAP_LIB_VERSION */
1241 #ifdef WIN32
1242 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
1243 (void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
1244 #else /* WIN32 */
1245 (void)fprintf(stderr, "%s version %s\n", program_name, version);
1246 (void)fprintf(stderr, "libpcap version %s\n", pcap_version);
1247 #endif /* WIN32 */
1248 #endif /* HAVE_PCAP_LIB_VERSION */
1249 (void)fprintf(stderr,
1250 "Usage: %s [-aAd" D_FLAG "eflLnNOpqRStu" U_FLAG "vxX]" B_FLAG_USAGE " [-c count] [ -C file_size ]\n", program_name);
1251 (void)fprintf(stderr,
1252 "\t\t[ -E algo:secret ] [ -F file ] [ -i interface ] [ -r file ]\n");
1253 (void)fprintf(stderr,
1254 "\t\t[ -s snaplen ] [ -T type ] [ -w file ] [ -W filecount ]\n");
1255 (void)fprintf(stderr,
1256 "\t\t[ -y datalinktype ] [ -Z user ]\n");
1257 (void)fprintf(stderr,
1258 "\t\t[ expression ]\n");
1259 exit(1);
1260 }