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 <epan/privileges.h>
66 #include <wiretap/file_util.h>
69 #include <epan/timestamp.h>
70 #include <epan/packet.h>
72 #include "disabled_protos.h"
73 #include <epan/prefs.h>
74 #include <epan/column.h>
76 #include <epan/addr_resolv.h>
78 #include "clopts_common.h"
79 #include "cmdarg_err.h"
80 #include "version_info.h"
81 #include <epan/conversation.h>
82 #include <epan/plugins.h>
84 #include "conditions.h"
85 #include "capture_stop_conditions.h"
86 #include "ringbuffer.h"
87 #include "capture_ui_utils.h"
88 #include <epan/epan_dissect.h>
90 #include <epan/stat_cmd_args.h>
91 #include <epan/timestamp.h>
96 #include "capture-pcap-util.h"
97 #include <wiretap/wtap-capture.h>
99 #include "capture-wpcap.h"
100 #include "capture_errs.h"
103 #include "capture_loop.h"
104 #endif /* HAVE_LIBPCAP */
105 #include "epan/emem.h"
109 * This is the template for the decode as option; it is shared between the
110 * various functions that output the usage for this parameter.
112 static const gchar decode_as_arg_template[] = "<layer_type>==<selector>,<decode_as_protocol>";
114 static nstime_t first_ts;
115 static nstime_t prev_ts;
116 static GString *comp_info_str, *runtime_info_str;
118 static gboolean print_packet_info; /* TRUE if we're to print packet information */
120 * The way the packet decode is to be written.
123 WRITE_TEXT, /* summary or detail text */
124 WRITE_XML /* PDML or PSML */
125 /* 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;
132 static guint32 cum_bytes = 0;
133 static print_format_e print_format = PR_FMT_TEXT;
134 static print_stream_t *print_stream;
138 * TRUE if we're to print packet counts to keep track of captured packets.
140 static gboolean print_packet_counts;
146 static capture_options capture_opts;
150 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
151 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
153 #endif /* HAVE_LIBPCAP */
156 static int capture(int);
157 static void capture_pcap_cb(u_char *, const struct pcap_pkthdr *,
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);
171 static gboolean process_packet(capture_file *cf, wtap_dumper *pdh, long offset,
172 const struct wtap_pkthdr *whdr, union wtap_pseudo_header *pseudo_header,
173 const guchar *pd, int *err);
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);
190 static void list_capture_types(void) {
193 fprintf(stderr, "editcap: The available capture file types for \"F\":\n");
194 for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
195 if (wtap_dump_can_open(i))
196 fprintf(stderr, " %s - %s\n",
197 wtap_file_type_short_string(i), wtap_file_type_string(i));
202 print_usage(gboolean print_ver)
209 "Tethereal " VERSION "%s\n"
210 "Dump and analyze network traffic.\n"
211 "See http://www.ethereal.com for more information.\n"
214 svnversion, get_copyright_info());
218 fprintf(output, "\n");
219 fprintf(output, "Usage: tethereal [options] ...\n");
220 fprintf(output, "\n");
223 fprintf(output, "Capture interface:\n");
224 fprintf(output, " -i <interface> name or idx of interface (def: first none loopback)\n");
225 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
226 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
227 fprintf(output, " -p don't capture in promiscuous mode\n");
229 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
231 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
232 fprintf(output, " -D print list of interfaces and exit\n");
233 fprintf(output, " -L print list of link-layer types of iface and exit\n");
234 fprintf(output, "\n");
235 fprintf(output, "Capture stop conditions:\n");
236 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
237 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
238 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
239 fprintf(output, " files:NUM - stop after NUM files\n");
240 /*fprintf(output, "\n");*/
241 fprintf(output, "Capture output:\n");
242 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
243 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
244 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
245 #endif /* HAVE_LIBPCAP */
247 /*fprintf(output, "\n");*/
248 fprintf(output, "Input file:\n");
249 fprintf(output, " -r <infile> set the filename to read from (no pipes or stdin!)\n");
251 fprintf(output, "\n");
252 fprintf(output, "Processing:\n");
253 fprintf(output, " -R <read filter> packet filter in Ethereal display filter syntax\n");
254 fprintf(output, " -n disable all name resolutions (def: all enabled)\n");
255 fprintf(output, " -N <name resolve flags> enable specific name resolution(s): \"mntC\"\n");
256 fprintf(output, " -d %s ...\n", decode_as_arg_template);
257 fprintf(output, " \"Decode As\", see the man page for details\n");
258 fprintf(output, " Example: tcp.port==8888,http\n");
260 /*fprintf(output, "\n");*/
261 fprintf(output, "Output:\n");
262 fprintf(stderr, " -w <outfile|-> set the output filename (or '-' for stdout)\n");
263 fprintf(stderr, " -F <output file type> set the output file type, default is libpcap\n");
264 fprintf(stderr, " an empty \"-F\" option will list the file types\n");
265 fprintf(output, " -V add output of packet tree (Packet Details)\n");
266 fprintf(output, " -x add output of hex and ASCII dump (Packet Bytes)\n");
267 fprintf(output, " -T pdml|ps|psml|text output format of text output (def: text)\n");
268 fprintf(output, " -t ad|a|r|d output format of time stamps (def: r: rel. to first)\n");
269 fprintf(output, " -l flush output after each packet\n");
270 fprintf(output, " -q be more quiet on stdout (e.g. when using statistics)\n");
271 fprintf(output, " -z <statistics> various statistics, see the man page for details\n");
273 fprintf(output, "\n");
274 fprintf(stderr, "Miscellaneous:\n");
275 fprintf(stderr, " -h display this help and exit\n");
276 fprintf(stderr, " -v display version info and exit\n");
277 fprintf(output, " -o <name>:<value> ... override preference setting\n");
281 * For a dissector table, print on the stream described by output,
282 * its short name (which is what's used in the "-d" option) and its
286 display_dissector_table_names(char *table_name, const char *ui_name,
289 fprintf((FILE *)output, "\t%s (%s)\n", table_name, ui_name);
293 * For a dissector handle, print on the stream described by output,
294 * the filter name (which is what's used in the "-d" option) and the full
295 * name for the protocol that corresponds to this handle.
298 display_dissector_names(const gchar *table _U_, gpointer handle, gpointer output)
301 const gchar* proto_filter_name;
302 const gchar* proto_ui_name;
304 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
306 if (proto_id != -1) {
307 proto_filter_name = proto_get_protocol_filter_name(proto_id);
308 proto_ui_name = proto_get_protocol_name(proto_id);
309 g_assert(proto_filter_name != NULL);
310 g_assert(proto_ui_name != NULL);
312 fprintf((FILE *)output, "\t%s (%s)\n",
319 * The protocol_name_search structure is used by find_protocol_name_func()
320 * to pass parameters and store results
322 struct protocol_name_search{
323 gchar *searched_name; /* Protocol filter name we are looking for */
324 dissector_handle_t matched_handle; /* Handle for a dissector whose protocol has the specified filter name */
325 guint nb_match; /* How many dissectors matched searched_name */
327 typedef struct protocol_name_search *protocol_name_search_t;
330 * This function parses all dissectors associated with a table to find the
331 * one whose protocol has the specified filter name. It is called
332 * as a reference function in a call to dissector_table_foreach_handle.
333 * The name we are looking for, as well as the results, are stored in the
334 * protocol_name_search struct pointed to by user_data.
335 * If called using dissector_table_foreach_handle, we actually parse the
336 * whole list of dissectors.
339 find_protocol_name_func(const gchar *table _U_, gpointer handle, gpointer user_data)
343 const gchar *protocol_filter_name;
344 protocol_name_search_t search_info;
348 search_info = (protocol_name_search_t)user_data;
350 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
351 if (proto_id != -1) {
352 protocol_filter_name = proto_get_protocol_filter_name(proto_id);
353 g_assert(protocol_filter_name != NULL);
354 if (strcmp(protocol_filter_name, search_info->searched_name) == 0) {
356 if (search_info->nb_match == 0) {
357 /* Record this handle only if this is the first match */
358 search_info->matched_handle = (dissector_handle_t)handle; /* Record the handle for this matching dissector */
360 search_info->nb_match++;
366 * Print all layer type names supported.
367 * We send the output to the stream described by the handle output.
371 fprint_all_layer_types(FILE *output)
374 dissector_all_tables_foreach_table(display_dissector_table_names, (gpointer)output);
378 * Print all protocol names supported for a specific layer type.
379 * table_name contains the layer type name in which the search is performed.
380 * We send the output to the stream described by the handle output.
384 fprint_all_protocols_for_layer_types(FILE *output, gchar *table_name)
387 dissector_table_foreach_handle(table_name,
388 display_dissector_names,
393 * The function below parses the command-line parameters for the decode as
394 * feature (a string pointer by cl_param).
395 * It checks the format of the command-line, searches for a matching table
396 * and dissector. If a table/dissector match is not found, we display a
397 * summary of the available tables/dissectors (on stderr) and return FALSE.
398 * If everything is fine, we get the "Decode as" preference activated,
399 * then we return TRUE.
402 add_decode_as(const gchar *cl_param)
406 gchar *decoded_param;
407 gchar *remaining_param;
409 gchar *dissector_str;
410 dissector_handle_t dissector_matching;
411 dissector_table_t table_matching;
412 ftenum_t dissector_table_selector_type;
413 struct protocol_name_search user_protocol_name;
415 /* The following code will allocate and copy the command-line options in a string pointed by decoded_param */
418 decoded_param = g_malloc( sizeof(gchar) * (strlen(cl_param) + 1) ); /* Allocate enough space to have a working copy of the command-line parameter */
419 g_assert(decoded_param);
420 strcpy(decoded_param, cl_param);
423 /* The lines below will parse this string (modifying it) to extract all
424 necessary information. Note that decoded_param is still needed since
425 strings are not copied - we just save pointers. */
427 /* This section extracts a layer type (table_name) from decoded_param */
428 table_name = decoded_param; /* Layer type string starts from beginning */
430 remaining_param = strchr(table_name, '=');
431 if (remaining_param == NULL) {
432 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
433 /* If the argument does not follow the template, carry on anyway to check
434 if the table name is at least correct. If remaining_param is NULL,
435 we'll exit anyway further down */
438 *remaining_param = '\0'; /* Terminate the layer type string (table_name) where '=' was detected */
441 /* Remove leading and trailing spaces from the table name */
442 while ( table_name[0] == ' ' )
444 while ( table_name[strlen(table_name) - 1] == ' ' )
445 table_name[strlen(table_name) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
447 /* The following part searches a table matching with the layer type specified */
448 table_matching = NULL;
450 /* Look for the requested table */
451 if ( !(*(table_name)) ) { /* Is the table name empty, if so, don't even search for anything, display a message */
452 cmdarg_err("No layer type specified"); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
455 table_matching = find_dissector_table(table_name);
456 if (!table_matching) {
457 cmdarg_err("Unknown layer type -- %s", table_name); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
461 if (!table_matching) {
462 /* Display a list of supported layer types to help the user, if the
463 specified layer type was not found */
464 cmdarg_err("Valid layer types are:");
465 fprint_all_layer_types(stderr);
467 if (remaining_param == NULL || !table_matching) {
468 /* Exit if the layer type was not found, or if no '=' separator was found
470 g_free(decoded_param);
474 if (*(remaining_param + 1) != '=') { /* Check for "==" and not only '=' */
475 cmdarg_err("WARNING: -d requires \"==\" instead of \"=\". Option will be treated as \"%s==%s\"", table_name, remaining_param + 1);
478 remaining_param++; /* Move to the second '=' */
479 *remaining_param = '\0'; /* Remove the second '=' */
481 remaining_param++; /* Position after the layer type string */
483 /* This section extracts a selector value (selector_str) from decoded_param */
485 selector_str = remaining_param; /* Next part starts with the selector number */
487 remaining_param = strchr(selector_str, ',');
488 if (remaining_param == NULL) {
489 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
490 /* If the argument does not follow the template, carry on anyway to check
491 if the selector value is at least correct. If remaining_param is NULL,
492 we'll exit anyway further down */
495 *remaining_param = '\0'; /* Terminate the selector number string (selector_str) where ',' was detected */
498 dissector_table_selector_type = get_dissector_table_selector_type(table_name);
500 switch (dissector_table_selector_type) {
506 /* The selector for this table is an unsigned number. Parse it as such.
507 There's no need to remove leading and trailing spaces from the
508 selector number string, because sscanf will do that for us. */
509 if ( sscanf(selector_str, "%u", &selector) != 1 ) {
510 cmdarg_err("Invalid selector number \"%s\"", selector_str);
511 g_free(decoded_param);
518 /* The selector for this table is a string. */
522 /* There are currently no dissector tables with any types other
523 than the ones listed above. */
524 g_assert_not_reached();
527 if (remaining_param == NULL) {
528 /* Exit if no ',' separator was found (see above) */
529 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
530 fprint_all_protocols_for_layer_types(stderr, table_name);
531 g_free(decoded_param);
535 remaining_param++; /* Position after the selector number string */
537 /* This section extracts a protocol filter name (dissector_str) from decoded_param */
539 dissector_str = remaining_param; /* All the rest of the string is the dissector (decode as protocol) name */
541 /* Remove leading and trailing spaces from the dissector name */
542 while ( dissector_str[0] == ' ' )
544 while ( dissector_str[strlen(dissector_str) - 1] == ' ' )
545 dissector_str[strlen(dissector_str) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
547 dissector_matching = NULL;
549 /* We now have a pointer to the handle for the requested table inside the variable table_matching */
550 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 */
551 cmdarg_err("No protocol name specified"); /* Note, we don't exit here, but dissector_matching will remain NULL, so we exit below */
554 user_protocol_name.nb_match = 0;
555 user_protocol_name.searched_name = dissector_str;
556 user_protocol_name.matched_handle = NULL;
558 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 */
560 if (user_protocol_name.nb_match != 0) {
561 dissector_matching = user_protocol_name.matched_handle;
562 if (user_protocol_name.nb_match > 1) {
563 cmdarg_err("WARNING: Protocol \"%s\" matched %u dissectors, first one will be used", dissector_str, user_protocol_name.nb_match);
567 /* OK, check whether the problem is that there isn't any such
568 protocol, or that there is but it's not specified as a protocol
569 that's valid for that dissector table.
570 Note, we don't exit here, but dissector_matching will remain NULL,
572 if (proto_get_id_by_filter_name(dissector_str) == -1) {
573 /* No such protocol */
574 cmdarg_err("Unknown protocol -- \"%s\"", dissector_str);
576 cmdarg_err("Protocol \"%s\" isn't valid for layer type \"%s\"",
577 dissector_str, table_name);
582 if (!dissector_matching) {
583 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
584 fprint_all_protocols_for_layer_types(stderr, table_name);
585 g_free(decoded_param);
589 /* This is the end of the code that parses the command-line options.
590 All information is now stored in the variables:
594 The above variables that are strings are still pointing to areas within
595 decoded_parm. decoded_parm thus still needs to be kept allocated in
596 until we stop needing these variables
597 decoded_param will be deallocated at each exit point of this function */
600 /* We now have a pointer to the handle for the requested dissector
601 (requested protocol) inside the variable dissector_matching */
602 switch (dissector_table_selector_type) {
608 /* The selector for this table is an unsigned number. */
609 dissector_change(table_name, selector, dissector_matching);
614 /* The selector for this table is a string. */
615 dissector_change_string(table_name, selector_str, dissector_matching);
619 /* There are currently no dissector tables with any types other
620 than the ones listed above. */
621 g_assert_not_reached();
623 g_free(decoded_param); /* "Decode As" rule has been succesfully added */
628 log_func_ignore (const gchar *log_domain _U_, GLogLevelFlags log_level _U_,
629 const gchar *message _U_, gpointer user_data _U_)
634 output_file_description(const char *fname)
636 char *save_file_string;
638 /* Get a string that describes what we're writing to */
639 if (strcmp(fname, "-") == 0) {
640 /* We're writing to the standard output */
641 save_file_string = g_strdup("standard output");
643 /* We're writing to a file with the name in save_file */
644 save_file_string = g_strdup_printf("file \"%s\"", fname);
646 return save_file_string;
650 main(int argc, char *argv[])
654 gboolean arg_error = FALSE;
660 char *gpf_path, *pf_path;
661 char *gdp_path, *dp_path;
662 int gpf_open_errno, gpf_read_errno;
663 int pf_open_errno, pf_read_errno;
664 int gdp_open_errno, gdp_read_errno;
665 int dp_open_errno, dp_read_errno;
668 gboolean capture_filter_specified = FALSE;
669 gboolean list_link_layer_types = FALSE;
670 gboolean start_capture = FALSE;
672 gboolean capture_option_specified = FALSE;
674 gboolean quiet = FALSE;
675 int out_file_type = WTAP_FILE_PCAP;
676 gchar *cf_name = NULL, *rfilter = NULL;
677 #ifdef HAVE_PCAP_OPEN_DEAD
678 struct bpf_program fcode;
680 dfilter_t *rfcode = NULL;
683 GLogLevelFlags log_flags;
685 #define OPTSTRING_INIT "a:b:c:d:Df:F:hi:lLnN:o:pqr:R:s:St:T:vVw:xy:z:"
688 #define OPTSTRING_WIN32 "B:"
690 #define OPTSTRING_WIN32 ""
693 #define OPTSTRING_WIN32 ""
694 #endif /* HAVE_LIBPCAP */
696 static const char optstring[] = OPTSTRING_INIT OPTSTRING_WIN32;
699 * Get credential information for later use.
701 get_credential_info();
703 /* nothing more than the standard GLib handler, but without a warning */
706 G_LOG_LEVEL_CRITICAL|
711 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
713 g_log_set_handler(NULL,
715 log_func_ignore, NULL /* user_data */);
716 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
718 log_func_ignore, NULL /* user_data */);
720 /* initialize memory allocation subsystem */
725 capture_opts_init(&capture_opts, NULL /* cfile */);
728 timestamp_set_type(TS_RELATIVE);
729 timestamp_set_precision(TS_PREC_AUTO);
731 /* Register all dissectors; we must do this before checking for the
732 "-G" flag, as the "-G" flag dumps information registered by the
733 dissectors, and we must do it before we read the preferences, in
734 case any dissectors register preferences. */
735 epan_init(PLUGIN_DIR,register_all_protocols,register_all_protocol_handoffs,
736 failure_message,open_failure_message,read_failure_message);
738 /* Register all tap listeners; we do this before we parse the arguments,
739 as the "-z" argument can specify a registered tap. */
741 /* we register the plugin taps before the other taps because
742 stats_tree taps plugins will be registered as tap listeners
743 by stats_tree_stat.c and need to registered before that */
745 register_all_plugin_tap_listeners();
747 register_all_tap_listeners();
749 /* Now register the preferences for any non-dissector modules.
750 We must do that before we read the preferences as well. */
751 prefs_register_modules();
753 /* If invoked with the "-G" flag, we dump out information based on
754 the argument to the "-G" flag; if no argument is specified,
755 for backwards compatibility we dump out a glossary of display
758 XXX - we do this here, for now, to support "-G" with no arguments.
759 If none of our build or other processes uses "-G" with no arguments,
760 we can just process it with the other arguments. */
761 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
763 proto_registrar_dump_fields(1);
765 if (strcmp(argv[2], "fields") == 0)
766 proto_registrar_dump_fields(1);
767 else if (strcmp(argv[2], "fields2") == 0)
768 proto_registrar_dump_fields(2);
769 else if (strcmp(argv[2], "fields3") == 0)
770 proto_registrar_dump_fields(3);
771 else if (strcmp(argv[2], "protocols") == 0)
772 proto_registrar_dump_protocols();
773 else if (strcmp(argv[2], "values") == 0)
774 proto_registrar_dump_values();
775 else if (strcmp(argv[2], "decodes") == 0)
776 dissector_dump_decodes();
777 else if (strcmp(argv[2], "defaultprefs") == 0)
779 else if (strcmp(argv[2], "currentprefs") == 0) {
780 read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
781 &pf_open_errno, &pf_read_errno, &pf_path);
784 cmdarg_err("Invalid \"%s\" option for -G flag", argv[2]);
791 /* Set the C-language locale to the native environment. */
792 setlocale(LC_ALL, "");
794 prefs = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
795 &pf_open_errno, &pf_read_errno, &pf_path);
796 if (gpf_path != NULL) {
797 if (gpf_open_errno != 0) {
798 cmdarg_err("Can't open global preferences file \"%s\": %s.",
799 pf_path, strerror(gpf_open_errno));
801 if (gpf_read_errno != 0) {
802 cmdarg_err("I/O error reading global preferences file \"%s\": %s.",
803 pf_path, strerror(gpf_read_errno));
806 if (pf_path != NULL) {
807 if (pf_open_errno != 0) {
808 cmdarg_err("Can't open your preferences file \"%s\": %s.", pf_path,
809 strerror(pf_open_errno));
811 if (pf_read_errno != 0) {
812 cmdarg_err("I/O error reading your preferences file \"%s\": %s.",
813 pf_path, strerror(pf_read_errno));
819 /* Set the name resolution code's flags from the preferences. */
820 g_resolv_flags = prefs->name_resolve;
822 /* Read the disabled protocols file. */
823 read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
824 &dp_path, &dp_open_errno, &dp_read_errno);
825 if (gdp_path != NULL) {
826 if (gdp_open_errno != 0) {
828 "Could not open global disabled protocols file\n\"%s\": %s.",
829 gdp_path, strerror(gdp_open_errno));
831 if (gdp_read_errno != 0) {
833 "I/O error reading global disabled protocols file\n\"%s\": %s.",
834 gdp_path, strerror(gdp_read_errno));
838 if (dp_path != NULL) {
839 if (dp_open_errno != 0) {
841 "Could not open your disabled protocols file\n\"%s\": %s.", dp_path,
842 strerror(dp_open_errno));
844 if (dp_read_errno != 0) {
846 "I/O error reading your disabled protocols file\n\"%s\": %s.", dp_path,
847 strerror(dp_read_errno));
853 /* Load Wpcap, if possible */
857 init_cap_file(&cfile);
859 /* Assemble the compile-time version information string */
860 comp_info_str = g_string_new("Compiled ");
861 get_compiled_version_info(comp_info_str);
863 /* Assemble the run-time version information string */
864 runtime_info_str = g_string_new("Running ");
865 get_runtime_version_info(runtime_info_str);
867 /* Print format defaults to this. */
868 print_format = PR_FMT_TEXT;
870 /* Now get our args */
871 while ((opt = getopt(argc, argv, optstring)) != -1) {
873 case 'a': /* autostop criteria */
874 case 'b': /* Ringbuffer option */
875 case 'c': /* Capture xxx packets */
876 case 'f': /* capture filter */
877 case 'i': /* Use interface xxx */
878 case 'p': /* Don't capture in promiscuous mode */
879 case 's': /* Set the snapshot (capture) length */
880 case 'w': /* Write to capture file xxx */
881 case 'y': /* Set the pcap data link type */
883 case 'B': /* Buffer size */
886 capture_opts_add_opt(&capture_opts, opt, optarg, &start_capture);
888 capture_option_specified = TRUE;
892 case 'd': /* Decode as rule */
893 if (!add_decode_as(optarg))
896 case 'D': /* Print a list of capture devices and exit */
898 capture_opts_list_interfaces();
901 capture_option_specified = TRUE;
906 out_file_type = wtap_short_string_to_file_type(optarg);
907 if (out_file_type < 0) {
908 cmdarg_err("\"%s\" isn't a valid capture file type",
910 list_capture_types();
914 case 'h': /* Print help and exit */
918 case 'l': /* "Line-buffer" standard output */
919 /* This isn't line-buffering, strictly speaking, it's just
920 flushing the standard output after the information for
921 each packet is printed; however, that should be good
922 enough for all the purposes to which "-l" is put (and
923 is probably actually better for "-V", as it does fewer
926 See the comment in "process_packet()" for an explanation of
927 why we do that, and why we don't just use "setvbuf()" to
928 make the standard output line-buffered (short version: in
929 Windows, "line-buffered" is the same as "fully-buffered",
930 and the output buffer is only flushed when it fills up). */
931 line_buffered = TRUE;
933 case 'L': /* Print list of link-layer types and exit */
935 list_link_layer_types = TRUE;
938 capture_option_specified = TRUE;
942 case 'n': /* No name resolution */
943 g_resolv_flags = RESOLV_NONE;
945 case 'N': /* Select what types of addresses/port #s to resolve */
946 if (g_resolv_flags == RESOLV_ALL)
947 g_resolv_flags = RESOLV_NONE;
948 badopt = string_to_name_resolve(optarg, &g_resolv_flags);
949 if (badopt != '\0') {
950 cmdarg_err("-N specifies unknown resolving option '%c'; valid options are 'm', 'n', and 't'",
955 case 'o': /* Override preference from command line */
956 switch (prefs_set_pref(optarg)) {
958 case PREFS_SET_SYNTAX_ERR:
959 cmdarg_err("Invalid -o flag \"%s\"", optarg);
963 case PREFS_SET_NO_SUCH_PREF:
964 case PREFS_SET_OBSOLETE:
965 cmdarg_err("-o flag \"%s\" specifies unknown preference",
971 case 'q': /* Quiet */
974 case 'r': /* Read capture file xxx */
975 cf_name = g_strdup(optarg);
977 case 'R': /* Read file filter */
980 case 'S': /* show packets in real time */
981 print_packet_info = TRUE;
983 case 't': /* Time stamp type */
984 if (strcmp(optarg, "r") == 0)
985 timestamp_set_type(TS_RELATIVE);
986 else if (strcmp(optarg, "a") == 0)
987 timestamp_set_type(TS_ABSOLUTE);
988 else if (strcmp(optarg, "ad") == 0)
989 timestamp_set_type(TS_ABSOLUTE_WITH_DATE);
990 else if (strcmp(optarg, "d") == 0)
991 timestamp_set_type(TS_DELTA);
993 cmdarg_err("Invalid time stamp type \"%s\"",
995 cmdarg_err_cont("It must be \"r\" for relative, \"a\" for absolute,");
996 cmdarg_err_cont("\"ad\" for absolute with date, or \"d\" for delta.");
1000 case 'T': /* printing Type */
1001 if (strcmp(optarg, "text") == 0) {
1002 output_action = WRITE_TEXT;
1003 print_format = PR_FMT_TEXT;
1004 } else if (strcmp(optarg, "ps") == 0) {
1005 output_action = WRITE_TEXT;
1006 print_format = PR_FMT_PS;
1007 } else if (strcmp(optarg, "pdml") == 0) {
1008 output_action = WRITE_XML;
1010 } else if (strcmp(optarg, "psml") == 0) {
1011 output_action = WRITE_XML;
1014 cmdarg_err("Invalid -T parameter.");
1015 cmdarg_err_cont("It must be \"ps\", \"text\", \"pdml\", or \"psml\".");
1019 case 'v': /* Show version and exit */
1020 printf("Tethereal " VERSION "%s\n"
1027 svnversion, get_copyright_info(), comp_info_str->str,
1028 runtime_info_str->str);
1031 case 'V': /* Verbose */
1034 case 'x': /* Print packet data in hex (and ASCII) */
1038 /* We won't call the init function for the stat this soon
1039 as it would disallow MATE's fields (which are registered
1040 by the preferences set callback) from being used as
1041 part of a tap filter. Instead, we just add the argument
1042 to a list of stat arguments. */
1043 if (!process_stat_cmd_arg(optarg)) {
1044 cmdarg_err("invalid -z argument.");
1045 cmdarg_err_cont(" -z argument must be one of :");
1046 list_stat_cmd_args();
1051 case '?': /* Bad flag - print usage message */
1054 list_capture_types();
1064 /* If no capture filter or read filter has been specified, and there are
1065 still command-line arguments, treat them as the tokens of a capture
1066 filter (if no "-r" flag was specified) or a read filter (if a "-r"
1067 flag was specified. */
1068 if (optind < argc) {
1069 if (cf_name != NULL) {
1070 if (rfilter != NULL) {
1071 cmdarg_err("Read filters were specified both with \"-R\" "
1072 "and with additional command-line arguments");
1075 rfilter = get_args_as_string(argc, argv, optind);
1078 if (capture_filter_specified) {
1079 cmdarg_err("Capture filters were specified both with \"-f\""
1080 " and with additional command-line arguments");
1083 capture_opts.cfilter = get_args_as_string(argc, argv, optind);
1085 capture_option_specified = TRUE;
1090 /* If we're not writing to a file and "-q" wasn't specified
1091 we should print packet information */
1092 if (capture_opts.save_file == NULL && !quiet)
1093 print_packet_info = TRUE;
1095 if (capture_opts.save_file != NULL &&
1096 strcmp(capture_opts.save_file, "-") == 0
1097 && print_packet_info) {
1098 /* If we're writing to the standard output.
1099 and we'll also be writing dissected packets to the standard
1100 output, reject the request. At best, we could redirect that
1101 to the standard error; we *can't* write both to the standard
1102 output and have either of them be useful. */
1103 cmdarg_err("You can't write both raw packet data and dissected packets"
1104 " to the standard output.");
1108 #ifndef HAVE_LIBPCAP
1109 if (capture_option_specified)
1110 cmdarg_err("This version of Tethereal was not built with support for capturing packets.");
1117 /* We don't support capture filters when reading from a capture file
1118 (the BPF compiler doesn't support all link-layer types that we
1119 support in capture files we read). */
1121 if (cf_name != NULL) {
1122 if (capture_filter_specified) {
1123 cmdarg_err("Only read filters, not capture filters, "
1124 "can be specified when reading a capture file.");
1131 if (output_action != WRITE_TEXT) {
1132 cmdarg_err("Raw packet hex data can only be printed as text or PostScript");
1138 if (list_link_layer_types) {
1139 /* We're supposed to list the link-layer types for an interface;
1140 did the user also specify a capture file to be read? */
1142 /* Yes - that's bogus. */
1143 cmdarg_err("You can't specify -L and a capture file to be read.");
1146 /* No - did they specify a ring buffer option? */
1147 if (capture_opts.multi_files_on) {
1148 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
1152 /* If they didn't specify a "-w" flag, but specified a maximum capture
1153 file size, tell them that this doesn't work, and exit. */
1154 if (capture_opts.has_autostop_filesize && capture_opts.save_file == NULL) {
1155 cmdarg_err("Maximum capture file size specified, but "
1156 "capture isn't being saved to a file.");
1160 if (capture_opts.multi_files_on) {
1161 /* Multiple-file mode works only under certain conditions:
1162 a) it doesn't work if you're not saving the capture to a file;
1163 b) it doesn't work if you're writing to the standard output;
1164 c) it doesn't work if you're writing to a pipe;
1165 d) it only works if you're saving in libpcap format;
1166 e) it makes no sense if the maximum file size is set to "infinite"
1167 (XXX - shouldn't that be "if there is no stop criterion",
1168 as you might want to switch files based on a packet count
1170 if (capture_opts.save_file == NULL) {
1171 cmdarg_err("Multiple capture files requested, but "
1172 "the capture isn't being saved to a file.");
1175 if (strcmp(capture_opts.save_file, "-") == 0) {
1176 cmdarg_err("Multiple capture files requested, but "
1177 "the capture is being written to the standard output.");
1180 if (capture_opts.output_to_pipe) {
1181 cmdarg_err("Multiple capture files requested, but "
1182 "the capture file is a pipe.");
1185 if (out_file_type != WTAP_FILE_PCAP) {
1186 cmdarg_err("Multiple capture files requested, but "
1187 "the capture isn't being saved in libpcap format.");
1190 if (!capture_opts.has_autostop_filesize) {
1191 cmdarg_err("Multiple capture files requested, but "
1192 "no maximum capture file size was specified.");
1200 /* Start windows sockets */
1201 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1204 /* Notify all registered modules that have had any of their preferences
1205 changed either from one of the preferences file or from the command
1206 line that their preferences have changed. */
1209 /* At this point MATE will have registered its field array so we can
1210 have a tap filter with one of MATE's late-registered fields as part
1211 of the filter. We can now process all the "-z" arguments. */
1212 start_requested_stats();
1214 /* disabled protocols as per configuration file */
1215 if (gdp_path == NULL && dp_path == NULL) {
1216 set_disabled_protos_list();
1219 /* Build the column format array */
1220 col_setup(&cfile.cinfo, prefs->num_cols);
1221 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1222 cfile.cinfo.col_fmt[i] = get_column_format(i);
1223 cfile.cinfo.col_title[i] = g_strdup(get_column_title(i));
1224 cfile.cinfo.fmt_matx[i] = (gboolean *) g_malloc0(sizeof(gboolean) *
1226 get_column_format_matches(cfile.cinfo.fmt_matx[i], cfile.cinfo.col_fmt[i]);
1227 cfile.cinfo.col_data[i] = NULL;
1228 if (cfile.cinfo.col_fmt[i] == COL_INFO)
1229 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_INFO_LEN);
1231 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1232 cfile.cinfo.col_fence[i] = 0;
1233 cfile.cinfo.col_expr[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1234 cfile.cinfo.col_expr_val[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1237 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1240 for (j = 0; j < NUM_COL_FMTS; j++) {
1241 if (!cfile.cinfo.fmt_matx[i][j])
1244 if (cfile.cinfo.col_first[j] == -1)
1245 cfile.cinfo.col_first[j] = i;
1246 cfile.cinfo.col_last[j] = i;
1251 capture_opts_trim_snaplen(&capture_opts, MIN_PACKET_SIZE);
1252 capture_opts_trim_ring_num_files(&capture_opts);
1255 if (rfilter != NULL) {
1256 if (!dfilter_compile(rfilter, &rfcode)) {
1257 cmdarg_err("%s", dfilter_error_msg);
1259 #ifdef HAVE_PCAP_OPEN_DEAD
1263 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1265 if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1267 " Note: That display filter code looks like a valid capture filter;");
1269 " maybe you mixed them up?");
1278 cfile.rfcode = rfcode;
1280 if (print_packet_info) {
1281 /* If we're printing as text or PostScript, we have
1282 to create a print stream. */
1283 if (output_action == WRITE_TEXT) {
1284 switch (print_format) {
1287 print_stream = print_stream_text_stdio_new(stdout);
1291 print_stream = print_stream_ps_stdio_new(stdout);
1295 g_assert_not_reached();
1300 /* We have to dissect each packet if:
1302 we're printing information about each packet;
1304 we're using a read filter on the packets;
1306 we're using any taps. */
1307 do_dissection = print_packet_info || rfcode || have_tap_listeners();
1311 * We're reading a capture file.
1315 * Immediately relinquish any special privileges we have; we must not
1316 * be allowed to read any capture files the user running Tethereal
1319 relinquish_special_privs_perm();
1321 if (cf_open(&cfile, cf_name, FALSE, &err) != CF_OK) {
1326 /* Set timestamp precision; there should arguably be a command-line
1327 option to let the user set this. */
1328 switch(wtap_file_tsprecision(cfile.wth)) {
1329 case(WTAP_FILE_TSPREC_SEC):
1330 timestamp_set_precision(TS_PREC_AUTO_SEC);
1332 case(WTAP_FILE_TSPREC_DSEC):
1333 timestamp_set_precision(TS_PREC_AUTO_DSEC);
1335 case(WTAP_FILE_TSPREC_CSEC):
1336 timestamp_set_precision(TS_PREC_AUTO_CSEC);
1338 case(WTAP_FILE_TSPREC_MSEC):
1339 timestamp_set_precision(TS_PREC_AUTO_MSEC);
1341 case(WTAP_FILE_TSPREC_USEC):
1342 timestamp_set_precision(TS_PREC_AUTO_USEC);
1344 case(WTAP_FILE_TSPREC_NSEC):
1345 timestamp_set_precision(TS_PREC_AUTO_NSEC);
1348 g_assert_not_reached();
1351 /* Process the packets in the file */
1352 err = load_cap_file(&cfile, capture_opts.save_file, out_file_type);
1359 /* No capture file specified, so we're supposed to do a live capture
1360 (or get a list of link-layer types for a live capture device);
1361 do we have support for live captures? */
1368 cmdarg_err("WinPcap couldn't be found.");
1369 detailed_err = cant_load_winpcap_err("Tethereal");
1370 cmdarg_err_cont("%s", detailed_err);
1371 g_free(detailed_err);
1376 /* trim the interface name and exit if that failed */
1377 if (!capture_opts_trim_iface(&capture_opts,
1378 (prefs->capture_device) ? get_if_name(prefs->capture_device) : NULL)) {
1382 /* if requested, list the link layer types and exit */
1383 if (list_link_layer_types) {
1384 capture_opts_list_link_layer_types(&capture_opts);
1390 * The user didn't ask us not to print a count of packets as
1391 * they arrive, so do so.
1393 print_packet_counts = TRUE;
1396 /* For now, assume libpcap gives microsecond precision. */
1397 timestamp_set_precision(TS_PREC_AUTO_USEC);
1399 capture(out_file_type);
1401 if (capture_opts.multi_files_on) {
1405 /* No - complain. */
1406 cmdarg_err("This version of Tethereal was not built with support for capturing packets.");
1411 draw_tap_listeners(TRUE);
1418 /* Do the low-level work of a capture.
1419 Returns TRUE if it succeeds, FALSE otherwise. */
1421 static condition *volatile cnd_file_duration = NULL; /* this must be visible in process_packet */
1424 capture(int out_file_type)
1427 int volatile volatile_err = 0;
1428 int volatile inpkts = 0;
1430 char errmsg[1024+1];
1431 condition *volatile cnd_autostop_size = NULL;
1432 condition *volatile cnd_autostop_duration = NULL;
1435 void (*oldhandler)(int);
1436 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
1438 struct pcap_stat stats;
1443 /* Initialize all data structures used for dissection. */
1446 ld.wtap_linktype = WTAP_ENCAP_UNKNOWN;
1448 ld.packet_cb = capture_pcap_cb;
1451 /* open the "input file" from network interface or capture pipe */
1452 if (!capture_loop_open_input(&capture_opts, &ld, errmsg, sizeof(errmsg)))
1458 * We've opened the capture device, so we shouldn't need any special
1459 * privileges any more; relinquish those privileges.
1461 * XXX - if we have saved set-user-ID support, we should give up those
1462 * privileges immediately, and then reclaim them long enough to get
1463 * a list of network interfaces and to open one, and then give them
1464 * up again, so that stuff we do while processing the argument list,
1465 * reading the user's preferences, loading and starting plugins
1466 * (especially *user* plugins), etc. is done with the user's privileges,
1467 * not special privileges.
1469 relinquish_special_privs_perm();
1471 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
1472 if (!capture_loop_open_output(&capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
1476 /* init the input filter from the network interface (capture pipe will do nothing) */
1477 if(!capture_loop_init_filter(ld.pcap_h, ld.from_cap_pipe,
1478 capture_opts.iface, capture_opts.cfilter, errmsg, sizeof errmsg))
1483 /* open the wiretap part of the output file (the output file is already open) */
1484 if(!capture_loop_init_wiretap_output(&capture_opts, save_file_fd, &ld, errmsg, sizeof errmsg))
1489 /* Save the capture file name. */
1490 ld.save_file = capture_opts.save_file;
1493 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1494 SetConsoleCtrlHandler(capture_cleanup, TRUE);
1496 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
1498 XXX - deal with signal semantics on various UNIX platforms. Or just
1499 use "sigaction()" and be done with it? */
1500 signal(SIGTERM, capture_cleanup);
1501 signal(SIGINT, capture_cleanup);
1502 if ((oldhandler = signal(SIGHUP, capture_cleanup)) != SIG_DFL)
1503 signal(SIGHUP, oldhandler);
1506 /* Catch SIGINFO and, if we get it and we're capturing to a file in
1507 quiet mode, report the number of packets we've captured. */
1508 signal(SIGINFO, report_counts_siginfo);
1509 #endif /* SIGINFO */
1512 /* Let the user know what interface was chosen. */
1513 descr = get_interface_descriptive_name(capture_opts.iface);
1514 fprintf(stderr, "Capturing on %s\n", descr);
1517 /* initialize capture stop conditions */
1518 init_capture_stop_conditions();
1519 /* create stop conditions */
1520 if (capture_opts.has_autostop_filesize)
1521 cnd_autostop_size = cnd_new((const char*)CND_CLASS_CAPTURESIZE,
1522 (long)capture_opts.autostop_filesize * 1024);
1523 if (capture_opts.has_autostop_duration)
1524 cnd_autostop_duration = cnd_new((const char*)CND_CLASS_TIMEOUT,
1525 (gint32)capture_opts.autostop_duration);
1527 if (capture_opts.multi_files_on && capture_opts.has_file_duration)
1528 cnd_file_duration = cnd_new(CND_CLASS_TIMEOUT,
1529 capture_opts.file_duration);
1531 if (!setjmp(ld.stopenv)) {
1533 ld.packet_count = 0;
1538 /* We need to be careful with automatic variables defined in the
1539 outer scope which are changed inside the loop. Most compilers
1540 don't try to roll them back to their original values after the
1541 longjmp which causes the loop to finish, but all that the
1542 standards say is that their values are indeterminate. If we
1543 don't want them to be rolled back, we should define them with the
1544 volatile attribute (paraphrasing W. Richard Stevens, Advanced
1545 Programming in the UNIX Environment, p. 178).
1547 The "err" variable causes a particular problem. If we give it
1548 the volatile attribute, then when we pass a reference to it (as
1549 in "&err") to a function, GCC warns: "passing arg <n> of
1550 <function> discards qualifiers from pointer target type".
1551 Therefore within the loop and just beyond we don't use "err".
1552 Within the loop we define "loop_err", and assign its value to
1553 "volatile_err", which is in the outer scope and is checked when
1556 We also define "packet_count_prev" here to keep things tidy,
1557 since it's used only inside the loop. If it were defined in the
1558 outer scope, GCC would give a warning (unnecessary in this case)
1559 that it might be clobbered, and we'd need to give it the volatile
1560 attribute to suppress the warning. */
1563 int packet_count_prev = 0;
1565 if (cnd_autostop_size == NULL && cnd_autostop_duration == NULL) {
1566 /* We're not stopping at a particular capture file size, and we're
1567 not stopping after some particular amount of time has expired,
1568 so either we have no stop condition or the only stop condition
1569 is a maximum packet count.
1571 If there's no maximum packet count, pass it -1, meaning "until
1572 you run out of packets in the bufferful you read". Otherwise,
1573 pass it the number of packets we have left to capture.
1575 We don't call "pcap_loop()" as, if we're saving to a file that's
1576 a FIFO, we want to flush the FIFO after we're done processing
1577 this libpcap bufferful of packets, so that the program
1578 reading the FIFO sees the packets immediately and doesn't get
1579 any partial packet, forcing it to block in the middle of reading
1581 if (capture_opts.autostop_packets == 0)
1584 if (ld.packet_count >= capture_opts.autostop_packets) {
1585 /* XXX do we need this test here? */
1586 /* It appears there's nothing more to capture. */
1589 pcap_cnt = capture_opts.autostop_packets - ld.packet_count;
1592 /* We need to check the capture file size or the timeout after
1597 if (ld.from_cap_pipe) {
1598 inpkts = cap_pipe_dispatch(ld.cap_pipe_fd, &ld, &ld.cap_pipe_hdr, &ld.cap_pipe_rechdr, pcap_data,
1599 errmsg, sizeof errmsg);
1602 inpkts = pcap_dispatch(ld.pcap_h, pcap_cnt, capture_pcap_cb, (u_char *) &ld);
1604 /* Error from "pcap_dispatch()", or error or "no more packets" from
1605 "cap_pipe_dispatch(). */
1607 } else if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
1608 /* The specified capture time has elapsed; stop the capture. */
1610 } else if (inpkts > 0) {
1611 if (capture_opts.autostop_packets != 0 &&
1612 ld.packet_count >= capture_opts.autostop_packets) {
1613 /* The specified number of packets have been captured and have
1614 passed both any capture filter in effect and any read filter
1617 } else if (cnd_autostop_size != NULL &&
1618 cnd_eval(cnd_autostop_size,
1619 (guint32)wtap_get_bytes_dumped(ld.wtap_pdh))) {
1620 /* We're saving the capture to a file, and the capture file reached
1621 its maximum size. */
1622 if (capture_opts.multi_files_on) {
1623 /* Switch to the next ringbuffer file */
1624 if (ringbuf_switch_file(&ld.wtap_pdh, &capture_opts.save_file, &save_file_fd, &loop_err)) {
1625 /* File switch succeeded: reset the condition */
1626 cnd_reset(cnd_autostop_size);
1627 if (cnd_file_duration) {
1628 cnd_reset(cnd_file_duration);
1631 /* File switch failed: stop here */
1632 volatile_err = loop_err;
1636 /* No ringbuffer - just stop. */
1640 if (capture_opts.output_to_pipe) {
1641 if (ld.packet_count > packet_count_prev) {
1642 wtap_dump_flush(ld.wtap_pdh);
1643 packet_count_prev = ld.packet_count;
1647 } /* while (ld.go) */
1649 /* delete stop conditions */
1650 if (cnd_autostop_size != NULL)
1651 cnd_delete(cnd_autostop_size);
1652 if (cnd_autostop_duration != NULL)
1653 cnd_delete(cnd_autostop_duration);
1654 if (cnd_file_duration != NULL)
1655 cnd_delete(cnd_file_duration);
1657 if (print_packet_counts) {
1658 /* We're printing packet counts to stderr.
1659 Send a newline so that we move to the line after the packet count. */
1660 fprintf(stderr, "\n");
1663 /* If we got an error while capturing, report it. */
1666 if (ld.from_cap_pipe) {
1667 if (ld.cap_pipe_err == PIPERR) {
1668 cmdarg_err("Error while capturing packets: %s",
1674 cmdarg_err("Error while capturing packets: %s",
1675 pcap_geterr(ld.pcap_h));
1679 if (volatile_err == 0)
1682 show_capture_file_io_error(capture_opts.save_file, volatile_err, FALSE);
1686 if (capture_opts.save_file != NULL) {
1687 /* We're saving to a file or files; close all files. */
1688 close_ok = capture_loop_close_output(&capture_opts, &ld, &err);
1690 /* If we've displayed a message about a write error, there's no point
1691 in displaying another message about an error on close. */
1692 if (!close_ok && write_ok)
1693 show_capture_file_io_error(capture_opts.save_file, err, TRUE);
1697 if (ld.from_cap_pipe && ld.cap_pipe_fd >= 0)
1698 eth_close(ld.cap_pipe_fd);
1702 /* Get the capture statistics, and, if any packets were dropped, report
1704 if (pcap_stats(ld.pcap_h, &stats) >= 0) {
1705 if (stats.ps_drop != 0) {
1706 fprintf(stderr, "%u packets dropped\n", stats.ps_drop);
1709 cmdarg_err("Can't get packet-drop statistics: %s",
1710 pcap_geterr(ld.pcap_h));
1712 pcap_close(ld.pcap_h);
1715 /* Report the number of captured packets if not reported during capture
1716 and we are saving to a file. */
1722 if (capture_opts.multi_files_on) {
1723 ringbuf_error_cleanup();
1725 g_free(capture_opts.save_file);
1726 capture_opts.save_file = NULL;
1727 cmdarg_err("%s", errmsg);
1729 if (ld.from_cap_pipe) {
1730 if (ld.cap_pipe_fd >= 0)
1731 eth_close(ld.cap_pipe_fd);
1735 if (ld.pcap_h != NULL)
1736 pcap_close(ld.pcap_h);
1743 capture_pcap_cb(u_char *user, const struct pcap_pkthdr *phdr,
1746 struct wtap_pkthdr whdr;
1747 union wtap_pseudo_header pseudo_header;
1748 loop_data *ld = (loop_data *) user;
1753 /* Convert from libpcap to Wiretap format.
1754 If that fails, ignore the packet (wtap_process_pcap_packet has
1755 written an error message). */
1756 pd = wtap_process_pcap_packet(ld->wtap_linktype, phdr, pd, &pseudo_header,
1763 * Prevent a SIGINFO handler from writing to stdout while we're
1764 * doing so; instead, have it just set a flag telling us to print
1765 * that information when we're done.
1768 #endif /* SIGINFO */
1770 /* The current packet may have arrived after a very long silence,
1771 * way past the time to switch files. In order not to have
1772 * the first packet of a new series of events as the last
1773 * [or only] packet in the file, switch before writing!
1775 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
1776 /* time elapsed for this ring file, switch to the next */
1777 if (ringbuf_switch_file(&ld->wtap_pdh, &ld->save_file, &save_file_fd, &loop_err)) {
1778 /* File switch succeeded: reset the condition */
1779 cnd_reset(cnd_file_duration);
1781 /* File switch failed: stop here */
1782 /* XXX - we should do something with "loop_err" */
1787 if (!process_packet(&cfile, ld->wtap_pdh, 0, &whdr, &pseudo_header, pd, &err)) {
1788 /* Error writing to a capture file */
1789 if (print_packet_counts) {
1790 /* We're printing counts of packets captured; move to the line after
1792 fprintf(stderr, "\n");
1794 show_capture_file_io_error(ld->save_file, err, FALSE);
1795 pcap_close(ld->pcap_h);
1796 wtap_dump_close(ld->wtap_pdh, &err);
1802 * Allow SIGINFO handlers to write.
1807 * If a SIGINFO handler asked us to write out capture counts, do so.
1811 #endif /* SIGINFO */
1816 capture_cleanup(DWORD ctrltype _U_)
1818 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1819 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1820 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1821 like SIGTERM at least when the machine's shutting down.
1823 For now, we handle them all as indications that we should clean up
1824 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
1827 However, as handlers run in a new thread, we can't just longjmp
1828 out; we have to set "ld.go" to FALSE, and must return TRUE so that
1829 no other handler - such as one that would terminate the process -
1832 XXX - for some reason, typing ^C to Tethereal, if you run this in
1833 a Cygwin console window in at least some versions of Cygwin,
1834 causes Tethereal to terminate immediately; this routine gets
1835 called, but the main loop doesn't get a chance to run and
1836 exit cleanly, at least if this is compiled with Microsoft Visual
1837 C++ (i.e., it's a property of the Cygwin console window or Bash;
1838 it happens if Tethereal is not built with Cygwin - for all I know,
1839 building it with Cygwin may make the problem go away). */
1845 capture_cleanup(int signum _U_)
1847 /* Longjmp back to the starting point; "pcap_dispatch()", on many
1848 UNIX platforms, just keeps looping if it gets EINTR, so if we set
1849 "ld.go" to FALSE and return, we won't break out of it and quit
1851 longjmp(ld.stopenv, 1);
1859 /* XXX - if we use sigaction, this doesn't have to be done.
1860 (Yes, this isn't necessary on BSD, but just in case a system
1861 where "signal()" has AT&T semantics adopts SIGINFO....) */
1862 signal(SIGINFO, report_counts_siginfo);
1863 #endif /* SIGINFO */
1865 if (!print_packet_counts) {
1866 /* Report the count only if we aren't printing a packet count
1867 as packets arrive. */
1868 fprintf(stderr, "%u packets captured\n", ld.packet_count);
1871 infoprint = FALSE; /* we just reported it */
1872 #endif /* SIGINFO */
1877 report_counts_siginfo(int signum _U_)
1879 int sav_errno = errno;
1880 /* If we've been told to delay printing, just set a flag asking
1881 that we print counts (if we're supposed to), otherwise print
1882 the count of packets captured (if we're supposed to). */
1889 #endif /* SIGINFO */
1890 #endif /* HAVE_LIBPCAP */
1893 load_cap_file(capture_file *cf, char *save_file, int out_file_type)
1896 int snapshot_length;
1901 char *save_file_string = NULL;
1903 linktype = wtap_file_encap(cf->wth);
1904 if (save_file != NULL) {
1905 /* Get a string that describes what we're writing to */
1906 save_file_string = output_file_description(save_file);
1908 /* Set up to write to the capture file. */
1909 snapshot_length = wtap_snapshot_length(cf->wth);
1910 if (snapshot_length == 0) {
1911 /* Snapshot length of input file not known. */
1912 snapshot_length = WTAP_MAX_PACKET_SIZE;
1914 pdh = wtap_dump_open(save_file, out_file_type,
1915 linktype, snapshot_length, FALSE /* compressed */, &err);
1918 /* We couldn't set up to write to the capture file. */
1921 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
1922 cmdarg_err("Capture files can't be written in that format.");
1925 case WTAP_ERR_UNSUPPORTED_ENCAP:
1926 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
1927 cmdarg_err("The capture file being read can't be written in "
1931 case WTAP_ERR_CANT_OPEN:
1932 cmdarg_err("The %s couldn't be created for some "
1933 "unknown reason.", save_file_string);
1936 case WTAP_ERR_SHORT_WRITE:
1937 cmdarg_err("A full header couldn't be written to the %s.",
1942 cmdarg_err("The %s could not be created: %s.", save_file_string,
1943 wtap_strerror(err));
1949 if (print_packet_info) {
1950 if (!write_preamble(cf)) {
1952 show_print_file_io_error(err);
1958 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
1959 if (!process_packet(cf, pdh, data_offset, wtap_phdr(cf->wth),
1960 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
1962 /* Error writing to a capture file */
1963 show_capture_file_io_error(save_file, err, FALSE);
1964 wtap_dump_close(pdh, &err);
1969 /* Print a message noting that the read failed somewhere along the line. */
1972 case WTAP_ERR_UNSUPPORTED_ENCAP:
1973 cmdarg_err("\"%s\" has a packet with a network type that Tethereal doesn't support.\n(%s)",
1974 cf->filename, err_info);
1977 case WTAP_ERR_CANT_READ:
1978 cmdarg_err("An attempt to read from \"%s\" failed for some unknown reason.",
1982 case WTAP_ERR_SHORT_READ:
1983 cmdarg_err("\"%s\" appears to have been cut short in the middle of a packet.",
1987 case WTAP_ERR_BAD_RECORD:
1988 cmdarg_err("\"%s\" appears to be damaged or corrupt.\n(%s)",
1989 cf->filename, err_info);
1993 cmdarg_err("An error occurred while reading \"%s\": %s.",
1994 cf->filename, wtap_strerror(err));
1997 if (save_file != NULL) {
1998 /* Now close the capture file. */
1999 if (!wtap_dump_close(pdh, &err))
2000 show_capture_file_io_error(save_file, err, TRUE);
2003 if (save_file != NULL) {
2004 /* Now close the capture file. */
2005 if (!wtap_dump_close(pdh, &err))
2006 show_capture_file_io_error(save_file, err, TRUE);
2008 if (print_packet_info) {
2009 if (!write_finale()) {
2011 show_print_file_io_error(err);
2018 wtap_close(cf->wth);
2021 if (save_file_string != NULL)
2022 g_free(save_file_string);
2028 fill_in_fdata(frame_data *fdata, capture_file *cf,
2029 const struct wtap_pkthdr *phdr, long offset)
2034 fdata->num = cf->count;
2035 fdata->pkt_len = phdr->len;
2036 cum_bytes += phdr->len;
2037 fdata->cum_bytes = cum_bytes;
2038 fdata->cap_len = phdr->caplen;
2039 fdata->file_off = offset;
2040 fdata->lnk_t = phdr->pkt_encap;
2041 fdata->abs_ts = *((nstime_t *) &phdr->ts);
2042 fdata->flags.passed_dfilter = 0;
2043 fdata->flags.encoding = CHAR_ASCII;
2044 fdata->flags.visited = 0;
2045 fdata->flags.marked = 0;
2046 fdata->flags.ref_time = 0;
2047 fdata->color_filter = NULL;
2049 /* If we don't have the time stamp of the first packet in the
2050 capture, it's because this is the first packet. Save the time
2051 stamp of this packet as the time stamp of the first packet. */
2052 if (nstime_is_zero(&first_ts)) {
2053 first_ts = fdata->abs_ts;
2056 /* If we don't have the time stamp of the previous displayed packet,
2057 it's because this is the first displayed packet. Save the time
2058 stamp of this packet as the time stamp of the previous displayed
2060 if (nstime_is_zero(&prev_ts)) {
2061 prev_ts = fdata->abs_ts;
2064 /* Get the time elapsed between the first packet and this packet. */
2065 nstime_delta(&fdata->rel_ts, &fdata->abs_ts, &first_ts);
2067 /* If it's greater than the current elapsed time, set the elapsed time
2068 to it (we check for "greater than" so as not to be confused by
2069 time moving backwards). */
2070 if ((gint32)cf->elapsed_time.secs < fdata->rel_ts.secs
2071 || ((gint32)cf->elapsed_time.secs == fdata->rel_ts.secs && (gint32)cf->elapsed_time.nsecs < fdata->rel_ts.nsecs)) {
2072 cf->elapsed_time = fdata->rel_ts;
2075 /* Get the time elapsed between the previous displayed packet and
2077 nstime_delta(&fdata->del_ts, &fdata->abs_ts, &prev_ts);
2078 prev_ts = fdata->abs_ts;
2081 /* Free up all data attached to a "frame_data" structure. */
2083 clear_fdata(frame_data *fdata)
2086 g_slist_free(fdata->pfd);
2090 process_packet(capture_file *cf, wtap_dumper *pdh, long offset,
2091 const struct wtap_pkthdr *whdr,
2092 union wtap_pseudo_header *pseudo_header, const guchar *pd,
2096 gboolean create_proto_tree;
2097 epan_dissect_t *edt;
2100 /* Count this packet. */
2103 /* If we're going to print packet information, or we're going to
2104 run a read filter, or we're going to process taps, set up to
2105 do a dissection and do so. */
2106 if (do_dissection) {
2107 fill_in_fdata(&fdata, cf, whdr, offset);
2109 if (print_packet_info) {
2110 /* Grab any resolved addresses */
2112 if (g_resolv_flags) {
2113 host_name_lookup_process(NULL);
2118 if (cf->rfcode || verbose || num_tap_filters!=0)
2119 create_proto_tree = TRUE;
2121 create_proto_tree = FALSE;
2122 /* The protocol tree will be "visible", i.e., printed, only if we're
2123 printing packet details, which is true if we're printing stuff
2124 ("print_packet_info" is true) and we're in verbose mode ("verbose"
2126 edt = epan_dissect_new(create_proto_tree, print_packet_info && verbose);
2128 /* If we're running a read filter, prime the epan_dissect_t with that
2131 epan_dissect_prime_dfilter(edt, cf->rfcode);
2133 tap_queue_init(edt);
2135 /* We only need the columns if we're printing packet info but we're
2136 *not* verbose; in verbose mode, we print the protocol tree, not
2137 the protocol summary. */
2138 epan_dissect_run(edt, pseudo_header, pd, &fdata,
2139 (print_packet_info && !verbose) ? &cf->cinfo : NULL);
2141 tap_push_tapped_queue(edt);
2143 /* Run the read filter if we have one. */
2145 passed = dfilter_apply_edt(cf->rfcode, edt);
2149 /* We're not running a display filter and we're not printing any
2150 packet information, so we don't need to do a dissection, and all
2151 packets are processed. */
2157 /* Count this packet. */
2162 /* Process this packet. */
2164 /* We're writing to a capture file; write this packet. */
2165 if (!wtap_dump(pdh, whdr, pseudo_header, pd, err))
2168 if (print_packet_counts) {
2169 /* We're printing packet counts. */
2170 if (ld.packet_count != 0) {
2171 fprintf(stderr, "\r%u ", ld.packet_count);
2172 /* stderr could be line buffered */
2178 if (print_packet_info) {
2179 /* We're printing packet information; print the information for
2181 print_packet(cf, edt);
2183 /* The ANSI C standard does not appear to *require* that a line-buffered
2184 stream be flushed to the host environment whenever a newline is
2185 written, it just says that, on such a stream, characters "are
2186 intended to be transmitted to or from the host environment as a
2187 block when a new-line character is encountered".
2189 The Visual C++ 6.0 C implementation doesn't do what is intended;
2190 even if you set a stream to be line-buffered, it still doesn't
2191 flush the buffer at the end of every line.
2193 So, if the "-l" flag was specified, we flush the standard output
2194 at the end of a packet. This will do the right thing if we're
2195 printing packet summary lines, and, as we print the entire protocol
2196 tree for a single packet without waiting for anything to happen,
2197 it should be as good as line-buffered mode if we're printing
2198 protocol trees. (The whole reason for the "-l" flag in either
2199 tcpdump or Tethereal is to allow the output of a live capture to
2200 be piped to a program or script and to have that script see the
2201 information for the packet as soon as it's printed, rather than
2202 having to wait until a standard I/O buffer fills up. */
2206 if (ferror(stdout)) {
2207 show_print_file_io_error(errno);
2213 if (do_dissection) {
2214 epan_dissect_free(edt);
2215 clear_fdata(&fdata);
2221 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
2223 char *save_file_string;
2225 save_file_string = output_file_description(fname);
2230 cmdarg_err("Not all the packets could be written to the %s because there is "
2231 "no space left on the file system.",
2237 cmdarg_err("Not all the packets could be written to the %s because you are "
2238 "too close to, or over your disk quota.",
2243 case WTAP_ERR_CANT_CLOSE:
2244 cmdarg_err("The %s couldn't be closed for some unknown reason.",
2248 case WTAP_ERR_SHORT_WRITE:
2249 cmdarg_err("Not all the packets could be written to the %s.",
2255 cmdarg_err("The %s could not be closed: %s.",
2256 save_file_string, wtap_strerror(err));
2258 cmdarg_err("An error occurred while writing to the %s: %s.",
2259 save_file_string, wtap_strerror(err));
2263 g_free(save_file_string);
2267 write_preamble(capture_file *cf)
2269 switch (output_action) {
2272 return print_preamble(print_stream, cf->filename);
2277 write_pdml_preamble(stdout);
2279 write_psml_preamble(stdout);
2280 return !ferror(stdout);
2283 g_assert_not_reached();
2289 get_line_buf(size_t len)
2291 static char *line_bufp = NULL;
2292 static size_t line_buf_len = 256;
2293 size_t new_line_buf_len;
2295 for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
2296 new_line_buf_len *= 2)
2298 if (line_bufp == NULL) {
2299 line_buf_len = new_line_buf_len;
2300 line_bufp = g_malloc(line_buf_len + 1);
2302 if (new_line_buf_len > line_buf_len) {
2303 line_buf_len = new_line_buf_len;
2304 line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2311 print_columns(capture_file *cf)
2318 line_bufp = get_line_buf(256);
2321 for (i = 0; i < cf->cinfo.num_cols; i++) {
2322 switch (cf->cinfo.col_fmt[i]) {
2326 * Don't print this if we're doing a live capture from a network
2327 * interface - if we're doing a live capture, you won't be
2328 * able to look at the capture in the future (it's not being
2329 * saved anywhere), so the frame numbers are unlikely to be
2332 * (XXX - it might be nice to be able to save and print at
2333 * the same time, sort of like an "Update list of packets
2334 * in real time" capture in Ethereal.)
2336 if (capture_opts.iface != NULL)
2339 column_len = strlen(cf->cinfo.col_data[i]);
2342 line_bufp = get_line_buf(buf_offset + column_len);
2343 sprintf(line_bufp + buf_offset, "%3s", cf->cinfo.col_data[i]);
2349 case COL_ABS_DATE_TIME: /* XXX - wider */
2350 column_len = strlen(cf->cinfo.col_data[i]);
2351 if (column_len < 10)
2353 line_bufp = get_line_buf(buf_offset + column_len);
2354 sprintf(line_bufp + buf_offset, "%10s", cf->cinfo.col_data[i]);
2360 case COL_DEF_DL_SRC:
2361 case COL_RES_DL_SRC:
2362 case COL_UNRES_DL_SRC:
2363 case COL_DEF_NET_SRC:
2364 case COL_RES_NET_SRC:
2365 case COL_UNRES_NET_SRC:
2366 column_len = strlen(cf->cinfo.col_data[i]);
2367 if (column_len < 12)
2369 line_bufp = get_line_buf(buf_offset + column_len);
2370 sprintf(line_bufp + buf_offset, "%12s", cf->cinfo.col_data[i]);
2376 case COL_DEF_DL_DST:
2377 case COL_RES_DL_DST:
2378 case COL_UNRES_DL_DST:
2379 case COL_DEF_NET_DST:
2380 case COL_RES_NET_DST:
2381 case COL_UNRES_NET_DST:
2382 column_len = strlen(cf->cinfo.col_data[i]);
2383 if (column_len < 12)
2385 line_bufp = get_line_buf(buf_offset + column_len);
2386 sprintf(line_bufp + buf_offset, "%-12s", cf->cinfo.col_data[i]);
2390 column_len = strlen(cf->cinfo.col_data[i]);
2391 line_bufp = get_line_buf(buf_offset + column_len);
2392 strcat(line_bufp + buf_offset, cf->cinfo.col_data[i]);
2395 buf_offset += column_len;
2396 if (i != cf->cinfo.num_cols - 1) {
2398 * This isn't the last column, so we need to print a
2399 * separator between this column and the next.
2401 * If we printed a network source and are printing a
2402 * network destination of the same type next, separate
2403 * them with "->"; if we printed a network destination
2404 * and are printing a network source of the same type
2405 * next, separate them with "<-"; otherwise separate them
2408 * We add enough space to the buffer for " <- " or " -> ",
2409 * even if we're only adding " ".
2411 line_bufp = get_line_buf(buf_offset + 4);
2412 switch (cf->cinfo.col_fmt[i]) {
2417 switch (cf->cinfo.col_fmt[i + 1]) {
2422 strcat(line_bufp + buf_offset, " -> ");
2427 strcat(line_bufp + buf_offset, " ");
2433 case COL_DEF_DL_SRC:
2434 case COL_RES_DL_SRC:
2435 case COL_UNRES_DL_SRC:
2436 switch (cf->cinfo.col_fmt[i + 1]) {
2438 case COL_DEF_DL_DST:
2439 case COL_RES_DL_DST:
2440 case COL_UNRES_DL_DST:
2441 strcat(line_bufp + buf_offset, " -> ");
2446 strcat(line_bufp + buf_offset, " ");
2452 case COL_DEF_NET_SRC:
2453 case COL_RES_NET_SRC:
2454 case COL_UNRES_NET_SRC:
2455 switch (cf->cinfo.col_fmt[i + 1]) {
2457 case COL_DEF_NET_DST:
2458 case COL_RES_NET_DST:
2459 case COL_UNRES_NET_DST:
2460 strcat(line_bufp + buf_offset, " -> ");
2465 strcat(line_bufp + buf_offset, " ");
2474 switch (cf->cinfo.col_fmt[i + 1]) {
2479 strcat(line_bufp + buf_offset, " <- ");
2484 strcat(line_bufp + buf_offset, " ");
2490 case COL_DEF_DL_DST:
2491 case COL_RES_DL_DST:
2492 case COL_UNRES_DL_DST:
2493 switch (cf->cinfo.col_fmt[i + 1]) {
2495 case COL_DEF_DL_SRC:
2496 case COL_RES_DL_SRC:
2497 case COL_UNRES_DL_SRC:
2498 strcat(line_bufp + buf_offset, " <- ");
2503 strcat(line_bufp + buf_offset, " ");
2509 case COL_DEF_NET_DST:
2510 case COL_RES_NET_DST:
2511 case COL_UNRES_NET_DST:
2512 switch (cf->cinfo.col_fmt[i + 1]) {
2514 case COL_DEF_NET_SRC:
2515 case COL_RES_NET_SRC:
2516 case COL_UNRES_NET_SRC:
2517 strcat(line_bufp + buf_offset, " <- ");
2522 strcat(line_bufp + buf_offset, " ");
2529 strcat(line_bufp + buf_offset, " ");
2535 return print_line(print_stream, 0, line_bufp);
2539 print_packet(capture_file *cf, epan_dissect_t *edt)
2541 print_args_t print_args;
2544 /* Print the information in the protocol tree. */
2545 switch (output_action) {
2548 print_args.to_file = TRUE;
2549 print_args.format = print_format;
2550 print_args.print_summary = !verbose;
2551 print_args.print_hex = verbose && print_hex;
2552 print_args.print_formfeed = FALSE;
2553 print_args.print_dissections = verbose ? print_dissections_expanded : print_dissections_none;
2555 /* init the packet range */
2556 packet_range_init(&print_args.range);
2558 if (!proto_tree_print(&print_args, edt, print_stream))
2561 /* "print_hex_data()" will put out a leading blank line, as well
2562 as a trailing one; print one here, to separate the packets,
2563 only if "print_hex_data()" won't be called. */
2564 if (!print_line(print_stream, 0, ""))
2570 proto_tree_write_pdml(edt, stdout);
2572 return !ferror(stdout);
2575 /* Just fill in the columns. */
2576 epan_dissect_fill_in_columns(edt);
2578 /* Now print them. */
2579 switch (output_action) {
2582 if (!print_columns(cf))
2587 proto_tree_write_psml(edt, stdout);
2588 return !ferror(stdout);
2592 if (!print_hex_data(print_stream, edt))
2594 if (!print_line(print_stream, 0, ""))
2603 switch (output_action) {
2606 return print_finale(print_stream);
2611 write_pdml_finale(stdout);
2613 write_psml_finale(stdout);
2614 return !ferror(stdout);
2617 g_assert_not_reached();
2623 show_print_file_io_error(int err)
2628 cmdarg_err("Not all the packets could be printed because there is "
2629 "no space left on the file system.");
2634 cmdarg_err("Not all the packets could be printed because you are "
2635 "too close to, or over your disk quota.");
2640 cmdarg_err("An error occurred while printing packets: %s.",
2647 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
2651 static char errmsg_errno[1024+1];
2654 /* Wiretap error. */
2657 case WTAP_ERR_NOT_REGULAR_FILE:
2658 errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
2661 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
2662 /* Seen only when opening a capture file for reading. */
2663 errmsg = "The file \"%s\" isn't a capture file in a format Tethereal understands.";
2666 case WTAP_ERR_UNSUPPORTED:
2667 /* Seen only when opening a capture file for reading. */
2668 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2669 "The file \"%%s\" isn't a capture file in a format Tethereal understands.\n"
2672 errmsg = errmsg_errno;
2675 case WTAP_ERR_CANT_WRITE_TO_PIPE:
2676 /* Seen only when opening a capture file for writing. */
2677 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2678 "The file \"%%s\" is a pipe, and %s capture files can't be "
2679 "written to a pipe.", wtap_file_type_string(file_type));
2680 errmsg = errmsg_errno;
2683 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2684 /* Seen only when opening a capture file for writing. */
2685 errmsg = "Tethereal doesn't support writing capture files in that format.";
2688 case WTAP_ERR_UNSUPPORTED_ENCAP:
2690 errmsg = "Tethereal can't save this capture in that format.";
2692 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2693 "The file \"%%s\" is a capture for a network type that Tethereal doesn't support.\n"
2696 errmsg = errmsg_errno;
2700 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2702 errmsg = "Tethereal can't save this capture in that format.";
2704 errmsg = "The file \"%s\" is a capture for a network type that Tethereal doesn't support.";
2707 case WTAP_ERR_BAD_RECORD:
2708 /* Seen only when opening a capture file for reading. */
2709 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2710 "The file \"%%s\" appears to be damaged or corrupt.\n"
2713 errmsg = errmsg_errno;
2716 case WTAP_ERR_CANT_OPEN:
2718 errmsg = "The file \"%s\" could not be created for some unknown reason.";
2720 errmsg = "The file \"%s\" could not be opened for some unknown reason.";
2723 case WTAP_ERR_SHORT_READ:
2724 errmsg = "The file \"%s\" appears to have been cut short"
2725 " in the middle of a packet or other data.";
2728 case WTAP_ERR_SHORT_WRITE:
2729 errmsg = "A full header couldn't be written to the file \"%s\".";
2733 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2734 "The file \"%%s\" could not be %s: %s.",
2735 for_writing ? "created" : "opened",
2736 wtap_strerror(err));
2737 errmsg = errmsg_errno;
2741 errmsg = file_open_error_message(err, for_writing);
2746 * Open/create errors are reported with an console message in Tethereal.
2749 open_failure_message(const char *filename, int err, gboolean for_writing)
2751 fprintf(stderr, "tethereal: ");
2752 fprintf(stderr, file_open_error_message(err, for_writing), filename);
2753 fprintf(stderr, "\n");
2757 cf_open(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
2761 char err_msg[2048+1];
2763 wth = wtap_open_offline(fname, err, &err_info, FALSE);
2767 /* The open succeeded. Fill in the information for this file. */
2769 /* Initialize all data structures used for dissection. */
2773 cf->f_datalen = 0; /* not used, but set it anyway */
2775 /* Set the file name because we need it to set the follow stream filter.
2776 XXX - is that still true? We need it for other reasons, though,
2778 cf->filename = g_strdup(fname);
2780 /* Indicate whether it's a permanent or temporary file. */
2781 cf->is_tempfile = is_tempfile;
2783 /* If it's a temporary capture buffer file, mark it as not saved. */
2784 cf->user_saved = !is_tempfile;
2786 cf->cd_t = wtap_file_type(cf->wth);
2788 cf->drops_known = FALSE;
2790 cf->snap = wtap_snapshot_length(cf->wth);
2791 if (cf->snap == 0) {
2792 /* Snapshot length not known. */
2793 cf->has_snap = FALSE;
2794 cf->snap = WTAP_MAX_PACKET_SIZE;
2796 cf->has_snap = TRUE;
2797 nstime_set_zero(&cf->elapsed_time);
2798 nstime_set_zero(&first_ts);
2799 nstime_set_zero(&prev_ts);
2804 g_snprintf(err_msg, sizeof err_msg,
2805 cf_open_error_message(*err, err_info, FALSE, 0), fname);
2806 cmdarg_err("%s", err_msg);
2812 * General errors are reported with an console message in Tethereal.
2815 failure_message(const char *msg_format, va_list ap)
2817 fprintf(stderr, "tethereal: ");
2818 vfprintf(stderr, msg_format, ap);
2819 fprintf(stderr, "\n");
2823 * Read errors are reported with an console message in Tethereal.
2826 read_failure_message(const char *filename, int err)
2828 cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
2829 filename, strerror(err));
2833 * Report an error in command-line arguments.
2836 cmdarg_err(const char *fmt, ...)
2841 fprintf(stderr, "tethereal: ");
2842 vfprintf(stderr, fmt, ap);
2843 fprintf(stderr, "\n");
2848 * Report additional information for an error in command-line arguments.
2851 cmdarg_err_cont(const char *fmt, ...)
2856 vfprintf(stderr, fmt, ap);
2857 fprintf(stderr, "\n");
2862 /****************************************************************************************************************/
2863 /* sync pipe "dummies", needed for capture_loop.c */
2867 /** the child has opened a new capture file, notify the parent */
2869 sync_pipe_filename_to_parent(const char *filename)
2871 /* shouldn't happen */
2875 /** the child captured some new packets, notify the parent */
2877 sync_pipe_packet_count_to_parent(int packet_count)
2879 /* shouldn't happen */
2883 /** the child stopped capturing, notify the parent */
2885 sync_pipe_drops_to_parent(int drops)
2887 /* shouldn't happen */
2891 /** the child encountered an error, notify the parent */
2893 sync_pipe_errmsg_to_parent(const char *errmsg)
2898 #endif /* HAVE_LIBPCAP */
2901 /****************************************************************************************************************/
2902 /* simple_dialog "dummies", needed for capture_loop.c */
2907 char *simple_dialog_primary_start(void)
2912 char *simple_dialog_primary_end(void)
2918 /* XXX - do we need to convert the string for the console? */
2920 simple_dialog_format_message(const char *msg)
2926 #if GTK_MAJOR_VERSION < 2
2927 str = g_strdup(msg);
2929 str = xml_escape(msg);
2937 #endif /* HAVE_LIBPCAP */