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