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