]> The Tcpdump Group git mirrors - tcpdump/blob - tcpdump.c
Merge remote branch 'github/master'
[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.283 2008-09-25 21:45:50 guy 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 <limits.h>
69 #ifndef WIN32
70 #include <sys/wait.h>
71 #include <sys/resource.h>
72 #include <pwd.h>
73 #include <grp.h>
74 #include <errno.h>
75 #endif /* WIN32 */
76
77 /* capabilities convinience library */
78 #ifdef HAVE_CAP_NG_H
79 #include <cap-ng.h>
80 #endif /* HAVE_CAP_NG_H */
81
82 #include "netdissect.h"
83 #include "interface.h"
84 #include "addrtoname.h"
85 #include "machdep.h"
86 #include "setsignal.h"
87 #include "gmt2local.h"
88 #include "pcap-missing.h"
89
90 #ifndef NAME_MAX
91 #define NAME_MAX 255
92 #endif
93
94 #ifdef SIGINFO
95 #define SIGNAL_REQ_INFO SIGINFO
96 #elif SIGUSR1
97 #define SIGNAL_REQ_INFO SIGUSR1
98 #endif
99
100 netdissect_options Gndo;
101 netdissect_options *gndo = &Gndo;
102
103 static int dflag; /* print filter code */
104 static int Lflag; /* list available data link types and exit */
105 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
106 static int Jflag; /* list available time stamp types */
107 #endif
108 static char *zflag = NULL; /* compress each savefile using a specified command (like gzip or bzip2) */
109
110 static int infodelay;
111 static int infoprint;
112
113 char *program_name;
114
115 int32_t thiszone; /* seconds offset from gmt to local time */
116
117 /* Forwards */
118 static RETSIGTYPE cleanup(int);
119 static RETSIGTYPE child_cleanup(int);
120 static void usage(void) __attribute__((noreturn));
121 static void show_dlts_and_exit(const char *device, pcap_t *pd) __attribute__((noreturn));
122
123 static void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
124 static void ndo_default_print(netdissect_options *, const u_char *, u_int);
125 static void dump_packet_and_trunc(u_char *, const struct pcap_pkthdr *, const u_char *);
126 static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
127 static void droproot(const char *, const char *);
128 static void ndo_error(netdissect_options *ndo, const char *fmt, ...)
129 __attribute__ ((noreturn, format (printf, 2, 3)));
130 static void ndo_warning(netdissect_options *ndo, const char *fmt, ...);
131
132 #ifdef SIGNAL_REQ_INFO
133 RETSIGTYPE requestinfo(int);
134 #endif
135
136 #if defined(USE_WIN32_MM_TIMER)
137 #include <MMsystem.h>
138 static UINT timer_id;
139 static void CALLBACK verbose_stats_dump(UINT, UINT, DWORD_PTR, DWORD_PTR, DWORD_PTR);
140 #elif defined(HAVE_ALARM)
141 static void verbose_stats_dump(int sig);
142 #endif
143
144 static void info(int);
145 static u_int packets_captured;
146
147 struct printer {
148 if_printer f;
149 int type;
150 };
151
152
153 struct ndo_printer {
154 if_ndo_printer f;
155 int type;
156 };
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 { token_if_print, DLT_IEEE802 },
165 #ifdef DLT_LANE8023
166 { lane_if_print, DLT_LANE8023 },
167 #endif
168 #ifdef DLT_CIP
169 { cip_if_print, DLT_CIP },
170 #endif
171 #ifdef DLT_ATM_CLIP
172 { cip_if_print, DLT_ATM_CLIP },
173 #endif
174 { sl_if_print, DLT_SLIP },
175 #ifdef DLT_SLIP_BSDOS
176 { sl_bsdos_if_print, DLT_SLIP_BSDOS },
177 #endif
178 { ppp_if_print, DLT_PPP },
179 #ifdef DLT_PPP_WITHDIRECTION
180 { ppp_if_print, DLT_PPP_WITHDIRECTION },
181 #endif
182 #ifdef DLT_PPP_BSDOS
183 { ppp_bsdos_if_print, DLT_PPP_BSDOS },
184 #endif
185 { fddi_if_print, DLT_FDDI },
186 { null_if_print, DLT_NULL },
187 #ifdef DLT_LOOP
188 { null_if_print, DLT_LOOP },
189 #endif
190 { raw_if_print, DLT_RAW },
191 { atm_if_print, DLT_ATM_RFC1483 },
192 #ifdef DLT_C_HDLC
193 { chdlc_if_print, DLT_C_HDLC },
194 #endif
195 #ifdef DLT_HDLC
196 { chdlc_if_print, DLT_HDLC },
197 #endif
198 #ifdef DLT_PPP_SERIAL
199 { ppp_hdlc_if_print, DLT_PPP_SERIAL },
200 #endif
201 #ifdef DLT_PPP_ETHER
202 { pppoe_if_print, DLT_PPP_ETHER },
203 #endif
204 #ifdef DLT_LINUX_SLL
205 { sll_if_print, DLT_LINUX_SLL },
206 #endif
207 #ifdef DLT_IEEE802_11
208 { ieee802_11_if_print, DLT_IEEE802_11},
209 #endif
210 #ifdef DLT_LTALK
211 { ltalk_if_print, DLT_LTALK },
212 #endif
213 #if defined(DLT_PFLOG) && defined(HAVE_NET_PFVAR_H)
214 { pflog_if_print, DLT_PFLOG },
215 #endif
216 #ifdef DLT_FR
217 { fr_if_print, DLT_FR },
218 #endif
219 #ifdef DLT_FRELAY
220 { fr_if_print, DLT_FRELAY },
221 #endif
222 #ifdef DLT_SUNATM
223 { sunatm_if_print, DLT_SUNATM },
224 #endif
225 #ifdef DLT_IP_OVER_FC
226 { ipfc_if_print, DLT_IP_OVER_FC },
227 #endif
228 #ifdef DLT_PRISM_HEADER
229 { prism_if_print, DLT_PRISM_HEADER },
230 #endif
231 #ifdef DLT_IEEE802_11_RADIO
232 { ieee802_11_radio_if_print, DLT_IEEE802_11_RADIO },
233 #endif
234 #ifdef DLT_ENC
235 { enc_if_print, DLT_ENC },
236 #endif
237 #ifdef DLT_SYMANTEC_FIREWALL
238 { symantec_if_print, DLT_SYMANTEC_FIREWALL },
239 #endif
240 #ifdef DLT_APPLE_IP_OVER_IEEE1394
241 { ap1394_if_print, DLT_APPLE_IP_OVER_IEEE1394 },
242 #endif
243 #ifdef DLT_IEEE802_11_RADIO_AVS
244 { ieee802_11_radio_avs_if_print, DLT_IEEE802_11_RADIO_AVS },
245 #endif
246 #ifdef DLT_JUNIPER_ATM1
247 { juniper_atm1_print, DLT_JUNIPER_ATM1 },
248 #endif
249 #ifdef DLT_JUNIPER_ATM2
250 { juniper_atm2_print, DLT_JUNIPER_ATM2 },
251 #endif
252 #ifdef DLT_JUNIPER_MFR
253 { juniper_mfr_print, DLT_JUNIPER_MFR },
254 #endif
255 #ifdef DLT_JUNIPER_MLFR
256 { juniper_mlfr_print, DLT_JUNIPER_MLFR },
257 #endif
258 #ifdef DLT_JUNIPER_MLPPP
259 { juniper_mlppp_print, DLT_JUNIPER_MLPPP },
260 #endif
261 #ifdef DLT_JUNIPER_PPPOE
262 { juniper_pppoe_print, DLT_JUNIPER_PPPOE },
263 #endif
264 #ifdef DLT_JUNIPER_PPPOE_ATM
265 { juniper_pppoe_atm_print, DLT_JUNIPER_PPPOE_ATM },
266 #endif
267 #ifdef DLT_JUNIPER_GGSN
268 { juniper_ggsn_print, DLT_JUNIPER_GGSN },
269 #endif
270 #ifdef DLT_JUNIPER_ES
271 { juniper_es_print, DLT_JUNIPER_ES },
272 #endif
273 #ifdef DLT_JUNIPER_MONITOR
274 { juniper_monitor_print, DLT_JUNIPER_MONITOR },
275 #endif
276 #ifdef DLT_JUNIPER_SERVICES
277 { juniper_services_print, DLT_JUNIPER_SERVICES },
278 #endif
279 #ifdef DLT_JUNIPER_ETHER
280 { juniper_ether_print, DLT_JUNIPER_ETHER },
281 #endif
282 #ifdef DLT_JUNIPER_PPP
283 { juniper_ppp_print, DLT_JUNIPER_PPP },
284 #endif
285 #ifdef DLT_JUNIPER_FRELAY
286 { juniper_frelay_print, DLT_JUNIPER_FRELAY },
287 #endif
288 #ifdef DLT_JUNIPER_CHDLC
289 { juniper_chdlc_print, DLT_JUNIPER_CHDLC },
290 #endif
291 #ifdef DLT_MFR
292 { mfr_if_print, DLT_MFR },
293 #endif
294 #if defined(DLT_BLUETOOTH_HCI_H4_WITH_PHDR) && defined(HAVE_PCAP_BLUETOOTH_H)
295 { bt_if_print, DLT_BLUETOOTH_HCI_H4_WITH_PHDR},
296 #endif
297 #ifdef HAVE_PCAP_USB_H
298 #ifdef DLT_USB_LINUX
299 { usb_linux_48_byte_print, DLT_USB_LINUX},
300 #endif /* DLT_USB_LINUX */
301 #ifdef DLT_USB_LINUX_MMAPPED
302 { usb_linux_64_byte_print, DLT_USB_LINUX_MMAPPED},
303 #endif /* DLT_USB_LINUX_MMAPPED */
304 #endif /* HAVE_PCAP_USB_H */
305 #ifdef DLT_IPV4
306 { raw_if_print, DLT_IPV4 },
307 #endif
308 #ifdef DLT_IPV6
309 { raw_if_print, DLT_IPV6 },
310 #endif
311 { NULL, 0 },
312 };
313
314 static struct ndo_printer ndo_printers[] = {
315 { ether_if_print, DLT_EN10MB },
316 #ifdef DLT_IPNET
317 { ipnet_if_print, DLT_IPNET },
318 #endif
319 #ifdef DLT_IEEE802_15_4
320 { ieee802_15_4_if_print, DLT_IEEE802_15_4 },
321 #endif
322 #ifdef DLT_IEEE802_15_4_NOFCS
323 { ieee802_15_4_if_print, DLT_IEEE802_15_4_NOFCS },
324 #endif
325 #ifdef DLT_PPI
326 { ppi_if_print, DLT_PPI },
327 #endif
328 #ifdef DLT_NETANALYZER
329 { netanalyzer_if_print, DLT_NETANALYZER },
330 #endif
331 #ifdef DLT_NETANALYZER_TRANSPARENT
332 { netanalyzer_transparent_if_print, DLT_NETANALYZER_TRANSPARENT },
333 #endif
334 { NULL, 0 },
335 };
336
337 if_printer
338 lookup_printer(int type)
339 {
340 struct printer *p;
341
342 for (p = printers; p->f; ++p)
343 if (type == p->type)
344 return p->f;
345
346 return NULL;
347 /* NOTREACHED */
348 }
349
350 if_ndo_printer
351 lookup_ndo_printer(int type)
352 {
353 struct ndo_printer *p;
354
355 for (p = ndo_printers; p->f; ++p)
356 if (type == p->type)
357 return p->f;
358
359 return NULL;
360 /* NOTREACHED */
361 }
362
363 static pcap_t *pd;
364
365 static int supports_monitor_mode;
366
367 extern int optind;
368 extern int opterr;
369 extern char *optarg;
370
371 struct print_info {
372 netdissect_options *ndo;
373 union {
374 if_printer printer;
375 if_ndo_printer ndo_printer;
376 } p;
377 int ndo_type;
378 };
379
380 struct dump_info {
381 char *WFileName;
382 char *CurrentFileName;
383 pcap_t *pd;
384 pcap_dumper_t *p;
385 };
386
387 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
388 static void
389 show_tstamp_types_and_exit(const char *device, pcap_t *pd)
390 {
391 int n_tstamp_types;
392 int *tstamp_types = 0;
393 const char *tstamp_type_name;
394 int i;
395
396 n_tstamp_types = pcap_list_tstamp_types(pd, &tstamp_types);
397 if (n_tstamp_types < 0)
398 error("%s", pcap_geterr(pd));
399
400 if (n_tstamp_types == 0) {
401 fprintf(stderr, "Time stamp type cannot be set for %s\n",
402 device);
403 exit(0);
404 }
405 fprintf(stderr, "Time stamp types for %s (use option -j to set):\n",
406 device);
407 for (i = 0; i < n_tstamp_types; i++) {
408 tstamp_type_name = pcap_tstamp_type_val_to_name(tstamp_types[i]);
409 if (tstamp_type_name != NULL) {
410 (void) fprintf(stderr, " %s (%s)\n", tstamp_type_name,
411 pcap_tstamp_type_val_to_description(tstamp_types[i]));
412 } else {
413 (void) fprintf(stderr, " %d\n", tstamp_types[i]);
414 }
415 }
416 pcap_free_tstamp_types(tstamp_types);
417 exit(0);
418 }
419 #endif
420
421 static void
422 show_dlts_and_exit(const char *device, pcap_t *pd)
423 {
424 int n_dlts;
425 int *dlts = 0;
426 const char *dlt_name;
427
428 n_dlts = pcap_list_datalinks(pd, &dlts);
429 if (n_dlts < 0)
430 error("%s", pcap_geterr(pd));
431 else if (n_dlts == 0 || !dlts)
432 error("No data link types.");
433
434 /*
435 * If the interface is known to support monitor mode, indicate
436 * whether these are the data link types available when not in
437 * monitor mode, if -I wasn't specified, or when in monitor mode,
438 * when -I was specified (the link-layer types available in
439 * monitor mode might be different from the ones available when
440 * not in monitor mode).
441 */
442 if (supports_monitor_mode)
443 (void) fprintf(stderr, "Data link types for %s %s (use option -y to set):\n",
444 device,
445 Iflag ? "when in monitor mode" : "when not in monitor mode");
446 else
447 (void) fprintf(stderr, "Data link types for %s (use option -y to set):\n",
448 device);
449
450 while (--n_dlts >= 0) {
451 dlt_name = pcap_datalink_val_to_name(dlts[n_dlts]);
452 if (dlt_name != NULL) {
453 (void) fprintf(stderr, " %s (%s)", dlt_name,
454 pcap_datalink_val_to_description(dlts[n_dlts]));
455
456 /*
457 * OK, does tcpdump handle that type?
458 */
459 if (lookup_printer(dlts[n_dlts]) == NULL
460 && lookup_ndo_printer(dlts[n_dlts]) == NULL)
461 (void) fprintf(stderr, " (printing not supported)");
462 fprintf(stderr, "\n");
463 } else {
464 (void) fprintf(stderr, " DLT %d (printing not supported)\n",
465 dlts[n_dlts]);
466 }
467 }
468 #ifdef HAVE_PCAP_FREE_DATALINKS
469 pcap_free_datalinks(dlts);
470 #endif
471 exit(0);
472 }
473
474 /*
475 * Set up flags that might or might not be supported depending on the
476 * version of libpcap we're using.
477 */
478 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
479 #define B_FLAG "B:"
480 #define B_FLAG_USAGE " [ -B size ]"
481 #else /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
482 #define B_FLAG
483 #define B_FLAG_USAGE
484 #endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
485
486 #ifdef HAVE_PCAP_CREATE
487 #define I_FLAG "I"
488 #else /* HAVE_PCAP_CREATE */
489 #define I_FLAG
490 #endif /* HAVE_PCAP_CREATE */
491
492 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
493 #define j_FLAG "j:"
494 #define j_FLAG_USAGE " [ -j tstamptype ]"
495 #define J_FLAG "J"
496 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
497 #define j_FLAG
498 #define j_FLAG_USAGE
499 #define J_FLAG
500 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
501
502 #ifdef HAVE_PCAP_FINDALLDEVS
503 #ifndef HAVE_PCAP_IF_T
504 #undef HAVE_PCAP_FINDALLDEVS
505 #endif
506 #endif
507
508 #ifdef HAVE_PCAP_FINDALLDEVS
509 #define D_FLAG "D"
510 #else
511 #define D_FLAG
512 #endif
513
514 #ifdef HAVE_PCAP_DUMP_FLUSH
515 #define U_FLAG "U"
516 #else
517 #define U_FLAG
518 #endif
519
520 #ifndef WIN32
521 /* Drop root privileges and chroot if necessary */
522 static void
523 droproot(const char *username, const char *chroot_dir)
524 {
525 struct passwd *pw = NULL;
526
527 if (chroot_dir && !username) {
528 fprintf(stderr, "tcpdump: Chroot without dropping root is insecure\n");
529 exit(1);
530 }
531
532 pw = getpwnam(username);
533 if (pw) {
534 if (chroot_dir) {
535 if (chroot(chroot_dir) != 0 || chdir ("/") != 0) {
536 fprintf(stderr, "tcpdump: Couldn't chroot/chdir to '%.64s': %s\n",
537 chroot_dir, pcap_strerror(errno));
538 exit(1);
539 }
540 }
541 #ifdef HAVE_CAP_NG_H
542 int ret = capng_change_id(pw->pw_uid, pw->pw_gid, CAPNG_NO_FLAG);
543 if (ret < 0) {
544 printf("error : ret %d\n", ret);
545 }
546 /* We don't need CAP_SETUID and CAP_SETGID */
547 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_SETUID);
548 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_SETUID);
549 capng_update(CAPNG_DROP, CAPNG_PERMITTED, CAP_SETUID);
550 capng_update(CAPNG_DROP, CAPNG_PERMITTED, CAP_SETUID);
551 capng_apply(CAPNG_SELECT_BOTH);
552
553 #else
554 if (initgroups(pw->pw_name, pw->pw_gid) != 0 ||
555 setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0) {
556 fprintf(stderr, "tcpdump: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
557 username,
558 (unsigned long)pw->pw_uid,
559 (unsigned long)pw->pw_gid,
560 pcap_strerror(errno));
561 exit(1);
562 }
563 #endif /* HAVE_CAP_NG_H */
564 }
565 else {
566 fprintf(stderr, "tcpdump: Couldn't find user '%.32s'\n",
567 username);
568 exit(1);
569 }
570 }
571 #endif /* WIN32 */
572
573 static int
574 getWflagChars(int x)
575 {
576 int c = 0;
577
578 x -= 1;
579 while (x > 0) {
580 c += 1;
581 x /= 10;
582 }
583
584 return c;
585 }
586
587
588 static void
589 MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
590 {
591 char *filename = malloc(NAME_MAX + 1);
592
593 /* Process with strftime if Gflag is set. */
594 if (Gflag != 0) {
595 struct tm *local_tm;
596
597 /* Convert Gflag_time to a usable format */
598 if ((local_tm = localtime(&Gflag_time)) == NULL) {
599 error("MakeTimedFilename: localtime");
600 }
601
602 /* There's no good way to detect an error in strftime since a return
603 * value of 0 isn't necessarily failure.
604 */
605 strftime(filename, NAME_MAX, orig_name, local_tm);
606 } else {
607 strncpy(filename, orig_name, NAME_MAX);
608 }
609
610 if (cnt == 0 && max_chars == 0)
611 strncpy(buffer, filename, NAME_MAX + 1);
612 else
613 if (snprintf(buffer, NAME_MAX + 1, "%s%0*d", filename, max_chars, cnt) > NAME_MAX)
614 /* Report an error if the filename is too large */
615 error("too many output files or filename is too long (> %d)", NAME_MAX);
616 free(filename);
617 }
618
619 static int tcpdump_printf(netdissect_options *ndo _U_,
620 const char *fmt, ...)
621 {
622
623 va_list args;
624 int ret;
625
626 va_start(args, fmt);
627 ret=vfprintf(stdout, fmt, args);
628 va_end(args);
629
630 return ret;
631 }
632
633 int
634 main(int argc, char **argv)
635 {
636 register int cnt, op, i;
637 bpf_u_int32 localnet, netmask;
638 register char *cp, *infile, *cmdbuf, *device, *RFileName, *WFileName;
639 pcap_handler callback;
640 int type;
641 struct bpf_program fcode;
642 #ifndef WIN32
643 RETSIGTYPE (*oldhandler)(int);
644 #endif
645 struct print_info printinfo;
646 struct dump_info dumpinfo;
647 u_char *pcap_userdata;
648 char ebuf[PCAP_ERRBUF_SIZE];
649 char *username = NULL;
650 char *chroot_dir = NULL;
651 #ifdef HAVE_PCAP_FINDALLDEVS
652 pcap_if_t *devpointer;
653 int devnum;
654 #endif
655 int status;
656 #ifdef WIN32
657 if(wsockinit() != 0) return 1;
658 #endif /* WIN32 */
659
660 jflag=-1; /* not set */
661 gndo->ndo_Oflag=1;
662 gndo->ndo_Rflag=1;
663 gndo->ndo_dlt=-1;
664 gndo->ndo_default_print=ndo_default_print;
665 gndo->ndo_printf=tcpdump_printf;
666 gndo->ndo_error=ndo_error;
667 gndo->ndo_warning=ndo_warning;
668 gndo->ndo_snaplen = DEFAULT_SNAPLEN;
669
670 cnt = -1;
671 device = NULL;
672 infile = NULL;
673 RFileName = NULL;
674 WFileName = NULL;
675 if ((cp = strrchr(argv[0], '/')) != NULL)
676 program_name = cp + 1;
677 else
678 program_name = argv[0];
679
680 if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
681 error("%s", ebuf);
682
683 #ifdef LIBSMI
684 smiInit("tcpdump");
685 #endif
686
687 while (
688 (op = getopt(argc, argv, "aAb" B_FLAG "c:C:d" D_FLAG "eE:fF:G:hHi:" I_FLAG j_FLAG J_FLAG "KlLm:M:nNOpqr:Rs:StT:u" U_FLAG "vw:W:xXy:Yz:Z:")) != -1)
689 switch (op) {
690
691 case 'a':
692 /* compatibility for old -a */
693 break;
694
695 case 'A':
696 ++Aflag;
697 break;
698
699 case 'b':
700 ++bflag;
701 break;
702
703 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
704 case 'B':
705 Bflag = atoi(optarg)*1024;
706 if (Bflag <= 0)
707 error("invalid packet buffer size %s", optarg);
708 break;
709 #endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
710
711 case 'c':
712 cnt = atoi(optarg);
713 if (cnt <= 0)
714 error("invalid packet count %s", optarg);
715 break;
716
717 case 'C':
718 Cflag = atoi(optarg) * 1000000;
719 if (Cflag < 0)
720 error("invalid file size %s", optarg);
721 break;
722
723 case 'd':
724 ++dflag;
725 break;
726
727 #ifdef HAVE_PCAP_FINDALLDEVS
728 case 'D':
729 if (pcap_findalldevs(&devpointer, ebuf) < 0)
730 error("%s", ebuf);
731 else {
732 for (i = 0; devpointer != 0; i++) {
733 printf("%d.%s", i+1, devpointer->name);
734 if (devpointer->description != NULL)
735 printf(" (%s)", devpointer->description);
736 printf("\n");
737 devpointer = devpointer->next;
738 }
739 }
740 return 0;
741 #endif /* HAVE_PCAP_FINDALLDEVS */
742
743 case 'L':
744 Lflag++;
745 break;
746
747 case 'e':
748 ++eflag;
749 break;
750
751 case 'E':
752 #ifndef HAVE_LIBCRYPTO
753 warning("crypto code not compiled in");
754 #endif
755 gndo->ndo_espsecret = optarg;
756 break;
757
758 case 'f':
759 ++fflag;
760 break;
761
762 case 'F':
763 infile = optarg;
764 break;
765
766 case 'G':
767 Gflag = atoi(optarg);
768 if (Gflag < 0)
769 error("invalid number of seconds %s", optarg);
770
771 /* We will create one file initially. */
772 Gflag_count = 0;
773
774 /* Grab the current time for rotation use. */
775 if ((Gflag_time = time(NULL)) == (time_t)-1) {
776 error("main: can't get current time: %s",
777 pcap_strerror(errno));
778 }
779 break;
780
781 case 'h':
782 usage();
783 break;
784
785 case 'H':
786 ++Hflag;
787 break;
788
789 case 'i':
790 if (optarg[0] == '0' && optarg[1] == 0)
791 error("Invalid adapter index");
792
793 #ifdef HAVE_PCAP_FINDALLDEVS
794 /*
795 * If the argument is a number, treat it as
796 * an index into the list of adapters, as
797 * printed by "tcpdump -D".
798 *
799 * This should be OK on UNIX systems, as interfaces
800 * shouldn't have names that begin with digits.
801 * It can be useful on Windows, where more than
802 * one interface can have the same name.
803 */
804 if ((devnum = atoi(optarg)) != 0) {
805 if (devnum < 0)
806 error("Invalid adapter index");
807
808 if (pcap_findalldevs(&devpointer, ebuf) < 0)
809 error("%s", ebuf);
810 else {
811 /*
812 * Look for the devnum-th entry
813 * in the list of devices
814 * (1-based).
815 */
816 for (i = 0;
817 i < devnum-1 && devpointer != NULL;
818 i++, devpointer = devpointer->next)
819 ;
820 if (devpointer == NULL)
821 error("Invalid adapter index");
822 }
823 device = devpointer->name;
824 break;
825 }
826 #endif /* HAVE_PCAP_FINDALLDEVS */
827 device = optarg;
828 break;
829
830 #ifdef HAVE_PCAP_CREATE
831 case 'I':
832 ++Iflag;
833 break;
834 #endif /* HAVE_PCAP_CREATE */
835
836 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
837 case 'j':
838 jflag = pcap_tstamp_type_name_to_val(optarg);
839 if (jflag < 0)
840 error("invalid time stamp type %s", optarg);
841 break;
842
843 case 'J':
844 Jflag++;
845 break;
846 #endif
847
848 case 'l':
849 #ifdef WIN32
850 /*
851 * _IOLBF is the same as _IOFBF in Microsoft's C
852 * libraries; the only alternative they offer
853 * is _IONBF.
854 *
855 * XXX - this should really be checking for MSVC++,
856 * not WIN32, if, for example, MinGW has its own
857 * C library that is more UNIX-compatible.
858 */
859 setvbuf(stdout, NULL, _IONBF, 0);
860 #else /* WIN32 */
861 #ifdef HAVE_SETLINEBUF
862 setlinebuf(stdout);
863 #else
864 setvbuf(stdout, NULL, _IOLBF, 0);
865 #endif
866 #endif /* WIN32 */
867 break;
868
869 case 'K':
870 ++Kflag;
871 break;
872
873 case 'm':
874 #ifdef LIBSMI
875 if (smiLoadModule(optarg) == 0) {
876 error("could not load MIB module %s", optarg);
877 }
878 sflag = 1;
879 #else
880 (void)fprintf(stderr, "%s: ignoring option `-m %s' ",
881 program_name, optarg);
882 (void)fprintf(stderr, "(no libsmi support)\n");
883 #endif
884 break;
885
886 case 'M':
887 /* TCP-MD5 shared secret */
888 #ifndef HAVE_LIBCRYPTO
889 warning("crypto code not compiled in");
890 #endif
891 sigsecret = optarg;
892 break;
893
894 case 'n':
895 ++nflag;
896 break;
897
898 case 'N':
899 ++Nflag;
900 break;
901
902 case 'O':
903 Oflag = 0;
904 break;
905
906 case 'p':
907 ++pflag;
908 break;
909
910 case 'q':
911 ++qflag;
912 ++suppress_default_print;
913 break;
914
915 case 'r':
916 RFileName = optarg;
917 break;
918
919 case 'R':
920 Rflag = 0;
921 break;
922
923 case 's': {
924 char *end;
925
926 snaplen = strtol(optarg, &end, 0);
927 if (optarg == end || *end != '\0'
928 || snaplen < 0 || snaplen > MAXIMUM_SNAPLEN)
929 error("invalid snaplen %s", optarg);
930 else if (snaplen == 0)
931 snaplen = MAXIMUM_SNAPLEN;
932 break;
933 }
934
935 case 'S':
936 ++Sflag;
937 break;
938
939 case 't':
940 ++tflag;
941 break;
942
943 case 'T':
944 if (strcasecmp(optarg, "vat") == 0)
945 packettype = PT_VAT;
946 else if (strcasecmp(optarg, "wb") == 0)
947 packettype = PT_WB;
948 else if (strcasecmp(optarg, "rpc") == 0)
949 packettype = PT_RPC;
950 else if (strcasecmp(optarg, "rtp") == 0)
951 packettype = PT_RTP;
952 else if (strcasecmp(optarg, "rtcp") == 0)
953 packettype = PT_RTCP;
954 else if (strcasecmp(optarg, "snmp") == 0)
955 packettype = PT_SNMP;
956 else if (strcasecmp(optarg, "cnfp") == 0)
957 packettype = PT_CNFP;
958 else if (strcasecmp(optarg, "tftp") == 0)
959 packettype = PT_TFTP;
960 else if (strcasecmp(optarg, "aodv") == 0)
961 packettype = PT_AODV;
962 else if (strcasecmp(optarg, "carp") == 0)
963 packettype = PT_CARP;
964 else if (strcasecmp(optarg, "radius") == 0)
965 packettype = PT_RADIUS;
966 else
967 error("unknown packet type `%s'", optarg);
968 break;
969
970 case 'u':
971 ++uflag;
972 break;
973
974 #ifdef HAVE_PCAP_DUMP_FLUSH
975 case 'U':
976 ++Uflag;
977 break;
978 #endif
979
980 case 'v':
981 ++vflag;
982 break;
983
984 case 'w':
985 WFileName = optarg;
986 break;
987
988 case 'W':
989 Wflag = atoi(optarg);
990 if (Wflag < 0)
991 error("invalid number of output files %s", optarg);
992 WflagChars = getWflagChars(Wflag);
993 break;
994
995 case 'x':
996 ++xflag;
997 ++suppress_default_print;
998 break;
999
1000 case 'X':
1001 ++Xflag;
1002 ++suppress_default_print;
1003 break;
1004
1005 case 'y':
1006 gndo->ndo_dltname = optarg;
1007 gndo->ndo_dlt =
1008 pcap_datalink_name_to_val(gndo->ndo_dltname);
1009 if (gndo->ndo_dlt < 0)
1010 error("invalid data link type %s", gndo->ndo_dltname);
1011 break;
1012
1013 #if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
1014 case 'Y':
1015 {
1016 /* Undocumented flag */
1017 #ifdef HAVE_PCAP_DEBUG
1018 extern int pcap_debug;
1019 pcap_debug = 1;
1020 #else
1021 extern int yydebug;
1022 yydebug = 1;
1023 #endif
1024 }
1025 break;
1026 #endif
1027 case 'z':
1028 if (optarg) {
1029 zflag = strdup(optarg);
1030 } else {
1031 usage();
1032 /* NOTREACHED */
1033 }
1034 break;
1035
1036 case 'Z':
1037 if (optarg) {
1038 username = strdup(optarg);
1039 }
1040 else {
1041 usage();
1042 /* NOTREACHED */
1043 }
1044 break;
1045
1046 default:
1047 usage();
1048 /* NOTREACHED */
1049 }
1050
1051 switch (tflag) {
1052
1053 case 0: /* Default */
1054 case 4: /* Default + Date*/
1055 thiszone = gmt2local(0);
1056 break;
1057
1058 case 1: /* No time stamp */
1059 case 2: /* Unix timeval style */
1060 case 3: /* Microseconds since previous packet */
1061 case 5: /* Microseconds since first packet */
1062 break;
1063
1064 default: /* Not supported */
1065 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1066 break;
1067 }
1068
1069 #ifdef WITH_CHROOT
1070 /* if run as root, prepare for chrooting */
1071 if (getuid() == 0 || geteuid() == 0) {
1072 /* future extensibility for cmd-line arguments */
1073 if (!chroot_dir)
1074 chroot_dir = WITH_CHROOT;
1075 }
1076 #endif
1077
1078 #ifdef WITH_USER
1079 /* if run as root, prepare for dropping root privileges */
1080 if (getuid() == 0 || geteuid() == 0) {
1081 /* Run with '-Z root' to restore old behaviour */
1082 if (!username)
1083 username = WITH_USER;
1084 }
1085 #endif
1086
1087 if (RFileName != NULL) {
1088 int dlt;
1089 const char *dlt_name;
1090
1091 #ifndef WIN32
1092 /*
1093 * We don't need network access, so relinquish any set-UID
1094 * or set-GID privileges we have (if any).
1095 *
1096 * We do *not* want set-UID privileges when opening a
1097 * trace file, as that might let the user read other
1098 * people's trace files (especially if we're set-UID
1099 * root).
1100 */
1101 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1102 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1103 #endif /* WIN32 */
1104 pd = pcap_open_offline(RFileName, ebuf);
1105 if (pd == NULL)
1106 error("%s", ebuf);
1107 dlt = pcap_datalink(pd);
1108 dlt_name = pcap_datalink_val_to_name(dlt);
1109 if (dlt_name == NULL) {
1110 fprintf(stderr, "reading from file %s, link-type %u\n",
1111 RFileName, dlt);
1112 } else {
1113 fprintf(stderr,
1114 "reading from file %s, link-type %s (%s)\n",
1115 RFileName, dlt_name,
1116 pcap_datalink_val_to_description(dlt));
1117 }
1118 localnet = 0;
1119 netmask = 0;
1120 if (fflag != 0)
1121 error("-f and -r options are incompatible");
1122 } else {
1123 if (device == NULL) {
1124 device = pcap_lookupdev(ebuf);
1125 if (device == NULL)
1126 error("%s", ebuf);
1127 }
1128 #ifdef WIN32
1129 if(strlen(device) == 1) //we assume that an ASCII string is always longer than 1 char
1130 { //a Unicode string has a \0 as second byte (so strlen() is 1)
1131 fprintf(stderr, "%s: listening on %ws\n", program_name, device);
1132 }
1133 else
1134 {
1135 fprintf(stderr, "%s: listening on %s\n", program_name, device);
1136 }
1137
1138 fflush(stderr);
1139 #endif /* WIN32 */
1140 #ifdef HAVE_PCAP_CREATE
1141 pd = pcap_create(device, ebuf);
1142 if (pd == NULL)
1143 error("%s", ebuf);
1144 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1145 if (Jflag)
1146 show_tstamp_types_and_exit(device, pd);
1147 #endif
1148 /*
1149 * Is this an interface that supports monitor mode?
1150 */
1151 if (pcap_can_set_rfmon(pd) == 1)
1152 supports_monitor_mode = 1;
1153 else
1154 supports_monitor_mode = 0;
1155 status = pcap_set_snaplen(pd, snaplen);
1156 if (status != 0)
1157 error("%s: Can't set snapshot length: %s",
1158 device, pcap_statustostr(status));
1159 status = pcap_set_promisc(pd, !pflag);
1160 if (status != 0)
1161 error("%s: Can't set promiscuous mode: %s",
1162 device, pcap_statustostr(status));
1163 if (Iflag) {
1164 status = pcap_set_rfmon(pd, 1);
1165 if (status != 0)
1166 error("%s: Can't set monitor mode: %s",
1167 device, pcap_statustostr(status));
1168 }
1169 status = pcap_set_timeout(pd, 1000);
1170 if (status != 0)
1171 error("%s: pcap_set_timeout failed: %s",
1172 device, pcap_statustostr(status));
1173 if (Bflag != 0) {
1174 status = pcap_set_buffer_size(pd, Bflag);
1175 if (status != 0)
1176 error("%s: Can't set buffer size: %s",
1177 device, pcap_statustostr(status));
1178 }
1179 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1180 if (jflag != -1) {
1181 status = pcap_set_tstamp_type(pd, jflag);
1182 if (status < 0)
1183 error("%s: Can't set time stamp type: %s",
1184 device, pcap_statustostr(status));
1185 }
1186 #endif
1187 status = pcap_activate(pd);
1188 if (status < 0) {
1189 /*
1190 * pcap_activate() failed.
1191 */
1192 cp = pcap_geterr(pd);
1193 if (status == PCAP_ERROR)
1194 error("%s", cp);
1195 else if ((status == PCAP_ERROR_NO_SUCH_DEVICE ||
1196 status == PCAP_ERROR_PERM_DENIED) &&
1197 *cp != '\0')
1198 error("%s: %s\n(%s)", device,
1199 pcap_statustostr(status), cp);
1200 else
1201 error("%s: %s", device,
1202 pcap_statustostr(status));
1203 } else if (status > 0) {
1204 /*
1205 * pcap_activate() succeeded, but it's warning us
1206 * of a problem it had.
1207 */
1208 cp = pcap_geterr(pd);
1209 if (status == PCAP_WARNING)
1210 warning("%s", cp);
1211 else if (status == PCAP_WARNING_PROMISC_NOTSUP &&
1212 *cp != '\0')
1213 warning("%s: %s\n(%s)", device,
1214 pcap_statustostr(status), cp);
1215 else
1216 warning("%s: %s", device,
1217 pcap_statustostr(status));
1218 }
1219 #else
1220 *ebuf = '\0';
1221 pd = pcap_open_live(device, snaplen, !pflag, 1000, ebuf);
1222 if (pd == NULL)
1223 error("%s", ebuf);
1224 else if (*ebuf)
1225 warning("%s", ebuf);
1226 #endif /* HAVE_PCAP_CREATE */
1227 /*
1228 * Let user own process after socket has been opened.
1229 */
1230 #ifndef WIN32
1231 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1232 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1233 #endif /* WIN32 */
1234 #if !defined(HAVE_PCAP_CREATE) && defined(WIN32)
1235 if(Bflag != 0)
1236 if(pcap_setbuff(pd, Bflag)==-1){
1237 error("%s", pcap_geterr(pd));
1238 }
1239 #endif /* !defined(HAVE_PCAP_CREATE) && defined(WIN32) */
1240 if (Lflag)
1241 show_dlts_and_exit(device, pd);
1242 if (gndo->ndo_dlt >= 0) {
1243 #ifdef HAVE_PCAP_SET_DATALINK
1244 if (pcap_set_datalink(pd, gndo->ndo_dlt) < 0)
1245 error("%s", pcap_geterr(pd));
1246 #else
1247 /*
1248 * We don't actually support changing the
1249 * data link type, so we only let them
1250 * set it to what it already is.
1251 */
1252 if (gndo->ndo_dlt != pcap_datalink(pd)) {
1253 error("%s is not one of the DLTs supported by this device\n",
1254 gndo->ndo_dltname);
1255 }
1256 #endif
1257 (void)fprintf(stderr, "%s: data link type %s\n",
1258 program_name, gndo->ndo_dltname);
1259 (void)fflush(stderr);
1260 }
1261 i = pcap_snapshot(pd);
1262 if (snaplen < i) {
1263 warning("snaplen raised from %d to %d", snaplen, i);
1264 snaplen = i;
1265 }
1266 if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
1267 localnet = 0;
1268 netmask = 0;
1269 warning("%s", ebuf);
1270 }
1271 }
1272 if (infile)
1273 cmdbuf = read_infile(infile);
1274 else
1275 cmdbuf = copy_argv(&argv[optind]);
1276
1277 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1278 error("%s", pcap_geterr(pd));
1279 free(cmdbuf);
1280 if (dflag) {
1281 bpf_dump(&fcode, dflag);
1282 pcap_close(pd);
1283 exit(0);
1284 }
1285 init_addrtoname(localnet, netmask);
1286 init_checksum();
1287
1288 #ifndef WIN32
1289 (void)setsignal(SIGPIPE, cleanup);
1290 (void)setsignal(SIGTERM, cleanup);
1291 (void)setsignal(SIGINT, cleanup);
1292 #endif /* WIN32 */
1293 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1294 (void)setsignal(SIGCHLD, child_cleanup);
1295 #endif
1296 /* Cooperate with nohup(1) */
1297 #ifndef WIN32
1298 if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
1299 (void)setsignal(SIGHUP, oldhandler);
1300 #endif /* WIN32 */
1301
1302 #ifndef WIN32
1303 /*
1304 * If a user name was specified with "-Z", attempt to switch to
1305 * that user's UID. This would probably be used with sudo,
1306 * to allow tcpdump to be run in a special restricted
1307 * account (if you just want to allow users to open capture
1308 * devices, and can't just give users that permission,
1309 * you'd make tcpdump set-UID or set-GID).
1310 *
1311 * Tcpdump doesn't necessarily write only to one savefile;
1312 * the general only way to allow a -Z instance to write to
1313 * savefiles as the user under whose UID it's run, rather
1314 * than as the user specified with -Z, would thus be to switch
1315 * to the original user ID before opening a capture file and
1316 * then switch back to the -Z user ID after opening the savefile.
1317 * Switching to the -Z user ID only after opening the first
1318 * savefile doesn't handle the general case.
1319 */
1320
1321 #ifdef HAVE_CAP_NG_H
1322 /* We are running as root and we will be writing to savefile */
1323 if ((getuid() == 0 || geteuid() == 0) && WFileName) {
1324 if (username) {
1325 /* Drop all capabilities from effective set */
1326 capng_clear(CAPNG_EFFECTIVE);
1327 /* Add capabilities we will need*/
1328 capng_update(CAPNG_ADD, CAPNG_PERMITTED, CAP_SETUID);
1329 capng_update(CAPNG_ADD, CAPNG_PERMITTED, CAP_SETGID);
1330 capng_update(CAPNG_ADD, CAPNG_PERMITTED, CAP_DAC_OVERRIDE);
1331
1332 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_SETUID);
1333 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_SETGID);
1334 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
1335
1336 capng_apply(CAPNG_SELECT_BOTH);
1337 }
1338 }
1339 #endif /* HAVE_CAP_NG_H */
1340
1341 if (getuid() == 0 || geteuid() == 0) {
1342 if (username || chroot_dir)
1343 droproot(username, chroot_dir);
1344
1345 }
1346 #endif /* WIN32 */
1347
1348 if (pcap_setfilter(pd, &fcode) < 0)
1349 error("%s", pcap_geterr(pd));
1350 if (WFileName) {
1351 pcap_dumper_t *p;
1352 /* Do not exceed the default NAME_MAX for files. */
1353 dumpinfo.CurrentFileName = (char *)malloc(NAME_MAX + 1);
1354
1355 if (dumpinfo.CurrentFileName == NULL)
1356 error("malloc of dumpinfo.CurrentFileName");
1357
1358 /* We do not need numbering for dumpfiles if Cflag isn't set. */
1359 if (Cflag != 0)
1360 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
1361 else
1362 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
1363
1364 p = pcap_dump_open(pd, dumpinfo.CurrentFileName);
1365 #ifdef HAVE_CAP_NG_H
1366 /* Give up capabilities, clear Effective set */
1367 capng_clear(CAPNG_EFFECTIVE);
1368 #endif
1369 if (p == NULL)
1370 error("%s", pcap_geterr(pd));
1371 if (Cflag != 0 || Gflag != 0) {
1372 callback = dump_packet_and_trunc;
1373 dumpinfo.WFileName = WFileName;
1374 dumpinfo.pd = pd;
1375 dumpinfo.p = p;
1376 pcap_userdata = (u_char *)&dumpinfo;
1377 } else {
1378 callback = dump_packet;
1379 pcap_userdata = (u_char *)p;
1380 }
1381 #ifdef HAVE_PCAP_DUMP_FLUSH
1382 if (Uflag)
1383 pcap_dump_flush(p);
1384 #endif
1385 } else {
1386 type = pcap_datalink(pd);
1387 printinfo.ndo_type = 1;
1388 printinfo.ndo = gndo;
1389 printinfo.p.ndo_printer = lookup_ndo_printer(type);
1390 if (printinfo.p.ndo_printer == NULL) {
1391 printinfo.p.printer = lookup_printer(type);
1392 printinfo.ndo_type = 0;
1393 if (printinfo.p.printer == NULL) {
1394 gndo->ndo_dltname = pcap_datalink_val_to_name(type);
1395 if (gndo->ndo_dltname != NULL)
1396 error("packet printing is not supported for link type %s: use -w",
1397 gndo->ndo_dltname);
1398 else
1399 error("packet printing is not supported for link type %d: use -w", type);
1400 }
1401 }
1402 callback = print_packet;
1403 pcap_userdata = (u_char *)&printinfo;
1404 }
1405
1406 #ifdef SIGNAL_REQ_INFO
1407 /*
1408 * We can't get statistics when reading from a file rather
1409 * than capturing from a device.
1410 */
1411 if (RFileName == NULL)
1412 (void)setsignal(SIGNAL_REQ_INFO, requestinfo);
1413 #endif
1414
1415 if (vflag > 0 && WFileName) {
1416 /*
1417 * When capturing to a file, "-v" means tcpdump should,
1418 * every 10 secodns, "v"erbosely report the number of
1419 * packets captured.
1420 */
1421 #ifdef USE_WIN32_MM_TIMER
1422 /* call verbose_stats_dump() each 1000 +/-100msec */
1423 timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
1424 setvbuf(stderr, NULL, _IONBF, 0);
1425 #elif defined(HAVE_ALARM)
1426 (void)setsignal(SIGALRM, verbose_stats_dump);
1427 alarm(1);
1428 #endif
1429 }
1430
1431 #ifndef WIN32
1432 if (RFileName == NULL) {
1433 int dlt;
1434 const char *dlt_name;
1435
1436 if (!vflag && !WFileName) {
1437 (void)fprintf(stderr,
1438 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
1439 program_name);
1440 } else
1441 (void)fprintf(stderr, "%s: ", program_name);
1442 dlt = pcap_datalink(pd);
1443 dlt_name = pcap_datalink_val_to_name(dlt);
1444 if (dlt_name == NULL) {
1445 (void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
1446 device, dlt, snaplen);
1447 } else {
1448 (void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
1449 device, dlt_name,
1450 pcap_datalink_val_to_description(dlt), snaplen);
1451 }
1452 (void)fflush(stderr);
1453 }
1454 #endif /* WIN32 */
1455 status = pcap_loop(pd, cnt, callback, pcap_userdata);
1456 if (WFileName == NULL) {
1457 /*
1458 * We're printing packets. Flush the printed output,
1459 * so it doesn't get intermingled with error output.
1460 */
1461 if (status == -2) {
1462 /*
1463 * We got interrupted, so perhaps we didn't
1464 * manage to finish a line we were printing.
1465 * Print an extra newline, just in case.
1466 */
1467 putchar('\n');
1468 }
1469 (void)fflush(stdout);
1470 }
1471 if (status == -1) {
1472 /*
1473 * Error. Report it.
1474 */
1475 (void)fprintf(stderr, "%s: pcap_loop: %s\n",
1476 program_name, pcap_geterr(pd));
1477 }
1478 if (RFileName == NULL) {
1479 /*
1480 * We're doing a live capture. Report the capture
1481 * statistics.
1482 */
1483 info(1);
1484 }
1485 pcap_close(pd);
1486 exit(status == -1 ? 1 : 0);
1487 }
1488
1489 /* make a clean exit on interrupts */
1490 static RETSIGTYPE
1491 cleanup(int signo _U_)
1492 {
1493 #ifdef USE_WIN32_MM_TIMER
1494 if (timer_id)
1495 timeKillEvent(timer_id);
1496 timer_id = 0;
1497 #elif defined(HAVE_ALARM)
1498 alarm(0);
1499 #endif
1500
1501 #ifdef HAVE_PCAP_BREAKLOOP
1502 /*
1503 * We have "pcap_breakloop()"; use it, so that we do as little
1504 * as possible in the signal handler (it's probably not safe
1505 * to do anything with standard I/O streams in a signal handler -
1506 * the ANSI C standard doesn't say it is).
1507 */
1508 pcap_breakloop(pd);
1509 #else
1510 /*
1511 * We don't have "pcap_breakloop()"; this isn't safe, but
1512 * it's the best we can do. Print the summary if we're
1513 * not reading from a savefile - i.e., if we're doing a
1514 * live capture - and exit.
1515 */
1516 if (pd != NULL && pcap_file(pd) == NULL) {
1517 /*
1518 * We got interrupted, so perhaps we didn't
1519 * manage to finish a line we were printing.
1520 * Print an extra newline, just in case.
1521 */
1522 putchar('\n');
1523 (void)fflush(stdout);
1524 info(1);
1525 }
1526 exit(0);
1527 #endif
1528 }
1529
1530 /*
1531 On windows, we do not use a fork, so we do not care less about
1532 waiting a child processes to die
1533 */
1534 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1535 static RETSIGTYPE
1536 child_cleanup(int signo _U_)
1537 {
1538 wait(NULL);
1539 }
1540 #endif /* HAVE_FORK && HAVE_VFORK */
1541
1542 static void
1543 info(register int verbose)
1544 {
1545 struct pcap_stat stat;
1546
1547 /*
1548 * Older versions of libpcap didn't set ps_ifdrop on some
1549 * platforms; initialize it to 0 to handle that.
1550 */
1551 stat.ps_ifdrop = 0;
1552 if (pcap_stats(pd, &stat) < 0) {
1553 (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
1554 infoprint = 0;
1555 return;
1556 }
1557
1558 if (!verbose)
1559 fprintf(stderr, "%s: ", program_name);
1560
1561 (void)fprintf(stderr, "%u packet%s captured", packets_captured,
1562 PLURAL_SUFFIX(packets_captured));
1563 if (!verbose)
1564 fputs(", ", stderr);
1565 else
1566 putc('\n', stderr);
1567 (void)fprintf(stderr, "%u packet%s received by filter", stat.ps_recv,
1568 PLURAL_SUFFIX(stat.ps_recv));
1569 if (!verbose)
1570 fputs(", ", stderr);
1571 else
1572 putc('\n', stderr);
1573 (void)fprintf(stderr, "%u packet%s dropped by kernel", stat.ps_drop,
1574 PLURAL_SUFFIX(stat.ps_drop));
1575 if (stat.ps_ifdrop != 0) {
1576 if (!verbose)
1577 fputs(", ", stderr);
1578 else
1579 putc('\n', stderr);
1580 (void)fprintf(stderr, "%u packet%s dropped by interface\n",
1581 stat.ps_ifdrop, PLURAL_SUFFIX(stat.ps_ifdrop));
1582 } else
1583 putc('\n', stderr);
1584 infoprint = 0;
1585 }
1586
1587 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1588 static void
1589 compress_savefile(const char *filename)
1590 {
1591 # ifdef HAVE_FORK
1592 if (fork())
1593 # else
1594 if (vfork())
1595 # endif
1596 return;
1597 /*
1598 * Set to lowest priority so that this doesn't disturb the capture
1599 */
1600 #ifdef NZERO
1601 setpriority(PRIO_PROCESS, 0, NZERO - 1);
1602 #else
1603 setpriority(PRIO_PROCESS, 0, 19);
1604 #endif
1605 if (execlp(zflag, zflag, filename, (char *)NULL) == -1)
1606 fprintf(stderr,
1607 "compress_savefile:execlp(%s, %s): %s\n",
1608 zflag,
1609 filename,
1610 strerror(errno));
1611 # ifdef HAVE_FORK
1612 exit(1);
1613 # else
1614 _exit(1);
1615 # endif
1616 }
1617 #else /* HAVE_FORK && HAVE_VFORK */
1618 static void
1619 compress_savefile(const char *filename)
1620 {
1621 fprintf(stderr,
1622 "compress_savefile failed. Functionality not implemented under your system\n");
1623 }
1624 #endif /* HAVE_FORK && HAVE_VFORK */
1625
1626 static void
1627 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1628 {
1629 struct dump_info *dump_info;
1630
1631 ++packets_captured;
1632
1633 ++infodelay;
1634
1635 dump_info = (struct dump_info *)user;
1636
1637 /*
1638 * XXX - this won't force the file to rotate on the specified time
1639 * boundary, but it will rotate on the first packet received after the
1640 * specified Gflag number of seconds. Note: if a Gflag time boundary
1641 * and a Cflag size boundary coincide, the time rotation will occur
1642 * first thereby cancelling the Cflag boundary (since the file should
1643 * be 0).
1644 */
1645 if (Gflag != 0) {
1646 /* Check if it is time to rotate */
1647 time_t t;
1648
1649 /* Get the current time */
1650 if ((t = time(NULL)) == (time_t)-1) {
1651 error("dump_and_trunc_packet: can't get current_time: %s",
1652 pcap_strerror(errno));
1653 }
1654
1655
1656 /* If the time is greater than the specified window, rotate */
1657 if (t - Gflag_time >= Gflag) {
1658 /* Update the Gflag_time */
1659 Gflag_time = t;
1660 /* Update Gflag_count */
1661 Gflag_count++;
1662 /*
1663 * Close the current file and open a new one.
1664 */
1665 pcap_dump_close(dump_info->p);
1666
1667 /*
1668 * Compress the file we just closed, if the user asked for it
1669 */
1670 if (zflag != NULL)
1671 compress_savefile(dump_info->CurrentFileName);
1672
1673 /*
1674 * Check to see if we've exceeded the Wflag (when
1675 * not using Cflag).
1676 */
1677 if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
1678 (void)fprintf(stderr, "Maximum file limit reached: %d\n",
1679 Wflag);
1680 exit(0);
1681 /* NOTREACHED */
1682 }
1683 if (dump_info->CurrentFileName != NULL)
1684 free(dump_info->CurrentFileName);
1685 /* Allocate space for max filename + \0. */
1686 dump_info->CurrentFileName = (char *)malloc(NAME_MAX + 1);
1687 if (dump_info->CurrentFileName == NULL)
1688 error("dump_packet_and_trunc: malloc");
1689 /*
1690 * This is always the first file in the Cflag
1691 * rotation: e.g. 0
1692 * We also don't need numbering if Cflag is not set.
1693 */
1694 if (Cflag != 0)
1695 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
1696 WflagChars);
1697 else
1698 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
1699
1700 #ifdef HAVE_CAP_NG_H
1701 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
1702 capng_apply(CAPNG_EFFECTIVE);
1703 #endif /* HAVE_CAP_NG_H */
1704 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
1705 #ifdef HAVE_CAP_NG_H
1706 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
1707 capng_apply(CAPNG_EFFECTIVE);
1708 #endif /* HAVE_CAP_NG_H */
1709 if (dump_info->p == NULL)
1710 error("%s", pcap_geterr(pd));
1711 }
1712 }
1713
1714 /*
1715 * XXX - this won't prevent capture files from getting
1716 * larger than Cflag - the last packet written to the
1717 * file could put it over Cflag.
1718 */
1719 if (Cflag != 0 && pcap_dump_ftell(dump_info->p) > Cflag) {
1720 /*
1721 * Close the current file and open a new one.
1722 */
1723 pcap_dump_close(dump_info->p);
1724
1725 /*
1726 * Compress the file we just closed, if the user asked for it
1727 */
1728 if (zflag != NULL)
1729 compress_savefile(dump_info->CurrentFileName);
1730
1731 Cflag_count++;
1732 if (Wflag > 0) {
1733 if (Cflag_count >= Wflag)
1734 Cflag_count = 0;
1735 }
1736 if (dump_info->CurrentFileName != NULL)
1737 free(dump_info->CurrentFileName);
1738 dump_info->CurrentFileName = (char *)malloc(NAME_MAX + 1);
1739 if (dump_info->CurrentFileName == NULL)
1740 error("dump_packet_and_trunc: malloc");
1741 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
1742 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
1743 if (dump_info->p == NULL)
1744 error("%s", pcap_geterr(pd));
1745 }
1746
1747 pcap_dump((u_char *)dump_info->p, h, sp);
1748 #ifdef HAVE_PCAP_DUMP_FLUSH
1749 if (Uflag)
1750 pcap_dump_flush(dump_info->p);
1751 #endif
1752
1753 --infodelay;
1754 if (infoprint)
1755 info(0);
1756 }
1757
1758 static void
1759 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1760 {
1761 ++packets_captured;
1762
1763 ++infodelay;
1764
1765 pcap_dump(user, h, sp);
1766 #ifdef HAVE_PCAP_DUMP_FLUSH
1767 if (Uflag)
1768 pcap_dump_flush((pcap_dumper_t *)user);
1769 #endif
1770
1771 --infodelay;
1772 if (infoprint)
1773 info(0);
1774 }
1775
1776 static void
1777 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1778 {
1779 struct print_info *print_info;
1780 u_int hdrlen;
1781
1782 ++packets_captured;
1783
1784 ++infodelay;
1785 ts_print(&h->ts);
1786
1787 print_info = (struct print_info *)user;
1788
1789 /*
1790 * Some printers want to check that they're not walking off the
1791 * end of the packet.
1792 * Rather than pass it all the way down, we set this global.
1793 */
1794 snapend = sp + h->caplen;
1795
1796 if(print_info->ndo_type) {
1797 hdrlen = (*print_info->p.ndo_printer)(print_info->ndo, h, sp);
1798 } else {
1799 hdrlen = (*print_info->p.printer)(h, sp);
1800 }
1801
1802 if (Xflag) {
1803 /*
1804 * Print the raw packet data in hex and ASCII.
1805 */
1806 if (Xflag > 1) {
1807 /*
1808 * Include the link-layer header.
1809 */
1810 hex_and_ascii_print("\n\t", sp, h->caplen);
1811 } else {
1812 /*
1813 * Don't include the link-layer header - and if
1814 * we have nothing past the link-layer header,
1815 * print nothing.
1816 */
1817 if (h->caplen > hdrlen)
1818 hex_and_ascii_print("\n\t", sp + hdrlen,
1819 h->caplen - hdrlen);
1820 }
1821 } else if (xflag) {
1822 /*
1823 * Print the raw packet data in hex.
1824 */
1825 if (xflag > 1) {
1826 /*
1827 * Include the link-layer header.
1828 */
1829 hex_print("\n\t", sp, h->caplen);
1830 } else {
1831 /*
1832 * Don't include the link-layer header - and if
1833 * we have nothing past the link-layer header,
1834 * print nothing.
1835 */
1836 if (h->caplen > hdrlen)
1837 hex_print("\n\t", sp + hdrlen,
1838 h->caplen - hdrlen);
1839 }
1840 } else if (Aflag) {
1841 /*
1842 * Print the raw packet data in ASCII.
1843 */
1844 if (Aflag > 1) {
1845 /*
1846 * Include the link-layer header.
1847 */
1848 ascii_print(sp, h->caplen);
1849 } else {
1850 /*
1851 * Don't include the link-layer header - and if
1852 * we have nothing past the link-layer header,
1853 * print nothing.
1854 */
1855 if (h->caplen > hdrlen)
1856 ascii_print(sp + hdrlen, h->caplen - hdrlen);
1857 }
1858 }
1859
1860 putchar('\n');
1861
1862 --infodelay;
1863 if (infoprint)
1864 info(0);
1865 }
1866
1867 #ifdef WIN32
1868 /*
1869 * XXX - there should really be libpcap calls to get the version
1870 * number as a string (the string would be generated from #defines
1871 * at run time, so that it's not generated from string constants
1872 * in the library, as, on many UNIX systems, those constants would
1873 * be statically linked into the application executable image, and
1874 * would thus reflect the version of libpcap on the system on
1875 * which the application was *linked*, not the system on which it's
1876 * *running*.
1877 *
1878 * That routine should be documented, unlike the "version[]"
1879 * string, so that UNIX vendors providing their own libpcaps
1880 * don't omit it (as a couple of vendors have...).
1881 *
1882 * Packet.dll should perhaps also export a routine to return the
1883 * version number of the Packet.dll code, to supply the
1884 * "Wpcap_version" information on Windows.
1885 */
1886 char WDversion[]="current-cvs.tcpdump.org";
1887 #if !defined(HAVE_GENERATED_VERSION)
1888 char version[]="current-cvs.tcpdump.org";
1889 #endif
1890 char pcap_version[]="current-cvs.tcpdump.org";
1891 char Wpcap_version[]="3.1";
1892 #endif
1893
1894 /*
1895 * By default, print the specified data out in hex and ASCII.
1896 */
1897 static void
1898 ndo_default_print(netdissect_options *ndo _U_, const u_char *bp, u_int length)
1899 {
1900 hex_and_ascii_print("\n\t", bp, length); /* pass on lf and identation string */
1901 }
1902
1903 void
1904 default_print(const u_char *bp, u_int length)
1905 {
1906 ndo_default_print(gndo, bp, length);
1907 }
1908
1909 #ifdef SIGNAL_REQ_INFO
1910 RETSIGTYPE requestinfo(int signo _U_)
1911 {
1912 if (infodelay)
1913 ++infoprint;
1914 else
1915 info(0);
1916 }
1917 #endif
1918
1919 /*
1920 * Called once each second in verbose mode while dumping to file
1921 */
1922 #ifdef USE_WIN32_MM_TIMER
1923 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
1924 DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
1925 {
1926 struct pcap_stat stat;
1927
1928 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
1929 fprintf(stderr, "Got %u\r", packets_captured);
1930 }
1931 #elif defined(HAVE_ALARM)
1932 static void verbose_stats_dump(int sig _U_)
1933 {
1934 struct pcap_stat stat;
1935
1936 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
1937 fprintf(stderr, "Got %u\r", packets_captured);
1938 alarm(1);
1939 }
1940 #endif
1941
1942 static void
1943 usage(void)
1944 {
1945 extern char version[];
1946 #ifndef HAVE_PCAP_LIB_VERSION
1947 #if defined(WIN32) || defined(HAVE_PCAP_VERSION)
1948 extern char pcap_version[];
1949 #else /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
1950 static char pcap_version[] = "unknown";
1951 #endif /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
1952 #endif /* HAVE_PCAP_LIB_VERSION */
1953
1954 #ifdef HAVE_PCAP_LIB_VERSION
1955 #ifdef WIN32
1956 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
1957 #else /* WIN32 */
1958 (void)fprintf(stderr, "%s version %s\n", program_name, version);
1959 #endif /* WIN32 */
1960 (void)fprintf(stderr, "%s\n",pcap_lib_version());
1961 #else /* HAVE_PCAP_LIB_VERSION */
1962 #ifdef WIN32
1963 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
1964 (void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
1965 #else /* WIN32 */
1966 (void)fprintf(stderr, "%s version %s\n", program_name, version);
1967 (void)fprintf(stderr, "libpcap version %s\n", pcap_version);
1968 #endif /* WIN32 */
1969 #endif /* HAVE_PCAP_LIB_VERSION */
1970 (void)fprintf(stderr,
1971 "Usage: %s [-aAbd" D_FLAG "efhH" I_FLAG J_FLAG "KlLnNOpqRStu" U_FLAG "vxX]" B_FLAG_USAGE " [ -c count ]\n", program_name);
1972 (void)fprintf(stderr,
1973 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
1974 (void)fprintf(stderr,
1975 "\t\t[ -i interface ]" j_FLAG_USAGE " [ -M secret ]\n");
1976 (void)fprintf(stderr,
1977 "\t\t[ -r file ] [ -s snaplen ] [ -T type ] [ -w file ]\n");
1978 (void)fprintf(stderr,
1979 "\t\t[ -W filecount ] [ -y datalinktype ] [ -z command ]\n");
1980 (void)fprintf(stderr,
1981 "\t\t[ -Z user ] [ expression ]\n");
1982 exit(1);
1983 }
1984
1985
1986
1987 /* VARARGS */
1988 static void
1989 ndo_error(netdissect_options *ndo _U_, const char *fmt, ...)
1990 {
1991 va_list ap;
1992
1993 (void)fprintf(stderr, "%s: ", program_name);
1994 va_start(ap, fmt);
1995 (void)vfprintf(stderr, fmt, ap);
1996 va_end(ap);
1997 if (*fmt) {
1998 fmt += strlen(fmt);
1999 if (fmt[-1] != '\n')
2000 (void)fputc('\n', stderr);
2001 }
2002 exit(1);
2003 /* NOTREACHED */
2004 }
2005
2006 /* VARARGS */
2007 static void
2008 ndo_warning(netdissect_options *ndo _U_, const char *fmt, ...)
2009 {
2010 va_list ap;
2011
2012 (void)fprintf(stderr, "%s: WARNING: ", program_name);
2013 va_start(ap, fmt);
2014 (void)vfprintf(stderr, fmt, ap);
2015 va_end(ap);
2016 if (*fmt) {
2017 fmt += strlen(fmt);
2018 if (fmt[-1] != '\n')
2019 (void)fputc('\n', stderr);
2020 }
2021 }