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