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