5 * Wireshark - Network traffic analyzer
6 * By Gerald Combs <gerald@wireshark.org>
7 * Copyright 1998 Gerald Combs
9 * Text-mode variant, by Gilbert Ramirez <gram@alumni.rice.edu>
10 * and Guy Harris <guy@alum.mit.edu>.
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
63 #include <epan/epan.h>
64 #include <epan/filesystem.h>
65 #include <epan/privileges.h>
68 #include <epan/timestamp.h>
69 #include <epan/packet.h>
71 #include "disabled_protos.h"
72 #include <epan/prefs.h>
73 #include <epan/column.h>
75 #include <epan/addr_resolv.h>
77 #include "clopts_common.h"
78 #include "cmdarg_err.h"
79 #include "version_info.h"
80 #include <epan/conversation.h>
81 #include <epan/plugins.h>
83 #include <epan/epan_dissect.h>
85 #include <epan/stat_cmd_args.h>
86 #include <epan/timestamp.h>
87 #include <epan/ex-opt.h>
90 #include "capture_ui_utils.h"
92 #include "capture-pcap-util.h"
94 #include "capture-wpcap.h"
95 #include "capture_errs.h"
97 #include "capture_sync.h"
98 #endif /* HAVE_LIBPCAP */
99 #include "epan/emem.h"
101 #include <epan/funnel.h>
105 * This is the template for the decode as option; it is shared between the
106 * various functions that output the usage for this parameter.
108 static const gchar decode_as_arg_template[] = "<layer_type>==<selector>,<decode_as_protocol>";
110 static nstime_t first_ts;
111 static nstime_t prev_dis_ts;
112 static nstime_t prev_cap_ts;
113 static GString *comp_info_str, *runtime_info_str;
115 static gboolean print_packet_info; /* TRUE if we're to print packet information */
117 * The way the packet decode is to be written.
120 WRITE_TEXT, /* summary or detail text */
121 WRITE_XML, /* PDML or PSML */
122 WRITE_FIELDS /* User defined list of fields */
123 /* Add CSV and the like here */
125 static output_action_e output_action;
126 static gboolean do_dissection; /* TRUE if we have to dissect each packet */
127 static gboolean verbose;
128 static gboolean print_hex;
129 static gboolean line_buffered;
130 static guint32 cum_bytes = 0;
131 static print_format_e print_format = PR_FMT_TEXT;
132 static print_stream_t *print_stream;
134 static output_fields_t* output_fields = NULL;
137 * Standard secondary message for unexpected errors.
139 static const char please_report[] =
140 "Please report this to the Wireshark developers";
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 int 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,
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);
188 * Mark a particular frame.
192 cf_mark_frame(capture_file *cf, frame_data *frame)
194 if (! frame->flags.marked) {
195 frame->flags.marked = TRUE;
196 if (cf->count > cf->marked_count)
202 * Unmark a particular frame.
206 cf_unmark_frame(capture_file *cf, frame_data *frame)
208 if (frame->flags.marked) {
209 frame->flags.marked = FALSE;
210 if (cf->marked_count > 0)
216 static void list_capture_types(void) {
219 fprintf(stderr, "editcap: The available capture file types for \"F\":\n");
220 for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
221 if (wtap_dump_can_open(i))
222 fprintf(stderr, " %s - %s\n",
223 wtap_file_type_short_string(i), wtap_file_type_string(i));
228 print_usage(gboolean print_ver)
235 "TShark " VERSION "%s\n"
236 "Dump and analyze network traffic.\n"
237 "See http://www.wireshark.org for more information.\n"
240 wireshark_svnversion, get_copyright_info());
244 fprintf(output, "\n");
245 fprintf(output, "Usage: tshark [options] ...\n");
246 fprintf(output, "\n");
249 fprintf(output, "Capture interface:\n");
250 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
251 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
252 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
253 fprintf(output, " -p don't capture in promiscuous mode\n");
255 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
257 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
258 fprintf(output, " -D print list of interfaces and exit\n");
259 fprintf(output, " -L print list of link-layer types of iface and exit\n");
260 fprintf(output, "\n");
261 fprintf(output, "Capture stop conditions:\n");
262 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
263 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
264 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
265 fprintf(output, " files:NUM - stop after NUM files\n");
266 /*fprintf(output, "\n");*/
267 fprintf(output, "Capture output:\n");
268 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
269 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
270 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
271 #endif /* HAVE_LIBPCAP */
273 /*fprintf(output, "\n");*/
274 fprintf(output, "Input file:\n");
275 fprintf(output, " -r <infile> set the filename to read from (no pipes or stdin!)\n");
277 fprintf(output, "\n");
278 fprintf(output, "Processing:\n");
279 fprintf(output, " -R <read filter> packet filter in Wireshark display filter syntax\n");
280 fprintf(output, " -n disable all name resolutions (def: all enabled)\n");
281 fprintf(output, " -N <name resolve flags> enable specific name resolution(s): \"mntC\"\n");
282 fprintf(output, " -d %s ...\n", decode_as_arg_template);
283 fprintf(output, " \"Decode As\", see the man page for details\n");
284 fprintf(output, " Example: tcp.port==8888,http\n");
286 /*fprintf(output, "\n");*/
287 fprintf(output, "Output:\n");
288 fprintf(output, " -w <outfile|-> set the output filename (or '-' for stdout)\n");
289 fprintf(output, " -C <config profile> start with specified configuration profile\n");
290 fprintf(output, " -F <output file type> set the output file type, default is libpcap\n");
291 fprintf(output, " an empty \"-F\" option will list the file types\n");
292 fprintf(output, " -V add output of packet tree (Packet Details)\n");
293 fprintf(output, " -S display packets even when writing to a file\n");
294 fprintf(output, " -x add output of hex and ASCII dump (Packet Bytes)\n");
295 fprintf(output, " -T pdml|ps|psml|text|fields\n");
296 fprintf(output, " format of text output (def: text)\n");
297 fprintf(output, " -e <field> field to print if -Tfields selected (e.g. tcp.port);\n");
298 fprintf(output, " this option can be repeated to print multiple fields\n");
299 fprintf(output, " -E<fieldsoption>=<value> set options for output when -Tfields selected:\n");
300 fprintf(output, " header=y|n switch headers on and off\n");
301 fprintf(output, " separator=/t|/s|<char> select tab, space, printable character as separator\n");
302 fprintf(output, " quote=d|s|n select double, single, no quotes for values\n");
303 fprintf(output, " -t ad|a|r|d|dd|e output format of time stamps (def: r: rel. to first)\n");
304 fprintf(output, " -l flush standard output after each packet\n");
305 fprintf(output, " -q be more quiet on stdout (e.g. when using statistics)\n");
306 fprintf(output, " -X <key>:<value> eXtension options, see the man page for details\n");
307 fprintf(output, " -z <statistics> various statistics, see the man page for details\n");
309 fprintf(output, "\n");
310 fprintf(output, "Miscellaneous:\n");
311 fprintf(output, " -h display this help and exit\n");
312 fprintf(output, " -v display version info and exit\n");
313 fprintf(output, " -o <name>:<value> ... override preference setting\n");
317 * For a dissector table, print on the stream described by output,
318 * its short name (which is what's used in the "-d" option) and its
322 display_dissector_table_names(const char *table_name, const char *ui_name,
325 fprintf((FILE *)output, "\t%s (%s)\n", table_name, ui_name);
329 * For a dissector handle, print on the stream described by output,
330 * the filter name (which is what's used in the "-d" option) and the full
331 * name for the protocol that corresponds to this handle.
334 display_dissector_names(const gchar *table _U_, gpointer handle, gpointer output)
337 const gchar* proto_filter_name;
338 const gchar* proto_ui_name;
340 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
342 if (proto_id != -1) {
343 proto_filter_name = proto_get_protocol_filter_name(proto_id);
344 proto_ui_name = proto_get_protocol_name(proto_id);
345 g_assert(proto_filter_name != NULL);
346 g_assert(proto_ui_name != NULL);
348 fprintf((FILE *)output, "\t%s (%s)\n",
355 * The protocol_name_search structure is used by find_protocol_name_func()
356 * to pass parameters and store results
358 struct protocol_name_search{
359 gchar *searched_name; /* Protocol filter name we are looking for */
360 dissector_handle_t matched_handle; /* Handle for a dissector whose protocol has the specified filter name */
361 guint nb_match; /* How many dissectors matched searched_name */
363 typedef struct protocol_name_search *protocol_name_search_t;
366 * This function parses all dissectors associated with a table to find the
367 * one whose protocol has the specified filter name. It is called
368 * as a reference function in a call to dissector_table_foreach_handle.
369 * The name we are looking for, as well as the results, are stored in the
370 * protocol_name_search struct pointed to by user_data.
371 * If called using dissector_table_foreach_handle, we actually parse the
372 * whole list of dissectors.
375 find_protocol_name_func(const gchar *table _U_, gpointer handle, gpointer user_data)
379 const gchar *protocol_filter_name;
380 protocol_name_search_t search_info;
384 search_info = (protocol_name_search_t)user_data;
386 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
387 if (proto_id != -1) {
388 protocol_filter_name = proto_get_protocol_filter_name(proto_id);
389 g_assert(protocol_filter_name != NULL);
390 if (strcmp(protocol_filter_name, search_info->searched_name) == 0) {
392 if (search_info->nb_match == 0) {
393 /* Record this handle only if this is the first match */
394 search_info->matched_handle = (dissector_handle_t)handle; /* Record the handle for this matching dissector */
396 search_info->nb_match++;
402 * Print all layer type names supported.
403 * We send the output to the stream described by the handle output.
407 fprint_all_layer_types(FILE *output)
410 dissector_all_tables_foreach_table(display_dissector_table_names, (gpointer)output);
414 * Print all protocol names supported for a specific layer type.
415 * table_name contains the layer type name in which the search is performed.
416 * We send the output to the stream described by the handle output.
420 fprint_all_protocols_for_layer_types(FILE *output, gchar *table_name)
423 dissector_table_foreach_handle(table_name,
424 display_dissector_names,
429 * The function below parses the command-line parameters for the decode as
430 * feature (a string pointer by cl_param).
431 * It checks the format of the command-line, searches for a matching table
432 * and dissector. If a table/dissector match is not found, we display a
433 * summary of the available tables/dissectors (on stderr) and return FALSE.
434 * If everything is fine, we get the "Decode as" preference activated,
435 * then we return TRUE.
438 add_decode_as(const gchar *cl_param)
442 gchar *decoded_param;
443 gchar *remaining_param;
445 gchar *dissector_str;
446 dissector_handle_t dissector_matching;
447 dissector_table_t table_matching;
448 ftenum_t dissector_table_selector_type;
449 struct protocol_name_search user_protocol_name;
451 /* The following code will allocate and copy the command-line options in a string pointed by decoded_param */
454 decoded_param = g_strdup(cl_param);
455 g_assert(decoded_param);
458 /* The lines below will parse this string (modifying it) to extract all
459 necessary information. Note that decoded_param is still needed since
460 strings are not copied - we just save pointers. */
462 /* This section extracts a layer type (table_name) from decoded_param */
463 table_name = decoded_param; /* Layer type string starts from beginning */
465 remaining_param = strchr(table_name, '=');
466 if (remaining_param == NULL) {
467 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
468 /* If the argument does not follow the template, carry on anyway to check
469 if the table name is at least correct. If remaining_param is NULL,
470 we'll exit anyway further down */
473 *remaining_param = '\0'; /* Terminate the layer type string (table_name) where '=' was detected */
476 /* Remove leading and trailing spaces from the table name */
477 while ( table_name[0] == ' ' )
479 while ( table_name[strlen(table_name) - 1] == ' ' )
480 table_name[strlen(table_name) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
482 /* The following part searches a table matching with the layer type specified */
483 table_matching = NULL;
485 /* Look for the requested table */
486 if ( !(*(table_name)) ) { /* Is the table name empty, if so, don't even search for anything, display a message */
487 cmdarg_err("No layer type specified"); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
490 table_matching = find_dissector_table(table_name);
491 if (!table_matching) {
492 cmdarg_err("Unknown layer type -- %s", table_name); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
496 if (!table_matching) {
497 /* Display a list of supported layer types to help the user, if the
498 specified layer type was not found */
499 cmdarg_err("Valid layer types are:");
500 fprint_all_layer_types(stderr);
502 if (remaining_param == NULL || !table_matching) {
503 /* Exit if the layer type was not found, or if no '=' separator was found
505 g_free(decoded_param);
509 if (*(remaining_param + 1) != '=') { /* Check for "==" and not only '=' */
510 cmdarg_err("WARNING: -d requires \"==\" instead of \"=\". Option will be treated as \"%s==%s\"", table_name, remaining_param + 1);
513 remaining_param++; /* Move to the second '=' */
514 *remaining_param = '\0'; /* Remove the second '=' */
516 remaining_param++; /* Position after the layer type string */
518 /* This section extracts a selector value (selector_str) from decoded_param */
520 selector_str = remaining_param; /* Next part starts with the selector number */
522 remaining_param = strchr(selector_str, ',');
523 if (remaining_param == NULL) {
524 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
525 /* If the argument does not follow the template, carry on anyway to check
526 if the selector value is at least correct. If remaining_param is NULL,
527 we'll exit anyway further down */
530 *remaining_param = '\0'; /* Terminate the selector number string (selector_str) where ',' was detected */
533 dissector_table_selector_type = get_dissector_table_selector_type(table_name);
535 switch (dissector_table_selector_type) {
541 /* The selector for this table is an unsigned number. Parse it as such.
542 There's no need to remove leading and trailing spaces from the
543 selector number string, because sscanf will do that for us. */
544 if ( sscanf(selector_str, "%u", &selector) != 1 ) {
545 cmdarg_err("Invalid selector number \"%s\"", selector_str);
546 g_free(decoded_param);
554 /* The selector for this table is a string. */
558 /* There are currently no dissector tables with any types other
559 than the ones listed above. */
560 g_assert_not_reached();
563 if (remaining_param == NULL) {
564 /* Exit if no ',' separator was found (see above) */
565 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
566 fprint_all_protocols_for_layer_types(stderr, table_name);
567 g_free(decoded_param);
571 remaining_param++; /* Position after the selector number string */
573 /* This section extracts a protocol filter name (dissector_str) from decoded_param */
575 dissector_str = remaining_param; /* All the rest of the string is the dissector (decode as protocol) name */
577 /* Remove leading and trailing spaces from the dissector name */
578 while ( dissector_str[0] == ' ' )
580 while ( dissector_str[strlen(dissector_str) - 1] == ' ' )
581 dissector_str[strlen(dissector_str) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
583 dissector_matching = NULL;
585 /* We now have a pointer to the handle for the requested table inside the variable table_matching */
586 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 */
587 cmdarg_err("No protocol name specified"); /* Note, we don't exit here, but dissector_matching will remain NULL, so we exit below */
590 user_protocol_name.nb_match = 0;
591 user_protocol_name.searched_name = dissector_str;
592 user_protocol_name.matched_handle = NULL;
594 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 */
596 if (user_protocol_name.nb_match != 0) {
597 dissector_matching = user_protocol_name.matched_handle;
598 if (user_protocol_name.nb_match > 1) {
599 cmdarg_err("WARNING: Protocol \"%s\" matched %u dissectors, first one will be used", dissector_str, user_protocol_name.nb_match);
603 /* OK, check whether the problem is that there isn't any such
604 protocol, or that there is but it's not specified as a protocol
605 that's valid for that dissector table.
606 Note, we don't exit here, but dissector_matching will remain NULL,
608 if (proto_get_id_by_filter_name(dissector_str) == -1) {
609 /* No such protocol */
610 cmdarg_err("Unknown protocol -- \"%s\"", dissector_str);
612 cmdarg_err("Protocol \"%s\" isn't valid for layer type \"%s\"",
613 dissector_str, table_name);
618 if (!dissector_matching) {
619 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
620 fprint_all_protocols_for_layer_types(stderr, table_name);
621 g_free(decoded_param);
625 /* This is the end of the code that parses the command-line options.
626 All information is now stored in the variables:
630 The above variables that are strings are still pointing to areas within
631 decoded_parm. decoded_parm thus still needs to be kept allocated in
632 until we stop needing these variables
633 decoded_param will be deallocated at each exit point of this function */
636 /* We now have a pointer to the handle for the requested dissector
637 (requested protocol) inside the variable dissector_matching */
638 switch (dissector_table_selector_type) {
644 /* The selector for this table is an unsigned number. */
645 dissector_change(table_name, selector, dissector_matching);
651 /* The selector for this table is a string. */
652 dissector_change_string(table_name, selector_str, dissector_matching);
656 /* There are currently no dissector tables with any types other
657 than the ones listed above. */
658 g_assert_not_reached();
660 g_free(decoded_param); /* "Decode As" rule has been succesfully added */
665 log_func_ignore (const gchar *log_domain _U_, GLogLevelFlags log_level _U_,
666 const gchar *message _U_, gpointer user_data _U_)
671 output_file_description(const char *fname)
673 char *save_file_string;
675 /* Get a string that describes what we're writing to */
676 if (strcmp(fname, "-") == 0) {
677 /* We're writing to the standard output */
678 save_file_string = g_strdup("standard output");
680 /* We're writing to a file with the name in save_file */
681 save_file_string = g_strdup_printf("file \"%s\"", fname);
683 return save_file_string;
687 print_current_user(void) {
688 gchar *cur_user, *cur_group;
689 if (started_with_special_privs()) {
690 cur_user = get_cur_username();
691 cur_group = get_cur_groupname();
692 fprintf(stderr, "Running as user \"%s\" and group \"%s\".",
693 cur_user, cur_group);
696 if (running_with_special_privs()) {
697 fprintf(stderr, " This could be dangerous.");
699 fprintf(stderr, "\n");
704 check_capture_privs(void) {
707 /* Warn the user if npf.sys isn't loaded. */
708 if (!npf_sys_is_running() && get_os_major_version() >= 6) {
709 fprintf(stderr, "The NPF driver isn't running. You may have trouble "
710 "capturing or\nlisting interfaces.\n");
718 main(int argc, char *argv[])
720 char *init_progfile_dir_error;
723 gboolean arg_error = FALSE;
729 char *gpf_path, *pf_path;
730 char *gdp_path, *dp_path;
731 int gpf_open_errno, gpf_read_errno;
732 int pf_open_errno, pf_read_errno;
733 int gdp_open_errno, gdp_read_errno;
734 int dp_open_errno, dp_read_errno;
737 gboolean list_link_layer_types = FALSE;
738 gboolean start_capture = FALSE;
741 gboolean capture_option_specified = FALSE;
743 gboolean quiet = FALSE;
744 int out_file_type = WTAP_FILE_PCAP;
745 gchar *cf_name = NULL, *rfilter = NULL;
746 #ifdef HAVE_PCAP_OPEN_DEAD
747 struct bpf_program fcode;
749 dfilter_t *rfcode = NULL;
752 GLogLevelFlags log_flags;
755 #define OPTSTRING_INIT "a:b:c:C:d:De:E:f:F:G:hi:lLnN:o:pqr:R:s:St:T:vVw:xX:y:z:"
758 #define OPTSTRING_WIN32 "B:"
760 #define OPTSTRING_WIN32 ""
763 #define OPTSTRING_WIN32 ""
764 #endif /* HAVE_LIBPCAP */
766 static const char optstring[] = OPTSTRING_INIT OPTSTRING_WIN32;
769 * Get credential information for later use.
771 get_credential_info();
774 * Attempt to get the pathname of the executable file.
776 init_progfile_dir_error = init_progfile_dir(argv[0]);
777 if (init_progfile_dir_error != NULL) {
778 fprintf(stderr, "tshark: Can't get pathname of tshark program: %s.\n",
779 init_progfile_dir_error);
783 * In order to have the -X opts assigned before the wslua machine starts
784 * we need to call getopts before epan_init() gets called.
787 optind_initial = optind;
789 while ((opt = getopt(argc, argv, optstring)) != -1) {
791 case 'C': /* Configuration Profile */
792 if (profile_exists (optarg)) {
793 set_profile_name (optarg);
795 cmdarg_err("Configuration Profile \"%s\" does not exist", optarg);
807 optind = optind_initial;
810 /* nothing more than the standard GLib handler, but without a warning */
817 g_log_set_handler(NULL,
819 log_func_ignore, NULL /* user_data */);
820 g_log_set_handler(LOG_DOMAIN_CAPTURE,
822 log_func_ignore, NULL /* user_data */);
824 initialize_funnel_ops();
827 capture_opts_init(&global_capture_opts, NULL /* cfile */);
830 timestamp_set_type(TS_RELATIVE);
831 timestamp_set_precision(TS_PREC_AUTO);
833 /* Register all dissectors; we must do this before checking for the
834 "-G" flag, as the "-G" flag dumps information registered by the
835 dissectors, and we must do it before we read the preferences, in
836 case any dissectors register preferences. */
837 epan_init(register_all_protocols, register_all_protocol_handoffs, NULL, NULL,
838 failure_message, open_failure_message, read_failure_message);
840 /* Register all tap listeners; we do this before we parse the arguments,
841 as the "-z" argument can specify a registered tap. */
843 /* we register the plugin taps before the other taps because
844 stats_tree taps plugins will be registered as tap listeners
845 by stats_tree_stat.c and need to registered before that */
847 register_all_plugin_tap_listeners();
849 register_all_tap_listeners();
851 /* Now register the preferences for any non-dissector modules.
852 We must do that before we read the preferences as well. */
853 prefs_register_modules();
855 /* If invoked with the "-G" flag, we dump out information based on
856 the argument to the "-G" flag; if no argument is specified,
857 for backwards compatibility we dump out a glossary of display
860 XXX - we do this here, for now, to support "-G" with no arguments.
861 If none of our build or other processes uses "-G" with no arguments,
862 we can just process it with the other arguments. */
863 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
864 proto_initialize_all_prefixes();
867 proto_registrar_dump_fields(1);
869 if (strcmp(argv[2], "fields") == 0)
870 proto_registrar_dump_fields(1);
871 else if (strcmp(argv[2], "fields2") == 0)
872 proto_registrar_dump_fields(2);
873 else if (strcmp(argv[2], "fields3") == 0)
874 proto_registrar_dump_fields(3);
875 else if (strcmp(argv[2], "protocols") == 0)
876 proto_registrar_dump_protocols();
877 else if (strcmp(argv[2], "values") == 0)
878 proto_registrar_dump_values();
879 else if (strcmp(argv[2], "decodes") == 0)
880 dissector_dump_decodes();
881 else if (strcmp(argv[2], "defaultprefs") == 0)
883 else if (strcmp(argv[2], "currentprefs") == 0) {
884 read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
885 &pf_open_errno, &pf_read_errno, &pf_path);
888 cmdarg_err("Invalid \"%s\" option for -G flag", argv[2]);
895 /* Set the C-language locale to the native environment. */
896 setlocale(LC_ALL, "");
898 prefs = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
899 &pf_open_errno, &pf_read_errno, &pf_path);
900 if (gpf_path != NULL) {
901 if (gpf_open_errno != 0) {
902 cmdarg_err("Can't open global preferences file \"%s\": %s.",
903 pf_path, strerror(gpf_open_errno));
905 if (gpf_read_errno != 0) {
906 cmdarg_err("I/O error reading global preferences file \"%s\": %s.",
907 pf_path, strerror(gpf_read_errno));
910 if (pf_path != NULL) {
911 if (pf_open_errno != 0) {
912 cmdarg_err("Can't open your preferences file \"%s\": %s.", pf_path,
913 strerror(pf_open_errno));
915 if (pf_read_errno != 0) {
916 cmdarg_err("I/O error reading your preferences file \"%s\": %s.",
917 pf_path, strerror(pf_read_errno));
923 /* Set the name resolution code's flags from the preferences. */
924 g_resolv_flags = prefs->name_resolve;
926 /* Read the disabled protocols file. */
927 read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
928 &dp_path, &dp_open_errno, &dp_read_errno);
929 if (gdp_path != NULL) {
930 if (gdp_open_errno != 0) {
931 cmdarg_err("Could not open global disabled protocols file\n\"%s\": %s.",
932 gdp_path, strerror(gdp_open_errno));
934 if (gdp_read_errno != 0) {
935 cmdarg_err("I/O error reading global disabled protocols file\n\"%s\": %s.",
936 gdp_path, strerror(gdp_read_errno));
940 if (dp_path != NULL) {
941 if (dp_open_errno != 0) {
943 "Could not open your disabled protocols file\n\"%s\": %s.", dp_path,
944 strerror(dp_open_errno));
946 if (dp_read_errno != 0) {
948 "I/O error reading your disabled protocols file\n\"%s\": %s.", dp_path,
949 strerror(dp_read_errno));
954 check_capture_privs();
956 init_cap_file(&cfile);
958 /* Assemble the compile-time version information string */
959 comp_info_str = g_string_new("Compiled ");
960 get_compiled_version_info(comp_info_str, get_epan_compiled_version_info);
962 /* Assemble the run-time version information string */
963 runtime_info_str = g_string_new("Running ");
964 get_runtime_version_info(runtime_info_str, NULL);
966 /* Print format defaults to this. */
967 print_format = PR_FMT_TEXT;
969 output_fields = output_fields_new();
971 /* Now get our args */
972 while ((opt = getopt(argc, argv, optstring)) != -1) {
974 case 'a': /* autostop criteria */
975 case 'b': /* Ringbuffer option */
976 case 'c': /* Capture x packets */
977 case 'f': /* capture filter */
978 case 'i': /* Use interface x */
979 case 'p': /* Don't capture in promiscuous mode */
980 case 's': /* Set the snapshot (capture) length */
981 case 'w': /* Write to capture file x */
982 case 'y': /* Set the pcap data link type */
984 case 'B': /* Buffer size */
987 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
992 capture_option_specified = TRUE;
997 /* Configuration profile settings were already processed just ignore them this time*/
999 case 'd': /* Decode as rule */
1000 if (!add_decode_as(optarg))
1003 case 'D': /* Print a list of capture devices and exit */
1005 status = capture_opts_list_interfaces(FALSE);
1008 capture_option_specified = TRUE;
1014 output_fields_add(output_fields, optarg);
1018 if(!output_fields_set_option(output_fields, optarg)) {
1019 cmdarg_err("\"%s\" is not a valid field output option=value pair.", optarg);
1020 output_fields_list_options(stderr);
1025 out_file_type = wtap_short_string_to_file_type(optarg);
1026 if (out_file_type < 0) {
1027 cmdarg_err("\"%s\" isn't a valid capture file type", optarg);
1028 list_capture_types();
1032 case 'h': /* Print help and exit */
1036 case 'l': /* "Line-buffer" standard output */
1037 /* This isn't line-buffering, strictly speaking, it's just
1038 flushing the standard output after the information for
1039 each packet is printed; however, that should be good
1040 enough for all the purposes to which "-l" is put (and
1041 is probably actually better for "-V", as it does fewer
1044 See the comment in "process_packet()" for an explanation of
1045 why we do that, and why we don't just use "setvbuf()" to
1046 make the standard output line-buffered (short version: in
1047 Windows, "line-buffered" is the same as "fully-buffered",
1048 and the output buffer is only flushed when it fills up). */
1049 line_buffered = TRUE;
1051 case 'L': /* Print list of link-layer types and exit */
1053 list_link_layer_types = TRUE;
1055 capture_option_specified = TRUE;
1059 case 'n': /* No name resolution */
1060 g_resolv_flags = RESOLV_NONE;
1062 case 'N': /* Select what types of addresses/port #s to resolve */
1063 if (g_resolv_flags == RESOLV_ALL)
1064 g_resolv_flags = RESOLV_NONE;
1065 badopt = string_to_name_resolve(optarg, &g_resolv_flags);
1066 if (badopt != '\0') {
1067 cmdarg_err("-N specifies unknown resolving option '%c';",
1069 cmdarg_err_cont( " Valid options are 'm', 'n', 't', and 'C'");
1073 case 'o': /* Override preference from command line */
1074 switch (prefs_set_pref(optarg)) {
1079 case PREFS_SET_SYNTAX_ERR:
1080 cmdarg_err("Invalid -o flag \"%s\"", optarg);
1084 case PREFS_SET_NO_SUCH_PREF:
1085 case PREFS_SET_OBSOLETE:
1086 cmdarg_err("-o flag \"%s\" specifies unknown preference", optarg);
1091 case 'q': /* Quiet */
1094 case 'r': /* Read capture file x */
1095 cf_name = g_strdup(optarg);
1097 case 'R': /* Read file filter */
1100 case 'S': /* show packets in real time */
1101 print_packet_info = TRUE;
1103 case 't': /* Time stamp type */
1104 if (strcmp(optarg, "r") == 0)
1105 timestamp_set_type(TS_RELATIVE);
1106 else if (strcmp(optarg, "a") == 0)
1107 timestamp_set_type(TS_ABSOLUTE);
1108 else if (strcmp(optarg, "ad") == 0)
1109 timestamp_set_type(TS_ABSOLUTE_WITH_DATE);
1110 else if (strcmp(optarg, "d") == 0)
1111 timestamp_set_type(TS_DELTA);
1112 else if (strcmp(optarg, "dd") == 0)
1113 timestamp_set_type(TS_DELTA_DIS);
1114 else if (strcmp(optarg, "e") == 0)
1115 timestamp_set_type(TS_EPOCH);
1117 cmdarg_err("Invalid time stamp type \"%s\"",
1119 cmdarg_err_cont("It must be \"r\" for relative, \"a\" for absolute,");
1120 cmdarg_err_cont("\"ad\" for absolute with date, or \"d\" for delta.");
1124 case 'T': /* printing Type */
1125 if (strcmp(optarg, "text") == 0) {
1126 output_action = WRITE_TEXT;
1127 print_format = PR_FMT_TEXT;
1128 } else if (strcmp(optarg, "ps") == 0) {
1129 output_action = WRITE_TEXT;
1130 print_format = PR_FMT_PS;
1131 } else if (strcmp(optarg, "pdml") == 0) {
1132 output_action = WRITE_XML;
1134 } else if (strcmp(optarg, "psml") == 0) {
1135 output_action = WRITE_XML;
1137 } else if(strcmp(optarg, "fields") == 0) {
1138 output_action = WRITE_FIELDS;
1139 verbose = TRUE; /* Need full tree info */
1141 cmdarg_err("Invalid -T parameter.");
1142 cmdarg_err_cont("It must be \"ps\", \"text\", \"pdml\", \"psml\" or \"fields\".");
1146 case 'v': /* Show version and exit */
1147 printf("TShark " VERSION "%s\n"
1154 wireshark_svnversion, get_copyright_info(), comp_info_str->str,
1155 runtime_info_str->str);
1158 case 'V': /* Verbose */
1161 case 'x': /* Print packet data in hex (and ASCII) */
1167 /* We won't call the init function for the stat this soon
1168 as it would disallow MATE's fields (which are registered
1169 by the preferences set callback) from being used as
1170 part of a tap filter. Instead, we just add the argument
1171 to a list of stat arguments. */
1172 if (!process_stat_cmd_arg(optarg)) {
1173 cmdarg_err("invalid -z argument.");
1174 cmdarg_err_cont(" -z argument must be one of :");
1175 list_stat_cmd_args();
1180 case '?': /* Bad flag - print usage message */
1183 list_capture_types();
1193 /* If we specified output fields, but not the output field type... */
1194 if(WRITE_FIELDS != output_action && 0 != output_fields_num_fields(output_fields)) {
1195 cmdarg_err("Output fields were specified with \"-e\", "
1196 "but \"-Tfields\" was not specified.");
1198 } else if(WRITE_FIELDS == output_action && 0 == output_fields_num_fields(output_fields)) {
1199 cmdarg_err("\"-Tfields\" was specified, but no fields were "
1200 "specified with \"-e\".");
1205 /* If no capture filter or read filter has been specified, and there are
1206 still command-line arguments, treat them as the tokens of a capture
1207 filter (if no "-r" flag was specified) or a read filter (if a "-r"
1208 flag was specified. */
1209 if (optind < argc) {
1210 if (cf_name != NULL) {
1211 if (rfilter != NULL) {
1212 cmdarg_err("Read filters were specified both with \"-R\" "
1213 "and with additional command-line arguments");
1216 rfilter = get_args_as_string(argc, argv, optind);
1219 if (global_capture_opts.has_cfilter) {
1220 cmdarg_err("Capture filters were specified both with \"-f\""
1221 " and with additional command-line arguments");
1224 global_capture_opts.has_cfilter = TRUE;
1225 global_capture_opts.cfilter = get_args_as_string(argc, argv, optind);
1227 capture_option_specified = TRUE;
1233 if (!global_capture_opts.saving_to_file) {
1234 /* We're not saving the capture to a file; if "-q" wasn't specified,
1235 we should print packet information */
1237 print_packet_info = TRUE;
1239 /* We're saving to a file; if we're writing to the standard output.
1240 and we'll also be writing dissected packets to the standard
1241 output, reject the request. At best, we could redirect that
1242 to the standard error; we *can't* write both to the standard
1243 output and have either of them be useful. */
1244 if (strcmp(global_capture_opts.save_file, "-") == 0 && print_packet_info) {
1245 cmdarg_err("You can't write both raw packet data and dissected packets"
1246 " to the standard output.");
1251 /* We're not saving the capture to a file; if "-q" wasn't specified,
1252 we should print packet information */
1254 print_packet_info = TRUE;
1257 #ifndef HAVE_LIBPCAP
1258 if (capture_option_specified)
1259 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1266 /* We don't support capture filters when reading from a capture file
1267 (the BPF compiler doesn't support all link-layer types that we
1268 support in capture files we read). */
1270 if (cf_name != NULL) {
1271 if (global_capture_opts.has_cfilter) {
1272 cmdarg_err("Only read filters, not capture filters, "
1273 "can be specified when reading a capture file.");
1280 if (output_action != WRITE_TEXT) {
1281 cmdarg_err("Raw packet hex data can only be printed as text or PostScript");
1287 if (list_link_layer_types) {
1288 /* We're supposed to list the link-layer types for an interface;
1289 did the user also specify a capture file to be read? */
1291 /* Yes - that's bogus. */
1292 cmdarg_err("You can't specify -L and a capture file to be read.");
1295 /* No - did they specify a ring buffer option? */
1296 if (global_capture_opts.multi_files_on) {
1297 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
1303 * "-r" was specified, so we're reading a capture file.
1304 * Capture options don't apply here.
1306 if (global_capture_opts.multi_files_on) {
1307 cmdarg_err("Multiple capture files requested, but "
1308 "a capture isn't being done.");
1311 if (global_capture_opts.has_file_duration) {
1312 cmdarg_err("Switching capture files after a time interval was specified, but "
1313 "a capture isn't being done.");
1316 if (global_capture_opts.has_ring_num_files) {
1317 cmdarg_err("A ring buffer of capture files was specified, but "
1318 "a capture isn't being done.");
1321 if (global_capture_opts.has_autostop_files) {
1322 cmdarg_err("A maximum number of capture files was specified, but "
1323 "a capture isn't being done.");
1327 /* Note: TShark now allows the restriction of a _read_ file by packet count
1328 * and byte count as well as a write file. Other autostop options remain valid
1329 * only for a write file.
1331 if (global_capture_opts.has_autostop_duration) {
1332 cmdarg_err("A maximum capture time was specified, but "
1333 "a capture isn't being done.");
1338 * "-r" wasn't specified, so we're doing a live capture.
1340 if (global_capture_opts.saving_to_file) {
1341 /* They specified a "-w" flag, so we'll be saving to a capture file. */
1343 /* When capturing, we only support writing libpcap format. */
1344 if (out_file_type != WTAP_FILE_PCAP) {
1345 cmdarg_err("Live captures can only be saved in libpcap format.");
1348 if (global_capture_opts.multi_files_on) {
1349 /* Multiple-file mode doesn't work under certain conditions:
1350 a) it doesn't work if you're writing to the standard output;
1351 b) it doesn't work if you're writing to a pipe;
1353 if (strcmp(global_capture_opts.save_file, "-") == 0) {
1354 cmdarg_err("Multiple capture files requested, but "
1355 "the capture is being written to the standard output.");
1358 if (global_capture_opts.output_to_pipe) {
1359 cmdarg_err("Multiple capture files requested, but "
1360 "the capture file is a pipe.");
1363 if (!global_capture_opts.has_autostop_filesize &&
1364 !global_capture_opts.has_file_duration) {
1365 cmdarg_err("Multiple capture files requested, but "
1366 "no maximum capture file size or duration was specified.");
1371 /* They didn't specify a "-w" flag, so we won't be saving to a
1372 capture file. Check for options that only make sense if
1373 we're saving to a file. */
1374 if (global_capture_opts.has_autostop_filesize) {
1375 cmdarg_err("Maximum capture file size specified, but "
1376 "capture isn't being saved to a file.");
1379 if (global_capture_opts.multi_files_on) {
1380 cmdarg_err("Multiple capture files requested, but "
1381 "the capture isn't being saved to a file.");
1390 /* Start windows sockets */
1391 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1394 /* Notify all registered modules that have had any of their preferences
1395 changed either from one of the preferences file or from the command
1396 line that their preferences have changed. */
1399 /* At this point MATE will have registered its field array so we can
1400 have a tap filter with one of MATE's late-registered fields as part
1401 of the filter. We can now process all the "-z" arguments. */
1402 start_requested_stats();
1404 /* disabled protocols as per configuration file */
1405 if (gdp_path == NULL && dp_path == NULL) {
1406 set_disabled_protos_list();
1409 /* Build the column format array */
1410 col_setup(&cfile.cinfo, prefs->num_cols);
1411 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1412 cfile.cinfo.col_fmt[i] = get_column_format(i);
1413 cfile.cinfo.col_title[i] = g_strdup(get_column_title(i));
1414 if (cfile.cinfo.col_fmt[i] == COL_CUSTOM) {
1415 cfile.cinfo.col_custom_field[i] = g_strdup(get_column_custom_field(i));
1417 cfile.cinfo.col_custom_field[i] = NULL;
1419 cfile.cinfo.fmt_matx[i] = (gboolean *) g_malloc0(sizeof(gboolean) *
1421 get_column_format_matches(cfile.cinfo.fmt_matx[i], cfile.cinfo.col_fmt[i]);
1422 cfile.cinfo.col_data[i] = NULL;
1423 if (cfile.cinfo.col_fmt[i] == COL_INFO)
1424 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_INFO_LEN);
1426 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1427 cfile.cinfo.col_fence[i] = 0;
1428 cfile.cinfo.col_expr.col_expr[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1429 cfile.cinfo.col_expr.col_expr_val[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1432 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1435 for (j = 0; j < NUM_COL_FMTS; j++) {
1436 if (!cfile.cinfo.fmt_matx[i][j])
1439 if (cfile.cinfo.col_first[j] == -1)
1440 cfile.cinfo.col_first[j] = i;
1441 cfile.cinfo.col_last[j] = i;
1446 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
1447 capture_opts_trim_ring_num_files(&global_capture_opts);
1450 if (rfilter != NULL) {
1451 if (!dfilter_compile(rfilter, &rfcode)) {
1452 cmdarg_err("%s", dfilter_error_msg);
1454 #ifdef HAVE_PCAP_OPEN_DEAD
1458 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1460 if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1462 " Note: That display filter code looks like a valid capture filter;");
1464 " maybe you mixed them up?");
1473 cfile.rfcode = rfcode;
1475 if (print_packet_info) {
1476 /* If we're printing as text or PostScript, we have
1477 to create a print stream. */
1478 if (output_action == WRITE_TEXT) {
1479 switch (print_format) {
1482 print_stream = print_stream_text_stdio_new(stdout);
1486 print_stream = print_stream_ps_stdio_new(stdout);
1490 g_assert_not_reached();
1495 /* We have to dissect each packet if:
1497 we're printing information about each packet;
1499 we're using a read filter on the packets;
1501 we're using any taps. */
1502 do_dissection = print_packet_info || rfcode || have_tap_listeners();
1506 * We're reading a capture file.
1510 * Immediately relinquish any special privileges we have; we must not
1511 * be allowed to read any capture files the user running TShark
1514 relinquish_special_privs_perm();
1515 print_current_user();
1517 if (cf_open(&cfile, cf_name, FALSE, &err) != CF_OK) {
1522 /* Set timestamp precision; there should arguably be a command-line
1523 option to let the user set this. */
1524 switch(wtap_file_tsprecision(cfile.wth)) {
1525 case(WTAP_FILE_TSPREC_SEC):
1526 timestamp_set_precision(TS_PREC_AUTO_SEC);
1528 case(WTAP_FILE_TSPREC_DSEC):
1529 timestamp_set_precision(TS_PREC_AUTO_DSEC);
1531 case(WTAP_FILE_TSPREC_CSEC):
1532 timestamp_set_precision(TS_PREC_AUTO_CSEC);
1534 case(WTAP_FILE_TSPREC_MSEC):
1535 timestamp_set_precision(TS_PREC_AUTO_MSEC);
1537 case(WTAP_FILE_TSPREC_USEC):
1538 timestamp_set_precision(TS_PREC_AUTO_USEC);
1540 case(WTAP_FILE_TSPREC_NSEC):
1541 timestamp_set_precision(TS_PREC_AUTO_NSEC);
1544 g_assert_not_reached();
1547 /* Process the packets in the file */
1549 err = load_cap_file(&cfile, global_capture_opts.save_file, out_file_type,
1550 global_capture_opts.has_autostop_packets ? global_capture_opts.autostop_packets : 0,
1551 global_capture_opts.has_autostop_filesize ? global_capture_opts.autostop_filesize : 0);
1553 err = load_cap_file(&cfile, NULL, out_file_type, 0, 0);
1561 /* No capture file specified, so we're supposed to do a live capture
1562 (or get a list of link-layer types for a live capture device);
1563 do we have support for live captures? */
1570 cmdarg_err("WinPcap couldn't be found.");
1571 detailed_err = cant_load_winpcap_err("TShark");
1572 cmdarg_err_cont("%s", detailed_err);
1573 g_free(detailed_err);
1578 /* trim the interface name and exit if that failed */
1579 if (!capture_opts_trim_iface(&global_capture_opts,
1580 (prefs->capture_device) ? get_if_name(prefs->capture_device) : NULL)) {
1584 /* if requested, list the link layer types and exit */
1585 if (list_link_layer_types) {
1586 status = capture_opts_list_link_layer_types(&global_capture_opts, FALSE);
1590 if (print_packet_info) {
1591 if (!write_preamble(NULL)) {
1593 show_print_file_io_error(err);
1596 } else if (!quiet) {
1598 * We're not printing information for each packet, and the user
1599 * didn't ask us not to print a count of packets as they arrive,
1600 * so print that count so the user knows that packets are arriving.
1602 * XXX - what if the user wants to do a live capture, doesn't want
1603 * to save it to a file, doesn't want information printed for each
1604 * packet, does want some "-z" statistic, and wants packet counts
1605 * so they know whether they're seeing any packets?
1607 print_packet_counts = TRUE;
1610 /* For now, assume libpcap gives microsecond precision. */
1611 timestamp_set_precision(TS_PREC_AUTO_USEC);
1615 if (print_packet_info) {
1616 if (!write_finale()) {
1618 show_print_file_io_error(err);
1622 /* No - complain. */
1623 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1628 draw_tap_listeners(TRUE);
1629 funnel_dump_all_text_windows();
1632 output_fields_free(output_fields);
1633 output_fields = NULL;
1638 /*#define USE_BROKEN_G_MAIN_LOOP*/
1640 #ifdef USE_BROKEN_G_MAIN_LOOP
1643 gboolean loop_running = FALSE;
1645 guint32 packet_count = 0;
1648 /* XXX - move to the right position / file */
1649 /* read from a pipe (callback) */
1650 typedef gboolean (*pipe_input_cb_t) (gint source, gpointer user_data);
1652 typedef struct pipe_input_tag {
1656 pipe_input_cb_t input_cb;
1657 guint pipe_input_id;
1659 GStaticMutex callback_running;
1663 static pipe_input_t pipe_input;
1666 /* The timer has expired, see if there's stuff to read from the pipe,
1667 if so, do the callback */
1669 pipe_timer_cb(gpointer data)
1673 gboolean result, result1;
1675 pipe_input_t *pipe_input = data;
1676 gint iterations = 0;
1679 g_static_mutex_lock (&pipe_input->callback_running);
1681 /* try to read data from the pipe only 5 times, to avoid blocking */
1682 while(iterations < 5) {
1683 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: new iteration");*/
1685 /* Oddly enough although Named pipes don't work on win9x,
1686 PeekNamedPipe does !!! */
1687 handle = (HANDLE) _get_osfhandle (pipe_input->source);
1688 result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
1690 /* Get the child process exit status */
1691 result1 = GetExitCodeProcess((HANDLE)*(pipe_input->child_process),
1694 /* If the Peek returned an error, or there are bytes to be read
1695 or the childwatcher thread has terminated then call the normal
1697 if (!result || avail > 0 || childstatus != STILL_ACTIVE) {
1699 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: data avail");*/
1701 /* And call the real handler */
1702 if (!pipe_input->input_cb(pipe_input->source, pipe_input->user_data)) {
1703 g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: input pipe closed, iterations: %u", iterations);
1704 /* pipe closed, return false so that the timer is stopped */
1705 g_static_mutex_unlock (&pipe_input->callback_running);
1710 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: no data avail");*/
1711 /* No data, stop now */
1718 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: finished with iterations: %u, new timer", iterations);*/
1720 g_static_mutex_unlock (&pipe_input->callback_running);
1722 /* we didn't stopped the timer, so let it run */
1729 pipe_input_set_handler(gint source, gpointer user_data, int *child_process, pipe_input_cb_t input_cb)
1732 pipe_input.source = source;
1733 pipe_input.child_process = child_process;
1734 pipe_input.user_data = user_data;
1735 pipe_input.input_cb = input_cb;
1738 g_static_mutex_init(&pipe_input.callback_running);
1739 /* Tricky to use pipes in win9x, as no concept of wait. NT can
1740 do this but that doesn't cover all win32 platforms. GTK can do
1741 this but doesn't seem to work over processes. Attempt to do
1742 something similar here, start a timer and check for data on every
1744 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_input_set_handler: new");*/
1745 pipe_input.pipe_input_id = g_timeout_add(200, pipe_timer_cb, &pipe_input);
1755 #ifdef USE_TSHARK_SELECT
1759 struct sigaction action, oldaction;
1763 * XXX - dropping privileges is still required, until code cleanup is done
1765 * remove all dependencies to pcap specific code and using only dumpcap is almost done.
1766 * when it's done, we don't need special privileges to run tshark at all,
1767 * therefore we don't need to drop these privileges
1768 * The only thing we might want to keep is a warning if tshark is run as root,
1769 * as it's no longer necessary and potentially dangerous.
1771 * THE FOLLOWING IS THE FORMER COMMENT WHICH IS NO LONGER REALLY VALID:
1772 * We've opened the capture device, so we shouldn't need any special
1773 * privileges any more; relinquish those privileges.
1775 * XXX - if we have saved set-user-ID support, we should give up those
1776 * privileges immediately, and then reclaim them long enough to get
1777 * a list of network interfaces and to open one, and then give them
1778 * up again, so that stuff we do while processing the argument list,
1779 * reading the user's preferences, loading and starting plugins
1780 * (especially *user* plugins), etc. is done with the user's privileges,
1781 * not special privileges.
1783 relinquish_special_privs_perm();
1784 print_current_user();
1786 /* Initialize all data structures used for dissection. */
1790 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1791 SetConsoleCtrlHandler(capture_cleanup, TRUE);
1793 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
1795 action.sa_handler = capture_cleanup;
1796 action.sa_flags = 0;
1797 sigemptyset(&action.sa_mask);
1798 sigaction(SIGTERM, &action, NULL);
1799 sigaction(SIGINT, &action, NULL);
1800 sigaction(SIGHUP, NULL, &oldaction);
1801 if (oldaction.sa_handler == SIG_DFL)
1802 sigaction(SIGHUP, &action, NULL);
1805 /* Catch SIGINFO and, if we get it and we're capturing to a file in
1806 quiet mode, report the number of packets we've captured. */
1807 action.sa_handler = report_counts_siginfo;
1808 action.sa_flags = 0;
1809 sigemptyset(&action.sa_mask);
1810 sigaction(SIGINFO, &action, NULL);
1811 #endif /* SIGINFO */
1814 global_capture_opts.state = CAPTURE_PREPARING;
1816 /* Let the user know what interface was chosen. */
1817 global_capture_opts.iface_descr = get_interface_descriptive_name(global_capture_opts.iface);
1818 fprintf(stderr, "Capturing on %s\n", global_capture_opts.iface_descr);
1820 ret = sync_pipe_start(&global_capture_opts);
1825 /* the actual capture loop
1827 * XXX - glib doesn't seem to provide any event based loop handling.
1829 * XXX - for whatever reason,
1830 * calling g_main_loop_new() ends up in 100% cpu load.
1832 * But that doesn't matter: in UNIX we can use select() to find an input
1833 * source with something to do.
1835 * But that doesn't matter because we're in a CLI (that doesn't need to
1836 * update a GUI or something at the same time) so it's OK if we block
1837 * trying to read from the pipe.
1839 * So all the stuff in USE_TSHARK_SELECT could be removed unless I'm
1840 * wrong (but I leave it there in case I am...).
1843 #ifdef USE_TSHARK_SELECT
1845 FD_SET(pipe_input.source, &readfds);
1848 loop_running = TRUE;
1850 while (loop_running)
1852 #ifdef USE_TSHARK_SELECT
1853 ret = select(pipe_input.source+1, &readfds, NULL, NULL, NULL);
1859 } else if (ret == 1) {
1861 /* Call the real handler */
1862 if (!pipe_input.input_cb(pipe_input.source, pipe_input.user_data)) {
1863 g_log(NULL, G_LOG_LEVEL_DEBUG, "input pipe closed");
1866 #ifdef USE_TSHARK_SELECT
1875 /* XXX - move the call to main_window_update() out of capture_sync.c */
1876 /* dummy for capture_sync.c to make linker happy */
1877 void main_window_update(void)
1881 /* capture child detected an error */
1883 capture_input_error_message(capture_options *capture_opts _U_, char *error_msg, char *secondary_error_msg)
1885 cmdarg_err("%s", error_msg);
1886 cmdarg_err_cont("%s", secondary_error_msg);
1890 /* capture child detected an capture filter related error */
1892 capture_input_cfilter_error_message(capture_options *capture_opts, char *error_message)
1894 dfilter_t *rfcode = NULL;
1897 if (dfilter_compile(capture_opts->cfilter, &rfcode) && rfcode != NULL) {
1899 "Invalid capture filter: \"%s\"!\n"
1901 "That string looks like a valid display filter; however, it isn't a valid\n"
1902 "capture filter (%s).\n"
1904 "Note that display filters and capture filters don't have the same syntax,\n"
1905 "so you can't use most display filter expressions as capture filters.\n"
1907 "See the User's Guide for a description of the capture filter syntax.",
1908 capture_opts->cfilter, error_message);
1909 dfilter_free(rfcode);
1912 "Invalid capture filter: \"%s\"!\n"
1914 "That string isn't a valid capture filter (%s).\n"
1915 "See the User's Guide for a description of the capture filter syntax.",
1916 capture_opts->cfilter, error_message);
1921 /* capture child tells us we have a new (or the first) capture file */
1923 capture_input_new_file(capture_options *capture_opts, gchar *new_file)
1925 gboolean is_tempfile;
1929 if(capture_opts->state == CAPTURE_PREPARING) {
1930 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "Capture started!");
1932 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "File: \"%s\"", new_file);
1934 g_assert(capture_opts->state == CAPTURE_PREPARING || capture_opts->state == CAPTURE_RUNNING);
1936 capture_opts->cf = &cfile;
1938 /* free the old filename */
1939 if(capture_opts->save_file != NULL) {
1940 /* we start a new capture file, close the old one (if we had one before) */
1941 if( ((capture_file *) capture_opts->cf)->state != FILE_CLOSED) {
1942 if(capture_opts->cf != NULL && ((capture_file *) capture_opts->cf)->wth != NULL) {
1943 wtap_close(((capture_file *) capture_opts->cf)->wth);
1946 g_free(capture_opts->save_file);
1947 is_tempfile = FALSE;
1949 /* we didn't had a save_file before, must be a tempfile */
1953 /* save the new filename */
1954 capture_opts->save_file = g_strdup(new_file);
1956 /* if we are in real-time mode, open the new file now */
1958 /* Attempt to open the capture file and set up to read from it. */
1959 switch(cf_open(capture_opts->cf, capture_opts->save_file, is_tempfile, &err)) {
1963 /* Don't unlink (delete) the save file - leave it around,
1964 for debugging purposes. */
1965 g_free(capture_opts->save_file);
1966 capture_opts->save_file = NULL;
1971 capture_opts->state = CAPTURE_RUNNING;
1977 /* capture child tells us we have new packets to read */
1979 capture_input_new_packets(capture_options *capture_opts, int to_read)
1985 capture_file *cf = capture_opts->cf;
1990 * Prevent a SIGINFO handler from writing to stdout while we're
1991 * doing so; instead, have it just set a flag telling us to print
1992 * that information when we're done.
1995 #endif /* SIGINFO */
1998 while (to_read-- && cf->wth) {
1999 ret = wtap_read(cf->wth, &err, &err_info, &data_offset);
2001 /* read from file failed, tell the capture child to stop */
2002 sync_pipe_stop(capture_opts);
2003 wtap_close(cf->wth);
2006 ret = process_packet(cf, data_offset, wtap_phdr(cf->wth),
2007 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth));
2010 /* packet sucessfully read and gone through the "Read Filter" */
2016 * Dumpcap's doing all the work; we're not doing any dissection.
2017 * Count all the packets it wrote.
2019 packet_count += to_read;
2022 if (print_packet_counts) {
2023 /* We're printing packet counts. */
2024 if (packet_count != 0) {
2025 fprintf(stderr, "\r%u ", packet_count);
2026 /* stderr could be line buffered */
2033 * Allow SIGINFO handlers to write.
2038 * If a SIGINFO handler asked us to write out capture counts, do so.
2042 #endif /* SIGINFO */
2048 if (!print_packet_counts) {
2049 /* Report the count only if we aren't printing a packet count
2050 as packets arrive. */
2051 fprintf(stderr, "%u packet%s captured\n", packet_count,
2052 plurality(packet_count, "", "s"));
2055 infoprint = FALSE; /* we just reported it */
2056 #endif /* SIGINFO */
2061 report_counts_siginfo(int signum _U_)
2063 int sav_errno = errno;
2064 /* If we've been told to delay printing, just set a flag asking
2065 that we print counts (if we're supposed to), otherwise print
2066 the count of packets captured (if we're supposed to). */
2073 #endif /* SIGINFO */
2076 /* capture child detected any packet drops? */
2078 capture_input_drops(capture_options *capture_opts _U_, int dropped)
2080 if (print_packet_counts) {
2081 /* We're printing packet counts to stderr.
2082 Send a newline so that we move to the line after the packet count. */
2083 fprintf(stderr, "\n");
2087 /* We're printing packet counts to stderr.
2088 Send a newline so that we move to the line after the packet count. */
2089 fprintf(stderr, "%u packet%s dropped\n", dropped, plurality(dropped, "", "s"));
2094 /* capture child closed its side of the pipe, do the required cleanup */
2096 capture_input_closed(capture_options *capture_opts)
2100 if(capture_opts->cf != NULL && ((capture_file *) capture_opts->cf)->wth != NULL) {
2101 wtap_close(((capture_file *) capture_opts->cf)->wth);
2103 #ifdef USE_BROKEN_G_MAIN_LOOP
2104 /*g_main_loop_quit(loop);*/
2107 loop_running = FALSE;
2116 capture_cleanup(DWORD ctrltype _U_)
2118 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
2119 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
2120 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
2121 like SIGTERM at least when the machine's shutting down.
2123 For now, we handle them all as indications that we should clean up
2124 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
2127 However, as handlers run in a new thread, we can't just longjmp
2128 out; we have to set "ld.go" to FALSE, and must return TRUE so that
2129 no other handler - such as one that would terminate the process -
2132 XXX - for some reason, typing ^C to TShark, if you run this in
2133 a Cygwin console window in at least some versions of Cygwin,
2134 causes TShark to terminate immediately; this routine gets
2135 called, but the main loop doesn't get a chance to run and
2136 exit cleanly, at least if this is compiled with Microsoft Visual
2137 C++ (i.e., it's a property of the Cygwin console window or Bash;
2138 it happens if TShark is not built with Cygwin - for all I know,
2139 building it with Cygwin may make the problem go away). */
2141 /* tell the capture child to stop */
2142 sync_pipe_stop(&global_capture_opts);
2144 /* don't stop our own loop already here, otherwise status messages and
2145 * cleanup wouldn't be done properly. The child will indicate the stop of
2146 * everything by calling capture_input_closed() later */
2152 capture_cleanup(int signum _U_)
2154 /* tell the capture child to stop */
2155 sync_pipe_stop(&global_capture_opts);
2158 #endif /* HAVE_LIBPCAP */
2161 load_cap_file(capture_file *cf, char *save_file, int out_file_type,
2162 int max_packet_count, gint64 max_byte_count)
2165 int snapshot_length;
2170 char *save_file_string = NULL;
2172 linktype = wtap_file_encap(cf->wth);
2173 if (save_file != NULL) {
2174 /* Get a string that describes what we're writing to */
2175 save_file_string = output_file_description(save_file);
2177 /* Set up to write to the capture file. */
2178 snapshot_length = wtap_snapshot_length(cf->wth);
2179 if (snapshot_length == 0) {
2180 /* Snapshot length of input file not known. */
2181 snapshot_length = WTAP_MAX_PACKET_SIZE;
2183 pdh = wtap_dump_open(save_file, out_file_type, linktype, snapshot_length,
2184 FALSE /* compressed */, &err);
2187 /* We couldn't set up to write to the capture file. */
2190 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2191 cmdarg_err("Capture files can't be written in that format.");
2194 case WTAP_ERR_UNSUPPORTED_ENCAP:
2195 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2196 cmdarg_err("The capture file being read can't be written in "
2200 case WTAP_ERR_CANT_OPEN:
2201 cmdarg_err("The %s couldn't be created for some "
2202 "unknown reason.", save_file_string);
2205 case WTAP_ERR_SHORT_WRITE:
2206 cmdarg_err("A full header couldn't be written to the %s.",
2211 cmdarg_err("The %s could not be created: %s.", save_file_string,
2212 wtap_strerror(err));
2218 if (print_packet_info) {
2219 if (!write_preamble(cf)) {
2221 show_print_file_io_error(err);
2227 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
2228 if (process_packet(cf, data_offset, wtap_phdr(cf->wth),
2229 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth))) {
2230 /* Either there's no read filtering or this packet passed the
2231 filter, so, if we're writing to a capture file, write
2234 if (!wtap_dump(pdh, wtap_phdr(cf->wth),
2235 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2237 /* Error writing to a capture file */
2238 show_capture_file_io_error(save_file, err, FALSE);
2239 wtap_dump_close(pdh, &err);
2243 /* Stop reading if we have the maximum number of packets;
2244 * When the -c option has not been used, max_packet_count
2245 * starts at 0, which practically means, never stop reading.
2246 * (unless we roll over max_packet_count ?)
2248 if( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
2249 err = 0; /* This is not an error */
2255 /* Print a message noting that the read failed somewhere along the line. */
2258 case WTAP_ERR_UNSUPPORTED_ENCAP:
2259 cmdarg_err("\"%s\" has a packet with a network type that TShark doesn't support.\n(%s)",
2260 cf->filename, err_info);
2264 case WTAP_ERR_CANT_READ:
2265 cmdarg_err("An attempt to read from \"%s\" failed for some unknown reason.",
2269 case WTAP_ERR_SHORT_READ:
2270 cmdarg_err("\"%s\" appears to have been cut short in the middle of a packet.",
2274 case WTAP_ERR_BAD_RECORD:
2275 cmdarg_err("\"%s\" appears to be damaged or corrupt.\n(%s)",
2276 cf->filename, err_info);
2281 cmdarg_err("An error occurred while reading \"%s\": %s.",
2282 cf->filename, wtap_strerror(err));
2285 if (save_file != NULL) {
2286 /* Now close the capture file. */
2287 if (!wtap_dump_close(pdh, &err))
2288 show_capture_file_io_error(save_file, err, TRUE);
2291 if (save_file != NULL) {
2292 /* Now close the capture file. */
2293 if (!wtap_dump_close(pdh, &err))
2294 show_capture_file_io_error(save_file, err, TRUE);
2296 if (print_packet_info) {
2297 if (!write_finale()) {
2299 show_print_file_io_error(err);
2306 wtap_close(cf->wth);
2309 if (save_file_string != NULL)
2310 g_free(save_file_string);
2316 fill_in_fdata(frame_data *fdata, capture_file *cf,
2317 const struct wtap_pkthdr *phdr, gint64 offset)
2322 fdata->num = cf->count;
2323 fdata->pkt_len = phdr->len;
2324 cum_bytes += phdr->len;
2325 fdata->cum_bytes = cum_bytes;
2326 fdata->cap_len = phdr->caplen;
2327 fdata->file_off = offset;
2328 fdata->lnk_t = phdr->pkt_encap;
2329 fdata->abs_ts.secs = phdr->ts.secs;
2330 fdata->abs_ts.nsecs = phdr->ts.nsecs;
2331 fdata->flags.passed_dfilter = 0;
2332 fdata->flags.encoding = CHAR_ASCII;
2333 fdata->flags.visited = 0;
2334 fdata->flags.marked = 0;
2335 fdata->flags.ref_time = 0;
2336 fdata->color_filter = NULL;
2338 /* If we don't have the time stamp of the first packet in the
2339 capture, it's because this is the first packet. Save the time
2340 stamp of this packet as the time stamp of the first packet. */
2341 if (nstime_is_unset(&first_ts)) {
2342 first_ts = fdata->abs_ts;
2345 /* If we don't have the time stamp of the previous captured packet,
2346 it's because this is the first packet. Save the time
2347 stamp of this packet as the time stamp of the previous captured
2349 if (nstime_is_unset(&prev_cap_ts)) {
2350 prev_cap_ts = fdata->abs_ts;
2353 /* Get the time elapsed between the first packet and this packet. */
2354 nstime_delta(&fdata->rel_ts, &fdata->abs_ts, &first_ts);
2356 /* If it's greater than the current elapsed time, set the elapsed time
2357 to it (we check for "greater than" so as not to be confused by
2358 time moving backwards). */
2359 if ((gint32)cf->elapsed_time.secs < fdata->rel_ts.secs
2360 || ((gint32)cf->elapsed_time.secs == fdata->rel_ts.secs && (gint32)cf->elapsed_time.nsecs < fdata->rel_ts.nsecs)) {
2361 cf->elapsed_time = fdata->rel_ts;
2364 /* If we don't have the time stamp of the previous displayed packet,
2365 it's because this is the first packet that's being displayed. Save the time
2366 stamp of this packet as the time stamp of the previous displayed
2368 if (nstime_is_unset(&prev_dis_ts))
2369 prev_dis_ts = fdata->abs_ts;
2371 /* Get the time elapsed between the previous displayed packet and
2373 nstime_delta(&fdata->del_dis_ts, &fdata->abs_ts, &prev_dis_ts);
2375 /* Get the time elapsed between the previous captured packet and
2377 nstime_delta(&fdata->del_cap_ts, &fdata->abs_ts, &prev_cap_ts);
2378 prev_cap_ts = fdata->abs_ts;
2381 /* Free up all data attached to a "frame_data" structure. */
2383 clear_fdata(frame_data *fdata)
2386 g_slist_free(fdata->pfd);
2390 process_packet(capture_file *cf, gint64 offset, const struct wtap_pkthdr *whdr,
2391 union wtap_pseudo_header *pseudo_header, const guchar *pd)
2394 gboolean create_proto_tree;
2395 epan_dissect_t *edt;
2398 /* Count this packet. */
2401 /* If we're going to print packet information, or we're going to
2402 run a read filter, or we're going to process taps, set up to
2403 do a dissection and do so. */
2404 if (do_dissection) {
2405 fill_in_fdata(&fdata, cf, whdr, offset);
2407 if (print_packet_info) {
2408 /* Grab any resolved addresses */
2410 if (g_resolv_flags) {
2411 host_name_lookup_process(NULL);
2416 if (cf->rfcode || verbose || num_tap_filters!=0 || have_custom_cols(&cf->cinfo))
2417 create_proto_tree = TRUE;
2419 create_proto_tree = FALSE;
2420 /* The protocol tree will be "visible", i.e., printed, only if we're
2421 printing packet details, which is true if we're printing stuff
2422 ("print_packet_info" is true) and we're in verbose mode ("verbose"
2424 edt = epan_dissect_new(create_proto_tree, print_packet_info && verbose);
2426 /* If we're running a read filter, prime the epan_dissect_t with that
2429 epan_dissect_prime_dfilter(edt, cf->rfcode);
2431 col_custom_prime_edt(edt, &cf->cinfo);
2433 tap_queue_init(edt);
2435 /* We only need the columns if we're printing packet info but we're
2436 *not* verbose; in verbose mode, we print the protocol tree, not
2437 the protocol summary. */
2438 epan_dissect_run(edt, pseudo_header, pd, &fdata,
2439 (print_packet_info && !verbose) ? &cf->cinfo : NULL);
2441 tap_push_tapped_queue(edt);
2443 /* Run the read filter if we have one. */
2445 passed = dfilter_apply_edt(cf->rfcode, edt);
2449 /* We're not running a display filter and we're not printing any
2450 packet information, so we don't need to do a dissection, and all
2451 packets are processed. */
2457 /* Keep the time of the current packet if the packet passed
2458 the read filter so that the delta time since last displayed
2459 packet can be calculated */
2460 prev_dis_ts = fdata.abs_ts;
2462 /* Process this packet. */
2463 if (print_packet_info) {
2464 /* We're printing packet information; print the information for
2466 print_packet(cf, edt);
2468 /* The ANSI C standard does not appear to *require* that a line-buffered
2469 stream be flushed to the host environment whenever a newline is
2470 written, it just says that, on such a stream, characters "are
2471 intended to be transmitted to or from the host environment as a
2472 block when a new-line character is encountered".
2474 The Visual C++ 6.0 C implementation doesn't do what is intended;
2475 even if you set a stream to be line-buffered, it still doesn't
2476 flush the buffer at the end of every line.
2478 So, if the "-l" flag was specified, we flush the standard output
2479 at the end of a packet. This will do the right thing if we're
2480 printing packet summary lines, and, as we print the entire protocol
2481 tree for a single packet without waiting for anything to happen,
2482 it should be as good as line-buffered mode if we're printing
2483 protocol trees. (The whole reason for the "-l" flag in either
2484 tcpdump or TShark is to allow the output of a live capture to
2485 be piped to a program or script and to have that script see the
2486 information for the packet as soon as it's printed, rather than
2487 having to wait until a standard I/O buffer fills up. */
2491 if (ferror(stdout)) {
2492 show_print_file_io_error(errno);
2498 if (do_dissection) {
2499 epan_dissect_free(edt);
2500 clear_fdata(&fdata);
2506 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
2508 char *save_file_string;
2510 save_file_string = output_file_description(fname);
2515 cmdarg_err("Not all the packets could be written to the %s because there is "
2516 "no space left on the file system.",
2522 cmdarg_err("Not all the packets could be written to the %s because you are "
2523 "too close to, or over your disk quota.",
2528 case WTAP_ERR_CANT_CLOSE:
2529 cmdarg_err("The %s couldn't be closed for some unknown reason.",
2533 case WTAP_ERR_SHORT_WRITE:
2534 cmdarg_err("Not all the packets could be written to the %s.",
2540 cmdarg_err("The %s could not be closed: %s.", save_file_string,
2541 wtap_strerror(err));
2543 cmdarg_err("An error occurred while writing to the %s: %s.",
2544 save_file_string, wtap_strerror(err));
2548 g_free(save_file_string);
2552 write_preamble(capture_file *cf)
2554 switch (output_action) {
2557 return print_preamble(print_stream, cf ? cf->filename : NULL);
2561 write_pdml_preamble(stdout);
2563 write_psml_preamble(stdout);
2564 return !ferror(stdout);
2567 write_fields_preamble(output_fields, stdout);
2568 return !ferror(stdout);
2571 g_assert_not_reached();
2577 get_line_buf(size_t len)
2579 static char *line_bufp = NULL;
2580 static size_t line_buf_len = 256;
2581 size_t new_line_buf_len;
2583 for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
2584 new_line_buf_len *= 2)
2586 if (line_bufp == NULL) {
2587 line_buf_len = new_line_buf_len;
2588 line_bufp = g_malloc(line_buf_len + 1);
2590 if (new_line_buf_len > line_buf_len) {
2591 line_buf_len = new_line_buf_len;
2592 line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2599 print_columns(capture_file *cf)
2606 line_bufp = get_line_buf(256);
2609 for (i = 0; i < cf->cinfo.num_cols; i++) {
2610 switch (cf->cinfo.col_fmt[i]) {
2614 * Don't print this if we're doing a live capture from a network
2615 * interface - if we're doing a live capture, you won't be
2616 * able to look at the capture in the future (it's not being
2617 * saved anywhere), so the frame numbers are unlikely to be
2620 * (XXX - it might be nice to be able to save and print at
2621 * the same time, sort of like an "Update list of packets
2622 * in real time" capture in Wireshark.)
2624 if (global_capture_opts.iface != NULL)
2627 column_len = strlen(cf->cinfo.col_data[i]);
2630 line_bufp = get_line_buf(buf_offset + column_len);
2631 sprintf(line_bufp + buf_offset, "%3s", cf->cinfo.col_data[i]);
2637 case COL_ABS_DATE_TIME: /* XXX - wider */
2638 column_len = strlen(cf->cinfo.col_data[i]);
2639 if (column_len < 10)
2641 line_bufp = get_line_buf(buf_offset + column_len);
2642 sprintf(line_bufp + buf_offset, "%10s", cf->cinfo.col_data[i]);
2648 case COL_DEF_DL_SRC:
2649 case COL_RES_DL_SRC:
2650 case COL_UNRES_DL_SRC:
2651 case COL_DEF_NET_SRC:
2652 case COL_RES_NET_SRC:
2653 case COL_UNRES_NET_SRC:
2654 column_len = strlen(cf->cinfo.col_data[i]);
2655 if (column_len < 12)
2657 line_bufp = get_line_buf(buf_offset + column_len);
2658 sprintf(line_bufp + buf_offset, "%12s", cf->cinfo.col_data[i]);
2664 case COL_DEF_DL_DST:
2665 case COL_RES_DL_DST:
2666 case COL_UNRES_DL_DST:
2667 case COL_DEF_NET_DST:
2668 case COL_RES_NET_DST:
2669 case COL_UNRES_NET_DST:
2670 column_len = strlen(cf->cinfo.col_data[i]);
2671 if (column_len < 12)
2673 line_bufp = get_line_buf(buf_offset + column_len);
2674 sprintf(line_bufp + buf_offset, "%-12s", cf->cinfo.col_data[i]);
2678 column_len = strlen(cf->cinfo.col_data[i]);
2679 line_bufp = get_line_buf(buf_offset + column_len);
2680 strcat(line_bufp + buf_offset, cf->cinfo.col_data[i]);
2683 buf_offset += column_len;
2684 if (i != cf->cinfo.num_cols - 1) {
2686 * This isn't the last column, so we need to print a
2687 * separator between this column and the next.
2689 * If we printed a network source and are printing a
2690 * network destination of the same type next, separate
2691 * them with "->"; if we printed a network destination
2692 * and are printing a network source of the same type
2693 * next, separate them with "<-"; otherwise separate them
2696 * We add enough space to the buffer for " <- " or " -> ",
2697 * even if we're only adding " ".
2699 line_bufp = get_line_buf(buf_offset + 4);
2700 switch (cf->cinfo.col_fmt[i]) {
2705 switch (cf->cinfo.col_fmt[i + 1]) {
2710 strcat(line_bufp + buf_offset, " -> ");
2715 strcat(line_bufp + buf_offset, " ");
2721 case COL_DEF_DL_SRC:
2722 case COL_RES_DL_SRC:
2723 case COL_UNRES_DL_SRC:
2724 switch (cf->cinfo.col_fmt[i + 1]) {
2726 case COL_DEF_DL_DST:
2727 case COL_RES_DL_DST:
2728 case COL_UNRES_DL_DST:
2729 strcat(line_bufp + buf_offset, " -> ");
2734 strcat(line_bufp + buf_offset, " ");
2740 case COL_DEF_NET_SRC:
2741 case COL_RES_NET_SRC:
2742 case COL_UNRES_NET_SRC:
2743 switch (cf->cinfo.col_fmt[i + 1]) {
2745 case COL_DEF_NET_DST:
2746 case COL_RES_NET_DST:
2747 case COL_UNRES_NET_DST:
2748 strcat(line_bufp + buf_offset, " -> ");
2753 strcat(line_bufp + buf_offset, " ");
2762 switch (cf->cinfo.col_fmt[i + 1]) {
2767 strcat(line_bufp + buf_offset, " <- ");
2772 strcat(line_bufp + buf_offset, " ");
2778 case COL_DEF_DL_DST:
2779 case COL_RES_DL_DST:
2780 case COL_UNRES_DL_DST:
2781 switch (cf->cinfo.col_fmt[i + 1]) {
2783 case COL_DEF_DL_SRC:
2784 case COL_RES_DL_SRC:
2785 case COL_UNRES_DL_SRC:
2786 strcat(line_bufp + buf_offset, " <- ");
2791 strcat(line_bufp + buf_offset, " ");
2797 case COL_DEF_NET_DST:
2798 case COL_RES_NET_DST:
2799 case COL_UNRES_NET_DST:
2800 switch (cf->cinfo.col_fmt[i + 1]) {
2802 case COL_DEF_NET_SRC:
2803 case COL_RES_NET_SRC:
2804 case COL_UNRES_NET_SRC:
2805 strcat(line_bufp + buf_offset, " <- ");
2810 strcat(line_bufp + buf_offset, " ");
2817 strcat(line_bufp + buf_offset, " ");
2823 return print_line(print_stream, 0, line_bufp);
2827 print_packet(capture_file *cf, epan_dissect_t *edt)
2829 print_args_t print_args;
2832 /* Print the information in the protocol tree. */
2833 switch (output_action) {
2836 print_args.to_file = TRUE;
2837 print_args.format = print_format;
2838 print_args.print_summary = !verbose;
2839 print_args.print_hex = verbose && print_hex;
2840 print_args.print_formfeed = FALSE;
2841 print_args.print_dissections = verbose ? print_dissections_expanded : print_dissections_none;
2843 /* init the packet range */
2844 packet_range_init(&print_args.range);
2846 if (!proto_tree_print(&print_args, edt, print_stream))
2849 /* "print_hex_data()" will put out a leading blank line, as well
2850 as a trailing one; print one here, to separate the packets,
2851 only if "print_hex_data()" won't be called. */
2852 if (!print_line(print_stream, 0, ""))
2858 proto_tree_write_pdml(edt, stdout);
2860 return !ferror(stdout);
2862 proto_tree_write_fields(output_fields, edt, stdout);
2864 return !ferror(stdout);
2867 /* Just fill in the columns. */
2868 epan_dissect_fill_in_columns(edt);
2870 /* Now print them. */
2871 switch (output_action) {
2874 if (!print_columns(cf))
2879 proto_tree_write_psml(edt, stdout);
2880 return !ferror(stdout);
2881 case WRITE_FIELDS: /*No non-verbose "fields" format */
2882 g_assert_not_reached();
2887 if (!print_hex_data(print_stream, edt))
2889 if (!print_line(print_stream, 0, ""))
2898 switch (output_action) {
2901 return print_finale(print_stream);
2905 write_pdml_finale(stdout);
2907 write_psml_finale(stdout);
2908 return !ferror(stdout);
2911 write_fields_finale(output_fields, stdout);
2912 return !ferror(stdout);
2915 g_assert_not_reached();
2921 show_print_file_io_error(int err)
2926 cmdarg_err("Not all the packets could be printed because there is "
2927 "no space left on the file system.");
2932 cmdarg_err("Not all the packets could be printed because you are "
2933 "too close to, or over your disk quota.");
2938 cmdarg_err("An error occurred while printing packets: %s.",
2945 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
2949 static char errmsg_errno[1024+1];
2952 /* Wiretap error. */
2955 case WTAP_ERR_NOT_REGULAR_FILE:
2956 errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
2959 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
2960 /* Seen only when opening a capture file for reading. */
2961 errmsg = "The file \"%s\" isn't a capture file in a format TShark understands.";
2964 case WTAP_ERR_UNSUPPORTED:
2965 /* Seen only when opening a capture file for reading. */
2966 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2967 "The file \"%%s\" isn't a capture file in a format TShark understands.\n"
2970 errmsg = errmsg_errno;
2973 case WTAP_ERR_CANT_WRITE_TO_PIPE:
2974 /* Seen only when opening a capture file for writing. */
2975 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2976 "The file \"%%s\" is a pipe, and %s capture files can't be "
2977 "written to a pipe.", wtap_file_type_string(file_type));
2978 errmsg = errmsg_errno;
2981 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2982 /* Seen only when opening a capture file for writing. */
2983 errmsg = "TShark doesn't support writing capture files in that format.";
2986 case WTAP_ERR_UNSUPPORTED_ENCAP:
2988 errmsg = "TShark can't save this capture in that format.";
2990 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2991 "The file \"%%s\" is a capture for a network type that TShark doesn't support.\n"
2994 errmsg = errmsg_errno;
2998 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
3000 errmsg = "TShark can't save this capture in that format.";
3002 errmsg = "The file \"%s\" is a capture for a network type that TShark doesn't support.";
3005 case WTAP_ERR_BAD_RECORD:
3006 /* Seen only when opening a capture file for reading. */
3007 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3008 "The file \"%%s\" appears to be damaged or corrupt.\n"
3011 errmsg = errmsg_errno;
3014 case WTAP_ERR_CANT_OPEN:
3016 errmsg = "The file \"%s\" could not be created for some unknown reason.";
3018 errmsg = "The file \"%s\" could not be opened for some unknown reason.";
3021 case WTAP_ERR_SHORT_READ:
3022 errmsg = "The file \"%s\" appears to have been cut short"
3023 " in the middle of a packet or other data.";
3026 case WTAP_ERR_SHORT_WRITE:
3027 errmsg = "A full header couldn't be written to the file \"%s\".";
3031 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3032 "The file \"%%s\" could not be %s: %s.",
3033 for_writing ? "created" : "opened",
3034 wtap_strerror(err));
3035 errmsg = errmsg_errno;
3039 errmsg = file_open_error_message(err, for_writing);
3044 * Open/create errors are reported with an console message in TShark.
3047 open_failure_message(const char *filename, int err, gboolean for_writing)
3049 fprintf(stderr, "tshark: ");
3050 fprintf(stderr, file_open_error_message(err, for_writing), filename);
3051 fprintf(stderr, "\n");
3055 cf_open(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
3059 char err_msg[2048+1];
3061 wth = wtap_open_offline(fname, err, &err_info, FALSE);
3065 /* The open succeeded. Fill in the information for this file. */
3067 /* Initialize all data structures used for dissection. */
3071 cf->f_datalen = 0; /* not used, but set it anyway */
3073 /* Set the file name because we need it to set the follow stream filter.
3074 XXX - is that still true? We need it for other reasons, though,
3076 cf->filename = g_strdup(fname);
3078 /* Indicate whether it's a permanent or temporary file. */
3079 cf->is_tempfile = is_tempfile;
3081 /* If it's a temporary capture buffer file, mark it as not saved. */
3082 cf->user_saved = !is_tempfile;
3084 cf->cd_t = wtap_file_type(cf->wth);
3086 cf->drops_known = FALSE;
3088 cf->snap = wtap_snapshot_length(cf->wth);
3089 if (cf->snap == 0) {
3090 /* Snapshot length not known. */
3091 cf->has_snap = FALSE;
3092 cf->snap = WTAP_MAX_PACKET_SIZE;
3094 cf->has_snap = TRUE;
3095 nstime_set_zero(&cf->elapsed_time);
3096 nstime_set_unset(&first_ts);
3097 nstime_set_unset(&prev_dis_ts);
3098 nstime_set_unset(&prev_cap_ts);
3103 g_snprintf(err_msg, sizeof err_msg,
3104 cf_open_error_message(*err, err_info, FALSE, cf->cd_t), fname);
3105 cmdarg_err("%s", err_msg);
3111 * General errors are reported with an console message in TShark.
3114 failure_message(const char *msg_format, va_list ap)
3116 fprintf(stderr, "tshark: ");
3117 vfprintf(stderr, msg_format, ap);
3118 fprintf(stderr, "\n");
3122 * Read errors are reported with an console message in TShark.
3125 read_failure_message(const char *filename, int err)
3127 cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
3128 filename, strerror(err));
3132 * Report an error in command-line arguments.
3135 cmdarg_err(const char *fmt, ...)
3140 failure_message(fmt, ap);
3145 * Report additional information for an error in command-line arguments.
3148 cmdarg_err_cont(const char *fmt, ...)
3153 vfprintf(stderr, fmt, ap);
3154 fprintf(stderr, "\n");