3 * Text-mode variant of Wireshark, along the lines of tcpdump and snoop,
4 * by Gilbert Ramirez <gram@alumni.rice.edu> and Guy Harris <guy@alum.mit.edu>.
8 * Wireshark - Network traffic analyzer
9 * By Gerald Combs <gerald@wireshark.org>
10 * Copyright 1998 Gerald Combs
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
50 #ifdef HAVE_SYS_STAT_H
51 # include <sys/stat.h>
54 #ifdef NEED_STRERROR_H
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/plugins.h>
82 #include <epan/epan_dissect.h>
84 #include <epan/stat_cmd_args.h>
85 #include <epan/timestamp.h>
86 #include <epan/ex-opt.h>
89 #include "capture_ui_utils.h"
91 #include "capture-pcap-util.h"
93 #include "capture-wpcap.h"
94 #include "capture_errs.h"
96 #include "capture_sync.h"
97 #endif /* HAVE_LIBPCAP */
99 #include <epan/funnel.h>
103 * This is the template for the decode as option; it is shared between the
104 * various functions that output the usage for this parameter.
106 static const gchar decode_as_arg_template[] = "<layer_type>==<selector>,<decode_as_protocol>";
108 static guint32 cum_bytes;
109 static nstime_t first_ts;
110 static nstime_t prev_dis_ts;
111 static nstime_t prev_cap_ts;
113 static gboolean print_packet_info; /* TRUE if we're to print packet information */
115 static gboolean perform_two_pass_analysis;
118 * The way the packet decode is to be written.
121 WRITE_TEXT, /* summary or detail text */
122 WRITE_XML, /* PDML or PSML */
123 WRITE_FIELDS /* User defined list of fields */
124 /* Add CSV and the like here */
127 static output_action_e output_action;
128 static gboolean do_dissection; /* TRUE if we have to dissect each packet */
129 static gboolean verbose;
130 static gboolean print_hex;
131 static gboolean line_buffered;
133 static print_format_e print_format = PR_FMT_TEXT;
134 static print_stream_t *print_stream;
136 static output_fields_t* output_fields = NULL;
139 * Standard secondary message for unexpected errors.
141 static const char please_report[] =
142 "Please report this to the Wireshark developers";
146 * TRUE if we're to print packet counts to keep track of captured packets.
148 static gboolean print_packet_counts;
151 static capture_options global_capture_opts;
154 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
155 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
158 static int capture(void);
159 static void report_counts(void);
161 static BOOL WINAPI capture_cleanup(DWORD);
163 static void capture_cleanup(int);
165 static void report_counts_siginfo(int);
168 #endif /* HAVE_LIBPCAP */
170 static int load_cap_file(capture_file *, char *, int, int, gint64);
171 static gboolean process_packet(capture_file *cf, gint64 offset,
172 const struct wtap_pkthdr *whdr, union wtap_pseudo_header *pseudo_header,
173 const guchar *pd, gboolean filtering_tap_listeners, guint tap_flags);
174 static void show_capture_file_io_error(const char *, int, gboolean);
175 static void show_print_file_io_error(int err);
176 static gboolean write_preamble(capture_file *cf);
177 static gboolean print_packet(capture_file *cf, epan_dissect_t *edt);
178 static gboolean write_finale(void);
179 static const char *cf_open_error_message(int err, gchar *err_info,
180 gboolean for_writing, int file_type);
182 static void open_failure_message(const char *filename, int err,
183 gboolean for_writing);
184 static void failure_message(const char *msg_format, va_list ap);
185 static void read_failure_message(const char *filename, int err);
186 static void write_failure_message(const char *filename, int err);
191 cf_mark_frame(capture_file *cf _U_, frame_data *frame _U_)
193 g_assert_not_reached();
196 static void list_capture_types(void) {
199 fprintf(stderr, "editcap: The available capture file types for \"F\":\n");
200 for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
201 if (wtap_dump_can_open(i))
202 fprintf(stderr, " %s - %s\n",
203 wtap_file_type_short_string(i), wtap_file_type_string(i));
208 print_usage(gboolean print_ver)
215 "TShark " VERSION "%s\n"
216 "Dump and analyze network traffic.\n"
217 "See http://www.wireshark.org for more information.\n"
220 wireshark_svnversion, get_copyright_info());
224 fprintf(output, "\n");
225 fprintf(output, "Usage: tshark [options] ...\n");
226 fprintf(output, "\n");
229 fprintf(output, "Capture interface:\n");
230 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
231 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
232 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
233 fprintf(output, " -p don't capture in promiscuous mode\n");
235 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
237 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
238 fprintf(output, " -D print list of interfaces and exit\n");
239 fprintf(output, " -L print list of link-layer types of iface and exit\n");
240 fprintf(output, "\n");
241 fprintf(output, "Capture stop conditions:\n");
242 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
243 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
244 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
245 fprintf(output, " files:NUM - stop after NUM files\n");
246 /*fprintf(output, "\n");*/
247 fprintf(output, "Capture output:\n");
248 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
249 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
250 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
251 #endif /* HAVE_LIBPCAP */
253 /*fprintf(output, "\n");*/
254 fprintf(output, "Input file:\n");
255 fprintf(output, " -r <infile> set the filename to read from (no pipes or stdin!)\n");
257 fprintf(output, "\n");
258 fprintf(output, "Processing:\n");
259 fprintf(output, " -R <read filter> packet filter in Wireshark display filter syntax\n");
260 fprintf(output, " -n disable all name resolutions (def: all enabled)\n");
261 fprintf(output, " -N <name resolve flags> enable specific name resolution(s): \"mntC\"\n");
262 fprintf(output, " -d %s ...\n", decode_as_arg_template);
263 fprintf(output, " \"Decode As\", see the man page for details\n");
264 fprintf(output, " Example: tcp.port==8888,http\n");
266 /*fprintf(output, "\n");*/
267 fprintf(output, "Output:\n");
268 fprintf(output, " -w <outfile|-> write packets to a pcap-format file named \"outfile\"\n");
269 fprintf(output, " (or to the standard output for \"-\")\n");
270 fprintf(output, " -C <config profile> start with specified configuration profile\n");
271 fprintf(output, " -F <output file type> set the output file type, default is libpcap\n");
272 fprintf(output, " an empty \"-F\" option will list the file types\n");
273 fprintf(output, " -V add output of packet tree (Packet Details)\n");
274 fprintf(output, " -S display packets even when writing to a file\n");
275 fprintf(output, " -x add output of hex and ASCII dump (Packet Bytes)\n");
276 fprintf(output, " -T pdml|ps|psml|text|fields\n");
277 fprintf(output, " format of text output (def: text)\n");
278 fprintf(output, " -e <field> field to print if -Tfields selected (e.g. tcp.port);\n");
279 fprintf(output, " this option can be repeated to print multiple fields\n");
280 fprintf(output, " -E<fieldsoption>=<value> set options for output when -Tfields selected:\n");
281 fprintf(output, " header=y|n switch headers on and off\n");
282 fprintf(output, " separator=/t|/s|<char> select tab, space, printable character as separator\n");
283 fprintf(output, " quote=d|s|n select double, single, no quotes for values\n");
284 fprintf(output, " -t ad|a|r|d|dd|e output format of time stamps (def: r: rel. to first)\n");
285 fprintf(output, " -l flush standard output after each packet\n");
286 fprintf(output, " -q be more quiet on stdout (e.g. when using statistics)\n");
287 fprintf(output, " -X <key>:<value> eXtension options, see the man page for details\n");
288 fprintf(output, " -z <statistics> various statistics, see the man page for details\n");
290 fprintf(output, "\n");
291 fprintf(output, "Miscellaneous:\n");
292 fprintf(output, " -h display this help and exit\n");
293 fprintf(output, " -v display version info and exit\n");
294 fprintf(output, " -o <name>:<value> ... override preference setting\n");
295 fprintf(output, " -K <keytab> keytab file to use for kerberos decryption\n");
299 * For a dissector table, print on the stream described by output,
300 * its short name (which is what's used in the "-d" option) and its
304 display_dissector_table_names(const char *table_name, const char *ui_name,
307 fprintf((FILE *)output, "\t%s (%s)\n", table_name, ui_name);
311 * For a dissector handle, print on the stream described by output,
312 * the filter name (which is what's used in the "-d" option) and the full
313 * name for the protocol that corresponds to this handle.
316 display_dissector_names(const gchar *table _U_, gpointer handle, gpointer output)
319 const gchar* proto_filter_name;
320 const gchar* proto_ui_name;
322 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
324 if (proto_id != -1) {
325 proto_filter_name = proto_get_protocol_filter_name(proto_id);
326 proto_ui_name = proto_get_protocol_name(proto_id);
327 g_assert(proto_filter_name != NULL);
328 g_assert(proto_ui_name != NULL);
330 fprintf((FILE *)output, "\t%s (%s)\n",
337 * The protocol_name_search structure is used by find_protocol_name_func()
338 * to pass parameters and store results
340 struct protocol_name_search{
341 gchar *searched_name; /* Protocol filter name we are looking for */
342 dissector_handle_t matched_handle; /* Handle for a dissector whose protocol has the specified filter name */
343 guint nb_match; /* How many dissectors matched searched_name */
345 typedef struct protocol_name_search *protocol_name_search_t;
348 * This function parses all dissectors associated with a table to find the
349 * one whose protocol has the specified filter name. It is called
350 * as a reference function in a call to dissector_table_foreach_handle.
351 * The name we are looking for, as well as the results, are stored in the
352 * protocol_name_search struct pointed to by user_data.
353 * If called using dissector_table_foreach_handle, we actually parse the
354 * whole list of dissectors.
357 find_protocol_name_func(const gchar *table _U_, gpointer handle, gpointer user_data)
361 const gchar *protocol_filter_name;
362 protocol_name_search_t search_info;
366 search_info = (protocol_name_search_t)user_data;
368 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
369 if (proto_id != -1) {
370 protocol_filter_name = proto_get_protocol_filter_name(proto_id);
371 g_assert(protocol_filter_name != NULL);
372 if (strcmp(protocol_filter_name, search_info->searched_name) == 0) {
374 if (search_info->nb_match == 0) {
375 /* Record this handle only if this is the first match */
376 search_info->matched_handle = (dissector_handle_t)handle; /* Record the handle for this matching dissector */
378 search_info->nb_match++;
384 * Print all layer type names supported.
385 * We send the output to the stream described by the handle output.
389 fprint_all_layer_types(FILE *output)
392 dissector_all_tables_foreach_table(display_dissector_table_names, (gpointer)output);
396 * Print all protocol names supported for a specific layer type.
397 * table_name contains the layer type name in which the search is performed.
398 * We send the output to the stream described by the handle output.
402 fprint_all_protocols_for_layer_types(FILE *output, gchar *table_name)
405 dissector_table_foreach_handle(table_name,
406 display_dissector_names,
411 * The function below parses the command-line parameters for the decode as
412 * feature (a string pointer by cl_param).
413 * It checks the format of the command-line, searches for a matching table
414 * and dissector. If a table/dissector match is not found, we display a
415 * summary of the available tables/dissectors (on stderr) and return FALSE.
416 * If everything is fine, we get the "Decode as" preference activated,
417 * then we return TRUE.
420 add_decode_as(const gchar *cl_param)
424 gchar *decoded_param;
425 gchar *remaining_param;
427 gchar *dissector_str;
428 dissector_handle_t dissector_matching;
429 dissector_table_t table_matching;
430 ftenum_t dissector_table_selector_type;
431 struct protocol_name_search user_protocol_name;
433 /* The following code will allocate and copy the command-line options in a string pointed by decoded_param */
436 decoded_param = g_strdup(cl_param);
437 g_assert(decoded_param);
440 /* The lines below will parse this string (modifying it) to extract all
441 necessary information. Note that decoded_param is still needed since
442 strings are not copied - we just save pointers. */
444 /* This section extracts a layer type (table_name) from decoded_param */
445 table_name = decoded_param; /* Layer type string starts from beginning */
447 remaining_param = strchr(table_name, '=');
448 if (remaining_param == NULL) {
449 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
450 /* If the argument does not follow the template, carry on anyway to check
451 if the table name is at least correct. If remaining_param is NULL,
452 we'll exit anyway further down */
455 *remaining_param = '\0'; /* Terminate the layer type string (table_name) where '=' was detected */
458 /* Remove leading and trailing spaces from the table name */
459 while ( table_name[0] == ' ' )
461 while ( table_name[strlen(table_name) - 1] == ' ' )
462 table_name[strlen(table_name) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
464 /* The following part searches a table matching with the layer type specified */
465 table_matching = NULL;
467 /* Look for the requested table */
468 if ( !(*(table_name)) ) { /* Is the table name empty, if so, don't even search for anything, display a message */
469 cmdarg_err("No layer type specified"); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
472 table_matching = find_dissector_table(table_name);
473 if (!table_matching) {
474 cmdarg_err("Unknown layer type -- %s", table_name); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
478 if (!table_matching) {
479 /* Display a list of supported layer types to help the user, if the
480 specified layer type was not found */
481 cmdarg_err("Valid layer types are:");
482 fprint_all_layer_types(stderr);
484 if (remaining_param == NULL || !table_matching) {
485 /* Exit if the layer type was not found, or if no '=' separator was found
487 g_free(decoded_param);
491 if (*(remaining_param + 1) != '=') { /* Check for "==" and not only '=' */
492 cmdarg_err("WARNING: -d requires \"==\" instead of \"=\". Option will be treated as \"%s==%s\"", table_name, remaining_param + 1);
495 remaining_param++; /* Move to the second '=' */
496 *remaining_param = '\0'; /* Remove the second '=' */
498 remaining_param++; /* Position after the layer type string */
500 /* This section extracts a selector value (selector_str) from decoded_param */
502 selector_str = remaining_param; /* Next part starts with the selector number */
504 remaining_param = strchr(selector_str, ',');
505 if (remaining_param == NULL) {
506 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
507 /* If the argument does not follow the template, carry on anyway to check
508 if the selector value is at least correct. If remaining_param is NULL,
509 we'll exit anyway further down */
512 *remaining_param = '\0'; /* Terminate the selector number string (selector_str) where ',' was detected */
515 dissector_table_selector_type = get_dissector_table_selector_type(table_name);
517 switch (dissector_table_selector_type) {
523 /* The selector for this table is an unsigned number. Parse it as such.
524 There's no need to remove leading and trailing spaces from the
525 selector number string, because sscanf will do that for us. */
526 if ( sscanf(selector_str, "%u", &selector) != 1 ) {
527 cmdarg_err("Invalid selector number \"%s\"", selector_str);
528 g_free(decoded_param);
536 /* The selector for this table is a string. */
540 /* There are currently no dissector tables with any types other
541 than the ones listed above. */
542 g_assert_not_reached();
545 if (remaining_param == NULL) {
546 /* Exit if no ',' separator was found (see above) */
547 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
548 fprint_all_protocols_for_layer_types(stderr, table_name);
549 g_free(decoded_param);
553 remaining_param++; /* Position after the selector number string */
555 /* This section extracts a protocol filter name (dissector_str) from decoded_param */
557 dissector_str = remaining_param; /* All the rest of the string is the dissector (decode as protocol) name */
559 /* Remove leading and trailing spaces from the dissector name */
560 while ( dissector_str[0] == ' ' )
562 while ( dissector_str[strlen(dissector_str) - 1] == ' ' )
563 dissector_str[strlen(dissector_str) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
565 dissector_matching = NULL;
567 /* We now have a pointer to the handle for the requested table inside the variable table_matching */
568 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 */
569 cmdarg_err("No protocol name specified"); /* Note, we don't exit here, but dissector_matching will remain NULL, so we exit below */
572 user_protocol_name.nb_match = 0;
573 user_protocol_name.searched_name = dissector_str;
574 user_protocol_name.matched_handle = NULL;
576 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 */
578 if (user_protocol_name.nb_match != 0) {
579 dissector_matching = user_protocol_name.matched_handle;
580 if (user_protocol_name.nb_match > 1) {
581 cmdarg_err("WARNING: Protocol \"%s\" matched %u dissectors, first one will be used", dissector_str, user_protocol_name.nb_match);
585 /* OK, check whether the problem is that there isn't any such
586 protocol, or that there is but it's not specified as a protocol
587 that's valid for that dissector table.
588 Note, we don't exit here, but dissector_matching will remain NULL,
590 if (proto_get_id_by_filter_name(dissector_str) == -1) {
591 /* No such protocol */
592 cmdarg_err("Unknown protocol -- \"%s\"", dissector_str);
594 cmdarg_err("Protocol \"%s\" isn't valid for layer type \"%s\"",
595 dissector_str, table_name);
600 if (!dissector_matching) {
601 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
602 fprint_all_protocols_for_layer_types(stderr, table_name);
603 g_free(decoded_param);
607 /* This is the end of the code that parses the command-line options.
608 All information is now stored in the variables:
612 The above variables that are strings are still pointing to areas within
613 decoded_parm. decoded_parm thus still needs to be kept allocated in
614 until we stop needing these variables
615 decoded_param will be deallocated at each exit point of this function */
618 /* We now have a pointer to the handle for the requested dissector
619 (requested protocol) inside the variable dissector_matching */
620 switch (dissector_table_selector_type) {
626 /* The selector for this table is an unsigned number. */
627 dissector_change(table_name, selector, dissector_matching);
633 /* The selector for this table is a string. */
634 dissector_change_string(table_name, selector_str, dissector_matching);
638 /* There are currently no dissector tables with any types other
639 than the ones listed above. */
640 g_assert_not_reached();
642 g_free(decoded_param); /* "Decode As" rule has been succesfully added */
647 tshark_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
648 const gchar *message, gpointer user_data)
650 /* ignore log message, if log_level isn't interesting based
651 upon the console log preferences.
652 If the preferences haven't been loaded loaded yet, display the
655 The default console_log_level preference value is such that only
656 ERROR, CRITICAL and WARNING level messages are processed;
657 MESSAGE, INFO and DEBUG level messages are ignored.
659 XXX: Aug 07, 2009: Prior tshark g_log code was hardwired to process only
660 ERROR and CRITICAL level messages so the current code is a behavioral
661 change. The current behavior is the same as in Wireshark.
663 if((log_level & G_LOG_LEVEL_MASK & prefs.console_log_level) == 0 &&
664 prefs.console_log_level != 0) {
668 g_log_default_handler(log_domain, log_level, message, user_data);
673 output_file_description(const char *fname)
675 char *save_file_string;
677 /* Get a string that describes what we're writing to */
678 if (strcmp(fname, "-") == 0) {
679 /* We're writing to the standard output */
680 save_file_string = g_strdup("standard output");
682 /* We're writing to a file with the name in save_file */
683 save_file_string = g_strdup_printf("file \"%s\"", fname);
685 return save_file_string;
689 print_current_user(void) {
690 gchar *cur_user, *cur_group;
691 if (started_with_special_privs()) {
692 cur_user = get_cur_username();
693 cur_group = get_cur_groupname();
694 fprintf(stderr, "Running as user \"%s\" and group \"%s\".",
695 cur_user, cur_group);
698 if (running_with_special_privs()) {
699 fprintf(stderr, " This could be dangerous.");
701 fprintf(stderr, "\n");
706 check_capture_privs(void) {
709 /* Warn the user if npf.sys isn't loaded. */
710 if (!npf_sys_is_running() && get_os_major_version() >= 6) {
711 fprintf(stderr, "The NPF driver isn't running. You may have trouble "
712 "capturing or\nlisting interfaces.\n");
718 show_version(GString *comp_info_str, GString *runtime_info_str)
720 printf("TShark " VERSION "%s\n"
727 wireshark_svnversion, get_copyright_info(), comp_info_str->str,
728 runtime_info_str->str);
732 main(int argc, char *argv[])
734 char *init_progfile_dir_error;
737 gboolean arg_error = FALSE;
743 char *gpf_path, *pf_path;
744 char *gdp_path, *dp_path;
745 int gpf_open_errno, gpf_read_errno;
746 int pf_open_errno, pf_read_errno;
747 int gdp_open_errno, gdp_read_errno;
748 int dp_open_errno, dp_read_errno;
751 gboolean list_link_layer_types = FALSE;
752 gboolean start_capture = FALSE;
755 gboolean capture_option_specified = FALSE;
757 gboolean quiet = FALSE;
758 int out_file_type = WTAP_FILE_PCAP;
759 gchar *cf_name = NULL, *rfilter = NULL;
760 #ifdef HAVE_PCAP_OPEN_DEAD
761 struct bpf_program fcode;
763 dfilter_t *rfcode = NULL;
766 GLogLevelFlags log_flags;
769 #define OPTSTRING_INIT "a:b:c:C:d:De:E:f:F:G:hi:K:lLnN:o:pPqr:R:s:St:T:vVw:xX:y:z:"
772 #define OPTSTRING_WIN32 "B:"
774 #define OPTSTRING_WIN32 ""
777 #define OPTSTRING_WIN32 ""
778 #endif /* HAVE_LIBPCAP */
780 static const char optstring[] = OPTSTRING_INIT OPTSTRING_WIN32;
783 * Get credential information for later use.
785 get_credential_info();
788 * Attempt to get the pathname of the executable file.
790 init_progfile_dir_error = init_progfile_dir(argv[0], main);
791 if (init_progfile_dir_error != NULL) {
792 fprintf(stderr, "tshark: Can't get pathname of tshark program: %s.\n",
793 init_progfile_dir_error);
797 * In order to have the -X opts assigned before the wslua machine starts
798 * we need to call getopts before epan_init() gets called.
801 optind_initial = optind;
803 while ((opt = getopt(argc, argv, optstring)) != -1) {
805 case 'C': /* Configuration Profile */
806 if (profile_exists (optarg)) {
807 set_profile_name (optarg);
809 cmdarg_err("Configuration Profile \"%s\" does not exist", optarg);
821 optind = optind_initial;
826 /** Send All g_log messages to our own handler **/
830 G_LOG_LEVEL_CRITICAL|
835 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
837 g_log_set_handler(NULL,
839 tshark_log_handler, NULL /* user_data */);
840 g_log_set_handler(LOG_DOMAIN_MAIN,
842 tshark_log_handler, NULL /* user_data */);
845 g_log_set_handler(LOG_DOMAIN_CAPTURE,
847 tshark_log_handler, NULL /* user_data */);
848 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
850 tshark_log_handler, NULL /* user_data */);
853 initialize_funnel_ops();
856 capture_opts_init(&global_capture_opts, &cfile);
859 timestamp_set_type(TS_RELATIVE);
860 timestamp_set_precision(TS_PREC_AUTO);
862 /* Register all dissectors; we must do this before checking for the
863 "-G" flag, as the "-G" flag dumps information registered by the
864 dissectors, and we must do it before we read the preferences, in
865 case any dissectors register preferences. */
866 epan_init(register_all_protocols, register_all_protocol_handoffs, NULL, NULL,
867 failure_message, open_failure_message, read_failure_message,
868 write_failure_message);
870 /* Register all tap listeners; we do this before we parse the arguments,
871 as the "-z" argument can specify a registered tap. */
873 /* we register the plugin taps before the other taps because
874 stats_tree taps plugins will be registered as tap listeners
875 by stats_tree_stat.c and need to registered before that */
877 register_all_plugin_tap_listeners();
879 register_all_tap_listeners();
881 /* Now register the preferences for any non-dissector modules.
882 We must do that before we read the preferences as well. */
883 prefs_register_modules();
885 /* If invoked with the "-G" flag, we dump out information based on
886 the argument to the "-G" flag; if no argument is specified,
887 for backwards compatibility we dump out a glossary of display
890 XXX - we do this here, for now, to support "-G" with no arguments.
891 If none of our build or other processes uses "-G" with no arguments,
892 we can just process it with the other arguments. */
893 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
894 proto_initialize_all_prefixes();
897 proto_registrar_dump_fields(1);
899 if (strcmp(argv[2], "fields") == 0)
900 proto_registrar_dump_fields(1);
901 else if (strcmp(argv[2], "fields2") == 0)
902 proto_registrar_dump_fields(2);
903 else if (strcmp(argv[2], "fields3") == 0)
904 proto_registrar_dump_fields(3);
905 else if (strcmp(argv[2], "protocols") == 0)
906 proto_registrar_dump_protocols();
907 else if (strcmp(argv[2], "values") == 0)
908 proto_registrar_dump_values();
909 else if (strcmp(argv[2], "decodes") == 0)
910 dissector_dump_decodes();
911 else if (strcmp(argv[2], "defaultprefs") == 0)
913 else if (strcmp(argv[2], "currentprefs") == 0) {
914 read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
915 &pf_open_errno, &pf_read_errno, &pf_path);
918 cmdarg_err("Invalid \"%s\" option for -G flag", argv[2]);
925 /* Set the C-language locale to the native environment. */
926 setlocale(LC_ALL, "");
928 prefs = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
929 &pf_open_errno, &pf_read_errno, &pf_path);
930 if (gpf_path != NULL) {
931 if (gpf_open_errno != 0) {
932 cmdarg_err("Can't open global preferences file \"%s\": %s.",
933 pf_path, strerror(gpf_open_errno));
935 if (gpf_read_errno != 0) {
936 cmdarg_err("I/O error reading global preferences file \"%s\": %s.",
937 pf_path, strerror(gpf_read_errno));
940 if (pf_path != NULL) {
941 if (pf_open_errno != 0) {
942 cmdarg_err("Can't open your preferences file \"%s\": %s.", pf_path,
943 strerror(pf_open_errno));
945 if (pf_read_errno != 0) {
946 cmdarg_err("I/O error reading your preferences file \"%s\": %s.",
947 pf_path, strerror(pf_read_errno));
953 /* Set the name resolution code's flags from the preferences. */
954 g_resolv_flags = prefs->name_resolve;
956 /* Read the disabled protocols file. */
957 read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
958 &dp_path, &dp_open_errno, &dp_read_errno);
959 if (gdp_path != NULL) {
960 if (gdp_open_errno != 0) {
961 cmdarg_err("Could not open global disabled protocols file\n\"%s\": %s.",
962 gdp_path, strerror(gdp_open_errno));
964 if (gdp_read_errno != 0) {
965 cmdarg_err("I/O error reading global disabled protocols file\n\"%s\": %s.",
966 gdp_path, strerror(gdp_read_errno));
970 if (dp_path != NULL) {
971 if (dp_open_errno != 0) {
973 "Could not open your disabled protocols file\n\"%s\": %s.", dp_path,
974 strerror(dp_open_errno));
976 if (dp_read_errno != 0) {
978 "I/O error reading your disabled protocols file\n\"%s\": %s.", dp_path,
979 strerror(dp_read_errno));
984 check_capture_privs();
986 cap_file_init(&cfile);
988 /* Print format defaults to this. */
989 print_format = PR_FMT_TEXT;
991 output_fields = output_fields_new();
993 /* Now get our args */
994 while ((opt = getopt(argc, argv, optstring)) != -1) {
996 case 'a': /* autostop criteria */
997 case 'b': /* Ringbuffer option */
998 case 'c': /* Capture x packets */
999 case 'f': /* capture filter */
1000 case 'i': /* Use interface x */
1001 case 'p': /* Don't capture in promiscuous mode */
1002 case 's': /* Set the snapshot (capture) length */
1003 case 'w': /* Write to capture file x */
1004 case 'y': /* Set the pcap data link type */
1006 case 'B': /* Buffer size */
1009 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
1014 capture_option_specified = TRUE;
1019 /* Configuration profile settings were already processed just ignore them this time*/
1021 case 'd': /* Decode as rule */
1022 if (!add_decode_as(optarg))
1025 #if defined(HAVE_HEIMDAL_KERBEROS) || defined(HAVE_MIT_KERBEROS)
1026 case 'K': /* Kerberos keytab file */
1027 read_keytab_file(optarg);
1030 case 'D': /* Print a list of capture devices and exit */
1032 status = capture_opts_list_interfaces(FALSE);
1035 capture_option_specified = TRUE;
1041 output_fields_add(output_fields, optarg);
1045 if(!output_fields_set_option(output_fields, optarg)) {
1046 cmdarg_err("\"%s\" is not a valid field output option=value pair.", optarg);
1047 output_fields_list_options(stderr);
1052 out_file_type = wtap_short_string_to_file_type(optarg);
1053 if (out_file_type < 0) {
1054 cmdarg_err("\"%s\" isn't a valid capture file type", optarg);
1055 list_capture_types();
1059 case 'h': /* Print help and exit */
1063 case 'l': /* "Line-buffer" standard output */
1064 /* This isn't line-buffering, strictly speaking, it's just
1065 flushing the standard output after the information for
1066 each packet is printed; however, that should be good
1067 enough for all the purposes to which "-l" is put (and
1068 is probably actually better for "-V", as it does fewer
1071 See the comment in "process_packet()" for an explanation of
1072 why we do that, and why we don't just use "setvbuf()" to
1073 make the standard output line-buffered (short version: in
1074 Windows, "line-buffered" is the same as "fully-buffered",
1075 and the output buffer is only flushed when it fills up). */
1076 line_buffered = TRUE;
1078 case 'L': /* Print list of link-layer types and exit */
1080 list_link_layer_types = TRUE;
1082 capture_option_specified = TRUE;
1086 #if GLIB_CHECK_VERSION(2,10,0)
1087 case 'P': /* Perform two pass analysis */
1088 perform_two_pass_analysis = TRUE;
1091 case 'n': /* No name resolution */
1092 g_resolv_flags = RESOLV_NONE;
1094 case 'N': /* Select what types of addresses/port #s to resolve */
1095 if (g_resolv_flags == RESOLV_ALL)
1096 g_resolv_flags = RESOLV_NONE;
1097 badopt = string_to_name_resolve(optarg, &g_resolv_flags);
1098 if (badopt != '\0') {
1099 cmdarg_err("-N specifies unknown resolving option '%c';",
1101 cmdarg_err_cont( " Valid options are 'm', 'n', 't', and 'C'");
1105 case 'o': /* Override preference from command line */
1106 switch (prefs_set_pref(optarg)) {
1111 case PREFS_SET_SYNTAX_ERR:
1112 cmdarg_err("Invalid -o flag \"%s\"", optarg);
1116 case PREFS_SET_NO_SUCH_PREF:
1117 case PREFS_SET_OBSOLETE:
1118 cmdarg_err("-o flag \"%s\" specifies unknown preference", optarg);
1123 case 'q': /* Quiet */
1126 case 'r': /* Read capture file x */
1127 cf_name = g_strdup(optarg);
1129 case 'R': /* Read file filter */
1132 case 'S': /* show packets in real time */
1133 print_packet_info = TRUE;
1135 case 't': /* Time stamp type */
1136 if (strcmp(optarg, "r") == 0)
1137 timestamp_set_type(TS_RELATIVE);
1138 else if (strcmp(optarg, "a") == 0)
1139 timestamp_set_type(TS_ABSOLUTE);
1140 else if (strcmp(optarg, "ad") == 0)
1141 timestamp_set_type(TS_ABSOLUTE_WITH_DATE);
1142 else if (strcmp(optarg, "d") == 0)
1143 timestamp_set_type(TS_DELTA);
1144 else if (strcmp(optarg, "dd") == 0)
1145 timestamp_set_type(TS_DELTA_DIS);
1146 else if (strcmp(optarg, "e") == 0)
1147 timestamp_set_type(TS_EPOCH);
1149 cmdarg_err("Invalid time stamp type \"%s\"",
1151 cmdarg_err_cont("It must be \"r\" for relative, \"a\" for absolute,");
1152 cmdarg_err_cont("\"ad\" for absolute with date, or \"d\" for delta.");
1156 case 'T': /* printing Type */
1157 if (strcmp(optarg, "text") == 0) {
1158 output_action = WRITE_TEXT;
1159 print_format = PR_FMT_TEXT;
1160 } else if (strcmp(optarg, "ps") == 0) {
1161 output_action = WRITE_TEXT;
1162 print_format = PR_FMT_PS;
1163 } else if (strcmp(optarg, "pdml") == 0) {
1164 output_action = WRITE_XML;
1166 } else if (strcmp(optarg, "psml") == 0) {
1167 output_action = WRITE_XML;
1169 } else if(strcmp(optarg, "fields") == 0) {
1170 output_action = WRITE_FIELDS;
1171 verbose = TRUE; /* Need full tree info */
1173 cmdarg_err("Invalid -T parameter.");
1174 cmdarg_err_cont("It must be \"ps\", \"text\", \"pdml\", \"psml\" or \"fields\".");
1178 case 'v': /* Show version and exit */
1180 GString *comp_info_str;
1181 GString *runtime_info_str;
1182 /* Assemble the compile-time version information string */
1183 comp_info_str = g_string_new("Compiled ");
1184 get_compiled_version_info(comp_info_str, get_epan_compiled_version_info);
1186 /* Assemble the run-time version information string */
1187 runtime_info_str = g_string_new("Running ");
1188 get_runtime_version_info(runtime_info_str, NULL);
1189 show_version(comp_info_str, runtime_info_str);
1190 g_string_free(comp_info_str, TRUE);
1191 g_string_free(runtime_info_str, TRUE);
1195 case 'V': /* Verbose */
1198 case 'x': /* Print packet data in hex (and ASCII) */
1204 /* We won't call the init function for the stat this soon
1205 as it would disallow MATE's fields (which are registered
1206 by the preferences set callback) from being used as
1207 part of a tap filter. Instead, we just add the argument
1208 to a list of stat arguments. */
1209 if (!process_stat_cmd_arg(optarg)) {
1210 cmdarg_err("invalid -z argument.");
1211 cmdarg_err_cont(" -z argument must be one of :");
1212 list_stat_cmd_args();
1217 case '?': /* Bad flag - print usage message */
1220 list_capture_types();
1230 /* If we specified output fields, but not the output field type... */
1231 if(WRITE_FIELDS != output_action && 0 != output_fields_num_fields(output_fields)) {
1232 cmdarg_err("Output fields were specified with \"-e\", "
1233 "but \"-Tfields\" was not specified.");
1235 } else if(WRITE_FIELDS == output_action && 0 == output_fields_num_fields(output_fields)) {
1236 cmdarg_err("\"-Tfields\" was specified, but no fields were "
1237 "specified with \"-e\".");
1242 /* If no capture filter or read filter has been specified, and there are
1243 still command-line arguments, treat them as the tokens of a capture
1244 filter (if no "-r" flag was specified) or a read filter (if a "-r"
1245 flag was specified. */
1246 if (optind < argc) {
1247 if (cf_name != NULL) {
1248 if (rfilter != NULL) {
1249 cmdarg_err("Read filters were specified both with \"-R\" "
1250 "and with additional command-line arguments");
1253 rfilter = get_args_as_string(argc, argv, optind);
1256 if (global_capture_opts.has_cfilter) {
1257 cmdarg_err("Capture filters were specified both with \"-f\""
1258 " and with additional command-line arguments");
1261 global_capture_opts.has_cfilter = TRUE;
1262 global_capture_opts.cfilter = get_args_as_string(argc, argv, optind);
1264 capture_option_specified = TRUE;
1270 if (!global_capture_opts.saving_to_file) {
1271 /* We're not saving the capture to a file; if "-q" wasn't specified,
1272 we should print packet information */
1274 print_packet_info = TRUE;
1276 /* We're saving to a file; if we're writing to the standard output.
1277 and we'll also be writing dissected packets to the standard
1278 output, reject the request. At best, we could redirect that
1279 to the standard error; we *can't* write both to the standard
1280 output and have either of them be useful. */
1281 if (strcmp(global_capture_opts.save_file, "-") == 0 && print_packet_info) {
1282 cmdarg_err("You can't write both raw packet data and dissected packets"
1283 " to the standard output.");
1288 /* We're not saving the capture to a file; if "-q" wasn't specified,
1289 we should print packet information */
1291 print_packet_info = TRUE;
1294 #ifndef HAVE_LIBPCAP
1295 if (capture_option_specified)
1296 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1303 /* We don't support capture filters when reading from a capture file
1304 (the BPF compiler doesn't support all link-layer types that we
1305 support in capture files we read). */
1307 if (cf_name != NULL) {
1308 if (global_capture_opts.has_cfilter) {
1309 cmdarg_err("Only read filters, not capture filters, "
1310 "can be specified when reading a capture file.");
1317 if (output_action != WRITE_TEXT) {
1318 cmdarg_err("Raw packet hex data can only be printed as text or PostScript");
1324 if (list_link_layer_types) {
1325 /* We're supposed to list the link-layer types for an interface;
1326 did the user also specify a capture file to be read? */
1328 /* Yes - that's bogus. */
1329 cmdarg_err("You can't specify -L and a capture file to be read.");
1332 /* No - did they specify a ring buffer option? */
1333 if (global_capture_opts.multi_files_on) {
1334 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
1340 * "-r" was specified, so we're reading a capture file.
1341 * Capture options don't apply here.
1343 if (global_capture_opts.multi_files_on) {
1344 cmdarg_err("Multiple capture files requested, but "
1345 "a capture isn't being done.");
1348 if (global_capture_opts.has_file_duration) {
1349 cmdarg_err("Switching capture files after a time interval was specified, but "
1350 "a capture isn't being done.");
1353 if (global_capture_opts.has_ring_num_files) {
1354 cmdarg_err("A ring buffer of capture files was specified, but "
1355 "a capture isn't being done.");
1358 if (global_capture_opts.has_autostop_files) {
1359 cmdarg_err("A maximum number of capture files was specified, but "
1360 "a capture isn't being done.");
1364 /* Note: TShark now allows the restriction of a _read_ file by packet count
1365 * and byte count as well as a write file. Other autostop options remain valid
1366 * only for a write file.
1368 if (global_capture_opts.has_autostop_duration) {
1369 cmdarg_err("A maximum capture time was specified, but "
1370 "a capture isn't being done.");
1375 * "-r" wasn't specified, so we're doing a live capture.
1377 if (global_capture_opts.saving_to_file) {
1378 /* They specified a "-w" flag, so we'll be saving to a capture file. */
1380 /* When capturing, we only support writing libpcap format. */
1381 if (out_file_type != WTAP_FILE_PCAP) {
1382 cmdarg_err("Live captures can only be saved in libpcap format.");
1385 if (global_capture_opts.multi_files_on) {
1386 /* Multiple-file mode doesn't work under certain conditions:
1387 a) it doesn't work if you're writing to the standard output;
1388 b) it doesn't work if you're writing to a pipe;
1390 if (strcmp(global_capture_opts.save_file, "-") == 0) {
1391 cmdarg_err("Multiple capture files requested, but "
1392 "the capture is being written to the standard output.");
1395 if (global_capture_opts.output_to_pipe) {
1396 cmdarg_err("Multiple capture files requested, but "
1397 "the capture file is a pipe.");
1400 if (!global_capture_opts.has_autostop_filesize &&
1401 !global_capture_opts.has_file_duration) {
1402 cmdarg_err("Multiple capture files requested, but "
1403 "no maximum capture file size or duration was specified.");
1408 /* They didn't specify a "-w" flag, so we won't be saving to a
1409 capture file. Check for options that only make sense if
1410 we're saving to a file. */
1411 if (global_capture_opts.has_autostop_filesize) {
1412 cmdarg_err("Maximum capture file size specified, but "
1413 "capture isn't being saved to a file.");
1416 if (global_capture_opts.multi_files_on) {
1417 cmdarg_err("Multiple capture files requested, but "
1418 "the capture isn't being saved to a file.");
1427 /* Start windows sockets */
1428 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1431 /* Notify all registered modules that have had any of their preferences
1432 changed either from one of the preferences file or from the command
1433 line that their preferences have changed. */
1436 /* At this point MATE will have registered its field array so we can
1437 have a tap filter with one of MATE's late-registered fields as part
1438 of the filter. We can now process all the "-z" arguments. */
1439 start_requested_stats();
1441 /* disabled protocols as per configuration file */
1442 if (gdp_path == NULL && dp_path == NULL) {
1443 set_disabled_protos_list();
1446 /* Build the column format array */
1447 build_column_format_array(&cfile.cinfo, prefs->num_cols, TRUE);
1450 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
1451 capture_opts_trim_ring_num_files(&global_capture_opts);
1454 if (rfilter != NULL) {
1455 if (!dfilter_compile(rfilter, &rfcode)) {
1456 cmdarg_err("%s", dfilter_error_msg);
1458 #ifdef HAVE_PCAP_OPEN_DEAD
1462 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1464 if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1466 " Note: That display filter code looks like a valid capture filter;");
1468 " maybe you mixed them up?");
1477 cfile.rfcode = rfcode;
1479 if (print_packet_info) {
1480 /* If we're printing as text or PostScript, we have
1481 to create a print stream. */
1482 if (output_action == WRITE_TEXT) {
1483 switch (print_format) {
1486 print_stream = print_stream_text_stdio_new(stdout);
1490 print_stream = print_stream_ps_stdio_new(stdout);
1494 g_assert_not_reached();
1499 /* We have to dissect each packet if:
1501 we're printing information about each packet;
1503 we're using a read filter on the packets;
1505 we're using any taps. */
1506 do_dissection = print_packet_info || rfcode || have_tap_listeners();
1510 * We're reading a capture file.
1514 * Immediately relinquish any special privileges we have; we must not
1515 * be allowed to read any capture files the user running TShark
1518 relinquish_special_privs_perm();
1519 print_current_user();
1521 if (cf_open(&cfile, cf_name, FALSE, &err) != CF_OK) {
1526 /* Set timestamp precision; there should arguably be a command-line
1527 option to let the user set this. */
1528 switch(wtap_file_tsprecision(cfile.wth)) {
1529 case(WTAP_FILE_TSPREC_SEC):
1530 timestamp_set_precision(TS_PREC_AUTO_SEC);
1532 case(WTAP_FILE_TSPREC_DSEC):
1533 timestamp_set_precision(TS_PREC_AUTO_DSEC);
1535 case(WTAP_FILE_TSPREC_CSEC):
1536 timestamp_set_precision(TS_PREC_AUTO_CSEC);
1538 case(WTAP_FILE_TSPREC_MSEC):
1539 timestamp_set_precision(TS_PREC_AUTO_MSEC);
1541 case(WTAP_FILE_TSPREC_USEC):
1542 timestamp_set_precision(TS_PREC_AUTO_USEC);
1544 case(WTAP_FILE_TSPREC_NSEC):
1545 timestamp_set_precision(TS_PREC_AUTO_NSEC);
1548 g_assert_not_reached();
1551 /* Process the packets in the file */
1553 err = load_cap_file(&cfile, global_capture_opts.save_file, out_file_type,
1554 global_capture_opts.has_autostop_packets ? global_capture_opts.autostop_packets : 0,
1555 global_capture_opts.has_autostop_filesize ? global_capture_opts.autostop_filesize : 0);
1557 err = load_cap_file(&cfile, NULL, out_file_type, 0, 0);
1565 /* No capture file specified, so we're supposed to do a live capture
1566 (or get a list of link-layer types for a live capture device);
1567 do we have support for live captures? */
1574 cmdarg_err("WinPcap couldn't be found.");
1575 detailed_err = cant_load_winpcap_err("TShark");
1576 cmdarg_err_cont("%s", detailed_err);
1577 g_free(detailed_err);
1582 /* trim the interface name and exit if that failed */
1583 if (!capture_opts_trim_iface(&global_capture_opts,
1584 (prefs->capture_device) ? get_if_name(prefs->capture_device) : NULL)) {
1588 /* if requested, list the link layer types and exit */
1589 if (list_link_layer_types) {
1590 status = capture_opts_list_link_layer_types(&global_capture_opts, FALSE);
1594 if (print_packet_info) {
1595 if (!write_preamble(NULL)) {
1597 show_print_file_io_error(err);
1600 } else if (!quiet) {
1602 * We're not printing information for each packet, and the user
1603 * didn't ask us not to print a count of packets as they arrive,
1604 * so print that count so the user knows that packets are arriving.
1606 * XXX - what if the user wants to do a live capture, doesn't want
1607 * to save it to a file, doesn't want information printed for each
1608 * packet, does want some "-z" statistic, and wants packet counts
1609 * so they know whether they're seeing any packets?
1611 print_packet_counts = TRUE;
1614 /* For now, assume libpcap gives microsecond precision. */
1615 timestamp_set_precision(TS_PREC_AUTO_USEC);
1619 if (print_packet_info) {
1620 if (!write_finale()) {
1622 show_print_file_io_error(err);
1626 /* No - complain. */
1627 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1632 #if GLIB_CHECK_VERSION(2,10,0)
1633 if (cfile.plist_start != NULL)
1634 g_slice_free_chain(frame_data, cfile.plist_start, next);
1637 draw_tap_listeners(TRUE);
1638 funnel_dump_all_text_windows();
1641 output_fields_free(output_fields);
1642 output_fields = NULL;
1647 /*#define USE_BROKEN_G_MAIN_LOOP*/
1649 #ifdef USE_BROKEN_G_MAIN_LOOP
1652 gboolean loop_running = FALSE;
1654 guint32 packet_count = 0;
1657 /* XXX - move to the right position / file */
1658 /* read from a pipe (callback) */
1659 typedef gboolean (*pipe_input_cb_t) (gint source, gpointer user_data);
1661 typedef struct pipe_input_tag {
1665 pipe_input_cb_t input_cb;
1666 guint pipe_input_id;
1668 GStaticMutex callback_running;
1672 static pipe_input_t pipe_input;
1675 /* The timer has expired, see if there's stuff to read from the pipe,
1676 if so, do the callback */
1678 pipe_timer_cb(gpointer data)
1682 gboolean result, result1;
1684 pipe_input_t *pipe_input = data;
1685 gint iterations = 0;
1688 g_static_mutex_lock (&pipe_input->callback_running);
1690 /* try to read data from the pipe only 5 times, to avoid blocking */
1691 while(iterations < 5) {
1692 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: new iteration");*/
1694 /* Oddly enough although Named pipes don't work on win9x,
1695 PeekNamedPipe does !!! */
1696 handle = (HANDLE) _get_osfhandle (pipe_input->source);
1697 result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
1699 /* Get the child process exit status */
1700 result1 = GetExitCodeProcess((HANDLE)*(pipe_input->child_process),
1703 /* If the Peek returned an error, or there are bytes to be read
1704 or the childwatcher thread has terminated then call the normal
1706 if (!result || avail > 0 || childstatus != STILL_ACTIVE) {
1708 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: data avail");*/
1710 /* And call the real handler */
1711 if (!pipe_input->input_cb(pipe_input->source, pipe_input->user_data)) {
1712 g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: input pipe closed, iterations: %u", iterations);
1713 /* pipe closed, return false so that the timer is stopped */
1714 g_static_mutex_unlock (&pipe_input->callback_running);
1719 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: no data avail");*/
1720 /* No data, stop now */
1727 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: finished with iterations: %u, new timer", iterations);*/
1729 g_static_mutex_unlock (&pipe_input->callback_running);
1731 /* we didn't stopped the timer, so let it run */
1738 pipe_input_set_handler(gint source, gpointer user_data, int *child_process, pipe_input_cb_t input_cb)
1741 pipe_input.source = source;
1742 pipe_input.child_process = child_process;
1743 pipe_input.user_data = user_data;
1744 pipe_input.input_cb = input_cb;
1747 g_static_mutex_init(&pipe_input.callback_running);
1748 /* Tricky to use pipes in win9x, as no concept of wait. NT can
1749 do this but that doesn't cover all win32 platforms. GTK can do
1750 this but doesn't seem to work over processes. Attempt to do
1751 something similar here, start a timer and check for data on every
1753 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_input_set_handler: new");*/
1754 pipe_input.pipe_input_id = g_timeout_add(200, pipe_timer_cb, &pipe_input);
1764 #ifdef USE_TSHARK_SELECT
1768 struct sigaction action, oldaction;
1772 * XXX - dropping privileges is still required, until code cleanup is done
1774 * remove all dependencies to pcap specific code and using only dumpcap is almost done.
1775 * when it's done, we don't need special privileges to run tshark at all,
1776 * therefore we don't need to drop these privileges
1777 * The only thing we might want to keep is a warning if tshark is run as root,
1778 * as it's no longer necessary and potentially dangerous.
1780 * THE FOLLOWING IS THE FORMER COMMENT WHICH IS NO LONGER REALLY VALID:
1781 * We've opened the capture device, so we shouldn't need any special
1782 * privileges any more; relinquish those privileges.
1784 * XXX - if we have saved set-user-ID support, we should give up those
1785 * privileges immediately, and then reclaim them long enough to get
1786 * a list of network interfaces and to open one, and then give them
1787 * up again, so that stuff we do while processing the argument list,
1788 * reading the user's preferences, loading and starting plugins
1789 * (especially *user* plugins), etc. is done with the user's privileges,
1790 * not special privileges.
1792 relinquish_special_privs_perm();
1793 print_current_user();
1795 /* Cleanup all data structures used for dissection. */
1796 cleanup_dissection();
1797 /* Initialize all data structures used for dissection. */
1801 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1802 SetConsoleCtrlHandler(capture_cleanup, TRUE);
1804 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
1806 action.sa_handler = capture_cleanup;
1807 action.sa_flags = 0;
1808 sigemptyset(&action.sa_mask);
1809 sigaction(SIGTERM, &action, NULL);
1810 sigaction(SIGINT, &action, NULL);
1811 sigaction(SIGHUP, NULL, &oldaction);
1812 if (oldaction.sa_handler == SIG_DFL)
1813 sigaction(SIGHUP, &action, NULL);
1816 /* Catch SIGINFO and, if we get it and we're capturing to a file in
1817 quiet mode, report the number of packets we've captured. */
1818 action.sa_handler = report_counts_siginfo;
1819 action.sa_flags = 0;
1820 sigemptyset(&action.sa_mask);
1821 sigaction(SIGINFO, &action, NULL);
1822 #endif /* SIGINFO */
1825 global_capture_opts.state = CAPTURE_PREPARING;
1827 /* Let the user know what interface was chosen. */
1828 global_capture_opts.iface_descr = get_interface_descriptive_name(global_capture_opts.iface);
1829 fprintf(stderr, "Capturing on %s\n", global_capture_opts.iface_descr);
1831 ret = sync_pipe_start(&global_capture_opts);
1836 /* the actual capture loop
1838 * XXX - glib doesn't seem to provide any event based loop handling.
1840 * XXX - for whatever reason,
1841 * calling g_main_loop_new() ends up in 100% cpu load.
1843 * But that doesn't matter: in UNIX we can use select() to find an input
1844 * source with something to do.
1846 * But that doesn't matter because we're in a CLI (that doesn't need to
1847 * update a GUI or something at the same time) so it's OK if we block
1848 * trying to read from the pipe.
1850 * So all the stuff in USE_TSHARK_SELECT could be removed unless I'm
1851 * wrong (but I leave it there in case I am...).
1854 #ifdef USE_TSHARK_SELECT
1856 FD_SET(pipe_input.source, &readfds);
1859 loop_running = TRUE;
1861 while (loop_running)
1863 #ifdef USE_TSHARK_SELECT
1864 ret = select(pipe_input.source+1, &readfds, NULL, NULL, NULL);
1870 } else if (ret == 1) {
1872 /* Call the real handler */
1873 if (!pipe_input.input_cb(pipe_input.source, pipe_input.user_data)) {
1874 g_log(NULL, G_LOG_LEVEL_DEBUG, "input pipe closed");
1877 #ifdef USE_TSHARK_SELECT
1886 /* XXX - move the call to main_window_update() out of capture_sync.c */
1887 /* dummy for capture_sync.c to make linker happy */
1888 void main_window_update(void)
1892 /* capture child detected an error */
1894 capture_input_error_message(capture_options *capture_opts _U_, char *error_msg, char *secondary_error_msg)
1896 cmdarg_err("%s", error_msg);
1897 cmdarg_err_cont("%s", secondary_error_msg);
1901 /* capture child detected an capture filter related error */
1903 capture_input_cfilter_error_message(capture_options *capture_opts, char *error_message)
1905 dfilter_t *rfcode = NULL;
1908 if (dfilter_compile(capture_opts->cfilter, &rfcode) && rfcode != NULL) {
1910 "Invalid capture filter: \"%s\"!\n"
1912 "That string looks like a valid display filter; however, it isn't a valid\n"
1913 "capture filter (%s).\n"
1915 "Note that display filters and capture filters don't have the same syntax,\n"
1916 "so you can't use most display filter expressions as capture filters.\n"
1918 "See the User's Guide for a description of the capture filter syntax.",
1919 capture_opts->cfilter, error_message);
1920 dfilter_free(rfcode);
1923 "Invalid capture filter: \"%s\"!\n"
1925 "That string isn't a valid capture filter (%s).\n"
1926 "See the User's Guide for a description of the capture filter syntax.",
1927 capture_opts->cfilter, error_message);
1932 /* capture child tells us we have a new (or the first) capture file */
1934 capture_input_new_file(capture_options *capture_opts, gchar *new_file)
1936 gboolean is_tempfile;
1940 if(capture_opts->state == CAPTURE_PREPARING) {
1941 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "Capture started!");
1943 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "File: \"%s\"", new_file);
1945 g_assert(capture_opts->state == CAPTURE_PREPARING || capture_opts->state == CAPTURE_RUNNING);
1947 /* free the old filename */
1948 if (capture_opts->save_file != NULL) {
1950 /* we start a new capture file, close the old one (if we had one before) */
1951 if( ((capture_file *) capture_opts->cf)->state != FILE_CLOSED) {
1952 if ( ((capture_file *) capture_opts->cf)->wth != NULL) {
1953 wtap_close(((capture_file *) capture_opts->cf)->wth);
1955 ((capture_file *) capture_opts->cf)->state = FILE_CLOSED;
1958 g_free(capture_opts->save_file);
1959 is_tempfile = FALSE;
1961 /* we didn't had a save_file before, must be a tempfile */
1965 /* save the new filename */
1966 capture_opts->save_file = g_strdup(new_file);
1968 /* if we are in real-time mode, open the new file now */
1970 /* Attempt to open the capture file and set up to read from it. */
1971 switch(cf_open(capture_opts->cf, capture_opts->save_file, is_tempfile, &err)) {
1975 /* Don't unlink (delete) the save file - leave it around,
1976 for debugging purposes. */
1977 g_free(capture_opts->save_file);
1978 capture_opts->save_file = NULL;
1983 capture_opts->state = CAPTURE_RUNNING;
1989 /* capture child tells us we have new packets to read */
1991 capture_input_new_packets(capture_options *capture_opts, int to_read)
1997 capture_file *cf = capture_opts->cf;
1998 gboolean filtering_tap_listeners;
2003 * Prevent a SIGINFO handler from writing to stdout while we're
2004 * doing so; instead, have it just set a flag telling us to print
2005 * that information when we're done.
2008 #endif /* SIGINFO */
2010 /* Do we have any tap listeners with filters? */
2011 filtering_tap_listeners = have_filtering_tap_listeners();
2013 /* Get the union of the flags for all tap listeners. */
2014 tap_flags = union_of_tap_listener_flags();
2017 while (to_read-- && cf->wth) {
2018 ret = wtap_read(cf->wth, &err, &err_info, &data_offset);
2020 /* read from file failed, tell the capture child to stop */
2021 sync_pipe_stop(capture_opts);
2022 wtap_close(cf->wth);
2025 ret = process_packet(cf, data_offset, wtap_phdr(cf->wth),
2026 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2027 filtering_tap_listeners, tap_flags);
2030 /* packet sucessfully read and gone through the "Read Filter" */
2036 * Dumpcap's doing all the work; we're not doing any dissection.
2037 * Count all the packets it wrote.
2039 packet_count += to_read;
2042 if (print_packet_counts) {
2043 /* We're printing packet counts. */
2044 if (packet_count != 0) {
2045 fprintf(stderr, "\r%u ", packet_count);
2046 /* stderr could be line buffered */
2053 * Allow SIGINFO handlers to write.
2058 * If a SIGINFO handler asked us to write out capture counts, do so.
2062 #endif /* SIGINFO */
2068 if (!print_packet_counts) {
2069 /* Report the count only if we aren't printing a packet count
2070 as packets arrive. */
2071 fprintf(stderr, "%u packet%s captured\n", packet_count,
2072 plurality(packet_count, "", "s"));
2075 infoprint = FALSE; /* we just reported it */
2076 #endif /* SIGINFO */
2081 report_counts_siginfo(int signum _U_)
2083 int sav_errno = errno;
2084 /* If we've been told to delay printing, just set a flag asking
2085 that we print counts (if we're supposed to), otherwise print
2086 the count of packets captured (if we're supposed to). */
2093 #endif /* SIGINFO */
2096 /* capture child detected any packet drops? */
2098 capture_input_drops(capture_options *capture_opts _U_, guint32 dropped)
2100 if (print_packet_counts) {
2101 /* We're printing packet counts to stderr.
2102 Send a newline so that we move to the line after the packet count. */
2103 fprintf(stderr, "\n");
2107 /* We're printing packet counts to stderr.
2108 Send a newline so that we move to the line after the packet count. */
2109 fprintf(stderr, "%u packet%s dropped\n", dropped, plurality(dropped, "", "s"));
2114 /* capture child closed its side of the pipe, do the required cleanup */
2116 capture_input_closed(capture_options *capture_opts)
2120 if(capture_opts->cf != NULL && ((capture_file *) capture_opts->cf)->wth != NULL) {
2121 wtap_close(((capture_file *) capture_opts->cf)->wth);
2123 #ifdef USE_BROKEN_G_MAIN_LOOP
2124 /*g_main_loop_quit(loop);*/
2127 loop_running = FALSE;
2136 capture_cleanup(DWORD ctrltype _U_)
2138 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
2139 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
2140 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
2141 like SIGTERM at least when the machine's shutting down.
2143 For now, we handle them all as indications that we should clean up
2144 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
2147 However, as handlers run in a new thread, we can't just longjmp
2148 out; we have to set "ld.go" to FALSE, and must return TRUE so that
2149 no other handler - such as one that would terminate the process -
2152 XXX - for some reason, typing ^C to TShark, if you run this in
2153 a Cygwin console window in at least some versions of Cygwin,
2154 causes TShark to terminate immediately; this routine gets
2155 called, but the main loop doesn't get a chance to run and
2156 exit cleanly, at least if this is compiled with Microsoft Visual
2157 C++ (i.e., it's a property of the Cygwin console window or Bash;
2158 it happens if TShark is not built with Cygwin - for all I know,
2159 building it with Cygwin may make the problem go away). */
2161 /* tell the capture child to stop */
2162 sync_pipe_stop(&global_capture_opts);
2164 /* don't stop our own loop already here, otherwise status messages and
2165 * cleanup wouldn't be done properly. The child will indicate the stop of
2166 * everything by calling capture_input_closed() later */
2172 capture_cleanup(int signum _U_)
2174 /* tell the capture child to stop */
2175 sync_pipe_stop(&global_capture_opts);
2178 #endif /* HAVE_LIBPCAP */
2180 #if GLIB_CHECK_VERSION(2,10,0)
2182 process_packet_first_pass(capture_file *cf,
2183 gint64 offset, const struct wtap_pkthdr *whdr,
2184 union wtap_pseudo_header *pseudo_header, const guchar *pd)
2186 frame_data *fdata = g_slice_new(frame_data);
2190 /* Count this packet. */
2193 /* If we're not running a display filter and we're not printing any
2194 packet information, we don't need to do a dissection. This means
2195 that all packets can be marked as 'passed'. */
2198 frame_data_init(fdata, cf->count, whdr, offset, cum_bytes);
2200 /* If we're going to print packet information, or we're going to
2201 run a read filter, or we're going to process taps, set up to
2202 do a dissection and do so. */
2203 if (do_dissection) {
2205 /* Grab any resolved addresses */
2206 host_name_lookup_process(NULL);
2208 /* The protocol tree will be "visible", i.e., printed, only if we're
2209 printing packet details, which is true if we're printing stuff
2210 ("print_packet_info" is true) and we're in verbose mode ("verbose"
2212 epan_dissect_init(&edt, FALSE, FALSE);
2214 /* If we're running a read filter, prime the epan_dissect_t with that
2217 epan_dissect_prime_dfilter(&edt, cf->rfcode);
2219 frame_data_set_before_dissect(fdata, &cf->elapsed_time,
2220 &first_ts, &prev_dis_ts, &prev_cap_ts);
2222 epan_dissect_run(&edt, pseudo_header, pd, fdata, NULL);
2224 /* Run the read filter if we have one. */
2226 passed = dfilter_apply_edt(cf->rfcode, &edt);
2230 frame_data_set_after_dissect(fdata, &cum_bytes, &prev_dis_ts);
2231 cap_file_add_fdata(cf, fdata);
2234 g_slice_free(frame_data, fdata);
2237 epan_dissect_cleanup(&edt);
2243 process_packet_second_pass(capture_file *cf, frame_data *fdata,
2244 gint64 offset, union wtap_pseudo_header *pseudo_header, const guchar *pd,
2245 gboolean filtering_tap_listeners, guint tap_flags)
2247 gboolean create_proto_tree;
2252 /* If we're not running a display filter and we're not printing any
2253 packet information, we don't need to do a dissection. This means
2254 that all packets can be marked as 'passed'. */
2257 /* If we're going to print packet information, or we're going to
2258 run a read filter, or we're going to process taps, set up to
2259 do a dissection and do so. */
2260 if (do_dissection) {
2262 /* Grab any resolved addresses */
2263 host_name_lookup_process(NULL);
2265 if (cf->rfcode || verbose || filtering_tap_listeners ||
2266 (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo))
2267 create_proto_tree = TRUE;
2269 create_proto_tree = FALSE;
2271 /* The protocol tree will be "visible", i.e., printed, only if we're
2272 printing packet details, which is true if we're printing stuff
2273 ("print_packet_info" is true) and we're in verbose mode ("verbose"
2275 epan_dissect_init(&edt, create_proto_tree, print_packet_info && verbose);
2277 /* If we're running a read filter, prime the epan_dissect_t with that
2280 epan_dissect_prime_dfilter(&edt, cf->rfcode);
2282 col_custom_prime_edt(&edt, &cf->cinfo);
2284 tap_queue_init(&edt);
2286 /* We only need the columns if either
2288 1) some tap needs the columns
2292 2) we're printing packet info but we're *not* verbose; in verbose
2293 mode, we print the protocol tree, not the protocol summary. */
2294 if ((tap_flags & TL_REQUIRES_COLUMNS) || (print_packet_info && !verbose))
2299 epan_dissect_run(&edt, pseudo_header, pd, fdata, cinfo);
2301 tap_push_tapped_queue(&edt);
2303 /* Run the read filter if we have one. */
2305 passed = dfilter_apply_edt(cf->rfcode, &edt);
2309 /* Process this packet. */
2310 if (print_packet_info) {
2311 /* We're printing packet information; print the information for
2314 print_packet(cf, &edt);
2316 print_packet(cf, NULL);
2318 /* The ANSI C standard does not appear to *require* that a line-buffered
2319 stream be flushed to the host environment whenever a newline is
2320 written, it just says that, on such a stream, characters "are
2321 intended to be transmitted to or from the host environment as a
2322 block when a new-line character is encountered".
2324 The Visual C++ 6.0 C implementation doesn't do what is intended;
2325 even if you set a stream to be line-buffered, it still doesn't
2326 flush the buffer at the end of every line.
2328 So, if the "-l" flag was specified, we flush the standard output
2329 at the end of a packet. This will do the right thing if we're
2330 printing packet summary lines, and, as we print the entire protocol
2331 tree for a single packet without waiting for anything to happen,
2332 it should be as good as line-buffered mode if we're printing
2333 protocol trees. (The whole reason for the "-l" flag in either
2334 tcpdump or TShark is to allow the output of a live capture to
2335 be piped to a program or script and to have that script see the
2336 information for the packet as soon as it's printed, rather than
2337 having to wait until a standard I/O buffer fills up. */
2341 if (ferror(stdout)) {
2342 show_print_file_io_error(errno);
2348 if (do_dissection) {
2349 epan_dissect_cleanup(&edt);
2356 load_cap_file(capture_file *cf, char *save_file, int out_file_type,
2357 int max_packet_count, gint64 max_byte_count)
2360 int snapshot_length;
2365 char *save_file_string = NULL;
2366 gboolean filtering_tap_listeners;
2369 linktype = wtap_file_encap(cf->wth);
2370 if (save_file != NULL) {
2371 /* Get a string that describes what we're writing to */
2372 save_file_string = output_file_description(save_file);
2374 /* Set up to write to the capture file. */
2375 snapshot_length = wtap_snapshot_length(cf->wth);
2376 if (snapshot_length == 0) {
2377 /* Snapshot length of input file not known. */
2378 snapshot_length = WTAP_MAX_PACKET_SIZE;
2380 pdh = wtap_dump_open(save_file, out_file_type, linktype, snapshot_length,
2381 FALSE /* compressed */, &err);
2384 /* We couldn't set up to write to the capture file. */
2387 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2388 cmdarg_err("Capture files can't be written in that format.");
2391 case WTAP_ERR_UNSUPPORTED_ENCAP:
2392 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2393 cmdarg_err("The capture file being read can't be written in "
2397 case WTAP_ERR_CANT_OPEN:
2398 cmdarg_err("The %s couldn't be created for some "
2399 "unknown reason.", save_file_string);
2402 case WTAP_ERR_SHORT_WRITE:
2403 cmdarg_err("A full header couldn't be written to the %s.",
2408 cmdarg_err("The %s could not be created: %s.", save_file_string,
2409 wtap_strerror(err));
2415 if (print_packet_info) {
2416 if (!write_preamble(cf)) {
2418 show_print_file_io_error(err);
2425 /* Do we have any tap listeners with filters? */
2426 filtering_tap_listeners = have_filtering_tap_listeners();
2428 /* Get the union of the flags for all tap listeners. */
2429 tap_flags = union_of_tap_listener_flags();
2431 if (perform_two_pass_analysis) {
2432 #if GLIB_CHECK_VERSION(2,10,0)
2434 int old_max_packet_count = max_packet_count;
2436 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
2437 if (process_packet_first_pass(cf, data_offset, wtap_phdr(cf->wth),
2438 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth))) {
2439 /* Stop reading if we have the maximum number of packets;
2440 * When the -c option has not been used, max_packet_count
2441 * starts at 0, which practically means, never stop reading.
2442 * (unless we roll over max_packet_count ?)
2444 if( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
2445 err = 0; /* This is not an error */
2451 /* Close the sequential I/O side, to free up memory it requires. */
2452 wtap_sequential_close(cf->wth);
2454 /* Allow the protocol dissectors to free up memory that they
2455 * don't need after the sequential run-through of the packets. */
2456 postseq_cleanup_all_protocols();
2458 max_packet_count = old_max_packet_count;
2460 for (fdata = cf->plist_start; err == 0 && fdata != NULL; fdata = fdata->next) {
2461 if (wtap_seek_read(cf->wth, fdata->file_off, &cf->pseudo_header,
2462 cf->pd, fdata->cap_len, &err, &err_info)) {
2463 if (process_packet_second_pass(cf, fdata, fdata->file_off,
2464 &cf->pseudo_header, cf->pd,
2465 filtering_tap_listeners, tap_flags)) {
2466 /* Either there's no read filtering or this packet passed the
2467 filter, so, if we're writing to a capture file, write
2470 if (!wtap_dump(pdh, wtap_phdr(cf->wth),
2471 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2473 /* Error writing to a capture file */
2474 show_capture_file_io_error(save_file, err, FALSE);
2475 wtap_dump_close(pdh, &err);
2479 /* Stop reading if we have the maximum number of packets;
2480 * When the -c option has not been used, max_packet_count
2481 * starts at 0, which practically means, never stop reading.
2482 * (unless we roll over max_packet_count ?)
2484 if( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
2485 err = 0; /* This is not an error */
2494 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
2495 if (process_packet(cf, data_offset, wtap_phdr(cf->wth),
2496 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2497 filtering_tap_listeners, tap_flags)) {
2498 /* Either there's no read filtering or this packet passed the
2499 filter, so, if we're writing to a capture file, write
2502 if (!wtap_dump(pdh, wtap_phdr(cf->wth),
2503 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2505 /* Error writing to a capture file */
2506 show_capture_file_io_error(save_file, err, FALSE);
2507 wtap_dump_close(pdh, &err);
2511 /* Stop reading if we have the maximum number of packets;
2512 * When the -c option has not been used, max_packet_count
2513 * starts at 0, which practically means, never stop reading.
2514 * (unless we roll over max_packet_count ?)
2516 if( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
2517 err = 0; /* This is not an error */
2525 /* Print a message noting that the read failed somewhere along the line. */
2528 case WTAP_ERR_UNSUPPORTED_ENCAP:
2529 cmdarg_err("\"%s\" has a packet with a network type that TShark doesn't support.\n(%s)",
2530 cf->filename, err_info);
2534 case WTAP_ERR_CANT_READ:
2535 cmdarg_err("An attempt to read from \"%s\" failed for some unknown reason.",
2539 case WTAP_ERR_SHORT_READ:
2540 cmdarg_err("\"%s\" appears to have been cut short in the middle of a packet.",
2544 case WTAP_ERR_BAD_RECORD:
2545 cmdarg_err("\"%s\" appears to be damaged or corrupt.\n(%s)",
2546 cf->filename, err_info);
2551 cmdarg_err("An error occurred while reading \"%s\": %s.",
2552 cf->filename, wtap_strerror(err));
2555 if (save_file != NULL) {
2556 /* Now close the capture file. */
2557 if (!wtap_dump_close(pdh, &err))
2558 show_capture_file_io_error(save_file, err, TRUE);
2561 if (save_file != NULL) {
2562 /* Now close the capture file. */
2563 if (!wtap_dump_close(pdh, &err))
2564 show_capture_file_io_error(save_file, err, TRUE);
2566 if (print_packet_info) {
2567 if (!write_finale()) {
2569 show_print_file_io_error(err);
2576 wtap_close(cf->wth);
2579 g_free(save_file_string);
2585 process_packet(capture_file *cf, gint64 offset, const struct wtap_pkthdr *whdr,
2586 union wtap_pseudo_header *pseudo_header, const guchar *pd,
2587 gboolean filtering_tap_listeners, guint tap_flags)
2590 gboolean create_proto_tree;
2595 /* Count this packet. */
2598 /* If we're not running a display filter and we're not printing any
2599 packet information, we don't need to do a dissection. This means
2600 that all packets can be marked as 'passed'. */
2603 frame_data_init(&fdata, cf->count, whdr, offset, cum_bytes);
2605 /* If we're going to print packet information, or we're going to
2606 run a read filter, or we're going to process taps, set up to
2607 do a dissection and do so. */
2608 if (do_dissection) {
2609 if (print_packet_info && g_resolv_flags)
2610 /* Grab any resolved addresses */
2611 host_name_lookup_process(NULL);
2613 if (cf->rfcode || verbose || filtering_tap_listeners ||
2614 (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo))
2615 create_proto_tree = TRUE;
2617 create_proto_tree = FALSE;
2619 /* The protocol tree will be "visible", i.e., printed, only if we're
2620 printing packet details, which is true if we're printing stuff
2621 ("print_packet_info" is true) and we're in verbose mode ("verbose"
2623 epan_dissect_init(&edt, create_proto_tree, print_packet_info && verbose);
2625 /* If we're running a read filter, prime the epan_dissect_t with that
2628 epan_dissect_prime_dfilter(&edt, cf->rfcode);
2630 col_custom_prime_edt(&edt, &cf->cinfo);
2632 tap_queue_init(&edt);
2634 /* We only need the columns if either
2636 1) some tap needs the columns
2640 2) we're printing packet info but we're *not* verbose; in verbose
2641 mode, we print the protocol tree, not the protocol summary. */
2642 if ((tap_flags & TL_REQUIRES_COLUMNS) || (print_packet_info && !verbose))
2647 frame_data_set_before_dissect(&fdata, &cf->elapsed_time,
2648 &first_ts, &prev_dis_ts, &prev_cap_ts);
2650 epan_dissect_run(&edt, pseudo_header, pd, &fdata, cinfo);
2652 tap_push_tapped_queue(&edt);
2654 /* Run the read filter if we have one. */
2656 passed = dfilter_apply_edt(cf->rfcode, &edt);
2660 frame_data_set_after_dissect(&fdata, &cum_bytes, &prev_dis_ts);
2662 /* Process this packet. */
2663 if (print_packet_info) {
2664 /* We're printing packet information; print the information for
2667 print_packet(cf, &edt);
2669 print_packet(cf, NULL);
2671 /* The ANSI C standard does not appear to *require* that a line-buffered
2672 stream be flushed to the host environment whenever a newline is
2673 written, it just says that, on such a stream, characters "are
2674 intended to be transmitted to or from the host environment as a
2675 block when a new-line character is encountered".
2677 The Visual C++ 6.0 C implementation doesn't do what is intended;
2678 even if you set a stream to be line-buffered, it still doesn't
2679 flush the buffer at the end of every line.
2681 So, if the "-l" flag was specified, we flush the standard output
2682 at the end of a packet. This will do the right thing if we're
2683 printing packet summary lines, and, as we print the entire protocol
2684 tree for a single packet without waiting for anything to happen,
2685 it should be as good as line-buffered mode if we're printing
2686 protocol trees. (The whole reason for the "-l" flag in either
2687 tcpdump or TShark is to allow the output of a live capture to
2688 be piped to a program or script and to have that script see the
2689 information for the packet as soon as it's printed, rather than
2690 having to wait until a standard I/O buffer fills up. */
2694 if (ferror(stdout)) {
2695 show_print_file_io_error(errno);
2701 if (do_dissection) {
2702 epan_dissect_cleanup(&edt);
2703 frame_data_cleanup(&fdata);
2709 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
2711 char *save_file_string;
2713 save_file_string = output_file_description(fname);
2718 cmdarg_err("Not all the packets could be written to the %s because there is "
2719 "no space left on the file system.",
2725 cmdarg_err("Not all the packets could be written to the %s because you are "
2726 "too close to, or over your disk quota.",
2731 case WTAP_ERR_CANT_CLOSE:
2732 cmdarg_err("The %s couldn't be closed for some unknown reason.",
2736 case WTAP_ERR_SHORT_WRITE:
2737 cmdarg_err("Not all the packets could be written to the %s.",
2743 cmdarg_err("The %s could not be closed: %s.", save_file_string,
2744 wtap_strerror(err));
2746 cmdarg_err("An error occurred while writing to the %s: %s.",
2747 save_file_string, wtap_strerror(err));
2751 g_free(save_file_string);
2755 write_preamble(capture_file *cf)
2757 switch (output_action) {
2760 return print_preamble(print_stream, cf ? cf->filename : NULL);
2764 write_pdml_preamble(stdout);
2766 write_psml_preamble(stdout);
2767 return !ferror(stdout);
2770 write_fields_preamble(output_fields, stdout);
2771 return !ferror(stdout);
2774 g_assert_not_reached();
2780 get_line_buf(size_t len)
2782 static char *line_bufp = NULL;
2783 static size_t line_buf_len = 256;
2784 size_t new_line_buf_len;
2786 for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
2787 new_line_buf_len *= 2)
2789 if (line_bufp == NULL) {
2790 line_buf_len = new_line_buf_len;
2791 line_bufp = g_malloc(line_buf_len + 1);
2793 if (new_line_buf_len > line_buf_len) {
2794 line_buf_len = new_line_buf_len;
2795 line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2802 print_columns(capture_file *cf)
2809 line_bufp = get_line_buf(256);
2812 for (i = 0; i < cf->cinfo.num_cols; i++) {
2813 switch (cf->cinfo.col_fmt[i]) {
2817 * Don't print this if we're doing a live capture from a network
2818 * interface - if we're doing a live capture, you won't be
2819 * able to look at the capture in the future (it's not being
2820 * saved anywhere), so the frame numbers are unlikely to be
2823 * (XXX - it might be nice to be able to save and print at
2824 * the same time, sort of like an "Update list of packets
2825 * in real time" capture in Wireshark.)
2827 if (global_capture_opts.iface != NULL)
2830 column_len = strlen(cf->cinfo.col_data[i]);
2833 line_bufp = get_line_buf(buf_offset + column_len);
2834 sprintf(line_bufp + buf_offset, "%3s", cf->cinfo.col_data[i]);
2840 case COL_ABS_DATE_TIME: /* XXX - wider */
2841 column_len = strlen(cf->cinfo.col_data[i]);
2842 if (column_len < 10)
2844 line_bufp = get_line_buf(buf_offset + column_len);
2845 sprintf(line_bufp + buf_offset, "%10s", cf->cinfo.col_data[i]);
2851 case COL_DEF_DL_SRC:
2852 case COL_RES_DL_SRC:
2853 case COL_UNRES_DL_SRC:
2854 case COL_DEF_NET_SRC:
2855 case COL_RES_NET_SRC:
2856 case COL_UNRES_NET_SRC:
2857 column_len = strlen(cf->cinfo.col_data[i]);
2858 if (column_len < 12)
2860 line_bufp = get_line_buf(buf_offset + column_len);
2861 sprintf(line_bufp + buf_offset, "%12s", cf->cinfo.col_data[i]);
2867 case COL_DEF_DL_DST:
2868 case COL_RES_DL_DST:
2869 case COL_UNRES_DL_DST:
2870 case COL_DEF_NET_DST:
2871 case COL_RES_NET_DST:
2872 case COL_UNRES_NET_DST:
2873 column_len = strlen(cf->cinfo.col_data[i]);
2874 if (column_len < 12)
2876 line_bufp = get_line_buf(buf_offset + column_len);
2877 sprintf(line_bufp + buf_offset, "%-12s", cf->cinfo.col_data[i]);
2881 column_len = strlen(cf->cinfo.col_data[i]);
2882 line_bufp = get_line_buf(buf_offset + column_len);
2883 strcat(line_bufp + buf_offset, cf->cinfo.col_data[i]);
2886 buf_offset += column_len;
2887 if (i != cf->cinfo.num_cols - 1) {
2889 * This isn't the last column, so we need to print a
2890 * separator between this column and the next.
2892 * If we printed a network source and are printing a
2893 * network destination of the same type next, separate
2894 * them with "->"; if we printed a network destination
2895 * and are printing a network source of the same type
2896 * next, separate them with "<-"; otherwise separate them
2899 * We add enough space to the buffer for " <- " or " -> ",
2900 * even if we're only adding " ".
2902 line_bufp = get_line_buf(buf_offset + 4);
2903 switch (cf->cinfo.col_fmt[i]) {
2908 switch (cf->cinfo.col_fmt[i + 1]) {
2913 strcat(line_bufp + buf_offset, " -> ");
2918 strcat(line_bufp + buf_offset, " ");
2924 case COL_DEF_DL_SRC:
2925 case COL_RES_DL_SRC:
2926 case COL_UNRES_DL_SRC:
2927 switch (cf->cinfo.col_fmt[i + 1]) {
2929 case COL_DEF_DL_DST:
2930 case COL_RES_DL_DST:
2931 case COL_UNRES_DL_DST:
2932 strcat(line_bufp + buf_offset, " -> ");
2937 strcat(line_bufp + buf_offset, " ");
2943 case COL_DEF_NET_SRC:
2944 case COL_RES_NET_SRC:
2945 case COL_UNRES_NET_SRC:
2946 switch (cf->cinfo.col_fmt[i + 1]) {
2948 case COL_DEF_NET_DST:
2949 case COL_RES_NET_DST:
2950 case COL_UNRES_NET_DST:
2951 strcat(line_bufp + buf_offset, " -> ");
2956 strcat(line_bufp + buf_offset, " ");
2965 switch (cf->cinfo.col_fmt[i + 1]) {
2970 strcat(line_bufp + buf_offset, " <- ");
2975 strcat(line_bufp + buf_offset, " ");
2981 case COL_DEF_DL_DST:
2982 case COL_RES_DL_DST:
2983 case COL_UNRES_DL_DST:
2984 switch (cf->cinfo.col_fmt[i + 1]) {
2986 case COL_DEF_DL_SRC:
2987 case COL_RES_DL_SRC:
2988 case COL_UNRES_DL_SRC:
2989 strcat(line_bufp + buf_offset, " <- ");
2994 strcat(line_bufp + buf_offset, " ");
3000 case COL_DEF_NET_DST:
3001 case COL_RES_NET_DST:
3002 case COL_UNRES_NET_DST:
3003 switch (cf->cinfo.col_fmt[i + 1]) {
3005 case COL_DEF_NET_SRC:
3006 case COL_RES_NET_SRC:
3007 case COL_UNRES_NET_SRC:
3008 strcat(line_bufp + buf_offset, " <- ");
3013 strcat(line_bufp + buf_offset, " ");
3020 strcat(line_bufp + buf_offset, " ");
3026 return print_line(print_stream, 0, line_bufp);
3030 print_packet(capture_file *cf, epan_dissect_t *edt)
3032 print_args_t print_args;
3035 /* Print the information in the protocol tree. */
3036 switch (output_action) {
3039 print_args.to_file = TRUE;
3040 print_args.format = print_format;
3041 print_args.print_summary = !verbose;
3042 print_args.print_hex = verbose && print_hex;
3043 print_args.print_formfeed = FALSE;
3044 print_args.print_dissections = verbose ? print_dissections_expanded : print_dissections_none;
3046 /* init the packet range */
3047 packet_range_init(&print_args.range);
3049 if (!proto_tree_print(&print_args, edt, print_stream))
3052 /* "print_hex_data()" will put out a leading blank line, as well
3053 as a trailing one; print one here, to separate the packets,
3054 only if "print_hex_data()" won't be called. */
3055 if (!print_line(print_stream, 0, ""))
3061 proto_tree_write_pdml(edt, stdout);
3063 return !ferror(stdout);
3065 proto_tree_write_fields(output_fields, edt, stdout);
3067 return !ferror(stdout);
3070 /* Just fill in the columns. */
3071 epan_dissect_fill_in_columns(edt, FALSE, TRUE);
3073 /* Now print them. */
3074 switch (output_action) {
3077 if (!print_columns(cf))
3082 proto_tree_write_psml(edt, stdout);
3083 return !ferror(stdout);
3084 case WRITE_FIELDS: /*No non-verbose "fields" format */
3085 g_assert_not_reached();
3090 if (!print_hex_data(print_stream, edt))
3092 if (!print_line(print_stream, 0, ""))
3101 switch (output_action) {
3104 return print_finale(print_stream);
3108 write_pdml_finale(stdout);
3110 write_psml_finale(stdout);
3111 return !ferror(stdout);
3114 write_fields_finale(output_fields, stdout);
3115 return !ferror(stdout);
3118 g_assert_not_reached();
3124 show_print_file_io_error(int err)
3129 cmdarg_err("Not all the packets could be printed because there is "
3130 "no space left on the file system.");
3135 cmdarg_err("Not all the packets could be printed because you are "
3136 "too close to, or over your disk quota.");
3141 cmdarg_err("An error occurred while printing packets: %s.",
3148 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
3152 static char errmsg_errno[1024+1];
3155 /* Wiretap error. */
3158 case WTAP_ERR_NOT_REGULAR_FILE:
3159 errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
3162 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
3163 /* Seen only when opening a capture file for reading. */
3164 errmsg = "The file \"%s\" isn't a capture file in a format TShark understands.";
3167 case WTAP_ERR_UNSUPPORTED:
3168 /* Seen only when opening a capture file for reading. */
3169 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3170 "The file \"%%s\" isn't a capture file in a format TShark understands.\n"
3173 errmsg = errmsg_errno;
3176 case WTAP_ERR_CANT_WRITE_TO_PIPE:
3177 /* Seen only when opening a capture file for writing. */
3178 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3179 "The file \"%%s\" is a pipe, and %s capture files can't be "
3180 "written to a pipe.", wtap_file_type_string(file_type));
3181 errmsg = errmsg_errno;
3184 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
3185 /* Seen only when opening a capture file for writing. */
3186 errmsg = "TShark doesn't support writing capture files in that format.";
3189 case WTAP_ERR_UNSUPPORTED_ENCAP:
3191 errmsg = "TShark can't save this capture in that format.";
3193 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3194 "The file \"%%s\" is a capture for a network type that TShark doesn't support.\n"
3197 errmsg = errmsg_errno;
3201 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
3203 errmsg = "TShark can't save this capture in that format.";
3205 errmsg = "The file \"%s\" is a capture for a network type that TShark doesn't support.";
3208 case WTAP_ERR_BAD_RECORD:
3209 /* Seen only when opening a capture file for reading. */
3210 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3211 "The file \"%%s\" appears to be damaged or corrupt.\n"
3214 errmsg = errmsg_errno;
3217 case WTAP_ERR_CANT_OPEN:
3219 errmsg = "The file \"%s\" could not be created for some unknown reason.";
3221 errmsg = "The file \"%s\" could not be opened for some unknown reason.";
3224 case WTAP_ERR_SHORT_READ:
3225 errmsg = "The file \"%s\" appears to have been cut short"
3226 " in the middle of a packet or other data.";
3229 case WTAP_ERR_SHORT_WRITE:
3230 errmsg = "A full header couldn't be written to the file \"%s\".";
3234 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3235 "The file \"%%s\" could not be %s: %s.",
3236 for_writing ? "created" : "opened",
3237 wtap_strerror(err));
3238 errmsg = errmsg_errno;
3242 errmsg = file_open_error_message(err, for_writing);
3247 * Open/create errors are reported with an console message in TShark.
3250 open_failure_message(const char *filename, int err, gboolean for_writing)
3252 fprintf(stderr, "tshark: ");
3253 fprintf(stderr, file_open_error_message(err, for_writing), filename);
3254 fprintf(stderr, "\n");
3258 cf_open(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
3262 char err_msg[2048+1];
3264 wth = wtap_open_offline(fname, err, &err_info, perform_two_pass_analysis);
3268 /* The open succeeded. Fill in the information for this file. */
3270 /* Cleanup all data structures used for dissection. */
3271 cleanup_dissection();
3272 /* Initialize all data structures used for dissection. */
3276 cf->f_datalen = 0; /* not used, but set it anyway */
3278 /* Set the file name because we need it to set the follow stream filter.
3279 XXX - is that still true? We need it for other reasons, though,
3281 cf->filename = g_strdup(fname);
3283 /* Indicate whether it's a permanent or temporary file. */
3284 cf->is_tempfile = is_tempfile;
3286 /* If it's a temporary capture buffer file, mark it as not saved. */
3287 cf->user_saved = !is_tempfile;
3289 cf->cd_t = wtap_file_type(cf->wth);
3291 cf->drops_known = FALSE;
3293 cf->snap = wtap_snapshot_length(cf->wth);
3294 if (cf->snap == 0) {
3295 /* Snapshot length not known. */
3296 cf->has_snap = FALSE;
3297 cf->snap = WTAP_MAX_PACKET_SIZE;
3299 cf->has_snap = TRUE;
3300 nstime_set_zero(&cf->elapsed_time);
3301 nstime_set_unset(&first_ts);
3302 nstime_set_unset(&prev_dis_ts);
3303 nstime_set_unset(&prev_cap_ts);
3305 cf->state = FILE_READ_IN_PROGRESS;
3310 g_snprintf(err_msg, sizeof err_msg,
3311 cf_open_error_message(*err, err_info, FALSE, cf->cd_t), fname);
3312 cmdarg_err("%s", err_msg);
3318 * General errors are reported with an console message in TShark.
3321 failure_message(const char *msg_format, va_list ap)
3323 fprintf(stderr, "tshark: ");
3324 vfprintf(stderr, msg_format, ap);
3325 fprintf(stderr, "\n");
3329 * Read errors are reported with an console message in TShark.
3332 read_failure_message(const char *filename, int err)
3334 cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
3335 filename, strerror(err));
3339 * Write errors are reported with an console message in TShark.
3342 write_failure_message(const char *filename, int err)
3344 cmdarg_err("An error occurred while writing to the file \"%s\": %s.",
3345 filename, strerror(err));
3349 * Report an error in command-line arguments.
3352 cmdarg_err(const char *fmt, ...)
3357 failure_message(fmt, ap);
3362 * Report additional information for an error in command-line arguments.
3365 cmdarg_err_cont(const char *fmt, ...)
3370 vfprintf(stderr, fmt, ap);
3371 fprintf(stderr, "\n");