use the same packet range things for "Print" dialog, as already implemented
[obnox/wireshark/wip.git] / tethereal.c
1 /* tethereal.c
2  *
3  * $Id: tethereal.c,v 1.215 2004/01/09 19:02:18 ulfl Exp $
4  *
5  * Ethereal - Network traffic analyzer
6  * By Gerald Combs <gerald@ethereal.com>
7  * Copyright 1998 Gerald Combs
8  *
9  * Text-mode variant, by Gilbert Ramirez <gram@alumni.rice.edu>
10  * and Guy Harris <guy@alum.mit.edu>.
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License
14  * as published by the Free Software Foundation; either version 2
15  * of the License, or (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25  */
26
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <string.h>
34 #include <ctype.h>
35 #include <locale.h>
36 #include <limits.h>
37
38 #ifdef HAVE_UNISTD_H
39 #include <unistd.h>
40 #endif
41
42 #include <errno.h>
43
44 #ifdef HAVE_FCNTL_H
45 #include <fcntl.h>
46 #endif
47
48 #include <signal.h>
49
50 #ifdef HAVE_LIBPCAP
51 #include <pcap.h>
52 #include <setjmp.h>
53 #endif
54
55 #ifdef HAVE_SYS_STAT_H
56 # include <sys/stat.h>
57 #endif
58
59 #ifdef NEED_SNPRINTF_H
60 # include "snprintf.h"
61 #endif
62
63 #ifdef NEED_STRERROR_H
64 #include "strerror.h"
65 #endif
66
67 #ifdef NEED_GETOPT_H
68 #include "getopt.h"
69 #endif
70
71 #include <glib.h>
72 #include <epan/epan.h>
73 #include <epan/filesystem.h>
74
75 #include "globals.h"
76 #include <epan/timestamp.h>
77 #include <epan/packet.h>
78 #include "file.h"
79 #include "disabled_protos.h"
80 #include "prefs.h"
81 #include "column.h"
82 #include "print.h"
83 #include <epan/resolv.h>
84 #include "util.h"
85 #ifdef HAVE_LIBPCAP
86 #include "pcap-util.h"
87 #endif
88 #include <epan/conversation.h>
89 #include <epan/plugins.h>
90 #include "register.h"
91 #include "conditions.h"
92 #include "capture_stop_conditions.h"
93 #include "ringbuffer.h"
94 #include <epan/epan_dissect.h>
95 #include "tap.h"
96
97 #ifdef HAVE_LIBPCAP
98 #include <wiretap/wtap-capture.h>
99 #include <wiretap/libpcap.h>
100 #endif
101
102 #ifdef _WIN32
103 #include "capture-wpcap.h"
104 #endif
105
106 /*
107  * This is the template for the decode as option; it is shared between the
108  * various functions that output the usage for this parameter.
109  */
110 static const gchar decode_as_arg_template[] = "<layer_type>==<selector>,<decode_as_protocol>";
111 static guint32 firstsec, firstusec;
112 static guint32 prevsec, prevusec;
113 static GString *comp_info_str, *runtime_info_str;
114 static gboolean quiet;
115 static gboolean decode;
116 static gboolean verbose;
117 static gboolean print_hex;
118 static gboolean line_buffered;
119 static guint32 cul_bytes = 0;
120 static int print_format;
121
122 #ifdef HAVE_LIBPCAP
123 typedef struct _loop_data {
124   gboolean       go;           /* TRUE as long as we're supposed to keep capturing */
125   gint           linktype;
126   gboolean       from_pipe;    /* TRUE if we are capturing data from a pipe */
127   pcap_t        *pch;
128   wtap_dumper   *pdh;
129   jmp_buf        stopenv;
130   gboolean       output_to_pipe;
131   int            packet_count;
132 #ifndef _WIN32
133   gboolean       modified;     /* TRUE if data in the pipe uses modified pcap headers */
134   gboolean       byte_swapped; /* TRUE if data in the pipe is byte swapped */
135   unsigned int   bytes_to_read, bytes_read; /* Used by pipe_dispatch */
136   enum {
137          STATE_EXPECT_REC_HDR, STATE_READ_REC_HDR,
138          STATE_EXPECT_DATA,     STATE_READ_DATA
139        } pipe_state;
140
141   enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } pipe_err;
142 #endif
143 } loop_data;
144
145 static loop_data ld;
146
147 static int capture(int);
148 static void capture_pcap_cb(guchar *, const struct pcap_pkthdr *,
149   const guchar *);
150 static void report_counts(void);
151 #ifdef _WIN32
152 static BOOL WINAPI capture_cleanup(DWORD);
153 #else /* _WIN32 */
154 static void capture_cleanup(int);
155 #ifdef SIGINFO
156 static void report_counts_siginfo(int);
157 #endif /* SIGINFO */
158 #endif /* _WIN32 */
159 #endif /* HAVE_LIBPCAP */
160
161 typedef struct {
162   capture_file *cf;
163   wtap_dumper *pdh;
164 } cb_args_t;
165
166 static int load_cap_file(capture_file *, int);
167 static void wtap_dispatch_cb_write(guchar *, const struct wtap_pkthdr *, long,
168     union wtap_pseudo_header *, const guchar *);
169 static void show_capture_file_io_error(const char *, int, gboolean);
170 static void wtap_dispatch_cb_print(guchar *, const struct wtap_pkthdr *, long,
171     union wtap_pseudo_header *, const guchar *);
172 #ifdef HAVE_LIBPCAP
173 #ifndef _WIN32
174 static void adjust_header(loop_data *, struct pcap_hdr *, struct pcaprec_hdr *);
175 static int pipe_open_live(char *, struct pcap_hdr *, loop_data *, char *, int);
176 static int pipe_dispatch(int, loop_data *, struct pcap_hdr *, \
177                 struct pcaprec_modified_hdr *, guchar *, char *, int);
178 #endif /* _WIN32 */
179 #endif
180
181 capture_file cfile;
182 ts_type timestamp_type = RELATIVE;
183 #ifdef HAVE_LIBPCAP
184 typedef struct {
185         int snaplen;                    /* Maximum captured packet length */
186         int promisc_mode;               /* Capture in promiscuous mode */
187         int autostop_count;             /* Maximum packet count */
188         gboolean has_autostop_duration; /* TRUE if maximum capture duration
189                                            is specified */
190         gint32 autostop_duration;       /* Maximum capture duration */
191         gboolean has_autostop_filesize; /* TRUE if maximum capture file size
192                                            is specified */
193         gint32 autostop_filesize;       /* Maximum capture file size */
194         gboolean ringbuffer_on;         /* TRUE if ring buffer in use */
195         guint32 ringbuffer_num_files;   /* Number of ring buffer files */
196         gboolean has_ring_duration;     /* TRUE if ring duration specified */
197         gint32 ringbuffer_duration;     /* Switch file after n seconds */
198         int linktype;                   /* Data link type to use, or -1 for
199                                            "use default" */
200 } capture_options;
201
202 static capture_options capture_opts = {
203         WTAP_MAX_PACKET_SIZE,           /* snapshot length - default is
204                                            infinite, in effect */
205         TRUE,                           /* promiscuous mode is the default */
206         0,                              /* max packet count - default is 0,
207                                            meaning infinite */
208         FALSE,                          /* maximum capture duration not
209                                            specified by default */
210         0,                              /* maximum capture duration */
211         FALSE,                          /* maximum capture file size not
212                                            specified by default */
213         0,                              /* maximum capture file size */
214         FALSE,                          /* ring buffer off by default */
215         RINGBUFFER_MIN_NUM_FILES,       /* default number of ring buffer
216                                            files */
217         FALSE,                          /* Switch ring file after some */
218         0,                              /* specified time is off by default */
219         -1                              /* Default to not change link type */
220 };
221
222 static gboolean list_link_layer_types;
223
224 #ifdef SIGINFO
225 static gboolean infodelay;      /* if TRUE, don't print capture info in SIGINFO handler */
226 static gboolean infoprint;      /* if TRUE, print capture info after clearing infodelay */
227 #endif /* SIGINFO */
228 #endif /* HAVE_LIBPCAP */
229
230 static void
231 print_usage(gboolean print_ver)
232 {
233   int i;
234
235   if (print_ver) {
236     fprintf(stderr, "This is GNU t%s %s\n%s\n%s\n", PACKAGE, VERSION,
237         comp_info_str->str, runtime_info_str->str);
238   }
239 #ifdef HAVE_LIBPCAP
240   fprintf(stderr, "\nt%s [ -vh ] [ -DlLnpqSVx ] [ -a <capture autostop condition> ] ...\n",
241           PACKAGE);
242   fprintf(stderr, "\t[ -b <number of ring buffer files>[:<duration>] ] [ -c <count> ]\n");
243   fprintf(stderr, "\t[ -d %s ] ...\n", decode_as_arg_template);
244   fprintf(stderr, "\t[ -f <capture filter> ] [ -F <output file type> ] [ -i <interface> ]\n");
245   fprintf(stderr, "\t[ -N <resolving> ] [ -o <preference setting> ] ... [ -r <infile> ]\n");
246   fprintf(stderr, "\t[ -R <read filter> ] [ -s <snaplen> ] [ -t <time stamp format> ]\n");
247   fprintf(stderr, "\t[ -T pdml|ps|text ] [ -w <savefile> ] [ -y <link type> ]\n");
248   fprintf(stderr, "\t[ -z <statistics string> ]\n");
249 #else
250   fprintf(stderr, "\nt%s [ -vh ] [ -lnVx ]\n", PACKAGE);
251   fprintf(stderr, "\t[ -d %s ] ...\n", decode_as_arg_template);
252   fprintf(stderr, "\t[ -F <output file type> ] [ -N <resolving> ]\n");
253   fprintf(stderr, "\t[ -o <preference setting> ] ... [ -r <infile> ] [ -R <read filter> ]\n");
254   fprintf(stderr, "\t[ -t <time stamp format> ] [ -T pdml|ps|text ] [ -w <savefile> ]\n");
255   fprintf(stderr, "\t[ -z <statistics string> ]\n");
256 #endif
257   fprintf(stderr, "Valid file type arguments to the \"-F\" flag:\n");
258   for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
259     if (wtap_dump_can_open(i))
260       fprintf(stderr, "\t%s - %s\n",
261         wtap_file_type_short_string(i), wtap_file_type_string(i));
262   }
263   fprintf(stderr, "\tdefault is libpcap\n");
264 }
265
266 #ifdef HAVE_LIBPCAP
267 static int
268 get_natural_int(const char *string, const char *name)
269 {
270   long number;
271   char *p;
272
273   number = strtol(string, &p, 10);
274   if (p == string || *p != '\0') {
275     fprintf(stderr, "tethereal: The specified %s \"%s\" is not a decimal number\n",
276             name, string);
277     exit(1);
278   }
279   if (number < 0) {
280     fprintf(stderr, "tethereal: The specified %s is a negative number\n",
281             name);
282     exit(1);
283   }
284   if (number > INT_MAX) {
285     fprintf(stderr, "tethereal: The specified %s is too large (greater than %d)\n",
286             name, INT_MAX);
287     exit(1);
288   }
289   return number;
290 }
291
292 static int
293 get_positive_int(const char *string, const char *name)
294 {
295   long number;
296
297   number = get_natural_int(string, name);
298
299   if (number == 0) {
300     fprintf(stderr, "tethereal: The specified %s is zero\n",
301             name);
302     exit(1);
303   }
304
305   return number;
306 }
307
308 /*
309  * Given a string of the form "<autostop criterion>:<value>", as might appear
310  * as an argument to a "-a" option, parse it and set the criterion in
311  * question.  Return an indication of whether it succeeded or failed
312  * in some fashion.
313  */
314 static gboolean
315 set_autostop_criterion(const char *autostoparg)
316 {
317   guchar *p, *colonp;
318
319   colonp = strchr(autostoparg, ':');
320   if (colonp == NULL)
321     return FALSE;
322
323   p = colonp;
324   *p++ = '\0';
325
326   /*
327    * Skip over any white space (there probably won't be any, but
328    * as we allow it in the preferences file, we might as well
329    * allow it here).
330    */
331   while (isspace(*p))
332     p++;
333   if (*p == '\0') {
334     /*
335      * Put the colon back, so if our caller uses, in an
336      * error message, the string they passed us, the message
337      * looks correct.
338      */
339     *colonp = ':';
340     return FALSE;
341   }
342   if (strcmp(autostoparg,"duration") == 0) {
343     capture_opts.has_autostop_duration = TRUE;
344     capture_opts.autostop_duration = get_positive_int(p,"autostop duration");
345   } else if (strcmp(autostoparg,"filesize") == 0) {
346     capture_opts.has_autostop_filesize = TRUE;
347     capture_opts.autostop_filesize = get_positive_int(p,"autostop filesize");
348   } else {
349     return FALSE;
350   }
351   *colonp = ':';        /* put the colon back */
352   return TRUE;
353 }
354
355 /*
356  * Given a string of the form "<ring buffer file>:<duration>", as might appear
357  * as an argument to a "-b" option, parse it and set the arguments in
358  * question.  Return an indication of whether it succeeded or failed
359  * in some fashion.
360  */
361 static gboolean
362 get_ring_arguments(const char *arg)
363 {
364   guchar *p = NULL, *colonp;
365
366   colonp = strchr(arg, ':');
367
368   if (colonp != NULL) {
369     p = colonp;
370     *p++ = '\0';
371   }
372
373   capture_opts.ringbuffer_num_files = 
374     get_natural_int(arg, "number of ring buffer files");
375
376   if (colonp == NULL)
377     return TRUE;
378
379   /*
380    * Skip over any white space (there probably won't be any, but
381    * as we allow it in the preferences file, we might as well
382    * allow it here).
383    */
384   while (isspace(*p))
385     p++;
386   if (*p == '\0') {
387     /*
388      * Put the colon back, so if our caller uses, in an
389      * error message, the string they passed us, the message
390      * looks correct.
391      */
392     *colonp = ':';
393     return FALSE;
394   }
395
396   capture_opts.has_ring_duration = TRUE;
397   capture_opts.ringbuffer_duration = get_positive_int(p,
398                                                       "ring buffer duration");
399
400   *colonp = ':';        /* put the colon back */
401   return TRUE;
402 }
403 #endif
404
405 /* structure to keep track of what tap listeners have been registered.
406  */
407 typedef struct _ethereal_tap_list {
408         struct _ethereal_tap_list *next;
409         char *cmd;
410         void (*func)(char *arg);
411 } ethereal_tap_list;
412 static ethereal_tap_list *tap_list=NULL;
413
414 void
415 register_ethereal_tap(char *cmd, void (*func)(char *arg))
416 {
417         ethereal_tap_list *newtl;
418
419         newtl=malloc(sizeof(ethereal_tap_list));
420         newtl->next=tap_list;
421         tap_list=newtl;
422         newtl->cmd=cmd;
423         newtl->func=func;
424
425 }
426
427 /*
428  * For a dissector table, print on the stream described by output,
429  * its short name (which is what's used in the "-d" option) and its
430  * descriptive name.
431  */
432 static void
433 display_dissector_table_names(char *table_name, char *ui_name, gpointer output)
434 {
435   fprintf((FILE *)output, "\t%s (%s)\n", table_name, ui_name);
436 }
437
438 /*
439  * For a dissector handle, print on the stream described by output,
440  * the filter name (which is what's used in the "-d" option) and the full
441  * name for the protocol that corresponds to this handle.
442  */
443 static void
444 display_dissector_names(gchar *table _U_, gpointer handle, gpointer output)
445 {
446   int                proto_id;
447   const gchar*       proto_filter_name;
448   const gchar*       proto_ui_name;
449
450   proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
451
452   if (proto_id != -1) {
453     proto_filter_name = proto_get_protocol_filter_name(proto_id);
454     proto_ui_name =  proto_get_protocol_name(proto_id);
455     g_assert(proto_filter_name != NULL);
456     g_assert(proto_ui_name != NULL);
457
458     fprintf((FILE *)output, "\t%s (%s)\n",
459             proto_filter_name,
460             proto_ui_name);
461   }
462 }
463
464 /*
465  * The protocol_name_search structure is used by find_protocol_name_func()
466  * to pass parameters and store results
467  */
468 struct protocol_name_search{
469   gchar              *searched_name;  /* Protocol filter name we are looking for */
470   dissector_handle_t  matched_handle; /* Handle for a dissector whose protocol has the specified filter name */
471   guint               nb_match;       /* How many dissectors matched searched_name */
472 };
473 typedef struct protocol_name_search *protocol_name_search_t;
474
475 /*
476  * This function parses all dissectors associated with a table to find the
477  * one whose protocol has the specified filter name.  It is called
478  * as a reference function in a call to dissector_table_foreach_handle.
479  * The name we are looking for, as well as the results, are stored in the
480  * protocol_name_search struct pointed to by user_data.
481  * If called using dissector_table_foreach_handle, we actually parse the
482  * whole list of dissectors.
483  */
484 static void
485 find_protocol_name_func(gchar *table _U_, gpointer handle, gpointer user_data)
486
487 {
488   int                         proto_id;
489   const gchar                *protocol_filter_name;
490   protocol_name_search_t      search_info;
491
492   g_assert(handle);
493
494   search_info = (protocol_name_search_t)user_data;
495
496   proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
497   if (proto_id != -1) {
498     protocol_filter_name = proto_get_protocol_filter_name(proto_id);
499     g_assert(protocol_filter_name != NULL);
500     if (strcmp(protocol_filter_name, search_info->searched_name) == 0) {
501       /* Found a match */
502       if (search_info->nb_match == 0) {
503         /* Record this handle only if this is the first match */
504         search_info->matched_handle = (dissector_handle_t)handle; /* Record the handle for this matching dissector */
505       }
506       search_info->nb_match++;
507     }
508   }
509 }
510
511 /*
512  * Print all layer type names supported.
513  * We send the output to the stream described by the handle output.
514  */
515
516 static void
517 fprint_all_layer_types(FILE *output)
518
519 {
520   dissector_all_tables_foreach_table(display_dissector_table_names, (gpointer)output);
521 }
522
523 /*
524  * Print all protocol names supported for a specific layer type.
525  * table_name contains the layer type name in which the search is performed.
526  * We send the output to the stream described by the handle output.
527  */
528
529 static void
530 fprint_all_protocols_for_layer_types(FILE *output, gchar *table_name)
531
532 {
533   dissector_table_foreach_handle(table_name,
534                                  display_dissector_names,
535                                  (gpointer)output);
536 }
537
538 /*
539  * The function below parses the command-line parameters for the decode as
540  * feature (a string pointer by cl_param).
541  * It checks the format of the command-line, searches for a matching table
542  * and dissector.  If a table/dissector match is not found, we display a
543  * summary of the available tables/dissectors (on stderr) and return FALSE.
544  * If everything is fine, we get the "Decode as" preference activated,
545  * then we return TRUE.
546  */
547 static gboolean
548 add_decode_as(const gchar *cl_param)
549 {
550   gchar                        *table_name;
551   guint32                       selector;
552   gchar                        *decoded_param;
553   gchar                        *remaining_param;
554   gchar                        *selector_str;
555   gchar                        *dissector_str;
556   dissector_handle_t            dissector_matching;
557   dissector_table_t             table_matching;
558   ftenum_t                      dissector_table_selector_type;
559   struct protocol_name_search   user_protocol_name;
560
561 /* The following code will allocate and copy the command-line options in a string pointed by decoded_param */
562
563   g_assert(cl_param);
564   decoded_param = g_malloc( sizeof(gchar) * (strlen(cl_param) + 1) ); /* Allocate enough space to have a working copy of the command-line parameter */
565   g_assert(decoded_param);
566   strcpy(decoded_param, cl_param);
567
568
569   /* The lines below will parse this string (modifying it) to extract all
570     necessary information.  Note that decoded_param is still needed since
571     strings are not copied - we just save pointers. */
572
573   /* This section extracts a layer type (table_name) from decoded_param */
574   table_name = decoded_param; /* Layer type string starts from beginning */
575
576   remaining_param = strchr(table_name, '=');
577   if (remaining_param == NULL) {
578     fprintf(stderr, "tethereal: Parameter \"%s\" doesn't follow the template \"%s\"\n", cl_param, decode_as_arg_template);
579     /* If the argument does not follow the template, carry on anyway to check
580        if the table name is at least correct.  If remaining_param is NULL,
581        we'll exit anyway further down */
582   }
583   else {
584     *remaining_param = '\0'; /* Terminate the layer type string (table_name) where '=' was detected */
585   }
586
587   /* Remove leading and trailing spaces from the table name */
588   while ( table_name[0] == ' ' )
589     table_name++; 
590   while ( table_name[strlen(table_name) - 1] == ' ' )
591     table_name[strlen(table_name) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
592
593 /* The following part searches a table matching with the layer type specified */
594   table_matching = NULL;
595
596 /* Look for the requested table */
597   if ( !(*(table_name)) ) { /* Is the table name empty, if so, don't even search for anything, display a message */
598     fprintf(stderr, "tethereal: No layer type specified\n"); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
599   }
600   else {
601     table_matching = find_dissector_table(table_name);
602     if (!table_matching) {
603       fprintf(stderr, "tethereal: Unknown layer type -- %s\n", table_name); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
604     }
605   }
606
607   if (!table_matching) {
608     /* Display a list of supported layer types to help the user, if the 
609        specified layer type was not found */
610     fprintf(stderr, "tethereal: Valid layer types are:\n");
611     fprint_all_layer_types(stderr);
612   }
613   if (remaining_param == NULL || !table_matching) {
614     /* Exit if the layer type was not found, or if no '=' separator was found
615        (see above) */
616     g_free(decoded_param); 
617     return FALSE;
618   }
619   
620   if (*(remaining_param + 1) != '=') { /* Check for "==" and not only '=' */
621     fprintf(stderr, "tethereal: WARNING: -d requires \"==\" instead of \"=\". Option will be treated as \"%s==%s\"\n", table_name, remaining_param + 1);
622   }
623   else {
624     remaining_param++; /* Move to the second '=' */
625     *remaining_param = '\0'; /* Remove the second '=' */
626   }
627   remaining_param++; /* Position after the layer type string */
628
629   /* This section extracts a selector value (selector_str) from decoded_param */
630
631   selector_str = remaining_param; /* Next part starts with the selector number */
632
633   remaining_param = strchr(selector_str, ',');
634   if (remaining_param == NULL) {
635     fprintf(stderr, "tethereal: Parameter \"%s\" doesn't follow the template \"%s\"\n", cl_param, decode_as_arg_template);
636     /* If the argument does not follow the template, carry on anyway to check
637        if the selector value is at least correct.  If remaining_param is NULL,
638        we'll exit anyway further down */
639   }
640   else {
641     *remaining_param = '\0'; /* Terminate the selector number string (selector_str) where ',' was detected */
642   }
643
644   dissector_table_selector_type = get_dissector_table_selector_type(table_name);
645
646   switch (dissector_table_selector_type) {
647
648   case FT_UINT8:
649   case FT_UINT16:
650   case FT_UINT24:
651   case FT_UINT32:
652     /* The selector for this table is an unsigned number.  Parse it as such.
653        There's no need to remove leading and trailing spaces from the
654        selector number string, because sscanf will do that for us. */
655     if ( sscanf(selector_str, "%u", &selector) != 1 ) {
656       fprintf(stderr, "tethereal: Invalid selector number \"%s\"\n", selector_str);
657       g_free(decoded_param);
658       return FALSE;
659     }
660     break;
661
662   case FT_STRING:
663   case FT_STRINGZ:
664     /* The selector for this table is a string. */
665     break;
666
667   default:
668     /* There are currently no dissector tables with any types other
669        than the ones listed above. */
670     g_assert_not_reached();
671   }
672
673   if (remaining_param == NULL) {
674     /* Exit if no ',' separator was found (see above) */
675     fprintf(stderr, "tethereal: Valid protocols for layer type \"%s\" are:\n", table_name);
676     fprint_all_protocols_for_layer_types(stderr, table_name);
677     g_free(decoded_param); 
678     return FALSE;
679   }
680
681   remaining_param++; /* Position after the selector number string */
682
683   /* This section extracts a protocol filter name (dissector_str) from decoded_param */
684
685   dissector_str = remaining_param; /* All the rest of the string is the dissector (decode as protocol) name */
686   
687   /* Remove leading and trailing spaces from the dissector name */
688   while ( dissector_str[0] == ' ' )
689     dissector_str++; 
690   while ( dissector_str[strlen(dissector_str) - 1] == ' ' )
691     dissector_str[strlen(dissector_str) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
692
693   dissector_matching = NULL;
694   
695   /* We now have a pointer to the handle for the requested table inside the variable table_matching */
696   if ( ! (*dissector_str) ) { /* Is the dissector name empty, if so, don't even search for a matching dissector and display all dissectors found for the selected table */
697     fprintf(stderr, "tethereal: No protocol name specified\n"); /* Note, we don't exit here, but dissector_matching will remain NULL, so we exit below */
698   }
699   else {
700     user_protocol_name.nb_match = 0;
701     user_protocol_name.searched_name = dissector_str;
702     user_protocol_name.matched_handle = NULL;
703     
704     dissector_table_foreach_handle(table_name, find_protocol_name_func, &user_protocol_name); /* Go and perform the search for this dissector in the this table's dissectors' names and shortnames */
705     
706     if (user_protocol_name.nb_match != 0) {
707       dissector_matching = user_protocol_name.matched_handle;
708       if (user_protocol_name.nb_match > 1) {
709         fprintf(stderr, "tethereal: WARNING: Protocol \"%s\" matched %u dissectors, first one will be used\n", dissector_str, user_protocol_name.nb_match);
710       }
711     }
712     else {
713       /* OK, check whether the problem is that there isn't any such
714          protocol, or that there is but it's not specified as a protocol
715          that's valid for that dissector table.
716          Note, we don't exit here, but dissector_matching will remain NULL,
717          so we exit below */
718       if (proto_get_id_by_filter_name(dissector_str) == -1) {
719         /* No such protocol */
720         fprintf(stderr, "tethereal: Unknown protocol -- \"%s\"\n", dissector_str);
721       } else {
722         fprintf(stderr, "tethereal: Protocol \"%s\" isn't valid for layer type \"%s\"\n",
723                 dissector_str, table_name);
724       }
725     }
726   }
727
728   if (!dissector_matching) {
729     fprintf(stderr, "tethereal: Valid protocols for layer type \"%s\" are:\n", table_name);
730     fprint_all_protocols_for_layer_types(stderr, table_name);
731     g_free(decoded_param); 
732     return FALSE;
733   }
734
735 /* This is the end of the code that parses the command-line options.
736    All information is now stored in the variables:
737    table_name
738    selector
739    dissector_matching
740    The above variables that are strings are still pointing to areas within
741    decoded_parm.  decoded_parm thus still needs to be kept allocated in 
742    until we stop needing these variables
743    decoded_param will be deallocated at each exit point of this function */
744
745
746   /* We now have a pointer to the handle for the requested dissector
747      (requested protocol) inside the variable dissector_matching */
748   switch (dissector_table_selector_type) {
749
750   case FT_UINT8:
751   case FT_UINT16:
752   case FT_UINT24:
753   case FT_UINT32:
754     /* The selector for this table is an unsigned number. */
755     dissector_change(table_name, selector, dissector_matching);
756     break;
757
758   case FT_STRING:
759   case FT_STRINGZ:
760     /* The selector for this table is a string. */
761     dissector_change_string(table_name, selector_str, dissector_matching);
762     break;
763
764   default:
765     /* There are currently no dissector tables with any types other
766        than the ones listed above. */
767     g_assert_not_reached();
768   }
769   g_free(decoded_param); /* "Decode As" rule has been succesfully added */
770   return TRUE;
771 }
772
773 int
774 main(int argc, char *argv[])
775 {
776   int                  opt, i;
777   extern char         *optarg;
778   gboolean             arg_error = FALSE;
779
780 #ifdef _WIN32
781   WSADATA               wsaData;
782 #endif  /* _WIN32 */
783
784   char                *gpf_path, *pf_path;
785   char                *gdp_path, *dp_path;
786   int                  gpf_open_errno, gpf_read_errno;
787   int                  pf_open_errno, pf_read_errno;
788   int                  gdp_open_errno, gdp_read_errno;
789   int                  dp_open_errno, dp_read_errno;
790   int                  err;
791 #ifdef HAVE_LIBPCAP
792   gboolean             capture_filter_specified = FALSE;
793   GList               *if_list, *if_entry;
794   if_info_t           *if_info;
795   long                 adapter_index;
796   char                *p;
797   gchar                err_str[PCAP_ERRBUF_SIZE];
798 #else
799   gboolean             capture_option_specified = FALSE;
800 #endif
801   int                  out_file_type = WTAP_FILE_PCAP;
802   gchar               *cf_name = NULL, *rfilter = NULL;
803 #ifdef HAVE_LIBPCAP
804   gchar               *if_text;
805   GList               *lt_list, *lt_entry;
806   data_link_info_t    *data_link_info;
807 #endif
808 #ifdef HAVE_PCAP_OPEN_DEAD
809   struct bpf_program   fcode;
810 #endif
811   dfilter_t           *rfcode = NULL;
812   e_prefs             *prefs;
813   char                 badopt;
814   ethereal_tap_list *tli;
815
816   /* Register all dissectors; we must do this before checking for the
817      "-G" flag, as the "-G" flag dumps information registered by the
818      dissectors, and we must do it before we read the preferences, in
819      case any dissectors register preferences. */
820   epan_init(PLUGIN_DIR,register_all_protocols,register_all_protocol_handoffs);
821
822   /* Register all tap listeners; we do this before we parse the arguments,
823      as the "-z" argument can specify a registered tap. */
824   register_all_tap_listeners();
825
826   /* Now register the preferences for any non-dissector modules.
827      We must do that before we read the preferences as well. */
828   prefs_register_modules();
829
830   /* If invoked with the "-G" flag, we dump out information based on
831      the argument to the "-G" flag; if no argument is specified,
832      for backwards compatibility we dump out a glossary of display
833      filter symbols.
834
835      We do this here to mirror what happens in the GTK+ version, although
836      it's not necessary here. */
837   if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
838     if (argc == 2)
839       proto_registrar_dump_fields();
840     else {
841       if (strcmp(argv[2], "fields") == 0)
842         proto_registrar_dump_fields();
843       else if (strcmp(argv[2], "protocols") == 0)
844         proto_registrar_dump_protocols();
845       else {
846         fprintf(stderr, "tethereal: Invalid \"%s\" option for -G flag\n",
847                 argv[2]);
848         exit(1);
849       }
850     }
851     exit(0);
852   }
853
854   /* Set the C-language locale to the native environment. */
855   setlocale(LC_ALL, "");
856
857   prefs = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
858                      &pf_open_errno, &pf_read_errno, &pf_path);
859   if (gpf_path != NULL) {
860     if (gpf_open_errno != 0) {
861       fprintf(stderr, "Can't open global preferences file \"%s\": %s.\n",
862               pf_path, strerror(gpf_open_errno));
863     }
864     if (gpf_read_errno != 0) {
865       fprintf(stderr, "I/O error reading global preferences file \"%s\": %s.\n",
866               pf_path, strerror(gpf_read_errno));
867     }
868   }
869   if (pf_path != NULL) {
870     if (pf_open_errno != 0) {
871       fprintf(stderr, "Can't open your preferences file \"%s\": %s.\n", pf_path,
872               strerror(pf_open_errno));
873     }
874     if (pf_read_errno != 0) {
875       fprintf(stderr, "I/O error reading your preferences file \"%s\": %s.\n",
876               pf_path, strerror(pf_read_errno));
877     }
878     g_free(pf_path);
879     pf_path = NULL;
880   }
881
882   /* Set the name resolution code's flags from the preferences. */
883   g_resolv_flags = prefs->name_resolve;
884
885   /* Read the disabled protocols file. */
886   read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
887                             &dp_path, &dp_open_errno, &dp_read_errno);
888   if (gdp_path != NULL) {
889     if (gdp_open_errno != 0) {
890       fprintf(stderr,
891         "Could not open global disabled protocols file\n\"%s\": %s.\n",
892         gdp_path, strerror(gdp_open_errno));
893     }
894     if (gdp_read_errno != 0) {
895       fprintf(stderr,
896         "I/O error reading global disabled protocols file\n\"%s\": %s.\n",
897         gdp_path, strerror(gdp_read_errno));
898     }
899     g_free(gdp_path);
900   }
901   if (dp_path != NULL) {
902     if (dp_open_errno != 0) {
903       fprintf(stderr,
904         "Could not open your disabled protocols file\n\"%s\": %s.\n", dp_path,
905         strerror(dp_open_errno));
906     }
907     if (dp_read_errno != 0) {
908       fprintf(stderr,
909         "I/O error reading your disabled protocols file\n\"%s\": %s.\n", dp_path,
910         strerror(dp_read_errno));
911     }
912     g_free(dp_path);
913   }
914
915 #ifdef _WIN32
916   /* Load Wpcap, if possible */
917   load_wpcap();
918 #endif
919
920   init_cap_file(&cfile);
921
922   /* Assemble the compile-time version information string */
923   comp_info_str = g_string_new("Compiled ");
924   get_compiled_version_info(comp_info_str);
925
926   /* Assemble the run-time version information string */
927   runtime_info_str = g_string_new("Running ");
928   get_runtime_version_info(runtime_info_str);
929
930   /* Print format defaults to this. */
931   print_format = PR_FMT_TEXT;
932
933   /* Now get our args */
934   while ((opt = getopt(argc, argv, "a:b:c:d:Df:F:hi:lLnN:o:pqr:R:s:St:T:vw:Vxy:z:")) != -1) {
935     switch (opt) {
936       case 'a':        /* autostop criteria */
937 #ifdef HAVE_LIBPCAP
938         if (set_autostop_criterion(optarg) == FALSE) {
939           fprintf(stderr, "tethereal: Invalid or unknown -a flag \"%s\"\n", optarg);
940           exit(1);
941         }
942 #else
943         capture_option_specified = TRUE;
944         arg_error = TRUE;
945 #endif
946         break;
947       case 'b':        /* Ringbuffer option */
948 #ifdef HAVE_LIBPCAP
949         capture_opts.ringbuffer_on = TRUE;
950         if (get_ring_arguments(optarg) == FALSE) {
951           fprintf(stderr, "tethereal: Invalid or unknown -b arg \"%s\"\n", optarg);
952           exit(1);
953         }
954 #else
955         capture_option_specified = TRUE;
956         arg_error = TRUE;
957 #endif
958         break;
959       case 'c':        /* Capture xxx packets */
960 #ifdef HAVE_LIBPCAP
961         capture_opts.autostop_count =
962             get_positive_int(optarg, "packet count");
963 #else
964         capture_option_specified = TRUE;
965         arg_error = TRUE;
966 #endif
967         break;
968       case 'd':        /* Decode as rule */
969         if (!add_decode_as(optarg))
970           exit(1);
971         break;
972       case 'D':        /* Print a list of capture devices */
973 #ifdef HAVE_LIBPCAP
974         if_list = get_interface_list(&err, err_str);
975         if (if_list == NULL) {
976             switch (err) {
977
978             case CANT_GET_INTERFACE_LIST:
979                 fprintf(stderr, "tethereal: Can't get list of interfaces: %s\n",
980                         err_str);
981                 break;
982
983             case NO_INTERFACES_FOUND:
984                 fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
985                 break;
986             }
987             exit(2);
988         }
989         i = 1;  /* Interface id number */
990         for (if_entry = g_list_first(if_list); if_entry != NULL;
991                 if_entry = g_list_next(if_entry)) {
992           if_info = if_entry->data;
993           printf("%d. %s", i++, if_info->name);
994           if (if_info->description != NULL)
995             printf(" (%s)", if_info->description);
996           printf("\n");
997         }
998         free_interface_list(if_list);
999         exit(0);
1000 #else
1001         capture_option_specified = TRUE;
1002         arg_error = TRUE;
1003 #endif
1004         break;
1005       case 'f':
1006 #ifdef HAVE_LIBPCAP
1007         capture_filter_specified = TRUE;
1008         if (cfile.cfilter)
1009                 g_free(cfile.cfilter);
1010         cfile.cfilter = g_strdup(optarg);
1011 #else
1012         capture_option_specified = TRUE;
1013         arg_error = TRUE;
1014 #endif
1015         break;
1016       case 'F':
1017         out_file_type = wtap_short_string_to_file_type(optarg);
1018         if (out_file_type < 0) {
1019           fprintf(stderr, "tethereal: \"%s\" is not a valid capture file type\n",
1020                         optarg);
1021           exit(1);
1022         }
1023         break;
1024       case 'h':        /* Print help and exit */
1025         print_usage(TRUE);
1026         exit(0);
1027         break;
1028       case 'i':        /* Use interface xxx */
1029 #ifdef HAVE_LIBPCAP
1030         /*
1031          * If the argument is a number, treat it as an index into the list
1032          * of adapters, as printed by "tethereal -D".
1033          *
1034          * This should be OK on UNIX systems, as interfaces shouldn't have
1035          * names that begin with digits.  It can be useful on Windows, where
1036          * more than one interface can have the same name.
1037          */
1038         adapter_index = strtol(optarg, &p, 10);
1039         if (p != NULL && *p == '\0') {
1040           if (adapter_index < 0) {
1041             fprintf(stderr,
1042                 "tethereal: The specified adapter index is a negative number\n");
1043            exit(1);
1044           }
1045           if (adapter_index > INT_MAX) {
1046             fprintf(stderr,
1047                 "tethereal: The specified adapter index is too large (greater than %d)\n",
1048                 INT_MAX);
1049             exit(1);
1050           }
1051           if (adapter_index == 0) {
1052             fprintf(stderr, "tethereal: there is no interface with that adapter index\n");
1053             exit(1);
1054           }
1055           if_list = get_interface_list(&err, err_str);
1056           if (if_list == NULL) {
1057             switch (err) {
1058
1059             case CANT_GET_INTERFACE_LIST:
1060                 fprintf(stderr, "tethereal: Can't get list of interfaces: %s\n",
1061                         err_str);
1062                 break;
1063
1064             case NO_INTERFACES_FOUND:
1065                 fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
1066                 break;
1067             }
1068             exit(2);
1069           }
1070           if_info = g_list_nth_data(if_list, adapter_index - 1);
1071           if (if_info == NULL) {
1072             fprintf(stderr, "tethereal: there is no interface with that adapter index\n");
1073             exit(1);
1074           }
1075           cfile.iface = g_strdup(if_info->name);
1076           free_interface_list(if_list);
1077         } else
1078           cfile.iface = g_strdup(optarg);
1079 #else
1080         capture_option_specified = TRUE;
1081         arg_error = TRUE;
1082 #endif
1083         break;
1084       case 'l':        /* "Line-buffer" standard output */
1085         /* This isn't line-buffering, strictly speaking, it's just
1086            flushing the standard output after the information for
1087            each packet is printed; however, that should be good
1088            enough for all the purposes to which "-l" is put (and
1089            is probably actually better for "-V", as it does fewer
1090            writes).
1091
1092            See the comment in "wtap_dispatch_cb_print()" for an
1093            explanation of why we do that, and why we don't just
1094            use "setvbuf()" to make the standard output line-buffered
1095            (short version: in Windows, "line-buffered" is the same
1096            as "fully-buffered", and the output buffer is only flushed
1097            when it fills up). */
1098         line_buffered = TRUE;
1099         break;
1100       case 'L':        /* Print list of link-layer types and exit */
1101 #ifdef HAVE_LIBPCAP
1102         list_link_layer_types = TRUE;
1103         break;
1104 #else
1105         capture_option_specified = TRUE;
1106         arg_error = TRUE;
1107 #endif
1108         break;
1109       case 'n':        /* No name resolution */
1110         g_resolv_flags = RESOLV_NONE;
1111         break;
1112       case 'N':        /* Select what types of addresses/port #s to resolve */
1113         if (g_resolv_flags == RESOLV_ALL)
1114           g_resolv_flags = RESOLV_NONE;
1115         badopt = string_to_name_resolve(optarg, &g_resolv_flags);
1116         if (badopt != '\0') {
1117           fprintf(stderr, "tethereal: -N specifies unknown resolving option '%c'; valid options are 'm', 'n', and 't'\n",
1118                         badopt);
1119           exit(1);
1120         }
1121         break;
1122       case 'o':        /* Override preference from command line */
1123         switch (prefs_set_pref(optarg)) {
1124
1125         case PREFS_SET_SYNTAX_ERR:
1126           fprintf(stderr, "tethereal: Invalid -o flag \"%s\"\n", optarg);
1127           exit(1);
1128           break;
1129
1130         case PREFS_SET_NO_SUCH_PREF:
1131         case PREFS_SET_OBSOLETE:
1132           fprintf(stderr, "tethereal: -o flag \"%s\" specifies unknown preference\n",
1133                         optarg);
1134           exit(1);
1135           break;
1136         }
1137         break;
1138       case 'p':        /* Don't capture in promiscuous mode */
1139 #ifdef HAVE_LIBPCAP
1140         capture_opts.promisc_mode = FALSE;
1141 #else
1142         capture_option_specified = TRUE;
1143         arg_error = TRUE;
1144 #endif
1145         break;
1146       case 'q':        /* Quiet */
1147         quiet = TRUE;
1148         break;
1149       case 'r':        /* Read capture file xxx */
1150         cf_name = g_strdup(optarg);
1151         break;
1152       case 'R':        /* Read file filter */
1153         rfilter = optarg;
1154         break;
1155       case 's':        /* Set the snapshot (capture) length */
1156 #ifdef HAVE_LIBPCAP
1157         capture_opts.snaplen = get_positive_int(optarg, "snapshot length");
1158 #else
1159         capture_option_specified = TRUE;
1160         arg_error = TRUE;
1161 #endif
1162         break;
1163       case 'S':        /* show packets in real time */
1164         decode = TRUE;
1165         break;
1166       case 't':        /* Time stamp type */
1167         if (strcmp(optarg, "r") == 0)
1168           timestamp_type = RELATIVE;
1169         else if (strcmp(optarg, "a") == 0)
1170           timestamp_type = ABSOLUTE;
1171         else if (strcmp(optarg, "ad") == 0)
1172           timestamp_type = ABSOLUTE_WITH_DATE;
1173         else if (strcmp(optarg, "d") == 0)
1174           timestamp_type = DELTA;
1175         else {
1176           fprintf(stderr, "tethereal: Invalid time stamp type \"%s\"\n",
1177             optarg);
1178           fprintf(stderr, "It must be \"r\" for relative, \"a\" for absolute,\n");
1179           fprintf(stderr, "\"ad\" for absolute with date, or \"d\" for delta.\n");
1180           exit(1);
1181         }
1182         break;
1183       case 'T':        /* printing Type */
1184         if (strcmp(optarg, "text") == 0)
1185                 print_format = PR_FMT_TEXT;
1186         else if (strcmp(optarg, "pdml") == 0)
1187                 print_format = PR_FMT_PDML;
1188         else if (strcmp(optarg, "ps") == 0)
1189                 print_format = PR_FMT_PS;
1190         else {
1191                 fprintf(stderr, "tethereal: Invalid -T parameter.\n");
1192                 fprintf(stderr, "It must be \"ps\", \"text\" or \"pdml\".\n");
1193                 exit(1);
1194         }
1195         break;
1196       case 'v':        /* Show version and exit */
1197         printf("t%s %s\n%s\n%s\n", PACKAGE, VERSION, comp_info_str->str,
1198                runtime_info_str->str);
1199         exit(0);
1200         break;
1201       case 'w':        /* Write to capture file xxx */
1202         cfile.save_file = g_strdup(optarg);
1203         break;
1204       case 'V':        /* Verbose */
1205         verbose = TRUE;
1206         break;
1207       case 'x':        /* Print packet data in hex (and ASCII) */
1208         print_hex = TRUE;
1209         break;
1210       case 'y':        /* Set the pcap data link type */
1211 #ifdef HAVE_LIBPCAP
1212 #ifdef HAVE_PCAP_DATALINK_NAME_TO_VAL
1213         capture_opts.linktype = pcap_datalink_name_to_val(optarg);
1214         if (capture_opts.linktype == -1) {
1215           fprintf(stderr, "tethereal: The specified data link type \"%s\" is not valid\n",
1216                   optarg);
1217           exit(1);
1218         }
1219 #else /* HAVE_PCAP_DATALINK_NAME_TO_VAL */
1220         /* XXX - just treat it as a number */
1221         capture_opts.linktype = get_natural_int(optarg, "data link type");
1222 #endif /* HAVE_PCAP_DATALINK_NAME_TO_VAL */
1223 #else
1224         capture_option_specified = TRUE;
1225         arg_error = TRUE;
1226 #endif
1227         break;
1228       case 'z':
1229         for(tli=tap_list;tli;tli=tli->next){
1230           if(!strncmp(tli->cmd,optarg,strlen(tli->cmd))){
1231             (*tli->func)(optarg);
1232             break;
1233           }
1234         }
1235         if(!tli){
1236           fprintf(stderr,"tethereal: invalid -z argument.\n");
1237           fprintf(stderr,"  -z argument must be one of :\n");
1238           for(tli=tap_list;tli;tli=tli->next){
1239             fprintf(stderr,"     %s\n",tli->cmd);
1240           }
1241           exit(1);
1242         }
1243         break;
1244       default:
1245       case '?':        /* Bad flag - print usage message */
1246         arg_error = TRUE;
1247         break;
1248     }
1249   }
1250
1251   /* If printing PDML or PS, force -V */
1252   if (print_format == PR_FMT_PDML || print_format == PR_FMT_PS)
1253           verbose = TRUE;
1254
1255   /* If no capture filter or read filter has been specified, and there are
1256      still command-line arguments, treat them as the tokens of a capture
1257      filter (if no "-r" flag was specified) or a read filter (if a "-r"
1258      flag was specified. */
1259   if (optind < argc) {
1260     if (cf_name != NULL) {
1261       if (rfilter != NULL) {
1262         fprintf(stderr,
1263 "tethereal: Read filters were specified both with \"-R\" and with additional command-line arguments\n");
1264         exit(2);
1265       }
1266       rfilter = get_args_as_string(argc, argv, optind);
1267     } else {
1268 #ifdef HAVE_LIBPCAP
1269       if (capture_filter_specified) {
1270         fprintf(stderr,
1271 "tethereal: Capture filters were specified both with \"-f\" and with additional command-line arguments\n");
1272         exit(2);
1273       }
1274       cfile.cfilter = get_args_as_string(argc, argv, optind);
1275 #else
1276       capture_option_specified = TRUE;
1277 #endif
1278     }
1279   }
1280
1281   /* See if we're writing a capture file and the file is a pipe */
1282 #ifdef HAVE_LIBPCAP
1283   ld.output_to_pipe = FALSE;
1284 #endif
1285   if (cfile.save_file != NULL) {
1286     if (strcmp(cfile.save_file, "-") == 0) {
1287       /* stdout */
1288       g_free(cfile.save_file);
1289       cfile.save_file = g_strdup("");
1290 #ifdef HAVE_LIBPCAP
1291       ld.output_to_pipe = TRUE;
1292 #endif
1293     }
1294 #ifdef HAVE_LIBPCAP
1295     else {
1296       err = test_for_fifo(cfile.save_file);
1297       switch (err) {
1298
1299       case ENOENT:      /* it doesn't exist, so we'll be creating it,
1300                            and it won't be a FIFO */
1301       case 0:           /* found it, but it's not a FIFO */
1302         break;
1303
1304       case ESPIPE:      /* it is a FIFO */
1305         ld.output_to_pipe = TRUE;
1306         break;
1307
1308       default:          /* couldn't stat it */
1309         fprintf(stderr,
1310                 "tethereal: Error testing whether capture file is a pipe: %s\n",
1311                 strerror(errno));
1312         exit(2);
1313       }
1314     }
1315 #endif
1316   }
1317
1318 #ifndef HAVE_LIBPCAP
1319   if (capture_option_specified)
1320     fprintf(stderr, "This version of Tethereal was not built with support for capturing packets.\n");
1321 #endif
1322   if (arg_error) {
1323     print_usage(FALSE);
1324     exit(1);
1325   }
1326
1327 #ifdef HAVE_LIBPCAP
1328   if (list_link_layer_types) {
1329     /* We're supposed to list the link-layer types for an interface;
1330        did the user also specify a capture file to be read? */
1331     if (cf_name) {
1332       /* Yes - that's bogus. */
1333       fprintf(stderr, "tethereal: You cannot specify -L and a capture file to be read.\n");
1334       exit(1);
1335     }
1336     /* No - did they specify a ring buffer option? */
1337     if (capture_opts.ringbuffer_on) {
1338       fprintf(stderr, "tethereal: Ring buffer requested, but a capture is not being done.\n");
1339       exit(1);
1340     }
1341   } else {
1342     /* If they didn't specify a "-w" flag, but specified a maximum capture
1343        file size, tell them that this doesn't work, and exit. */
1344     if (capture_opts.has_autostop_filesize && cfile.save_file == NULL) {
1345       fprintf(stderr, "tethereal: Maximum capture file size specified, but "
1346         "capture isn't being saved to a file.\n");
1347       exit(1);
1348     }
1349
1350     if (capture_opts.ringbuffer_on) {
1351       /* Ring buffer works only under certain conditions:
1352          a) ring buffer does not work if you're not saving the capture to
1353             a file;
1354          b) ring buffer only works if you're saving in libpcap format;
1355          c) it makes no sense to enable the ring buffer if the maximum
1356             file size is set to "infinite";
1357          d) file must not be a pipe. */
1358       if (cfile.save_file == NULL) {
1359         fprintf(stderr, "tethereal: Ring buffer requested, but "
1360           "capture isn't being saved to a file.\n");
1361         exit(1);
1362       }
1363       if (out_file_type != WTAP_FILE_PCAP) {
1364         fprintf(stderr, "tethereal: Ring buffer requested, but "
1365           "capture isn't being saved in libpcap format.\n");
1366         exit(2);
1367       }
1368       if (!capture_opts.has_autostop_filesize) {
1369         fprintf(stderr, "tethereal: Ring buffer requested, but "
1370           "no maximum capture file size was specified.\n");
1371         exit(2);
1372       }
1373       if (ld.output_to_pipe) {
1374         fprintf(stderr, "tethereal: Ring buffer requested, but "
1375           "capture file is a pipe.\n");
1376         exit(2);
1377       }
1378     }
1379   }
1380 #endif
1381
1382 #ifdef _WIN32
1383   /* Start windows sockets */
1384   WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1385 #endif  /* _WIN32 */
1386
1387   /* Notify all registered modules that have had any of their preferences
1388      changed either from one of the preferences file or from the command
1389      line that their preferences have changed. */
1390   prefs_apply_all();
1391
1392   /* disabled protocols as per configuration file */
1393   if (gdp_path == NULL && dp_path == NULL) {
1394     set_disabled_protos_list();
1395   }
1396
1397   /* Build the column format array */
1398   col_setup(&cfile.cinfo, prefs->num_cols);
1399   for (i = 0; i < cfile.cinfo.num_cols; i++) {
1400     cfile.cinfo.col_fmt[i] = get_column_format(i);
1401     cfile.cinfo.col_title[i] = g_strdup(get_column_title(i));
1402     cfile.cinfo.fmt_matx[i] = (gboolean *) g_malloc0(sizeof(gboolean) *
1403       NUM_COL_FMTS);
1404     get_column_format_matches(cfile.cinfo.fmt_matx[i], cfile.cinfo.col_fmt[i]);
1405     cfile.cinfo.col_data[i] = NULL;
1406     if (cfile.cinfo.col_fmt[i] == COL_INFO)
1407       cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_INFO_LEN);
1408     else
1409       cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1410     cfile.cinfo.col_fence[i] = 0;
1411     cfile.cinfo.col_expr[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1412     cfile.cinfo.col_expr_val[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1413   }
1414
1415   for (i = 0; i < cfile.cinfo.num_cols; i++) {
1416       int j;
1417
1418       for (j = 0; j < NUM_COL_FMTS; j++) {
1419          if (!cfile.cinfo.fmt_matx[i][j])
1420              continue;
1421          
1422          if (cfile.cinfo.col_first[j] == -1)
1423              cfile.cinfo.col_first[j] = i;
1424          cfile.cinfo.col_last[j] = i;
1425       }
1426   }
1427
1428 #ifdef HAVE_LIBPCAP
1429   if (capture_opts.snaplen < 1)
1430     capture_opts.snaplen = WTAP_MAX_PACKET_SIZE;
1431   else if (capture_opts.snaplen < MIN_PACKET_SIZE)
1432     capture_opts.snaplen = MIN_PACKET_SIZE;
1433
1434   /* Check the value range of the ringbuffer_num_files parameter */
1435   if (capture_opts.ringbuffer_num_files > RINGBUFFER_MAX_NUM_FILES)
1436     capture_opts.ringbuffer_num_files = RINGBUFFER_MAX_NUM_FILES;
1437 #if RINGBUFFER_MIN_NUM_FILES > 0
1438   else if (capture_opts.ringbuffer_num_files < RINGBUFFER_MIN_NUM_FILES)
1439     capture_opts.ringbuffer_num_files = RINGBUFFER_MIN_NUM_FILES;
1440 #endif
1441 #endif
1442
1443   if (rfilter != NULL) {
1444     if (!dfilter_compile(rfilter, &rfcode)) {
1445       fprintf(stderr, "tethereal: %s\n", dfilter_error_msg);
1446       epan_cleanup();
1447 #ifdef HAVE_PCAP_OPEN_DEAD
1448       {
1449         pcap_t *p;
1450
1451         p = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1452         if (p != NULL) {
1453           if (pcap_compile(p, &fcode, rfilter, 0, 0) != -1) {
1454             fprintf(stderr,
1455               "  Note: That display filter code looks like a valid capture filter;\n"
1456               "        maybe you mixed them up?\n");
1457           }
1458           pcap_close(p);
1459         }
1460       }
1461 #endif
1462       exit(2);
1463     }
1464   }
1465   cfile.rfcode = rfcode;
1466   if (cf_name) {
1467     /*
1468      * We're reading a capture file.
1469      */
1470
1471 #ifndef _WIN32
1472     /*
1473      * Immediately relinquish any set-UID or set-GID privileges we have;
1474      * we must not be allowed to read any capture files the user running
1475      * Tethereal can't open.
1476      */
1477     setuid(getuid());
1478     setgid(getgid());
1479 #endif
1480
1481     err = cf_open(cf_name, FALSE, &cfile);
1482     if (err != 0) {
1483       epan_cleanup();
1484       exit(2);
1485     }
1486     err = load_cap_file(&cfile, out_file_type);
1487     if (err != 0) {
1488       epan_cleanup();
1489       exit(2);
1490     }
1491     cf_name[0] = '\0';
1492   } else {
1493     /* No capture file specified, so we're supposed to do a live capture
1494        (or get a list of link-layer types for a live capture device);
1495        do we have support for live captures? */
1496 #ifdef HAVE_LIBPCAP
1497
1498 #ifdef _WIN32
1499     if (!has_wpcap) {
1500         fprintf(stderr, "tethereal: Could not load wpcap.dll.\n");
1501         exit(2);
1502     }
1503 #endif
1504
1505     /* Yes; did the user specify an interface to use? */
1506     if (cfile.iface == NULL) {
1507         /* No - is a default specified in the preferences file? */
1508         if (prefs->capture_device != NULL) {
1509             /* Yes - use it. */
1510             if_text = strrchr(prefs->capture_device, ' ');
1511             if (if_text == NULL) {
1512                 cfile.iface = g_strdup(prefs->capture_device);
1513             } else {
1514                 cfile.iface = g_strdup(if_text + 1); /* Skip over space */
1515             }
1516         } else {
1517             /* No - pick the first one from the list of interfaces. */
1518             if_list = get_interface_list(&err, err_str);
1519             if (if_list == NULL) {
1520                 switch (err) {
1521
1522                 case CANT_GET_INTERFACE_LIST:
1523                     fprintf(stderr, "tethereal: Can't get list of interfaces: %s\n",
1524                             err_str);
1525                     break;
1526
1527                 case NO_INTERFACES_FOUND:
1528                     fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
1529                     break;
1530                 }
1531                 exit(2);
1532             }
1533             if_info = if_list->data;    /* first interface */
1534             cfile.iface = g_strdup(if_info->name);
1535             free_interface_list(if_list);
1536         }
1537     }
1538
1539     if (list_link_layer_types) {
1540       /* We were asked to list the link-layer types for an interface.
1541          Get the list of link-layer types for the capture device. */
1542       lt_list = get_pcap_linktype_list(cfile.iface, err_str);
1543       if (lt_list == NULL) {
1544         if (err_str[0] != '\0') {
1545           fprintf(stderr, "tethereal: The list of data link types for the capture device could not be obtained (%s).\n"
1546             "Please check to make sure you have sufficient permissions, and that\n"
1547             "you have the proper interface or pipe specified.\n", err_str);
1548         } else
1549           fprintf(stderr, "tethereal: The capture device has no data link types.\n");
1550         exit(2);
1551       }
1552       fprintf(stderr, "Data link types (use option -y to set):\n");
1553       for (lt_entry = lt_list; lt_entry != NULL;
1554            lt_entry = g_list_next(lt_entry)) {
1555         data_link_info = lt_entry->data;
1556         fprintf(stderr, "  %s", data_link_info->name);
1557         if (data_link_info->description != NULL)
1558           fprintf(stderr, " (%s)", data_link_info->description);
1559         else
1560           fprintf(stderr, " (not supported)");
1561         putchar('\n');
1562       }
1563       free_pcap_linktype_list(lt_list);
1564       exit(0);
1565     }
1566
1567     capture(out_file_type);
1568
1569     if (capture_opts.ringbuffer_on) {
1570       ringbuf_free();
1571     }
1572 #else
1573     /* No - complain. */
1574     fprintf(stderr, "This version of Tethereal was not built with support for capturing packets.\n");
1575     exit(2);
1576 #endif
1577   }
1578
1579   draw_tap_listeners(TRUE);
1580   epan_cleanup();
1581
1582   return 0;
1583 }
1584
1585 #ifdef HAVE_LIBPCAP
1586 /* Do the low-level work of a capture.
1587    Returns TRUE if it succeeds, FALSE otherwise. */
1588
1589 static condition  *volatile cnd_ring_timeout = NULL; /* this must be visible in wtap_dispatch_cb_write */
1590
1591 static int
1592 capture(int out_file_type)
1593 {
1594   int         pcap_encap;
1595   int         file_snaplen;
1596   gchar       open_err_str[PCAP_ERRBUF_SIZE];
1597   gchar       lookup_net_err_str[PCAP_ERRBUF_SIZE];
1598   bpf_u_int32 netnum, netmask;
1599   struct bpf_program fcode;
1600   const char *set_linktype_err_str;
1601   int         err = 0;
1602   int         volatile volatile_err = 0;
1603   int         volatile inpkts = 0;
1604   int         pcap_cnt;
1605   char        errmsg[1024+1];
1606   condition  *volatile cnd_stop_capturesize = NULL;
1607   condition  *volatile cnd_stop_timeout = NULL;
1608 #ifndef _WIN32
1609   void        (*oldhandler)(int);
1610   static const char ppamsg[] = "can't find PPA for ";
1611   char       *libpcap_warn;
1612   volatile int pipe_fd = -1;
1613   struct pcap_hdr hdr;
1614   struct pcaprec_modified_hdr rechdr;
1615   guchar pcap_data[WTAP_MAX_PACKET_SIZE];
1616 #endif
1617   struct pcap_stat stats;
1618   gboolean    write_err;
1619   gboolean    dump_ok;
1620   dfilter_t   *rfcode = NULL;
1621
1622   /* Initialize all data structures used for dissection. */
1623   init_dissection();
1624
1625   ld.linktype       = WTAP_ENCAP_UNKNOWN;
1626   ld.pdh            = NULL;
1627
1628   /* Open the network interface to capture from it.
1629      Some versions of libpcap may put warnings into the error buffer
1630      if they succeed; to tell if that's happened, we have to clear
1631      the error buffer, and check if it's still a null string.  */
1632   open_err_str[0] = '\0';
1633   ld.pch = pcap_open_live(cfile.iface, capture_opts.snaplen,
1634                           capture_opts.promisc_mode, 1000, open_err_str);
1635
1636   if (ld.pch != NULL) {
1637     /* setting the data link type only works on real interfaces */
1638     if (capture_opts.linktype != -1) {
1639       set_linktype_err_str = set_pcap_linktype(ld.pch, cfile.iface,
1640         capture_opts.linktype);
1641       if (set_linktype_err_str != NULL) {
1642         snprintf(errmsg, sizeof errmsg, "Unable to set data link type (%s).",
1643           set_linktype_err_str);
1644         goto error;
1645       }
1646     }
1647   } else {
1648     /* We couldn't open "cfile.iface" as a network device. */
1649 #ifdef _WIN32
1650     /* On Windows, we don't support capturing on pipes, so we give up. */
1651
1652     /* On Win32 OSes, the capture devices are probably available to all
1653        users; don't warn about permissions problems.
1654
1655        Do, however, warn that WAN devices aren't supported. */
1656     snprintf(errmsg, sizeof errmsg,
1657         "The capture session could not be initiated (%s).\n"
1658         "Please check that you have the proper interface specified.\n"
1659         "\n"
1660         "Note that the driver Tethereal uses for packet capture on Windows doesn't\n"
1661         "support capturing on PPP/WAN interfaces in Windows NT/2000/XP/.NET Server.\n",
1662         open_err_str);
1663     goto error;
1664 #else
1665     /* try to open cfile.iface as a pipe */
1666     pipe_fd = pipe_open_live(cfile.iface, &hdr, &ld, errmsg, sizeof errmsg);
1667
1668     if (pipe_fd == -1) {
1669
1670       if (ld.pipe_err == PIPNEXIST) {
1671         /* Pipe doesn't exist, so output message for interface */
1672
1673         /* If we got a "can't find PPA for XXX" message, warn the user (who
1674            is running Tethereal on HP-UX) that they don't have a version
1675            of libpcap that properly handles HP-UX (libpcap 0.6.x and later
1676            versions, which properly handle HP-UX, say "can't find /dev/dlpi
1677            PPA for XXX" rather than "can't find PPA for XXX"). */
1678         if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
1679           libpcap_warn =
1680             "\n\n"
1681             "You are running Tethereal with a version of the libpcap library\n"
1682             "that doesn't handle HP-UX network devices well; this means that\n"
1683             "Tethereal may not be able to capture packets.\n"
1684             "\n"
1685             "To fix this, you should install libpcap 0.6.2, or a later version\n"
1686             "of libpcap, rather than libpcap 0.4 or 0.5.x.  It is available in\n"
1687             "packaged binary form from the Software Porting And Archive Centre\n"
1688             "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
1689             "at the URL lists a number of mirror sites.";
1690         else
1691           libpcap_warn = "";
1692         snprintf(errmsg, sizeof errmsg,
1693           "The capture session could not be initiated (%s).\n"
1694           "Please check to make sure you have sufficient permissions, and that\n"
1695           "you have the proper interface or pipe specified.%s", open_err_str,
1696           libpcap_warn);
1697       }
1698       /*
1699        * Else pipe (or file) does exist and pipe_open_live() has
1700        * filled in errmsg
1701        */
1702       goto error;
1703     } else
1704       /* pipe_open_live() succeeded; don't want
1705          error message from pcap_open_live() */
1706       open_err_str[0] = '\0';
1707 #endif
1708   }
1709
1710 #ifndef _WIN32
1711   /*
1712    * We've opened the capture device, so, if we're set-UID or set-GID,
1713    * relinquish those privileges.
1714    *
1715    * XXX - if we have saved set-user-ID support, we should give up those
1716    * privileges immediately, and then reclaim them long enough to get
1717    * a list of network interfaces and to open one, and then give them
1718    * up again, so that stuff we do while processing the argument list,
1719    * reading the user's preferences, etc. is done as the real user and
1720    * group, not the effective user and group.
1721    */
1722   setuid(getuid());
1723   setgid(getgid());
1724 #endif
1725
1726   if (cfile.cfilter && !ld.from_pipe) {
1727     /* A capture filter was specified; set it up. */
1728     if (pcap_lookupnet(cfile.iface, &netnum, &netmask, lookup_net_err_str) < 0) {
1729       /*
1730        * Well, we can't get the netmask for this interface; it's used
1731        * only for filters that check for broadcast IP addresses, so
1732        * we just warn the user, and punt and use 0.
1733        */
1734       fprintf(stderr,
1735         "Warning:  Couldn't obtain netmask info (%s).\n", lookup_net_err_str);
1736       netmask = 0;
1737     }
1738     if (pcap_compile(ld.pch, &fcode, cfile.cfilter, 1, netmask) < 0) {
1739       if (dfilter_compile(cfile.cfilter, &rfcode)) {
1740         snprintf(errmsg, sizeof errmsg,
1741           "Unable to parse capture filter string (%s).\n"
1742           "  Interestingly enough, this looks like a valid display filter\n"
1743           "  Are you sure you didn't mix them up?",
1744           pcap_geterr(ld.pch));
1745       } else {
1746         snprintf(errmsg, sizeof errmsg,
1747           "Unable to parse capture filter string (%s).",
1748           pcap_geterr(ld.pch));
1749       }
1750       goto error;
1751     }
1752     if (pcap_setfilter(ld.pch, &fcode) < 0) {
1753       snprintf(errmsg, sizeof errmsg, "Can't install filter (%s).",
1754         pcap_geterr(ld.pch));
1755       goto error;
1756     }
1757   }
1758
1759   /* Set up to write to the capture file. */
1760 #ifndef _WIN32
1761   if (ld.from_pipe) {
1762     pcap_encap = hdr.network;
1763     file_snaplen = hdr.snaplen;
1764   } else
1765 #endif
1766   {
1767     pcap_encap = get_pcap_linktype(ld.pch, cfile.iface);
1768     file_snaplen = pcap_snapshot(ld.pch);
1769   }
1770   ld.linktype = wtap_pcap_encap_to_wtap_encap(pcap_encap);
1771   if (cfile.save_file != NULL) {
1772     /* Set up to write to the capture file. */
1773     if (ld.linktype == WTAP_ENCAP_UNKNOWN) {
1774       strcpy(errmsg, "The network you're capturing from is of a type"
1775                " that Tethereal doesn't support.");
1776       goto error;
1777     }
1778     if (capture_opts.ringbuffer_on) {
1779       cfile.save_file_fd = ringbuf_init(cfile.save_file,
1780         capture_opts.ringbuffer_num_files);
1781       if (cfile.save_file_fd != -1) {
1782         ld.pdh = ringbuf_init_wtap_dump_fdopen(out_file_type, ld.linktype,
1783           pcap_snapshot(ld.pch), &err);
1784       } else {
1785         err = errno;    /* "ringbuf_init()" failed */
1786         ld.pdh = NULL;
1787       }
1788     } else {
1789       ld.pdh = wtap_dump_open(cfile.save_file, out_file_type,
1790                  ld.linktype, pcap_snapshot(ld.pch), &err);
1791     }
1792
1793     if (ld.pdh == NULL) {
1794       snprintf(errmsg, sizeof errmsg,
1795                file_open_error_message(err, TRUE, out_file_type),
1796                *cfile.save_file == '\0' ? "stdout" : cfile.save_file);
1797       goto error;
1798     }
1799   }
1800
1801   /* Does "open_err_str" contain a non-empty string?  If so, "pcap_open_live()"
1802      returned a warning; print it, but keep capturing. */
1803   if (open_err_str[0] != '\0')
1804     fprintf(stderr, "tethereal: WARNING: %s.\n", open_err_str);
1805
1806 #ifdef _WIN32
1807   /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1808   SetConsoleCtrlHandler(capture_cleanup, TRUE);
1809 #else /* _WIN32 */
1810   /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
1811      and exit.
1812      XXX - deal with signal semantics on various UNIX platforms.  Or just
1813      use "sigaction()" and be done with it? */
1814   signal(SIGTERM, capture_cleanup);
1815   signal(SIGINT, capture_cleanup);
1816   if ((oldhandler = signal(SIGHUP, capture_cleanup)) != SIG_DFL)
1817     signal(SIGHUP, oldhandler);
1818
1819 #ifdef SIGINFO
1820   /* Catch SIGINFO and, if we get it and we're capturing to a file in
1821      quiet mode, report the number of packets we've captured. */
1822   signal(SIGINFO, report_counts_siginfo);
1823 #endif /* SIGINFO */
1824 #endif /* _WIN32 */
1825
1826   /* Let the user know what interface was chosen. */
1827   fprintf(stderr, "Capturing on %s\n", cfile.iface);
1828
1829   /* initialize capture stop conditions */
1830   init_capture_stop_conditions();
1831   /* create stop conditions */
1832   if (capture_opts.has_autostop_filesize)
1833     cnd_stop_capturesize = cnd_new((const char*)CND_CLASS_CAPTURESIZE,
1834                                    (long)capture_opts.autostop_filesize * 1000);
1835   if (capture_opts.has_autostop_duration)
1836     cnd_stop_timeout = cnd_new((const char*)CND_CLASS_TIMEOUT,
1837                                (gint32)capture_opts.autostop_duration);
1838
1839   if (capture_opts.ringbuffer_on && capture_opts.has_ring_duration)
1840     cnd_ring_timeout = cnd_new(CND_CLASS_TIMEOUT, 
1841                                capture_opts.ringbuffer_duration);
1842
1843   if (!setjmp(ld.stopenv)) {
1844     ld.go = TRUE;
1845     ld.packet_count = 0;
1846   } else
1847     ld.go = FALSE;
1848   while (ld.go) {
1849     /* We need to be careful with automatic variables defined in the
1850        outer scope which are changed inside the loop.  Most compilers
1851        don't try to roll them back to their original values after the
1852        longjmp which causes the loop to finish, but all that the
1853        standards say is that their values are indeterminate.  If we
1854        don't want them to be rolled back, we should define them with the
1855        volatile attribute (paraphrasing W. Richard Stevens, Advanced
1856        Programming in the UNIX Environment, p. 178).
1857
1858        The "err" variable causes a particular problem.  If we give it
1859        the volatile attribute, then when we pass a reference to it (as
1860        in "&err") to a function, GCC warns: "passing arg <n> of
1861        <function> discards qualifiers from pointer target type".
1862        Therefore within the loop and just beyond we don't use "err".
1863        Within the loop we define "loop_err", and assign its value to
1864        "volatile_err", which is in the outer scope and is checked when
1865        the loop finishes.
1866
1867        We also define "packet_count_prev" here to keep things tidy,
1868        since it's used only inside the loop.  If it were defined in the
1869        outer scope, GCC would give a warning (unnecessary in this case)
1870        that it might be clobbered, and we'd need to give it the volatile
1871        attribute to suppress the warning. */
1872
1873     int loop_err = 0;
1874     int packet_count_prev = 0;
1875
1876     if (cnd_stop_capturesize == NULL && cnd_stop_timeout == NULL) {
1877       /* We're not stopping at a particular capture file size, and we're
1878          not stopping after some particular amount of time has expired,
1879          so either we have no stop condition or the only stop condition
1880          is a maximum packet count.
1881
1882          If there's no maximum packet count, pass it -1, meaning "until
1883          you run out of packets in the bufferful you read".  Otherwise,
1884          pass it the number of packets we have left to capture.
1885
1886          We don't call "pcap_loop()" as, if we're saving to a file that's
1887          a FIFO, we want to flush the FIFO after we're done processing
1888          this libpcap bufferful of packets, so that the program
1889          reading the FIFO sees the packets immediately and doesn't get
1890          any partial packet, forcing it to block in the middle of reading
1891          that packet. */
1892       if (capture_opts.autostop_count == 0)
1893         pcap_cnt = -1;
1894       else {
1895         if (ld.packet_count >= capture_opts.autostop_count) {
1896           /* XXX do we need this test here? */
1897           /* It appears there's nothing more to capture. */
1898           break;
1899         }
1900         pcap_cnt = capture_opts.autostop_count - ld.packet_count;
1901       }
1902     } else {
1903       /* We need to check the capture file size or the timeout after
1904          each packet. */
1905       pcap_cnt = 1;
1906     }
1907 #ifndef _WIN32
1908     if (ld.from_pipe) {
1909       inpkts = pipe_dispatch(pipe_fd, &ld, &hdr, &rechdr, pcap_data,
1910         errmsg, sizeof errmsg);
1911     } else
1912 #endif
1913       inpkts = pcap_dispatch(ld.pch, pcap_cnt, capture_pcap_cb, (guchar *) &ld);
1914     if (inpkts < 0) {
1915       /* Error from "pcap_dispatch()", or error or "no more packets" from
1916          "pipe_dispatch(). */
1917       ld.go = FALSE;
1918     } else if (cnd_stop_timeout != NULL && cnd_eval(cnd_stop_timeout)) {
1919       /* The specified capture time has elapsed; stop the capture. */
1920       ld.go = FALSE;
1921     } else if (inpkts > 0) {
1922       if (capture_opts.autostop_count != 0 &&
1923                  ld.packet_count >= capture_opts.autostop_count) {
1924         /* The specified number of packets have been captured and have
1925            passed both any capture filter in effect and any read filter
1926            in effect. */
1927         ld.go = FALSE;
1928       } else if (cnd_stop_capturesize != NULL &&
1929                     cnd_eval(cnd_stop_capturesize,
1930                               (guint32)wtap_get_bytes_dumped(ld.pdh))) {
1931         /* We're saving the capture to a file, and the capture file reached
1932            its maximum size. */
1933         if (capture_opts.ringbuffer_on) {
1934           /* Switch to the next ringbuffer file */
1935           if (ringbuf_switch_file(&cfile, &ld.pdh, &loop_err)) {
1936             /* File switch succeeded: reset the condition */
1937             cnd_reset(cnd_stop_capturesize);
1938             if (cnd_ring_timeout) {
1939               cnd_reset(cnd_ring_timeout);
1940             }
1941           } else {
1942             /* File switch failed: stop here */
1943             volatile_err = loop_err;
1944             ld.go = FALSE;
1945           }
1946         } else {
1947           /* No ringbuffer - just stop. */
1948           ld.go = FALSE;
1949         }
1950       }
1951       if (ld.output_to_pipe) {
1952         if (ld.packet_count > packet_count_prev) {
1953           if (fflush(wtap_dump_file(ld.pdh))) {
1954             volatile_err = errno;
1955             ld.go = FALSE;
1956           }
1957           packet_count_prev = ld.packet_count;
1958         }
1959       }
1960     } /* inpkts > 0 */
1961   } /* while (ld.go) */
1962
1963   /* delete stop conditions */
1964   if (cnd_stop_capturesize != NULL)
1965     cnd_delete(cnd_stop_capturesize);
1966   if (cnd_stop_timeout != NULL)
1967     cnd_delete(cnd_stop_timeout);
1968   if (cnd_ring_timeout != NULL)
1969     cnd_delete(cnd_ring_timeout);
1970
1971   if ((cfile.save_file != NULL) && !quiet) {
1972     /* We're saving to a file, which means we're printing packet counts
1973        to stderr if we are not running silent and deep.
1974        Send a newline so that we move to the line after the packet count. */
1975     fprintf(stderr, "\n");
1976   }
1977
1978   /* If we got an error while capturing, report it. */
1979   if (inpkts < 0) {
1980 #ifndef _WIN32
1981     if (ld.from_pipe) {
1982       if (ld.pipe_err == PIPERR) {
1983         fprintf(stderr, "tethereal: Error while capturing packets: %s\n",
1984           errmsg);
1985       }
1986     } else
1987 #endif
1988     {
1989       fprintf(stderr, "tethereal: Error while capturing packets: %s\n",
1990           pcap_geterr(ld.pch));
1991     }
1992   }
1993
1994   if (volatile_err == 0)
1995     write_err = FALSE;
1996   else {
1997     show_capture_file_io_error(cfile.save_file, volatile_err, FALSE);
1998     write_err = TRUE;
1999   }
2000
2001   if (cfile.save_file != NULL) {
2002     /* We're saving to a file or files; close all files. */
2003     if (capture_opts.ringbuffer_on) {
2004       dump_ok = ringbuf_wtap_dump_close(&cfile, &err);
2005     } else {
2006       dump_ok = wtap_dump_close(ld.pdh, &err);
2007     }
2008     /* If we've displayed a message about a write error, there's no point
2009        in displaying another message about an error on close. */
2010     if (!dump_ok && !write_err)
2011       show_capture_file_io_error(cfile.save_file, err, TRUE);
2012   }
2013
2014 #ifndef _WIN32
2015   if (ld.from_pipe && pipe_fd >= 0)
2016     close(pipe_fd);
2017   else
2018 #endif
2019   {
2020     /* Get the capture statistics, and, if any packets were dropped, report
2021        that. */
2022     if (pcap_stats(ld.pch, &stats) >= 0) {
2023       if (stats.ps_drop != 0) {
2024         fprintf(stderr, "%u packets dropped\n", stats.ps_drop);
2025       }
2026     } else {
2027       fprintf(stderr, "tethereal: Can't get packet-drop statistics: %s\n",
2028           pcap_geterr(ld.pch));
2029     }
2030     pcap_close(ld.pch);
2031   }
2032
2033   /* Report the number of captured packets if not reported during capture
2034      and we are saving to a file. */
2035   report_counts();
2036
2037   return TRUE;
2038
2039 error:
2040   if (capture_opts.ringbuffer_on) {
2041     ringbuf_error_cleanup();
2042   }
2043   g_free(cfile.save_file);
2044   cfile.save_file = NULL;
2045   fprintf(stderr, "tethereal: %s\n", errmsg);
2046 #ifndef _WIN32
2047   if (ld.from_pipe) {
2048     if (pipe_fd >= 0)
2049       close(pipe_fd);
2050   } else
2051 #endif
2052   {
2053   if (ld.pch != NULL)
2054     pcap_close(ld.pch);
2055   }
2056
2057   return FALSE;
2058 }
2059
2060 static void
2061 capture_pcap_cb(guchar *user, const struct pcap_pkthdr *phdr,
2062   const guchar *pd)
2063 {
2064   struct wtap_pkthdr whdr;
2065   union wtap_pseudo_header pseudo_header;
2066   loop_data *ld = (loop_data *) user;
2067   cb_args_t args;
2068   int err;
2069
2070   /* Convert from libpcap to Wiretap format.
2071      If that fails, ignore the packet (wtap_process_pcap_packet has
2072      written an error message). */
2073   pd = wtap_process_pcap_packet(ld->linktype, phdr, pd, &pseudo_header,
2074                                 &whdr, &err);
2075   if (pd == NULL) {
2076     return;
2077   }
2078
2079   args.cf = &cfile;
2080   args.pdh = ld->pdh;
2081   if (ld->pdh) {
2082     wtap_dispatch_cb_write((guchar *)&args, &whdr, 0, &pseudo_header, pd);
2083     /* Report packet capture count if not quiet */
2084     if (!quiet) {
2085       if (!decode) {
2086          if (ld->packet_count != 0) {
2087            fprintf(stderr, "\r%u ", ld->packet_count);
2088            /* stderr could be line buffered */
2089            fflush(stderr);
2090          }
2091       } else {
2092            wtap_dispatch_cb_print((guchar *)&args, &whdr, 0,
2093                                   &pseudo_header, pd);
2094       }
2095     }
2096   } else {
2097     wtap_dispatch_cb_print((guchar *)&args, &whdr, 0, &pseudo_header, pd);
2098   }
2099 }
2100
2101 #ifdef _WIN32
2102 static BOOL WINAPI
2103 capture_cleanup(DWORD ctrltype _U_)
2104 {
2105   /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
2106      Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
2107      is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
2108      like SIGTERM at least when the machine's shutting down.
2109
2110      For now, we handle them all as indications that we should clean up
2111      and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
2112      way on UNIX.
2113
2114      However, as handlers run in a new thread, we can't just longjmp
2115      out; we have to set "ld.go" to FALSE, and must return TRUE so that
2116      no other handler - such as one that would terminate the process -
2117      gets called.
2118
2119      XXX - for some reason, typing ^C to Tethereal, if you run this in
2120      a Cygwin console window in at least some versions of Cygwin,
2121      causes Tethereal to terminate immediately; this routine gets
2122      called, but the main loop doesn't get a chance to run and
2123      exit cleanly, at least if this is compiled with Microsoft Visual
2124      C++ (i.e., it's a property of the Cygwin console window or Bash;
2125      it happens if Tethereal is not built with Cygwin - for all I know,
2126      building it with Cygwin may make the problem go away). */
2127   ld.go = FALSE;
2128   return TRUE;
2129 }
2130 #else
2131 static void
2132 capture_cleanup(int signum _U_)
2133 {
2134   /* Longjmp back to the starting point; "pcap_dispatch()", on many
2135      UNIX platforms, just keeps looping if it gets EINTR, so if we set
2136      "ld.go" to FALSE and return, we won't break out of it and quit
2137      capturing. */
2138   longjmp(ld.stopenv, 1);
2139 }
2140 #endif /* _WIN32 */
2141
2142 static void
2143 report_counts(void)
2144 {
2145 #ifdef SIGINFO
2146   /* XXX - if we use sigaction, this doesn't have to be done.
2147      (Yes, this isn't necessary on BSD, but just in case a system
2148      where "signal()" has AT&T semantics adopts SIGINFO....) */
2149   signal(SIGINFO, report_counts_siginfo);
2150 #endif /* SIGINFO */
2151
2152   if (cfile.save_file != NULL && quiet) {
2153     /* Report the count only if we're capturing to a file (rather
2154        than printing captured packet information out) and aren't
2155        updating a count as packets arrive. */
2156     fprintf(stderr, "%u packets captured\n", ld.packet_count);
2157   }
2158 #ifdef SIGINFO
2159   infoprint = FALSE;    /* we just reported it */
2160 #endif /* SIGINFO */
2161 }
2162
2163 #ifdef SIGINFO
2164 static void
2165 report_counts_siginfo(int signum _U_)
2166 {
2167   int sav_errno = errno;
2168   /* If we've been told to delay printing, just set a flag asking
2169      that we print counts (if we're supposed to), otherwise print
2170      the count of packets captured (if we're supposed to). */
2171   if (infodelay)
2172     infoprint = TRUE;
2173   else
2174     report_counts();
2175   errno = sav_errno;
2176 }
2177 #endif /* SIGINFO */
2178 #endif /* HAVE_LIBPCAP */
2179
2180 static int
2181 load_cap_file(capture_file *cf, int out_file_type)
2182 {
2183   gint         linktype;
2184   int          snapshot_length;
2185   wtap_dumper *pdh;
2186   int          err;
2187   int          success;
2188   cb_args_t    args;
2189
2190   linktype = wtap_file_encap(cf->wth);
2191   if (cf->save_file != NULL) {
2192     /* Set up to write to the capture file. */
2193     snapshot_length = wtap_snapshot_length(cf->wth);
2194     if (snapshot_length == 0) {
2195       /* Snapshot length of input file not known. */
2196       snapshot_length = WTAP_MAX_PACKET_SIZE;
2197     }
2198     pdh = wtap_dump_open(cf->save_file, out_file_type,
2199                 linktype, snapshot_length, &err);
2200
2201     if (pdh == NULL) {
2202       /* We couldn't set up to write to the capture file. */
2203       switch (err) {
2204
2205       case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2206         fprintf(stderr,
2207                 "tethereal: Capture files can't be written in that format.\n");
2208         break;
2209
2210       case WTAP_ERR_UNSUPPORTED_ENCAP:
2211       case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2212         fprintf(stderr,
2213           "tethereal: The capture file being read cannot be written in "
2214           "that format.\n");
2215         break;
2216
2217       case WTAP_ERR_CANT_OPEN:
2218         fprintf(stderr,
2219           "tethereal: The file \"%s\" couldn't be created for some "
2220           "unknown reason.\n",
2221             *cf->save_file == '\0' ? "stdout" : cf->save_file);
2222         break;
2223
2224       case WTAP_ERR_SHORT_WRITE:
2225         fprintf(stderr,
2226           "tethereal: A full header couldn't be written to the file \"%s\".\n",
2227                 *cf->save_file == '\0' ? "stdout" : cf->save_file);
2228         break;
2229
2230       default:
2231         fprintf(stderr,
2232           "tethereal: The file \"%s\" could not be created: %s\n.",
2233                 *cf->save_file == '\0' ? "stdout" : cf->save_file,
2234                 wtap_strerror(err));
2235         break;
2236       }
2237       goto out;
2238     }
2239     args.cf = cf;
2240     args.pdh = pdh;
2241     success = wtap_loop(cf->wth, 0, wtap_dispatch_cb_write, (guchar *) &args,
2242                         &err);
2243
2244     /* Now close the capture file. */
2245     if (!wtap_dump_close(pdh, &err))
2246       show_capture_file_io_error(cfile.save_file, err, TRUE);
2247   } else {
2248     args.cf = cf;
2249     args.pdh = NULL;
2250     print_preamble(stdout, print_format);
2251     success = wtap_loop(cf->wth, 0, wtap_dispatch_cb_print, (guchar *) &args,
2252                         &err);
2253     print_finale(stdout, print_format);
2254   }
2255   if (!success) {
2256     /* Print up a message box noting that the read failed somewhere along
2257        the line. */
2258     switch (err) {
2259
2260     case WTAP_ERR_UNSUPPORTED_ENCAP:
2261       fprintf(stderr,
2262 "tethereal: \"%s\" is a capture file is for a network type that Tethereal doesn't support.\n",
2263         cf->filename);
2264       break;
2265
2266     case WTAP_ERR_CANT_READ:
2267       fprintf(stderr,
2268 "tethereal: An attempt to read from \"%s\" failed for some unknown reason.\n",
2269         cf->filename);
2270       break;
2271
2272     case WTAP_ERR_SHORT_READ:
2273       fprintf(stderr,
2274 "tethereal: \"%s\" appears to have been cut short in the middle of a packet.\n",
2275         cf->filename);
2276       break;
2277
2278     case WTAP_ERR_BAD_RECORD:
2279       fprintf(stderr,
2280 "tethereal: \"%s\" appears to be damaged or corrupt.\n",
2281         cf->filename);
2282       break;
2283
2284     default:
2285       fprintf(stderr,
2286 "tethereal: An error occurred while reading \"%s\": %s.\n",
2287         cf->filename, wtap_strerror(err));
2288       break;
2289     }
2290   }
2291
2292 out:
2293   wtap_close(cf->wth);
2294   cf->wth = NULL;
2295
2296   return err;
2297 }
2298
2299 static void
2300 fill_in_fdata(frame_data *fdata, capture_file *cf,
2301         const struct wtap_pkthdr *phdr, long offset)
2302 {
2303   fdata->next = NULL;
2304   fdata->prev = NULL;
2305   fdata->pfd = NULL;
2306   fdata->num = cf->count;
2307   fdata->pkt_len = phdr->len;
2308   cul_bytes += phdr->len;
2309   fdata->cul_bytes  = cul_bytes;
2310   fdata->cap_len = phdr->caplen;
2311   fdata->file_off = offset;
2312   fdata->lnk_t = phdr->pkt_encap;
2313   fdata->abs_secs  = phdr->ts.tv_sec;
2314   fdata->abs_usecs = phdr->ts.tv_usec;
2315   fdata->flags.passed_dfilter = 0;
2316   fdata->flags.encoding = CHAR_ASCII;
2317   fdata->flags.visited = 0;
2318   fdata->flags.marked = 0;
2319   fdata->flags.ref_time = 0;
2320
2321   /* If we don't have the time stamp of the first packet in the
2322      capture, it's because this is the first packet.  Save the time
2323      stamp of this packet as the time stamp of the first packet. */
2324   if (!firstsec && !firstusec) {
2325     firstsec  = fdata->abs_secs;
2326     firstusec = fdata->abs_usecs;
2327   }
2328
2329   /* If we don't have the time stamp of the previous displayed packet,
2330      it's because this is the first displayed packet.  Save the time
2331      stamp of this packet as the time stamp of the previous displayed
2332      packet. */
2333   if (!prevsec && !prevusec) {
2334     prevsec  = fdata->abs_secs;
2335     prevusec = fdata->abs_usecs;
2336   }
2337
2338   /* Get the time elapsed between the first packet and this packet. */
2339   compute_timestamp_diff(&fdata->rel_secs, &fdata->rel_usecs,
2340                 fdata->abs_secs, fdata->abs_usecs, firstsec, firstusec);
2341
2342   /* If it's greater than the current elapsed time, set the elapsed time
2343      to it (we check for "greater than" so as not to be confused by
2344      time moving backwards). */
2345   if ((gint32)cf->esec < fdata->rel_secs
2346         || ((gint32)cf->esec == fdata->rel_secs && (gint32)cf->eusec < fdata->rel_usecs)) {
2347     cf->esec = fdata->rel_secs;
2348     cf->eusec = fdata->rel_usecs;
2349   }
2350
2351   /* Get the time elapsed between the previous displayed packet and
2352      this packet. */
2353   compute_timestamp_diff(&fdata->del_secs, &fdata->del_usecs,
2354                 fdata->abs_secs, fdata->abs_usecs, prevsec, prevusec);
2355   prevsec = fdata->abs_secs;
2356   prevusec = fdata->abs_usecs;
2357 }
2358
2359 /* Free up all data attached to a "frame_data" structure. */
2360 static void
2361 clear_fdata(frame_data *fdata)
2362 {
2363   if (fdata->pfd)
2364     g_slist_free(fdata->pfd);
2365 }
2366
2367 static void
2368 wtap_dispatch_cb_write(guchar *user, const struct wtap_pkthdr *phdr,
2369   long offset, union wtap_pseudo_header *pseudo_header, const guchar *buf)
2370 {
2371   cb_args_t    *args = (cb_args_t *) user;
2372   capture_file *cf = args->cf;
2373   wtap_dumper  *pdh = args->pdh;
2374   frame_data    fdata;
2375   int           err;
2376   gboolean      passed;
2377   epan_dissect_t *edt;
2378
2379 #ifdef HAVE_LIBPCAP
2380 #ifdef SIGINFO
2381   /*
2382    * Prevent a SIGINFO handler from writing to stdout while we're
2383    * doing so; instead, have it just set a flag telling us to print
2384    * that information when we're done.
2385    */
2386   infodelay = TRUE;
2387 #endif /* SIGINFO */
2388 #endif /* HAVE_LIBPCAP */
2389
2390   cf->count++;
2391   if (cf->rfcode) {
2392     fill_in_fdata(&fdata, cf, phdr, offset);
2393     edt = epan_dissect_new(TRUE, FALSE);
2394     epan_dissect_prime_dfilter(edt, cf->rfcode);
2395     epan_dissect_run(edt, pseudo_header, buf, &fdata, NULL);
2396     passed = dfilter_apply_edt(cf->rfcode, edt);
2397   } else {
2398     passed = TRUE;
2399     edt = NULL;
2400   }
2401   if (passed) {
2402     /* The packet passed the read filter. */
2403 #ifdef HAVE_LIBPCAP
2404     int loop_err;
2405
2406     ld.packet_count++;
2407
2408     /* The current packet may have arrived after a very long silence,
2409      * way past the time to switch files.  In order not to have
2410      * the first packet of a new series of events as the last
2411      * [or only] packet in the file, switch before writing!
2412      */
2413     if (cnd_ring_timeout != NULL && cnd_eval(cnd_ring_timeout)) {
2414       /* time elasped for this ring file, switch to the next */
2415       if (ringbuf_switch_file(&cfile, &ld.pdh, &loop_err)) {
2416         /* File switch succeeded: reset the condition */
2417         cnd_reset(cnd_ring_timeout);
2418       } else {
2419         /* File switch failed: stop here */
2420         /* XXX - we should do something with "loop_err" */
2421         ld.go = FALSE;
2422       }
2423     }
2424 #endif
2425     if (!wtap_dump(pdh, phdr, pseudo_header, buf, &err)) {
2426 #ifdef HAVE_LIBPCAP
2427       if (ld.pch != NULL && !quiet) {
2428         /* We're capturing packets, so (if -q not specified) we're printing
2429            a count of packets captured; move to the line after the count. */
2430         fprintf(stderr, "\n");
2431       }
2432 #endif
2433       show_capture_file_io_error(cf->save_file, err, FALSE);
2434 #ifdef HAVE_LIBPCAP
2435       if (ld.pch != NULL)
2436         pcap_close(ld.pch);
2437 #endif
2438       wtap_dump_close(pdh, &err);
2439       exit(2);
2440     }
2441   }
2442   if (edt != NULL)
2443     epan_dissect_free(edt);
2444   if (cf->rfcode)
2445     clear_fdata(&fdata);
2446
2447 #ifdef HAVE_LIBPCAP
2448 #ifdef SIGINFO
2449   /*
2450    * Allow SIGINFO handlers to write.
2451    */
2452   infodelay = FALSE;
2453
2454   /*
2455    * If a SIGINFO handler asked us to write out capture counts, do so.
2456    */
2457   if (infoprint)
2458     report_counts();
2459 #endif /* SIGINFO */
2460 #endif /* HAVE_LIBPCAP */
2461 }
2462
2463 static void
2464 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
2465 {
2466   if (*fname == '\0')
2467     fname = "stdout";
2468
2469   switch (err) {
2470
2471   case ENOSPC:
2472     fprintf(stderr,
2473 "tethereal: Not all the packets could be written to \"%s\" because there is "
2474 "no space left on the file system.\n",
2475         fname);
2476     break;
2477
2478 #ifdef EDQUOT
2479   case EDQUOT:
2480     fprintf(stderr,
2481 "tethereal: Not all the packets could be written to \"%s\" because you are "
2482 "too close to, or over your disk quota.\n",
2483         fname);
2484   break;
2485 #endif
2486
2487   case WTAP_ERR_CANT_CLOSE:
2488     fprintf(stderr,
2489 "tethereal: \"%s\" couldn't be closed for some unknown reason.\n",
2490         fname);
2491     break;
2492
2493   case WTAP_ERR_SHORT_WRITE:
2494     fprintf(stderr,
2495 "tethereal: Not all the packets could be written to \"%s\".\n",
2496         fname);
2497     break;
2498
2499   default:
2500     if (is_close) {
2501       fprintf(stderr,
2502 "tethereal: \"%s\" could not be closed: %s.\n",
2503         fname, wtap_strerror(err));
2504     } else {
2505       fprintf(stderr,
2506 "tethereal: An error occurred while writing to \"%s\": %s.\n",
2507         fname, wtap_strerror(err));
2508     }
2509     break;
2510   }
2511 }
2512
2513 static void
2514 wtap_dispatch_cb_print(guchar *user, const struct wtap_pkthdr *phdr,
2515   long offset, union wtap_pseudo_header *pseudo_header, const guchar *buf)
2516 {
2517   cb_args_t    *args = (cb_args_t *) user;
2518   capture_file *cf = args->cf;
2519   frame_data    fdata;
2520   gboolean      passed;
2521   print_args_t  print_args;
2522   epan_dissect_t *edt;
2523   gboolean      create_proto_tree;
2524   int           i;
2525
2526   cf->count++;
2527
2528   fill_in_fdata(&fdata, cf, phdr, offset);
2529
2530   /* Grab any resolved addresses */
2531   if (g_resolv_flags) {
2532     host_name_lookup_process(NULL);
2533   }
2534
2535   passed = TRUE;
2536   if (cf->rfcode || verbose || num_tap_filters!=0)
2537     create_proto_tree = TRUE;
2538   else
2539     create_proto_tree = FALSE;
2540   /* The protocol tree will be "visible", i.e., printed, only if we're
2541      not printing a summary.
2542
2543      We only need the columns if we're *not* verbose; in verbose mode,
2544      we print the protocol tree, not the protocol summary. */
2545
2546   edt = epan_dissect_new(create_proto_tree, verbose);
2547   if (cf->rfcode) {
2548     epan_dissect_prime_dfilter(edt, cf->rfcode);
2549   }
2550
2551   tap_queue_init(edt);
2552   epan_dissect_run(edt, pseudo_header, buf, &fdata, verbose ? NULL : &cf->cinfo);
2553   tap_push_tapped_queue(edt);
2554
2555   if (cf->rfcode) {
2556     passed = dfilter_apply_edt(cf->rfcode, edt);
2557   }
2558   if (passed) {
2559     /* The packet passed the read filter. */
2560 #ifdef HAVE_LIBPCAP
2561     ld.packet_count++;
2562 #endif
2563     print_args.to_file = TRUE;
2564     print_args.format = print_format;
2565     print_args.print_summary = !verbose;
2566     print_args.print_hex = print_hex;
2567     print_args.print_dissections = print_dissections_expanded;
2568
2569     /* init the packet range */
2570     packet_range_init(&print_args.range);
2571
2572     if (verbose) {
2573       /* Print the information in the protocol tree. */
2574       proto_tree_print(&print_args, edt, stdout);
2575       if (!print_hex) {
2576         /* "print_hex_data()" will put out a leading blank line, as well
2577            as a trailing one; print one here, to separate the packets,
2578            only if "print_hex_data()" won't be called. */
2579         printf("\n");
2580       }
2581     } else {
2582       /* Just fill in the columns. */
2583       epan_dissect_fill_in_columns(edt);
2584
2585       /* Now print them. */
2586       for (i = 0; i < cf->cinfo.num_cols; i++) {
2587         switch (cf->cinfo.col_fmt[i]) {
2588         case COL_NUMBER:
2589           /*
2590            * Don't print this if we're doing a live capture from a network
2591            * interface - if we're doing a live capture, you won't be
2592            * able to look at the capture in the future (it's not being
2593            * saved anywhere), so the frame numbers are unlikely to be
2594            * useful.
2595            *
2596            * (XXX - it might be nice to be able to save and print at
2597            * the same time, sort of like an "Update list of packets
2598            * in real time" capture in Ethereal.)
2599            */
2600           if (cf->iface != NULL)
2601             continue;
2602           printf("%3s", cf->cinfo.col_data[i]);
2603           break;
2604
2605         case COL_CLS_TIME:
2606         case COL_REL_TIME:
2607         case COL_ABS_TIME:
2608         case COL_ABS_DATE_TIME: /* XXX - wider */
2609           printf("%10s", cf->cinfo.col_data[i]);
2610           break;
2611
2612         case COL_DEF_SRC:
2613         case COL_RES_SRC:
2614         case COL_UNRES_SRC:
2615         case COL_DEF_DL_SRC:
2616         case COL_RES_DL_SRC:
2617         case COL_UNRES_DL_SRC:
2618         case COL_DEF_NET_SRC:
2619         case COL_RES_NET_SRC:
2620         case COL_UNRES_NET_SRC:
2621           printf("%12s", cf->cinfo.col_data[i]);
2622           break;
2623
2624         case COL_DEF_DST:
2625         case COL_RES_DST:
2626         case COL_UNRES_DST:
2627         case COL_DEF_DL_DST:
2628         case COL_RES_DL_DST:
2629         case COL_UNRES_DL_DST:
2630         case COL_DEF_NET_DST:
2631         case COL_RES_NET_DST:
2632         case COL_UNRES_NET_DST:
2633           printf("%-12s", cf->cinfo.col_data[i]);
2634           break;
2635
2636         default:
2637           printf("%s", cf->cinfo.col_data[i]);
2638           break;
2639         }
2640         if (i != cf->cinfo.num_cols - 1) {
2641           /*
2642            * This isn't the last column, so we need to print a
2643            * separator between this column and the next.
2644            *
2645            * If we printed a network source and are printing a
2646            * network destination of the same type next, separate
2647            * them with "->"; if we printed a network destination
2648            * and are printing a network source of the same type
2649            * next, separate them with "<-"; otherwise separate them
2650            * with a space.
2651            */
2652           switch (cf->cinfo.col_fmt[i]) {
2653
2654           case COL_DEF_SRC:
2655           case COL_RES_SRC:
2656           case COL_UNRES_SRC:
2657             switch (cf->cinfo.col_fmt[i + 1]) {
2658
2659             case COL_DEF_DST:
2660             case COL_RES_DST:
2661             case COL_UNRES_DST:
2662               printf(" -> ");
2663               break;
2664
2665             default:
2666               putchar(' ');
2667               break;
2668             }
2669             break;
2670
2671           case COL_DEF_DL_SRC:
2672           case COL_RES_DL_SRC:
2673           case COL_UNRES_DL_SRC:
2674             switch (cf->cinfo.col_fmt[i + 1]) {
2675
2676             case COL_DEF_DL_DST:
2677             case COL_RES_DL_DST:
2678             case COL_UNRES_DL_DST:
2679               printf(" -> ");
2680               break;
2681
2682             default:
2683               putchar(' ');
2684               break;
2685             }
2686             break;
2687
2688           case COL_DEF_NET_SRC:
2689           case COL_RES_NET_SRC:
2690           case COL_UNRES_NET_SRC:
2691             switch (cf->cinfo.col_fmt[i + 1]) {
2692
2693             case COL_DEF_NET_DST:
2694             case COL_RES_NET_DST:
2695             case COL_UNRES_NET_DST:
2696               printf(" -> ");
2697               break;
2698
2699             default:
2700               putchar(' ');
2701               break;
2702             }
2703             break;
2704
2705           case COL_DEF_DST:
2706           case COL_RES_DST:
2707           case COL_UNRES_DST:
2708             switch (cf->cinfo.col_fmt[i + 1]) {
2709
2710             case COL_DEF_SRC:
2711             case COL_RES_SRC:
2712             case COL_UNRES_SRC:
2713               printf(" <- ");
2714               break;
2715
2716             default:
2717               putchar(' ');
2718               break;
2719             }
2720             break;
2721
2722           case COL_DEF_DL_DST:
2723           case COL_RES_DL_DST:
2724           case COL_UNRES_DL_DST:
2725             switch (cf->cinfo.col_fmt[i + 1]) {
2726
2727             case COL_DEF_DL_SRC:
2728             case COL_RES_DL_SRC:
2729             case COL_UNRES_DL_SRC:
2730               printf(" <- ");
2731               break;
2732
2733             default:
2734               putchar(' ');
2735               break;
2736             }
2737             break;
2738
2739           case COL_DEF_NET_DST:
2740           case COL_RES_NET_DST:
2741           case COL_UNRES_NET_DST:
2742             switch (cf->cinfo.col_fmt[i + 1]) {
2743
2744             case COL_DEF_NET_SRC:
2745             case COL_RES_NET_SRC:
2746             case COL_UNRES_NET_SRC:
2747               printf(" <- ");
2748               break;
2749
2750             default:
2751               putchar(' ');
2752               break;
2753             }
2754             break;
2755
2756           default:
2757             putchar(' ');
2758             break;
2759           }
2760         }
2761       }
2762       putchar('\n');
2763     }
2764     if (print_hex) {
2765       print_hex_data(stdout, print_args.format, edt);
2766       putchar('\n');
2767     }
2768   }
2769
2770   /* The ANSI C standard does not appear to *require* that a line-buffered
2771      stream be flushed to the host environment whenever a newline is
2772      written, it just says that, on such a stream, characters "are
2773      intended to be transmitted to or from the host environment as a
2774      block when a new-line character is encountered".
2775
2776      The Visual C++ 6.0 C implementation doesn't do what is intended;
2777      even if you set a stream to be line-buffered, it still doesn't
2778      flush the buffer at the end of every line.
2779
2780      So, if the "-l" flag was specified, we flush the standard output
2781      at the end of a packet.  This will do the right thing if we're
2782      printing packet summary lines, and, as we print the entire protocol
2783      tree for a single packet without waiting for anything to happen,
2784      it should be as good as line-buffered mode if we're printing
2785      protocol trees.  (The whole reason for the "-l" flag in either
2786      tcpdump or Tethereal is to allow the output of a live capture to
2787      be piped to a program or script and to have that script see the
2788      information for the packet as soon as it's printed, rather than
2789      having to wait until a standard I/O buffer fills up. */
2790   if (line_buffered)
2791     fflush(stdout);
2792
2793   epan_dissect_free(edt);
2794
2795   clear_fdata(&fdata);
2796 }
2797
2798 char *
2799 file_open_error_message(int err, gboolean for_writing, int file_type)
2800 {
2801   char *errmsg;
2802   static char errmsg_errno[1024+1];
2803
2804   switch (err) {
2805
2806   case WTAP_ERR_NOT_REGULAR_FILE:
2807     errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
2808     break;
2809
2810   case WTAP_ERR_FILE_UNKNOWN_FORMAT:
2811   case WTAP_ERR_UNSUPPORTED:
2812     /* Seen only when opening a capture file for reading. */
2813     errmsg = "The file \"%s\" is not a capture file in a format Tethereal understands.";
2814     break;
2815
2816   case WTAP_ERR_CANT_WRITE_TO_PIPE:
2817     /* Seen only when opening a capture file for writing. */
2818     snprintf(errmsg_errno, sizeof(errmsg_errno),
2819              "The file \"%%s\" is a pipe, and %s capture files cannot be "
2820              "written to a pipe.", wtap_file_type_string(file_type));
2821     errmsg = errmsg_errno;
2822     break;
2823
2824   case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2825     /* Seen only when opening a capture file for writing. */
2826     errmsg = "Tethereal does not support writing capture files in that format.";
2827     break;
2828
2829   case WTAP_ERR_UNSUPPORTED_ENCAP:
2830   case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2831     if (for_writing)
2832       errmsg = "Tethereal cannot save this capture in that format.";
2833     else
2834       errmsg = "The file \"%s\" is a capture for a network type that Tethereal doesn't support.";
2835     break;
2836
2837   case WTAP_ERR_BAD_RECORD:
2838     errmsg = "The file \"%s\" appears to be damaged or corrupt.";
2839     break;
2840
2841   case WTAP_ERR_CANT_OPEN:
2842     if (for_writing)
2843       errmsg = "The file \"%s\" could not be created for some unknown reason.";
2844     else
2845       errmsg = "The file \"%s\" could not be opened for some unknown reason.";
2846     break;
2847
2848   case WTAP_ERR_SHORT_READ:
2849     errmsg = "The file \"%s\" appears to have been cut short"
2850              " in the middle of a packet or other data.";
2851     break;
2852
2853   case WTAP_ERR_SHORT_WRITE:
2854     errmsg = "A full header couldn't be written to the file \"%s\".";
2855     break;
2856
2857   case ENOENT:
2858     if (for_writing)
2859       errmsg = "The path to the file \"%s\" does not exist.";
2860     else
2861       errmsg = "The file \"%s\" does not exist.";
2862     break;
2863
2864   case EACCES:
2865     if (for_writing)
2866       errmsg = "You do not have permission to create or write to the file \"%s\".";
2867     else
2868       errmsg = "You do not have permission to read the file \"%s\".";
2869     break;
2870
2871   case EISDIR:
2872     errmsg = "\"%s\" is a directory (folder), not a file.";
2873     break;
2874
2875   default:
2876     snprintf(errmsg_errno, sizeof(errmsg_errno),
2877              "The file \"%%s\" could not be %s: %s.",
2878              for_writing ? "created" : "opened",
2879              wtap_strerror(err));
2880     errmsg = errmsg_errno;
2881     break;
2882   }
2883   return errmsg;
2884 }
2885
2886 int
2887 cf_open(char *fname, gboolean is_tempfile, capture_file *cf)
2888 {
2889   wtap       *wth;
2890   int         err;
2891   char        err_msg[2048+1];
2892
2893   wth = wtap_open_offline(fname, &err, FALSE);
2894   if (wth == NULL)
2895     goto fail;
2896
2897   /* The open succeeded.  Fill in the information for this file. */
2898
2899   /* Initialize all data structures used for dissection. */
2900   init_dissection();
2901
2902   cf->wth = wth;
2903   cf->filed = -1;       /* not used, but set it anyway */
2904   cf->f_len = 0;        /* not used, but set it anyway */
2905
2906   /* Set the file name because we need it to set the follow stream filter.
2907      XXX - is that still true?  We need it for other reasons, though,
2908      in any case. */
2909   cf->filename = g_strdup(fname);
2910
2911   /* Indicate whether it's a permanent or temporary file. */
2912   cf->is_tempfile = is_tempfile;
2913
2914   /* If it's a temporary capture buffer file, mark it as not saved. */
2915   cf->user_saved = !is_tempfile;
2916
2917   cf->cd_t      = wtap_file_type(cf->wth);
2918   cf->count     = 0;
2919   cf->drops_known = FALSE;
2920   cf->drops     = 0;
2921   cf->esec      = 0;
2922   cf->eusec     = 0;
2923   cf->snap      = wtap_snapshot_length(cf->wth);
2924   if (cf->snap == 0) {
2925     /* Snapshot length not known. */
2926     cf->has_snap = FALSE;
2927     cf->snap = WTAP_MAX_PACKET_SIZE;
2928   } else
2929     cf->has_snap = TRUE;
2930   cf->progbar_quantum = 0;
2931   cf->progbar_nextstep = 0;
2932   firstsec = 0, firstusec = 0;
2933   prevsec = 0, prevusec = 0;
2934
2935   return (0);
2936
2937 fail:
2938   snprintf(err_msg, sizeof err_msg, file_open_error_message(err, FALSE, 0),
2939            fname);
2940   fprintf(stderr, "tethereal: %s\n", err_msg);
2941   return (err);
2942 }
2943
2944 #ifdef HAVE_LIBPCAP
2945 #ifndef _WIN32
2946 /* Take care of byte order in the libpcap headers read from pipes.
2947  * (function taken from wiretap/libpcap.c) */
2948 static void
2949 adjust_header(loop_data *ld, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
2950 {
2951   if (ld->byte_swapped) {
2952     /* Byte-swap the record header fields. */
2953     rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
2954     rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
2955     rechdr->incl_len = BSWAP32(rechdr->incl_len);
2956     rechdr->orig_len = BSWAP32(rechdr->orig_len);
2957   }
2958
2959   /* In file format version 2.3, the "incl_len" and "orig_len" fields were
2960      swapped, in order to match the BPF header layout.
2961
2962      Unfortunately, some files were, according to a comment in the "libpcap"
2963      source, written with version 2.3 in their headers but without the
2964      interchanged fields, so if "incl_len" is greater than "orig_len" - which
2965      would make no sense - we assume that we need to swap them.  */
2966   if (hdr->version_major == 2 &&
2967       (hdr->version_minor < 3 ||
2968        (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
2969     guint32 temp;
2970
2971     temp = rechdr->orig_len;
2972     rechdr->orig_len = rechdr->incl_len;
2973     rechdr->incl_len = temp;
2974   }
2975 }
2976
2977 /* Mimic pcap_open_live() for pipe captures
2978  * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
2979  * header.
2980  * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
2981  * because we can't seek on pipes (see wiretap/libpcap.c for details) */
2982 static int
2983 pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
2984                  char *errmsg, int errmsgl)
2985 {
2986   struct stat pipe_stat;
2987   int         fd;
2988   guint32     magic;
2989   int         b;
2990   unsigned int bytes_read;
2991
2992   /*
2993    * XXX Tethereal blocks until we return
2994    */
2995   if (strcmp(pipename, "-") == 0)
2996     fd = 0; /* read from stdin */
2997   else {
2998     if (stat(pipename, &pipe_stat) < 0) {
2999       if (errno == ENOENT || errno == ENOTDIR)
3000         ld->pipe_err = PIPNEXIST;
3001       else {
3002         snprintf(errmsg, errmsgl,
3003           "The capture session could not be initiated "
3004           "due to error on pipe: %s", strerror(errno));
3005         ld->pipe_err = PIPERR;
3006       }
3007       return -1;
3008     }
3009     if (! S_ISFIFO(pipe_stat.st_mode)) {
3010       if (S_ISCHR(pipe_stat.st_mode)) {
3011         /*
3012          * Assume the user specified an interface on a system where
3013          * interfaces are in /dev.  Pretend we haven't seen it.
3014          */
3015          ld->pipe_err = PIPNEXIST;
3016       } else {
3017         snprintf(errmsg, errmsgl,
3018             "The capture session could not be initiated because\n"
3019             "\"%s\" is neither an interface nor a pipe", pipename);
3020         ld->pipe_err = PIPERR;
3021       }
3022       return -1;
3023     }
3024     fd = open(pipename, O_RDONLY);
3025     if (fd == -1) {
3026       snprintf(errmsg, errmsgl,
3027           "The capture session could not be initiated "
3028           "due to error on pipe open: %s", strerror(errno));
3029       ld->pipe_err = PIPERR;
3030       return -1;
3031     }
3032   }
3033
3034   ld->from_pipe = TRUE;
3035
3036   /* read the pcap header */
3037   bytes_read = 0;
3038   while (bytes_read < sizeof magic) {
3039     b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
3040     if (b <= 0) {
3041       if (b == 0)
3042         snprintf(errmsg, errmsgl, "End of file on pipe during open");
3043       else
3044         snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
3045           strerror(errno));
3046       goto error;
3047     }
3048     bytes_read += b;
3049   }
3050
3051   switch (magic) {
3052   case PCAP_MAGIC:
3053     /* Host that wrote it has our byte order, and was running
3054        a program using either standard or ss990417 libpcap. */
3055     ld->byte_swapped = FALSE;
3056     ld->modified = FALSE;
3057     break;
3058   case PCAP_MODIFIED_MAGIC:
3059     /* Host that wrote it has our byte order, but was running
3060        a program using either ss990915 or ss991029 libpcap. */
3061     ld->byte_swapped = FALSE;
3062     ld->modified = TRUE;
3063     break;
3064   case PCAP_SWAPPED_MAGIC:
3065     /* Host that wrote it has a byte order opposite to ours,
3066        and was running a program using either standard or
3067        ss990417 libpcap. */
3068     ld->byte_swapped = TRUE;
3069     ld->modified = FALSE;
3070     break;
3071   case PCAP_SWAPPED_MODIFIED_MAGIC:
3072     /* Host that wrote it out has a byte order opposite to
3073        ours, and was running a program using either ss990915
3074        or ss991029 libpcap. */
3075     ld->byte_swapped = TRUE;
3076     ld->modified = TRUE;
3077     break;
3078   default:
3079     /* Not a "libpcap" type we know about. */
3080     snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
3081     goto error;
3082   }
3083
3084   /* Read the rest of the header */
3085   bytes_read = 0;
3086   while (bytes_read < sizeof(struct pcap_hdr)) {
3087     b = read(fd, ((char *)hdr)+bytes_read,
3088           sizeof(struct pcap_hdr) - bytes_read);
3089     if (b <= 0) {
3090       if (b == 0)
3091         snprintf(errmsg, errmsgl, "End of file on pipe during open");
3092       else
3093         snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
3094           strerror(errno));
3095       goto error;
3096     }
3097     bytes_read += b;
3098   }
3099
3100   if (ld->byte_swapped) {
3101     /* Byte-swap the header fields about which we care. */
3102     hdr->version_major = BSWAP16(hdr->version_major);
3103     hdr->version_minor = BSWAP16(hdr->version_minor);
3104     hdr->snaplen = BSWAP32(hdr->snaplen);
3105     hdr->network = BSWAP32(hdr->network);
3106   }
3107
3108   if (hdr->version_major < 2) {
3109     snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
3110     goto error;
3111   }
3112
3113   ld->pipe_state = STATE_EXPECT_REC_HDR;
3114   ld->pipe_err = PIPOK;
3115   return fd;
3116
3117 error:
3118   ld->pipe_err = PIPERR;
3119   close(fd);
3120   return -1;
3121
3122 }
3123 /* We read one record from the pipe, take care of byte order in the record
3124  * header, write the record in the capture file, and update capture statistics. */
3125
3126 static int
3127 pipe_dispatch(int fd, loop_data *ld, struct pcap_hdr *hdr,
3128                 struct pcaprec_modified_hdr *rechdr, guchar *data,
3129                 char *errmsg, int errmsgl)
3130 {
3131   struct pcap_pkthdr phdr;
3132   int b;
3133   enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
3134           PD_ERR } result;
3135
3136   switch (ld->pipe_state) {
3137
3138   case STATE_EXPECT_REC_HDR:
3139     ld->bytes_to_read = ld->modified ?
3140       sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
3141     ld->bytes_read = 0;
3142     ld->pipe_state = STATE_READ_REC_HDR;
3143     /* Fall through */
3144
3145   case STATE_READ_REC_HDR:
3146     b = read(fd, ((char *)rechdr)+ld->bytes_read,
3147       ld->bytes_to_read - ld->bytes_read);
3148     if (b <= 0) {
3149       if (b == 0)
3150         result = PD_PIPE_EOF;
3151       else
3152         result = PD_PIPE_ERR;
3153       break;
3154     }
3155     if ((ld->bytes_read += b) < ld->bytes_to_read)
3156         return 0;
3157     result = PD_REC_HDR_READ;
3158     break;
3159
3160   case STATE_EXPECT_DATA:
3161     ld->bytes_read = 0;
3162     ld->pipe_state = STATE_READ_DATA;
3163     /* Fall through */
3164
3165   case STATE_READ_DATA:
3166     b = read(fd, data+ld->bytes_read, rechdr->hdr.incl_len - ld->bytes_read);
3167     if (b <= 0) {
3168       if (b == 0)
3169         result = PD_PIPE_EOF;
3170       else
3171         result = PD_PIPE_ERR;
3172       break;
3173     }
3174     if ((ld->bytes_read += b) < rechdr->hdr.incl_len)
3175       return 0;
3176     result = PD_DATA_READ;
3177     break;
3178
3179   default:
3180     snprintf(errmsg, errmsgl, "pipe_dispatch: invalid state");
3181     result = PD_ERR;
3182
3183   } /* switch (ld->pipe_state) */
3184
3185   /*
3186    * We've now read as much data as we were expecting, so process it.
3187    */
3188   switch (result) {
3189
3190   case PD_REC_HDR_READ:
3191     /* We've read the header. Take care of byte order. */
3192     adjust_header(ld, hdr, &rechdr->hdr);
3193     if (rechdr->hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
3194       snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
3195         ld->packet_count+1, rechdr->hdr.incl_len);
3196       break;
3197     }
3198     ld->pipe_state = STATE_EXPECT_DATA;
3199     return 0;
3200
3201   case PD_DATA_READ:
3202     /* Fill in a "struct pcap_pkthdr", and process the packet. */
3203     phdr.ts.tv_sec = rechdr->hdr.ts_sec;
3204     phdr.ts.tv_usec = rechdr->hdr.ts_usec;
3205     phdr.caplen = rechdr->hdr.incl_len;
3206     phdr.len = rechdr->hdr.orig_len;
3207
3208     capture_pcap_cb((guchar *)ld, &phdr, data);
3209
3210     ld->pipe_state = STATE_EXPECT_REC_HDR;
3211     return 1;
3212
3213   case PD_PIPE_EOF:
3214     ld->pipe_err = PIPEOF;
3215     return -1;
3216
3217   case PD_PIPE_ERR:
3218     snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
3219       strerror(errno));
3220     /* Fall through */
3221   case PD_ERR:
3222     break;
3223   }
3224
3225   ld->pipe_err = PIPERR;
3226   /* Return here rather than inside the switch to prevent GCC warning */
3227   return -1;
3228 }
3229 #endif /* _WIN32 */
3230 #endif /* HAVE_LIBPCAP */