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>.
8 * Wireshark - Network traffic analyzer
9 * By Gerald Combs <gerald@wireshark.org>
10 * Copyright 1998 Gerald Combs
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.
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.
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.
50 #ifdef HAVE_SYS_STAT_H
51 # include <sys/stat.h>
54 #ifdef NEED_STRERROR_H
55 #include "wsutil/strerror.h"
61 #include "wsutil/wsgetopt.h"
65 #include <epan/epan.h>
66 #include <epan/filesystem.h>
67 #include <wsutil/privileges.h>
68 #include <wsutil/file_util.h>
71 #include <epan/timestamp.h>
72 #include <epan/packet.h>
74 #include "disabled_protos.h"
75 #include <epan/prefs.h>
76 #include <epan/column.h>
78 #include <epan/addr_resolv.h>
80 #include "clopts_common.h"
81 #include "console_io.h"
82 #include "cmdarg_err.h"
83 #include "version_info.h"
84 #include <epan/plugins.h>
86 #include <epan/epan_dissect.h>
88 #include <epan/stat_cmd_args.h>
89 #include <epan/timestamp.h>
90 #include <epan/ex-opt.h>
93 #include "capture_ui_utils.h"
94 #include "capture_ifinfo.h"
95 #include "capture-pcap-util.h"
97 #include "capture-wpcap.h"
98 #include "capture_errs.h"
100 #include "capture_sync.h"
101 #endif /* HAVE_LIBPCAP */
103 #include <epan/funnel.h>
107 * This is the template for the decode as option; it is shared between the
108 * various functions that output the usage for this parameter.
110 static const gchar decode_as_arg_template[] = "<layer_type>==<selector>,<decode_as_protocol>";
112 static guint32 cum_bytes;
113 static nstime_t first_ts;
114 static nstime_t prev_dis_ts;
115 static nstime_t prev_cap_ts;
117 static gboolean print_packet_info; /* TRUE if we're to print packet information */
119 static gboolean perform_two_pass_analysis;
122 * The way the packet decode is to be written.
125 WRITE_TEXT, /* summary or detail text */
126 WRITE_XML, /* PDML or PSML */
127 WRITE_FIELDS /* User defined list of fields */
128 /* Add CSV and the like here */
131 static output_action_e output_action;
132 static gboolean do_dissection; /* TRUE if we have to dissect each packet */
133 static gboolean verbose;
134 static gboolean print_hex;
135 static gboolean line_buffered;
137 static print_format_e print_format = PR_FMT_TEXT;
138 static print_stream_t *print_stream;
140 static output_fields_t* output_fields = NULL;
144 * TRUE if we're to print packet counts to keep track of captured packets.
146 static gboolean print_packet_counts;
149 static capture_options global_capture_opts;
152 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
153 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
156 static gboolean capture(void);
157 static void report_counts(void);
159 static BOOL WINAPI capture_cleanup(DWORD);
161 static void capture_cleanup(int);
163 static void report_counts_siginfo(int);
166 #endif /* HAVE_LIBPCAP */
168 static int load_cap_file(capture_file *, char *, int, int, gint64);
169 static gboolean process_packet(capture_file *cf, gint64 offset,
170 const struct wtap_pkthdr *whdr, union wtap_pseudo_header *pseudo_header,
171 const guchar *pd, gboolean filtering_tap_listeners, guint tap_flags);
172 static void show_capture_file_io_error(const char *, int, gboolean);
173 static void show_print_file_io_error(int err);
174 static gboolean write_preamble(capture_file *cf);
175 static gboolean print_packet(capture_file *cf, epan_dissect_t *edt);
176 static gboolean write_finale(void);
177 static const char *cf_open_error_message(int err, gchar *err_info,
178 gboolean for_writing, int file_type);
180 static void open_failure_message(const char *filename, int err,
181 gboolean for_writing);
182 static void failure_message(const char *msg_format, va_list ap);
183 static void read_failure_message(const char *filename, int err);
184 static void write_failure_message(const char *filename, int err);
188 static void list_capture_types(void) {
191 fprintf(stderr, "editcap: The available capture file types for \"F\":\n");
192 for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
193 if (wtap_dump_can_open(i))
194 fprintf(stderr, " %s - %s\n",
195 wtap_file_type_short_string(i), wtap_file_type_string(i));
200 print_usage(gboolean print_ver)
207 "TShark " VERSION "%s\n"
208 "Dump and analyze network traffic.\n"
209 "See http://www.wireshark.org for more information.\n"
212 wireshark_svnversion, get_copyright_info());
216 fprintf(output, "\n");
217 fprintf(output, "Usage: tshark [options] ...\n");
218 fprintf(output, "\n");
221 fprintf(output, "Capture interface:\n");
222 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
223 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
224 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
225 fprintf(output, " -p don't capture in promiscuous mode\n");
226 #ifdef HAVE_PCAP_CREATE
227 fprintf(output, " -I capture in monitor mode, if available\n");
229 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
230 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
232 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
233 fprintf(output, " -D print list of interfaces and exit\n");
234 fprintf(output, " -L print list of link-layer types of iface and exit\n");
235 fprintf(output, "\n");
236 fprintf(output, "Capture stop conditions:\n");
237 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
238 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
239 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
240 fprintf(output, " files:NUM - stop after NUM files\n");
241 /*fprintf(output, "\n");*/
242 fprintf(output, "Capture output:\n");
243 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
244 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
245 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
246 #endif /* HAVE_LIBPCAP */
248 /*fprintf(output, "\n");*/
249 fprintf(output, "Input file:\n");
250 fprintf(output, " -r <infile> set the filename to read from (no pipes or stdin!)\n");
252 fprintf(output, "\n");
253 fprintf(output, "Processing:\n");
254 fprintf(output, " -R <read filter> packet filter in Wireshark display filter syntax\n");
255 fprintf(output, " -n disable all name resolutions (def: all enabled)\n");
256 fprintf(output, " -N <name resolve flags> enable specific name resolution(s): \"mntC\"\n");
257 fprintf(output, " -d %s ...\n", decode_as_arg_template);
258 fprintf(output, " \"Decode As\", see the man page for details\n");
259 fprintf(output, " Example: tcp.port==8888,http\n");
261 /*fprintf(output, "\n");*/
262 fprintf(output, "Output:\n");
263 fprintf(output, " -w <outfile|-> write packets to a pcap-format file named \"outfile\"\n");
264 fprintf(output, " (or to the standard output for \"-\")\n");
265 fprintf(output, " -C <config profile> start with specified configuration profile\n");
266 fprintf(output, " -F <output file type> set the output file type, default is libpcap\n");
267 fprintf(output, " an empty \"-F\" option will list the file types\n");
268 fprintf(output, " -V add output of packet tree (Packet Details)\n");
269 fprintf(output, " -S display packets even when writing to a file\n");
270 fprintf(output, " -x add output of hex and ASCII dump (Packet Bytes)\n");
271 fprintf(output, " -T pdml|ps|psml|text|fields\n");
272 fprintf(output, " format of text output (def: text)\n");
273 fprintf(output, " -e <field> field to print if -Tfields selected (e.g. tcp.port);\n");
274 fprintf(output, " this option can be repeated to print multiple fields\n");
275 fprintf(output, " -E<fieldsoption>=<value> set options for output when -Tfields selected:\n");
276 fprintf(output, " header=y|n switch headers on and off\n");
277 fprintf(output, " separator=/t|/s|<char> select tab, space, printable character as separator\n");
278 fprintf(output, " occurrence=f|l|a print first, last or all occurrences of each field\n");
279 fprintf(output, " aggregator=,|/s|<char> select comma, space, printable character as aggregator\n");
280 fprintf(output, " quote=d|s|n select double, single, no quotes for values\n");
281 fprintf(output, " -t ad|a|r|d|dd|e output format of time stamps (def: r: rel. to first)\n");
282 fprintf(output, " -u s|hms output format of seconds (def: s: seconds)\n");
283 fprintf(output, " -l flush standard output after each packet\n");
284 fprintf(output, " -q be more quiet on stdout (e.g. when using statistics)\n");
285 fprintf(output, " -X <key>:<value> eXtension options, see the man page for details\n");
286 fprintf(output, " -z <statistics> various statistics, see the man page for details\n");
288 fprintf(output, "\n");
289 fprintf(output, "Miscellaneous:\n");
290 fprintf(output, " -h display this help and exit\n");
291 fprintf(output, " -v display version info and exit\n");
292 fprintf(output, " -o <name>:<value> ... override preference setting\n");
293 fprintf(output, " -K <keytab> keytab file to use for kerberos decryption\n");
294 fprintf(output, " -G [report] dump one of several available reports and exit\n");
295 fprintf(output, " default report=\"fields\"\n");
296 fprintf(output, " use \"-G ?\" for more help\n");
300 glossary_option_help(void)
306 fprintf(output, "TShark " VERSION "%s\n", wireshark_svnversion);
308 fprintf(output, "\n");
309 fprintf(output, "Usage: tshark -G [report]\n");
310 fprintf(output, "\n");
311 fprintf(output, "Glossary table reports:\n");
312 fprintf(output, " -G [fields] dump glossary in original format and exit\n");
313 fprintf(output, " -G fields2 dump glossary in format 2 and exit\n");
314 fprintf(output, " -G fields3 dump glossary in format 3 and exit\n");
315 fprintf(output, " -G protocols dump protocols in registration database and exit\n");
316 fprintf(output, " -G values dump value, range, true/false strings and exit\n");
317 fprintf(output, " -G decodes dump \"layer type\"/\"decode as\" associations and exit\n");
318 fprintf(output, "\n");
319 fprintf(output, "Preference reports:\n");
320 fprintf(output, " -G defaultprefs dump default preferences and exit\n");
321 fprintf(output, " -G currentprefs dump current preferences and exit\n");
322 fprintf(output, "\n");
327 * For a dissector table, print on the stream described by output,
328 * its short name (which is what's used in the "-d" option) and its
332 display_dissector_table_names(const char *table_name, const char *ui_name,
335 fprintf((FILE *)output, "\t%s (%s)\n", table_name, ui_name);
339 * For a dissector handle, print on the stream described by output,
340 * the filter name (which is what's used in the "-d" option) and the full
341 * name for the protocol that corresponds to this handle.
344 display_dissector_names(const gchar *table _U_, gpointer handle, gpointer output)
347 const gchar* proto_filter_name;
348 const gchar* proto_ui_name;
350 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
352 if (proto_id != -1) {
353 proto_filter_name = proto_get_protocol_filter_name(proto_id);
354 proto_ui_name = proto_get_protocol_name(proto_id);
355 g_assert(proto_filter_name != NULL);
356 g_assert(proto_ui_name != NULL);
358 fprintf((FILE *)output, "\t%s (%s)\n",
365 * The protocol_name_search structure is used by find_protocol_name_func()
366 * to pass parameters and store results
368 struct protocol_name_search{
369 gchar *searched_name; /* Protocol filter name we are looking for */
370 dissector_handle_t matched_handle; /* Handle for a dissector whose protocol has the specified filter name */
371 guint nb_match; /* How many dissectors matched searched_name */
373 typedef struct protocol_name_search *protocol_name_search_t;
376 * This function parses all dissectors associated with a table to find the
377 * one whose protocol has the specified filter name. It is called
378 * as a reference function in a call to dissector_table_foreach_handle.
379 * The name we are looking for, as well as the results, are stored in the
380 * protocol_name_search struct pointed to by user_data.
381 * If called using dissector_table_foreach_handle, we actually parse the
382 * whole list of dissectors.
385 find_protocol_name_func(const gchar *table _U_, gpointer handle, gpointer user_data)
389 const gchar *protocol_filter_name;
390 protocol_name_search_t search_info;
394 search_info = (protocol_name_search_t)user_data;
396 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
397 if (proto_id != -1) {
398 protocol_filter_name = proto_get_protocol_filter_name(proto_id);
399 g_assert(protocol_filter_name != NULL);
400 if (strcmp(protocol_filter_name, search_info->searched_name) == 0) {
402 if (search_info->nb_match == 0) {
403 /* Record this handle only if this is the first match */
404 search_info->matched_handle = (dissector_handle_t)handle; /* Record the handle for this matching dissector */
406 search_info->nb_match++;
412 * Print all layer type names supported.
413 * We send the output to the stream described by the handle output.
417 fprint_all_layer_types(FILE *output)
420 dissector_all_tables_foreach_table(display_dissector_table_names, (gpointer)output);
424 * Print all protocol names supported for a specific layer type.
425 * table_name contains the layer type name in which the search is performed.
426 * We send the output to the stream described by the handle output.
430 fprint_all_protocols_for_layer_types(FILE *output, gchar *table_name)
433 dissector_table_foreach_handle(table_name,
434 display_dissector_names,
439 * The function below parses the command-line parameters for the decode as
440 * feature (a string pointer by cl_param).
441 * It checks the format of the command-line, searches for a matching table
442 * and dissector. If a table/dissector match is not found, we display a
443 * summary of the available tables/dissectors (on stderr) and return FALSE.
444 * If everything is fine, we get the "Decode as" preference activated,
445 * then we return TRUE.
448 add_decode_as(const gchar *cl_param)
452 gchar *decoded_param;
453 gchar *remaining_param;
455 gchar *dissector_str;
456 dissector_handle_t dissector_matching;
457 dissector_table_t table_matching;
458 ftenum_t dissector_table_selector_type;
459 struct protocol_name_search user_protocol_name;
461 /* The following code will allocate and copy the command-line options in a string pointed by decoded_param */
464 decoded_param = g_strdup(cl_param);
465 g_assert(decoded_param);
468 /* The lines below will parse this string (modifying it) to extract all
469 necessary information. Note that decoded_param is still needed since
470 strings are not copied - we just save pointers. */
472 /* This section extracts a layer type (table_name) from decoded_param */
473 table_name = decoded_param; /* Layer type string starts from beginning */
475 remaining_param = strchr(table_name, '=');
476 if (remaining_param == NULL) {
477 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
478 /* If the argument does not follow the template, carry on anyway to check
479 if the table name is at least correct. If remaining_param is NULL,
480 we'll exit anyway further down */
483 *remaining_param = '\0'; /* Terminate the layer type string (table_name) where '=' was detected */
486 /* Remove leading and trailing spaces from the table name */
487 while ( table_name[0] == ' ' )
489 while ( table_name[strlen(table_name) - 1] == ' ' )
490 table_name[strlen(table_name) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
492 /* The following part searches a table matching with the layer type specified */
493 table_matching = NULL;
495 /* Look for the requested table */
496 if ( !(*(table_name)) ) { /* Is the table name empty, if so, don't even search for anything, display a message */
497 cmdarg_err("No layer type specified"); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
500 table_matching = find_dissector_table(table_name);
501 if (!table_matching) {
502 cmdarg_err("Unknown layer type -- %s", table_name); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
506 if (!table_matching) {
507 /* Display a list of supported layer types to help the user, if the
508 specified layer type was not found */
509 cmdarg_err("Valid layer types are:");
510 fprint_all_layer_types(stderr);
512 if (remaining_param == NULL || !table_matching) {
513 /* Exit if the layer type was not found, or if no '=' separator was found
515 g_free(decoded_param);
519 if (*(remaining_param + 1) != '=') { /* Check for "==" and not only '=' */
520 cmdarg_err("WARNING: -d requires \"==\" instead of \"=\". Option will be treated as \"%s==%s\"", table_name, remaining_param + 1);
523 remaining_param++; /* Move to the second '=' */
524 *remaining_param = '\0'; /* Remove the second '=' */
526 remaining_param++; /* Position after the layer type string */
528 /* This section extracts a selector value (selector_str) from decoded_param */
530 selector_str = remaining_param; /* Next part starts with the selector number */
532 remaining_param = strchr(selector_str, ',');
533 if (remaining_param == NULL) {
534 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
535 /* If the argument does not follow the template, carry on anyway to check
536 if the selector value is at least correct. If remaining_param is NULL,
537 we'll exit anyway further down */
540 *remaining_param = '\0'; /* Terminate the selector number string (selector_str) where ',' was detected */
543 dissector_table_selector_type = get_dissector_table_selector_type(table_name);
545 switch (dissector_table_selector_type) {
551 /* The selector for this table is an unsigned number. Parse it as such.
552 There's no need to remove leading and trailing spaces from the
553 selector number string, because sscanf will do that for us. */
554 if ( sscanf(selector_str, "%u", &selector) != 1 ) {
555 cmdarg_err("Invalid selector number \"%s\"", selector_str);
556 g_free(decoded_param);
564 /* The selector for this table is a string. */
568 /* There are currently no dissector tables with any types other
569 than the ones listed above. */
570 g_assert_not_reached();
573 if (remaining_param == NULL) {
574 /* Exit if no ',' separator was found (see above) */
575 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
576 fprint_all_protocols_for_layer_types(stderr, table_name);
577 g_free(decoded_param);
581 remaining_param++; /* Position after the selector number string */
583 /* This section extracts a protocol filter name (dissector_str) from decoded_param */
585 dissector_str = remaining_param; /* All the rest of the string is the dissector (decode as protocol) name */
587 /* Remove leading and trailing spaces from the dissector name */
588 while ( dissector_str[0] == ' ' )
590 while ( dissector_str[strlen(dissector_str) - 1] == ' ' )
591 dissector_str[strlen(dissector_str) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
593 dissector_matching = NULL;
595 /* We now have a pointer to the handle for the requested table inside the variable table_matching */
596 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 */
597 cmdarg_err("No protocol name specified"); /* Note, we don't exit here, but dissector_matching will remain NULL, so we exit below */
600 user_protocol_name.nb_match = 0;
601 user_protocol_name.searched_name = dissector_str;
602 user_protocol_name.matched_handle = NULL;
604 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 */
606 if (user_protocol_name.nb_match != 0) {
607 dissector_matching = user_protocol_name.matched_handle;
608 if (user_protocol_name.nb_match > 1) {
609 cmdarg_err("WARNING: Protocol \"%s\" matched %u dissectors, first one will be used", dissector_str, user_protocol_name.nb_match);
613 /* OK, check whether the problem is that there isn't any such
614 protocol, or that there is but it's not specified as a protocol
615 that's valid for that dissector table.
616 Note, we don't exit here, but dissector_matching will remain NULL,
618 if (proto_get_id_by_filter_name(dissector_str) == -1) {
619 /* No such protocol */
620 cmdarg_err("Unknown protocol -- \"%s\"", dissector_str);
622 cmdarg_err("Protocol \"%s\" isn't valid for layer type \"%s\"",
623 dissector_str, table_name);
628 if (!dissector_matching) {
629 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
630 fprint_all_protocols_for_layer_types(stderr, table_name);
631 g_free(decoded_param);
635 /* This is the end of the code that parses the command-line options.
636 All information is now stored in the variables:
640 The above variables that are strings are still pointing to areas within
641 decoded_parm. decoded_parm thus still needs to be kept allocated in
642 until we stop needing these variables
643 decoded_param will be deallocated at each exit point of this function */
646 /* We now have a pointer to the handle for the requested dissector
647 (requested protocol) inside the variable dissector_matching */
648 switch (dissector_table_selector_type) {
654 /* The selector for this table is an unsigned number. */
655 dissector_change_uint(table_name, selector, dissector_matching);
661 /* The selector for this table is a string. */
662 dissector_change_string(table_name, selector_str, dissector_matching);
666 /* There are currently no dissector tables with any types other
667 than the ones listed above. */
668 g_assert_not_reached();
670 g_free(decoded_param); /* "Decode As" rule has been succesfully added */
675 tshark_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
676 const gchar *message, gpointer user_data)
678 /* ignore log message, if log_level isn't interesting based
679 upon the console log preferences.
680 If the preferences haven't been loaded loaded yet, display the
683 The default console_log_level preference value is such that only
684 ERROR, CRITICAL and WARNING level messages are processed;
685 MESSAGE, INFO and DEBUG level messages are ignored.
687 XXX: Aug 07, 2009: Prior tshark g_log code was hardwired to process only
688 ERROR and CRITICAL level messages so the current code is a behavioral
689 change. The current behavior is the same as in Wireshark.
691 if((log_level & G_LOG_LEVEL_MASK & prefs.console_log_level) == 0 &&
692 prefs.console_log_level != 0) {
696 g_log_default_handler(log_domain, log_level, message, user_data);
701 output_file_description(const char *fname)
703 char *save_file_string;
705 /* Get a string that describes what we're writing to */
706 if (strcmp(fname, "-") == 0) {
707 /* We're writing to the standard output */
708 save_file_string = g_strdup("standard output");
710 /* We're writing to a file with the name in save_file */
711 save_file_string = g_strdup_printf("file \"%s\"", fname);
713 return save_file_string;
717 print_current_user(void) {
718 gchar *cur_user, *cur_group;
719 if (started_with_special_privs()) {
720 cur_user = get_cur_username();
721 cur_group = get_cur_groupname();
722 fprintf(stderr, "Running as user \"%s\" and group \"%s\".",
723 cur_user, cur_group);
726 if (running_with_special_privs()) {
727 fprintf(stderr, " This could be dangerous.");
729 fprintf(stderr, "\n");
734 check_capture_privs(void) {
737 /* Warn the user if npf.sys isn't loaded. */
738 if (!npf_sys_is_running() && get_os_major_version() >= 6) {
739 fprintf(stderr, "The NPF driver isn't running. You may have trouble "
740 "capturing or\nlisting interfaces.\n");
746 show_version(GString *comp_info_str, GString *runtime_info_str)
748 printf("TShark " VERSION "%s\n"
755 wireshark_svnversion, get_copyright_info(), comp_info_str->str,
756 runtime_info_str->str);
760 main(int argc, char *argv[])
762 char *init_progfile_dir_error;
764 gboolean arg_error = FALSE;
770 char *gpf_path, *pf_path;
771 char *gdp_path, *dp_path;
772 int gpf_open_errno, gpf_read_errno;
773 int pf_open_errno, pf_read_errno;
774 int gdp_open_errno, gdp_read_errno;
775 int dp_open_errno, dp_read_errno;
779 gboolean list_link_layer_types = FALSE;
780 gboolean start_capture = FALSE;
785 gboolean capture_option_specified = FALSE;
787 gboolean quiet = FALSE;
788 int out_file_type = WTAP_FILE_PCAP;
789 gchar *cf_name = NULL, *rfilter = NULL;
790 #ifdef HAVE_PCAP_OPEN_DEAD
791 struct bpf_program fcode;
793 dfilter_t *rfcode = NULL;
796 GLogLevelFlags log_flags;
800 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
801 #define OPTSTRING_B "B:"
803 #define OPTSTRING_B ""
804 #endif /* _WIN32 or HAVE_PCAP_CREATE */
805 #else /* HAVE_LIBPCAP */
806 #define OPTSTRING_B ""
807 #endif /* HAVE_LIBPCAP */
809 #ifdef HAVE_PCAP_CREATE
810 #define OPTSTRING_I "I"
812 #define OPTSTRING_I ""
815 #define OPTSTRING "a:b:" OPTSTRING_B "c:C:d:De:E:f:F:G:hi:" OPTSTRING_I "K:lLnN:o:pPqr:R:s:St:T:u:vVw:xX:y:z:"
817 static const char optstring[] = OPTSTRING;
820 * Get credential information for later use.
822 init_process_policies();
825 * Attempt to get the pathname of the executable file.
827 init_progfile_dir_error = init_progfile_dir(argv[0], main);
828 if (init_progfile_dir_error != NULL) {
829 fprintf(stderr, "tshark: Can't get pathname of tshark program: %s.\n",
830 init_progfile_dir_error);
834 * In order to have the -X opts assigned before the wslua machine starts
835 * we need to call getopts before epan_init() gets called.
838 optind_initial = optind;
840 while ((opt = getopt(argc, argv, optstring)) != -1) {
842 case 'C': /* Configuration Profile */
843 if (profile_exists (optarg)) {
844 set_profile_name (optarg);
846 cmdarg_err("Configuration Profile \"%s\" does not exist", optarg);
858 optind = optind_initial;
863 /** Send All g_log messages to our own handler **/
867 G_LOG_LEVEL_CRITICAL|
872 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
874 g_log_set_handler(NULL,
876 tshark_log_handler, NULL /* user_data */);
877 g_log_set_handler(LOG_DOMAIN_MAIN,
879 tshark_log_handler, NULL /* user_data */);
882 g_log_set_handler(LOG_DOMAIN_CAPTURE,
884 tshark_log_handler, NULL /* user_data */);
885 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
887 tshark_log_handler, NULL /* user_data */);
890 initialize_funnel_ops();
893 capture_opts_init(&global_capture_opts, &cfile);
896 timestamp_set_type(TS_RELATIVE);
897 timestamp_set_precision(TS_PREC_AUTO);
898 timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
900 /* Register all dissectors; we must do this before checking for the
901 "-G" flag, as the "-G" flag dumps information registered by the
902 dissectors, and we must do it before we read the preferences, in
903 case any dissectors register preferences. */
904 epan_init(register_all_protocols, register_all_protocol_handoffs, NULL, NULL,
905 failure_message, open_failure_message, read_failure_message,
906 write_failure_message);
908 /* Register all tap listeners; we do this before we parse the arguments,
909 as the "-z" argument can specify a registered tap. */
911 /* we register the plugin taps before the other taps because
912 stats_tree taps plugins will be registered as tap listeners
913 by stats_tree_stat.c and need to registered before that */
915 register_all_plugin_tap_listeners();
917 register_all_tap_listeners();
919 /* Now register the preferences for any non-dissector modules.
920 We must do that before we read the preferences as well. */
921 prefs_register_modules();
923 /* If invoked with the "-G" flag, we dump out information based on
924 the argument to the "-G" flag; if no argument is specified,
925 for backwards compatibility we dump out a glossary of display
928 XXX - we do this here, for now, to support "-G" with no arguments.
929 If none of our build or other processes uses "-G" with no arguments,
930 we can just process it with the other arguments. */
931 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
932 proto_initialize_all_prefixes();
935 proto_registrar_dump_fields(1);
937 if (strcmp(argv[2], "fields") == 0)
938 proto_registrar_dump_fields(1);
939 else if (strcmp(argv[2], "fields2") == 0)
940 proto_registrar_dump_fields(2);
941 else if (strcmp(argv[2], "fields3") == 0)
942 proto_registrar_dump_fields(3);
943 else if (strcmp(argv[2], "protocols") == 0)
944 proto_registrar_dump_protocols();
945 else if (strcmp(argv[2], "values") == 0)
946 proto_registrar_dump_values();
947 else if (strcmp(argv[2], "decodes") == 0)
948 dissector_dump_decodes();
949 else if (strcmp(argv[2], "defaultprefs") == 0)
951 else if (strcmp(argv[2], "?") == 0)
952 glossary_option_help();
953 else if (strcmp(argv[2], "-?") == 0)
954 glossary_option_help();
955 else if (strcmp(argv[2], "currentprefs") == 0) {
956 read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
957 &pf_open_errno, &pf_read_errno, &pf_path);
960 cmdarg_err("Invalid \"%s\" option for -G flag, enter -G ? for more help.", argv[2]);
967 /* Set the C-language locale to the native environment. */
968 setlocale(LC_ALL, "");
970 prefs_p = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
971 &pf_open_errno, &pf_read_errno, &pf_path);
972 if (gpf_path != NULL) {
973 if (gpf_open_errno != 0) {
974 cmdarg_err("Can't open global preferences file \"%s\": %s.",
975 pf_path, strerror(gpf_open_errno));
977 if (gpf_read_errno != 0) {
978 cmdarg_err("I/O error reading global preferences file \"%s\": %s.",
979 pf_path, strerror(gpf_read_errno));
982 if (pf_path != NULL) {
983 if (pf_open_errno != 0) {
984 cmdarg_err("Can't open your preferences file \"%s\": %s.", pf_path,
985 strerror(pf_open_errno));
987 if (pf_read_errno != 0) {
988 cmdarg_err("I/O error reading your preferences file \"%s\": %s.",
989 pf_path, strerror(pf_read_errno));
995 /* Set the name resolution code's flags from the preferences. */
996 gbl_resolv_flags = prefs_p->name_resolve;
998 /* Read the disabled protocols file. */
999 read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
1000 &dp_path, &dp_open_errno, &dp_read_errno);
1001 if (gdp_path != NULL) {
1002 if (gdp_open_errno != 0) {
1003 cmdarg_err("Could not open global disabled protocols file\n\"%s\": %s.",
1004 gdp_path, strerror(gdp_open_errno));
1006 if (gdp_read_errno != 0) {
1007 cmdarg_err("I/O error reading global disabled protocols file\n\"%s\": %s.",
1008 gdp_path, strerror(gdp_read_errno));
1012 if (dp_path != NULL) {
1013 if (dp_open_errno != 0) {
1015 "Could not open your disabled protocols file\n\"%s\": %s.", dp_path,
1016 strerror(dp_open_errno));
1018 if (dp_read_errno != 0) {
1020 "I/O error reading your disabled protocols file\n\"%s\": %s.", dp_path,
1021 strerror(dp_read_errno));
1026 check_capture_privs();
1028 cap_file_init(&cfile);
1030 /* Print format defaults to this. */
1031 print_format = PR_FMT_TEXT;
1033 output_fields = output_fields_new();
1035 /* Now get our args */
1036 while ((opt = getopt(argc, argv, optstring)) != -1) {
1038 case 'a': /* autostop criteria */
1039 case 'b': /* Ringbuffer option */
1040 case 'c': /* Capture x packets */
1041 case 'f': /* capture filter */
1042 case 'i': /* Use interface x */
1043 case 'p': /* Don't capture in promiscuous mode */
1044 #ifdef HAVE_PCAP_CREATE
1045 case 'I': /* Capture in monitor mode, if available */
1047 case 's': /* Set the snapshot (capture) length */
1048 case 'w': /* Write to capture file x */
1049 case 'y': /* Set the pcap data link type */
1050 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
1051 case 'B': /* Buffer size */
1052 #endif /* _WIN32 or HAVE_PCAP_CREATE */
1054 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
1059 capture_option_specified = TRUE;
1064 /* Configuration profile settings were already processed just ignore them this time*/
1066 case 'd': /* Decode as rule */
1067 if (!add_decode_as(optarg))
1070 #if defined(HAVE_HEIMDAL_KERBEROS) || defined(HAVE_MIT_KERBEROS)
1071 case 'K': /* Kerberos keytab file */
1072 read_keytab_file(optarg);
1075 case 'D': /* Print a list of capture devices and exit */
1077 if_list = capture_interface_list(&err, &err_str);
1078 if (if_list == NULL) {
1080 case CANT_GET_INTERFACE_LIST:
1081 cmdarg_err("%s", err_str);
1085 case NO_INTERFACES_FOUND:
1086 cmdarg_err("There are no interfaces on which a capture can be done");
1091 capture_opts_print_interfaces(if_list);
1092 free_interface_list(if_list);
1095 capture_option_specified = TRUE;
1101 output_fields_add(output_fields, optarg);
1105 if(!output_fields_set_option(output_fields, optarg)) {
1106 cmdarg_err("\"%s\" is not a valid field output option=value pair.", optarg);
1107 output_fields_list_options(stderr);
1112 out_file_type = wtap_short_string_to_file_type(optarg);
1113 if (out_file_type < 0) {
1114 cmdarg_err("\"%s\" isn't a valid capture file type", optarg);
1115 list_capture_types();
1119 case 'h': /* Print help and exit */
1123 case 'l': /* "Line-buffer" standard output */
1124 /* This isn't line-buffering, strictly speaking, it's just
1125 flushing the standard output after the information for
1126 each packet is printed; however, that should be good
1127 enough for all the purposes to which "-l" is put (and
1128 is probably actually better for "-V", as it does fewer
1131 See the comment in "process_packet()" for an explanation of
1132 why we do that, and why we don't just use "setvbuf()" to
1133 make the standard output line-buffered (short version: in
1134 Windows, "line-buffered" is the same as "fully-buffered",
1135 and the output buffer is only flushed when it fills up). */
1136 line_buffered = TRUE;
1138 case 'L': /* Print list of link-layer types and exit */
1140 list_link_layer_types = TRUE;
1142 capture_option_specified = TRUE;
1146 #if GLIB_CHECK_VERSION(2,10,0)
1147 case 'P': /* Perform two pass analysis */
1148 perform_two_pass_analysis = TRUE;
1151 case 'n': /* No name resolution */
1152 gbl_resolv_flags = RESOLV_NONE;
1154 case 'N': /* Select what types of addresses/port #s to resolve */
1155 if (gbl_resolv_flags == RESOLV_ALL)
1156 gbl_resolv_flags = RESOLV_NONE;
1157 badopt = string_to_name_resolve(optarg, &gbl_resolv_flags);
1158 if (badopt != '\0') {
1159 cmdarg_err("-N specifies unknown resolving option '%c';",
1161 cmdarg_err_cont( " Valid options are 'm', 'n', 't', and 'C'");
1165 case 'o': /* Override preference from command line */
1166 switch (prefs_set_pref(optarg)) {
1171 case PREFS_SET_SYNTAX_ERR:
1172 cmdarg_err("Invalid -o flag \"%s\"", optarg);
1176 case PREFS_SET_NO_SUCH_PREF:
1177 case PREFS_SET_OBSOLETE:
1178 cmdarg_err("-o flag \"%s\" specifies unknown preference", optarg);
1183 case 'q': /* Quiet */
1186 case 'r': /* Read capture file x */
1187 cf_name = g_strdup(optarg);
1189 case 'R': /* Read file filter */
1192 case 'S': /* show packets in real time */
1193 print_packet_info = TRUE;
1195 case 't': /* Time stamp type */
1196 if (strcmp(optarg, "r") == 0)
1197 timestamp_set_type(TS_RELATIVE);
1198 else if (strcmp(optarg, "a") == 0)
1199 timestamp_set_type(TS_ABSOLUTE);
1200 else if (strcmp(optarg, "ad") == 0)
1201 timestamp_set_type(TS_ABSOLUTE_WITH_DATE);
1202 else if (strcmp(optarg, "d") == 0)
1203 timestamp_set_type(TS_DELTA);
1204 else if (strcmp(optarg, "dd") == 0)
1205 timestamp_set_type(TS_DELTA_DIS);
1206 else if (strcmp(optarg, "e") == 0)
1207 timestamp_set_type(TS_EPOCH);
1209 cmdarg_err("Invalid time stamp type \"%s\"",
1211 cmdarg_err_cont("It must be \"r\" for relative, \"a\" for absolute,");
1212 cmdarg_err_cont("\"ad\" for absolute with date, or \"d\" for delta.");
1216 case 'T': /* printing Type */
1217 if (strcmp(optarg, "text") == 0) {
1218 output_action = WRITE_TEXT;
1219 print_format = PR_FMT_TEXT;
1220 } else if (strcmp(optarg, "ps") == 0) {
1221 output_action = WRITE_TEXT;
1222 print_format = PR_FMT_PS;
1223 } else if (strcmp(optarg, "pdml") == 0) {
1224 output_action = WRITE_XML;
1226 } else if (strcmp(optarg, "psml") == 0) {
1227 output_action = WRITE_XML;
1229 } else if(strcmp(optarg, "fields") == 0) {
1230 output_action = WRITE_FIELDS;
1231 verbose = TRUE; /* Need full tree info */
1233 cmdarg_err("Invalid -T parameter.");
1234 cmdarg_err_cont("It must be \"ps\", \"text\", \"pdml\", \"psml\" or \"fields\".");
1238 case 'u': /* Seconds type */
1239 if (strcmp(optarg, "s") == 0)
1240 timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
1241 else if (strcmp(optarg, "hms") == 0)
1242 timestamp_set_seconds_type(TS_SECONDS_HOUR_MIN_SEC);
1244 cmdarg_err("Invalid seconds type \"%s\"", optarg);
1245 cmdarg_err_cont("It must be \"s\" for seconds or \"hms\" for hours, minutes and seconds.");
1249 case 'v': /* Show version and exit */
1251 GString *comp_info_str;
1252 GString *runtime_info_str;
1253 /* Assemble the compile-time version information string */
1254 comp_info_str = g_string_new("Compiled ");
1255 get_compiled_version_info(comp_info_str, NULL, epan_get_compiled_version_info);
1257 /* Assemble the run-time version information string */
1258 runtime_info_str = g_string_new("Running ");
1259 get_runtime_version_info(runtime_info_str, NULL);
1260 show_version(comp_info_str, runtime_info_str);
1261 g_string_free(comp_info_str, TRUE);
1262 g_string_free(runtime_info_str, TRUE);
1266 case 'V': /* Verbose */
1268 /* The user asked for a verbose output, so let's ensure they get it,
1269 * even if they're writing to a file.
1271 print_packet_info = TRUE;
1273 case 'x': /* Print packet data in hex (and ASCII) */
1275 /* The user asked for hex output, so let's ensure they get it,
1276 * even if they're writing to a file.
1278 print_packet_info = TRUE;
1283 /* We won't call the init function for the stat this soon
1284 as it would disallow MATE's fields (which are registered
1285 by the preferences set callback) from being used as
1286 part of a tap filter. Instead, we just add the argument
1287 to a list of stat arguments. */
1288 if (!process_stat_cmd_arg(optarg)) {
1289 cmdarg_err("invalid -z argument.");
1290 cmdarg_err_cont(" -z argument must be one of :");
1291 list_stat_cmd_args();
1296 case '?': /* Bad flag - print usage message */
1299 list_capture_types();
1309 /* If we specified output fields, but not the output field type... */
1310 if(WRITE_FIELDS != output_action && 0 != output_fields_num_fields(output_fields)) {
1311 cmdarg_err("Output fields were specified with \"-e\", "
1312 "but \"-Tfields\" was not specified.");
1314 } else if(WRITE_FIELDS == output_action && 0 == output_fields_num_fields(output_fields)) {
1315 cmdarg_err("\"-Tfields\" was specified, but no fields were "
1316 "specified with \"-e\".");
1321 /* If no capture filter or read filter has been specified, and there are
1322 still command-line arguments, treat them as the tokens of a capture
1323 filter (if no "-r" flag was specified) or a read filter (if a "-r"
1324 flag was specified. */
1325 if (optind < argc) {
1326 if (cf_name != NULL) {
1327 if (rfilter != NULL) {
1328 cmdarg_err("Read filters were specified both with \"-R\" "
1329 "and with additional command-line arguments");
1332 rfilter = get_args_as_string(argc, argv, optind);
1335 if (global_capture_opts.has_cfilter) {
1336 cmdarg_err("Capture filters were specified both with \"-f\""
1337 " and with additional command-line arguments");
1340 global_capture_opts.has_cfilter = TRUE;
1341 global_capture_opts.cfilter = get_args_as_string(argc, argv, optind);
1343 capture_option_specified = TRUE;
1349 if (!global_capture_opts.saving_to_file) {
1350 /* We're not saving the capture to a file; if "-q" wasn't specified,
1351 we should print packet information */
1353 print_packet_info = TRUE;
1355 /* We're saving to a file; if we're writing to the standard output.
1356 and we'll also be writing dissected packets to the standard
1357 output, reject the request. At best, we could redirect that
1358 to the standard error; we *can't* write both to the standard
1359 output and have either of them be useful. */
1360 if (strcmp(global_capture_opts.save_file, "-") == 0 && print_packet_info) {
1361 cmdarg_err("You can't write both raw packet data and dissected packets"
1362 " to the standard output.");
1367 /* We're not saving the capture to a file; if "-q" wasn't specified,
1368 we should print packet information */
1370 print_packet_info = TRUE;
1373 #ifndef HAVE_LIBPCAP
1374 if (capture_option_specified)
1375 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1382 /* We don't support capture filters when reading from a capture file
1383 (the BPF compiler doesn't support all link-layer types that we
1384 support in capture files we read). */
1386 if (cf_name != NULL) {
1387 if (global_capture_opts.has_cfilter) {
1388 cmdarg_err("Only read filters, not capture filters, "
1389 "can be specified when reading a capture file.");
1396 if (output_action != WRITE_TEXT) {
1397 cmdarg_err("Raw packet hex data can only be printed as text or PostScript");
1403 if (list_link_layer_types) {
1404 /* We're supposed to list the link-layer types for an interface;
1405 did the user also specify a capture file to be read? */
1407 /* Yes - that's bogus. */
1408 cmdarg_err("You can't specify -L and a capture file to be read.");
1411 /* No - did they specify a ring buffer option? */
1412 if (global_capture_opts.multi_files_on) {
1413 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
1419 * "-r" was specified, so we're reading a capture file.
1420 * Capture options don't apply here.
1422 if (global_capture_opts.multi_files_on) {
1423 cmdarg_err("Multiple capture files requested, but "
1424 "a capture isn't being done.");
1427 if (global_capture_opts.has_file_duration) {
1428 cmdarg_err("Switching capture files after a time interval was specified, but "
1429 "a capture isn't being done.");
1432 if (global_capture_opts.has_ring_num_files) {
1433 cmdarg_err("A ring buffer of capture files was specified, but "
1434 "a capture isn't being done.");
1437 if (global_capture_opts.has_autostop_files) {
1438 cmdarg_err("A maximum number of capture files was specified, but "
1439 "a capture isn't being done.");
1443 /* Note: TShark now allows the restriction of a _read_ file by packet count
1444 * and byte count as well as a write file. Other autostop options remain valid
1445 * only for a write file.
1447 if (global_capture_opts.has_autostop_duration) {
1448 cmdarg_err("A maximum capture time was specified, but "
1449 "a capture isn't being done.");
1454 * "-r" wasn't specified, so we're doing a live capture.
1456 if (global_capture_opts.saving_to_file) {
1457 /* They specified a "-w" flag, so we'll be saving to a capture file. */
1459 /* When capturing, we only support writing libpcap format. */
1460 if (out_file_type != WTAP_FILE_PCAP) {
1461 cmdarg_err("Live captures can only be saved in libpcap format.");
1464 if (global_capture_opts.multi_files_on) {
1465 /* Multiple-file mode doesn't work under certain conditions:
1466 a) it doesn't work if you're writing to the standard output;
1467 b) it doesn't work if you're writing to a pipe;
1469 if (strcmp(global_capture_opts.save_file, "-") == 0) {
1470 cmdarg_err("Multiple capture files requested, but "
1471 "the capture is being written to the standard output.");
1474 if (global_capture_opts.output_to_pipe) {
1475 cmdarg_err("Multiple capture files requested, but "
1476 "the capture file is a pipe.");
1479 if (!global_capture_opts.has_autostop_filesize &&
1480 !global_capture_opts.has_file_duration) {
1481 cmdarg_err("Multiple capture files requested, but "
1482 "no maximum capture file size or duration was specified.");
1486 /* Currently, we don't support read filters when capturing
1487 and saving the packets. */
1488 if (rfilter != NULL) {
1489 cmdarg_err("Read filters aren't supported when capturing and saving the captured packets.");
1493 /* They didn't specify a "-w" flag, so we won't be saving to a
1494 capture file. Check for options that only make sense if
1495 we're saving to a file. */
1496 if (global_capture_opts.has_autostop_filesize) {
1497 cmdarg_err("Maximum capture file size specified, but "
1498 "capture isn't being saved to a file.");
1501 if (global_capture_opts.multi_files_on) {
1502 cmdarg_err("Multiple capture files requested, but "
1503 "the capture isn't being saved to a file.");
1512 /* Start windows sockets */
1513 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1516 /* Notify all registered modules that have had any of their preferences
1517 changed either from one of the preferences file or from the command
1518 line that their preferences have changed. */
1521 /* At this point MATE will have registered its field array so we can
1522 have a tap filter with one of MATE's late-registered fields as part
1523 of the filter. We can now process all the "-z" arguments. */
1524 start_requested_stats();
1527 /* We currently don't support taps, or printing dissected packets,
1528 if we're writing to a pipe. */
1529 if (global_capture_opts.saving_to_file &&
1530 global_capture_opts.output_to_pipe) {
1531 if (have_tap_listeners()) {
1532 cmdarg_err("Taps aren't supported when saving to a pipe.");
1535 if (print_packet_info) {
1536 cmdarg_err("Printing dissected packets isn't supported when saving to a pipe.");
1542 /* disabled protocols as per configuration file */
1543 if (gdp_path == NULL && dp_path == NULL) {
1544 set_disabled_protos_list();
1547 /* Build the column format array */
1548 build_column_format_array(&cfile.cinfo, prefs_p->num_cols, TRUE);
1551 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
1552 capture_opts_trim_ring_num_files(&global_capture_opts);
1555 if (rfilter != NULL) {
1556 if (!dfilter_compile(rfilter, &rfcode)) {
1557 cmdarg_err("%s", dfilter_error_msg);
1559 #ifdef HAVE_PCAP_OPEN_DEAD
1563 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1565 if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1567 " Note: That display filter code looks like a valid capture filter;");
1569 " maybe you mixed them up?");
1578 cfile.rfcode = rfcode;
1580 if (print_packet_info) {
1581 /* If we're printing as text or PostScript, we have
1582 to create a print stream. */
1583 if (output_action == WRITE_TEXT) {
1584 switch (print_format) {
1587 print_stream = print_stream_text_stdio_new(stdout);
1591 print_stream = print_stream_ps_stdio_new(stdout);
1595 g_assert_not_reached();
1600 /* We have to dissect each packet if:
1602 we're printing information about each packet;
1604 we're using a read filter on the packets;
1606 we're using any taps. */
1607 do_dissection = print_packet_info || rfcode || have_tap_listeners();
1611 * We're reading a capture file.
1615 * Immediately relinquish any special privileges we have; we must not
1616 * be allowed to read any capture files the user running TShark
1619 relinquish_special_privs_perm();
1620 print_current_user();
1622 if (cf_open(&cfile, cf_name, FALSE, &err) != CF_OK) {
1627 /* Set timestamp precision; there should arguably be a command-line
1628 option to let the user set this. */
1629 switch(wtap_file_tsprecision(cfile.wth)) {
1630 case(WTAP_FILE_TSPREC_SEC):
1631 timestamp_set_precision(TS_PREC_AUTO_SEC);
1633 case(WTAP_FILE_TSPREC_DSEC):
1634 timestamp_set_precision(TS_PREC_AUTO_DSEC);
1636 case(WTAP_FILE_TSPREC_CSEC):
1637 timestamp_set_precision(TS_PREC_AUTO_CSEC);
1639 case(WTAP_FILE_TSPREC_MSEC):
1640 timestamp_set_precision(TS_PREC_AUTO_MSEC);
1642 case(WTAP_FILE_TSPREC_USEC):
1643 timestamp_set_precision(TS_PREC_AUTO_USEC);
1645 case(WTAP_FILE_TSPREC_NSEC):
1646 timestamp_set_precision(TS_PREC_AUTO_NSEC);
1649 g_assert_not_reached();
1652 /* Process the packets in the file */
1654 err = load_cap_file(&cfile, global_capture_opts.save_file, out_file_type,
1655 global_capture_opts.has_autostop_packets ? global_capture_opts.autostop_packets : 0,
1656 global_capture_opts.has_autostop_filesize ? global_capture_opts.autostop_filesize : 0);
1658 err = load_cap_file(&cfile, NULL, out_file_type, 0, 0);
1661 /* We still dump out the results of taps, etc., as we might have
1662 read some packets; however, we exit with an error status. */
1666 /* No capture file specified, so we're supposed to do a live capture
1667 (or get a list of link-layer types for a live capture device);
1668 do we have support for live captures? */
1675 cmdarg_err("WinPcap couldn't be found.");
1676 detailed_err = cant_load_winpcap_err("TShark");
1677 cmdarg_err_cont("%s", detailed_err);
1678 g_free(detailed_err);
1683 /* trim the interface name and exit if that failed */
1684 if (!capture_opts_trim_iface(&global_capture_opts,
1685 (prefs_p->capture_device) ? get_if_name(prefs_p->capture_device) : NULL)) {
1689 /* if requested, list the link layer types and exit */
1690 if (list_link_layer_types) {
1691 /* Get the list of link-layer types for the capture device. */
1692 if_capabilities_t *caps;
1694 caps = capture_get_if_capabilities(global_capture_opts.iface,
1695 global_capture_opts.monitor_mode,
1698 cmdarg_err("%s", err_str);
1702 if (caps->data_link_types == NULL) {
1703 cmdarg_err("The capture device \"%s\" has no data link types.", global_capture_opts.iface);
1706 capture_opts_print_if_capabilities(caps,
1707 global_capture_opts.monitor_mode);
1708 free_if_capabilities(caps);
1712 if (print_packet_info) {
1713 if (!write_preamble(NULL)) {
1714 show_print_file_io_error(errno);
1717 } else if (!quiet) {
1719 * We're not printing information for each packet, and the user
1720 * didn't ask us not to print a count of packets as they arrive,
1721 * so print that count so the user knows that packets are arriving.
1723 * XXX - what if the user wants to do a live capture, doesn't want
1724 * to save it to a file, doesn't want information printed for each
1725 * packet, does want some "-z" statistic, and wants packet counts
1726 * so they know whether they're seeing any packets?
1728 print_packet_counts = TRUE;
1731 /* For now, assume libpcap gives microsecond precision. */
1732 timestamp_set_precision(TS_PREC_AUTO_USEC);
1735 * XXX - this returns FALSE if an error occurred, but it also
1736 * returns FALSE if the capture stops because a time limit
1737 * was reached (and possibly other limits), so we can't assume
1738 * it means an error.
1740 * The capture code is a bit twisty, so it doesn't appear to
1741 * be an easy fix. We just ignore the return value for now.
1742 * Instead, pass on the exit status from the capture child.
1745 exit_status = global_capture_opts.fork_child_status;
1747 if (print_packet_info) {
1748 if (!write_finale()) {
1750 show_print_file_io_error(err);
1754 /* No - complain. */
1755 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1762 #if GLIB_CHECK_VERSION(2,10,0)
1763 if (cfile.plist_start != NULL)
1764 g_slice_free_chain(frame_data, cfile.plist_start, next);
1767 draw_tap_listeners(TRUE);
1768 funnel_dump_all_text_windows();
1771 output_fields_free(output_fields);
1772 output_fields = NULL;
1777 /*#define USE_BROKEN_G_MAIN_LOOP*/
1779 #ifdef USE_BROKEN_G_MAIN_LOOP
1782 gboolean loop_running = FALSE;
1784 guint32 packet_count = 0;
1787 /* XXX - move to the right position / file */
1788 /* read from a pipe (callback) */
1789 typedef gboolean (*pipe_input_cb_t) (gint source, gpointer user_data);
1791 typedef struct pipe_input_tag {
1795 pipe_input_cb_t input_cb;
1796 guint pipe_input_id;
1798 GStaticMutex callback_running;
1802 static pipe_input_t pipe_input;
1805 /* The timer has expired, see if there's stuff to read from the pipe,
1806 if so, do the callback */
1808 pipe_timer_cb(gpointer data)
1812 gboolean result, result1;
1814 pipe_input_t *pipe_input = data;
1815 gint iterations = 0;
1818 g_static_mutex_lock (&pipe_input->callback_running);
1820 /* try to read data from the pipe only 5 times, to avoid blocking */
1821 while(iterations < 5) {
1822 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: new iteration");*/
1824 /* Oddly enough although Named pipes don't work on win9x,
1825 PeekNamedPipe does !!! */
1826 handle = (HANDLE) _get_osfhandle (pipe_input->source);
1827 result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
1829 /* Get the child process exit status */
1830 result1 = GetExitCodeProcess((HANDLE)*(pipe_input->child_process),
1833 /* If the Peek returned an error, or there are bytes to be read
1834 or the childwatcher thread has terminated then call the normal
1836 if (!result || avail > 0 || childstatus != STILL_ACTIVE) {
1838 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: data avail");*/
1840 /* And call the real handler */
1841 if (!pipe_input->input_cb(pipe_input->source, pipe_input->user_data)) {
1842 g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: input pipe closed, iterations: %u", iterations);
1843 /* pipe closed, return false so that the timer is stopped */
1844 g_static_mutex_unlock (&pipe_input->callback_running);
1849 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: no data avail");*/
1850 /* No data, stop now */
1857 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: finished with iterations: %u, new timer", iterations);*/
1859 g_static_mutex_unlock (&pipe_input->callback_running);
1861 /* we didn't stopped the timer, so let it run */
1868 pipe_input_set_handler(gint source, gpointer user_data, int *child_process, pipe_input_cb_t input_cb)
1871 pipe_input.source = source;
1872 pipe_input.child_process = child_process;
1873 pipe_input.user_data = user_data;
1874 pipe_input.input_cb = input_cb;
1877 g_static_mutex_init(&pipe_input.callback_running);
1878 /* Tricky to use pipes in win9x, as no concept of wait. NT can
1879 do this but that doesn't cover all win32 platforms. GTK can do
1880 this but doesn't seem to work over processes. Attempt to do
1881 something similar here, start a timer and check for data on every
1883 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_input_set_handler: new");*/
1884 pipe_input.pipe_input_id = g_timeout_add(200, pipe_timer_cb, &pipe_input);
1894 #ifdef USE_TSHARK_SELECT
1898 struct sigaction action, oldaction;
1902 * XXX - dropping privileges is still required, until code cleanup is done
1904 * remove all dependencies to pcap specific code and using only dumpcap is almost done.
1905 * when it's done, we don't need special privileges to run tshark at all,
1906 * therefore we don't need to drop these privileges
1907 * The only thing we might want to keep is a warning if tshark is run as root,
1908 * as it's no longer necessary and potentially dangerous.
1910 * THE FOLLOWING IS THE FORMER COMMENT WHICH IS NO LONGER REALLY VALID:
1911 * We've opened the capture device, so we shouldn't need any special
1912 * privileges any more; relinquish those privileges.
1914 * XXX - if we have saved set-user-ID support, we should give up those
1915 * privileges immediately, and then reclaim them long enough to get
1916 * a list of network interfaces and to open one, and then give them
1917 * up again, so that stuff we do while processing the argument list,
1918 * reading the user's preferences, loading and starting plugins
1919 * (especially *user* plugins), etc. is done with the user's privileges,
1920 * not special privileges.
1922 relinquish_special_privs_perm();
1923 print_current_user();
1925 /* Cleanup all data structures used for dissection. */
1926 cleanup_dissection();
1927 /* Initialize all data structures used for dissection. */
1931 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1932 SetConsoleCtrlHandler(capture_cleanup, TRUE);
1934 /* Catch SIGINT and SIGTERM and, if we get either of them,
1935 clean up and exit. If SIGHUP isn't being ignored, catch
1936 it too and, if we get it, clean up and exit.
1938 We restart any read that was in progress, so that it doesn't
1939 disrupt reading from the sync pipe. The signal handler tells
1940 the capture child to finish; it will report that it finished,
1941 or will exit abnormally, so we'll stop reading from the sync
1942 pipe, pick up the exit status, and quit. */
1943 action.sa_handler = capture_cleanup;
1944 action.sa_flags = SA_RESTART;
1945 sigemptyset(&action.sa_mask);
1946 sigaction(SIGTERM, &action, NULL);
1947 sigaction(SIGINT, &action, NULL);
1948 sigaction(SIGHUP, NULL, &oldaction);
1949 if (oldaction.sa_handler == SIG_DFL)
1950 sigaction(SIGHUP, &action, NULL);
1953 /* Catch SIGINFO and, if we get it and we're capturing to a file in
1954 quiet mode, report the number of packets we've captured.
1956 Again, restart any read that was in progress, so that it doesn't
1957 disrupt reading from the sync pipe. */
1958 action.sa_handler = report_counts_siginfo;
1959 action.sa_flags = SA_RESTART;
1960 sigemptyset(&action.sa_mask);
1961 sigaction(SIGINFO, &action, NULL);
1962 #endif /* SIGINFO */
1965 global_capture_opts.state = CAPTURE_PREPARING;
1967 /* Let the user know what interface was chosen. */
1968 global_capture_opts.iface_descr = get_interface_descriptive_name(global_capture_opts.iface);
1969 fprintf(stderr, "Capturing on %s\n", global_capture_opts.iface_descr);
1971 ret = sync_pipe_start(&global_capture_opts);
1976 /* the actual capture loop
1978 * XXX - glib doesn't seem to provide any event based loop handling.
1980 * XXX - for whatever reason,
1981 * calling g_main_loop_new() ends up in 100% cpu load.
1983 * But that doesn't matter: in UNIX we can use select() to find an input
1984 * source with something to do.
1986 * But that doesn't matter because we're in a CLI (that doesn't need to
1987 * update a GUI or something at the same time) so it's OK if we block
1988 * trying to read from the pipe.
1990 * So all the stuff in USE_TSHARK_SELECT could be removed unless I'm
1991 * wrong (but I leave it there in case I am...).
1994 #ifdef USE_TSHARK_SELECT
1996 FD_SET(pipe_input.source, &readfds);
1999 loop_running = TRUE;
2001 while (loop_running)
2003 #ifdef USE_TSHARK_SELECT
2004 ret = select(pipe_input.source+1, &readfds, NULL, NULL, NULL);
2010 } else if (ret == 1) {
2012 /* Call the real handler */
2013 if (!pipe_input.input_cb(pipe_input.source, pipe_input.user_data)) {
2014 g_log(NULL, G_LOG_LEVEL_DEBUG, "input pipe closed");
2017 #ifdef USE_TSHARK_SELECT
2026 /* XXX - move the call to main_window_update() out of capture_sync.c */
2027 /* dummy for capture_sync.c to make linker happy */
2028 void main_window_update(void)
2032 /* capture child detected an error */
2034 capture_input_error_message(capture_options *capture_opts _U_, char *error_msg, char *secondary_error_msg)
2036 cmdarg_err("%s", error_msg);
2037 cmdarg_err_cont("%s", secondary_error_msg);
2041 /* capture child detected an capture filter related error */
2043 capture_input_cfilter_error_message(capture_options *capture_opts, char *error_message)
2045 dfilter_t *rfcode = NULL;
2048 if (dfilter_compile(capture_opts->cfilter, &rfcode) && rfcode != NULL) {
2050 "Invalid capture filter: \"%s\"!\n"
2052 "That string looks like a valid display filter; however, it isn't a valid\n"
2053 "capture filter (%s).\n"
2055 "Note that display filters and capture filters don't have the same syntax,\n"
2056 "so you can't use most display filter expressions as capture filters.\n"
2058 "See the User's Guide for a description of the capture filter syntax.",
2059 capture_opts->cfilter, error_message);
2060 dfilter_free(rfcode);
2063 "Invalid capture filter: \"%s\"!\n"
2065 "That string isn't a valid capture filter (%s).\n"
2066 "See the User's Guide for a description of the capture filter syntax.",
2067 capture_opts->cfilter, error_message);
2072 /* capture child tells us we have a new (or the first) capture file */
2074 capture_input_new_file(capture_options *capture_opts, gchar *new_file)
2076 gboolean is_tempfile;
2079 if(capture_opts->state == CAPTURE_PREPARING) {
2080 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "Capture started!");
2082 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "File: \"%s\"", new_file);
2084 g_assert(capture_opts->state == CAPTURE_PREPARING || capture_opts->state == CAPTURE_RUNNING);
2086 /* free the old filename */
2087 if (capture_opts->save_file != NULL) {
2089 /* we start a new capture file, close the old one (if we had one before) */
2090 if( ((capture_file *) capture_opts->cf)->state != FILE_CLOSED) {
2091 if ( ((capture_file *) capture_opts->cf)->wth != NULL) {
2092 wtap_close(((capture_file *) capture_opts->cf)->wth);
2094 ((capture_file *) capture_opts->cf)->state = FILE_CLOSED;
2097 g_free(capture_opts->save_file);
2098 is_tempfile = FALSE;
2100 /* we didn't had a save_file before, must be a tempfile */
2104 /* save the new filename */
2105 capture_opts->save_file = g_strdup(new_file);
2107 /* if we are in real-time mode, open the new file now */
2109 /* Attempt to open the capture file and set up to read from it. */
2110 switch(cf_open(capture_opts->cf, capture_opts->save_file, is_tempfile, &err)) {
2114 /* Don't unlink (delete) the save file - leave it around,
2115 for debugging purposes. */
2116 g_free(capture_opts->save_file);
2117 capture_opts->save_file = NULL;
2122 capture_opts->state = CAPTURE_RUNNING;
2128 /* capture child tells us we have new packets to read */
2130 capture_input_new_packets(capture_options *capture_opts, int to_read)
2136 capture_file *cf = capture_opts->cf;
2137 gboolean filtering_tap_listeners;
2142 * Prevent a SIGINFO handler from writing to the standard error while
2143 * we're doing so or writing to the standard output; instead, have it
2144 * just set a flag telling us to print that information when we're done.
2147 #endif /* SIGINFO */
2149 /* Do we have any tap listeners with filters? */
2150 filtering_tap_listeners = have_filtering_tap_listeners();
2152 /* Get the union of the flags for all tap listeners. */
2153 tap_flags = union_of_tap_listener_flags();
2156 while (to_read-- && cf->wth) {
2157 wtap_cleareof(cf->wth);
2158 ret = wtap_read(cf->wth, &err, &err_info, &data_offset);
2160 /* read from file failed, tell the capture child to stop */
2161 sync_pipe_stop(capture_opts);
2162 wtap_close(cf->wth);
2165 ret = process_packet(cf, data_offset, wtap_phdr(cf->wth),
2166 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2167 filtering_tap_listeners, tap_flags);
2170 /* packet sucessfully read and gone through the "Read Filter" */
2176 * Dumpcap's doing all the work; we're not doing any dissection.
2177 * Count all the packets it wrote.
2179 packet_count += to_read;
2182 if (print_packet_counts) {
2183 /* We're printing packet counts. */
2184 if (packet_count != 0) {
2185 fprintf(stderr, "\r%u ", packet_count);
2186 /* stderr could be line buffered */
2193 * Allow SIGINFO handlers to write.
2198 * If a SIGINFO handler asked us to write out capture counts, do so.
2202 #endif /* SIGINFO */
2208 if (!print_packet_counts) {
2209 /* Report the count only if we aren't printing a packet count
2210 as packets arrive. */
2211 fprintf(stderr, "%u packet%s captured\n", packet_count,
2212 plurality(packet_count, "", "s"));
2215 infoprint = FALSE; /* we just reported it */
2216 #endif /* SIGINFO */
2221 report_counts_siginfo(int signum _U_)
2223 int sav_errno = errno;
2224 /* If we've been told to delay printing, just set a flag asking
2225 that we print counts (if we're supposed to), otherwise print
2226 the count of packets captured (if we're supposed to). */
2233 #endif /* SIGINFO */
2236 /* capture child detected any packet drops? */
2238 capture_input_drops(capture_options *capture_opts _U_, guint32 dropped)
2240 if (print_packet_counts) {
2241 /* We're printing packet counts to stderr.
2242 Send a newline so that we move to the line after the packet count. */
2243 fprintf(stderr, "\n");
2247 /* We're printing packet counts to stderr.
2248 Send a newline so that we move to the line after the packet count. */
2249 fprintf(stderr, "%u packet%s dropped\n", dropped, plurality(dropped, "", "s"));
2255 * Capture child closed its side of the pipe, report any error and
2256 * do the required cleanup.
2259 capture_input_closed(capture_options *capture_opts, gchar *msg)
2262 fprintf(stderr, "tshark: %s\n", msg);
2266 if(capture_opts->cf != NULL && ((capture_file *) capture_opts->cf)->wth != NULL) {
2267 wtap_close(((capture_file *) capture_opts->cf)->wth);
2268 if(((capture_file *) capture_opts->cf)->user_saved == FALSE){
2269 ws_unlink(((capture_file *) capture_opts->cf)->filename);
2272 #ifdef USE_BROKEN_G_MAIN_LOOP
2273 /*g_main_loop_quit(loop);*/
2276 loop_running = FALSE;
2285 capture_cleanup(DWORD ctrltype _U_)
2287 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
2288 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
2289 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
2290 like SIGTERM at least when the machine's shutting down.
2292 For now, we handle them all as indications that we should clean up
2293 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
2296 We must return TRUE so that no other handler - such as one that would
2297 terminate the process - gets called.
2299 XXX - for some reason, typing ^C to TShark, if you run this in
2300 a Cygwin console window in at least some versions of Cygwin,
2301 causes TShark to terminate immediately; this routine gets
2302 called, but the main loop doesn't get a chance to run and
2303 exit cleanly, at least if this is compiled with Microsoft Visual
2304 C++ (i.e., it's a property of the Cygwin console window or Bash;
2305 it happens if TShark is not built with Cygwin - for all I know,
2306 building it with Cygwin may make the problem go away). */
2308 /* tell the capture child to stop */
2309 sync_pipe_stop(&global_capture_opts);
2311 /* don't stop our own loop already here, otherwise status messages and
2312 * cleanup wouldn't be done properly. The child will indicate the stop of
2313 * everything by calling capture_input_closed() later */
2319 capture_cleanup(int signum _U_)
2321 /* tell the capture child to stop */
2322 sync_pipe_stop(&global_capture_opts);
2324 /* don't stop our own loop already here, otherwise status messages and
2325 * cleanup wouldn't be done properly. The child will indicate the stop of
2326 * everything by calling capture_input_closed() later */
2329 #endif /* HAVE_LIBPCAP */
2331 #if GLIB_CHECK_VERSION(2,10,0)
2333 process_packet_first_pass(capture_file *cf,
2334 gint64 offset, const struct wtap_pkthdr *whdr,
2335 union wtap_pseudo_header *pseudo_header, const guchar *pd)
2337 frame_data *fdata = g_slice_new(frame_data);
2341 /* Count this packet. */
2344 /* If we're not running a display filter and we're not printing any
2345 packet information, we don't need to do a dissection. This means
2346 that all packets can be marked as 'passed'. */
2349 frame_data_init(fdata, cf->count, whdr, offset, cum_bytes);
2351 /* If we're going to print packet information, or we're going to
2352 run a read filter, or we're going to process taps, set up to
2353 do a dissection and do so. */
2354 if (do_dissection) {
2355 if (gbl_resolv_flags)
2356 /* Grab any resolved addresses */
2357 host_name_lookup_process(NULL);
2359 /* The protocol tree will be "visible", i.e., printed, only if we're
2360 printing packet details, which is true if we're printing stuff
2361 ("print_packet_info" is true) and we're in verbose mode ("verbose"
2363 epan_dissect_init(&edt, FALSE, FALSE);
2365 /* If we're running a read filter, prime the epan_dissect_t with that
2368 epan_dissect_prime_dfilter(&edt, cf->rfcode);
2370 frame_data_set_before_dissect(fdata, &cf->elapsed_time,
2371 &first_ts, &prev_dis_ts, &prev_cap_ts);
2373 epan_dissect_run(&edt, pseudo_header, pd, fdata, NULL);
2375 /* Run the read filter if we have one. */
2377 passed = dfilter_apply_edt(cf->rfcode, &edt);
2381 frame_data_set_after_dissect(fdata, &cum_bytes, &prev_dis_ts);
2382 cap_file_add_fdata(cf, fdata);
2385 g_slice_free(frame_data, fdata);
2388 epan_dissect_cleanup(&edt);
2394 process_packet_second_pass(capture_file *cf, frame_data *fdata,
2395 union wtap_pseudo_header *pseudo_header, const guchar *pd,
2396 gboolean filtering_tap_listeners, guint tap_flags)
2398 gboolean create_proto_tree;
2403 /* If we're not running a display filter and we're not printing any
2404 packet information, we don't need to do a dissection. This means
2405 that all packets can be marked as 'passed'. */
2408 /* If we're going to print packet information, or we're going to
2409 run a read filter, or we're going to process taps, set up to
2410 do a dissection and do so. */
2411 if (do_dissection) {
2412 if (gbl_resolv_flags)
2413 /* Grab any resolved addresses */
2414 host_name_lookup_process(NULL);
2416 if (cf->rfcode || verbose || filtering_tap_listeners ||
2417 (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo))
2418 create_proto_tree = TRUE;
2420 create_proto_tree = FALSE;
2422 /* The protocol tree will be "visible", i.e., printed, only if we're
2423 printing packet details, which is true if we're printing stuff
2424 ("print_packet_info" is true) and we're in verbose mode ("verbose"
2426 epan_dissect_init(&edt, create_proto_tree, print_packet_info && verbose);
2428 /* If we're running a read filter, prime the epan_dissect_t with that
2431 epan_dissect_prime_dfilter(&edt, cf->rfcode);
2433 col_custom_prime_edt(&edt, &cf->cinfo);
2435 tap_queue_init(&edt);
2437 /* We only need the columns if either
2439 1) some tap needs the columns
2443 2) we're printing packet info but we're *not* verbose; in verbose
2444 mode, we print the protocol tree, not the protocol summary. */
2445 if ((tap_flags & TL_REQUIRES_COLUMNS) || (print_packet_info && !verbose))
2450 epan_dissect_run(&edt, pseudo_header, pd, fdata, cinfo);
2452 tap_push_tapped_queue(&edt);
2454 /* Run the read filter if we have one. */
2456 passed = dfilter_apply_edt(cf->rfcode, &edt);
2460 /* Process this packet. */
2461 if (print_packet_info) {
2462 /* We're printing packet information; print the information for
2465 print_packet(cf, &edt);
2467 print_packet(cf, NULL);
2469 /* The ANSI C standard does not appear to *require* that a line-buffered
2470 stream be flushed to the host environment whenever a newline is
2471 written, it just says that, on such a stream, characters "are
2472 intended to be transmitted to or from the host environment as a
2473 block when a new-line character is encountered".
2475 The Visual C++ 6.0 C implementation doesn't do what is intended;
2476 even if you set a stream to be line-buffered, it still doesn't
2477 flush the buffer at the end of every line.
2479 So, if the "-l" flag was specified, we flush the standard output
2480 at the end of a packet. This will do the right thing if we're
2481 printing packet summary lines, and, as we print the entire protocol
2482 tree for a single packet without waiting for anything to happen,
2483 it should be as good as line-buffered mode if we're printing
2484 protocol trees. (The whole reason for the "-l" flag in either
2485 tcpdump or TShark is to allow the output of a live capture to
2486 be piped to a program or script and to have that script see the
2487 information for the packet as soon as it's printed, rather than
2488 having to wait until a standard I/O buffer fills up. */
2492 if (ferror(stdout)) {
2493 show_print_file_io_error(errno);
2499 if (do_dissection) {
2500 epan_dissect_cleanup(&edt);
2507 load_cap_file(capture_file *cf, char *save_file, int out_file_type,
2508 int max_packet_count, gint64 max_byte_count)
2511 int snapshot_length;
2516 char *save_file_string = NULL;
2517 gboolean filtering_tap_listeners;
2520 linktype = wtap_file_encap(cf->wth);
2521 if (save_file != NULL) {
2522 /* Get a string that describes what we're writing to */
2523 save_file_string = output_file_description(save_file);
2525 /* Set up to write to the capture file. */
2526 snapshot_length = wtap_snapshot_length(cf->wth);
2527 if (snapshot_length == 0) {
2528 /* Snapshot length of input file not known. */
2529 snapshot_length = WTAP_MAX_PACKET_SIZE;
2531 pdh = wtap_dump_open(save_file, out_file_type, linktype, snapshot_length,
2532 FALSE /* compressed */, &err);
2535 /* We couldn't set up to write to the capture file. */
2538 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2539 cmdarg_err("Capture files can't be written in that format.");
2542 case WTAP_ERR_UNSUPPORTED_ENCAP:
2543 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2544 cmdarg_err("The capture file being read can't be written in "
2548 case WTAP_ERR_CANT_OPEN:
2549 cmdarg_err("The %s couldn't be created for some "
2550 "unknown reason.", save_file_string);
2553 case WTAP_ERR_SHORT_WRITE:
2554 cmdarg_err("A full header couldn't be written to the %s.",
2559 cmdarg_err("The %s could not be created: %s.", save_file_string,
2560 wtap_strerror(err));
2566 if (print_packet_info) {
2567 if (!write_preamble(cf)) {
2569 show_print_file_io_error(err);
2576 /* Do we have any tap listeners with filters? */
2577 filtering_tap_listeners = have_filtering_tap_listeners();
2579 /* Get the union of the flags for all tap listeners. */
2580 tap_flags = union_of_tap_listener_flags();
2582 if (perform_two_pass_analysis) {
2583 #if GLIB_CHECK_VERSION(2,10,0)
2585 int old_max_packet_count = max_packet_count;
2587 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
2588 if (process_packet_first_pass(cf, data_offset, wtap_phdr(cf->wth),
2589 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth))) {
2590 /* Stop reading if we have the maximum number of packets;
2591 * When the -c option has not been used, max_packet_count
2592 * starts at 0, which practically means, never stop reading.
2593 * (unless we roll over max_packet_count ?)
2595 if( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
2596 err = 0; /* This is not an error */
2602 /* Close the sequential I/O side, to free up memory it requires. */
2603 wtap_sequential_close(cf->wth);
2605 /* Allow the protocol dissectors to free up memory that they
2606 * don't need after the sequential run-through of the packets. */
2607 postseq_cleanup_all_protocols();
2609 max_packet_count = old_max_packet_count;
2611 for (fdata = cf->plist_start; err == 0 && fdata != NULL; fdata = fdata->next) {
2612 if (wtap_seek_read(cf->wth, fdata->file_off, &cf->pseudo_header,
2613 cf->pd, fdata->cap_len, &err, &err_info)) {
2614 if (process_packet_second_pass(cf, fdata,
2615 &cf->pseudo_header, cf->pd,
2616 filtering_tap_listeners, tap_flags)) {
2617 /* Either there's no read filtering or this packet passed the
2618 filter, so, if we're writing to a capture file, write
2621 if (!wtap_dump(pdh, wtap_phdr(cf->wth),
2622 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2624 /* Error writing to a capture file */
2625 show_capture_file_io_error(save_file, err, FALSE);
2626 wtap_dump_close(pdh, &err);
2630 /* Stop reading if we have the maximum number of packets;
2631 * When the -c option has not been used, max_packet_count
2632 * starts at 0, which practically means, never stop reading.
2633 * (unless we roll over max_packet_count ?)
2635 if( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
2636 err = 0; /* This is not an error */
2645 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
2646 if (process_packet(cf, data_offset, wtap_phdr(cf->wth),
2647 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2648 filtering_tap_listeners, tap_flags)) {
2649 /* Either there's no read filtering or this packet passed the
2650 filter, so, if we're writing to a capture file, write
2653 if (!wtap_dump(pdh, wtap_phdr(cf->wth),
2654 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2656 /* Error writing to a capture file */
2657 show_capture_file_io_error(save_file, err, FALSE);
2658 wtap_dump_close(pdh, &err);
2662 /* Stop reading if we have the maximum number of packets;
2663 * When the -c option has not been used, max_packet_count
2664 * starts at 0, which practically means, never stop reading.
2665 * (unless we roll over max_packet_count ?)
2667 if( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
2668 err = 0; /* This is not an error */
2677 * Print a message noting that the read failed somewhere along the line.
2679 * If we're printing packet data, and the standard output and error are
2680 * going to the same place, flush the standard output, so everything
2681 * buffered up is written, and then print a newline to the standard error
2682 * before printing the error message, to separate it from the packet
2683 * data. (Alas, that only works on UN*X; st_dev is meaningless, and
2684 * the _fstat() documentation at Microsoft doesn't indicate whether
2685 * st_ino is even supported.)
2688 if (print_packet_info) {
2689 struct stat stat_stdout, stat_stderr;
2691 if (fstat(1, &stat_stdout) == 0 && fstat(2, &stat_stderr) == 0) {
2692 if (stat_stdout.st_dev == stat_stderr.st_dev &&
2693 stat_stdout.st_ino == stat_stderr.st_ino) {
2695 fprintf(stderr, "\n");
2702 case WTAP_ERR_UNSUPPORTED_ENCAP:
2703 cmdarg_err("\"%s\" has a packet with a network type that TShark doesn't support.\n(%s)",
2704 cf->filename, err_info);
2708 case WTAP_ERR_CANT_READ:
2709 cmdarg_err("An attempt to read from \"%s\" failed for some unknown reason.",
2713 case WTAP_ERR_SHORT_READ:
2714 cmdarg_err("\"%s\" appears to have been cut short in the middle of a packet.",
2718 case WTAP_ERR_BAD_RECORD:
2719 cmdarg_err("\"%s\" appears to be damaged or corrupt.\n(%s)",
2720 cf->filename, err_info);
2725 cmdarg_err("An error occurred while reading \"%s\": %s.",
2726 cf->filename, wtap_strerror(err));
2729 if (save_file != NULL) {
2730 /* Now close the capture file. */
2731 if (!wtap_dump_close(pdh, &err))
2732 show_capture_file_io_error(save_file, err, TRUE);
2735 if (save_file != NULL) {
2736 /* Now close the capture file. */
2737 if (!wtap_dump_close(pdh, &err))
2738 show_capture_file_io_error(save_file, err, TRUE);
2740 if (print_packet_info) {
2741 if (!write_finale()) {
2743 show_print_file_io_error(err);
2750 wtap_close(cf->wth);
2753 g_free(save_file_string);
2759 process_packet(capture_file *cf, gint64 offset, const struct wtap_pkthdr *whdr,
2760 union wtap_pseudo_header *pseudo_header, const guchar *pd,
2761 gboolean filtering_tap_listeners, guint tap_flags)
2764 gboolean create_proto_tree;
2769 /* Count this packet. */
2772 /* If we're not running a display filter and we're not printing any
2773 packet information, we don't need to do a dissection. This means
2774 that all packets can be marked as 'passed'. */
2777 frame_data_init(&fdata, cf->count, whdr, offset, cum_bytes);
2779 /* If we're going to print packet information, or we're going to
2780 run a read filter, or we're going to process taps, set up to
2781 do a dissection and do so. */
2782 if (do_dissection) {
2783 if (print_packet_info && gbl_resolv_flags)
2784 /* Grab any resolved addresses */
2785 host_name_lookup_process(NULL);
2787 if (cf->rfcode || verbose || filtering_tap_listeners ||
2788 (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo))
2789 create_proto_tree = TRUE;
2791 create_proto_tree = FALSE;
2793 /* The protocol tree will be "visible", i.e., printed, only if we're
2794 printing packet details, which is true if we're printing stuff
2795 ("print_packet_info" is true) and we're in verbose mode ("verbose"
2797 epan_dissect_init(&edt, create_proto_tree, print_packet_info && verbose);
2799 /* If we're running a read filter, prime the epan_dissect_t with that
2802 epan_dissect_prime_dfilter(&edt, cf->rfcode);
2804 col_custom_prime_edt(&edt, &cf->cinfo);
2806 tap_queue_init(&edt);
2808 /* We only need the columns if either
2810 1) some tap needs the columns
2814 2) we're printing packet info but we're *not* verbose; in verbose
2815 mode, we print the protocol tree, not the protocol summary. */
2816 if ((tap_flags & TL_REQUIRES_COLUMNS) || (print_packet_info && !verbose))
2821 frame_data_set_before_dissect(&fdata, &cf->elapsed_time,
2822 &first_ts, &prev_dis_ts, &prev_cap_ts);
2824 epan_dissect_run(&edt, pseudo_header, pd, &fdata, cinfo);
2826 tap_push_tapped_queue(&edt);
2828 /* Run the read filter if we have one. */
2830 passed = dfilter_apply_edt(cf->rfcode, &edt);
2834 frame_data_set_after_dissect(&fdata, &cum_bytes, &prev_dis_ts);
2836 /* Process this packet. */
2837 if (print_packet_info) {
2838 /* We're printing packet information; print the information for
2841 print_packet(cf, &edt);
2843 print_packet(cf, NULL);
2845 /* The ANSI C standard does not appear to *require* that a line-buffered
2846 stream be flushed to the host environment whenever a newline is
2847 written, it just says that, on such a stream, characters "are
2848 intended to be transmitted to or from the host environment as a
2849 block when a new-line character is encountered".
2851 The Visual C++ 6.0 C implementation doesn't do what is intended;
2852 even if you set a stream to be line-buffered, it still doesn't
2853 flush the buffer at the end of every line.
2855 So, if the "-l" flag was specified, we flush the standard output
2856 at the end of a packet. This will do the right thing if we're
2857 printing packet summary lines, and, as we print the entire protocol
2858 tree for a single packet without waiting for anything to happen,
2859 it should be as good as line-buffered mode if we're printing
2860 protocol trees. (The whole reason for the "-l" flag in either
2861 tcpdump or TShark is to allow the output of a live capture to
2862 be piped to a program or script and to have that script see the
2863 information for the packet as soon as it's printed, rather than
2864 having to wait until a standard I/O buffer fills up. */
2868 if (ferror(stdout)) {
2869 show_print_file_io_error(errno);
2875 if (do_dissection) {
2876 epan_dissect_cleanup(&edt);
2877 frame_data_cleanup(&fdata);
2883 write_preamble(capture_file *cf)
2885 switch (output_action) {
2888 return print_preamble(print_stream, cf ? cf->filename : NULL);
2892 write_pdml_preamble(stdout);
2894 write_psml_preamble(stdout);
2895 return !ferror(stdout);
2898 write_fields_preamble(output_fields, stdout);
2899 return !ferror(stdout);
2902 g_assert_not_reached();
2908 get_line_buf(size_t len)
2910 static char *line_bufp = NULL;
2911 static size_t line_buf_len = 256;
2912 size_t new_line_buf_len;
2914 for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
2915 new_line_buf_len *= 2)
2917 if (line_bufp == NULL) {
2918 line_buf_len = new_line_buf_len;
2919 line_bufp = g_malloc(line_buf_len + 1);
2921 if (new_line_buf_len > line_buf_len) {
2922 line_buf_len = new_line_buf_len;
2923 line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2930 print_columns(capture_file *cf)
2937 line_bufp = get_line_buf(256);
2940 for (i = 0; i < cf->cinfo.num_cols; i++) {
2941 switch (cf->cinfo.col_fmt[i]) {
2945 * Don't print this if we're doing a live capture from a network
2946 * interface - if we're doing a live capture, you won't be
2947 * able to look at the capture in the future (it's not being
2948 * saved anywhere), so the frame numbers are unlikely to be
2951 * (XXX - it might be nice to be able to save and print at
2952 * the same time, sort of like an "Update list of packets
2953 * in real time" capture in Wireshark.)
2955 if (global_capture_opts.iface != NULL)
2958 column_len = strlen(cf->cinfo.col_data[i]);
2961 line_bufp = get_line_buf(buf_offset + column_len);
2962 sprintf(line_bufp + buf_offset, "%3s", cf->cinfo.col_data[i]);
2968 case COL_ABS_DATE_TIME: /* XXX - wider */
2969 column_len = strlen(cf->cinfo.col_data[i]);
2970 if (column_len < 10)
2972 line_bufp = get_line_buf(buf_offset + column_len);
2973 sprintf(line_bufp + buf_offset, "%10s", cf->cinfo.col_data[i]);
2979 case COL_DEF_DL_SRC:
2980 case COL_RES_DL_SRC:
2981 case COL_UNRES_DL_SRC:
2982 case COL_DEF_NET_SRC:
2983 case COL_RES_NET_SRC:
2984 case COL_UNRES_NET_SRC:
2985 column_len = strlen(cf->cinfo.col_data[i]);
2986 if (column_len < 12)
2988 line_bufp = get_line_buf(buf_offset + column_len);
2989 sprintf(line_bufp + buf_offset, "%12s", cf->cinfo.col_data[i]);
2995 case COL_DEF_DL_DST:
2996 case COL_RES_DL_DST:
2997 case COL_UNRES_DL_DST:
2998 case COL_DEF_NET_DST:
2999 case COL_RES_NET_DST:
3000 case COL_UNRES_NET_DST:
3001 column_len = strlen(cf->cinfo.col_data[i]);
3002 if (column_len < 12)
3004 line_bufp = get_line_buf(buf_offset + column_len);
3005 sprintf(line_bufp + buf_offset, "%-12s", cf->cinfo.col_data[i]);
3009 column_len = strlen(cf->cinfo.col_data[i]);
3010 line_bufp = get_line_buf(buf_offset + column_len);
3011 strcat(line_bufp + buf_offset, cf->cinfo.col_data[i]);
3014 buf_offset += column_len;
3015 if (i != cf->cinfo.num_cols - 1) {
3017 * This isn't the last column, so we need to print a
3018 * separator between this column and the next.
3020 * If we printed a network source and are printing a
3021 * network destination of the same type next, separate
3022 * them with "->"; if we printed a network destination
3023 * and are printing a network source of the same type
3024 * next, separate them with "<-"; otherwise separate them
3027 * We add enough space to the buffer for " <- " or " -> ",
3028 * even if we're only adding " ".
3030 line_bufp = get_line_buf(buf_offset + 4);
3031 switch (cf->cinfo.col_fmt[i]) {
3036 switch (cf->cinfo.col_fmt[i + 1]) {
3041 strcat(line_bufp + buf_offset, " -> ");
3046 strcat(line_bufp + buf_offset, " ");
3052 case COL_DEF_DL_SRC:
3053 case COL_RES_DL_SRC:
3054 case COL_UNRES_DL_SRC:
3055 switch (cf->cinfo.col_fmt[i + 1]) {
3057 case COL_DEF_DL_DST:
3058 case COL_RES_DL_DST:
3059 case COL_UNRES_DL_DST:
3060 strcat(line_bufp + buf_offset, " -> ");
3065 strcat(line_bufp + buf_offset, " ");
3071 case COL_DEF_NET_SRC:
3072 case COL_RES_NET_SRC:
3073 case COL_UNRES_NET_SRC:
3074 switch (cf->cinfo.col_fmt[i + 1]) {
3076 case COL_DEF_NET_DST:
3077 case COL_RES_NET_DST:
3078 case COL_UNRES_NET_DST:
3079 strcat(line_bufp + buf_offset, " -> ");
3084 strcat(line_bufp + buf_offset, " ");
3093 switch (cf->cinfo.col_fmt[i + 1]) {
3098 strcat(line_bufp + buf_offset, " <- ");
3103 strcat(line_bufp + buf_offset, " ");
3109 case COL_DEF_DL_DST:
3110 case COL_RES_DL_DST:
3111 case COL_UNRES_DL_DST:
3112 switch (cf->cinfo.col_fmt[i + 1]) {
3114 case COL_DEF_DL_SRC:
3115 case COL_RES_DL_SRC:
3116 case COL_UNRES_DL_SRC:
3117 strcat(line_bufp + buf_offset, " <- ");
3122 strcat(line_bufp + buf_offset, " ");
3128 case COL_DEF_NET_DST:
3129 case COL_RES_NET_DST:
3130 case COL_UNRES_NET_DST:
3131 switch (cf->cinfo.col_fmt[i + 1]) {
3133 case COL_DEF_NET_SRC:
3134 case COL_RES_NET_SRC:
3135 case COL_UNRES_NET_SRC:
3136 strcat(line_bufp + buf_offset, " <- ");
3141 strcat(line_bufp + buf_offset, " ");
3148 strcat(line_bufp + buf_offset, " ");
3154 return print_line(print_stream, 0, line_bufp);
3158 print_packet(capture_file *cf, epan_dissect_t *edt)
3160 print_args_t print_args;
3163 /* Print the information in the protocol tree. */
3164 switch (output_action) {
3167 print_args.to_file = TRUE;
3168 print_args.format = print_format;
3169 print_args.print_summary = !verbose;
3170 print_args.print_hex = verbose && print_hex;
3171 print_args.print_formfeed = FALSE;
3172 print_args.print_dissections = verbose ? print_dissections_expanded : print_dissections_none;
3174 /* init the packet range */
3175 packet_range_init(&print_args.range);
3177 if (!proto_tree_print(&print_args, edt, print_stream))
3180 /* "print_hex_data()" will put out a leading blank line, as well
3181 as a trailing one; print one here, to separate the packets,
3182 only if "print_hex_data()" won't be called. */
3183 if (!print_line(print_stream, 0, ""))
3189 proto_tree_write_pdml(edt, stdout);
3191 return !ferror(stdout);
3193 proto_tree_write_fields(output_fields, edt, stdout);
3195 return !ferror(stdout);
3198 /* Just fill in the columns. */
3199 epan_dissect_fill_in_columns(edt, FALSE, TRUE);
3201 /* Now print them. */
3202 switch (output_action) {
3205 if (!print_columns(cf))
3210 proto_tree_write_psml(edt, stdout);
3211 return !ferror(stdout);
3212 case WRITE_FIELDS: /*No non-verbose "fields" format */
3213 g_assert_not_reached();
3218 if (!print_hex_data(print_stream, edt))
3220 if (!print_line(print_stream, 0, ""))
3229 switch (output_action) {
3232 return print_finale(print_stream);
3236 write_pdml_finale(stdout);
3238 write_psml_finale(stdout);
3239 return !ferror(stdout);
3242 write_fields_finale(output_fields, stdout);
3243 return !ferror(stdout);
3246 g_assert_not_reached();
3252 cf_open(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
3256 char err_msg[2048+1];
3258 wth = wtap_open_offline(fname, err, &err_info, perform_two_pass_analysis);
3262 /* The open succeeded. Fill in the information for this file. */
3264 /* Cleanup all data structures used for dissection. */
3265 cleanup_dissection();
3266 /* Initialize all data structures used for dissection. */
3270 cf->f_datalen = 0; /* not used, but set it anyway */
3272 /* Set the file name because we need it to set the follow stream filter.
3273 XXX - is that still true? We need it for other reasons, though,
3275 cf->filename = g_strdup(fname);
3277 /* Indicate whether it's a permanent or temporary file. */
3278 cf->is_tempfile = is_tempfile;
3280 /* If it's a temporary capture buffer file, mark it as not saved. */
3281 cf->user_saved = !is_tempfile;
3283 cf->cd_t = wtap_file_type(cf->wth);
3285 cf->drops_known = FALSE;
3287 cf->snap = wtap_snapshot_length(cf->wth);
3288 if (cf->snap == 0) {
3289 /* Snapshot length not known. */
3290 cf->has_snap = FALSE;
3291 cf->snap = WTAP_MAX_PACKET_SIZE;
3293 cf->has_snap = TRUE;
3294 nstime_set_zero(&cf->elapsed_time);
3295 nstime_set_unset(&first_ts);
3296 nstime_set_unset(&prev_dis_ts);
3297 nstime_set_unset(&prev_cap_ts);
3299 cf->state = FILE_READ_IN_PROGRESS;
3304 g_snprintf(err_msg, sizeof err_msg,
3305 cf_open_error_message(*err, err_info, FALSE, cf->cd_t), fname);
3306 cmdarg_err("%s", err_msg);
3311 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
3313 char *save_file_string;
3315 save_file_string = output_file_description(fname);
3320 cmdarg_err("Not all the packets could be written to the %s because there is "
3321 "no space left on the file system.",
3327 cmdarg_err("Not all the packets could be written to the %s because you are "
3328 "too close to, or over your disk quota.",
3333 case WTAP_ERR_CANT_CLOSE:
3334 cmdarg_err("The %s couldn't be closed for some unknown reason.",
3338 case WTAP_ERR_SHORT_WRITE:
3339 cmdarg_err("Not all the packets could be written to the %s.",
3345 cmdarg_err("The %s could not be closed: %s.", save_file_string,
3346 wtap_strerror(err));
3348 cmdarg_err("An error occurred while writing to the %s: %s.",
3349 save_file_string, wtap_strerror(err));
3353 g_free(save_file_string);
3357 show_print_file_io_error(int err)
3362 cmdarg_err("Not all the packets could be printed because there is "
3363 "no space left on the file system.");
3368 cmdarg_err("Not all the packets could be printed because you are "
3369 "too close to, or over your disk quota.");
3374 cmdarg_err("An error occurred while printing packets: %s.",
3381 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
3385 static char errmsg_errno[1024+1];
3388 /* Wiretap error. */
3391 case WTAP_ERR_NOT_REGULAR_FILE:
3392 errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
3395 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
3396 /* Seen only when opening a capture file for reading. */
3397 errmsg = "The file \"%s\" isn't a capture file in a format TShark understands.";
3400 case WTAP_ERR_UNSUPPORTED:
3401 /* Seen only when opening a capture file for reading. */
3402 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3403 "The file \"%%s\" isn't a capture file in a format TShark understands.\n"
3406 errmsg = errmsg_errno;
3409 case WTAP_ERR_CANT_WRITE_TO_PIPE:
3410 /* Seen only when opening a capture file for writing. */
3411 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3412 "The file \"%%s\" is a pipe, and %s capture files can't be "
3413 "written to a pipe.", wtap_file_type_string(file_type));
3414 errmsg = errmsg_errno;
3417 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
3418 /* Seen only when opening a capture file for writing. */
3419 errmsg = "TShark doesn't support writing capture files in that format.";
3422 case WTAP_ERR_UNSUPPORTED_ENCAP:
3424 errmsg = "TShark can't save this capture in that format.";
3426 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3427 "The file \"%%s\" is a capture for a network type that TShark doesn't support.\n"
3430 errmsg = errmsg_errno;
3434 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
3436 errmsg = "TShark can't save this capture in that format.";
3438 errmsg = "The file \"%s\" is a capture for a network type that TShark doesn't support.";
3441 case WTAP_ERR_BAD_RECORD:
3442 /* Seen only when opening a capture file for reading. */
3443 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3444 "The file \"%%s\" appears to be damaged or corrupt.\n"
3447 errmsg = errmsg_errno;
3450 case WTAP_ERR_CANT_OPEN:
3452 errmsg = "The file \"%s\" could not be created for some unknown reason.";
3454 errmsg = "The file \"%s\" could not be opened for some unknown reason.";
3457 case WTAP_ERR_SHORT_READ:
3458 errmsg = "The file \"%s\" appears to have been cut short"
3459 " in the middle of a packet or other data.";
3462 case WTAP_ERR_SHORT_WRITE:
3463 errmsg = "A full header couldn't be written to the file \"%s\".";
3467 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3468 "The file \"%%s\" could not be %s: %s.",
3469 for_writing ? "created" : "opened",
3470 wtap_strerror(err));
3471 errmsg = errmsg_errno;
3475 errmsg = file_open_error_message(err, for_writing);
3480 * Open/create errors are reported with an console message in TShark.
3483 open_failure_message(const char *filename, int err, gboolean for_writing)
3485 fprintf(stderr, "tshark: ");
3486 fprintf(stderr, file_open_error_message(err, for_writing), filename);
3487 fprintf(stderr, "\n");
3492 * General errors are reported with an console message in TShark.
3495 failure_message(const char *msg_format, va_list ap)
3497 fprintf(stderr, "tshark: ");
3498 vfprintf(stderr, msg_format, ap);
3499 fprintf(stderr, "\n");
3503 * Read errors are reported with an console message in TShark.
3506 read_failure_message(const char *filename, int err)
3508 cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
3509 filename, strerror(err));
3513 * Write errors are reported with an console message in TShark.
3516 write_failure_message(const char *filename, int err)
3518 cmdarg_err("An error occurred while writing to the file \"%s\": %s.",
3519 filename, strerror(err));
3523 * Print to the standard error. This is a command-line tool, so there's
3524 * no need to pop up a console.
3527 vfprintf_stderr(const char *fmt, va_list ap)
3529 vfprintf(stderr, fmt, ap);
3533 fprintf_stderr(const char *fmt, ...)
3538 vfprintf_stderr(fmt, ap);
3543 * Report an error in command-line arguments.
3546 cmdarg_err(const char *fmt, ...)
3551 failure_message(fmt, ap);
3556 * Report additional information for an error in command-line arguments.
3559 cmdarg_err_cont(const char *fmt, ...)
3564 vfprintf(stderr, fmt, ap);
3565 fprintf(stderr, "\n");