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