]> The Tcpdump Group git mirrors - tcpdump/blob - tcpdump.c
Merge pull request #25 from dogbert2/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 if (filename == NULL)
593 error("Makefilename: malloc);
594
595 /* Process with strftime if Gflag is set. */
596 if (Gflag != 0) {
597 struct tm *local_tm;
598
599 /* Convert Gflag_time to a usable format */
600 if ((local_tm = localtime(&Gflag_time)) == NULL) {
601 error("MakeTimedFilename: localtime");
602 }
603
604 /* There's no good way to detect an error in strftime since a return
605 * value of 0 isn't necessarily failure.
606 */
607 strftime(filename, NAME_MAX, orig_name, local_tm);
608 } else {
609 strncpy(filename, orig_name, NAME_MAX);
610 }
611
612 if (cnt == 0 && max_chars == 0)
613 strncpy(buffer, filename, NAME_MAX + 1);
614 else
615 if (snprintf(buffer, NAME_MAX + 1, "%s%0*d", filename, max_chars, cnt) > NAME_MAX)
616 /* Report an error if the filename is too large */
617 error("too many output files or filename is too long (> %d)", NAME_MAX);
618 free(filename);
619 }
620
621 static int tcpdump_printf(netdissect_options *ndo _U_,
622 const char *fmt, ...)
623 {
624
625 va_list args;
626 int ret;
627
628 va_start(args, fmt);
629 ret=vfprintf(stdout, fmt, args);
630 va_end(args);
631
632 return ret;
633 }
634
635 int
636 main(int argc, char **argv)
637 {
638 register int cnt, op, i;
639 bpf_u_int32 localnet, netmask;
640 register char *cp, *infile, *cmdbuf, *device, *RFileName, *WFileName;
641 pcap_handler callback;
642 int type;
643 struct bpf_program fcode;
644 #ifndef WIN32
645 RETSIGTYPE (*oldhandler)(int);
646 #endif
647 struct print_info printinfo;
648 struct dump_info dumpinfo;
649 u_char *pcap_userdata;
650 char ebuf[PCAP_ERRBUF_SIZE];
651 char *username = NULL;
652 char *chroot_dir = NULL;
653 #ifdef HAVE_PCAP_FINDALLDEVS
654 pcap_if_t *devpointer;
655 int devnum;
656 #endif
657 int status;
658 #ifdef WIN32
659 if(wsockinit() != 0) return 1;
660 #endif /* WIN32 */
661
662 jflag=-1; /* not set */
663 gndo->ndo_Oflag=1;
664 gndo->ndo_Rflag=1;
665 gndo->ndo_dlt=-1;
666 gndo->ndo_default_print=ndo_default_print;
667 gndo->ndo_printf=tcpdump_printf;
668 gndo->ndo_error=ndo_error;
669 gndo->ndo_warning=ndo_warning;
670 gndo->ndo_snaplen = DEFAULT_SNAPLEN;
671
672 cnt = -1;
673 device = NULL;
674 infile = NULL;
675 RFileName = NULL;
676 WFileName = NULL;
677 if ((cp = strrchr(argv[0], '/')) != NULL)
678 program_name = cp + 1;
679 else
680 program_name = argv[0];
681
682 if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
683 error("%s", ebuf);
684
685 #ifdef LIBSMI
686 smiInit("tcpdump");
687 #endif
688
689 while (
690 (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)
691 switch (op) {
692
693 case 'a':
694 /* compatibility for old -a */
695 break;
696
697 case 'A':
698 ++Aflag;
699 break;
700
701 case 'b':
702 ++bflag;
703 break;
704
705 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
706 case 'B':
707 Bflag = atoi(optarg)*1024;
708 if (Bflag <= 0)
709 error("invalid packet buffer size %s", optarg);
710 break;
711 #endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
712
713 case 'c':
714 cnt = atoi(optarg);
715 if (cnt <= 0)
716 error("invalid packet count %s", optarg);
717 break;
718
719 case 'C':
720 Cflag = atoi(optarg) * 1000000;
721 if (Cflag < 0)
722 error("invalid file size %s", optarg);
723 break;
724
725 case 'd':
726 ++dflag;
727 break;
728
729 #ifdef HAVE_PCAP_FINDALLDEVS
730 case 'D':
731 if (pcap_findalldevs(&devpointer, ebuf) < 0)
732 error("%s", ebuf);
733 else {
734 for (i = 0; devpointer != 0; i++) {
735 printf("%d.%s", i+1, devpointer->name);
736 if (devpointer->description != NULL)
737 printf(" (%s)", devpointer->description);
738 printf("\n");
739 devpointer = devpointer->next;
740 }
741 }
742 return 0;
743 #endif /* HAVE_PCAP_FINDALLDEVS */
744
745 case 'L':
746 Lflag++;
747 break;
748
749 case 'e':
750 ++eflag;
751 break;
752
753 case 'E':
754 #ifndef HAVE_LIBCRYPTO
755 warning("crypto code not compiled in");
756 #endif
757 gndo->ndo_espsecret = optarg;
758 break;
759
760 case 'f':
761 ++fflag;
762 break;
763
764 case 'F':
765 infile = optarg;
766 break;
767
768 case 'G':
769 Gflag = atoi(optarg);
770 if (Gflag < 0)
771 error("invalid number of seconds %s", optarg);
772
773 /* We will create one file initially. */
774 Gflag_count = 0;
775
776 /* Grab the current time for rotation use. */
777 if ((Gflag_time = time(NULL)) == (time_t)-1) {
778 error("main: can't get current time: %s",
779 pcap_strerror(errno));
780 }
781 break;
782
783 case 'h':
784 usage();
785 break;
786
787 case 'H':
788 ++Hflag;
789 break;
790
791 case 'i':
792 if (optarg[0] == '0' && optarg[1] == 0)
793 error("Invalid adapter index");
794
795 #ifdef HAVE_PCAP_FINDALLDEVS
796 /*
797 * If the argument is a number, treat it as
798 * an index into the list of adapters, as
799 * printed by "tcpdump -D".
800 *
801 * This should be OK on UNIX systems, as interfaces
802 * shouldn't have names that begin with digits.
803 * It can be useful on Windows, where more than
804 * one interface can have the same name.
805 */
806 if ((devnum = atoi(optarg)) != 0) {
807 if (devnum < 0)
808 error("Invalid adapter index");
809
810 if (pcap_findalldevs(&devpointer, ebuf) < 0)
811 error("%s", ebuf);
812 else {
813 /*
814 * Look for the devnum-th entry
815 * in the list of devices
816 * (1-based).
817 */
818 for (i = 0;
819 i < devnum-1 && devpointer != NULL;
820 i++, devpointer = devpointer->next)
821 ;
822 if (devpointer == NULL)
823 error("Invalid adapter index");
824 }
825 device = devpointer->name;
826 break;
827 }
828 #endif /* HAVE_PCAP_FINDALLDEVS */
829 device = optarg;
830 break;
831
832 #ifdef HAVE_PCAP_CREATE
833 case 'I':
834 ++Iflag;
835 break;
836 #endif /* HAVE_PCAP_CREATE */
837
838 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
839 case 'j':
840 jflag = pcap_tstamp_type_name_to_val(optarg);
841 if (jflag < 0)
842 error("invalid time stamp type %s", optarg);
843 break;
844
845 case 'J':
846 Jflag++;
847 break;
848 #endif
849
850 case 'l':
851 #ifdef WIN32
852 /*
853 * _IOLBF is the same as _IOFBF in Microsoft's C
854 * libraries; the only alternative they offer
855 * is _IONBF.
856 *
857 * XXX - this should really be checking for MSVC++,
858 * not WIN32, if, for example, MinGW has its own
859 * C library that is more UNIX-compatible.
860 */
861 setvbuf(stdout, NULL, _IONBF, 0);
862 #else /* WIN32 */
863 #ifdef HAVE_SETLINEBUF
864 setlinebuf(stdout);
865 #else
866 setvbuf(stdout, NULL, _IOLBF, 0);
867 #endif
868 #endif /* WIN32 */
869 break;
870
871 case 'K':
872 ++Kflag;
873 break;
874
875 case 'm':
876 #ifdef LIBSMI
877 if (smiLoadModule(optarg) == 0) {
878 error("could not load MIB module %s", optarg);
879 }
880 sflag = 1;
881 #else
882 (void)fprintf(stderr, "%s: ignoring option `-m %s' ",
883 program_name, optarg);
884 (void)fprintf(stderr, "(no libsmi support)\n");
885 #endif
886 break;
887
888 case 'M':
889 /* TCP-MD5 shared secret */
890 #ifndef HAVE_LIBCRYPTO
891 warning("crypto code not compiled in");
892 #endif
893 sigsecret = optarg;
894 break;
895
896 case 'n':
897 ++nflag;
898 break;
899
900 case 'N':
901 ++Nflag;
902 break;
903
904 case 'O':
905 Oflag = 0;
906 break;
907
908 case 'p':
909 ++pflag;
910 break;
911
912 case 'q':
913 ++qflag;
914 ++suppress_default_print;
915 break;
916
917 case 'r':
918 RFileName = optarg;
919 break;
920
921 case 'R':
922 Rflag = 0;
923 break;
924
925 case 's': {
926 char *end;
927
928 snaplen = strtol(optarg, &end, 0);
929 if (optarg == end || *end != '\0'
930 || snaplen < 0 || snaplen > MAXIMUM_SNAPLEN)
931 error("invalid snaplen %s", optarg);
932 else if (snaplen == 0)
933 snaplen = MAXIMUM_SNAPLEN;
934 break;
935 }
936
937 case 'S':
938 ++Sflag;
939 break;
940
941 case 't':
942 ++tflag;
943 break;
944
945 case 'T':
946 if (strcasecmp(optarg, "vat") == 0)
947 packettype = PT_VAT;
948 else if (strcasecmp(optarg, "wb") == 0)
949 packettype = PT_WB;
950 else if (strcasecmp(optarg, "rpc") == 0)
951 packettype = PT_RPC;
952 else if (strcasecmp(optarg, "rtp") == 0)
953 packettype = PT_RTP;
954 else if (strcasecmp(optarg, "rtcp") == 0)
955 packettype = PT_RTCP;
956 else if (strcasecmp(optarg, "snmp") == 0)
957 packettype = PT_SNMP;
958 else if (strcasecmp(optarg, "cnfp") == 0)
959 packettype = PT_CNFP;
960 else if (strcasecmp(optarg, "tftp") == 0)
961 packettype = PT_TFTP;
962 else if (strcasecmp(optarg, "aodv") == 0)
963 packettype = PT_AODV;
964 else if (strcasecmp(optarg, "carp") == 0)
965 packettype = PT_CARP;
966 else if (strcasecmp(optarg, "radius") == 0)
967 packettype = PT_RADIUS;
968 else
969 error("unknown packet type `%s'", optarg);
970 break;
971
972 case 'u':
973 ++uflag;
974 break;
975
976 #ifdef HAVE_PCAP_DUMP_FLUSH
977 case 'U':
978 ++Uflag;
979 break;
980 #endif
981
982 case 'v':
983 ++vflag;
984 break;
985
986 case 'w':
987 WFileName = optarg;
988 break;
989
990 case 'W':
991 Wflag = atoi(optarg);
992 if (Wflag < 0)
993 error("invalid number of output files %s", optarg);
994 WflagChars = getWflagChars(Wflag);
995 break;
996
997 case 'x':
998 ++xflag;
999 ++suppress_default_print;
1000 break;
1001
1002 case 'X':
1003 ++Xflag;
1004 ++suppress_default_print;
1005 break;
1006
1007 case 'y':
1008 gndo->ndo_dltname = optarg;
1009 gndo->ndo_dlt =
1010 pcap_datalink_name_to_val(gndo->ndo_dltname);
1011 if (gndo->ndo_dlt < 0)
1012 error("invalid data link type %s", gndo->ndo_dltname);
1013 break;
1014
1015 #if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
1016 case 'Y':
1017 {
1018 /* Undocumented flag */
1019 #ifdef HAVE_PCAP_DEBUG
1020 extern int pcap_debug;
1021 pcap_debug = 1;
1022 #else
1023 extern int yydebug;
1024 yydebug = 1;
1025 #endif
1026 }
1027 break;
1028 #endif
1029 case 'z':
1030 if (optarg) {
1031 zflag = strdup(optarg);
1032 } else {
1033 usage();
1034 /* NOTREACHED */
1035 }
1036 break;
1037
1038 case 'Z':
1039 if (optarg) {
1040 username = strdup(optarg);
1041 }
1042 else {
1043 usage();
1044 /* NOTREACHED */
1045 }
1046 break;
1047
1048 default:
1049 usage();
1050 /* NOTREACHED */
1051 }
1052
1053 switch (tflag) {
1054
1055 case 0: /* Default */
1056 case 4: /* Default + Date*/
1057 thiszone = gmt2local(0);
1058 break;
1059
1060 case 1: /* No time stamp */
1061 case 2: /* Unix timeval style */
1062 case 3: /* Microseconds since previous packet */
1063 case 5: /* Microseconds since first packet */
1064 break;
1065
1066 default: /* Not supported */
1067 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1068 break;
1069 }
1070
1071 #ifdef WITH_CHROOT
1072 /* if run as root, prepare for chrooting */
1073 if (getuid() == 0 || geteuid() == 0) {
1074 /* future extensibility for cmd-line arguments */
1075 if (!chroot_dir)
1076 chroot_dir = WITH_CHROOT;
1077 }
1078 #endif
1079
1080 #ifdef WITH_USER
1081 /* if run as root, prepare for dropping root privileges */
1082 if (getuid() == 0 || geteuid() == 0) {
1083 /* Run with '-Z root' to restore old behaviour */
1084 if (!username)
1085 username = WITH_USER;
1086 }
1087 #endif
1088
1089 if (RFileName != NULL) {
1090 int dlt;
1091 const char *dlt_name;
1092
1093 #ifndef WIN32
1094 /*
1095 * We don't need network access, so relinquish any set-UID
1096 * or set-GID privileges we have (if any).
1097 *
1098 * We do *not* want set-UID privileges when opening a
1099 * trace file, as that might let the user read other
1100 * people's trace files (especially if we're set-UID
1101 * root).
1102 */
1103 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1104 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1105 #endif /* WIN32 */
1106 pd = pcap_open_offline(RFileName, ebuf);
1107 if (pd == NULL)
1108 error("%s", ebuf);
1109 dlt = pcap_datalink(pd);
1110 dlt_name = pcap_datalink_val_to_name(dlt);
1111 if (dlt_name == NULL) {
1112 fprintf(stderr, "reading from file %s, link-type %u\n",
1113 RFileName, dlt);
1114 } else {
1115 fprintf(stderr,
1116 "reading from file %s, link-type %s (%s)\n",
1117 RFileName, dlt_name,
1118 pcap_datalink_val_to_description(dlt));
1119 }
1120 localnet = 0;
1121 netmask = 0;
1122 if (fflag != 0)
1123 error("-f and -r options are incompatible");
1124 } else {
1125 if (device == NULL) {
1126 device = pcap_lookupdev(ebuf);
1127 if (device == NULL)
1128 error("%s", ebuf);
1129 }
1130 #ifdef WIN32
1131 if(strlen(device) == 1) //we assume that an ASCII string is always longer than 1 char
1132 { //a Unicode string has a \0 as second byte (so strlen() is 1)
1133 fprintf(stderr, "%s: listening on %ws\n", program_name, device);
1134 }
1135 else
1136 {
1137 fprintf(stderr, "%s: listening on %s\n", program_name, device);
1138 }
1139
1140 fflush(stderr);
1141 #endif /* WIN32 */
1142 #ifdef HAVE_PCAP_CREATE
1143 pd = pcap_create(device, ebuf);
1144 if (pd == NULL)
1145 error("%s", ebuf);
1146 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1147 if (Jflag)
1148 show_tstamp_types_and_exit(device, pd);
1149 #endif
1150 /*
1151 * Is this an interface that supports monitor mode?
1152 */
1153 if (pcap_can_set_rfmon(pd) == 1)
1154 supports_monitor_mode = 1;
1155 else
1156 supports_monitor_mode = 0;
1157 status = pcap_set_snaplen(pd, snaplen);
1158 if (status != 0)
1159 error("%s: Can't set snapshot length: %s",
1160 device, pcap_statustostr(status));
1161 status = pcap_set_promisc(pd, !pflag);
1162 if (status != 0)
1163 error("%s: Can't set promiscuous mode: %s",
1164 device, pcap_statustostr(status));
1165 if (Iflag) {
1166 status = pcap_set_rfmon(pd, 1);
1167 if (status != 0)
1168 error("%s: Can't set monitor mode: %s",
1169 device, pcap_statustostr(status));
1170 }
1171 status = pcap_set_timeout(pd, 1000);
1172 if (status != 0)
1173 error("%s: pcap_set_timeout failed: %s",
1174 device, pcap_statustostr(status));
1175 if (Bflag != 0) {
1176 status = pcap_set_buffer_size(pd, Bflag);
1177 if (status != 0)
1178 error("%s: Can't set buffer size: %s",
1179 device, pcap_statustostr(status));
1180 }
1181 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1182 if (jflag != -1) {
1183 status = pcap_set_tstamp_type(pd, jflag);
1184 if (status < 0)
1185 error("%s: Can't set time stamp type: %s",
1186 device, pcap_statustostr(status));
1187 }
1188 #endif
1189 status = pcap_activate(pd);
1190 if (status < 0) {
1191 /*
1192 * pcap_activate() failed.
1193 */
1194 cp = pcap_geterr(pd);
1195 if (status == PCAP_ERROR)
1196 error("%s", cp);
1197 else if ((status == PCAP_ERROR_NO_SUCH_DEVICE ||
1198 status == PCAP_ERROR_PERM_DENIED) &&
1199 *cp != '\0')
1200 error("%s: %s\n(%s)", device,
1201 pcap_statustostr(status), cp);
1202 else
1203 error("%s: %s", device,
1204 pcap_statustostr(status));
1205 } else if (status > 0) {
1206 /*
1207 * pcap_activate() succeeded, but it's warning us
1208 * of a problem it had.
1209 */
1210 cp = pcap_geterr(pd);
1211 if (status == PCAP_WARNING)
1212 warning("%s", cp);
1213 else if (status == PCAP_WARNING_PROMISC_NOTSUP &&
1214 *cp != '\0')
1215 warning("%s: %s\n(%s)", device,
1216 pcap_statustostr(status), cp);
1217 else
1218 warning("%s: %s", device,
1219 pcap_statustostr(status));
1220 }
1221 #else
1222 *ebuf = '\0';
1223 pd = pcap_open_live(device, snaplen, !pflag, 1000, ebuf);
1224 if (pd == NULL)
1225 error("%s", ebuf);
1226 else if (*ebuf)
1227 warning("%s", ebuf);
1228 #endif /* HAVE_PCAP_CREATE */
1229 /*
1230 * Let user own process after socket has been opened.
1231 */
1232 #ifndef WIN32
1233 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1234 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1235 #endif /* WIN32 */
1236 #if !defined(HAVE_PCAP_CREATE) && defined(WIN32)
1237 if(Bflag != 0)
1238 if(pcap_setbuff(pd, Bflag)==-1){
1239 error("%s", pcap_geterr(pd));
1240 }
1241 #endif /* !defined(HAVE_PCAP_CREATE) && defined(WIN32) */
1242 if (Lflag)
1243 show_dlts_and_exit(device, pd);
1244 if (gndo->ndo_dlt >= 0) {
1245 #ifdef HAVE_PCAP_SET_DATALINK
1246 if (pcap_set_datalink(pd, gndo->ndo_dlt) < 0)
1247 error("%s", pcap_geterr(pd));
1248 #else
1249 /*
1250 * We don't actually support changing the
1251 * data link type, so we only let them
1252 * set it to what it already is.
1253 */
1254 if (gndo->ndo_dlt != pcap_datalink(pd)) {
1255 error("%s is not one of the DLTs supported by this device\n",
1256 gndo->ndo_dltname);
1257 }
1258 #endif
1259 (void)fprintf(stderr, "%s: data link type %s\n",
1260 program_name, gndo->ndo_dltname);
1261 (void)fflush(stderr);
1262 }
1263 i = pcap_snapshot(pd);
1264 if (snaplen < i) {
1265 warning("snaplen raised from %d to %d", snaplen, i);
1266 snaplen = i;
1267 }
1268 if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
1269 localnet = 0;
1270 netmask = 0;
1271 warning("%s", ebuf);
1272 }
1273 }
1274 if (infile)
1275 cmdbuf = read_infile(infile);
1276 else
1277 cmdbuf = copy_argv(&argv[optind]);
1278
1279 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1280 error("%s", pcap_geterr(pd));
1281 free(cmdbuf);
1282 if (dflag) {
1283 bpf_dump(&fcode, dflag);
1284 pcap_close(pd);
1285 exit(0);
1286 }
1287 init_addrtoname(localnet, netmask);
1288 init_checksum();
1289
1290 #ifndef WIN32
1291 (void)setsignal(SIGPIPE, cleanup);
1292 (void)setsignal(SIGTERM, cleanup);
1293 (void)setsignal(SIGINT, cleanup);
1294 #endif /* WIN32 */
1295 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1296 (void)setsignal(SIGCHLD, child_cleanup);
1297 #endif
1298 /* Cooperate with nohup(1) */
1299 #ifndef WIN32
1300 if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
1301 (void)setsignal(SIGHUP, oldhandler);
1302 #endif /* WIN32 */
1303
1304 #ifndef WIN32
1305 /*
1306 * If a user name was specified with "-Z", attempt to switch to
1307 * that user's UID. This would probably be used with sudo,
1308 * to allow tcpdump to be run in a special restricted
1309 * account (if you just want to allow users to open capture
1310 * devices, and can't just give users that permission,
1311 * you'd make tcpdump set-UID or set-GID).
1312 *
1313 * Tcpdump doesn't necessarily write only to one savefile;
1314 * the general only way to allow a -Z instance to write to
1315 * savefiles as the user under whose UID it's run, rather
1316 * than as the user specified with -Z, would thus be to switch
1317 * to the original user ID before opening a capture file and
1318 * then switch back to the -Z user ID after opening the savefile.
1319 * Switching to the -Z user ID only after opening the first
1320 * savefile doesn't handle the general case.
1321 */
1322
1323 #ifdef HAVE_CAP_NG_H
1324 /* We are running as root and we will be writing to savefile */
1325 if ((getuid() == 0 || geteuid() == 0) && WFileName) {
1326 if (username) {
1327 /* Drop all capabilities from effective set */
1328 capng_clear(CAPNG_EFFECTIVE);
1329 /* Add capabilities we will need*/
1330 capng_update(CAPNG_ADD, CAPNG_PERMITTED, CAP_SETUID);
1331 capng_update(CAPNG_ADD, CAPNG_PERMITTED, CAP_SETGID);
1332 capng_update(CAPNG_ADD, CAPNG_PERMITTED, CAP_DAC_OVERRIDE);
1333
1334 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_SETUID);
1335 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_SETGID);
1336 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
1337
1338 capng_apply(CAPNG_SELECT_BOTH);
1339 }
1340 }
1341 #endif /* HAVE_CAP_NG_H */
1342
1343 if (getuid() == 0 || geteuid() == 0) {
1344 if (username || chroot_dir)
1345 droproot(username, chroot_dir);
1346
1347 }
1348 #endif /* WIN32 */
1349
1350 if (pcap_setfilter(pd, &fcode) < 0)
1351 error("%s", pcap_geterr(pd));
1352 if (WFileName) {
1353 pcap_dumper_t *p;
1354 /* Do not exceed the default NAME_MAX for files. */
1355 dumpinfo.CurrentFileName = (char *)malloc(NAME_MAX + 1);
1356
1357 if (dumpinfo.CurrentFileName == NULL)
1358 error("malloc of dumpinfo.CurrentFileName");
1359
1360 /* We do not need numbering for dumpfiles if Cflag isn't set. */
1361 if (Cflag != 0)
1362 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
1363 else
1364 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
1365
1366 p = pcap_dump_open(pd, dumpinfo.CurrentFileName);
1367 #ifdef HAVE_CAP_NG_H
1368 /* Give up capabilities, clear Effective set */
1369 capng_clear(CAPNG_EFFECTIVE);
1370 #endif
1371 if (p == NULL)
1372 error("%s", pcap_geterr(pd));
1373 if (Cflag != 0 || Gflag != 0) {
1374 callback = dump_packet_and_trunc;
1375 dumpinfo.WFileName = WFileName;
1376 dumpinfo.pd = pd;
1377 dumpinfo.p = p;
1378 pcap_userdata = (u_char *)&dumpinfo;
1379 } else {
1380 callback = dump_packet;
1381 pcap_userdata = (u_char *)p;
1382 }
1383 #ifdef HAVE_PCAP_DUMP_FLUSH
1384 if (Uflag)
1385 pcap_dump_flush(p);
1386 #endif
1387 } else {
1388 type = pcap_datalink(pd);
1389 printinfo.ndo_type = 1;
1390 printinfo.ndo = gndo;
1391 printinfo.p.ndo_printer = lookup_ndo_printer(type);
1392 if (printinfo.p.ndo_printer == NULL) {
1393 printinfo.p.printer = lookup_printer(type);
1394 printinfo.ndo_type = 0;
1395 if (printinfo.p.printer == NULL) {
1396 gndo->ndo_dltname = pcap_datalink_val_to_name(type);
1397 if (gndo->ndo_dltname != NULL)
1398 error("packet printing is not supported for link type %s: use -w",
1399 gndo->ndo_dltname);
1400 else
1401 error("packet printing is not supported for link type %d: use -w", type);
1402 }
1403 }
1404 callback = print_packet;
1405 pcap_userdata = (u_char *)&printinfo;
1406 }
1407
1408 #ifdef SIGNAL_REQ_INFO
1409 /*
1410 * We can't get statistics when reading from a file rather
1411 * than capturing from a device.
1412 */
1413 if (RFileName == NULL)
1414 (void)setsignal(SIGNAL_REQ_INFO, requestinfo);
1415 #endif
1416
1417 if (vflag > 0 && WFileName) {
1418 /*
1419 * When capturing to a file, "-v" means tcpdump should,
1420 * every 10 secodns, "v"erbosely report the number of
1421 * packets captured.
1422 */
1423 #ifdef USE_WIN32_MM_TIMER
1424 /* call verbose_stats_dump() each 1000 +/-100msec */
1425 timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
1426 setvbuf(stderr, NULL, _IONBF, 0);
1427 #elif defined(HAVE_ALARM)
1428 (void)setsignal(SIGALRM, verbose_stats_dump);
1429 alarm(1);
1430 #endif
1431 }
1432
1433 #ifndef WIN32
1434 if (RFileName == NULL) {
1435 int dlt;
1436 const char *dlt_name;
1437
1438 if (!vflag && !WFileName) {
1439 (void)fprintf(stderr,
1440 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
1441 program_name);
1442 } else
1443 (void)fprintf(stderr, "%s: ", program_name);
1444 dlt = pcap_datalink(pd);
1445 dlt_name = pcap_datalink_val_to_name(dlt);
1446 if (dlt_name == NULL) {
1447 (void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
1448 device, dlt, snaplen);
1449 } else {
1450 (void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
1451 device, dlt_name,
1452 pcap_datalink_val_to_description(dlt), snaplen);
1453 }
1454 (void)fflush(stderr);
1455 }
1456 #endif /* WIN32 */
1457 status = pcap_loop(pd, cnt, callback, pcap_userdata);
1458 if (WFileName == NULL) {
1459 /*
1460 * We're printing packets. Flush the printed output,
1461 * so it doesn't get intermingled with error output.
1462 */
1463 if (status == -2) {
1464 /*
1465 * We got interrupted, so perhaps we didn't
1466 * manage to finish a line we were printing.
1467 * Print an extra newline, just in case.
1468 */
1469 putchar('\n');
1470 }
1471 (void)fflush(stdout);
1472 }
1473 if (status == -1) {
1474 /*
1475 * Error. Report it.
1476 */
1477 (void)fprintf(stderr, "%s: pcap_loop: %s\n",
1478 program_name, pcap_geterr(pd));
1479 }
1480 if (RFileName == NULL) {
1481 /*
1482 * We're doing a live capture. Report the capture
1483 * statistics.
1484 */
1485 info(1);
1486 }
1487 pcap_close(pd);
1488 exit(status == -1 ? 1 : 0);
1489 }
1490
1491 /* make a clean exit on interrupts */
1492 static RETSIGTYPE
1493 cleanup(int signo _U_)
1494 {
1495 #ifdef USE_WIN32_MM_TIMER
1496 if (timer_id)
1497 timeKillEvent(timer_id);
1498 timer_id = 0;
1499 #elif defined(HAVE_ALARM)
1500 alarm(0);
1501 #endif
1502
1503 #ifdef HAVE_PCAP_BREAKLOOP
1504 /*
1505 * We have "pcap_breakloop()"; use it, so that we do as little
1506 * as possible in the signal handler (it's probably not safe
1507 * to do anything with standard I/O streams in a signal handler -
1508 * the ANSI C standard doesn't say it is).
1509 */
1510 pcap_breakloop(pd);
1511 #else
1512 /*
1513 * We don't have "pcap_breakloop()"; this isn't safe, but
1514 * it's the best we can do. Print the summary if we're
1515 * not reading from a savefile - i.e., if we're doing a
1516 * live capture - and exit.
1517 */
1518 if (pd != NULL && pcap_file(pd) == NULL) {
1519 /*
1520 * We got interrupted, so perhaps we didn't
1521 * manage to finish a line we were printing.
1522 * Print an extra newline, just in case.
1523 */
1524 putchar('\n');
1525 (void)fflush(stdout);
1526 info(1);
1527 }
1528 exit(0);
1529 #endif
1530 }
1531
1532 /*
1533 On windows, we do not use a fork, so we do not care less about
1534 waiting a child processes to die
1535 */
1536 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1537 static RETSIGTYPE
1538 child_cleanup(int signo _U_)
1539 {
1540 wait(NULL);
1541 }
1542 #endif /* HAVE_FORK && HAVE_VFORK */
1543
1544 static void
1545 info(register int verbose)
1546 {
1547 struct pcap_stat stat;
1548
1549 /*
1550 * Older versions of libpcap didn't set ps_ifdrop on some
1551 * platforms; initialize it to 0 to handle that.
1552 */
1553 stat.ps_ifdrop = 0;
1554 if (pcap_stats(pd, &stat) < 0) {
1555 (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
1556 infoprint = 0;
1557 return;
1558 }
1559
1560 if (!verbose)
1561 fprintf(stderr, "%s: ", program_name);
1562
1563 (void)fprintf(stderr, "%u packet%s captured", packets_captured,
1564 PLURAL_SUFFIX(packets_captured));
1565 if (!verbose)
1566 fputs(", ", stderr);
1567 else
1568 putc('\n', stderr);
1569 (void)fprintf(stderr, "%u packet%s received by filter", stat.ps_recv,
1570 PLURAL_SUFFIX(stat.ps_recv));
1571 if (!verbose)
1572 fputs(", ", stderr);
1573 else
1574 putc('\n', stderr);
1575 (void)fprintf(stderr, "%u packet%s dropped by kernel", stat.ps_drop,
1576 PLURAL_SUFFIX(stat.ps_drop));
1577 if (stat.ps_ifdrop != 0) {
1578 if (!verbose)
1579 fputs(", ", stderr);
1580 else
1581 putc('\n', stderr);
1582 (void)fprintf(stderr, "%u packet%s dropped by interface\n",
1583 stat.ps_ifdrop, PLURAL_SUFFIX(stat.ps_ifdrop));
1584 } else
1585 putc('\n', stderr);
1586 infoprint = 0;
1587 }
1588
1589 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1590 static void
1591 compress_savefile(const char *filename)
1592 {
1593 # ifdef HAVE_FORK
1594 if (fork())
1595 # else
1596 if (vfork())
1597 # endif
1598 return;
1599 /*
1600 * Set to lowest priority so that this doesn't disturb the capture
1601 */
1602 #ifdef NZERO
1603 setpriority(PRIO_PROCESS, 0, NZERO - 1);
1604 #else
1605 setpriority(PRIO_PROCESS, 0, 19);
1606 #endif
1607 if (execlp(zflag, zflag, filename, (char *)NULL) == -1)
1608 fprintf(stderr,
1609 "compress_savefile:execlp(%s, %s): %s\n",
1610 zflag,
1611 filename,
1612 strerror(errno));
1613 # ifdef HAVE_FORK
1614 exit(1);
1615 # else
1616 _exit(1);
1617 # endif
1618 }
1619 #else /* HAVE_FORK && HAVE_VFORK */
1620 static void
1621 compress_savefile(const char *filename)
1622 {
1623 fprintf(stderr,
1624 "compress_savefile failed. Functionality not implemented under your system\n");
1625 }
1626 #endif /* HAVE_FORK && HAVE_VFORK */
1627
1628 static void
1629 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1630 {
1631 struct dump_info *dump_info;
1632
1633 ++packets_captured;
1634
1635 ++infodelay;
1636
1637 dump_info = (struct dump_info *)user;
1638
1639 /*
1640 * XXX - this won't force the file to rotate on the specified time
1641 * boundary, but it will rotate on the first packet received after the
1642 * specified Gflag number of seconds. Note: if a Gflag time boundary
1643 * and a Cflag size boundary coincide, the time rotation will occur
1644 * first thereby cancelling the Cflag boundary (since the file should
1645 * be 0).
1646 */
1647 if (Gflag != 0) {
1648 /* Check if it is time to rotate */
1649 time_t t;
1650
1651 /* Get the current time */
1652 if ((t = time(NULL)) == (time_t)-1) {
1653 error("dump_and_trunc_packet: can't get current_time: %s",
1654 pcap_strerror(errno));
1655 }
1656
1657
1658 /* If the time is greater than the specified window, rotate */
1659 if (t - Gflag_time >= Gflag) {
1660 /* Update the Gflag_time */
1661 Gflag_time = t;
1662 /* Update Gflag_count */
1663 Gflag_count++;
1664 /*
1665 * Close the current file and open a new one.
1666 */
1667 pcap_dump_close(dump_info->p);
1668
1669 /*
1670 * Compress the file we just closed, if the user asked for it
1671 */
1672 if (zflag != NULL)
1673 compress_savefile(dump_info->CurrentFileName);
1674
1675 /*
1676 * Check to see if we've exceeded the Wflag (when
1677 * not using Cflag).
1678 */
1679 if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
1680 (void)fprintf(stderr, "Maximum file limit reached: %d\n",
1681 Wflag);
1682 exit(0);
1683 /* NOTREACHED */
1684 }
1685 if (dump_info->CurrentFileName != NULL)
1686 free(dump_info->CurrentFileName);
1687 /* Allocate space for max filename + \0. */
1688 dump_info->CurrentFileName = (char *)malloc(NAME_MAX + 1);
1689 if (dump_info->CurrentFileName == NULL)
1690 error("dump_packet_and_trunc: malloc");
1691 /*
1692 * This is always the first file in the Cflag
1693 * rotation: e.g. 0
1694 * We also don't need numbering if Cflag is not set.
1695 */
1696 if (Cflag != 0)
1697 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
1698 WflagChars);
1699 else
1700 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
1701
1702 #ifdef HAVE_CAP_NG_H
1703 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
1704 capng_apply(CAPNG_EFFECTIVE);
1705 #endif /* HAVE_CAP_NG_H */
1706 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
1707 #ifdef HAVE_CAP_NG_H
1708 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
1709 capng_apply(CAPNG_EFFECTIVE);
1710 #endif /* HAVE_CAP_NG_H */
1711 if (dump_info->p == NULL)
1712 error("%s", pcap_geterr(pd));
1713 }
1714 }
1715
1716 /*
1717 * XXX - this won't prevent capture files from getting
1718 * larger than Cflag - the last packet written to the
1719 * file could put it over Cflag.
1720 */
1721 if (Cflag != 0 && pcap_dump_ftell(dump_info->p) > Cflag) {
1722 /*
1723 * Close the current file and open a new one.
1724 */
1725 pcap_dump_close(dump_info->p);
1726
1727 /*
1728 * Compress the file we just closed, if the user asked for it
1729 */
1730 if (zflag != NULL)
1731 compress_savefile(dump_info->CurrentFileName);
1732
1733 Cflag_count++;
1734 if (Wflag > 0) {
1735 if (Cflag_count >= Wflag)
1736 Cflag_count = 0;
1737 }
1738 if (dump_info->CurrentFileName != NULL)
1739 free(dump_info->CurrentFileName);
1740 dump_info->CurrentFileName = (char *)malloc(NAME_MAX + 1);
1741 if (dump_info->CurrentFileName == NULL)
1742 error("dump_packet_and_trunc: malloc");
1743 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
1744 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
1745 if (dump_info->p == NULL)
1746 error("%s", pcap_geterr(pd));
1747 }
1748
1749 pcap_dump((u_char *)dump_info->p, h, sp);
1750 #ifdef HAVE_PCAP_DUMP_FLUSH
1751 if (Uflag)
1752 pcap_dump_flush(dump_info->p);
1753 #endif
1754
1755 --infodelay;
1756 if (infoprint)
1757 info(0);
1758 }
1759
1760 static void
1761 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1762 {
1763 ++packets_captured;
1764
1765 ++infodelay;
1766
1767 pcap_dump(user, h, sp);
1768 #ifdef HAVE_PCAP_DUMP_FLUSH
1769 if (Uflag)
1770 pcap_dump_flush((pcap_dumper_t *)user);
1771 #endif
1772
1773 --infodelay;
1774 if (infoprint)
1775 info(0);
1776 }
1777
1778 static void
1779 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1780 {
1781 struct print_info *print_info;
1782 u_int hdrlen;
1783
1784 ++packets_captured;
1785
1786 ++infodelay;
1787 ts_print(&h->ts);
1788
1789 print_info = (struct print_info *)user;
1790
1791 /*
1792 * Some printers want to check that they're not walking off the
1793 * end of the packet.
1794 * Rather than pass it all the way down, we set this global.
1795 */
1796 snapend = sp + h->caplen;
1797
1798 if(print_info->ndo_type) {
1799 hdrlen = (*print_info->p.ndo_printer)(print_info->ndo, h, sp);
1800 } else {
1801 hdrlen = (*print_info->p.printer)(h, sp);
1802 }
1803
1804 if (Xflag) {
1805 /*
1806 * Print the raw packet data in hex and ASCII.
1807 */
1808 if (Xflag > 1) {
1809 /*
1810 * Include the link-layer header.
1811 */
1812 hex_and_ascii_print("\n\t", sp, h->caplen);
1813 } else {
1814 /*
1815 * Don't include the link-layer header - and if
1816 * we have nothing past the link-layer header,
1817 * print nothing.
1818 */
1819 if (h->caplen > hdrlen)
1820 hex_and_ascii_print("\n\t", sp + hdrlen,
1821 h->caplen - hdrlen);
1822 }
1823 } else if (xflag) {
1824 /*
1825 * Print the raw packet data in hex.
1826 */
1827 if (xflag > 1) {
1828 /*
1829 * Include the link-layer header.
1830 */
1831 hex_print("\n\t", sp, h->caplen);
1832 } else {
1833 /*
1834 * Don't include the link-layer header - and if
1835 * we have nothing past the link-layer header,
1836 * print nothing.
1837 */
1838 if (h->caplen > hdrlen)
1839 hex_print("\n\t", sp + hdrlen,
1840 h->caplen - hdrlen);
1841 }
1842 } else if (Aflag) {
1843 /*
1844 * Print the raw packet data in ASCII.
1845 */
1846 if (Aflag > 1) {
1847 /*
1848 * Include the link-layer header.
1849 */
1850 ascii_print(sp, h->caplen);
1851 } else {
1852 /*
1853 * Don't include the link-layer header - and if
1854 * we have nothing past the link-layer header,
1855 * print nothing.
1856 */
1857 if (h->caplen > hdrlen)
1858 ascii_print(sp + hdrlen, h->caplen - hdrlen);
1859 }
1860 }
1861
1862 putchar('\n');
1863
1864 --infodelay;
1865 if (infoprint)
1866 info(0);
1867 }
1868
1869 #ifdef WIN32
1870 /*
1871 * XXX - there should really be libpcap calls to get the version
1872 * number as a string (the string would be generated from #defines
1873 * at run time, so that it's not generated from string constants
1874 * in the library, as, on many UNIX systems, those constants would
1875 * be statically linked into the application executable image, and
1876 * would thus reflect the version of libpcap on the system on
1877 * which the application was *linked*, not the system on which it's
1878 * *running*.
1879 *
1880 * That routine should be documented, unlike the "version[]"
1881 * string, so that UNIX vendors providing their own libpcaps
1882 * don't omit it (as a couple of vendors have...).
1883 *
1884 * Packet.dll should perhaps also export a routine to return the
1885 * version number of the Packet.dll code, to supply the
1886 * "Wpcap_version" information on Windows.
1887 */
1888 char WDversion[]="current-cvs.tcpdump.org";
1889 #if !defined(HAVE_GENERATED_VERSION)
1890 char version[]="current-cvs.tcpdump.org";
1891 #endif
1892 char pcap_version[]="current-cvs.tcpdump.org";
1893 char Wpcap_version[]="3.1";
1894 #endif
1895
1896 /*
1897 * By default, print the specified data out in hex and ASCII.
1898 */
1899 static void
1900 ndo_default_print(netdissect_options *ndo _U_, const u_char *bp, u_int length)
1901 {
1902 hex_and_ascii_print("\n\t", bp, length); /* pass on lf and identation string */
1903 }
1904
1905 void
1906 default_print(const u_char *bp, u_int length)
1907 {
1908 ndo_default_print(gndo, bp, length);
1909 }
1910
1911 #ifdef SIGNAL_REQ_INFO
1912 RETSIGTYPE requestinfo(int signo _U_)
1913 {
1914 if (infodelay)
1915 ++infoprint;
1916 else
1917 info(0);
1918 }
1919 #endif
1920
1921 /*
1922 * Called once each second in verbose mode while dumping to file
1923 */
1924 #ifdef USE_WIN32_MM_TIMER
1925 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
1926 DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
1927 {
1928 struct pcap_stat stat;
1929
1930 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
1931 fprintf(stderr, "Got %u\r", packets_captured);
1932 }
1933 #elif defined(HAVE_ALARM)
1934 static void verbose_stats_dump(int sig _U_)
1935 {
1936 struct pcap_stat stat;
1937
1938 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
1939 fprintf(stderr, "Got %u\r", packets_captured);
1940 alarm(1);
1941 }
1942 #endif
1943
1944 static void
1945 usage(void)
1946 {
1947 extern char version[];
1948 #ifndef HAVE_PCAP_LIB_VERSION
1949 #if defined(WIN32) || defined(HAVE_PCAP_VERSION)
1950 extern char pcap_version[];
1951 #else /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
1952 static char pcap_version[] = "unknown";
1953 #endif /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
1954 #endif /* HAVE_PCAP_LIB_VERSION */
1955
1956 #ifdef HAVE_PCAP_LIB_VERSION
1957 #ifdef WIN32
1958 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
1959 #else /* WIN32 */
1960 (void)fprintf(stderr, "%s version %s\n", program_name, version);
1961 #endif /* WIN32 */
1962 (void)fprintf(stderr, "%s\n",pcap_lib_version());
1963 #else /* HAVE_PCAP_LIB_VERSION */
1964 #ifdef WIN32
1965 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
1966 (void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
1967 #else /* WIN32 */
1968 (void)fprintf(stderr, "%s version %s\n", program_name, version);
1969 (void)fprintf(stderr, "libpcap version %s\n", pcap_version);
1970 #endif /* WIN32 */
1971 #endif /* HAVE_PCAP_LIB_VERSION */
1972 (void)fprintf(stderr,
1973 "Usage: %s [-aAbd" D_FLAG "efhH" I_FLAG J_FLAG "KlLnNOpqRStu" U_FLAG "vxX]" B_FLAG_USAGE " [ -c count ]\n", program_name);
1974 (void)fprintf(stderr,
1975 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
1976 (void)fprintf(stderr,
1977 "\t\t[ -i interface ]" j_FLAG_USAGE " [ -M secret ]\n");
1978 (void)fprintf(stderr,
1979 "\t\t[ -r file ] [ -s snaplen ] [ -T type ] [ -w file ]\n");
1980 (void)fprintf(stderr,
1981 "\t\t[ -W filecount ] [ -y datalinktype ] [ -z command ]\n");
1982 (void)fprintf(stderr,
1983 "\t\t[ -Z user ] [ expression ]\n");
1984 exit(1);
1985 }
1986
1987
1988
1989 /* VARARGS */
1990 static void
1991 ndo_error(netdissect_options *ndo _U_, const char *fmt, ...)
1992 {
1993 va_list ap;
1994
1995 (void)fprintf(stderr, "%s: ", program_name);
1996 va_start(ap, fmt);
1997 (void)vfprintf(stderr, fmt, ap);
1998 va_end(ap);
1999 if (*fmt) {
2000 fmt += strlen(fmt);
2001 if (fmt[-1] != '\n')
2002 (void)fputc('\n', stderr);
2003 }
2004 exit(1);
2005 /* NOTREACHED */
2006 }
2007
2008 /* VARARGS */
2009 static void
2010 ndo_warning(netdissect_options *ndo _U_, const char *fmt, ...)
2011 {
2012 va_list ap;
2013
2014 (void)fprintf(stderr, "%s: WARNING: ", program_name);
2015 va_start(ap, fmt);
2016 (void)vfprintf(stderr, fmt, ap);
2017 va_end(ap);
2018 if (*fmt) {
2019 fmt += strlen(fmt);
2020 if (fmt[-1] != '\n')
2021 (void)fputc('\n', stderr);
2022 }
2023 }