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