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