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