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