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