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