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