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