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