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 <wsutil/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 */
100 #include <epan/funnel.h>
104 * This is the template for the decode as option; it is shared between the
105 * various functions that output the usage for this parameter.
107 static const gchar decode_as_arg_template[] = "<layer_type>==<selector>,<decode_as_protocol>";
109 static nstime_t first_ts;
110 static nstime_t prev_dis_ts;
111 static nstime_t prev_cap_ts;
112 static GString *comp_info_str, *runtime_info_str;
114 static gboolean print_packet_info; /* TRUE if we're to print packet information */
116 * The way the packet decode is to be written.
119 WRITE_TEXT, /* summary or detail text */
120 WRITE_XML, /* PDML or PSML */
121 WRITE_FIELDS /* User defined list of fields */
122 /* Add CSV and the like here */
124 static output_action_e output_action;
125 static gboolean do_dissection; /* TRUE if we have to dissect each packet */
126 static gboolean verbose;
127 static gboolean print_hex;
128 static gboolean line_buffered;
129 static guint32 cum_bytes = 0;
130 static print_format_e print_format = PR_FMT_TEXT;
131 static print_stream_t *print_stream;
133 static output_fields_t* output_fields = NULL;
136 * Standard secondary message for unexpected errors.
138 static const char please_report[] =
139 "Please report this to the Wireshark developers";
143 * TRUE if we're to print packet counts to keep track of captured packets.
145 static gboolean print_packet_counts;
148 static capture_options global_capture_opts;
151 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
152 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
155 static int capture(void);
156 static void report_counts(void);
158 static BOOL WINAPI capture_cleanup(DWORD);
160 static void capture_cleanup(int);
162 static void report_counts_siginfo(int);
165 #endif /* HAVE_LIBPCAP */
167 static int load_cap_file(capture_file *, char *, int, int, gint64);
168 static gboolean process_packet(capture_file *cf, gint64 offset,
169 const struct wtap_pkthdr *whdr, union wtap_pseudo_header *pseudo_header,
171 static void show_capture_file_io_error(const char *, int, gboolean);
172 static void show_print_file_io_error(int err);
173 static gboolean write_preamble(capture_file *cf);
174 static gboolean print_packet(capture_file *cf, epan_dissect_t *edt);
175 static gboolean write_finale(void);
176 static const char *cf_open_error_message(int err, gchar *err_info,
177 gboolean for_writing, int file_type);
179 static void open_failure_message(const char *filename, int err,
180 gboolean for_writing);
181 static void failure_message(const char *msg_format, va_list ap);
182 static void read_failure_message(const char *filename, int err);
187 * Mark a particular frame.
191 cf_mark_frame(capture_file *cf, frame_data *frame)
193 if (! frame->flags.marked) {
194 frame->flags.marked = TRUE;
195 if (cf->count > cf->marked_count)
201 * Unmark a particular frame.
205 cf_unmark_frame(capture_file *cf, frame_data *frame)
207 if (frame->flags.marked) {
208 frame->flags.marked = FALSE;
209 if (cf->marked_count > 0)
215 static void list_capture_types(void) {
218 fprintf(stderr, "editcap: The available capture file types for \"F\":\n");
219 for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
220 if (wtap_dump_can_open(i))
221 fprintf(stderr, " %s - %s\n",
222 wtap_file_type_short_string(i), wtap_file_type_string(i));
227 print_usage(gboolean print_ver)
234 "TShark " VERSION "%s\n"
235 "Dump and analyze network traffic.\n"
236 "See http://www.wireshark.org for more information.\n"
239 wireshark_svnversion, get_copyright_info());
243 fprintf(output, "\n");
244 fprintf(output, "Usage: tshark [options] ...\n");
245 fprintf(output, "\n");
248 fprintf(output, "Capture interface:\n");
249 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
250 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
251 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
252 fprintf(output, " -p don't capture in promiscuous mode\n");
254 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
256 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
257 fprintf(output, " -D print list of interfaces and exit\n");
258 fprintf(output, " -L print list of link-layer types of iface and exit\n");
259 fprintf(output, "\n");
260 fprintf(output, "Capture stop conditions:\n");
261 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
262 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
263 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
264 fprintf(output, " files:NUM - stop after NUM files\n");
265 /*fprintf(output, "\n");*/
266 fprintf(output, "Capture output:\n");
267 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
268 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
269 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
270 #endif /* HAVE_LIBPCAP */
272 /*fprintf(output, "\n");*/
273 fprintf(output, "Input file:\n");
274 fprintf(output, " -r <infile> set the filename to read from (no pipes or stdin!)\n");
276 fprintf(output, "\n");
277 fprintf(output, "Processing:\n");
278 fprintf(output, " -R <read filter> packet filter in Wireshark display filter syntax\n");
279 fprintf(output, " -n disable all name resolutions (def: all enabled)\n");
280 fprintf(output, " -N <name resolve flags> enable specific name resolution(s): \"mntC\"\n");
281 fprintf(output, " -d %s ...\n", decode_as_arg_template);
282 fprintf(output, " \"Decode As\", see the man page for details\n");
283 fprintf(output, " Example: tcp.port==8888,http\n");
285 /*fprintf(output, "\n");*/
286 fprintf(output, "Output:\n");
287 fprintf(output, " -w <outfile|-> set the output filename (or '-' for stdout)\n");
288 fprintf(output, " -C <config profile> start with specified configuration profile\n");
289 fprintf(output, " -F <output file type> set the output file type, default is libpcap\n");
290 fprintf(output, " an empty \"-F\" option will list the file types\n");
291 fprintf(output, " -V add output of packet tree (Packet Details)\n");
292 fprintf(output, " -S display packets even when writing to a file\n");
293 fprintf(output, " -x add output of hex and ASCII dump (Packet Bytes)\n");
294 fprintf(output, " -T pdml|ps|psml|text|fields\n");
295 fprintf(output, " format of text output (def: text)\n");
296 fprintf(output, " -e <field> field to print if -Tfields selected (e.g. tcp.port);\n");
297 fprintf(output, " this option can be repeated to print multiple fields\n");
298 fprintf(output, " -E<fieldsoption>=<value> set options for output when -Tfields selected:\n");
299 fprintf(output, " header=y|n switch headers on and off\n");
300 fprintf(output, " separator=/t|/s|<char> select tab, space, printable character as separator\n");
301 fprintf(output, " quote=d|s|n select double, single, no quotes for values\n");
302 fprintf(output, " -t ad|a|r|d|dd|e output format of time stamps (def: r: rel. to first)\n");
303 fprintf(output, " -l flush standard output after each packet\n");
304 fprintf(output, " -q be more quiet on stdout (e.g. when using statistics)\n");
305 fprintf(output, " -X <key>:<value> eXtension options, see the man page for details\n");
306 fprintf(output, " -z <statistics> various statistics, see the man page for details\n");
308 fprintf(output, "\n");
309 fprintf(output, "Miscellaneous:\n");
310 fprintf(output, " -h display this help and exit\n");
311 fprintf(output, " -v display version info and exit\n");
312 fprintf(output, " -o <name>:<value> ... override preference setting\n");
313 fprintf(output, " -K <keytab> keytab file to use for kerberos decryption\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:K: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 #if defined(HAVE_HEIMDAL_KERBEROS) || defined(HAVE_MIT_KERBEROS)
1004 case 'K': /* Kerberos keytab file */
1005 read_keytab_file(optarg);
1008 case 'D': /* Print a list of capture devices and exit */
1010 status = capture_opts_list_interfaces(FALSE);
1013 capture_option_specified = TRUE;
1019 output_fields_add(output_fields, optarg);
1023 if(!output_fields_set_option(output_fields, optarg)) {
1024 cmdarg_err("\"%s\" is not a valid field output option=value pair.", optarg);
1025 output_fields_list_options(stderr);
1030 out_file_type = wtap_short_string_to_file_type(optarg);
1031 if (out_file_type < 0) {
1032 cmdarg_err("\"%s\" isn't a valid capture file type", optarg);
1033 list_capture_types();
1037 case 'h': /* Print help and exit */
1041 case 'l': /* "Line-buffer" standard output */
1042 /* This isn't line-buffering, strictly speaking, it's just
1043 flushing the standard output after the information for
1044 each packet is printed; however, that should be good
1045 enough for all the purposes to which "-l" is put (and
1046 is probably actually better for "-V", as it does fewer
1049 See the comment in "process_packet()" for an explanation of
1050 why we do that, and why we don't just use "setvbuf()" to
1051 make the standard output line-buffered (short version: in
1052 Windows, "line-buffered" is the same as "fully-buffered",
1053 and the output buffer is only flushed when it fills up). */
1054 line_buffered = TRUE;
1056 case 'L': /* Print list of link-layer types and exit */
1058 list_link_layer_types = TRUE;
1060 capture_option_specified = TRUE;
1064 case 'n': /* No name resolution */
1065 g_resolv_flags = RESOLV_NONE;
1067 case 'N': /* Select what types of addresses/port #s to resolve */
1068 if (g_resolv_flags == RESOLV_ALL)
1069 g_resolv_flags = RESOLV_NONE;
1070 badopt = string_to_name_resolve(optarg, &g_resolv_flags);
1071 if (badopt != '\0') {
1072 cmdarg_err("-N specifies unknown resolving option '%c';",
1074 cmdarg_err_cont( " Valid options are 'm', 'n', 't', and 'C'");
1078 case 'o': /* Override preference from command line */
1079 switch (prefs_set_pref(optarg)) {
1084 case PREFS_SET_SYNTAX_ERR:
1085 cmdarg_err("Invalid -o flag \"%s\"", optarg);
1089 case PREFS_SET_NO_SUCH_PREF:
1090 case PREFS_SET_OBSOLETE:
1091 cmdarg_err("-o flag \"%s\" specifies unknown preference", optarg);
1096 case 'q': /* Quiet */
1099 case 'r': /* Read capture file x */
1100 cf_name = g_strdup(optarg);
1102 case 'R': /* Read file filter */
1105 case 'S': /* show packets in real time */
1106 print_packet_info = TRUE;
1108 case 't': /* Time stamp type */
1109 if (strcmp(optarg, "r") == 0)
1110 timestamp_set_type(TS_RELATIVE);
1111 else if (strcmp(optarg, "a") == 0)
1112 timestamp_set_type(TS_ABSOLUTE);
1113 else if (strcmp(optarg, "ad") == 0)
1114 timestamp_set_type(TS_ABSOLUTE_WITH_DATE);
1115 else if (strcmp(optarg, "d") == 0)
1116 timestamp_set_type(TS_DELTA);
1117 else if (strcmp(optarg, "dd") == 0)
1118 timestamp_set_type(TS_DELTA_DIS);
1119 else if (strcmp(optarg, "e") == 0)
1120 timestamp_set_type(TS_EPOCH);
1122 cmdarg_err("Invalid time stamp type \"%s\"",
1124 cmdarg_err_cont("It must be \"r\" for relative, \"a\" for absolute,");
1125 cmdarg_err_cont("\"ad\" for absolute with date, or \"d\" for delta.");
1129 case 'T': /* printing Type */
1130 if (strcmp(optarg, "text") == 0) {
1131 output_action = WRITE_TEXT;
1132 print_format = PR_FMT_TEXT;
1133 } else if (strcmp(optarg, "ps") == 0) {
1134 output_action = WRITE_TEXT;
1135 print_format = PR_FMT_PS;
1136 } else if (strcmp(optarg, "pdml") == 0) {
1137 output_action = WRITE_XML;
1139 } else if (strcmp(optarg, "psml") == 0) {
1140 output_action = WRITE_XML;
1142 } else if(strcmp(optarg, "fields") == 0) {
1143 output_action = WRITE_FIELDS;
1144 verbose = TRUE; /* Need full tree info */
1146 cmdarg_err("Invalid -T parameter.");
1147 cmdarg_err_cont("It must be \"ps\", \"text\", \"pdml\", \"psml\" or \"fields\".");
1151 case 'v': /* Show version and exit */
1152 printf("TShark " VERSION "%s\n"
1159 wireshark_svnversion, get_copyright_info(), comp_info_str->str,
1160 runtime_info_str->str);
1163 case 'V': /* Verbose */
1166 case 'x': /* Print packet data in hex (and ASCII) */
1172 /* We won't call the init function for the stat this soon
1173 as it would disallow MATE's fields (which are registered
1174 by the preferences set callback) from being used as
1175 part of a tap filter. Instead, we just add the argument
1176 to a list of stat arguments. */
1177 if (!process_stat_cmd_arg(optarg)) {
1178 cmdarg_err("invalid -z argument.");
1179 cmdarg_err_cont(" -z argument must be one of :");
1180 list_stat_cmd_args();
1185 case '?': /* Bad flag - print usage message */
1188 list_capture_types();
1198 /* If we specified output fields, but not the output field type... */
1199 if(WRITE_FIELDS != output_action && 0 != output_fields_num_fields(output_fields)) {
1200 cmdarg_err("Output fields were specified with \"-e\", "
1201 "but \"-Tfields\" was not specified.");
1203 } else if(WRITE_FIELDS == output_action && 0 == output_fields_num_fields(output_fields)) {
1204 cmdarg_err("\"-Tfields\" was specified, but no fields were "
1205 "specified with \"-e\".");
1210 /* If no capture filter or read filter has been specified, and there are
1211 still command-line arguments, treat them as the tokens of a capture
1212 filter (if no "-r" flag was specified) or a read filter (if a "-r"
1213 flag was specified. */
1214 if (optind < argc) {
1215 if (cf_name != NULL) {
1216 if (rfilter != NULL) {
1217 cmdarg_err("Read filters were specified both with \"-R\" "
1218 "and with additional command-line arguments");
1221 rfilter = get_args_as_string(argc, argv, optind);
1224 if (global_capture_opts.has_cfilter) {
1225 cmdarg_err("Capture filters were specified both with \"-f\""
1226 " and with additional command-line arguments");
1229 global_capture_opts.has_cfilter = TRUE;
1230 global_capture_opts.cfilter = get_args_as_string(argc, argv, optind);
1232 capture_option_specified = TRUE;
1238 if (!global_capture_opts.saving_to_file) {
1239 /* We're not saving the capture to a file; if "-q" wasn't specified,
1240 we should print packet information */
1242 print_packet_info = TRUE;
1244 /* We're saving to a file; if we're writing to the standard output.
1245 and we'll also be writing dissected packets to the standard
1246 output, reject the request. At best, we could redirect that
1247 to the standard error; we *can't* write both to the standard
1248 output and have either of them be useful. */
1249 if (strcmp(global_capture_opts.save_file, "-") == 0 && print_packet_info) {
1250 cmdarg_err("You can't write both raw packet data and dissected packets"
1251 " to the standard output.");
1256 /* We're not saving the capture to a file; if "-q" wasn't specified,
1257 we should print packet information */
1259 print_packet_info = TRUE;
1262 #ifndef HAVE_LIBPCAP
1263 if (capture_option_specified)
1264 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1271 /* We don't support capture filters when reading from a capture file
1272 (the BPF compiler doesn't support all link-layer types that we
1273 support in capture files we read). */
1275 if (cf_name != NULL) {
1276 if (global_capture_opts.has_cfilter) {
1277 cmdarg_err("Only read filters, not capture filters, "
1278 "can be specified when reading a capture file.");
1285 if (output_action != WRITE_TEXT) {
1286 cmdarg_err("Raw packet hex data can only be printed as text or PostScript");
1292 if (list_link_layer_types) {
1293 /* We're supposed to list the link-layer types for an interface;
1294 did the user also specify a capture file to be read? */
1296 /* Yes - that's bogus. */
1297 cmdarg_err("You can't specify -L and a capture file to be read.");
1300 /* No - did they specify a ring buffer option? */
1301 if (global_capture_opts.multi_files_on) {
1302 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
1308 * "-r" was specified, so we're reading a capture file.
1309 * Capture options don't apply here.
1311 if (global_capture_opts.multi_files_on) {
1312 cmdarg_err("Multiple capture files requested, but "
1313 "a capture isn't being done.");
1316 if (global_capture_opts.has_file_duration) {
1317 cmdarg_err("Switching capture files after a time interval was specified, but "
1318 "a capture isn't being done.");
1321 if (global_capture_opts.has_ring_num_files) {
1322 cmdarg_err("A ring buffer of capture files was specified, but "
1323 "a capture isn't being done.");
1326 if (global_capture_opts.has_autostop_files) {
1327 cmdarg_err("A maximum number of capture files was specified, but "
1328 "a capture isn't being done.");
1332 /* Note: TShark now allows the restriction of a _read_ file by packet count
1333 * and byte count as well as a write file. Other autostop options remain valid
1334 * only for a write file.
1336 if (global_capture_opts.has_autostop_duration) {
1337 cmdarg_err("A maximum capture time was specified, but "
1338 "a capture isn't being done.");
1343 * "-r" wasn't specified, so we're doing a live capture.
1345 if (global_capture_opts.saving_to_file) {
1346 /* They specified a "-w" flag, so we'll be saving to a capture file. */
1348 /* When capturing, we only support writing libpcap format. */
1349 if (out_file_type != WTAP_FILE_PCAP) {
1350 cmdarg_err("Live captures can only be saved in libpcap format.");
1353 if (global_capture_opts.multi_files_on) {
1354 /* Multiple-file mode doesn't work under certain conditions:
1355 a) it doesn't work if you're writing to the standard output;
1356 b) it doesn't work if you're writing to a pipe;
1358 if (strcmp(global_capture_opts.save_file, "-") == 0) {
1359 cmdarg_err("Multiple capture files requested, but "
1360 "the capture is being written to the standard output.");
1363 if (global_capture_opts.output_to_pipe) {
1364 cmdarg_err("Multiple capture files requested, but "
1365 "the capture file is a pipe.");
1368 if (!global_capture_opts.has_autostop_filesize &&
1369 !global_capture_opts.has_file_duration) {
1370 cmdarg_err("Multiple capture files requested, but "
1371 "no maximum capture file size or duration was specified.");
1376 /* They didn't specify a "-w" flag, so we won't be saving to a
1377 capture file. Check for options that only make sense if
1378 we're saving to a file. */
1379 if (global_capture_opts.has_autostop_filesize) {
1380 cmdarg_err("Maximum capture file size specified, but "
1381 "capture isn't being saved to a file.");
1384 if (global_capture_opts.multi_files_on) {
1385 cmdarg_err("Multiple capture files requested, but "
1386 "the capture isn't being saved to a file.");
1395 /* Start windows sockets */
1396 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1399 /* Notify all registered modules that have had any of their preferences
1400 changed either from one of the preferences file or from the command
1401 line that their preferences have changed. */
1404 /* At this point MATE will have registered its field array so we can
1405 have a tap filter with one of MATE's late-registered fields as part
1406 of the filter. We can now process all the "-z" arguments. */
1407 start_requested_stats();
1409 /* disabled protocols as per configuration file */
1410 if (gdp_path == NULL && dp_path == NULL) {
1411 set_disabled_protos_list();
1414 /* Build the column format array */
1415 col_setup(&cfile.cinfo, prefs->num_cols);
1416 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1417 cfile.cinfo.col_fmt[i] = get_column_format(i);
1418 cfile.cinfo.col_title[i] = g_strdup(get_column_title(i));
1419 if (cfile.cinfo.col_fmt[i] == COL_CUSTOM) {
1420 cfile.cinfo.col_custom_field[i] = g_strdup(get_column_custom_field(i));
1422 cfile.cinfo.col_custom_field[i] = NULL;
1424 cfile.cinfo.fmt_matx[i] = (gboolean *) g_malloc0(sizeof(gboolean) *
1426 get_column_format_matches(cfile.cinfo.fmt_matx[i], cfile.cinfo.col_fmt[i]);
1427 cfile.cinfo.col_data[i] = NULL;
1428 if (cfile.cinfo.col_fmt[i] == COL_INFO)
1429 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_INFO_LEN);
1431 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1432 cfile.cinfo.col_fence[i] = 0;
1433 cfile.cinfo.col_expr.col_expr[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1434 cfile.cinfo.col_expr.col_expr_val[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1437 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1440 for (j = 0; j < NUM_COL_FMTS; j++) {
1441 if (!cfile.cinfo.fmt_matx[i][j])
1444 if (cfile.cinfo.col_first[j] == -1)
1445 cfile.cinfo.col_first[j] = i;
1446 cfile.cinfo.col_last[j] = i;
1451 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
1452 capture_opts_trim_ring_num_files(&global_capture_opts);
1455 if (rfilter != NULL) {
1456 if (!dfilter_compile(rfilter, &rfcode)) {
1457 cmdarg_err("%s", dfilter_error_msg);
1459 #ifdef HAVE_PCAP_OPEN_DEAD
1463 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1465 if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1467 " Note: That display filter code looks like a valid capture filter;");
1469 " maybe you mixed them up?");
1478 cfile.rfcode = rfcode;
1480 if (print_packet_info) {
1481 /* If we're printing as text or PostScript, we have
1482 to create a print stream. */
1483 if (output_action == WRITE_TEXT) {
1484 switch (print_format) {
1487 print_stream = print_stream_text_stdio_new(stdout);
1491 print_stream = print_stream_ps_stdio_new(stdout);
1495 g_assert_not_reached();
1500 /* We have to dissect each packet if:
1502 we're printing information about each packet;
1504 we're using a read filter on the packets;
1506 we're using any taps. */
1507 do_dissection = print_packet_info || rfcode || have_tap_listeners();
1511 * We're reading a capture file.
1515 * Immediately relinquish any special privileges we have; we must not
1516 * be allowed to read any capture files the user running TShark
1519 relinquish_special_privs_perm();
1520 print_current_user();
1522 if (cf_open(&cfile, cf_name, FALSE, &err) != CF_OK) {
1527 /* Set timestamp precision; there should arguably be a command-line
1528 option to let the user set this. */
1529 switch(wtap_file_tsprecision(cfile.wth)) {
1530 case(WTAP_FILE_TSPREC_SEC):
1531 timestamp_set_precision(TS_PREC_AUTO_SEC);
1533 case(WTAP_FILE_TSPREC_DSEC):
1534 timestamp_set_precision(TS_PREC_AUTO_DSEC);
1536 case(WTAP_FILE_TSPREC_CSEC):
1537 timestamp_set_precision(TS_PREC_AUTO_CSEC);
1539 case(WTAP_FILE_TSPREC_MSEC):
1540 timestamp_set_precision(TS_PREC_AUTO_MSEC);
1542 case(WTAP_FILE_TSPREC_USEC):
1543 timestamp_set_precision(TS_PREC_AUTO_USEC);
1545 case(WTAP_FILE_TSPREC_NSEC):
1546 timestamp_set_precision(TS_PREC_AUTO_NSEC);
1549 g_assert_not_reached();
1552 /* Process the packets in the file */
1554 err = load_cap_file(&cfile, global_capture_opts.save_file, out_file_type,
1555 global_capture_opts.has_autostop_packets ? global_capture_opts.autostop_packets : 0,
1556 global_capture_opts.has_autostop_filesize ? global_capture_opts.autostop_filesize : 0);
1558 err = load_cap_file(&cfile, NULL, out_file_type, 0, 0);
1566 /* No capture file specified, so we're supposed to do a live capture
1567 (or get a list of link-layer types for a live capture device);
1568 do we have support for live captures? */
1575 cmdarg_err("WinPcap couldn't be found.");
1576 detailed_err = cant_load_winpcap_err("TShark");
1577 cmdarg_err_cont("%s", detailed_err);
1578 g_free(detailed_err);
1583 /* trim the interface name and exit if that failed */
1584 if (!capture_opts_trim_iface(&global_capture_opts,
1585 (prefs->capture_device) ? get_if_name(prefs->capture_device) : NULL)) {
1589 /* if requested, list the link layer types and exit */
1590 if (list_link_layer_types) {
1591 status = capture_opts_list_link_layer_types(&global_capture_opts, FALSE);
1595 if (print_packet_info) {
1596 if (!write_preamble(NULL)) {
1598 show_print_file_io_error(err);
1601 } else if (!quiet) {
1603 * We're not printing information for each packet, and the user
1604 * didn't ask us not to print a count of packets as they arrive,
1605 * so print that count so the user knows that packets are arriving.
1607 * XXX - what if the user wants to do a live capture, doesn't want
1608 * to save it to a file, doesn't want information printed for each
1609 * packet, does want some "-z" statistic, and wants packet counts
1610 * so they know whether they're seeing any packets?
1612 print_packet_counts = TRUE;
1615 /* For now, assume libpcap gives microsecond precision. */
1616 timestamp_set_precision(TS_PREC_AUTO_USEC);
1620 if (print_packet_info) {
1621 if (!write_finale()) {
1623 show_print_file_io_error(err);
1627 /* No - complain. */
1628 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1633 draw_tap_listeners(TRUE);
1634 funnel_dump_all_text_windows();
1637 output_fields_free(output_fields);
1638 output_fields = NULL;
1643 /*#define USE_BROKEN_G_MAIN_LOOP*/
1645 #ifdef USE_BROKEN_G_MAIN_LOOP
1648 gboolean loop_running = FALSE;
1650 guint32 packet_count = 0;
1653 /* XXX - move to the right position / file */
1654 /* read from a pipe (callback) */
1655 typedef gboolean (*pipe_input_cb_t) (gint source, gpointer user_data);
1657 typedef struct pipe_input_tag {
1661 pipe_input_cb_t input_cb;
1662 guint pipe_input_id;
1664 GStaticMutex callback_running;
1668 static pipe_input_t pipe_input;
1671 /* The timer has expired, see if there's stuff to read from the pipe,
1672 if so, do the callback */
1674 pipe_timer_cb(gpointer data)
1678 gboolean result, result1;
1680 pipe_input_t *pipe_input = data;
1681 gint iterations = 0;
1684 g_static_mutex_lock (&pipe_input->callback_running);
1686 /* try to read data from the pipe only 5 times, to avoid blocking */
1687 while(iterations < 5) {
1688 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: new iteration");*/
1690 /* Oddly enough although Named pipes don't work on win9x,
1691 PeekNamedPipe does !!! */
1692 handle = (HANDLE) _get_osfhandle (pipe_input->source);
1693 result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
1695 /* Get the child process exit status */
1696 result1 = GetExitCodeProcess((HANDLE)*(pipe_input->child_process),
1699 /* If the Peek returned an error, or there are bytes to be read
1700 or the childwatcher thread has terminated then call the normal
1702 if (!result || avail > 0 || childstatus != STILL_ACTIVE) {
1704 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: data avail");*/
1706 /* And call the real handler */
1707 if (!pipe_input->input_cb(pipe_input->source, pipe_input->user_data)) {
1708 g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: input pipe closed, iterations: %u", iterations);
1709 /* pipe closed, return false so that the timer is stopped */
1710 g_static_mutex_unlock (&pipe_input->callback_running);
1715 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: no data avail");*/
1716 /* No data, stop now */
1723 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: finished with iterations: %u, new timer", iterations);*/
1725 g_static_mutex_unlock (&pipe_input->callback_running);
1727 /* we didn't stopped the timer, so let it run */
1734 pipe_input_set_handler(gint source, gpointer user_data, int *child_process, pipe_input_cb_t input_cb)
1737 pipe_input.source = source;
1738 pipe_input.child_process = child_process;
1739 pipe_input.user_data = user_data;
1740 pipe_input.input_cb = input_cb;
1743 g_static_mutex_init(&pipe_input.callback_running);
1744 /* Tricky to use pipes in win9x, as no concept of wait. NT can
1745 do this but that doesn't cover all win32 platforms. GTK can do
1746 this but doesn't seem to work over processes. Attempt to do
1747 something similar here, start a timer and check for data on every
1749 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_input_set_handler: new");*/
1750 pipe_input.pipe_input_id = g_timeout_add(200, pipe_timer_cb, &pipe_input);
1760 #ifdef USE_TSHARK_SELECT
1764 struct sigaction action, oldaction;
1768 * XXX - dropping privileges is still required, until code cleanup is done
1770 * remove all dependencies to pcap specific code and using only dumpcap is almost done.
1771 * when it's done, we don't need special privileges to run tshark at all,
1772 * therefore we don't need to drop these privileges
1773 * The only thing we might want to keep is a warning if tshark is run as root,
1774 * as it's no longer necessary and potentially dangerous.
1776 * THE FOLLOWING IS THE FORMER COMMENT WHICH IS NO LONGER REALLY VALID:
1777 * We've opened the capture device, so we shouldn't need any special
1778 * privileges any more; relinquish those privileges.
1780 * XXX - if we have saved set-user-ID support, we should give up those
1781 * privileges immediately, and then reclaim them long enough to get
1782 * a list of network interfaces and to open one, and then give them
1783 * up again, so that stuff we do while processing the argument list,
1784 * reading the user's preferences, loading and starting plugins
1785 * (especially *user* plugins), etc. is done with the user's privileges,
1786 * not special privileges.
1788 relinquish_special_privs_perm();
1789 print_current_user();
1791 /* Initialize all data structures used for dissection. */
1795 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1796 SetConsoleCtrlHandler(capture_cleanup, TRUE);
1798 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
1800 action.sa_handler = capture_cleanup;
1801 action.sa_flags = 0;
1802 sigemptyset(&action.sa_mask);
1803 sigaction(SIGTERM, &action, NULL);
1804 sigaction(SIGINT, &action, NULL);
1805 sigaction(SIGHUP, NULL, &oldaction);
1806 if (oldaction.sa_handler == SIG_DFL)
1807 sigaction(SIGHUP, &action, NULL);
1810 /* Catch SIGINFO and, if we get it and we're capturing to a file in
1811 quiet mode, report the number of packets we've captured. */
1812 action.sa_handler = report_counts_siginfo;
1813 action.sa_flags = 0;
1814 sigemptyset(&action.sa_mask);
1815 sigaction(SIGINFO, &action, NULL);
1816 #endif /* SIGINFO */
1819 global_capture_opts.state = CAPTURE_PREPARING;
1821 /* Let the user know what interface was chosen. */
1822 global_capture_opts.iface_descr = get_interface_descriptive_name(global_capture_opts.iface);
1823 fprintf(stderr, "Capturing on %s\n", global_capture_opts.iface_descr);
1825 ret = sync_pipe_start(&global_capture_opts);
1830 /* the actual capture loop
1832 * XXX - glib doesn't seem to provide any event based loop handling.
1834 * XXX - for whatever reason,
1835 * calling g_main_loop_new() ends up in 100% cpu load.
1837 * But that doesn't matter: in UNIX we can use select() to find an input
1838 * source with something to do.
1840 * But that doesn't matter because we're in a CLI (that doesn't need to
1841 * update a GUI or something at the same time) so it's OK if we block
1842 * trying to read from the pipe.
1844 * So all the stuff in USE_TSHARK_SELECT could be removed unless I'm
1845 * wrong (but I leave it there in case I am...).
1848 #ifdef USE_TSHARK_SELECT
1850 FD_SET(pipe_input.source, &readfds);
1853 loop_running = TRUE;
1855 while (loop_running)
1857 #ifdef USE_TSHARK_SELECT
1858 ret = select(pipe_input.source+1, &readfds, NULL, NULL, NULL);
1864 } else if (ret == 1) {
1866 /* Call the real handler */
1867 if (!pipe_input.input_cb(pipe_input.source, pipe_input.user_data)) {
1868 g_log(NULL, G_LOG_LEVEL_DEBUG, "input pipe closed");
1871 #ifdef USE_TSHARK_SELECT
1880 /* XXX - move the call to main_window_update() out of capture_sync.c */
1881 /* dummy for capture_sync.c to make linker happy */
1882 void main_window_update(void)
1886 /* capture child detected an error */
1888 capture_input_error_message(capture_options *capture_opts _U_, char *error_msg, char *secondary_error_msg)
1890 cmdarg_err("%s", error_msg);
1891 cmdarg_err_cont("%s", secondary_error_msg);
1895 /* capture child detected an capture filter related error */
1897 capture_input_cfilter_error_message(capture_options *capture_opts, char *error_message)
1899 dfilter_t *rfcode = NULL;
1902 if (dfilter_compile(capture_opts->cfilter, &rfcode) && rfcode != NULL) {
1904 "Invalid capture filter: \"%s\"!\n"
1906 "That string looks like a valid display filter; however, it isn't a valid\n"
1907 "capture filter (%s).\n"
1909 "Note that display filters and capture filters don't have the same syntax,\n"
1910 "so you can't use most display filter expressions as capture filters.\n"
1912 "See the User's Guide for a description of the capture filter syntax.",
1913 capture_opts->cfilter, error_message);
1914 dfilter_free(rfcode);
1917 "Invalid capture filter: \"%s\"!\n"
1919 "That string isn't a valid capture filter (%s).\n"
1920 "See the User's Guide for a description of the capture filter syntax.",
1921 capture_opts->cfilter, error_message);
1926 /* capture child tells us we have a new (or the first) capture file */
1928 capture_input_new_file(capture_options *capture_opts, gchar *new_file)
1930 gboolean is_tempfile;
1934 if(capture_opts->state == CAPTURE_PREPARING) {
1935 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "Capture started!");
1937 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "File: \"%s\"", new_file);
1939 g_assert(capture_opts->state == CAPTURE_PREPARING || capture_opts->state == CAPTURE_RUNNING);
1941 capture_opts->cf = &cfile;
1943 /* free the old filename */
1944 if(capture_opts->save_file != NULL) {
1945 /* we start a new capture file, close the old one (if we had one before) */
1946 if( ((capture_file *) capture_opts->cf)->state != FILE_CLOSED) {
1947 if(capture_opts->cf != NULL && ((capture_file *) capture_opts->cf)->wth != NULL) {
1948 wtap_close(((capture_file *) capture_opts->cf)->wth);
1951 g_free(capture_opts->save_file);
1952 is_tempfile = FALSE;
1954 /* we didn't had a save_file before, must be a tempfile */
1958 /* save the new filename */
1959 capture_opts->save_file = g_strdup(new_file);
1961 /* if we are in real-time mode, open the new file now */
1963 /* Attempt to open the capture file and set up to read from it. */
1964 switch(cf_open(capture_opts->cf, capture_opts->save_file, is_tempfile, &err)) {
1968 /* Don't unlink (delete) the save file - leave it around,
1969 for debugging purposes. */
1970 g_free(capture_opts->save_file);
1971 capture_opts->save_file = NULL;
1976 capture_opts->state = CAPTURE_RUNNING;
1982 /* capture child tells us we have new packets to read */
1984 capture_input_new_packets(capture_options *capture_opts, int to_read)
1990 capture_file *cf = capture_opts->cf;
1995 * Prevent a SIGINFO handler from writing to stdout while we're
1996 * doing so; instead, have it just set a flag telling us to print
1997 * that information when we're done.
2000 #endif /* SIGINFO */
2003 while (to_read-- && cf->wth) {
2004 ret = wtap_read(cf->wth, &err, &err_info, &data_offset);
2006 /* read from file failed, tell the capture child to stop */
2007 sync_pipe_stop(capture_opts);
2008 wtap_close(cf->wth);
2011 ret = process_packet(cf, data_offset, wtap_phdr(cf->wth),
2012 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth));
2015 /* packet sucessfully read and gone through the "Read Filter" */
2021 * Dumpcap's doing all the work; we're not doing any dissection.
2022 * Count all the packets it wrote.
2024 packet_count += to_read;
2027 if (print_packet_counts) {
2028 /* We're printing packet counts. */
2029 if (packet_count != 0) {
2030 fprintf(stderr, "\r%u ", packet_count);
2031 /* stderr could be line buffered */
2038 * Allow SIGINFO handlers to write.
2043 * If a SIGINFO handler asked us to write out capture counts, do so.
2047 #endif /* SIGINFO */
2053 if (!print_packet_counts) {
2054 /* Report the count only if we aren't printing a packet count
2055 as packets arrive. */
2056 fprintf(stderr, "%u packet%s captured\n", packet_count,
2057 plurality(packet_count, "", "s"));
2060 infoprint = FALSE; /* we just reported it */
2061 #endif /* SIGINFO */
2066 report_counts_siginfo(int signum _U_)
2068 int sav_errno = errno;
2069 /* If we've been told to delay printing, just set a flag asking
2070 that we print counts (if we're supposed to), otherwise print
2071 the count of packets captured (if we're supposed to). */
2078 #endif /* SIGINFO */
2081 /* capture child detected any packet drops? */
2083 capture_input_drops(capture_options *capture_opts _U_, guint32 dropped)
2085 if (print_packet_counts) {
2086 /* We're printing packet counts to stderr.
2087 Send a newline so that we move to the line after the packet count. */
2088 fprintf(stderr, "\n");
2092 /* We're printing packet counts to stderr.
2093 Send a newline so that we move to the line after the packet count. */
2094 fprintf(stderr, "%u packet%s dropped\n", dropped, plurality(dropped, "", "s"));
2099 /* capture child closed its side of the pipe, do the required cleanup */
2101 capture_input_closed(capture_options *capture_opts)
2105 if(capture_opts->cf != NULL && ((capture_file *) capture_opts->cf)->wth != NULL) {
2106 wtap_close(((capture_file *) capture_opts->cf)->wth);
2108 #ifdef USE_BROKEN_G_MAIN_LOOP
2109 /*g_main_loop_quit(loop);*/
2112 loop_running = FALSE;
2121 capture_cleanup(DWORD ctrltype _U_)
2123 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
2124 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
2125 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
2126 like SIGTERM at least when the machine's shutting down.
2128 For now, we handle them all as indications that we should clean up
2129 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
2132 However, as handlers run in a new thread, we can't just longjmp
2133 out; we have to set "ld.go" to FALSE, and must return TRUE so that
2134 no other handler - such as one that would terminate the process -
2137 XXX - for some reason, typing ^C to TShark, if you run this in
2138 a Cygwin console window in at least some versions of Cygwin,
2139 causes TShark to terminate immediately; this routine gets
2140 called, but the main loop doesn't get a chance to run and
2141 exit cleanly, at least if this is compiled with Microsoft Visual
2142 C++ (i.e., it's a property of the Cygwin console window or Bash;
2143 it happens if TShark is not built with Cygwin - for all I know,
2144 building it with Cygwin may make the problem go away). */
2146 /* tell the capture child to stop */
2147 sync_pipe_stop(&global_capture_opts);
2149 /* don't stop our own loop already here, otherwise status messages and
2150 * cleanup wouldn't be done properly. The child will indicate the stop of
2151 * everything by calling capture_input_closed() later */
2157 capture_cleanup(int signum _U_)
2159 /* tell the capture child to stop */
2160 sync_pipe_stop(&global_capture_opts);
2163 #endif /* HAVE_LIBPCAP */
2166 load_cap_file(capture_file *cf, char *save_file, int out_file_type,
2167 int max_packet_count, gint64 max_byte_count)
2170 int snapshot_length;
2175 char *save_file_string = NULL;
2177 linktype = wtap_file_encap(cf->wth);
2178 if (save_file != NULL) {
2179 /* Get a string that describes what we're writing to */
2180 save_file_string = output_file_description(save_file);
2182 /* Set up to write to the capture file. */
2183 snapshot_length = wtap_snapshot_length(cf->wth);
2184 if (snapshot_length == 0) {
2185 /* Snapshot length of input file not known. */
2186 snapshot_length = WTAP_MAX_PACKET_SIZE;
2188 pdh = wtap_dump_open(save_file, out_file_type, linktype, snapshot_length,
2189 FALSE /* compressed */, &err);
2192 /* We couldn't set up to write to the capture file. */
2195 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2196 cmdarg_err("Capture files can't be written in that format.");
2199 case WTAP_ERR_UNSUPPORTED_ENCAP:
2200 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2201 cmdarg_err("The capture file being read can't be written in "
2205 case WTAP_ERR_CANT_OPEN:
2206 cmdarg_err("The %s couldn't be created for some "
2207 "unknown reason.", save_file_string);
2210 case WTAP_ERR_SHORT_WRITE:
2211 cmdarg_err("A full header couldn't be written to the %s.",
2216 cmdarg_err("The %s could not be created: %s.", save_file_string,
2217 wtap_strerror(err));
2223 if (print_packet_info) {
2224 if (!write_preamble(cf)) {
2226 show_print_file_io_error(err);
2232 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
2233 if (process_packet(cf, data_offset, wtap_phdr(cf->wth),
2234 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth))) {
2235 /* Either there's no read filtering or this packet passed the
2236 filter, so, if we're writing to a capture file, write
2239 if (!wtap_dump(pdh, wtap_phdr(cf->wth),
2240 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2242 /* Error writing to a capture file */
2243 show_capture_file_io_error(save_file, err, FALSE);
2244 wtap_dump_close(pdh, &err);
2248 /* Stop reading if we have the maximum number of packets;
2249 * When the -c option has not been used, max_packet_count
2250 * starts at 0, which practically means, never stop reading.
2251 * (unless we roll over max_packet_count ?)
2253 if( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
2254 err = 0; /* This is not an error */
2260 /* Print a message noting that the read failed somewhere along the line. */
2263 case WTAP_ERR_UNSUPPORTED_ENCAP:
2264 cmdarg_err("\"%s\" has a packet with a network type that TShark doesn't support.\n(%s)",
2265 cf->filename, err_info);
2269 case WTAP_ERR_CANT_READ:
2270 cmdarg_err("An attempt to read from \"%s\" failed for some unknown reason.",
2274 case WTAP_ERR_SHORT_READ:
2275 cmdarg_err("\"%s\" appears to have been cut short in the middle of a packet.",
2279 case WTAP_ERR_BAD_RECORD:
2280 cmdarg_err("\"%s\" appears to be damaged or corrupt.\n(%s)",
2281 cf->filename, err_info);
2286 cmdarg_err("An error occurred while reading \"%s\": %s.",
2287 cf->filename, wtap_strerror(err));
2290 if (save_file != NULL) {
2291 /* Now close the capture file. */
2292 if (!wtap_dump_close(pdh, &err))
2293 show_capture_file_io_error(save_file, err, TRUE);
2296 if (save_file != NULL) {
2297 /* Now close the capture file. */
2298 if (!wtap_dump_close(pdh, &err))
2299 show_capture_file_io_error(save_file, err, TRUE);
2301 if (print_packet_info) {
2302 if (!write_finale()) {
2304 show_print_file_io_error(err);
2311 wtap_close(cf->wth);
2314 if (save_file_string != NULL)
2315 g_free(save_file_string);
2321 fill_in_fdata(frame_data *fdata, capture_file *cf,
2322 const struct wtap_pkthdr *phdr, gint64 offset)
2327 fdata->num = cf->count;
2328 fdata->pkt_len = phdr->len;
2329 cum_bytes += phdr->len;
2330 fdata->cum_bytes = cum_bytes;
2331 fdata->cap_len = phdr->caplen;
2332 fdata->file_off = offset;
2333 fdata->lnk_t = phdr->pkt_encap;
2334 fdata->abs_ts.secs = phdr->ts.secs;
2335 fdata->abs_ts.nsecs = phdr->ts.nsecs;
2336 fdata->flags.passed_dfilter = 0;
2337 fdata->flags.encoding = CHAR_ASCII;
2338 fdata->flags.visited = 0;
2339 fdata->flags.marked = 0;
2340 fdata->flags.ref_time = 0;
2341 fdata->color_filter = NULL;
2343 /* If we don't have the time stamp of the first packet in the
2344 capture, it's because this is the first packet. Save the time
2345 stamp of this packet as the time stamp of the first packet. */
2346 if (nstime_is_unset(&first_ts)) {
2347 first_ts = fdata->abs_ts;
2350 /* If we don't have the time stamp of the previous captured packet,
2351 it's because this is the first packet. Save the time
2352 stamp of this packet as the time stamp of the previous captured
2354 if (nstime_is_unset(&prev_cap_ts)) {
2355 prev_cap_ts = fdata->abs_ts;
2358 /* Get the time elapsed between the first packet and this packet. */
2359 nstime_delta(&fdata->rel_ts, &fdata->abs_ts, &first_ts);
2361 /* If it's greater than the current elapsed time, set the elapsed time
2362 to it (we check for "greater than" so as not to be confused by
2363 time moving backwards). */
2364 if ((gint32)cf->elapsed_time.secs < fdata->rel_ts.secs
2365 || ((gint32)cf->elapsed_time.secs == fdata->rel_ts.secs && (gint32)cf->elapsed_time.nsecs < fdata->rel_ts.nsecs)) {
2366 cf->elapsed_time = fdata->rel_ts;
2369 /* If we don't have the time stamp of the previous displayed packet,
2370 it's because this is the first packet that's being displayed. Save the time
2371 stamp of this packet as the time stamp of the previous displayed
2373 if (nstime_is_unset(&prev_dis_ts))
2374 prev_dis_ts = fdata->abs_ts;
2376 /* Get the time elapsed between the previous displayed packet and
2378 nstime_delta(&fdata->del_dis_ts, &fdata->abs_ts, &prev_dis_ts);
2380 /* Get the time elapsed between the previous captured packet and
2382 nstime_delta(&fdata->del_cap_ts, &fdata->abs_ts, &prev_cap_ts);
2383 prev_cap_ts = fdata->abs_ts;
2386 /* Free up all data attached to a "frame_data" structure. */
2388 clear_fdata(frame_data *fdata)
2391 g_slist_free(fdata->pfd);
2395 process_packet(capture_file *cf, gint64 offset, const struct wtap_pkthdr *whdr,
2396 union wtap_pseudo_header *pseudo_header, const guchar *pd)
2399 gboolean create_proto_tree;
2400 epan_dissect_t *edt;
2403 /* Count this packet. */
2406 /* If we're going to print packet information, or we're going to
2407 run a read filter, or we're going to process taps, set up to
2408 do a dissection and do so. */
2409 if (do_dissection) {
2410 fill_in_fdata(&fdata, cf, whdr, offset);
2412 if (print_packet_info) {
2413 /* Grab any resolved addresses */
2415 if (g_resolv_flags) {
2416 host_name_lookup_process(NULL);
2421 if (cf->rfcode || verbose || num_tap_filters!=0 || have_custom_cols(&cf->cinfo))
2422 create_proto_tree = TRUE;
2424 create_proto_tree = FALSE;
2425 /* The protocol tree will be "visible", i.e., printed, only if we're
2426 printing packet details, which is true if we're printing stuff
2427 ("print_packet_info" is true) and we're in verbose mode ("verbose"
2429 edt = epan_dissect_new(create_proto_tree, print_packet_info && verbose);
2431 /* If we're running a read filter, prime the epan_dissect_t with that
2434 epan_dissect_prime_dfilter(edt, cf->rfcode);
2436 col_custom_prime_edt(edt, &cf->cinfo);
2438 tap_queue_init(edt);
2440 /* We only need the columns if we're printing packet info but we're
2441 *not* verbose; in verbose mode, we print the protocol tree, not
2442 the protocol summary. */
2443 epan_dissect_run(edt, pseudo_header, pd, &fdata,
2444 (print_packet_info && !verbose) ? &cf->cinfo : NULL);
2446 tap_push_tapped_queue(edt);
2448 /* Run the read filter if we have one. */
2450 passed = dfilter_apply_edt(cf->rfcode, edt);
2454 /* We're not running a display filter and we're not printing any
2455 packet information, so we don't need to do a dissection, and all
2456 packets are processed. */
2462 /* Keep the time of the current packet if the packet passed
2463 the read filter so that the delta time since last displayed
2464 packet can be calculated */
2465 prev_dis_ts = fdata.abs_ts;
2467 /* Process this packet. */
2468 if (print_packet_info) {
2469 /* We're printing packet information; print the information for
2471 print_packet(cf, edt);
2473 /* The ANSI C standard does not appear to *require* that a line-buffered
2474 stream be flushed to the host environment whenever a newline is
2475 written, it just says that, on such a stream, characters "are
2476 intended to be transmitted to or from the host environment as a
2477 block when a new-line character is encountered".
2479 The Visual C++ 6.0 C implementation doesn't do what is intended;
2480 even if you set a stream to be line-buffered, it still doesn't
2481 flush the buffer at the end of every line.
2483 So, if the "-l" flag was specified, we flush the standard output
2484 at the end of a packet. This will do the right thing if we're
2485 printing packet summary lines, and, as we print the entire protocol
2486 tree for a single packet without waiting for anything to happen,
2487 it should be as good as line-buffered mode if we're printing
2488 protocol trees. (The whole reason for the "-l" flag in either
2489 tcpdump or TShark is to allow the output of a live capture to
2490 be piped to a program or script and to have that script see the
2491 information for the packet as soon as it's printed, rather than
2492 having to wait until a standard I/O buffer fills up. */
2496 if (ferror(stdout)) {
2497 show_print_file_io_error(errno);
2503 if (do_dissection) {
2504 epan_dissect_free(edt);
2505 clear_fdata(&fdata);
2511 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
2513 char *save_file_string;
2515 save_file_string = output_file_description(fname);
2520 cmdarg_err("Not all the packets could be written to the %s because there is "
2521 "no space left on the file system.",
2527 cmdarg_err("Not all the packets could be written to the %s because you are "
2528 "too close to, or over your disk quota.",
2533 case WTAP_ERR_CANT_CLOSE:
2534 cmdarg_err("The %s couldn't be closed for some unknown reason.",
2538 case WTAP_ERR_SHORT_WRITE:
2539 cmdarg_err("Not all the packets could be written to the %s.",
2545 cmdarg_err("The %s could not be closed: %s.", save_file_string,
2546 wtap_strerror(err));
2548 cmdarg_err("An error occurred while writing to the %s: %s.",
2549 save_file_string, wtap_strerror(err));
2553 g_free(save_file_string);
2557 write_preamble(capture_file *cf)
2559 switch (output_action) {
2562 return print_preamble(print_stream, cf ? cf->filename : NULL);
2566 write_pdml_preamble(stdout);
2568 write_psml_preamble(stdout);
2569 return !ferror(stdout);
2572 write_fields_preamble(output_fields, stdout);
2573 return !ferror(stdout);
2576 g_assert_not_reached();
2582 get_line_buf(size_t len)
2584 static char *line_bufp = NULL;
2585 static size_t line_buf_len = 256;
2586 size_t new_line_buf_len;
2588 for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
2589 new_line_buf_len *= 2)
2591 if (line_bufp == NULL) {
2592 line_buf_len = new_line_buf_len;
2593 line_bufp = g_malloc(line_buf_len + 1);
2595 if (new_line_buf_len > line_buf_len) {
2596 line_buf_len = new_line_buf_len;
2597 line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2604 print_columns(capture_file *cf)
2611 line_bufp = get_line_buf(256);
2614 for (i = 0; i < cf->cinfo.num_cols; i++) {
2615 switch (cf->cinfo.col_fmt[i]) {
2619 * Don't print this if we're doing a live capture from a network
2620 * interface - if we're doing a live capture, you won't be
2621 * able to look at the capture in the future (it's not being
2622 * saved anywhere), so the frame numbers are unlikely to be
2625 * (XXX - it might be nice to be able to save and print at
2626 * the same time, sort of like an "Update list of packets
2627 * in real time" capture in Wireshark.)
2629 if (global_capture_opts.iface != NULL)
2632 column_len = strlen(cf->cinfo.col_data[i]);
2635 line_bufp = get_line_buf(buf_offset + column_len);
2636 sprintf(line_bufp + buf_offset, "%3s", cf->cinfo.col_data[i]);
2642 case COL_ABS_DATE_TIME: /* XXX - wider */
2643 column_len = strlen(cf->cinfo.col_data[i]);
2644 if (column_len < 10)
2646 line_bufp = get_line_buf(buf_offset + column_len);
2647 sprintf(line_bufp + buf_offset, "%10s", cf->cinfo.col_data[i]);
2653 case COL_DEF_DL_SRC:
2654 case COL_RES_DL_SRC:
2655 case COL_UNRES_DL_SRC:
2656 case COL_DEF_NET_SRC:
2657 case COL_RES_NET_SRC:
2658 case COL_UNRES_NET_SRC:
2659 column_len = strlen(cf->cinfo.col_data[i]);
2660 if (column_len < 12)
2662 line_bufp = get_line_buf(buf_offset + column_len);
2663 sprintf(line_bufp + buf_offset, "%12s", cf->cinfo.col_data[i]);
2669 case COL_DEF_DL_DST:
2670 case COL_RES_DL_DST:
2671 case COL_UNRES_DL_DST:
2672 case COL_DEF_NET_DST:
2673 case COL_RES_NET_DST:
2674 case COL_UNRES_NET_DST:
2675 column_len = strlen(cf->cinfo.col_data[i]);
2676 if (column_len < 12)
2678 line_bufp = get_line_buf(buf_offset + column_len);
2679 sprintf(line_bufp + buf_offset, "%-12s", cf->cinfo.col_data[i]);
2683 column_len = strlen(cf->cinfo.col_data[i]);
2684 line_bufp = get_line_buf(buf_offset + column_len);
2685 strcat(line_bufp + buf_offset, cf->cinfo.col_data[i]);
2688 buf_offset += column_len;
2689 if (i != cf->cinfo.num_cols - 1) {
2691 * This isn't the last column, so we need to print a
2692 * separator between this column and the next.
2694 * If we printed a network source and are printing a
2695 * network destination of the same type next, separate
2696 * them with "->"; if we printed a network destination
2697 * and are printing a network source of the same type
2698 * next, separate them with "<-"; otherwise separate them
2701 * We add enough space to the buffer for " <- " or " -> ",
2702 * even if we're only adding " ".
2704 line_bufp = get_line_buf(buf_offset + 4);
2705 switch (cf->cinfo.col_fmt[i]) {
2710 switch (cf->cinfo.col_fmt[i + 1]) {
2715 strcat(line_bufp + buf_offset, " -> ");
2720 strcat(line_bufp + buf_offset, " ");
2726 case COL_DEF_DL_SRC:
2727 case COL_RES_DL_SRC:
2728 case COL_UNRES_DL_SRC:
2729 switch (cf->cinfo.col_fmt[i + 1]) {
2731 case COL_DEF_DL_DST:
2732 case COL_RES_DL_DST:
2733 case COL_UNRES_DL_DST:
2734 strcat(line_bufp + buf_offset, " -> ");
2739 strcat(line_bufp + buf_offset, " ");
2745 case COL_DEF_NET_SRC:
2746 case COL_RES_NET_SRC:
2747 case COL_UNRES_NET_SRC:
2748 switch (cf->cinfo.col_fmt[i + 1]) {
2750 case COL_DEF_NET_DST:
2751 case COL_RES_NET_DST:
2752 case COL_UNRES_NET_DST:
2753 strcat(line_bufp + buf_offset, " -> ");
2758 strcat(line_bufp + buf_offset, " ");
2767 switch (cf->cinfo.col_fmt[i + 1]) {
2772 strcat(line_bufp + buf_offset, " <- ");
2777 strcat(line_bufp + buf_offset, " ");
2783 case COL_DEF_DL_DST:
2784 case COL_RES_DL_DST:
2785 case COL_UNRES_DL_DST:
2786 switch (cf->cinfo.col_fmt[i + 1]) {
2788 case COL_DEF_DL_SRC:
2789 case COL_RES_DL_SRC:
2790 case COL_UNRES_DL_SRC:
2791 strcat(line_bufp + buf_offset, " <- ");
2796 strcat(line_bufp + buf_offset, " ");
2802 case COL_DEF_NET_DST:
2803 case COL_RES_NET_DST:
2804 case COL_UNRES_NET_DST:
2805 switch (cf->cinfo.col_fmt[i + 1]) {
2807 case COL_DEF_NET_SRC:
2808 case COL_RES_NET_SRC:
2809 case COL_UNRES_NET_SRC:
2810 strcat(line_bufp + buf_offset, " <- ");
2815 strcat(line_bufp + buf_offset, " ");
2822 strcat(line_bufp + buf_offset, " ");
2828 return print_line(print_stream, 0, line_bufp);
2832 print_packet(capture_file *cf, epan_dissect_t *edt)
2834 print_args_t print_args;
2837 /* Print the information in the protocol tree. */
2838 switch (output_action) {
2841 print_args.to_file = TRUE;
2842 print_args.format = print_format;
2843 print_args.print_summary = !verbose;
2844 print_args.print_hex = verbose && print_hex;
2845 print_args.print_formfeed = FALSE;
2846 print_args.print_dissections = verbose ? print_dissections_expanded : print_dissections_none;
2848 /* init the packet range */
2849 packet_range_init(&print_args.range);
2851 if (!proto_tree_print(&print_args, edt, print_stream))
2854 /* "print_hex_data()" will put out a leading blank line, as well
2855 as a trailing one; print one here, to separate the packets,
2856 only if "print_hex_data()" won't be called. */
2857 if (!print_line(print_stream, 0, ""))
2863 proto_tree_write_pdml(edt, stdout);
2865 return !ferror(stdout);
2867 proto_tree_write_fields(output_fields, edt, stdout);
2869 return !ferror(stdout);
2872 /* Just fill in the columns. */
2873 epan_dissect_fill_in_columns(edt);
2875 /* Now print them. */
2876 switch (output_action) {
2879 if (!print_columns(cf))
2884 proto_tree_write_psml(edt, stdout);
2885 return !ferror(stdout);
2886 case WRITE_FIELDS: /*No non-verbose "fields" format */
2887 g_assert_not_reached();
2892 if (!print_hex_data(print_stream, edt))
2894 if (!print_line(print_stream, 0, ""))
2903 switch (output_action) {
2906 return print_finale(print_stream);
2910 write_pdml_finale(stdout);
2912 write_psml_finale(stdout);
2913 return !ferror(stdout);
2916 write_fields_finale(output_fields, stdout);
2917 return !ferror(stdout);
2920 g_assert_not_reached();
2926 show_print_file_io_error(int err)
2931 cmdarg_err("Not all the packets could be printed because there is "
2932 "no space left on the file system.");
2937 cmdarg_err("Not all the packets could be printed because you are "
2938 "too close to, or over your disk quota.");
2943 cmdarg_err("An error occurred while printing packets: %s.",
2950 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
2954 static char errmsg_errno[1024+1];
2957 /* Wiretap error. */
2960 case WTAP_ERR_NOT_REGULAR_FILE:
2961 errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
2964 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
2965 /* Seen only when opening a capture file for reading. */
2966 errmsg = "The file \"%s\" isn't a capture file in a format TShark understands.";
2969 case WTAP_ERR_UNSUPPORTED:
2970 /* Seen only when opening a capture file for reading. */
2971 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2972 "The file \"%%s\" isn't a capture file in a format TShark understands.\n"
2975 errmsg = errmsg_errno;
2978 case WTAP_ERR_CANT_WRITE_TO_PIPE:
2979 /* Seen only when opening a capture file for writing. */
2980 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2981 "The file \"%%s\" is a pipe, and %s capture files can't be "
2982 "written to a pipe.", wtap_file_type_string(file_type));
2983 errmsg = errmsg_errno;
2986 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2987 /* Seen only when opening a capture file for writing. */
2988 errmsg = "TShark doesn't support writing capture files in that format.";
2991 case WTAP_ERR_UNSUPPORTED_ENCAP:
2993 errmsg = "TShark can't save this capture in that format.";
2995 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2996 "The file \"%%s\" is a capture for a network type that TShark doesn't support.\n"
2999 errmsg = errmsg_errno;
3003 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
3005 errmsg = "TShark can't save this capture in that format.";
3007 errmsg = "The file \"%s\" is a capture for a network type that TShark doesn't support.";
3010 case WTAP_ERR_BAD_RECORD:
3011 /* Seen only when opening a capture file for reading. */
3012 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3013 "The file \"%%s\" appears to be damaged or corrupt.\n"
3016 errmsg = errmsg_errno;
3019 case WTAP_ERR_CANT_OPEN:
3021 errmsg = "The file \"%s\" could not be created for some unknown reason.";
3023 errmsg = "The file \"%s\" could not be opened for some unknown reason.";
3026 case WTAP_ERR_SHORT_READ:
3027 errmsg = "The file \"%s\" appears to have been cut short"
3028 " in the middle of a packet or other data.";
3031 case WTAP_ERR_SHORT_WRITE:
3032 errmsg = "A full header couldn't be written to the file \"%s\".";
3036 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3037 "The file \"%%s\" could not be %s: %s.",
3038 for_writing ? "created" : "opened",
3039 wtap_strerror(err));
3040 errmsg = errmsg_errno;
3044 errmsg = file_open_error_message(err, for_writing);
3049 * Open/create errors are reported with an console message in TShark.
3052 open_failure_message(const char *filename, int err, gboolean for_writing)
3054 fprintf(stderr, "tshark: ");
3055 fprintf(stderr, file_open_error_message(err, for_writing), filename);
3056 fprintf(stderr, "\n");
3060 cf_open(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
3064 char err_msg[2048+1];
3066 wth = wtap_open_offline(fname, err, &err_info, FALSE);
3070 /* The open succeeded. Fill in the information for this file. */
3072 /* Initialize all data structures used for dissection. */
3076 cf->f_datalen = 0; /* not used, but set it anyway */
3078 /* Set the file name because we need it to set the follow stream filter.
3079 XXX - is that still true? We need it for other reasons, though,
3081 cf->filename = g_strdup(fname);
3083 /* Indicate whether it's a permanent or temporary file. */
3084 cf->is_tempfile = is_tempfile;
3086 /* If it's a temporary capture buffer file, mark it as not saved. */
3087 cf->user_saved = !is_tempfile;
3089 cf->cd_t = wtap_file_type(cf->wth);
3091 cf->drops_known = FALSE;
3093 cf->snap = wtap_snapshot_length(cf->wth);
3094 if (cf->snap == 0) {
3095 /* Snapshot length not known. */
3096 cf->has_snap = FALSE;
3097 cf->snap = WTAP_MAX_PACKET_SIZE;
3099 cf->has_snap = TRUE;
3100 nstime_set_zero(&cf->elapsed_time);
3101 nstime_set_unset(&first_ts);
3102 nstime_set_unset(&prev_dis_ts);
3103 nstime_set_unset(&prev_cap_ts);
3108 g_snprintf(err_msg, sizeof err_msg,
3109 cf_open_error_message(*err, err_info, FALSE, cf->cd_t), fname);
3110 cmdarg_err("%s", err_msg);
3116 * General errors are reported with an console message in TShark.
3119 failure_message(const char *msg_format, va_list ap)
3121 fprintf(stderr, "tshark: ");
3122 vfprintf(stderr, msg_format, ap);
3123 fprintf(stderr, "\n");
3127 * Read errors are reported with an console message in TShark.
3130 read_failure_message(const char *filename, int err)
3132 cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
3133 filename, strerror(err));
3137 * Report an error in command-line arguments.
3140 cmdarg_err(const char *fmt, ...)
3145 failure_message(fmt, ap);
3150 * Report additional information for an error in command-line arguments.
3153 cmdarg_err_cont(const char *fmt, ...)
3158 vfprintf(stderr, fmt, ap);
3159 fprintf(stderr, "\n");