5 * Ethereal - Network traffic analyzer
6 * By Gerald Combs <gerald@ethereal.com>
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 <wiretap/file_util.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 "conditions.h"
84 #include "capture_stop_conditions.h"
85 #include "ringbuffer.h"
86 #include "capture_ui_utils.h"
87 #include <epan/epan_dissect.h>
89 #include <epan/stat_cmd_args.h>
90 #include <epan/timestamp.h>
95 #include "capture-pcap-util.h"
96 #include <wiretap/wtap-capture.h>
98 #include "capture-wpcap.h"
99 #include "capture_errs.h"
102 #include "capture_loop.h"
103 #endif /* HAVE_LIBPCAP */
104 #include "epan/emem.h"
108 * This is the template for the decode as option; it is shared between the
109 * various functions that output the usage for this parameter.
111 static const gchar decode_as_arg_template[] = "<layer_type>==<selector>,<decode_as_protocol>";
113 static nstime_t first_ts;
114 static nstime_t prev_ts;
115 static GString *comp_info_str, *runtime_info_str;
117 static gboolean print_packet_info; /* TRUE if we're to print packet information */
119 * The way the packet decode is to be written.
122 WRITE_TEXT, /* summary or detail text */
123 WRITE_XML /* PDML or PSML */
124 /* Add CSV and the like here */
126 static output_action_e output_action;
127 static gboolean do_dissection; /* TRUE if we have to dissect each packet */
128 static gboolean verbose;
129 static gboolean print_hex;
130 static gboolean line_buffered;
131 static guint32 cum_bytes = 0;
132 static print_format_e print_format = PR_FMT_TEXT;
133 static print_stream_t *print_stream;
137 * TRUE if we're to print packet counts to keep track of captured packets.
139 static gboolean print_packet_counts;
145 static capture_options capture_opts;
149 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
150 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
152 #endif /* HAVE_LIBPCAP */
155 static int capture(char *, int);
156 static void capture_pcap_cb(u_char *, const struct pcap_pkthdr *,
158 static void report_counts(void);
160 static BOOL WINAPI capture_cleanup(DWORD);
162 static void capture_cleanup(int);
164 static void report_counts_siginfo(int);
167 #endif /* HAVE_LIBPCAP */
169 static int load_cap_file(capture_file *, char *, int);
170 static gboolean process_packet(capture_file *cf, wtap_dumper *pdh, long offset,
171 const struct wtap_pkthdr *whdr, union wtap_pseudo_header *pseudo_header,
172 const guchar *pd, int *err);
173 static void show_capture_file_io_error(const char *, int, gboolean);
174 static void show_print_file_io_error(int err);
175 static gboolean write_preamble(capture_file *cf);
176 static gboolean print_packet(capture_file *cf, epan_dissect_t *edt);
177 static gboolean write_finale(void);
178 static const char *cf_open_error_message(int err, gchar *err_info,
179 gboolean for_writing, int file_type);
181 static void open_failure_message(const char *filename, int err,
182 gboolean for_writing);
183 static void failure_message(const char *msg_format, va_list ap);
184 static void read_failure_message(const char *filename, int err);
190 print_usage(gboolean print_ver)
197 fprintf(output, "This is t" PACKAGE " " VERSION "%s\n"
205 svnversion, get_copyright_info(), comp_info_str->str,
206 runtime_info_str->str);
211 fprintf(output, "\nt%s [ -vh ] [ -DlLnpqSVx ] [ -a <capture autostop condition> ] ...\n",
213 fprintf(output, "\t[ -b <capture ring buffer option> ] ...\n");
215 fprintf(output, "\t[ -B <capture buffer size> ]\n");
217 fprintf(output, "\t[ -c <capture packet count> ]\n");
218 fprintf(output, "\t[ -d %s ] ...\n", decode_as_arg_template);
219 fprintf(output, "\t[ -f <capture filter> ] [ -F <output file type> ]\n");
220 fprintf(output, "\t[ -i <capture interface> ] [ -N <name resolving flags> ]\n");
221 fprintf(output, "\t[ -o <preference setting> ] ... [ -r <infile> ]\n");
222 fprintf(output, "\t[ -R <read (display) filter> ] [ -s <capture snaplen> ]\n");
223 fprintf(output, "\t[ -t <time stamp format> ] [ -T pdml|ps|psml|text ]\n");
224 fprintf(output, "\t[ -w <savefile> ] [ -y <capture link type> ] [ -z <statistics> ]\n");
226 fprintf(output, "\nt%s [ -vh ] [ -lnVx ]\n", PACKAGE);
227 fprintf(output, "\t[ -d %s ] ...\n", decode_as_arg_template);
228 fprintf(output, "\t[ -F <output file type> ] [ -N <name resolving flags> ]\n");
229 fprintf(output, "\t[ -o <preference setting> ] ... [ -r <infile> ]\n");
230 fprintf(output, "\t[ -R <read (display) filter> ] \t[ -t <time stamp format> ]\n");
231 fprintf(output, "\t[ -T pdml|ps|psml|text ] [ -w <savefile> ] [ -z <statistics ]\n");
233 fprintf(output, "Valid file type arguments to the \"-F\" flag:\n");
234 for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
235 if (wtap_dump_can_open(i))
236 fprintf(output, "\t%s - %s\n",
237 wtap_file_type_short_string(i), wtap_file_type_string(i));
239 fprintf(output, "\tdefault is libpcap\n");
243 * For a dissector table, print on the stream described by output,
244 * its short name (which is what's used in the "-d" option) and its
248 display_dissector_table_names(char *table_name, const char *ui_name,
251 fprintf((FILE *)output, "\t%s (%s)\n", table_name, ui_name);
255 * For a dissector handle, print on the stream described by output,
256 * the filter name (which is what's used in the "-d" option) and the full
257 * name for the protocol that corresponds to this handle.
260 display_dissector_names(const gchar *table _U_, gpointer handle, gpointer output)
263 const gchar* proto_filter_name;
264 const gchar* proto_ui_name;
266 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
268 if (proto_id != -1) {
269 proto_filter_name = proto_get_protocol_filter_name(proto_id);
270 proto_ui_name = proto_get_protocol_name(proto_id);
271 g_assert(proto_filter_name != NULL);
272 g_assert(proto_ui_name != NULL);
274 fprintf((FILE *)output, "\t%s (%s)\n",
281 * The protocol_name_search structure is used by find_protocol_name_func()
282 * to pass parameters and store results
284 struct protocol_name_search{
285 gchar *searched_name; /* Protocol filter name we are looking for */
286 dissector_handle_t matched_handle; /* Handle for a dissector whose protocol has the specified filter name */
287 guint nb_match; /* How many dissectors matched searched_name */
289 typedef struct protocol_name_search *protocol_name_search_t;
292 * This function parses all dissectors associated with a table to find the
293 * one whose protocol has the specified filter name. It is called
294 * as a reference function in a call to dissector_table_foreach_handle.
295 * The name we are looking for, as well as the results, are stored in the
296 * protocol_name_search struct pointed to by user_data.
297 * If called using dissector_table_foreach_handle, we actually parse the
298 * whole list of dissectors.
301 find_protocol_name_func(const gchar *table _U_, gpointer handle, gpointer user_data)
305 const gchar *protocol_filter_name;
306 protocol_name_search_t search_info;
310 search_info = (protocol_name_search_t)user_data;
312 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
313 if (proto_id != -1) {
314 protocol_filter_name = proto_get_protocol_filter_name(proto_id);
315 g_assert(protocol_filter_name != NULL);
316 if (strcmp(protocol_filter_name, search_info->searched_name) == 0) {
318 if (search_info->nb_match == 0) {
319 /* Record this handle only if this is the first match */
320 search_info->matched_handle = (dissector_handle_t)handle; /* Record the handle for this matching dissector */
322 search_info->nb_match++;
328 * Print all layer type names supported.
329 * We send the output to the stream described by the handle output.
333 fprint_all_layer_types(FILE *output)
336 dissector_all_tables_foreach_table(display_dissector_table_names, (gpointer)output);
340 * Print all protocol names supported for a specific layer type.
341 * table_name contains the layer type name in which the search is performed.
342 * We send the output to the stream described by the handle output.
346 fprint_all_protocols_for_layer_types(FILE *output, gchar *table_name)
349 dissector_table_foreach_handle(table_name,
350 display_dissector_names,
355 * The function below parses the command-line parameters for the decode as
356 * feature (a string pointer by cl_param).
357 * It checks the format of the command-line, searches for a matching table
358 * and dissector. If a table/dissector match is not found, we display a
359 * summary of the available tables/dissectors (on stderr) and return FALSE.
360 * If everything is fine, we get the "Decode as" preference activated,
361 * then we return TRUE.
364 add_decode_as(const gchar *cl_param)
368 gchar *decoded_param;
369 gchar *remaining_param;
371 gchar *dissector_str;
372 dissector_handle_t dissector_matching;
373 dissector_table_t table_matching;
374 ftenum_t dissector_table_selector_type;
375 struct protocol_name_search user_protocol_name;
377 /* The following code will allocate and copy the command-line options in a string pointed by decoded_param */
380 decoded_param = g_malloc( sizeof(gchar) * (strlen(cl_param) + 1) ); /* Allocate enough space to have a working copy of the command-line parameter */
381 g_assert(decoded_param);
382 strcpy(decoded_param, cl_param);
385 /* The lines below will parse this string (modifying it) to extract all
386 necessary information. Note that decoded_param is still needed since
387 strings are not copied - we just save pointers. */
389 /* This section extracts a layer type (table_name) from decoded_param */
390 table_name = decoded_param; /* Layer type string starts from beginning */
392 remaining_param = strchr(table_name, '=');
393 if (remaining_param == NULL) {
394 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
395 /* If the argument does not follow the template, carry on anyway to check
396 if the table name is at least correct. If remaining_param is NULL,
397 we'll exit anyway further down */
400 *remaining_param = '\0'; /* Terminate the layer type string (table_name) where '=' was detected */
403 /* Remove leading and trailing spaces from the table name */
404 while ( table_name[0] == ' ' )
406 while ( table_name[strlen(table_name) - 1] == ' ' )
407 table_name[strlen(table_name) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
409 /* The following part searches a table matching with the layer type specified */
410 table_matching = NULL;
412 /* Look for the requested table */
413 if ( !(*(table_name)) ) { /* Is the table name empty, if so, don't even search for anything, display a message */
414 cmdarg_err("No layer type specified"); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
417 table_matching = find_dissector_table(table_name);
418 if (!table_matching) {
419 cmdarg_err("Unknown layer type -- %s", table_name); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
423 if (!table_matching) {
424 /* Display a list of supported layer types to help the user, if the
425 specified layer type was not found */
426 cmdarg_err("Valid layer types are:");
427 fprint_all_layer_types(stderr);
429 if (remaining_param == NULL || !table_matching) {
430 /* Exit if the layer type was not found, or if no '=' separator was found
432 g_free(decoded_param);
436 if (*(remaining_param + 1) != '=') { /* Check for "==" and not only '=' */
437 cmdarg_err("WARNING: -d requires \"==\" instead of \"=\". Option will be treated as \"%s==%s\"", table_name, remaining_param + 1);
440 remaining_param++; /* Move to the second '=' */
441 *remaining_param = '\0'; /* Remove the second '=' */
443 remaining_param++; /* Position after the layer type string */
445 /* This section extracts a selector value (selector_str) from decoded_param */
447 selector_str = remaining_param; /* Next part starts with the selector number */
449 remaining_param = strchr(selector_str, ',');
450 if (remaining_param == NULL) {
451 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
452 /* If the argument does not follow the template, carry on anyway to check
453 if the selector value is at least correct. If remaining_param is NULL,
454 we'll exit anyway further down */
457 *remaining_param = '\0'; /* Terminate the selector number string (selector_str) where ',' was detected */
460 dissector_table_selector_type = get_dissector_table_selector_type(table_name);
462 switch (dissector_table_selector_type) {
468 /* The selector for this table is an unsigned number. Parse it as such.
469 There's no need to remove leading and trailing spaces from the
470 selector number string, because sscanf will do that for us. */
471 if ( sscanf(selector_str, "%u", &selector) != 1 ) {
472 cmdarg_err("Invalid selector number \"%s\"", selector_str);
473 g_free(decoded_param);
480 /* The selector for this table is a string. */
484 /* There are currently no dissector tables with any types other
485 than the ones listed above. */
486 g_assert_not_reached();
489 if (remaining_param == NULL) {
490 /* Exit if no ',' separator was found (see above) */
491 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
492 fprint_all_protocols_for_layer_types(stderr, table_name);
493 g_free(decoded_param);
497 remaining_param++; /* Position after the selector number string */
499 /* This section extracts a protocol filter name (dissector_str) from decoded_param */
501 dissector_str = remaining_param; /* All the rest of the string is the dissector (decode as protocol) name */
503 /* Remove leading and trailing spaces from the dissector name */
504 while ( dissector_str[0] == ' ' )
506 while ( dissector_str[strlen(dissector_str) - 1] == ' ' )
507 dissector_str[strlen(dissector_str) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
509 dissector_matching = NULL;
511 /* We now have a pointer to the handle for the requested table inside the variable table_matching */
512 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 */
513 cmdarg_err("No protocol name specified"); /* Note, we don't exit here, but dissector_matching will remain NULL, so we exit below */
516 user_protocol_name.nb_match = 0;
517 user_protocol_name.searched_name = dissector_str;
518 user_protocol_name.matched_handle = NULL;
520 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 */
522 if (user_protocol_name.nb_match != 0) {
523 dissector_matching = user_protocol_name.matched_handle;
524 if (user_protocol_name.nb_match > 1) {
525 cmdarg_err("WARNING: Protocol \"%s\" matched %u dissectors, first one will be used", dissector_str, user_protocol_name.nb_match);
529 /* OK, check whether the problem is that there isn't any such
530 protocol, or that there is but it's not specified as a protocol
531 that's valid for that dissector table.
532 Note, we don't exit here, but dissector_matching will remain NULL,
534 if (proto_get_id_by_filter_name(dissector_str) == -1) {
535 /* No such protocol */
536 cmdarg_err("Unknown protocol -- \"%s\"", dissector_str);
538 cmdarg_err("Protocol \"%s\" isn't valid for layer type \"%s\"",
539 dissector_str, table_name);
544 if (!dissector_matching) {
545 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
546 fprint_all_protocols_for_layer_types(stderr, table_name);
547 g_free(decoded_param);
551 /* This is the end of the code that parses the command-line options.
552 All information is now stored in the variables:
556 The above variables that are strings are still pointing to areas within
557 decoded_parm. decoded_parm thus still needs to be kept allocated in
558 until we stop needing these variables
559 decoded_param will be deallocated at each exit point of this function */
562 /* We now have a pointer to the handle for the requested dissector
563 (requested protocol) inside the variable dissector_matching */
564 switch (dissector_table_selector_type) {
570 /* The selector for this table is an unsigned number. */
571 dissector_change(table_name, selector, dissector_matching);
576 /* The selector for this table is a string. */
577 dissector_change_string(table_name, selector_str, dissector_matching);
581 /* There are currently no dissector tables with any types other
582 than the ones listed above. */
583 g_assert_not_reached();
585 g_free(decoded_param); /* "Decode As" rule has been succesfully added */
590 log_func_ignore (const gchar *log_domain _U_, GLogLevelFlags log_level _U_,
591 const gchar *message _U_, gpointer user_data _U_)
596 main(int argc, char *argv[])
600 gboolean arg_error = FALSE;
606 char *gpf_path, *pf_path;
607 char *gdp_path, *dp_path;
608 int gpf_open_errno, gpf_read_errno;
609 int pf_open_errno, pf_read_errno;
610 int gdp_open_errno, gdp_read_errno;
611 int dp_open_errno, dp_read_errno;
614 gboolean capture_filter_specified = FALSE;
615 gboolean list_link_layer_types = FALSE;
616 gboolean start_capture = FALSE;
618 gboolean capture_option_specified = FALSE;
620 gboolean quiet = FALSE;
621 gchar *save_file = NULL;
622 int out_file_type = WTAP_FILE_PCAP;
623 gchar *cf_name = NULL, *rfilter = NULL;
624 #ifdef HAVE_PCAP_OPEN_DEAD
625 struct bpf_program fcode;
627 dfilter_t *rfcode = NULL;
630 GLogLevelFlags log_flags;
632 #define OPTSTRING_INIT "a:b:c:d:Df:F:hi:lLnN:o:pqr:R:s:St:T:vVw:xy:z:"
635 #define OPTSTRING_WIN32 "B:"
637 #define OPTSTRING_WIN32 ""
640 #define OPTSTRING_WIN32 ""
641 #endif /* HAVE_LIBPCAP */
643 static const char optstring[] = OPTSTRING_INIT OPTSTRING_WIN32;
645 /* nothing more than the standard GLib handler, but without a warning */
648 G_LOG_LEVEL_CRITICAL|
653 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
655 g_log_set_handler(NULL,
657 log_func_ignore, NULL /* user_data */);
658 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
660 log_func_ignore, NULL /* user_data */);
662 /* initialize memory allocation subsystem */
667 capture_opts_init(&capture_opts, NULL /* cfile */);
670 timestamp_set_type(TS_RELATIVE);
671 timestamp_set_precision(TS_PREC_AUTO);
673 /* Register all dissectors; we must do this before checking for the
674 "-G" flag, as the "-G" flag dumps information registered by the
675 dissectors, and we must do it before we read the preferences, in
676 case any dissectors register preferences. */
677 epan_init(PLUGIN_DIR,register_all_protocols,register_all_protocol_handoffs,
678 failure_message,open_failure_message,read_failure_message);
680 /* Register all tap listeners; we do this before we parse the arguments,
681 as the "-z" argument can specify a registered tap. */
683 /* we register the plugin taps before the other taps because
684 stats_tree taps plugins will be registered as tap listeners
685 by stats_tree_stat.c and need to registered before that */
687 register_all_plugin_tap_listeners();
689 register_all_tap_listeners();
691 /* Now register the preferences for any non-dissector modules.
692 We must do that before we read the preferences as well. */
693 prefs_register_modules();
695 /* If invoked with the "-G" flag, we dump out information based on
696 the argument to the "-G" flag; if no argument is specified,
697 for backwards compatibility we dump out a glossary of display
700 XXX - we do this here, for now, to support "-G" with no arguments.
701 If none of our build or other processes uses "-G" with no arguments,
702 we can just process it with the other arguments. */
703 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
705 proto_registrar_dump_fields(1);
707 if (strcmp(argv[2], "fields") == 0)
708 proto_registrar_dump_fields(1);
709 else if (strcmp(argv[2], "fields2") == 0)
710 proto_registrar_dump_fields(2);
711 else if (strcmp(argv[2], "fields3") == 0)
712 proto_registrar_dump_fields(3);
713 else if (strcmp(argv[2], "protocols") == 0)
714 proto_registrar_dump_protocols();
715 else if (strcmp(argv[2], "values") == 0)
716 proto_registrar_dump_values();
717 else if (strcmp(argv[2], "decodes") == 0)
718 dissector_dump_decodes();
719 else if (strcmp(argv[2], "defaultprefs") == 0)
721 else if (strcmp(argv[2], "currentprefs") == 0) {
722 read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
723 &pf_open_errno, &pf_read_errno, &pf_path);
726 cmdarg_err("Invalid \"%s\" option for -G flag", argv[2]);
733 /* Set the C-language locale to the native environment. */
734 setlocale(LC_ALL, "");
736 prefs = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
737 &pf_open_errno, &pf_read_errno, &pf_path);
738 if (gpf_path != NULL) {
739 if (gpf_open_errno != 0) {
740 cmdarg_err("Can't open global preferences file \"%s\": %s.",
741 pf_path, strerror(gpf_open_errno));
743 if (gpf_read_errno != 0) {
744 cmdarg_err("I/O error reading global preferences file \"%s\": %s.",
745 pf_path, strerror(gpf_read_errno));
748 if (pf_path != NULL) {
749 if (pf_open_errno != 0) {
750 cmdarg_err("Can't open your preferences file \"%s\": %s.", pf_path,
751 strerror(pf_open_errno));
753 if (pf_read_errno != 0) {
754 cmdarg_err("I/O error reading your preferences file \"%s\": %s.",
755 pf_path, strerror(pf_read_errno));
761 /* Set the name resolution code's flags from the preferences. */
762 g_resolv_flags = prefs->name_resolve;
764 /* Read the disabled protocols file. */
765 read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
766 &dp_path, &dp_open_errno, &dp_read_errno);
767 if (gdp_path != NULL) {
768 if (gdp_open_errno != 0) {
770 "Could not open global disabled protocols file\n\"%s\": %s.",
771 gdp_path, strerror(gdp_open_errno));
773 if (gdp_read_errno != 0) {
775 "I/O error reading global disabled protocols file\n\"%s\": %s.",
776 gdp_path, strerror(gdp_read_errno));
780 if (dp_path != NULL) {
781 if (dp_open_errno != 0) {
783 "Could not open your disabled protocols file\n\"%s\": %s.", dp_path,
784 strerror(dp_open_errno));
786 if (dp_read_errno != 0) {
788 "I/O error reading your disabled protocols file\n\"%s\": %s.", dp_path,
789 strerror(dp_read_errno));
795 /* Load Wpcap, if possible */
799 init_cap_file(&cfile);
801 /* Assemble the compile-time version information string */
802 comp_info_str = g_string_new("Compiled ");
803 get_compiled_version_info(comp_info_str);
805 /* Assemble the run-time version information string */
806 runtime_info_str = g_string_new("Running ");
807 get_runtime_version_info(runtime_info_str);
809 /* Print format defaults to this. */
810 print_format = PR_FMT_TEXT;
812 /* Now get our args */
813 while ((opt = getopt(argc, argv, optstring)) != -1) {
815 case 'a': /* autostop criteria */
816 case 'b': /* Ringbuffer option */
817 case 'c': /* Capture xxx packets */
818 case 'f': /* capture filter */
819 case 'i': /* Use interface xxx */
820 case 'p': /* Don't capture in promiscuous mode */
821 case 's': /* Set the snapshot (capture) length */
822 case 'y': /* Set the pcap data link type */
824 case 'B': /* Buffer size */
827 capture_opts_add_opt(&capture_opts, opt, optarg, &start_capture);
829 capture_option_specified = TRUE;
833 case 'd': /* Decode as rule */
834 if (!add_decode_as(optarg))
837 case 'D': /* Print a list of capture devices and exit */
839 capture_opts_list_interfaces();
842 capture_option_specified = TRUE;
847 out_file_type = wtap_short_string_to_file_type(optarg);
848 if (out_file_type < 0) {
849 cmdarg_err("\"%s\" isn't a valid capture file type",
854 case 'h': /* Print help and exit */
858 case 'l': /* "Line-buffer" standard output */
859 /* This isn't line-buffering, strictly speaking, it's just
860 flushing the standard output after the information for
861 each packet is printed; however, that should be good
862 enough for all the purposes to which "-l" is put (and
863 is probably actually better for "-V", as it does fewer
866 See the comment in "process_packet()" for an explanation of
867 why we do that, and why we don't just use "setvbuf()" to
868 make the standard output line-buffered (short version: in
869 Windows, "line-buffered" is the same as "fully-buffered",
870 and the output buffer is only flushed when it fills up). */
871 line_buffered = TRUE;
873 case 'L': /* Print list of link-layer types and exit */
875 list_link_layer_types = TRUE;
878 capture_option_specified = TRUE;
882 case 'n': /* No name resolution */
883 g_resolv_flags = RESOLV_NONE;
885 case 'N': /* Select what types of addresses/port #s to resolve */
886 if (g_resolv_flags == RESOLV_ALL)
887 g_resolv_flags = RESOLV_NONE;
888 badopt = string_to_name_resolve(optarg, &g_resolv_flags);
889 if (badopt != '\0') {
890 cmdarg_err("-N specifies unknown resolving option '%c'; valid options are 'm', 'n', and 't'",
895 case 'o': /* Override preference from command line */
896 switch (prefs_set_pref(optarg)) {
898 case PREFS_SET_SYNTAX_ERR:
899 cmdarg_err("Invalid -o flag \"%s\"", optarg);
903 case PREFS_SET_NO_SUCH_PREF:
904 case PREFS_SET_OBSOLETE:
905 cmdarg_err("-o flag \"%s\" specifies unknown preference",
911 case 'q': /* Quiet */
914 case 'r': /* Read capture file xxx */
915 cf_name = g_strdup(optarg);
917 case 'R': /* Read file filter */
920 case 'S': /* show packets in real time */
921 print_packet_info = TRUE;
923 case 't': /* Time stamp type */
924 if (strcmp(optarg, "r") == 0)
925 timestamp_set_type(TS_RELATIVE);
926 else if (strcmp(optarg, "a") == 0)
927 timestamp_set_type(TS_ABSOLUTE);
928 else if (strcmp(optarg, "ad") == 0)
929 timestamp_set_type(TS_ABSOLUTE_WITH_DATE);
930 else if (strcmp(optarg, "d") == 0)
931 timestamp_set_type(TS_DELTA);
933 cmdarg_err("Invalid time stamp type \"%s\"",
935 cmdarg_err_cont("It must be \"r\" for relative, \"a\" for absolute,");
936 cmdarg_err_cont("\"ad\" for absolute with date, or \"d\" for delta.");
940 case 'T': /* printing Type */
941 if (strcmp(optarg, "text") == 0) {
942 output_action = WRITE_TEXT;
943 print_format = PR_FMT_TEXT;
944 } else if (strcmp(optarg, "ps") == 0) {
945 output_action = WRITE_TEXT;
946 print_format = PR_FMT_PS;
947 } else if (strcmp(optarg, "pdml") == 0) {
948 output_action = WRITE_XML;
950 } else if (strcmp(optarg, "psml") == 0) {
951 output_action = WRITE_XML;
954 cmdarg_err("Invalid -T parameter.");
955 cmdarg_err_cont("It must be \"ps\", \"text\", \"pdml\", or \"psml\".");
959 case 'v': /* Show version and exit */
960 printf("t" PACKAGE " " VERSION "%s\n"
967 svnversion, get_copyright_info(), comp_info_str->str,
968 runtime_info_str->str);
971 case 'w': /* Write to capture file xxx */
972 save_file = g_strdup(optarg);
974 case 'V': /* Verbose */
977 case 'x': /* Print packet data in hex (and ASCII) */
981 /* We won't call the init function for the stat this soon
982 as it would disallow MATE's fields (which are registered
983 by the preferences set callback) from being used as
984 part of a tap filter. Instead, we just add the argument
985 to a list of stat arguments. */
986 if (!process_stat_cmd_arg(optarg)) {
987 cmdarg_err("invalid -z argument.");
988 cmdarg_err_cont(" -z argument must be one of :");
989 list_stat_cmd_args();
994 case '?': /* Bad flag - print usage message */
1000 /* If no capture filter or read filter has been specified, and there are
1001 still command-line arguments, treat them as the tokens of a capture
1002 filter (if no "-r" flag was specified) or a read filter (if a "-r"
1003 flag was specified. */
1004 if (optind < argc) {
1005 if (cf_name != NULL) {
1006 if (rfilter != NULL) {
1007 cmdarg_err("Read filters were specified both with \"-R\" "
1008 "and with additional command-line arguments");
1011 rfilter = get_args_as_string(argc, argv, optind);
1014 if (capture_filter_specified) {
1015 cmdarg_err("Capture filters were specified both with \"-f\""
1016 " and with additional command-line arguments");
1019 capture_opts.cfilter = get_args_as_string(argc, argv, optind);
1021 capture_option_specified = TRUE;
1026 /* See if we're writing a capture file and the file is a pipe */
1028 ld.output_to_pipe = FALSE;
1030 if (save_file != NULL) {
1031 /* We're writing to a capture file. */
1032 if (strcmp(save_file, "-") == 0) {
1033 /* Write to the standard output. */
1035 save_file = g_strdup("");
1037 /* XXX - should we check whether it's a pipe? It's arguably
1038 silly to do "-w - >output_file" rather than "-w output_file",
1039 but by not checking we might be violating the Principle Of
1040 Least Astonishment. */
1041 ld.output_to_pipe = TRUE;
1046 err = test_for_fifo(save_file);
1049 case ENOENT: /* it doesn't exist, so we'll be creating it,
1050 and it won't be a FIFO */
1051 case 0: /* found it, but it's not a FIFO */
1054 case ESPIPE: /* it is a FIFO */
1055 ld.output_to_pipe = TRUE;
1058 default: /* couldn't stat it */
1059 cmdarg_err("Error testing whether capture file is a pipe: %s",
1066 /* We're not writing to a file, so we should print packet information
1067 unless "-q" was specified. */
1069 print_packet_info = TRUE;
1072 #ifndef HAVE_LIBPCAP
1073 if (capture_option_specified)
1074 cmdarg_err("This version of Tethereal was not built with support for capturing packets.");
1081 /* We don't support capture filters when reading from a capture file
1082 (the BPF compiler doesn't support all link-layer types that we
1083 support in capture files we read). */
1085 if (cf_name != NULL) {
1086 if (capture_filter_specified) {
1087 cmdarg_err("Only read filters, not capture filters, "
1088 "can be specified when reading a capture file.");
1095 if (output_action != WRITE_TEXT) {
1096 cmdarg_err("Raw packet hex data can only be printed as text or PostScript");
1102 if (list_link_layer_types) {
1103 /* We're supposed to list the link-layer types for an interface;
1104 did the user also specify a capture file to be read? */
1106 /* Yes - that's bogus. */
1107 cmdarg_err("You can't specify -L and a capture file to be read.");
1110 /* No - did they specify a ring buffer option? */
1111 if (capture_opts.multi_files_on) {
1112 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
1116 /* If they didn't specify a "-w" flag, but specified a maximum capture
1117 file size, tell them that this doesn't work, and exit. */
1118 if (capture_opts.has_autostop_filesize && save_file == NULL) {
1119 cmdarg_err("Maximum capture file size specified, but "
1120 "capture isn't being saved to a file.");
1124 if (capture_opts.multi_files_on) {
1125 /* Ring buffer works only under certain conditions:
1126 a) ring buffer does not work if you're not saving the capture to
1128 b) ring buffer only works if you're saving in libpcap format;
1129 c) it makes no sense to enable the ring buffer if the maximum
1130 file size is set to "infinite";
1131 d) file must not be a pipe. */
1132 if (save_file == NULL) {
1133 cmdarg_err("Ring buffer requested, but capture isn't being saved to a file.");
1136 if (out_file_type != WTAP_FILE_PCAP) {
1137 cmdarg_err("Ring buffer requested, but "
1138 "capture isn't being saved in libpcap format.");
1141 if (!capture_opts.has_autostop_filesize) {
1142 cmdarg_err("Ring buffer requested, but "
1143 "no maximum capture file size was specified.");
1146 if (ld.output_to_pipe) {
1147 cmdarg_err("Ring buffer requested, but capture file is a pipe.");
1155 /* Start windows sockets */
1156 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1159 /* Notify all registered modules that have had any of their preferences
1160 changed either from one of the preferences file or from the command
1161 line that their preferences have changed. */
1164 /* At this point MATE will have registered its field array so we can
1165 have a tap filter with one of MATE's late-registered fields as part
1166 of the filter. We can now process all the "-z" arguments. */
1167 start_requested_stats();
1169 /* disabled protocols as per configuration file */
1170 if (gdp_path == NULL && dp_path == NULL) {
1171 set_disabled_protos_list();
1174 /* Build the column format array */
1175 col_setup(&cfile.cinfo, prefs->num_cols);
1176 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1177 cfile.cinfo.col_fmt[i] = get_column_format(i);
1178 cfile.cinfo.col_title[i] = g_strdup(get_column_title(i));
1179 cfile.cinfo.fmt_matx[i] = (gboolean *) g_malloc0(sizeof(gboolean) *
1181 get_column_format_matches(cfile.cinfo.fmt_matx[i], cfile.cinfo.col_fmt[i]);
1182 cfile.cinfo.col_data[i] = NULL;
1183 if (cfile.cinfo.col_fmt[i] == COL_INFO)
1184 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_INFO_LEN);
1186 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1187 cfile.cinfo.col_fence[i] = 0;
1188 cfile.cinfo.col_expr[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1189 cfile.cinfo.col_expr_val[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1192 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1195 for (j = 0; j < NUM_COL_FMTS; j++) {
1196 if (!cfile.cinfo.fmt_matx[i][j])
1199 if (cfile.cinfo.col_first[j] == -1)
1200 cfile.cinfo.col_first[j] = i;
1201 cfile.cinfo.col_last[j] = i;
1206 capture_opts_trim_snaplen(&capture_opts, MIN_PACKET_SIZE);
1207 capture_opts_trim_ring_num_files(&capture_opts);
1210 if (rfilter != NULL) {
1211 if (!dfilter_compile(rfilter, &rfcode)) {
1212 cmdarg_err("%s", dfilter_error_msg);
1214 #ifdef HAVE_PCAP_OPEN_DEAD
1218 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1220 if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1222 " Note: That display filter code looks like a valid capture filter;");
1224 " maybe you mixed them up?");
1233 cfile.rfcode = rfcode;
1235 if (print_packet_info) {
1236 /* If we're printing as text or PostScript, we have
1237 to create a print stream. */
1238 if (output_action == WRITE_TEXT) {
1239 switch (print_format) {
1242 print_stream = print_stream_text_stdio_new(stdout);
1246 print_stream = print_stream_ps_stdio_new(stdout);
1250 g_assert_not_reached();
1255 /* We have to dissect each packet if:
1257 we're printing information about each packet;
1259 we're using a read filter on the packets;
1261 we're using any taps. */
1262 do_dissection = print_packet_info || rfcode || have_tap_listeners();
1266 * We're reading a capture file.
1271 * Immediately relinquish any set-UID or set-GID privileges we have;
1272 * we must not be allowed to read any capture files the user running
1273 * Tethereal can't open.
1279 if (cf_open(&cfile, cf_name, FALSE, &err) != CF_OK) {
1284 /* Set timestamp precision; there should arguably be a command-line
1285 option to let the user set this. */
1286 switch(wtap_file_tsprecision(cfile.wth)) {
1287 case(WTAP_FILE_TSPREC_SEC):
1288 timestamp_set_precision(TS_PREC_AUTO_SEC);
1290 case(WTAP_FILE_TSPREC_DSEC):
1291 timestamp_set_precision(TS_PREC_AUTO_DSEC);
1293 case(WTAP_FILE_TSPREC_CSEC):
1294 timestamp_set_precision(TS_PREC_AUTO_CSEC);
1296 case(WTAP_FILE_TSPREC_MSEC):
1297 timestamp_set_precision(TS_PREC_AUTO_MSEC);
1299 case(WTAP_FILE_TSPREC_USEC):
1300 timestamp_set_precision(TS_PREC_AUTO_USEC);
1302 case(WTAP_FILE_TSPREC_NSEC):
1303 timestamp_set_precision(TS_PREC_AUTO_NSEC);
1306 g_assert_not_reached();
1309 /* Process the packets in the file */
1310 err = load_cap_file(&cfile, save_file, out_file_type);
1317 /* No capture file specified, so we're supposed to do a live capture
1318 (or get a list of link-layer types for a live capture device);
1319 do we have support for live captures? */
1326 cmdarg_err("WinPcap couldn't be found.");
1327 detailed_err = cant_load_winpcap_err("Tethereal");
1328 cmdarg_err_cont("%s", detailed_err);
1329 g_free(detailed_err);
1334 /* trim the interface name and exit if that failed */
1335 if (!capture_opts_trim_iface(&capture_opts,
1336 (prefs->capture_device) ? get_if_name(prefs->capture_device) : NULL)) {
1340 /* if requested, list the link layer types and exit */
1341 if (list_link_layer_types) {
1342 capture_opts_list_link_layer_types(&capture_opts);
1348 * The user didn't ask us not to print a count of packets as
1349 * they arrive, so do so.
1351 print_packet_counts = TRUE;
1354 /* For now, assume libpcap gives microsecond precision. */
1355 timestamp_set_precision(TS_PREC_AUTO_USEC);
1357 capture(save_file, out_file_type);
1359 if (capture_opts.multi_files_on) {
1363 /* No - complain. */
1364 cmdarg_err("This version of Tethereal was not built with support for capturing packets.");
1369 draw_tap_listeners(TRUE);
1376 /* Do the low-level work of a capture.
1377 Returns TRUE if it succeeds, FALSE otherwise. */
1379 static condition *volatile cnd_file_duration = NULL; /* this must be visible in process_packet */
1382 capture(char *save_file, int out_file_type)
1385 int volatile volatile_err = 0;
1386 int volatile inpkts = 0;
1388 char errmsg[1024+1];
1389 condition *volatile cnd_autostop_size = NULL;
1390 condition *volatile cnd_autostop_duration = NULL;
1393 void (*oldhandler)(int);
1394 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
1396 struct pcap_stat stats;
1401 /* Initialize all data structures used for dissection. */
1404 ld.wtap_linktype = WTAP_ENCAP_UNKNOWN;
1406 ld.packet_cb = capture_pcap_cb;
1409 /* open the "input file" from network interface or capture pipe */
1410 if (!capture_loop_open_input(&capture_opts, &ld, errmsg, sizeof(errmsg)))
1417 * We've opened the capture device, so, if we're set-UID or set-GID,
1418 * relinquish those privileges.
1420 * XXX - if we have saved set-user-ID support, we should give up those
1421 * privileges immediately, and then reclaim them long enough to get
1422 * a list of network interfaces and to open one, and then give them
1423 * up again, so that stuff we do while processing the argument list,
1424 * reading the user's preferences, etc. is done as the real user and
1425 * group, not the effective user and group.
1431 capture_opts.save_file = save_file;
1433 /* open the output file (temporary/specified name/ringbuffer) */
1434 if (!capture_loop_open_output(&capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
1438 /* init the input filter from the network interface (capture pipe will do nothing) */
1439 if(!capture_loop_init_filter(ld.pcap_h, ld.from_cap_pipe,
1440 capture_opts.iface, capture_opts.cfilter, errmsg, sizeof errmsg))
1445 /* open the wiretap part of the output file (the output file is already open) */
1446 if(!capture_loop_init_wiretap_output(&capture_opts, save_file_fd, &ld, errmsg, sizeof errmsg))
1453 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1454 SetConsoleCtrlHandler(capture_cleanup, TRUE);
1456 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
1458 XXX - deal with signal semantics on various UNIX platforms. Or just
1459 use "sigaction()" and be done with it? */
1460 signal(SIGTERM, capture_cleanup);
1461 signal(SIGINT, capture_cleanup);
1462 if ((oldhandler = signal(SIGHUP, capture_cleanup)) != SIG_DFL)
1463 signal(SIGHUP, oldhandler);
1466 /* Catch SIGINFO and, if we get it and we're capturing to a file in
1467 quiet mode, report the number of packets we've captured. */
1468 signal(SIGINFO, report_counts_siginfo);
1469 #endif /* SIGINFO */
1472 /* Let the user know what interface was chosen. */
1473 descr = get_interface_descriptive_name(capture_opts.iface);
1474 fprintf(stderr, "Capturing on %s\n", descr);
1477 /* initialize capture stop conditions */
1478 init_capture_stop_conditions();
1479 /* create stop conditions */
1480 if (capture_opts.has_autostop_filesize)
1481 cnd_autostop_size = cnd_new((const char*)CND_CLASS_CAPTURESIZE,
1482 (long)capture_opts.autostop_filesize * 1024);
1483 if (capture_opts.has_autostop_duration)
1484 cnd_autostop_duration = cnd_new((const char*)CND_CLASS_TIMEOUT,
1485 (gint32)capture_opts.autostop_duration);
1487 if (capture_opts.multi_files_on && capture_opts.has_file_duration)
1488 cnd_file_duration = cnd_new(CND_CLASS_TIMEOUT,
1489 capture_opts.file_duration);
1491 if (!setjmp(ld.stopenv)) {
1493 ld.packet_count = 0;
1498 /* We need to be careful with automatic variables defined in the
1499 outer scope which are changed inside the loop. Most compilers
1500 don't try to roll them back to their original values after the
1501 longjmp which causes the loop to finish, but all that the
1502 standards say is that their values are indeterminate. If we
1503 don't want them to be rolled back, we should define them with the
1504 volatile attribute (paraphrasing W. Richard Stevens, Advanced
1505 Programming in the UNIX Environment, p. 178).
1507 The "err" variable causes a particular problem. If we give it
1508 the volatile attribute, then when we pass a reference to it (as
1509 in "&err") to a function, GCC warns: "passing arg <n> of
1510 <function> discards qualifiers from pointer target type".
1511 Therefore within the loop and just beyond we don't use "err".
1512 Within the loop we define "loop_err", and assign its value to
1513 "volatile_err", which is in the outer scope and is checked when
1516 We also define "packet_count_prev" here to keep things tidy,
1517 since it's used only inside the loop. If it were defined in the
1518 outer scope, GCC would give a warning (unnecessary in this case)
1519 that it might be clobbered, and we'd need to give it the volatile
1520 attribute to suppress the warning. */
1523 int packet_count_prev = 0;
1525 if (cnd_autostop_size == NULL && cnd_autostop_duration == NULL) {
1526 /* We're not stopping at a particular capture file size, and we're
1527 not stopping after some particular amount of time has expired,
1528 so either we have no stop condition or the only stop condition
1529 is a maximum packet count.
1531 If there's no maximum packet count, pass it -1, meaning "until
1532 you run out of packets in the bufferful you read". Otherwise,
1533 pass it the number of packets we have left to capture.
1535 We don't call "pcap_loop()" as, if we're saving to a file that's
1536 a FIFO, we want to flush the FIFO after we're done processing
1537 this libpcap bufferful of packets, so that the program
1538 reading the FIFO sees the packets immediately and doesn't get
1539 any partial packet, forcing it to block in the middle of reading
1541 if (capture_opts.autostop_packets == 0)
1544 if (ld.packet_count >= capture_opts.autostop_packets) {
1545 /* XXX do we need this test here? */
1546 /* It appears there's nothing more to capture. */
1549 pcap_cnt = capture_opts.autostop_packets - ld.packet_count;
1552 /* We need to check the capture file size or the timeout after
1557 if (ld.from_cap_pipe) {
1558 inpkts = cap_pipe_dispatch(ld.cap_pipe_fd, &ld, &ld.cap_pipe_hdr, &ld.cap_pipe_rechdr, pcap_data,
1559 errmsg, sizeof errmsg);
1562 inpkts = pcap_dispatch(ld.pcap_h, pcap_cnt, capture_pcap_cb, (u_char *) &ld);
1564 /* Error from "pcap_dispatch()", or error or "no more packets" from
1565 "cap_pipe_dispatch(). */
1567 } else if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
1568 /* The specified capture time has elapsed; stop the capture. */
1570 } else if (inpkts > 0) {
1571 if (capture_opts.autostop_packets != 0 &&
1572 ld.packet_count >= capture_opts.autostop_packets) {
1573 /* The specified number of packets have been captured and have
1574 passed both any capture filter in effect and any read filter
1577 } else if (cnd_autostop_size != NULL &&
1578 cnd_eval(cnd_autostop_size,
1579 (guint32)wtap_get_bytes_dumped(ld.wtap_pdh))) {
1580 /* We're saving the capture to a file, and the capture file reached
1581 its maximum size. */
1582 if (capture_opts.multi_files_on) {
1583 /* Switch to the next ringbuffer file */
1584 if (ringbuf_switch_file(&ld.wtap_pdh, &save_file, &save_file_fd, &loop_err)) {
1585 /* File switch succeeded: reset the condition */
1586 cnd_reset(cnd_autostop_size);
1587 if (cnd_file_duration) {
1588 cnd_reset(cnd_file_duration);
1591 /* File switch failed: stop here */
1592 volatile_err = loop_err;
1596 /* No ringbuffer - just stop. */
1600 if (ld.output_to_pipe) {
1601 if (ld.packet_count > packet_count_prev) {
1602 wtap_dump_flush(ld.wtap_pdh);
1603 packet_count_prev = ld.packet_count;
1607 } /* while (ld.go) */
1609 /* delete stop conditions */
1610 if (cnd_autostop_size != NULL)
1611 cnd_delete(cnd_autostop_size);
1612 if (cnd_autostop_duration != NULL)
1613 cnd_delete(cnd_autostop_duration);
1614 if (cnd_file_duration != NULL)
1615 cnd_delete(cnd_file_duration);
1617 if (print_packet_counts) {
1618 /* We're printing packet counts to stderr.
1619 Send a newline so that we move to the line after the packet count. */
1620 fprintf(stderr, "\n");
1623 /* If we got an error while capturing, report it. */
1626 if (ld.from_cap_pipe) {
1627 if (ld.cap_pipe_err == PIPERR) {
1628 cmdarg_err("Error while capturing packets: %s",
1634 cmdarg_err("Error while capturing packets: %s",
1635 pcap_geterr(ld.pcap_h));
1639 if (volatile_err == 0)
1642 show_capture_file_io_error(save_file, volatile_err, FALSE);
1646 if (save_file != NULL) {
1647 /* We're saving to a file or files; close all files. */
1648 close_ok = capture_loop_close_output(&capture_opts, &ld, &err);
1650 /* If we've displayed a message about a write error, there's no point
1651 in displaying another message about an error on close. */
1652 if (!close_ok && write_ok)
1653 show_capture_file_io_error(save_file, err, TRUE);
1657 if (ld.from_cap_pipe && ld.cap_pipe_fd >= 0)
1658 eth_close(ld.cap_pipe_fd);
1662 /* Get the capture statistics, and, if any packets were dropped, report
1664 if (pcap_stats(ld.pcap_h, &stats) >= 0) {
1665 if (stats.ps_drop != 0) {
1666 fprintf(stderr, "%u packets dropped\n", stats.ps_drop);
1669 cmdarg_err("Can't get packet-drop statistics: %s",
1670 pcap_geterr(ld.pcap_h));
1672 pcap_close(ld.pcap_h);
1675 /* Report the number of captured packets if not reported during capture
1676 and we are saving to a file. */
1682 if (capture_opts.multi_files_on) {
1683 ringbuf_error_cleanup();
1687 cmdarg_err("%s", errmsg);
1689 if (ld.from_cap_pipe) {
1690 if (ld.cap_pipe_fd >= 0)
1691 eth_close(ld.cap_pipe_fd);
1695 if (ld.pcap_h != NULL)
1696 pcap_close(ld.pcap_h);
1703 capture_pcap_cb(u_char *user, const struct pcap_pkthdr *phdr,
1706 struct wtap_pkthdr whdr;
1707 union wtap_pseudo_header pseudo_header;
1708 loop_data *ld = (loop_data *) user;
1713 /* Convert from libpcap to Wiretap format.
1714 If that fails, ignore the packet (wtap_process_pcap_packet has
1715 written an error message). */
1716 pd = wtap_process_pcap_packet(ld->wtap_linktype, phdr, pd, &pseudo_header,
1723 * Prevent a SIGINFO handler from writing to stdout while we're
1724 * doing so; instead, have it just set a flag telling us to print
1725 * that information when we're done.
1728 #endif /* SIGINFO */
1730 /* The current packet may have arrived after a very long silence,
1731 * way past the time to switch files. In order not to have
1732 * the first packet of a new series of events as the last
1733 * [or only] packet in the file, switch before writing!
1735 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
1736 /* time elapsed for this ring file, switch to the next */
1737 if (ringbuf_switch_file(&ld->wtap_pdh, &ld->save_file, &save_file_fd, &loop_err)) {
1738 /* File switch succeeded: reset the condition */
1739 cnd_reset(cnd_file_duration);
1741 /* File switch failed: stop here */
1742 /* XXX - we should do something with "loop_err" */
1747 if (!process_packet(&cfile, ld->wtap_pdh, 0, &whdr, &pseudo_header, pd, &err)) {
1748 /* Error writing to a capture file */
1749 if (print_packet_counts) {
1750 /* We're printing counts of packets captured; move to the line after
1752 fprintf(stderr, "\n");
1754 show_capture_file_io_error(ld->save_file, err, FALSE);
1755 pcap_close(ld->pcap_h);
1756 wtap_dump_close(ld->wtap_pdh, &err);
1762 * Allow SIGINFO handlers to write.
1767 * If a SIGINFO handler asked us to write out capture counts, do so.
1771 #endif /* SIGINFO */
1776 capture_cleanup(DWORD ctrltype _U_)
1778 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1779 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1780 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1781 like SIGTERM at least when the machine's shutting down.
1783 For now, we handle them all as indications that we should clean up
1784 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
1787 However, as handlers run in a new thread, we can't just longjmp
1788 out; we have to set "ld.go" to FALSE, and must return TRUE so that
1789 no other handler - such as one that would terminate the process -
1792 XXX - for some reason, typing ^C to Tethereal, if you run this in
1793 a Cygwin console window in at least some versions of Cygwin,
1794 causes Tethereal to terminate immediately; this routine gets
1795 called, but the main loop doesn't get a chance to run and
1796 exit cleanly, at least if this is compiled with Microsoft Visual
1797 C++ (i.e., it's a property of the Cygwin console window or Bash;
1798 it happens if Tethereal is not built with Cygwin - for all I know,
1799 building it with Cygwin may make the problem go away). */
1805 capture_cleanup(int signum _U_)
1807 /* Longjmp back to the starting point; "pcap_dispatch()", on many
1808 UNIX platforms, just keeps looping if it gets EINTR, so if we set
1809 "ld.go" to FALSE and return, we won't break out of it and quit
1811 longjmp(ld.stopenv, 1);
1819 /* XXX - if we use sigaction, this doesn't have to be done.
1820 (Yes, this isn't necessary on BSD, but just in case a system
1821 where "signal()" has AT&T semantics adopts SIGINFO....) */
1822 signal(SIGINFO, report_counts_siginfo);
1823 #endif /* SIGINFO */
1825 if (!print_packet_counts) {
1826 /* Report the count only if we aren't printing a packet count
1827 as packets arrive. */
1828 fprintf(stderr, "%u packets captured\n", ld.packet_count);
1831 infoprint = FALSE; /* we just reported it */
1832 #endif /* SIGINFO */
1837 report_counts_siginfo(int signum _U_)
1839 int sav_errno = errno;
1840 /* If we've been told to delay printing, just set a flag asking
1841 that we print counts (if we're supposed to), otherwise print
1842 the count of packets captured (if we're supposed to). */
1849 #endif /* SIGINFO */
1850 #endif /* HAVE_LIBPCAP */
1853 load_cap_file(capture_file *cf, char *save_file, int out_file_type)
1856 int snapshot_length;
1862 linktype = wtap_file_encap(cf->wth);
1863 if (save_file != NULL) {
1864 /* Set up to write to the capture file. */
1865 snapshot_length = wtap_snapshot_length(cf->wth);
1866 if (snapshot_length == 0) {
1867 /* Snapshot length of input file not known. */
1868 snapshot_length = WTAP_MAX_PACKET_SIZE;
1870 pdh = wtap_dump_open(save_file, out_file_type,
1871 linktype, snapshot_length, FALSE /* compressed */, &err);
1874 /* We couldn't set up to write to the capture file. */
1877 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
1878 cmdarg_err("Capture files can't be written in that format.");
1881 case WTAP_ERR_UNSUPPORTED_ENCAP:
1882 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
1883 cmdarg_err("The capture file being read can't be written in "
1887 case WTAP_ERR_CANT_OPEN:
1888 cmdarg_err("The file \"%s\" couldn't be created for some "
1890 *save_file == '\0' ? "stdout" : save_file);
1893 case WTAP_ERR_SHORT_WRITE:
1894 cmdarg_err("A full header couldn't be written to the file \"%s\".",
1895 *save_file == '\0' ? "stdout" : save_file);
1899 cmdarg_err("The file \"%s\" could not be created: %s.",
1900 *save_file == '\0' ? "stdout" : save_file,
1901 wtap_strerror(err));
1907 if (print_packet_info) {
1908 if (!write_preamble(cf)) {
1910 show_print_file_io_error(err);
1916 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
1917 if (!process_packet(cf, pdh, data_offset, wtap_phdr(cf->wth),
1918 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
1920 /* Error writing to a capture file */
1921 show_capture_file_io_error(save_file, err, FALSE);
1922 wtap_dump_close(pdh, &err);
1927 /* Print a message noting that the read failed somewhere along the line. */
1930 case WTAP_ERR_UNSUPPORTED_ENCAP:
1931 cmdarg_err("\"%s\" has a packet with a network type that Tethereal doesn't support.\n(%s)",
1932 cf->filename, err_info);
1935 case WTAP_ERR_CANT_READ:
1936 cmdarg_err("An attempt to read from \"%s\" failed for some unknown reason.",
1940 case WTAP_ERR_SHORT_READ:
1941 cmdarg_err("\"%s\" appears to have been cut short in the middle of a packet.",
1945 case WTAP_ERR_BAD_RECORD:
1946 cmdarg_err("\"%s\" appears to be damaged or corrupt.\n(%s)",
1947 cf->filename, err_info);
1951 cmdarg_err("An error occurred while reading \"%s\": %s.",
1952 cf->filename, wtap_strerror(err));
1955 if (save_file != NULL) {
1956 /* Now close the capture file. */
1957 if (!wtap_dump_close(pdh, &err))
1958 show_capture_file_io_error(save_file, err, TRUE);
1961 if (save_file != NULL) {
1962 /* Now close the capture file. */
1963 if (!wtap_dump_close(pdh, &err))
1964 show_capture_file_io_error(save_file, err, TRUE);
1966 if (print_packet_info) {
1967 if (!write_finale()) {
1969 show_print_file_io_error(err);
1976 wtap_close(cf->wth);
1983 fill_in_fdata(frame_data *fdata, capture_file *cf,
1984 const struct wtap_pkthdr *phdr, long offset)
1989 fdata->num = cf->count;
1990 fdata->pkt_len = phdr->len;
1991 cum_bytes += phdr->len;
1992 fdata->cum_bytes = cum_bytes;
1993 fdata->cap_len = phdr->caplen;
1994 fdata->file_off = offset;
1995 fdata->lnk_t = phdr->pkt_encap;
1996 fdata->abs_ts = *((nstime_t *) &phdr->ts);
1997 fdata->flags.passed_dfilter = 0;
1998 fdata->flags.encoding = CHAR_ASCII;
1999 fdata->flags.visited = 0;
2000 fdata->flags.marked = 0;
2001 fdata->flags.ref_time = 0;
2003 /* If we don't have the time stamp of the first packet in the
2004 capture, it's because this is the first packet. Save the time
2005 stamp of this packet as the time stamp of the first packet. */
2006 if (nstime_is_zero(&first_ts)) {
2007 first_ts = fdata->abs_ts;
2010 /* If we don't have the time stamp of the previous displayed packet,
2011 it's because this is the first displayed packet. Save the time
2012 stamp of this packet as the time stamp of the previous displayed
2014 if (nstime_is_zero(&prev_ts)) {
2015 prev_ts = fdata->abs_ts;
2018 /* Get the time elapsed between the first packet and this packet. */
2019 nstime_delta(&fdata->rel_ts, &fdata->abs_ts, &first_ts);
2021 /* If it's greater than the current elapsed time, set the elapsed time
2022 to it (we check for "greater than" so as not to be confused by
2023 time moving backwards). */
2024 if ((gint32)cf->elapsed_time.secs < fdata->rel_ts.secs
2025 || ((gint32)cf->elapsed_time.secs == fdata->rel_ts.secs && (gint32)cf->elapsed_time.nsecs < fdata->rel_ts.nsecs)) {
2026 cf->elapsed_time = fdata->rel_ts;
2029 /* Get the time elapsed between the previous displayed packet and
2031 nstime_delta(&fdata->del_ts, &fdata->abs_ts, &prev_ts);
2032 prev_ts = fdata->abs_ts;
2035 /* Free up all data attached to a "frame_data" structure. */
2037 clear_fdata(frame_data *fdata)
2040 g_slist_free(fdata->pfd);
2044 process_packet(capture_file *cf, wtap_dumper *pdh, long offset,
2045 const struct wtap_pkthdr *whdr,
2046 union wtap_pseudo_header *pseudo_header, const guchar *pd,
2050 gboolean create_proto_tree;
2051 epan_dissect_t *edt;
2054 /* Count this packet. */
2057 /* If we're going to print packet information, or we're going to
2058 run a read filter, or we're going to process taps, set up to
2059 do a dissection and do so. */
2060 if (do_dissection) {
2061 fill_in_fdata(&fdata, cf, whdr, offset);
2063 if (print_packet_info) {
2064 /* Grab any resolved addresses */
2066 if (g_resolv_flags) {
2067 host_name_lookup_process(NULL);
2072 if (cf->rfcode || verbose || num_tap_filters!=0)
2073 create_proto_tree = TRUE;
2075 create_proto_tree = FALSE;
2076 /* The protocol tree will be "visible", i.e., printed, only if we're
2077 printing packet details, which is true if we're printing stuff
2078 ("print_packet_info" is true) and we're in verbose mode ("verbose"
2080 edt = epan_dissect_new(create_proto_tree, print_packet_info && verbose);
2082 /* If we're running a read filter, prime the epan_dissect_t with that
2085 epan_dissect_prime_dfilter(edt, cf->rfcode);
2087 tap_queue_init(edt);
2089 /* We only need the columns if we're printing packet info but we're
2090 *not* verbose; in verbose mode, we print the protocol tree, not
2091 the protocol summary. */
2092 epan_dissect_run(edt, pseudo_header, pd, &fdata,
2093 (print_packet_info && !verbose) ? &cf->cinfo : NULL);
2095 tap_push_tapped_queue(edt);
2097 /* Run the read filter if we have one. */
2099 passed = dfilter_apply_edt(cf->rfcode, edt);
2103 /* We're not running a display filter and we're not printing any
2104 packet information, so we don't need to do a dissection, and all
2105 packets are processed. */
2111 /* Count this packet. */
2116 /* Process this packet. */
2118 /* We're writing to a capture file; write this packet. */
2119 if (!wtap_dump(pdh, whdr, pseudo_header, pd, err))
2122 if (print_packet_counts) {
2123 /* We're printing packet counts. */
2124 if (ld.packet_count != 0) {
2125 fprintf(stderr, "\r%u ", ld.packet_count);
2126 /* stderr could be line buffered */
2132 if (print_packet_info) {
2133 /* We're printing packet information; print the information for
2135 print_packet(cf, edt);
2137 /* The ANSI C standard does not appear to *require* that a line-buffered
2138 stream be flushed to the host environment whenever a newline is
2139 written, it just says that, on such a stream, characters "are
2140 intended to be transmitted to or from the host environment as a
2141 block when a new-line character is encountered".
2143 The Visual C++ 6.0 C implementation doesn't do what is intended;
2144 even if you set a stream to be line-buffered, it still doesn't
2145 flush the buffer at the end of every line.
2147 So, if the "-l" flag was specified, we flush the standard output
2148 at the end of a packet. This will do the right thing if we're
2149 printing packet summary lines, and, as we print the entire protocol
2150 tree for a single packet without waiting for anything to happen,
2151 it should be as good as line-buffered mode if we're printing
2152 protocol trees. (The whole reason for the "-l" flag in either
2153 tcpdump or Tethereal is to allow the output of a live capture to
2154 be piped to a program or script and to have that script see the
2155 information for the packet as soon as it's printed, rather than
2156 having to wait until a standard I/O buffer fills up. */
2160 if (ferror(stdout)) {
2161 show_print_file_io_error(errno);
2167 if (do_dissection) {
2168 epan_dissect_free(edt);
2169 clear_fdata(&fdata);
2175 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
2183 cmdarg_err("Not all the packets could be written to \"%s\" because there is "
2184 "no space left on the file system.",
2190 cmdarg_err("Not all the packets could be written to \"%s\" because you are "
2191 "too close to, or over your disk quota.",
2196 case WTAP_ERR_CANT_CLOSE:
2197 cmdarg_err("\"%s\" couldn't be closed for some unknown reason.",
2201 case WTAP_ERR_SHORT_WRITE:
2202 cmdarg_err("Not all the packets could be written to \"%s\".",
2208 cmdarg_err("\"%s\" could not be closed: %s.",
2209 fname, wtap_strerror(err));
2211 cmdarg_err("An error occurred while writing to \"%s\": %s.",
2212 fname, wtap_strerror(err));
2219 write_preamble(capture_file *cf)
2221 switch (output_action) {
2224 return print_preamble(print_stream, cf->filename);
2229 write_pdml_preamble(stdout);
2231 write_psml_preamble(stdout);
2232 return !ferror(stdout);
2235 g_assert_not_reached();
2241 get_line_buf(size_t len)
2243 static char *line_bufp = NULL;
2244 static size_t line_buf_len = 256;
2245 size_t new_line_buf_len;
2247 for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
2248 new_line_buf_len *= 2)
2250 if (line_bufp == NULL) {
2251 line_buf_len = new_line_buf_len;
2252 line_bufp = g_malloc(line_buf_len + 1);
2254 if (new_line_buf_len > line_buf_len) {
2255 line_buf_len = new_line_buf_len;
2256 line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2263 print_columns(capture_file *cf)
2270 line_bufp = get_line_buf(256);
2273 for (i = 0; i < cf->cinfo.num_cols; i++) {
2274 switch (cf->cinfo.col_fmt[i]) {
2278 * Don't print this if we're doing a live capture from a network
2279 * interface - if we're doing a live capture, you won't be
2280 * able to look at the capture in the future (it's not being
2281 * saved anywhere), so the frame numbers are unlikely to be
2284 * (XXX - it might be nice to be able to save and print at
2285 * the same time, sort of like an "Update list of packets
2286 * in real time" capture in Ethereal.)
2288 if (capture_opts.iface != NULL)
2291 column_len = strlen(cf->cinfo.col_data[i]);
2294 line_bufp = get_line_buf(buf_offset + column_len);
2295 sprintf(line_bufp + buf_offset, "%3s", cf->cinfo.col_data[i]);
2301 case COL_ABS_DATE_TIME: /* XXX - wider */
2302 column_len = strlen(cf->cinfo.col_data[i]);
2303 if (column_len < 10)
2305 line_bufp = get_line_buf(buf_offset + column_len);
2306 sprintf(line_bufp + buf_offset, "%10s", cf->cinfo.col_data[i]);
2312 case COL_DEF_DL_SRC:
2313 case COL_RES_DL_SRC:
2314 case COL_UNRES_DL_SRC:
2315 case COL_DEF_NET_SRC:
2316 case COL_RES_NET_SRC:
2317 case COL_UNRES_NET_SRC:
2318 column_len = strlen(cf->cinfo.col_data[i]);
2319 if (column_len < 12)
2321 line_bufp = get_line_buf(buf_offset + column_len);
2322 sprintf(line_bufp + buf_offset, "%12s", cf->cinfo.col_data[i]);
2328 case COL_DEF_DL_DST:
2329 case COL_RES_DL_DST:
2330 case COL_UNRES_DL_DST:
2331 case COL_DEF_NET_DST:
2332 case COL_RES_NET_DST:
2333 case COL_UNRES_NET_DST:
2334 column_len = strlen(cf->cinfo.col_data[i]);
2335 if (column_len < 12)
2337 line_bufp = get_line_buf(buf_offset + column_len);
2338 sprintf(line_bufp + buf_offset, "%-12s", cf->cinfo.col_data[i]);
2342 column_len = strlen(cf->cinfo.col_data[i]);
2343 line_bufp = get_line_buf(buf_offset + column_len);
2344 strcat(line_bufp + buf_offset, cf->cinfo.col_data[i]);
2347 buf_offset += column_len;
2348 if (i != cf->cinfo.num_cols - 1) {
2350 * This isn't the last column, so we need to print a
2351 * separator between this column and the next.
2353 * If we printed a network source and are printing a
2354 * network destination of the same type next, separate
2355 * them with "->"; if we printed a network destination
2356 * and are printing a network source of the same type
2357 * next, separate them with "<-"; otherwise separate them
2360 * We add enough space to the buffer for " <- " or " -> ",
2361 * even if we're only adding " ".
2363 line_bufp = get_line_buf(buf_offset + 4);
2364 switch (cf->cinfo.col_fmt[i]) {
2369 switch (cf->cinfo.col_fmt[i + 1]) {
2374 strcat(line_bufp + buf_offset, " -> ");
2379 strcat(line_bufp + buf_offset, " ");
2385 case COL_DEF_DL_SRC:
2386 case COL_RES_DL_SRC:
2387 case COL_UNRES_DL_SRC:
2388 switch (cf->cinfo.col_fmt[i + 1]) {
2390 case COL_DEF_DL_DST:
2391 case COL_RES_DL_DST:
2392 case COL_UNRES_DL_DST:
2393 strcat(line_bufp + buf_offset, " -> ");
2398 strcat(line_bufp + buf_offset, " ");
2404 case COL_DEF_NET_SRC:
2405 case COL_RES_NET_SRC:
2406 case COL_UNRES_NET_SRC:
2407 switch (cf->cinfo.col_fmt[i + 1]) {
2409 case COL_DEF_NET_DST:
2410 case COL_RES_NET_DST:
2411 case COL_UNRES_NET_DST:
2412 strcat(line_bufp + buf_offset, " -> ");
2417 strcat(line_bufp + buf_offset, " ");
2426 switch (cf->cinfo.col_fmt[i + 1]) {
2431 strcat(line_bufp + buf_offset, " <- ");
2436 strcat(line_bufp + buf_offset, " ");
2442 case COL_DEF_DL_DST:
2443 case COL_RES_DL_DST:
2444 case COL_UNRES_DL_DST:
2445 switch (cf->cinfo.col_fmt[i + 1]) {
2447 case COL_DEF_DL_SRC:
2448 case COL_RES_DL_SRC:
2449 case COL_UNRES_DL_SRC:
2450 strcat(line_bufp + buf_offset, " <- ");
2455 strcat(line_bufp + buf_offset, " ");
2461 case COL_DEF_NET_DST:
2462 case COL_RES_NET_DST:
2463 case COL_UNRES_NET_DST:
2464 switch (cf->cinfo.col_fmt[i + 1]) {
2466 case COL_DEF_NET_SRC:
2467 case COL_RES_NET_SRC:
2468 case COL_UNRES_NET_SRC:
2469 strcat(line_bufp + buf_offset, " <- ");
2474 strcat(line_bufp + buf_offset, " ");
2481 strcat(line_bufp + buf_offset, " ");
2487 return print_line(print_stream, 0, line_bufp);
2491 print_packet(capture_file *cf, epan_dissect_t *edt)
2493 print_args_t print_args;
2496 /* Print the information in the protocol tree. */
2497 switch (output_action) {
2500 print_args.to_file = TRUE;
2501 print_args.format = print_format;
2502 print_args.print_summary = !verbose;
2503 print_args.print_hex = verbose && print_hex;
2504 print_args.print_formfeed = FALSE;
2505 print_args.print_dissections = verbose ? print_dissections_expanded : print_dissections_none;
2507 /* init the packet range */
2508 packet_range_init(&print_args.range);
2510 if (!proto_tree_print(&print_args, edt, print_stream))
2513 /* "print_hex_data()" will put out a leading blank line, as well
2514 as a trailing one; print one here, to separate the packets,
2515 only if "print_hex_data()" won't be called. */
2516 if (!print_line(print_stream, 0, ""))
2522 proto_tree_write_pdml(edt, stdout);
2524 return !ferror(stdout);
2527 /* Just fill in the columns. */
2528 epan_dissect_fill_in_columns(edt);
2530 /* Now print them. */
2531 switch (output_action) {
2534 if (!print_columns(cf))
2539 proto_tree_write_psml(edt, stdout);
2540 return !ferror(stdout);
2544 if (!print_hex_data(print_stream, edt))
2546 if (!print_line(print_stream, 0, ""))
2555 switch (output_action) {
2558 return print_finale(print_stream);
2563 write_pdml_finale(stdout);
2565 write_psml_finale(stdout);
2566 return !ferror(stdout);
2569 g_assert_not_reached();
2575 show_print_file_io_error(int err)
2580 cmdarg_err("Not all the packets could be printed because there is "
2581 "no space left on the file system.");
2586 cmdarg_err("Not all the packets could be printed because you are "
2587 "too close to, or over your disk quota.");
2592 cmdarg_err("An error occurred while printing packets: %s.",
2599 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
2603 static char errmsg_errno[1024+1];
2606 /* Wiretap error. */
2609 case WTAP_ERR_NOT_REGULAR_FILE:
2610 errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
2613 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
2614 /* Seen only when opening a capture file for reading. */
2615 errmsg = "The file \"%s\" isn't a capture file in a format Tethereal understands.";
2618 case WTAP_ERR_UNSUPPORTED:
2619 /* Seen only when opening a capture file for reading. */
2620 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2621 "The file \"%%s\" isn't a capture file in a format Tethereal understands.\n"
2624 errmsg = errmsg_errno;
2627 case WTAP_ERR_CANT_WRITE_TO_PIPE:
2628 /* Seen only when opening a capture file for writing. */
2629 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2630 "The file \"%%s\" is a pipe, and %s capture files can't be "
2631 "written to a pipe.", wtap_file_type_string(file_type));
2632 errmsg = errmsg_errno;
2635 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2636 /* Seen only when opening a capture file for writing. */
2637 errmsg = "Tethereal doesn't support writing capture files in that format.";
2640 case WTAP_ERR_UNSUPPORTED_ENCAP:
2642 errmsg = "Tethereal can't save this capture in that format.";
2644 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2645 "The file \"%%s\" is a capture for a network type that Tethereal doesn't support.\n"
2648 errmsg = errmsg_errno;
2652 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2654 errmsg = "Tethereal can't save this capture in that format.";
2656 errmsg = "The file \"%s\" is a capture for a network type that Tethereal doesn't support.";
2659 case WTAP_ERR_BAD_RECORD:
2660 /* Seen only when opening a capture file for reading. */
2661 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2662 "The file \"%%s\" appears to be damaged or corrupt.\n"
2665 errmsg = errmsg_errno;
2668 case WTAP_ERR_CANT_OPEN:
2670 errmsg = "The file \"%s\" could not be created for some unknown reason.";
2672 errmsg = "The file \"%s\" could not be opened for some unknown reason.";
2675 case WTAP_ERR_SHORT_READ:
2676 errmsg = "The file \"%s\" appears to have been cut short"
2677 " in the middle of a packet or other data.";
2680 case WTAP_ERR_SHORT_WRITE:
2681 errmsg = "A full header couldn't be written to the file \"%s\".";
2685 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2686 "The file \"%%s\" could not be %s: %s.",
2687 for_writing ? "created" : "opened",
2688 wtap_strerror(err));
2689 errmsg = errmsg_errno;
2693 errmsg = file_open_error_message(err, for_writing);
2698 * Open/create errors are reported with an console message in Tethereal.
2701 open_failure_message(const char *filename, int err, gboolean for_writing)
2703 fprintf(stderr, "tethereal: ");
2704 fprintf(stderr, file_open_error_message(err, for_writing), filename);
2705 fprintf(stderr, "\n");
2709 cf_open(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
2713 char err_msg[2048+1];
2715 wth = wtap_open_offline(fname, err, &err_info, FALSE);
2719 /* The open succeeded. Fill in the information for this file. */
2721 /* Initialize all data structures used for dissection. */
2725 cf->f_datalen = 0; /* not used, but set it anyway */
2727 /* Set the file name because we need it to set the follow stream filter.
2728 XXX - is that still true? We need it for other reasons, though,
2730 cf->filename = g_strdup(fname);
2732 /* Indicate whether it's a permanent or temporary file. */
2733 cf->is_tempfile = is_tempfile;
2735 /* If it's a temporary capture buffer file, mark it as not saved. */
2736 cf->user_saved = !is_tempfile;
2738 cf->cd_t = wtap_file_type(cf->wth);
2740 cf->drops_known = FALSE;
2742 cf->snap = wtap_snapshot_length(cf->wth);
2743 if (cf->snap == 0) {
2744 /* Snapshot length not known. */
2745 cf->has_snap = FALSE;
2746 cf->snap = WTAP_MAX_PACKET_SIZE;
2748 cf->has_snap = TRUE;
2749 nstime_set_zero(&cf->elapsed_time);
2750 nstime_set_zero(&first_ts);
2751 nstime_set_zero(&prev_ts);
2756 g_snprintf(err_msg, sizeof err_msg,
2757 cf_open_error_message(*err, err_info, FALSE, 0), fname);
2758 cmdarg_err("%s", err_msg);
2764 * General errors are reported with an console message in Tethereal.
2767 failure_message(const char *msg_format, va_list ap)
2769 fprintf(stderr, "tethereal: ");
2770 vfprintf(stderr, msg_format, ap);
2771 fprintf(stderr, "\n");
2775 * Read errors are reported with an console message in Tethereal.
2778 read_failure_message(const char *filename, int err)
2780 cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
2781 filename, strerror(err));
2785 * Report an error in command-line arguments.
2788 cmdarg_err(const char *fmt, ...)
2793 fprintf(stderr, "tethereal: ");
2794 vfprintf(stderr, fmt, ap);
2795 fprintf(stderr, "\n");
2800 * Report additional information for an error in command-line arguments.
2803 cmdarg_err_cont(const char *fmt, ...)
2808 vfprintf(stderr, fmt, ap);
2809 fprintf(stderr, "\n");
2814 /****************************************************************************************************************/
2815 /* sync pipe "dummies", needed for capture_loop.c */
2819 /** the child has opened a new capture file, notify the parent */
2821 sync_pipe_filename_to_parent(const char *filename)
2823 /* shouldn't happen */
2827 /** the child captured some new packets, notify the parent */
2829 sync_pipe_packet_count_to_parent(int packet_count)
2831 /* shouldn't happen */
2835 /** the child stopped capturing, notify the parent */
2837 sync_pipe_drops_to_parent(int drops)
2839 /* shouldn't happen */
2843 /** the child encountered an error, notify the parent */
2845 sync_pipe_errmsg_to_parent(const char *errmsg)
2850 #endif /* HAVE_LIBPCAP */
2853 /****************************************************************************************************************/
2854 /* simple_dialog "dummies", needed for capture_loop.c */
2859 char *simple_dialog_primary_start(void)
2864 char *simple_dialog_primary_end(void)
2870 /* XXX - do we need to convert the string for the console? */
2872 simple_dialog_format_message(const char *msg)
2878 #if GTK_MAJOR_VERSION < 2
2879 str = g_strdup(msg);
2881 str = xml_escape(msg);
2889 #endif /* HAVE_LIBPCAP */