6 * Wireshark - Network traffic analyzer
7 * By Gerald Combs <gerald@wireshark.org>
8 * Copyright 1998 Gerald Combs
10 * This program is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU General Public License
12 * as published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
44 #include <epan/epan.h>
45 #include <epan/filesystem.h>
48 #include "color_filters.h"
50 #include <epan/column.h>
51 #include <epan/packet.h>
52 #include <epan/column-utils.h>
53 #include "packet-range.h"
60 #include <epan/prefs.h>
61 #include <epan/dfilter/dfilter.h>
62 #include <epan/epan_dissect.h>
64 #include <epan/dissectors/packet-data.h>
65 #include <epan/dissectors/packet-ber.h>
66 #include <epan/timestamp.h>
67 #include <epan/dfilter/dfilter-macro.h>
68 #include <wsutil/file_util.h>
69 #include <epan/strutil.h>
70 #include <epan/addr_resolv.h>
72 #include "ui/alert_box.h"
73 #include "ui/simple_dialog.h"
74 #include "ui/main_statusbar.h"
75 #include "ui/progress_dlg.h"
76 #include "ui/ui_util.h"
78 /* Needed for addrinfo */
79 #ifdef HAVE_SYS_TYPES_H
80 # include <sys/types.h>
83 #ifdef HAVE_SYS_SOCKET_H
84 #include <sys/socket.h>
87 #ifdef HAVE_NETINET_IN_H
88 # include <netinet/in.h>
95 #ifdef HAVE_WINSOCK2_H
96 # include <winsock2.h>
99 #if defined(_WIN32) && defined(INET6)
100 # include <ws2tcpip.h>
104 gboolean auto_scroll_live;
107 static guint32 cum_bytes;
108 static nstime_t first_ts;
109 static frame_data *prev_dis;
110 static frame_data *prev_cap;
112 static gulong computed_elapsed;
114 static void cf_reset_state(capture_file *cf);
116 static int read_packet(capture_file *cf, dfilter_t *dfcode,
117 gboolean create_proto_tree, column_info *cinfo, gint64 offset);
119 static void rescan_packets(capture_file *cf, const char *action, const char *action_item, gboolean redissect);
126 static match_result match_protocol_tree(capture_file *cf, frame_data *fdata,
128 static void match_subtree_text(proto_node *node, gpointer data);
129 static match_result match_summary_line(capture_file *cf, frame_data *fdata,
131 static match_result match_narrow_and_wide(capture_file *cf, frame_data *fdata,
133 static match_result match_narrow(capture_file *cf, frame_data *fdata,
135 static match_result match_wide(capture_file *cf, frame_data *fdata,
137 static match_result match_binary(capture_file *cf, frame_data *fdata,
139 static match_result match_dfilter(capture_file *cf, frame_data *fdata,
141 static match_result match_marked(capture_file *cf, frame_data *fdata,
143 static match_result match_time_reference(capture_file *cf, frame_data *fdata,
145 static gboolean find_packet(capture_file *cf,
146 match_result (*match_function)(capture_file *, frame_data *, void *),
147 void *criterion, search_direction dir);
149 static void cf_open_failure_alert_box(const char *filename, int err,
150 gchar *err_info, gboolean for_writing,
152 static void cf_rename_failure_alert_box(const char *filename, int err);
153 static void cf_close_failure_alert_box(const char *filename, int err);
154 static void ref_time_packets(capture_file *cf);
155 /* Update the progress bar this many times when reading a file. */
156 #define N_PROGBAR_UPDATES 100
157 /* We read around 200k/100ms don't update the progress bar more often than that */
158 #define MIN_QUANTUM 200000
159 #define MIN_NUMBER_OF_PACKET 1500
162 * We could probably use g_signal_...() instead of the callbacks below but that
163 * would require linking our CLI programs to libgobject and creating an object
164 * instance for the signals.
167 cf_callback_t cb_fct;
169 } cf_callback_data_t;
171 static GList *cf_callbacks = NULL;
174 cf_callback_invoke(int event, gpointer data)
176 cf_callback_data_t *cb;
177 GList *cb_item = cf_callbacks;
179 /* there should be at least one interested */
180 g_assert(cb_item != NULL);
182 while (cb_item != NULL) {
183 cb = (cf_callback_data_t *)cb_item->data;
184 cb->cb_fct(event, data, cb->user_data);
185 cb_item = g_list_next(cb_item);
191 cf_callback_add(cf_callback_t func, gpointer user_data)
193 cf_callback_data_t *cb;
195 cb = g_new(cf_callback_data_t,1);
197 cb->user_data = user_data;
199 cf_callbacks = g_list_append(cf_callbacks, cb);
203 cf_callback_remove(cf_callback_t func)
205 cf_callback_data_t *cb;
206 GList *cb_item = cf_callbacks;
208 while (cb_item != NULL) {
209 cb = (cf_callback_data_t *)cb_item->data;
210 if (cb->cb_fct == func) {
211 cf_callbacks = g_list_remove(cf_callbacks, cb);
215 cb_item = g_list_next(cb_item);
218 g_assert_not_reached();
222 cf_timestamp_auto_precision(capture_file *cf)
225 int prec = timestamp_get_precision();
228 /* don't try to get the file's precision if none is opened */
229 if (cf->state == FILE_CLOSED) {
233 /* if we are in auto mode, set precision of current file */
234 if (prec == TS_PREC_AUTO ||
235 prec == TS_PREC_AUTO_SEC ||
236 prec == TS_PREC_AUTO_DSEC ||
237 prec == TS_PREC_AUTO_CSEC ||
238 prec == TS_PREC_AUTO_MSEC ||
239 prec == TS_PREC_AUTO_USEC ||
240 prec == TS_PREC_AUTO_NSEC)
242 switch(wtap_file_tsprecision(cf->wth)) {
243 case(WTAP_FILE_TSPREC_SEC):
244 timestamp_set_precision(TS_PREC_AUTO_SEC);
246 case(WTAP_FILE_TSPREC_DSEC):
247 timestamp_set_precision(TS_PREC_AUTO_DSEC);
249 case(WTAP_FILE_TSPREC_CSEC):
250 timestamp_set_precision(TS_PREC_AUTO_CSEC);
252 case(WTAP_FILE_TSPREC_MSEC):
253 timestamp_set_precision(TS_PREC_AUTO_MSEC);
255 case(WTAP_FILE_TSPREC_USEC):
256 timestamp_set_precision(TS_PREC_AUTO_USEC);
258 case(WTAP_FILE_TSPREC_NSEC):
259 timestamp_set_precision(TS_PREC_AUTO_NSEC);
262 g_assert_not_reached();
265 /* Set the column widths of those columns that show the time in
266 "command-line-specified" format. */
267 for (i = 0; i < cf->cinfo.num_cols; i++) {
268 if (col_has_time_fmt(&cf->cinfo, i)) {
269 packet_list_resize_column(i);
275 cf_get_computed_elapsed(void)
277 return computed_elapsed;
280 static void reset_elapsed(void)
282 computed_elapsed = 0;
286 * GLIB_CHECK_VERSION(2,28,0) adds g_get_real_time which could minimize or
289 static void compute_elapsed(GTimeVal *start_time)
294 g_get_current_time(&time_now);
296 delta_time = (time_now.tv_sec - start_time->tv_sec) * 1e6 +
297 time_now.tv_usec - start_time->tv_usec;
299 computed_elapsed = (gulong) (delta_time / 1000); /* ms */
303 cf_open(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
308 wth = wtap_open_offline(fname, err, &err_info, TRUE);
312 /* The open succeeded. Close whatever capture file we had open,
313 and fill in the information for this file. */
316 /* Cleanup all data structures used for dissection. */
317 cleanup_dissection();
318 /* Initialize all data structures used for dissection. */
321 /* We're about to start reading the file. */
322 cf->state = FILE_READ_IN_PROGRESS;
327 /* Set the file name because we need it to set the follow stream filter.
328 XXX - is that still true? We need it for other reasons, though,
330 cf->filename = g_strdup(fname);
332 /* Indicate whether it's a permanent or temporary file. */
333 cf->is_tempfile = is_tempfile;
335 /* No user changes yet. */
336 cf->unsaved_changes = FALSE;
340 cf->cd_t = wtap_file_type(cf->wth);
341 cf->linktypes = g_array_sized_new(FALSE, FALSE, (guint) sizeof(int), 1);
343 cf->packet_comment_count = 0;
344 cf->displayed_count = 0;
345 cf->marked_count = 0;
346 cf->ignored_count = 0;
347 cf->ref_time_count = 0;
348 cf->drops_known = FALSE;
350 cf->snap = wtap_snapshot_length(cf->wth);
352 /* Snapshot length not known. */
353 cf->has_snap = FALSE;
354 cf->snap = WTAP_MAX_PACKET_SIZE;
358 /* Allocate a frame_data_sequence for the frames in this file */
359 cf->frames = new_frame_data_sequence();
361 nstime_set_zero(&cf->elapsed_time);
362 nstime_set_unset(&first_ts);
367 /* Adjust timestamp precision if auto is selected, col width will be adjusted */
368 cf_timestamp_auto_precision(cf);
370 packet_list_queue_draw();
371 cf_callback_invoke(cf_cb_file_opened, cf);
373 if (cf->cd_t == WTAP_FILE_BER) {
374 /* tell the BER dissector the file name */
375 ber_set_filename(cf->filename);
378 wtap_set_cb_new_ipv4(cf->wth, add_ipv4_name);
379 wtap_set_cb_new_ipv6(cf->wth, (wtap_new_ipv6_callback_t) add_ipv6_name);
384 cf_open_failure_alert_box(fname, *err, err_info, FALSE, 0);
389 * Add an encapsulation type to cf->linktypes.
392 cf_add_encapsulation_type(capture_file *cf, int encap)
396 for (i = 0; i < cf->linktypes->len; i++) {
397 if (g_array_index(cf->linktypes, gint, i) == encap)
398 return; /* it's already there */
400 /* It's not already there - add it. */
401 g_array_append_val(cf->linktypes, encap);
405 * Reset the state for the currently closed file, but don't do the
406 * UI callbacks; this is for use in "cf_open()", where we don't
407 * want the UI to go from "file open" to "file closed" back to
408 * "file open", we want it to go from "old file open" to "new file
409 * open and being read".
411 * XXX - currently, cf_open() calls cf_close(), rather than
415 cf_reset_state(capture_file *cf)
417 /* Die if we're in the middle of reading a file. */
418 g_assert(cf->state != FILE_READ_IN_PROGRESS);
424 /* We have no file open... */
425 if (cf->filename != NULL) {
426 /* If it's a temporary file, remove it. */
428 ws_unlink(cf->filename);
429 g_free(cf->filename);
432 /* ...which means we have no changes to that file to save. */
433 cf->unsaved_changes = FALSE;
435 dfilter_free(cf->rfcode);
437 if (cf->frames != NULL) {
438 free_frame_data_sequence(cf->frames);
441 #ifdef WANT_PACKET_EDITOR
442 if (cf->edited_frames) {
443 g_tree_destroy(cf->edited_frames);
444 cf->edited_frames = NULL;
447 cf_unselect_packet(cf); /* nothing to select */
448 cf->first_displayed = 0;
449 cf->last_displayed = 0;
451 /* No frames, no frame selected, no field in that frame selected. */
453 cf->current_frame = 0;
455 cf->finfo_selected = NULL;
457 /* No frame link-layer types, either. */
458 g_array_free(cf->linktypes, TRUE);
459 cf->linktypes = NULL;
461 /* Clear the packet list. */
462 packet_list_freeze();
467 nstime_set_zero(&cf->elapsed_time);
469 reset_tap_listeners();
471 /* We have no file open. */
472 cf->state = FILE_CLOSED;
475 /* Reset everything to a pristine state */
477 cf_close(capture_file *cf)
479 if (cf->state != FILE_CLOSED) {
480 cf_callback_invoke(cf_cb_file_closing, cf);
482 /* close things, if not already closed before */
483 color_filters_cleanup();
485 cleanup_dissection();
487 cf_callback_invoke(cf_cb_file_closed, cf);
492 calc_progbar_val(capture_file *cf, gint64 size, gint64 file_pos, gchar *status_str, gulong status_size)
496 progbar_val = (gfloat) file_pos / (gfloat) size;
497 if (progbar_val > 1.0) {
499 /* The file probably grew while we were reading it.
500 * Update file size, and try again.
502 size = wtap_file_size(cf->wth, NULL);
505 progbar_val = (gfloat) file_pos / (gfloat) size;
507 /* If it's still > 1, either "wtap_file_size()" failed (in which
508 * case there's not much we can do about it), or the file
509 * *shrank* (in which case there's not much we can do about
510 * it); just clip the progress value at 1.0.
512 if (progbar_val > 1.0f)
516 g_snprintf(status_str, status_size,
517 "%" G_GINT64_MODIFIER "dKB of %" G_GINT64_MODIFIER "dKB",
518 file_pos / 1024, size / 1024);
524 cf_read(capture_file *cf, gboolean reloading)
529 progdlg_t *progbar = NULL;
533 volatile gboolean create_proto_tree;
537 /* Compile the current display filter.
538 * We assume this will not fail since cf->dfilter is only set in
539 * cf_filter IFF the filter was valid.
541 compiled = dfilter_compile(cf->dfilter, &dfcode);
542 g_assert(!cf->dfilter || (compiled && dfcode));
544 /* Get the union of the flags for all tap listeners. */
545 tap_flags = union_of_tap_listener_flags();
547 (dfcode != NULL || have_filtering_tap_listeners() || (tap_flags & TL_REQUIRES_PROTO_TREE));
549 reset_tap_listeners();
551 name_ptr = g_filename_display_basename(cf->filename);
554 cf_callback_invoke(cf_cb_file_reload_started, cf);
556 cf_callback_invoke(cf_cb_file_read_started, cf);
558 /* Record whether the file is compressed.
559 XXX - do we know this at open time? */
560 cf->iscompressed = wtap_iscompressed(cf->wth);
562 /* The packet list window will be empty until the file is completly loaded */
563 packet_list_freeze();
566 g_get_current_time(&start_time);
570 int displayed_once = 0;
578 gint64 progbar_quantum;
579 gint64 progbar_nextstep;
581 gchar status_str[100];
585 cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
587 /* Find the size of the file. */
588 size = wtap_file_size(cf->wth, NULL);
590 /* Update the progress bar when it gets to this value. */
591 progbar_nextstep = 0;
592 /* When we reach the value that triggers a progress bar update,
593 bump that value by this amount. */
595 progbar_quantum = size/N_PROGBAR_UPDATES;
596 if (progbar_quantum < MIN_QUANTUM)
597 progbar_quantum = MIN_QUANTUM;
600 /* Progress so far. */
603 while ((wtap_read(cf->wth, &err, &err_info, &data_offset))) {
606 file_pos = wtap_read_so_far(cf->wth);
608 /* Create the progress bar if necessary.
609 * Check whether it should be created or not every MIN_NUMBER_OF_PACKET
611 if ((progbar == NULL) && !(count % MIN_NUMBER_OF_PACKET)) {
612 progbar_val = calc_progbar_val(cf, size, file_pos, status_str, sizeof(status_str));
614 progbar = delayed_create_progress_dlg(cf->window, "Reloading", name_ptr,
615 TRUE, &stop_flag, &start_time, progbar_val);
617 progbar = delayed_create_progress_dlg(cf->window, "Loading", name_ptr,
618 TRUE, &stop_flag, &start_time, progbar_val);
621 /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
622 when we update it, we have to run the GTK+ main loop to get it
623 to repaint what's pending, and doing so may involve an "ioctl()"
624 to see if there's any pending input from an X server, and doing
625 that for every packet can be costly, especially on a big file. */
626 if (file_pos >= progbar_nextstep) {
627 if (progbar != NULL) {
628 progbar_val = calc_progbar_val(cf, size, file_pos, status_str, sizeof(status_str));
629 /* update the packet bar content on the first run or frequently on very large files */
631 if (progbar_quantum > 500000 || displayed_once == 0) {
632 if ((auto_scroll_live || displayed_once == 0 || cf->displayed_count < 1000) && cf->count != 0) {
634 packets_bar_update();
637 #endif /* HAVE_LIBPCAP */
638 update_progress_dlg(progbar, progbar_val, status_str);
640 progbar_nextstep += progbar_quantum;
645 /* Well, the user decided to abort the read. He/She will be warned and
646 it might be enough for him/her to work with the already loaded
648 This is especially true for very large capture files, where you don't
649 want to wait loading the whole file (which may last minutes or even
650 hours even on fast machines) just to see that it was the wrong file. */
653 read_packet(cf, dfcode, create_proto_tree, cinfo, data_offset);
656 CATCH(OutOfMemoryError) {
657 simple_message_box(ESD_TYPE_ERROR, NULL,
658 "Some infos / workarounds can be found at:\n"
659 "http://wiki.wireshark.org/KnownBugs/OutOfMemory",
660 "Sorry, but Wireshark has run out of memory and has to terminate now!");
662 /* Could we close the current capture and free up memory from that? */
664 /* we have to terminate, as we cannot recover from the memory error */
670 /* Free the display name */
673 /* Cleanup and release all dfilter resources */
674 if (dfcode != NULL) {
675 dfilter_free(dfcode);
678 /* We're done reading the file; destroy the progress bar if it was created. */
680 destroy_progress_dlg(progbar);
682 /* We're done reading sequentially through the file. */
683 cf->state = FILE_READ_DONE;
685 /* Close the sequential I/O side, to free up memory it requires. */
686 wtap_sequential_close(cf->wth);
688 /* Allow the protocol dissectors to free up memory that they
689 * don't need after the sequential run-through of the packets. */
690 postseq_cleanup_all_protocols();
692 /* compute the time it took to load the file */
693 compute_elapsed(&start_time);
695 /* Set the file encapsulation type now; we don't know what it is until
696 we've looked at all the packets, as we don't know until then whether
697 there's more than one type (and thus whether it's
698 WTAP_ENCAP_PER_PACKET). */
699 cf->lnk_t = wtap_file_encap(cf->wth);
701 cf->current_frame = frame_data_sequence_find(cf->frames, cf->first_displayed);
706 cf_callback_invoke(cf_cb_file_reload_finished, cf);
708 cf_callback_invoke(cf_cb_file_read_finished, cf);
710 /* If we have any displayed packets to select, select the first of those
711 packets by making the first row the selected row. */
712 if (cf->first_displayed != 0) {
713 packet_list_select_first_row();
717 simple_message_box(ESD_TYPE_WARN, NULL,
718 "The remaining packets in the file were discarded.\n"
720 "As a lot of packets from the original file will be missing,\n"
721 "remember to be careful when saving the current content to a file.\n",
722 "File loading was cancelled!");
723 return CF_READ_ERROR;
727 /* Put up a message box noting that the read failed somewhere along
728 the line. Don't throw out the stuff we managed to read, though,
732 case WTAP_ERR_UNSUPPORTED:
733 simple_error_message_box(
734 "The capture file contains record data that Wireshark doesn't support.\n(%s)",
739 case WTAP_ERR_UNSUPPORTED_ENCAP:
740 simple_error_message_box(
741 "The capture file has a packet with a network type that Wireshark doesn't support.\n(%s)",
746 case WTAP_ERR_CANT_READ:
747 simple_error_message_box(
748 "An attempt to read from the capture file failed for"
749 " some unknown reason.");
752 case WTAP_ERR_SHORT_READ:
753 simple_error_message_box(
754 "The capture file appears to have been cut short"
755 " in the middle of a packet.");
758 case WTAP_ERR_BAD_FILE:
759 simple_error_message_box(
760 "The capture file appears to be damaged or corrupt.\n(%s)",
765 case WTAP_ERR_DECOMPRESS:
766 simple_error_message_box(
767 "The compressed capture file appears to be damaged or corrupt.\n"
773 simple_error_message_box(
774 "An error occurred while reading the"
775 " capture file: %s.", wtap_strerror(err));
778 return CF_READ_ERROR;
785 cf_start_tail(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
787 cf_status_t cf_status;
789 cf_status = cf_open(cf, fname, is_tempfile, err);
794 cf_continue_tail(capture_file *cf, volatile int to_read, int *err)
797 int newly_displayed_packets = 0;
799 volatile gboolean create_proto_tree;
803 /* Compile the current display filter.
804 * We assume this will not fail since cf->dfilter is only set in
805 * cf_filter IFF the filter was valid.
807 compiled = dfilter_compile(cf->dfilter, &dfcode);
808 g_assert(!cf->dfilter || (compiled && dfcode));
810 /* Get the union of the flags for all tap listeners. */
811 tap_flags = union_of_tap_listener_flags();
813 (dfcode != NULL || have_filtering_tap_listeners() || (tap_flags & TL_REQUIRES_PROTO_TREE));
817 packet_list_check_end();
818 /* Don't freeze/thaw the list when doing live capture */
819 /*packet_list_freeze();*/
821 /*g_log(NULL, G_LOG_LEVEL_MESSAGE, "cf_continue_tail: %u new: %u", cf->count, to_read);*/
824 gint64 data_offset = 0;
827 cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
829 while (to_read != 0) {
830 wtap_cleareof(cf->wth);
831 if (!wtap_read(cf->wth, err, &err_info, &data_offset)) {
834 if (cf->state == FILE_READ_ABORTED) {
835 /* Well, the user decided to exit Wireshark. Break out of the
836 loop, and let the code below (which is called even if there
837 aren't any packets left to read) exit. */
840 if (read_packet(cf, dfcode, create_proto_tree, (column_info *) cinfo, data_offset) != -1) {
841 newly_displayed_packets++;
846 CATCH(OutOfMemoryError) {
847 simple_message_box(ESD_TYPE_ERROR, NULL,
848 "Some infos / workarounds can be found at:\n"
849 "http://wiki.wireshark.org/KnownBugs/OutOfMemory",
850 "Sorry, but Wireshark has run out of memory and has to terminate now!");
852 /* Could we close the current capture and free up memory from that? */
853 return CF_READ_ABORTED;
855 /* we have to terminate, as we cannot recover from the memory error */
861 /* Update the file encapsulation; it might have changed based on the
862 packets we've read. */
863 cf->lnk_t = wtap_file_encap(cf->wth);
865 /* Cleanup and release all dfilter resources */
866 if (dfcode != NULL) {
867 dfilter_free(dfcode);
870 /*g_log(NULL, G_LOG_LEVEL_MESSAGE, "cf_continue_tail: count %u state: %u err: %u",
871 cf->count, cf->state, *err);*/
873 /* Don't freeze/thaw the list when doing live capture */
874 /*packet_list_thaw();*/
875 /* With the new packet list the first packet
876 * isn't automatically selected.
878 if (!cf->current_frame)
879 packet_list_select_first_row();
881 /* moving to the end of the packet list - if the user requested so and
882 we have some new packets. */
883 if (newly_displayed_packets && auto_scroll_live && cf->count != 0)
884 packet_list_moveto_end();
886 if (cf->state == FILE_READ_ABORTED) {
887 /* Well, the user decided to exit Wireshark. Return CF_READ_ABORTED
888 so that our caller can kill off the capture child process;
889 this will cause an EOF on the pipe from the child, so
890 "cf_finish_tail()" will be called, and it will clean up
892 return CF_READ_ABORTED;
893 } else if (*err != 0) {
894 /* We got an error reading the capture file.
895 XXX - pop up a dialog box instead? */
896 g_warning("Error \"%s\" while reading: \"%s\" (\"%s\")",
897 wtap_strerror(*err), err_info, cf->filename);
900 return CF_READ_ERROR;
906 cf_fake_continue_tail(capture_file *cf) {
907 cf->state = FILE_READ_DONE;
911 cf_finish_tail(capture_file *cf, int *err)
917 gboolean create_proto_tree;
921 /* Compile the current display filter.
922 * We assume this will not fail since cf->dfilter is only set in
923 * cf_filter IFF the filter was valid.
925 compiled = dfilter_compile(cf->dfilter, &dfcode);
926 g_assert(!cf->dfilter || (compiled && dfcode));
928 /* Get the union of the flags for all tap listeners. */
929 tap_flags = union_of_tap_listener_flags();
930 cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
932 (dfcode != NULL || have_filtering_tap_listeners() || (tap_flags & TL_REQUIRES_PROTO_TREE));
934 if (cf->wth == NULL) {
936 return CF_READ_ERROR;
939 packet_list_check_end();
940 /* Don't freeze/thaw the list when doing live capture */
941 /*packet_list_freeze();*/
943 while ((wtap_read(cf->wth, err, &err_info, &data_offset))) {
944 if (cf->state == FILE_READ_ABORTED) {
945 /* Well, the user decided to abort the read. Break out of the
946 loop, and let the code below (which is called even if there
947 aren't any packets left to read) exit. */
950 read_packet(cf, dfcode, create_proto_tree, cinfo, data_offset);
953 /* Cleanup and release all dfilter resources */
954 if (dfcode != NULL) {
955 dfilter_free(dfcode);
958 /* Don't freeze/thaw the list when doing live capture */
959 /*packet_list_thaw();*/
961 if (cf->state == FILE_READ_ABORTED) {
962 /* Well, the user decided to abort the read. We're only called
963 when the child capture process closes the pipe to us (meaning
964 it's probably exited), so we can just close the capture
965 file; we return CF_READ_ABORTED so our caller can do whatever
966 is appropriate when that happens. */
968 return CF_READ_ABORTED;
971 if (auto_scroll_live && cf->count != 0)
972 packet_list_moveto_end();
974 /* We're done reading sequentially through the file. */
975 cf->state = FILE_READ_DONE;
977 /* We're done reading sequentially through the file; close the
978 sequential I/O side, to free up memory it requires. */
979 wtap_sequential_close(cf->wth);
981 /* Allow the protocol dissectors to free up memory that they
982 * don't need after the sequential run-through of the packets. */
983 postseq_cleanup_all_protocols();
985 /* Update the file encapsulation; it might have changed based on the
986 packets we've read. */
987 cf->lnk_t = wtap_file_encap(cf->wth);
989 /* Update the details in the file-set dialog, as the capture file
990 * has likely grown since we first stat-ed it */
991 fileset_update_file(cf->filename);
994 /* We got an error reading the capture file.
995 XXX - pop up a dialog box? */
997 g_warning("Error \"%s\" while reading: \"%s\" (\"%s\")",
998 wtap_strerror(*err), err_info, cf->filename);
1000 return CF_READ_ERROR;
1005 #endif /* HAVE_LIBPCAP */
1008 cf_get_display_name(capture_file *cf)
1012 /* Return a name to use in displays */
1013 if (!cf->is_tempfile) {
1014 /* Get the last component of the file name, and use that. */
1016 displayname = g_filename_display_basename(cf->filename);
1018 displayname=g_strdup("(No file)");
1021 /* The file we read is a temporary file from a live capture or
1022 a merge operation; we don't mention its name, but, if it's
1023 from a capture, give the source of the capture. */
1025 displayname = g_strdup(cf->source);
1027 displayname = g_strdup("(Untitled)");
1033 void cf_set_tempfile_source(capture_file *cf, gchar *source) {
1039 cf->source = g_strdup(source);
1041 cf->source = g_strdup("");
1045 const gchar *cf_get_tempfile_source(capture_file *cf) {
1053 /* XXX - use a macro instead? */
1055 cf_get_packet_count(capture_file *cf)
1060 /* XXX - use a macro instead? */
1062 cf_set_packet_count(capture_file *cf, int packet_count)
1064 cf->count = packet_count;
1067 /* XXX - use a macro instead? */
1069 cf_is_tempfile(capture_file *cf)
1071 return cf->is_tempfile;
1074 void cf_set_tempfile(capture_file *cf, gboolean is_tempfile)
1076 cf->is_tempfile = is_tempfile;
1080 /* XXX - use a macro instead? */
1081 void cf_set_drops_known(capture_file *cf, gboolean drops_known)
1083 cf->drops_known = drops_known;
1086 /* XXX - use a macro instead? */
1087 void cf_set_drops(capture_file *cf, guint32 drops)
1092 /* XXX - use a macro instead? */
1093 gboolean cf_get_drops_known(capture_file *cf)
1095 return cf->drops_known;
1098 /* XXX - use a macro instead? */
1099 guint32 cf_get_drops(capture_file *cf)
1104 void cf_set_rfcode(capture_file *cf, dfilter_t *rfcode)
1106 cf->rfcode = rfcode;
1110 add_packet_to_packet_list(frame_data *fdata, capture_file *cf,
1111 dfilter_t *dfcode, gboolean create_proto_tree, column_info *cinfo,
1112 struct wtap_pkthdr *phdr, const guchar *buf,
1113 gboolean add_to_packet_list)
1118 frame_data_set_before_dissect(fdata, &cf->elapsed_time,
1119 &first_ts, prev_dis, prev_cap);
1122 /* Dissect the frame. */
1123 epan_dissect_init(&edt, create_proto_tree, FALSE);
1125 if (dfcode != NULL) {
1126 epan_dissect_prime_dfilter(&edt, dfcode);
1129 epan_dissect_run_with_taps(&edt, phdr, buf, fdata, cinfo);
1131 /* If we don't have a display filter, set "passed_dfilter" to 1. */
1132 if (dfcode != NULL) {
1133 fdata->flags.passed_dfilter = dfilter_apply_edt(dfcode, &edt) ? 1 : 0;
1135 if (fdata->flags.passed_dfilter) {
1136 /* This frame passed the display filter but it may depend on other
1137 * (potentially not displayed) frames. Find those frames and mark them
1140 g_slist_foreach(edt.pi.dependent_frames, find_and_mark_frame_depended_upon, cf->frames);
1143 fdata->flags.passed_dfilter = 1;
1145 if (fdata->flags.passed_dfilter || fdata->flags.ref_time)
1146 cf->displayed_count++;
1148 if (add_to_packet_list) {
1149 /* We fill the needed columns from new_packet_list */
1150 row = packet_list_append(cinfo, fdata, &edt.pi);
1153 if (fdata->flags.passed_dfilter || fdata->flags.ref_time)
1155 frame_data_set_after_dissect(fdata, &cum_bytes);
1158 /* If we haven't yet seen the first frame, this is it.
1160 XXX - we must do this before we add the row to the display,
1161 as, if the display's GtkCList's selection mode is
1162 GTK_SELECTION_BROWSE, when the first entry is added to it,
1163 "cf_select_packet()" will be called, and it will fetch the row
1164 data for the 0th row, and will get a null pointer rather than
1165 "fdata", as "gtk_clist_append()" won't yet have returned and
1166 thus "gtk_clist_set_row_data()" won't yet have been called.
1168 We thus need to leave behind bread crumbs so that
1169 "cf_select_packet()" can find this frame. See the comment
1170 in "cf_select_packet()". */
1171 if (cf->first_displayed == 0)
1172 cf->first_displayed = fdata->num;
1174 /* This is the last frame we've seen so far. */
1175 cf->last_displayed = fdata->num;
1178 epan_dissect_cleanup(&edt);
1182 /* read in a new packet */
1183 /* returns the row of the new packet in the packet list or -1 if not displayed */
1185 read_packet(capture_file *cf, dfilter_t *dfcode,
1186 gboolean create_proto_tree, column_info *cinfo, gint64 offset)
1188 struct wtap_pkthdr *phdr = wtap_phdr(cf->wth);
1189 const guchar *buf = wtap_buf_ptr(cf->wth);
1196 /* Add this packet's link-layer encapsulation type to cf->linktypes, if
1197 it's not already there.
1198 XXX - yes, this is O(N), so if every packet had a different
1199 link-layer encapsulation type, it'd be O(N^2) to read the file, but
1200 there are probably going to be a small number of encapsulation types
1202 cf_add_encapsulation_type(cf, phdr->pkt_encap);
1204 /* The frame number of this packet is one more than the count of
1205 frames in the file so far. */
1206 framenum = cf->count + 1;
1208 frame_data_init(&fdlocal, framenum, phdr, offset, cum_bytes);
1213 epan_dissect_init(&edt, TRUE, FALSE);
1214 epan_dissect_prime_dfilter(&edt, cf->rfcode);
1215 epan_dissect_run(&edt, phdr, buf, &fdlocal, NULL);
1216 passed = dfilter_apply_edt(cf->rfcode, &edt);
1217 epan_dissect_cleanup(&edt);
1221 /* This does a shallow copy of fdlocal, which is good enough. */
1222 fdata = frame_data_sequence_add(cf->frames, &fdlocal);
1225 if (fdlocal.opt_comment != NULL)
1226 cf->packet_comment_count++;
1227 cf->f_datalen = offset + fdlocal.cap_len;
1229 if (!cf->redissecting) {
1230 row = add_packet_to_packet_list(fdata, cf, dfcode,
1231 create_proto_tree, cinfo,
1240 cf_merge_files(char **out_filenamep, int in_file_count,
1241 char *const *in_filenames, int file_type, gboolean do_append)
1243 merge_in_file_t *in_files, *in_file;
1248 int open_err, read_err, write_err, close_err;
1252 gboolean got_read_error = FALSE, got_write_error = FALSE;
1254 progdlg_t *progbar = NULL;
1256 gint64 f_len, file_pos;
1258 GTimeVal start_time;
1259 gchar status_str[100];
1260 gint64 progbar_nextstep;
1261 gint64 progbar_quantum;
1262 gchar *display_basename;
1263 int selected_frame_type;
1264 gboolean fake_interface_ids = FALSE;
1266 /* open the input files */
1267 if (!merge_open_in_files(in_file_count, in_filenames, &in_files,
1268 &open_err, &err_info, &err_fileno)) {
1270 cf_open_failure_alert_box(in_filenames[err_fileno], open_err, err_info,
1275 if (*out_filenamep != NULL) {
1276 out_filename = *out_filenamep;
1277 out_fd = ws_open(out_filename, O_CREAT|O_TRUNC|O_BINARY, 0600);
1281 out_fd = create_tempfile(&tmpname, "wireshark");
1284 out_filename = g_strdup(tmpname);
1285 *out_filenamep = out_filename;
1289 merge_close_in_files(in_file_count, in_files);
1291 cf_open_failure_alert_box(out_filename, open_err, NULL, TRUE, file_type);
1295 selected_frame_type = merge_select_frame_type(in_file_count, in_files);
1297 /* If we are trying to merge a number of libpcap files with different encapsulation types
1298 * change the output file type to pcapng and create SHB and IDB:s for the new file use the
1299 * interface index stored in in_files per file to change the phdr before writing the datablock.
1300 * XXX should it be an option to convert to pcapng?
1302 * We need something similar when merging pcapng files possibly with an option to say
1303 * the same interface(s) used in all in files. SHBs comments should be merged together.
1305 if ((selected_frame_type == WTAP_ENCAP_PER_PACKET)&&(file_type == WTAP_FILE_PCAP)) {
1306 /* Write output in pcapng format */
1307 wtapng_section_t *shb_hdr;
1308 wtapng_iface_descriptions_t *idb_inf, *idb_inf_merge_file;
1309 wtapng_if_descr_t int_data, *file_int_data;
1310 GString *comment_gstr;
1312 fake_interface_ids = TRUE;
1313 /* Create SHB info */
1314 shb_hdr = wtap_file_get_shb_info(in_files[0].wth);
1315 comment_gstr = g_string_new("");
1316 g_string_append_printf(comment_gstr, "%s \n",shb_hdr->opt_comment);
1317 g_string_append_printf(comment_gstr, "File created by merging: \n");
1318 file_type = WTAP_FILE_PCAPNG;
1320 for (i = 0; i < in_file_count; i++) {
1321 g_string_append_printf(comment_gstr, "File%d: %s \n",i+1,in_files[i].filename);
1323 shb_hdr->section_length = -1;
1325 shb_hdr->opt_comment = g_string_free(comment_gstr, FALSE); /* NULL if not available */
1326 shb_hdr->shb_hardware = NULL; /* NULL if not available, UTF-8 string containing the */
1327 /* description of the hardware used to create this section. */
1328 shb_hdr->shb_os = NULL; /* NULL if not available, UTF-8 string containing the name */
1329 /* of the operating system used to create this section. */
1330 shb_hdr->shb_user_appl = "Wireshark"; /* NULL if not available, UTF-8 string containing the name */
1331 /* of the application used to create this section. */
1333 /* create fake IDB info */
1334 idb_inf = g_new(wtapng_iface_descriptions_t,1);
1335 idb_inf->number_of_interfaces = in_file_count; /* TODO make this the number of DIFFERENT encapsulation types
1336 * check that snaplength is the same too?
1338 idb_inf->interface_data = g_array_new(FALSE, FALSE, sizeof(wtapng_if_descr_t));
1340 for (i = 0; i < in_file_count; i++) {
1341 idb_inf_merge_file = wtap_file_get_idb_info(in_files[i].wth);
1342 /* read the interface data from the in file to our combined interfca data */
1343 file_int_data = &g_array_index (idb_inf_merge_file->interface_data, wtapng_if_descr_t, 0);
1344 int_data.wtap_encap = file_int_data->wtap_encap;
1345 int_data.time_units_per_second = file_int_data->time_units_per_second;
1346 int_data.link_type = file_int_data->link_type;
1347 int_data.snap_len = file_int_data->snap_len;
1348 int_data.if_name = g_strdup(file_int_data->if_name);
1349 int_data.opt_comment = NULL;
1350 int_data.if_description = NULL;
1351 int_data.if_speed = 0;
1352 int_data.if_tsresol = 6;
1353 int_data.if_filter_str = NULL;
1354 int_data.bpf_filter_len = 0;
1355 int_data.if_filter_bpf_bytes = NULL;
1356 int_data.if_os = NULL;
1357 int_data.if_fcslen = -1;
1358 int_data.num_stat_entries = 0; /* Number of ISB:s */
1359 int_data.interface_statistics = NULL;
1361 g_array_append_val(idb_inf->interface_data, int_data);
1362 g_free(idb_inf_merge_file);
1364 /* Set fake interface Id in per file data */
1365 in_files[i].interface_id = i;
1368 pdh = wtap_dump_fdopen_ng(out_fd, file_type,
1369 selected_frame_type,
1370 merge_max_snapshot_length(in_file_count, in_files),
1371 FALSE /* compressed */, shb_hdr, idb_inf /* wtapng_iface_descriptions_t *idb_inf */, &open_err);
1375 merge_close_in_files(in_file_count, in_files);
1377 cf_open_failure_alert_box(out_filename, open_err, err_info, TRUE,
1384 pdh = wtap_dump_fdopen(out_fd, file_type,
1385 selected_frame_type,
1386 merge_max_snapshot_length(in_file_count, in_files),
1387 FALSE /* compressed */, &open_err);
1390 merge_close_in_files(in_file_count, in_files);
1392 cf_open_failure_alert_box(out_filename, open_err, err_info, TRUE,
1398 /* Get the sum of the sizes of all the files. */
1400 for (i = 0; i < in_file_count; i++)
1401 f_len += in_files[i].size;
1403 /* Update the progress bar when it gets to this value. */
1404 progbar_nextstep = 0;
1405 /* When we reach the value that triggers a progress bar update,
1406 bump that value by this amount. */
1407 progbar_quantum = f_len/N_PROGBAR_UPDATES;
1408 /* Progress so far. */
1412 g_get_current_time(&start_time);
1414 /* do the merge (or append) */
1417 in_file = merge_append_read_packet(in_file_count, in_files, &read_err,
1420 in_file = merge_read_packet(in_file_count, in_files, &read_err,
1422 if (in_file == NULL) {
1427 if (read_err != 0) {
1428 /* I/O error reading from in_file */
1429 got_read_error = TRUE;
1433 /* Get the sum of the data offsets in all of the files. */
1435 for (i = 0; i < in_file_count; i++)
1436 data_offset += in_files[i].data_offset;
1438 /* Create the progress bar if necessary.
1439 We check on every iteration of the loop, so that it takes no
1440 longer than the standard time to create it (otherwise, for a
1441 large file, we might take considerably longer than that standard
1442 time in order to get to the next progress bar step). */
1443 if (progbar == NULL) {
1444 progbar = delayed_create_progress_dlg(NULL, "Merging", "files",
1445 FALSE, &stop_flag, &start_time, progbar_val);
1448 /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
1449 when we update it, we have to run the GTK+ main loop to get it
1450 to repaint what's pending, and doing so may involve an "ioctl()"
1451 to see if there's any pending input from an X server, and doing
1452 that for every packet can be costly, especially on a big file. */
1453 if (data_offset >= progbar_nextstep) {
1454 /* Get the sum of the seek positions in all of the files. */
1456 for (i = 0; i < in_file_count; i++)
1457 file_pos += wtap_read_so_far(in_files[i].wth);
1458 progbar_val = (gfloat) file_pos / (gfloat) f_len;
1459 if (progbar_val > 1.0f) {
1460 /* Some file probably grew while we were reading it.
1461 That "shouldn't happen", so we'll just clip the progress
1465 if (progbar != NULL) {
1466 g_snprintf(status_str, sizeof(status_str),
1467 "%" G_GINT64_MODIFIER "dKB of %" G_GINT64_MODIFIER "dKB",
1468 file_pos / 1024, f_len / 1024);
1469 update_progress_dlg(progbar, progbar_val, status_str);
1471 progbar_nextstep += progbar_quantum;
1475 /* Well, the user decided to abort the merge. */
1479 /* If we have WTAP_ENCAP_PER_PACKETend the infiles are of type WTAP_FILE_PCAP
1480 * we need to set the interface id in the paket header = the interface index we used
1481 * in the IDBs interface description for this file(encapsulation type).
1483 if (fake_interface_ids) {
1484 struct wtap_pkthdr *phdr;
1486 phdr = wtap_phdr(in_file->wth);
1487 phdr->interface_id = in_file->interface_id;
1488 phdr->presence_flags = phdr->presence_flags | WTAP_HAS_INTERFACE_ID;
1490 if (!wtap_dump(pdh, wtap_phdr(in_file->wth),
1491 wtap_buf_ptr(in_file->wth), &write_err)) {
1492 got_write_error = TRUE;
1497 /* We're done merging the files; destroy the progress bar if it was created. */
1498 if (progbar != NULL)
1499 destroy_progress_dlg(progbar);
1501 merge_close_in_files(in_file_count, in_files);
1502 if (!got_read_error && !got_write_error) {
1503 if (!wtap_dump_close(pdh, &write_err))
1504 got_write_error = TRUE;
1506 wtap_dump_close(pdh, &close_err);
1508 if (got_read_error) {
1510 * Find the file on which we got the error, and report the error.
1512 for (i = 0; i < in_file_count; i++) {
1513 if (in_files[i].state == GOT_ERROR) {
1514 /* Put up a message box noting that a read failed somewhere along
1516 display_basename = g_filename_display_basename(in_files[i].filename);
1519 case WTAP_ERR_UNSUPPORTED_ENCAP:
1520 simple_error_message_box(
1521 "The capture file %s has a packet with a network type that Wireshark doesn't support.\n(%s)",
1522 display_basename, err_info);
1526 case WTAP_ERR_CANT_READ:
1527 simple_error_message_box(
1528 "An attempt to read from the capture file %s failed for"
1529 " some unknown reason.", display_basename);
1532 case WTAP_ERR_SHORT_READ:
1533 simple_error_message_box(
1534 "The capture file %s appears to have been cut short"
1535 " in the middle of a packet.", display_basename);
1538 case WTAP_ERR_BAD_FILE:
1539 simple_error_message_box(
1540 "The capture file %s appears to be damaged or corrupt.\n(%s)",
1541 display_basename, err_info);
1545 case WTAP_ERR_DECOMPRESS:
1546 simple_error_message_box(
1547 "The compressed capture file %s appears to be damaged or corrupt.\n"
1548 "(%s)", display_basename, err_info);
1553 simple_error_message_box(
1554 "An error occurred while reading the"
1555 " capture file %s: %s.",
1556 display_basename, wtap_strerror(read_err));
1559 g_free(display_basename);
1564 if (got_write_error) {
1565 /* Put up an alert box for the write error. */
1566 if (write_err < 0) {
1567 /* Wiretap error. */
1568 switch (write_err) {
1570 case WTAP_ERR_UNSUPPORTED_ENCAP:
1572 * This is a problem with the particular frame we're writing;
1573 * note that, and give the frame number.
1575 display_basename = g_filename_display_basename(in_file->filename);
1576 simple_error_message_box(
1577 "Frame %u of \"%s\" has a network type that can't be saved in a \"%s\" file.",
1578 in_file->packet_num, display_basename,
1579 wtap_file_type_string(file_type));
1580 g_free(display_basename);
1584 display_basename = g_filename_display_basename(out_filename);
1585 simple_error_message_box(
1586 "An error occurred while writing to the file \"%s\": %s.",
1587 out_filename, wtap_strerror(write_err));
1588 g_free(display_basename);
1593 write_failure_alert_box(out_filename, write_err);
1597 if (got_read_error || got_write_error || stop_flag) {
1598 /* Callers aren't expected to treat an error or an explicit abort
1599 differently - we put up error dialogs ourselves, so they don't
1607 cf_filter_packets(capture_file *cf, gchar *dftext, gboolean force)
1609 const char *filter_new = dftext ? dftext : "";
1610 const char *filter_old = cf->dfilter ? cf->dfilter : "";
1612 GTimeVal start_time;
1614 /* if new filter equals old one, do nothing unless told to do so */
1615 if (!force && strcmp(filter_new, filter_old) == 0) {
1621 if (dftext == NULL) {
1622 /* The new filter is an empty filter (i.e., display all packets).
1623 * so leave dfcode==NULL
1627 * We have a filter; make a copy of it (as we'll be saving it),
1628 * and try to compile it.
1630 dftext = g_strdup(dftext);
1631 if (!dfilter_compile(dftext, &dfcode)) {
1632 /* The attempt failed; report an error. */
1633 simple_message_box(ESD_TYPE_ERROR, NULL,
1634 "See the help for a description of the display filter syntax.",
1635 "\"%s\" isn't a valid display filter: %s",
1636 dftext, dfilter_error_msg);
1642 if (dfcode == NULL) {
1643 /* Yes - free the filter text, and set it to null. */
1649 /* We have a valid filter. Replace the current filter. */
1650 g_free(cf->dfilter);
1651 cf->dfilter = dftext;
1652 g_get_current_time(&start_time);
1655 /* Now rescan the packet list, applying the new filter, but not
1656 throwing away information constructed on a previous pass. */
1657 if (dftext == NULL) {
1658 rescan_packets(cf, "Resetting", "Filter", FALSE);
1660 rescan_packets(cf, "Filtering", dftext, FALSE);
1663 /* Cleanup and release all dfilter resources */
1664 dfilter_free(dfcode);
1670 cf_reftime_packets(capture_file *cf)
1672 ref_time_packets(cf);
1676 cf_redissect_packets(capture_file *cf)
1678 rescan_packets(cf, "Reprocessing", "all packets", TRUE);
1682 cf_read_frame_r(capture_file *cf, frame_data *fdata,
1683 struct wtap_pkthdr *phdr, guint8 *pd)
1687 gchar *display_basename;
1689 #ifdef WANT_PACKET_EDITOR
1690 /* if fdata->file_off == -1 it means packet was edited, and we must find data inside edited_frames tree */
1691 if (G_UNLIKELY(fdata->file_off == -1)) {
1692 const modified_frame_data *frame = (const modified_frame_data *) g_tree_lookup(cf->edited_frames, GINT_TO_POINTER(fdata->num));
1695 simple_error_message_box("fdata->file_off == -1, but can't find modified frame!");
1699 *phdr = frame->phdr;
1700 memcpy(pd, frame->pd, fdata->cap_len);
1705 if (!wtap_seek_read(cf->wth, fdata->file_off, phdr, pd,
1706 fdata->cap_len, &err, &err_info)) {
1707 display_basename = g_filename_display_basename(cf->filename);
1710 case WTAP_ERR_UNSUPPORTED_ENCAP:
1711 simple_error_message_box("The file \"%s\" has a packet with a network type that Wireshark doesn't support.\n(%s)",
1712 display_basename, err_info);
1716 case WTAP_ERR_BAD_FILE:
1717 simple_error_message_box("An error occurred while reading from the file \"%s\": %s.\n(%s)",
1718 display_basename, wtap_strerror(err), err_info);
1723 simple_error_message_box(
1724 "An error occurred while reading from the file \"%s\": %s.",
1725 display_basename, wtap_strerror(err));
1728 g_free(display_basename);
1735 cf_read_frame(capture_file *cf, frame_data *fdata)
1737 return cf_read_frame_r(cf, fdata, &cf->phdr, cf->pd);
1740 /* Rescan the list of packets, reconstructing the CList.
1742 "action" describes why we're doing this; it's used in the progress
1745 "action_item" describes what we're doing; it's used in the progress
1748 "redissect" is TRUE if we need to make the dissectors reconstruct
1749 any state information they have (because a preference that affects
1750 some dissector has changed, meaning some dissector might construct
1751 its state differently from the way it was constructed the last time). */
1753 rescan_packets(capture_file *cf, const char *action, const char *action_item, gboolean redissect)
1755 /* Rescan packets new packet list */
1758 progdlg_t *progbar = NULL;
1761 frame_data *selected_frame, *preceding_frame, *following_frame, *prev_frame;
1762 int selected_frame_num, preceding_frame_num, following_frame_num, prev_frame_num;
1763 gboolean selected_frame_seen;
1765 GTimeVal start_time;
1766 gchar status_str[100];
1767 int progbar_nextstep;
1768 int progbar_quantum;
1771 gboolean create_proto_tree;
1773 gboolean add_to_packet_list = FALSE;
1775 guint32 frames_count;
1777 /* Compile the current display filter.
1778 * We assume this will not fail since cf->dfilter is only set in
1779 * cf_filter IFF the filter was valid.
1781 compiled = dfilter_compile(cf->dfilter, &dfcode);
1782 g_assert(!cf->dfilter || (compiled && dfcode));
1784 /* Get the union of the flags for all tap listeners. */
1785 tap_flags = union_of_tap_listener_flags();
1786 cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
1788 (dfcode != NULL || have_filtering_tap_listeners() || (tap_flags & TL_REQUIRES_PROTO_TREE));
1790 reset_tap_listeners();
1791 /* Which frame, if any, is the currently selected frame?
1792 XXX - should the selected frame or the focus frame be the "current"
1793 frame, that frame being the one from which "Find Frame" searches
1795 selected_frame = cf->current_frame;
1797 /* Mark frame num as not found */
1798 selected_frame_num = -1;
1800 /* Freeze the packet list while we redo it, so we don't get any
1801 screen updates while it happens. */
1802 packet_list_freeze();
1805 /* We need to re-initialize all the state information that protocols
1806 keep, because some preference that controls a dissector has changed,
1807 which might cause the state information to be constructed differently
1808 by that dissector. */
1810 /* We might receive new packets while redissecting, and we don't
1811 want to dissect those before their time. */
1812 cf->redissecting = TRUE;
1814 /* Cleanup all data structures used for dissection. */
1815 cleanup_dissection();
1816 /* Initialize all data structures used for dissection. */
1819 /* We need to redissect the packets so we have to discard our old
1820 * packet list store. */
1821 packet_list_clear();
1822 add_to_packet_list = TRUE;
1825 /* We don't yet know which will be the first and last frames displayed. */
1826 cf->first_displayed = 0;
1827 cf->last_displayed = 0;
1829 /* We currently don't display any packets */
1830 cf->displayed_count = 0;
1832 /* Iterate through the list of frames. Call a routine for each frame
1833 to check whether it should be displayed and, if so, add it to
1834 the display list. */
1835 nstime_set_unset(&first_ts);
1840 /* Update the progress bar when it gets to this value. */
1841 progbar_nextstep = 0;
1842 /* When we reach the value that triggers a progress bar update,
1843 bump that value by this amount. */
1844 progbar_quantum = cf->count/N_PROGBAR_UPDATES;
1845 /* Count of packets at which we've looked. */
1847 /* Progress so far. */
1851 g_get_current_time(&start_time);
1853 /* no previous row yet */
1854 prev_frame_num = -1;
1857 preceding_frame_num = -1;
1858 preceding_frame = NULL;
1859 following_frame_num = -1;
1860 following_frame = NULL;
1862 selected_frame_seen = FALSE;
1864 frames_count = cf->count;
1865 for (framenum = 1; framenum <= frames_count; framenum++) {
1866 fdata = frame_data_sequence_find(cf->frames, framenum);
1868 /* Create the progress bar if necessary.
1869 We check on every iteration of the loop, so that it takes no
1870 longer than the standard time to create it (otherwise, for a
1871 large file, we might take considerably longer than that standard
1872 time in order to get to the next progress bar step). */
1873 if (progbar == NULL)
1874 progbar = delayed_create_progress_dlg(cf->window, action, action_item, TRUE,
1875 &stop_flag, &start_time,
1878 /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
1879 when we update it, we have to run the GTK+ main loop to get it
1880 to repaint what's pending, and doing so may involve an "ioctl()"
1881 to see if there's any pending input from an X server, and doing
1882 that for every packet can be costly, especially on a big file. */
1883 if (count >= progbar_nextstep) {
1884 /* let's not divide by zero. I should never be started
1885 * with count == 0, so let's assert that
1887 g_assert(cf->count > 0);
1888 progbar_val = (gfloat) count / frames_count;
1890 if (progbar != NULL) {
1891 g_snprintf(status_str, sizeof(status_str),
1892 "%4u of %u frames", count, frames_count);
1893 update_progress_dlg(progbar, progbar_val, status_str);
1896 progbar_nextstep += progbar_quantum;
1900 /* Well, the user decided to abort the filtering. Just stop.
1902 XXX - go back to the previous filter? Users probably just
1903 want not to wait for a filtering operation to finish;
1904 unless we cancel by having no filter, reverting to the
1905 previous filter will probably be even more expensive than
1906 continuing the filtering, as it involves going back to the
1907 beginning and filtering, and even with no filter we currently
1908 have to re-generate the entire clist, which is also expensive.
1910 I'm not sure what Network Monitor does, but it doesn't appear
1911 to give you an unfiltered display if you cancel. */
1918 /* Since all state for the frame was destroyed, mark the frame
1919 * as not visited, free the GSList referring to the state
1920 * data (the per-frame data itself was freed by
1921 * "init_dissection()"), and null out the GSList pointer. */
1922 frame_data_reset(fdata);
1923 frames_count = cf->count;
1926 /* Frame dependencies from the previous dissection/filtering are no longer valid. */
1927 fdata->flags.dependent_of_displayed = 0;
1929 if (!cf_read_frame(cf, fdata))
1930 break; /* error reading the frame */
1932 /* If the previous frame is displayed, and we haven't yet seen the
1933 selected frame, remember that frame - it's the closest one we've
1934 yet seen before the selected frame. */
1935 if (prev_frame_num != -1 && !selected_frame_seen && prev_frame->flags.passed_dfilter) {
1936 preceding_frame_num = prev_frame_num;
1937 preceding_frame = prev_frame;
1939 add_packet_to_packet_list(fdata, cf, dfcode, create_proto_tree,
1940 cinfo, &cf->phdr, cf->pd,
1941 add_to_packet_list);
1943 /* If this frame is displayed, and this is the first frame we've
1944 seen displayed after the selected frame, remember this frame -
1945 it's the closest one we've yet seen at or after the selected
1947 if (fdata->flags.passed_dfilter && selected_frame_seen && following_frame_num == -1) {
1948 following_frame_num = fdata->num;
1949 following_frame = fdata;
1951 if (fdata == selected_frame) {
1952 selected_frame_seen = TRUE;
1953 if (fdata->flags.passed_dfilter)
1954 selected_frame_num = fdata->num;
1957 /* Remember this frame - it'll be the previous frame
1958 on the next pass through the loop. */
1959 prev_frame_num = fdata->num;
1963 /* We are done redissecting the packet list. */
1964 cf->redissecting = FALSE;
1967 frames_count = cf->count;
1968 /* Clear out what remains of the visited flags and per-frame data
1971 XXX - that may cause various forms of bogosity when dissecting
1972 these frames, as they won't have been seen by this sequential
1973 pass, but the only alternative I see is to keep scanning them
1974 even though the user requested that the scan stop, and that
1975 would leave the user stuck with an Wireshark grinding on
1976 until it finishes. Should we just stick them with that? */
1977 for (; framenum <= frames_count; framenum++) {
1978 fdata = frame_data_sequence_find(cf->frames, framenum);
1979 frame_data_reset(fdata);
1983 /* We're done filtering the packets; destroy the progress bar if it
1985 if (progbar != NULL)
1986 destroy_progress_dlg(progbar);
1988 /* Unfreeze the packet list. */
1989 if (!add_to_packet_list)
1990 packet_list_recreate_visible_rows();
1992 /* Compute the time it took to filter the file */
1993 compute_elapsed(&start_time);
1997 if (selected_frame_num == -1) {
1998 /* The selected frame didn't pass the filter. */
1999 if (selected_frame == NULL) {
2000 /* That's because there *was* no selected frame. Make the first
2001 displayed frame the current frame. */
2002 selected_frame_num = 0;
2004 /* Find the nearest displayed frame to the selected frame (whether
2005 it's before or after that frame) and make that the current frame.
2006 If the next and previous displayed frames are equidistant from the
2007 selected frame, choose the next one. */
2008 g_assert(following_frame == NULL ||
2009 following_frame->num >= selected_frame->num);
2010 g_assert(preceding_frame == NULL ||
2011 preceding_frame->num <= selected_frame->num);
2012 if (following_frame == NULL) {
2013 /* No frame after the selected frame passed the filter, so we
2014 have to select the last displayed frame before the selected
2016 selected_frame_num = preceding_frame_num;
2017 selected_frame = preceding_frame;
2018 } else if (preceding_frame == NULL) {
2019 /* No frame before the selected frame passed the filter, so we
2020 have to select the first displayed frame after the selected
2022 selected_frame_num = following_frame_num;
2023 selected_frame = following_frame;
2025 /* Frames before and after the selected frame passed the filter, so
2026 we'll select the previous frame */
2027 selected_frame_num = preceding_frame_num;
2028 selected_frame = preceding_frame;
2033 if (selected_frame_num == -1) {
2034 /* There are no frames displayed at all. */
2035 cf_unselect_packet(cf);
2037 /* Either the frame that was selected passed the filter, or we've
2038 found the nearest displayed frame to that frame. Select it, make
2039 it the focus row, and make it visible. */
2040 /* Set to invalid to force update of packet list and packet details */
2041 cf->current_row = -1;
2042 if (selected_frame_num == 0) {
2043 packet_list_select_first_row();
2045 if (!packet_list_select_row_from_data(selected_frame)) {
2046 /* We didn't find a row corresponding to this frame.
2047 This means that the frame isn't being displayed currently,
2048 so we can't select it. */
2049 simple_message_box(ESD_TYPE_INFO, NULL,
2050 "The capture file is probably not fully dissected.",
2051 "End of capture exceeded!");
2056 /* Cleanup and release all dfilter resources */
2057 dfilter_free(dfcode);
2062 * Scan trough all frame data and recalculate the ref time
2063 * without rereading the file.
2064 * XXX - do we need a progres bar or is this fast enough?
2067 ref_time_packets(capture_file *cf)
2072 nstime_set_unset(&first_ts);
2076 for (framenum = 1; framenum <= cf->count; framenum++) {
2077 fdata = frame_data_sequence_find(cf->frames, framenum);
2079 /* just add some value here until we know if it is being displayed or not */
2080 fdata->cum_bytes = cum_bytes + fdata->pkt_len;
2086 /* If we don't have the time stamp of the first packet in the
2087 capture, it's because this is the first packet. Save the time
2088 stamp of this packet as the time stamp of the first packet. */
2089 if (nstime_is_unset(&first_ts)) {
2090 first_ts = fdata->abs_ts;
2092 /* if this frames is marked as a reference time frame, reset
2093 firstsec and firstusec to this frame */
2094 if (fdata->flags.ref_time) {
2095 first_ts = fdata->abs_ts;
2098 /* If we don't have the time stamp of the previous displayed packet,
2099 it's because this is the first displayed packet. Save the time
2100 stamp of this packet as the time stamp of the previous displayed
2102 if (prev_dis == NULL) {
2106 /* Get the time elapsed between the first packet and this packet. */
2107 nstime_delta(&fdata->rel_ts, &fdata->abs_ts, &first_ts);
2109 /* If it's greater than the current elapsed time, set the elapsed time
2110 to it (we check for "greater than" so as not to be confused by
2111 time moving backwards). */
2112 if ((gint32)cf->elapsed_time.secs < fdata->rel_ts.secs
2113 || ((gint32)cf->elapsed_time.secs == fdata->rel_ts.secs && (gint32)cf->elapsed_time.nsecs < fdata->rel_ts.nsecs)) {
2114 cf->elapsed_time = fdata->rel_ts;
2117 /* If this frame is displayed, get the time elapsed between the
2118 previous displayed packet and this packet. */
2119 if ( fdata->flags.passed_dfilter ) {
2120 fdata->prev_dis = prev_dis;
2127 if ( (fdata->flags.passed_dfilter) || (fdata->flags.ref_time) ) {
2128 /* This frame either passed the display filter list or is marked as
2129 a time reference frame. All time reference frames are displayed
2130 even if they dont pass the display filter */
2131 if (fdata->flags.ref_time) {
2132 /* if this was a TIME REF frame we should reset the cum_bytes field */
2133 cum_bytes = fdata->pkt_len;
2134 fdata->cum_bytes = cum_bytes;
2136 /* increase cum_bytes with this packets length */
2137 cum_bytes += fdata->pkt_len;
2150 process_specified_packets(capture_file *cf, packet_range_t *range,
2151 const char *string1, const char *string2, gboolean terminate_is_stop,
2152 gboolean (*callback)(capture_file *, frame_data *,
2153 struct wtap_pkthdr *, const guint8 *, void *),
2154 void *callback_args)
2158 guint8 pd[WTAP_MAX_PACKET_SIZE+1];
2159 psp_return_t ret = PSP_FINISHED;
2161 progdlg_t *progbar = NULL;
2164 gboolean progbar_stop_flag;
2165 GTimeVal progbar_start_time;
2166 gchar progbar_status_str[100];
2167 int progbar_nextstep;
2168 int progbar_quantum;
2169 range_process_e process_this;
2170 struct wtap_pkthdr phdr;
2172 /* Update the progress bar when it gets to this value. */
2173 progbar_nextstep = 0;
2174 /* When we reach the value that triggers a progress bar update,
2175 bump that value by this amount. */
2176 progbar_quantum = cf->count/N_PROGBAR_UPDATES;
2177 /* Count of packets at which we've looked. */
2179 /* Progress so far. */
2182 progbar_stop_flag = FALSE;
2183 g_get_current_time(&progbar_start_time);
2186 packet_range_process_init(range);
2188 /* Iterate through all the packets, printing the packets that
2189 were selected by the current display filter. */
2190 for (framenum = 1; framenum <= cf->count; framenum++) {
2191 fdata = frame_data_sequence_find(cf->frames, framenum);
2193 /* Create the progress bar if necessary.
2194 We check on every iteration of the loop, so that it takes no
2195 longer than the standard time to create it (otherwise, for a
2196 large file, we might take considerably longer than that standard
2197 time in order to get to the next progress bar step). */
2198 if (progbar == NULL)
2199 progbar = delayed_create_progress_dlg(cf->window, string1, string2,
2202 &progbar_start_time,
2205 /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
2206 when we update it, we have to run the GTK+ main loop to get it
2207 to repaint what's pending, and doing so may involve an "ioctl()"
2208 to see if there's any pending input from an X server, and doing
2209 that for every packet can be costly, especially on a big file. */
2210 if (progbar_count >= progbar_nextstep) {
2211 /* let's not divide by zero. I should never be started
2212 * with count == 0, so let's assert that
2214 g_assert(cf->count > 0);
2215 progbar_val = (gfloat) progbar_count / cf->count;
2217 if (progbar != NULL) {
2218 g_snprintf(progbar_status_str, sizeof(progbar_status_str),
2219 "%4u of %u packets", progbar_count, cf->count);
2220 update_progress_dlg(progbar, progbar_val, progbar_status_str);
2223 progbar_nextstep += progbar_quantum;
2226 if (progbar_stop_flag) {
2227 /* Well, the user decided to abort the operation. Just stop,
2228 and arrange to return PSP_STOPPED to our caller, so they know
2229 it was stopped explicitly. */
2236 if (range != NULL) {
2237 /* do we have to process this packet? */
2238 process_this = packet_range_process_packet(range, fdata);
2239 if (process_this == range_process_next) {
2240 /* this packet uninteresting, continue with next one */
2242 } else if (process_this == range_processing_finished) {
2243 /* all interesting packets processed, stop the loop */
2248 /* Get the packet */
2249 if (!cf_read_frame_r(cf, fdata, &phdr, pd)) {
2250 /* Attempt to get the packet failed. */
2254 /* Process the packet */
2255 if (!callback(cf, fdata, &phdr, pd, callback_args)) {
2256 /* Callback failed. We assume it reported the error appropriately. */
2262 /* We're done printing the packets; destroy the progress bar if
2264 if (progbar != NULL)
2265 destroy_progress_dlg(progbar);
2271 gboolean construct_protocol_tree;
2273 } retap_callback_args_t;
2276 retap_packet(capture_file *cf _U_, frame_data *fdata,
2277 struct wtap_pkthdr *phdr, const guint8 *pd,
2280 retap_callback_args_t *args = (retap_callback_args_t *)argsp;
2283 epan_dissect_init(&edt, args->construct_protocol_tree, FALSE);
2284 epan_dissect_run_with_taps(&edt, phdr, pd, fdata, args->cinfo);
2285 epan_dissect_cleanup(&edt);
2291 cf_retap_packets(capture_file *cf)
2293 packet_range_t range;
2294 retap_callback_args_t callback_args;
2295 gboolean filtering_tap_listeners;
2298 /* Do we have any tap listeners with filters? */
2299 filtering_tap_listeners = have_filtering_tap_listeners();
2301 tap_flags = union_of_tap_listener_flags();
2303 /* If any tap listeners have filters, or require the protocol tree,
2304 construct the protocol tree. */
2305 callback_args.construct_protocol_tree = filtering_tap_listeners ||
2306 (tap_flags & TL_REQUIRES_PROTO_TREE);
2308 /* If any tap listeners require the columns, construct them. */
2309 callback_args.cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
2311 /* Reset the tap listeners. */
2312 reset_tap_listeners();
2314 /* Iterate through the list of packets, dissecting all packets and
2315 re-running the taps. */
2316 packet_range_init(&range, cf);
2317 packet_range_process_init(&range);
2318 switch (process_specified_packets(cf, &range, "Recalculating statistics on",
2319 "all packets", TRUE, retap_packet,
2322 /* Completed successfully. */
2326 /* Well, the user decided to abort the refiltering.
2327 Return CF_READ_ABORTED so our caller knows they did that. */
2328 return CF_READ_ABORTED;
2331 /* Error while retapping. */
2332 return CF_READ_ERROR;
2335 g_assert_not_reached();
2340 print_args_t *print_args;
2341 gboolean print_header_line;
2342 char *header_line_buf;
2343 int header_line_buf_len;
2344 gboolean print_formfeed;
2345 gboolean print_separator;
2349 int num_visible_cols;
2351 } print_callback_args_t;
2354 print_packet(capture_file *cf, frame_data *fdata,
2355 struct wtap_pkthdr *phdr, const guint8 *pd,
2358 print_callback_args_t *args = (print_callback_args_t *)argsp;
2365 gboolean proto_tree_needed;
2366 char bookmark_name[9+10+1]; /* "__frameNNNNNNNNNN__\0" */
2367 char bookmark_title[6+10+1]; /* "Frame NNNNNNNNNN__\0" */
2369 /* Create the protocol tree, and make it visible, if we're printing
2370 the dissection or the hex data.
2371 XXX - do we need it if we're just printing the hex data? */
2373 args->print_args->print_dissections != print_dissections_none || args->print_args->print_hex || have_custom_cols(&cf->cinfo);
2374 epan_dissect_init(&edt, proto_tree_needed, proto_tree_needed);
2376 /* Fill in the column information if we're printing the summary
2378 if (args->print_args->print_summary) {
2379 col_custom_prime_edt(&edt, &cf->cinfo);
2380 epan_dissect_run(&edt, phdr, pd, fdata, &cf->cinfo);
2381 epan_dissect_fill_in_columns(&edt, FALSE, TRUE);
2383 epan_dissect_run(&edt, phdr, pd, fdata, NULL);
2385 if (args->print_formfeed) {
2386 if (!new_page(args->print_args->stream))
2389 if (args->print_separator) {
2390 if (!print_line(args->print_args->stream, 0, ""))
2396 * We generate bookmarks, if the output format supports them.
2397 * The name is "__frameN__".
2399 g_snprintf(bookmark_name, sizeof bookmark_name, "__frame%u__", fdata->num);
2401 if (args->print_args->print_summary) {
2402 if (args->print_header_line) {
2403 if (!print_line(args->print_args->stream, 0, args->header_line_buf))
2405 args->print_header_line = FALSE; /* we might not need to print any more */
2407 cp = &args->line_buf[0];
2409 for (i = 0; i < args->num_visible_cols; i++) {
2410 /* Find the length of the string for this column. */
2411 column_len = (int) strlen(cf->cinfo.col_data[args->visible_cols[i]]);
2412 if (args->col_widths[i] > column_len)
2413 column_len = args->col_widths[i];
2415 /* Make sure there's room in the line buffer for the column; if not,
2416 double its length. */
2417 line_len += column_len + 1; /* "+1" for space */
2418 if (line_len > args->line_buf_len) {
2419 cp_off = (int) (cp - args->line_buf);
2420 args->line_buf_len = 2 * line_len;
2421 args->line_buf = (char *)g_realloc(args->line_buf, args->line_buf_len + 1);
2422 cp = args->line_buf + cp_off;
2425 /* Right-justify the packet number column. */
2426 if (cf->cinfo.col_fmt[args->visible_cols[i]] == COL_NUMBER)
2427 g_snprintf(cp, column_len+1, "%*s", args->col_widths[i], cf->cinfo.col_data[args->visible_cols[i]]);
2429 g_snprintf(cp, column_len+1, "%-*s", args->col_widths[i], cf->cinfo.col_data[args->visible_cols[i]]);
2431 if (i != args->num_visible_cols - 1)
2437 * Generate a bookmark, using the summary line as the title.
2439 if (!print_bookmark(args->print_args->stream, bookmark_name,
2443 if (!print_line(args->print_args->stream, 0, args->line_buf))
2447 * Generate a bookmark, using "Frame N" as the title, as we're not
2448 * printing the summary line.
2450 g_snprintf(bookmark_title, sizeof bookmark_title, "Frame %u", fdata->num);
2451 if (!print_bookmark(args->print_args->stream, bookmark_name,
2454 } /* if (print_summary) */
2456 if (args->print_args->print_dissections != print_dissections_none) {
2457 if (args->print_args->print_summary) {
2458 /* Separate the summary line from the tree with a blank line. */
2459 if (!print_line(args->print_args->stream, 0, ""))
2463 /* Print the information in that tree. */
2464 if (!proto_tree_print(args->print_args, &edt, args->print_args->stream))
2467 /* Print a blank line if we print anything after this (aka more than one packet). */
2468 args->print_separator = TRUE;
2470 /* Print a header line if we print any more packet summaries */
2471 args->print_header_line = TRUE;
2474 if (args->print_args->print_hex) {
2475 if (args->print_args->print_summary || (args->print_args->print_dissections != print_dissections_none)) {
2476 if (!print_line(args->print_args->stream, 0, ""))
2479 /* Print the full packet data as hex. */
2480 if (!print_hex_data(args->print_args->stream, &edt))
2483 /* Print a blank line if we print anything after this (aka more than one packet). */
2484 args->print_separator = TRUE;
2486 /* Print a header line if we print any more packet summaries */
2487 args->print_header_line = TRUE;
2488 } /* if (args->print_args->print_dissections != print_dissections_none) */
2490 epan_dissect_cleanup(&edt);
2492 /* do we want to have a formfeed between each packet from now on? */
2493 if (args->print_args->print_formfeed) {
2494 args->print_formfeed = TRUE;
2500 epan_dissect_cleanup(&edt);
2505 cf_print_packets(capture_file *cf, print_args_t *print_args)
2507 print_callback_args_t callback_args;
2510 int i, cp_off, column_len, line_len;
2511 int num_visible_col = 0, last_visible_col = 0, visible_col_count;
2516 callback_args.print_args = print_args;
2517 callback_args.print_header_line = TRUE;
2518 callback_args.header_line_buf = NULL;
2519 callback_args.header_line_buf_len = 256;
2520 callback_args.print_formfeed = FALSE;
2521 callback_args.print_separator = FALSE;
2522 callback_args.line_buf = NULL;
2523 callback_args.line_buf_len = 256;
2524 callback_args.col_widths = NULL;
2525 callback_args.num_visible_cols = 0;
2526 callback_args.visible_cols = NULL;
2528 if (!print_preamble(print_args->stream, cf->filename)) {
2529 destroy_print_stream(print_args->stream);
2530 return CF_PRINT_WRITE_ERROR;
2533 if (print_args->print_summary) {
2534 /* We're printing packet summaries. Allocate the header line buffer
2535 and get the column widths. */
2536 callback_args.header_line_buf = (char *)g_malloc(callback_args.header_line_buf_len + 1);
2538 /* Find the number of visible columns and the last visible column */
2539 for (i = 0; i < prefs.num_cols; i++) {
2541 clp = g_list_nth(prefs.col_list, i);
2542 if (clp == NULL) /* Sanity check, Invalid column requested */
2545 cfmt = (fmt_data *) clp->data;
2546 if (cfmt->visible) {
2548 last_visible_col = i;
2552 /* Find the widths for each of the columns - maximum of the
2553 width of the title and the width of the data - and construct
2554 a buffer with a line containing the column titles. */
2555 callback_args.num_visible_cols = num_visible_col;
2556 callback_args.col_widths = (gint *) g_malloc(sizeof(gint) * num_visible_col);
2557 callback_args.visible_cols = (gint *) g_malloc(sizeof(gint) * num_visible_col);
2558 cp = &callback_args.header_line_buf[0];
2560 visible_col_count = 0;
2561 for (i = 0; i < cf->cinfo.num_cols; i++) {
2563 clp = g_list_nth(prefs.col_list, i);
2564 if (clp == NULL) /* Sanity check, Invalid column requested */
2567 cfmt = (fmt_data *) clp->data;
2568 if (cfmt->visible == FALSE)
2571 /* Save the order of visible columns */
2572 callback_args.visible_cols[visible_col_count] = i;
2574 /* Don't pad the last column. */
2575 if (i == last_visible_col)
2576 callback_args.col_widths[visible_col_count] = 0;
2578 callback_args.col_widths[visible_col_count] = (gint) strlen(cf->cinfo.col_title[i]);
2579 data_width = get_column_char_width(get_column_format(i));
2580 if (data_width > callback_args.col_widths[visible_col_count])
2581 callback_args.col_widths[visible_col_count] = data_width;
2584 /* Find the length of the string for this column. */
2585 column_len = (int) strlen(cf->cinfo.col_title[i]);
2586 if (callback_args.col_widths[i] > column_len)
2587 column_len = callback_args.col_widths[visible_col_count];
2589 /* Make sure there's room in the line buffer for the column; if not,
2590 double its length. */
2591 line_len += column_len + 1; /* "+1" for space */
2592 if (line_len > callback_args.header_line_buf_len) {
2593 cp_off = (int) (cp - callback_args.header_line_buf);
2594 callback_args.header_line_buf_len = 2 * line_len;
2595 callback_args.header_line_buf = (char *)g_realloc(callback_args.header_line_buf,
2596 callback_args.header_line_buf_len + 1);
2597 cp = callback_args.header_line_buf + cp_off;
2600 /* Right-justify the packet number column. */
2601 /* if (cf->cinfo.col_fmt[i] == COL_NUMBER)
2602 g_snprintf(cp, column_len+1, "%*s", callback_args.col_widths[visible_col_count], cf->cinfo.col_title[i]);
2604 g_snprintf(cp, column_len+1, "%-*s", callback_args.col_widths[visible_col_count], cf->cinfo.col_title[i]);
2606 if (i != cf->cinfo.num_cols - 1)
2609 visible_col_count++;
2613 /* Now start out the main line buffer with the same length as the
2614 header line buffer. */
2615 callback_args.line_buf_len = callback_args.header_line_buf_len;
2616 callback_args.line_buf = (char *)g_malloc(callback_args.line_buf_len + 1);
2617 } /* if (print_summary) */
2619 /* Iterate through the list of packets, printing the packets we were
2621 ret = process_specified_packets(cf, &print_args->range, "Printing",
2622 "selected packets", TRUE, print_packet,
2625 g_free(callback_args.header_line_buf);
2626 g_free(callback_args.line_buf);
2627 g_free(callback_args.col_widths);
2628 g_free(callback_args.visible_cols);
2633 /* Completed successfully. */
2637 /* Well, the user decided to abort the printing.
2639 XXX - note that what got generated before they did that
2640 will get printed if we're piping to a print program; we'd
2641 have to write to a file and then hand that to the print
2642 program to make it actually not print anything. */
2646 /* Error while printing.
2648 XXX - note that what got generated before they did that
2649 will get printed if we're piping to a print program; we'd
2650 have to write to a file and then hand that to the print
2651 program to make it actually not print anything. */
2652 destroy_print_stream(print_args->stream);
2653 return CF_PRINT_WRITE_ERROR;
2656 if (!print_finale(print_args->stream)) {
2657 destroy_print_stream(print_args->stream);
2658 return CF_PRINT_WRITE_ERROR;
2661 if (!destroy_print_stream(print_args->stream))
2662 return CF_PRINT_WRITE_ERROR;
2668 write_pdml_packet(capture_file *cf _U_, frame_data *fdata,
2669 struct wtap_pkthdr *phdr, const guint8 *pd,
2672 FILE *fh = (FILE *)argsp;
2675 /* Create the protocol tree, but don't fill in the column information. */
2676 epan_dissect_init(&edt, TRUE, TRUE);
2677 epan_dissect_run(&edt, phdr, pd, fdata, NULL);
2679 /* Write out the information in that tree. */
2680 proto_tree_write_pdml(&edt, fh);
2682 epan_dissect_cleanup(&edt);
2688 cf_write_pdml_packets(capture_file *cf, print_args_t *print_args)
2693 fh = ws_fopen(print_args->file, "w");
2695 return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2697 write_pdml_preamble(fh, cf->filename);
2700 return CF_PRINT_WRITE_ERROR;
2703 /* Iterate through the list of packets, printing the packets we were
2705 ret = process_specified_packets(cf, &print_args->range, "Writing PDML",
2706 "selected packets", TRUE,
2707 write_pdml_packet, fh);
2712 /* Completed successfully. */
2716 /* Well, the user decided to abort the printing. */
2720 /* Error while printing. */
2722 return CF_PRINT_WRITE_ERROR;
2725 write_pdml_finale(fh);
2728 return CF_PRINT_WRITE_ERROR;
2731 /* XXX - check for an error */
2738 write_psml_packet(capture_file *cf, frame_data *fdata,
2739 struct wtap_pkthdr *phdr, const guint8 *pd,
2742 FILE *fh = (FILE *)argsp;
2744 gboolean proto_tree_needed;
2746 /* Fill in the column information, only create the protocol tree
2747 if having custom columns. */
2748 proto_tree_needed = have_custom_cols(&cf->cinfo);
2749 epan_dissect_init(&edt, proto_tree_needed, proto_tree_needed);
2750 col_custom_prime_edt(&edt, &cf->cinfo);
2751 epan_dissect_run(&edt, phdr, pd, fdata, &cf->cinfo);
2752 epan_dissect_fill_in_columns(&edt, FALSE, TRUE);
2754 /* Write out the information in that tree. */
2755 proto_tree_write_psml(&edt, fh);
2757 epan_dissect_cleanup(&edt);
2763 cf_write_psml_packets(capture_file *cf, print_args_t *print_args)
2768 fh = ws_fopen(print_args->file, "w");
2770 return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2772 write_psml_preamble(fh);
2775 return CF_PRINT_WRITE_ERROR;
2778 /* Iterate through the list of packets, printing the packets we were
2780 ret = process_specified_packets(cf, &print_args->range, "Writing PSML",
2781 "selected packets", TRUE,
2782 write_psml_packet, fh);
2787 /* Completed successfully. */
2791 /* Well, the user decided to abort the printing. */
2795 /* Error while printing. */
2797 return CF_PRINT_WRITE_ERROR;
2800 write_psml_finale(fh);
2803 return CF_PRINT_WRITE_ERROR;
2806 /* XXX - check for an error */
2813 write_csv_packet(capture_file *cf, frame_data *fdata,
2814 struct wtap_pkthdr *phdr, const guint8 *pd,
2817 FILE *fh = (FILE *)argsp;
2819 gboolean proto_tree_needed;
2821 /* Fill in the column information, only create the protocol tree
2822 if having custom columns. */
2823 proto_tree_needed = have_custom_cols(&cf->cinfo);
2824 epan_dissect_init(&edt, proto_tree_needed, proto_tree_needed);
2825 col_custom_prime_edt(&edt, &cf->cinfo);
2826 epan_dissect_run(&edt, phdr, pd, fdata, &cf->cinfo);
2827 epan_dissect_fill_in_columns(&edt, FALSE, TRUE);
2829 /* Write out the information in that tree. */
2830 proto_tree_write_csv(&edt, fh);
2832 epan_dissect_cleanup(&edt);
2838 cf_write_csv_packets(capture_file *cf, print_args_t *print_args)
2843 fh = ws_fopen(print_args->file, "w");
2845 return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2847 write_csv_preamble(fh);
2850 return CF_PRINT_WRITE_ERROR;
2853 /* Iterate through the list of packets, printing the packets we were
2855 ret = process_specified_packets(cf, &print_args->range, "Writing CSV",
2856 "selected packets", TRUE,
2857 write_csv_packet, fh);
2862 /* Completed successfully. */
2866 /* Well, the user decided to abort the printing. */
2870 /* Error while printing. */
2872 return CF_PRINT_WRITE_ERROR;
2875 write_csv_finale(fh);
2878 return CF_PRINT_WRITE_ERROR;
2881 /* XXX - check for an error */
2888 write_carrays_packet(capture_file *cf _U_, frame_data *fdata,
2889 struct wtap_pkthdr *phdr,
2890 const guint8 *pd, void *argsp)
2892 FILE *fh = (FILE *)argsp;
2895 epan_dissect_init(&edt, TRUE, TRUE);
2896 epan_dissect_run(&edt, phdr, pd, fdata, NULL);
2897 proto_tree_write_carrays(fdata->num, fh, &edt);
2898 epan_dissect_cleanup(&edt);
2904 cf_write_carrays_packets(capture_file *cf, print_args_t *print_args)
2909 fh = ws_fopen(print_args->file, "w");
2912 return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2914 write_carrays_preamble(fh);
2918 return CF_PRINT_WRITE_ERROR;
2921 /* Iterate through the list of packets, printing the packets we were
2923 ret = process_specified_packets(cf, &print_args->range,
2925 "selected packets", TRUE,
2926 write_carrays_packet, fh);
2929 /* Completed successfully. */
2932 /* Well, the user decided to abort the printing. */
2935 /* Error while printing. */
2937 return CF_PRINT_WRITE_ERROR;
2940 write_carrays_finale(fh);
2944 return CF_PRINT_WRITE_ERROR;
2952 cf_find_packet_protocol_tree(capture_file *cf, const char *string,
2953 search_direction dir)
2957 mdata.string = string;
2958 mdata.string_len = strlen(string);
2959 return find_packet(cf, match_protocol_tree, &mdata, dir);
2963 cf_find_string_protocol_tree(capture_file *cf, proto_tree *tree, match_data *mdata)
2965 mdata->frame_matched = FALSE;
2966 mdata->string = convert_string_case(cf->sfilter, cf->case_type);
2967 mdata->string_len = strlen(mdata->string);
2969 /* Iterate through all the nodes looking for matching text */
2970 proto_tree_children_foreach(tree, match_subtree_text, mdata);
2971 return mdata->frame_matched ? MR_MATCHED : MR_NOTMATCHED;
2975 match_protocol_tree(capture_file *cf, frame_data *fdata, void *criterion)
2977 match_data *mdata = (match_data *)criterion;
2980 /* Load the frame's data. */
2981 if (!cf_read_frame(cf, fdata)) {
2982 /* Attempt to get the packet failed. */
2986 /* Construct the protocol tree, including the displayed text */
2987 epan_dissect_init(&edt, TRUE, TRUE);
2988 /* We don't need the column information */
2989 epan_dissect_run(&edt, &cf->phdr, cf->pd, fdata, NULL);
2991 /* Iterate through all the nodes, seeing if they have text that matches. */
2993 mdata->frame_matched = FALSE;
2994 proto_tree_children_foreach(edt.tree, match_subtree_text, mdata);
2995 epan_dissect_cleanup(&edt);
2996 return mdata->frame_matched ? MR_MATCHED : MR_NOTMATCHED;
3000 match_subtree_text(proto_node *node, gpointer data)
3002 match_data *mdata = (match_data *) data;
3003 const gchar *string = mdata->string;
3004 size_t string_len = mdata->string_len;
3005 capture_file *cf = mdata->cf;
3006 field_info *fi = PNODE_FINFO(node);
3007 gchar label_str[ITEM_LABEL_LENGTH];
3014 /* dissection with an invisible proto tree? */
3017 if (mdata->frame_matched) {
3018 /* We already had a match; don't bother doing any more work. */
3022 /* Don't match invisible entries. */
3023 if (PROTO_ITEM_IS_HIDDEN(node))
3026 /* was a free format label produced? */
3028 label_ptr = fi->rep->representation;
3030 /* no, make a generic label */
3031 label_ptr = label_str;
3032 proto_item_fill_label(fi, label_str);
3035 /* Does that label match? */
3036 label_len = strlen(label_ptr);
3037 for (i = 0; i < label_len; i++) {
3038 c_char = label_ptr[i];
3040 c_char = toupper(c_char);
3041 if (c_char == string[c_match]) {
3043 if (c_match == string_len) {
3044 /* No need to look further; we have a match */
3045 mdata->frame_matched = TRUE;
3053 /* Recurse into the subtree, if it exists */
3054 if (node->first_child != NULL)
3055 proto_tree_children_foreach(node, match_subtree_text, mdata);
3059 cf_find_packet_summary_line(capture_file *cf, const char *string,
3060 search_direction dir)
3064 mdata.string = string;
3065 mdata.string_len = strlen(string);
3066 return find_packet(cf, match_summary_line, &mdata, dir);
3070 match_summary_line(capture_file *cf, frame_data *fdata, void *criterion)
3072 match_data *mdata = (match_data *)criterion;
3073 const gchar *string = mdata->string;
3074 size_t string_len = mdata->string_len;
3076 const char *info_column;
3077 size_t info_column_len;
3078 match_result result = MR_NOTMATCHED;
3084 /* Load the frame's data. */
3085 if (!cf_read_frame(cf, fdata)) {
3086 /* Attempt to get the packet failed. */
3090 /* Don't bother constructing the protocol tree */
3091 epan_dissect_init(&edt, FALSE, FALSE);
3092 /* Get the column information */
3093 epan_dissect_run(&edt, &cf->phdr, cf->pd, fdata, &cf->cinfo);
3095 /* Find the Info column */
3096 for (colx = 0; colx < cf->cinfo.num_cols; colx++) {
3097 if (cf->cinfo.fmt_matx[colx][COL_INFO]) {
3098 /* Found it. See if we match. */
3099 info_column = edt.pi.cinfo->col_data[colx];
3100 info_column_len = strlen(info_column);
3101 for (i = 0; i < info_column_len; i++) {
3102 c_char = info_column[i];
3104 c_char = toupper(c_char);
3105 if (c_char == string[c_match]) {
3107 if (c_match == string_len) {
3108 result = MR_MATCHED;
3117 epan_dissect_cleanup(&edt);
3124 } cbs_t; /* "Counted byte string" */
3128 * The current match_* routines only support ASCII case insensitivity and don't
3129 * convert UTF-8 inputs to UTF-16 for matching.
3131 * We could modify them to use the GLib Unicode routines or the International
3132 * Components for Unicode library but it's not apparent that we could do so
3133 * without consuming a lot more CPU and memory or that searching would be
3134 * significantly better.
3138 cf_find_packet_data(capture_file *cf, const guint8 *string, size_t string_size,
3139 search_direction dir)
3144 info.data_len = string_size;
3146 /* String or hex search? */
3148 /* String search - what type of string? */
3149 switch (cf->scs_type) {
3151 case SCS_NARROW_AND_WIDE:
3152 return find_packet(cf, match_narrow_and_wide, &info, dir);
3155 return find_packet(cf, match_narrow, &info, dir);
3158 return find_packet(cf, match_wide, &info, dir);
3161 g_assert_not_reached();
3165 return find_packet(cf, match_binary, &info, dir);
3169 match_narrow_and_wide(capture_file *cf, frame_data *fdata, void *criterion)
3171 cbs_t *info = (cbs_t *)criterion;
3172 const guint8 *ascii_text = info->data;
3173 size_t textlen = info->data_len;
3174 match_result result;
3180 /* Load the frame's data. */
3181 if (!cf_read_frame(cf, fdata)) {
3182 /* Attempt to get the packet failed. */
3186 result = MR_NOTMATCHED;
3187 buf_len = fdata->cap_len;
3189 while (i < buf_len) {
3192 c_char = toupper(c_char);
3193 if (c_char != '\0') {
3194 if (c_char == ascii_text[c_match]) {
3196 if (c_match == textlen) {
3197 result = MR_MATCHED;
3198 cf->search_pos = i; /* Save the position of the last character
3199 for highlighting the field. */
3204 g_assert(i>=c_match);
3205 i -= (guint32)c_match;
3215 match_narrow(capture_file *cf, frame_data *fdata, void *criterion)
3217 cbs_t *info = (cbs_t *)criterion;
3218 const guint8 *ascii_text = info->data;
3219 size_t textlen = info->data_len;
3220 match_result result;
3226 /* Load the frame's data. */
3227 if (!cf_read_frame(cf, fdata)) {
3228 /* Attempt to get the packet failed. */
3232 result = MR_NOTMATCHED;
3233 buf_len = fdata->cap_len;
3235 while (i < buf_len) {
3238 c_char = toupper(c_char);
3239 if (c_char == ascii_text[c_match]) {
3241 if (c_match == textlen) {
3242 result = MR_MATCHED;
3243 cf->search_pos = i; /* Save the position of the last character
3244 for highlighting the field. */
3249 g_assert(i>=c_match);
3250 i -= (guint32)c_match;
3260 match_wide(capture_file *cf, frame_data *fdata, void *criterion)
3262 cbs_t *info = (cbs_t *)criterion;
3263 const guint8 *ascii_text = info->data;
3264 size_t textlen = info->data_len;
3265 match_result result;
3271 /* Load the frame's data. */
3272 if (!cf_read_frame(cf, fdata)) {
3273 /* Attempt to get the packet failed. */
3277 result = MR_NOTMATCHED;
3278 buf_len = fdata->cap_len;
3280 while (i < buf_len) {
3283 c_char = toupper(c_char);
3284 if (c_char == ascii_text[c_match]) {
3286 if (c_match == textlen) {
3287 result = MR_MATCHED;
3288 cf->search_pos = i; /* Save the position of the last character
3289 for highlighting the field. */
3295 g_assert(i>=(c_match*2));
3296 i -= (guint32)c_match*2;
3305 match_binary(capture_file *cf, frame_data *fdata, void *criterion)
3307 cbs_t *info = (cbs_t *)criterion;
3308 const guint8 *binary_data = info->data;
3309 size_t datalen = info->data_len;
3310 match_result result;
3315 /* Load the frame's data. */
3316 if (!cf_read_frame(cf, fdata)) {
3317 /* Attempt to get the packet failed. */
3321 result = MR_NOTMATCHED;
3322 buf_len = fdata->cap_len;
3324 while (i < buf_len) {
3325 if (cf->pd[i] == binary_data[c_match]) {
3327 if (c_match == datalen) {
3328 result = MR_MATCHED;
3329 cf->search_pos = i; /* Save the position of the last character
3330 for highlighting the field. */
3335 g_assert(i>=c_match);
3336 i -= (guint32)c_match;
3345 cf_find_packet_dfilter(capture_file *cf, dfilter_t *sfcode,
3346 search_direction dir)
3348 return find_packet(cf, match_dfilter, sfcode, dir);
3352 cf_find_packet_dfilter_string(capture_file *cf, const char *filter,
3353 search_direction dir)
3358 if (!dfilter_compile(filter, &sfcode)) {
3360 * XXX - this shouldn't happen, as the filter string is machine
3365 if (sfcode == NULL) {
3367 * XXX - this shouldn't happen, as the filter string is machine
3372 result = find_packet(cf, match_dfilter, sfcode, dir);
3373 dfilter_free(sfcode);
3378 match_dfilter(capture_file *cf, frame_data *fdata, void *criterion)
3380 dfilter_t *sfcode = (dfilter_t *)criterion;
3382 match_result result;
3384 /* Load the frame's data. */
3385 if (!cf_read_frame(cf, fdata)) {
3386 /* Attempt to get the packet failed. */
3390 epan_dissect_init(&edt, TRUE, FALSE);
3391 epan_dissect_prime_dfilter(&edt, sfcode);
3392 epan_dissect_run(&edt, &cf->phdr, cf->pd, fdata, NULL);
3393 result = dfilter_apply_edt(sfcode, &edt) ? MR_MATCHED : MR_NOTMATCHED;
3394 epan_dissect_cleanup(&edt);
3399 cf_find_packet_marked(capture_file *cf, search_direction dir)
3401 return find_packet(cf, match_marked, NULL, dir);
3405 match_marked(capture_file *cf _U_, frame_data *fdata, void *criterion _U_)
3407 return fdata->flags.marked ? MR_MATCHED : MR_NOTMATCHED;
3411 cf_find_packet_time_reference(capture_file *cf, search_direction dir)
3413 return find_packet(cf, match_time_reference, NULL, dir);
3417 match_time_reference(capture_file *cf _U_, frame_data *fdata, void *criterion _U_)
3419 return fdata->flags.ref_time ? MR_MATCHED : MR_NOTMATCHED;
3423 find_packet(capture_file *cf,
3424 match_result (*match_function)(capture_file *, frame_data *, void *),
3425 void *criterion, search_direction dir)
3427 frame_data *start_fd;
3430 frame_data *new_fd = NULL;
3431 progdlg_t *progbar = NULL;
3436 GTimeVal start_time;
3437 gchar status_str[100];
3438 int progbar_nextstep;
3439 int progbar_quantum;
3441 match_result result;
3443 start_fd = cf->current_frame;
3444 if (start_fd != NULL) {
3445 /* Iterate through the list of packets, starting at the packet we've
3446 picked, calling a routine to run the filter on the packet, see if
3447 it matches, and stop if so. */
3449 framenum = start_fd->num;
3451 /* Update the progress bar when it gets to this value. */
3452 progbar_nextstep = 0;
3453 /* When we reach the value that triggers a progress bar update,
3454 bump that value by this amount. */
3455 progbar_quantum = cf->count/N_PROGBAR_UPDATES;
3456 /* Progress so far. */
3460 g_get_current_time(&start_time);
3462 title = cf->sfilter?cf->sfilter:"";
3464 /* Create the progress bar if necessary.
3465 We check on every iteration of the loop, so that it takes no
3466 longer than the standard time to create it (otherwise, for a
3467 large file, we might take considerably longer than that standard
3468 time in order to get to the next progress bar step). */
3469 if (progbar == NULL)
3470 progbar = delayed_create_progress_dlg(cf->window, "Searching", title,
3471 FALSE, &stop_flag, &start_time, progbar_val);
3473 /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
3474 when we update it, we have to run the GTK+ main loop to get it
3475 to repaint what's pending, and doing so may involve an "ioctl()"
3476 to see if there's any pending input from an X server, and doing
3477 that for every packet can be costly, especially on a big file. */
3478 if (count >= progbar_nextstep) {
3479 /* let's not divide by zero. I should never be started
3480 * with count == 0, so let's assert that
3482 g_assert(cf->count > 0);
3484 progbar_val = (gfloat) count / cf->count;
3486 if (progbar != NULL) {
3487 g_snprintf(status_str, sizeof(status_str),
3488 "%4u of %u packets", count, cf->count);
3489 update_progress_dlg(progbar, progbar_val, status_str);
3492 progbar_nextstep += progbar_quantum;
3496 /* Well, the user decided to abort the search. Go back to the
3497 frame where we started. */
3502 /* Go past the current frame. */
3503 if (dir == SD_BACKWARD) {
3504 /* Go on to the previous frame. */
3505 if (framenum == 1) {
3507 * XXX - other apps have a bit more of a detailed message
3508 * for this, and instead of offering "OK" and "Cancel",
3509 * they offer things such as "Continue" and "Cancel";
3510 * we need an API for popping up alert boxes with
3511 * {Verb} and "Cancel".
3514 if (prefs.gui_find_wrap)
3516 statusbar_push_temporary_msg("Search reached the beginning. Continuing at end.");
3517 framenum = cf->count; /* wrap around */
3521 statusbar_push_temporary_msg("Search reached the beginning.");
3522 framenum = start_fd->num; /* stay on previous packet */
3527 /* Go on to the next frame. */
3528 if (framenum == cf->count) {
3529 if (prefs.gui_find_wrap)
3531 statusbar_push_temporary_msg("Search reached the end. Continuing at beginning.");
3532 framenum = 1; /* wrap around */
3536 statusbar_push_temporary_msg("Search reached the end.");
3537 framenum = start_fd->num; /* stay on previous packet */
3542 fdata = frame_data_sequence_find(cf->frames, framenum);
3546 /* Is this packet in the display? */
3547 if (fdata->flags.passed_dfilter) {
3548 /* Yes. Does it match the search criterion? */
3549 result = (*match_function)(cf, fdata, criterion);
3550 if (result == MR_ERROR) {
3551 /* Error; our caller has reported the error. Go back to the frame
3552 where we started. */
3555 } else if (result == MR_MATCHED) {
3556 /* Yes. Go to the new frame. */
3562 if (fdata == start_fd) {
3563 /* We're back to the frame we were on originally, and that frame
3564 doesn't match the search filter. The search failed. */
3569 /* We're done scanning the packets; destroy the progress bar if it
3571 if (progbar != NULL)
3572 destroy_progress_dlg(progbar);
3575 if (new_fd != NULL) {
3576 /* Find and select */
3577 cf->search_in_progress = TRUE;
3578 found = packet_list_select_row_from_data(new_fd);
3579 cf->search_in_progress = FALSE;
3580 cf->search_pos = 0; /* Reset the position */
3582 /* We didn't find a row corresponding to this frame.
3583 This means that the frame isn't being displayed currently,
3584 so we can't select it. */
3585 simple_message_box(ESD_TYPE_INFO, NULL,
3586 "The capture file is probably not fully dissected.",
3587 "End of capture exceeded!");
3590 return TRUE; /* success */
3592 return FALSE; /* failure */
3596 cf_goto_frame(capture_file *cf, guint fnumber)
3600 fdata = frame_data_sequence_find(cf->frames, fnumber);
3602 if (fdata == NULL) {
3603 /* we didn't find a packet with that packet number */
3604 statusbar_push_temporary_msg("There is no packet number %u.", fnumber);
3605 return FALSE; /* we failed to go to that packet */
3607 if (!fdata->flags.passed_dfilter) {
3608 /* that packet currently isn't displayed */
3609 /* XXX - add it to the set of displayed packets? */
3610 statusbar_push_temporary_msg("Packet number %u isn't displayed.", fnumber);
3611 return FALSE; /* we failed to go to that packet */
3614 if (!packet_list_select_row_from_data(fdata)) {
3615 /* We didn't find a row corresponding to this frame.
3616 This means that the frame isn't being displayed currently,
3617 so we can't select it. */
3618 simple_message_box(ESD_TYPE_INFO, NULL,
3619 "The capture file is probably not fully dissected.",
3620 "End of capture exceeded!");
3623 return TRUE; /* we got to that packet */
3627 cf_goto_top_frame(void)
3629 /* Find and select */
3630 packet_list_select_first_row();
3631 return TRUE; /* we got to that packet */
3635 cf_goto_bottom_frame(void)
3637 /* Find and select */
3638 packet_list_select_last_row();
3639 return TRUE; /* we got to that packet */
3643 * Go to frame specified by currently selected protocol tree item.
3646 cf_goto_framenum(capture_file *cf)
3648 header_field_info *hfinfo;
3651 if (cf->finfo_selected) {
3652 hfinfo = cf->finfo_selected->hfinfo;
3654 if (hfinfo->type == FT_FRAMENUM) {
3655 framenum = fvalue_get_uinteger(&cf->finfo_selected->value);
3657 return cf_goto_frame(cf, framenum);
3664 /* Select the packet on a given row. */
3666 cf_select_packet(capture_file *cf, int row)
3668 epan_dissect_t *old_edt;
3671 /* Get the frame data struct pointer for this frame */
3672 fdata = packet_list_get_row_data(row);
3674 if (fdata == NULL) {
3675 /* XXX - if a GtkCList's selection mode is GTK_SELECTION_BROWSE, when
3676 the first entry is added to it by "real_insert_row()", that row
3677 is selected (see "real_insert_row()", in "ui/gtk/gtkclist.c", in both
3678 our version and the vanilla GTK+ version).
3680 This means that a "select-row" signal is emitted; this causes
3681 "packet_list_select_cb()" to be called, which causes "cf_select_packet()"
3684 "cf_select_packet()" fetches, above, the data associated with the
3685 row that was selected; however, as "gtk_clist_append()", which
3686 called "real_insert_row()", hasn't yet returned, we haven't yet
3687 associated any data with that row, so we get back a null pointer.
3689 We can't assume that there's only one frame in the frame list,
3690 either, as we may be filtering the display.
3692 We therefore assume that, if "row" is 0, i.e. the first row
3693 is being selected, and "cf->first_displayed" equals
3694 "cf->last_displayed", i.e. there's only one frame being
3695 displayed, that frame is the frame we want.
3697 This means we have to set "cf->first_displayed" and
3698 "cf->last_displayed" before adding the row to the
3699 GtkCList; see the comment in "add_packet_to_packet_list()". */
3701 if (row == 0 && cf->first_displayed == cf->last_displayed)
3702 fdata = frame_data_sequence_find(cf->frames, cf->first_displayed);
3705 /* If fdata _still_ isn't set simply give up. */
3706 if (fdata == NULL) {
3710 /* Get the data in that frame. */
3711 if (!cf_read_frame (cf, fdata)) {
3715 /* Record that this frame is the current frame. */
3716 cf->current_frame = fdata;
3717 cf->current_row = row;
3720 /* Create the logical protocol tree. */
3721 /* We don't need the columns here. */
3722 cf->edt = epan_dissect_new(TRUE, TRUE);
3724 tap_build_interesting(cf->edt);
3725 epan_dissect_run(cf->edt, &cf->phdr, cf->pd, cf->current_frame,
3728 dfilter_macro_build_ftv_cache(cf->edt->tree);
3730 cf_callback_invoke(cf_cb_packet_selected, cf);
3732 if (old_edt != NULL)
3733 epan_dissect_free(old_edt);
3737 /* Unselect the selected packet, if any. */
3739 cf_unselect_packet(capture_file *cf)
3741 epan_dissect_t *old_edt = cf->edt;
3745 /* No packet is selected. */
3746 cf->current_frame = NULL;
3747 cf->current_row = 0;
3749 cf_callback_invoke(cf_cb_packet_unselected, cf);
3751 /* No protocol tree means no selected field. */
3752 cf_unselect_field(cf);
3754 /* Destroy the epan_dissect_t for the unselected packet. */
3755 if (old_edt != NULL)
3756 epan_dissect_free(old_edt);
3759 /* Unset the selected protocol tree field, if any. */
3761 cf_unselect_field(capture_file *cf)
3763 cf->finfo_selected = NULL;
3765 cf_callback_invoke(cf_cb_field_unselected, cf);
3769 * Mark a particular frame.
3772 cf_mark_frame(capture_file *cf, frame_data *frame)
3774 if (! frame->flags.marked) {
3775 frame->flags.marked = TRUE;
3776 if (cf->count > cf->marked_count)
3782 * Unmark a particular frame.
3785 cf_unmark_frame(capture_file *cf, frame_data *frame)
3787 if (frame->flags.marked) {
3788 frame->flags.marked = FALSE;
3789 if (cf->marked_count > 0)
3795 * Ignore a particular frame.
3798 cf_ignore_frame(capture_file *cf, frame_data *frame)
3800 if (! frame->flags.ignored) {
3801 frame->flags.ignored = TRUE;
3802 if (cf->count > cf->ignored_count)
3803 cf->ignored_count++;
3808 * Un-ignore a particular frame.
3811 cf_unignore_frame(capture_file *cf, frame_data *frame)
3813 if (frame->flags.ignored) {
3814 frame->flags.ignored = FALSE;
3815 if (cf->ignored_count > 0)
3816 cf->ignored_count--;
3821 * Read the comment in SHB block
3825 cf_read_shb_comment(capture_file *cf)
3827 wtapng_section_t *shb_inf;
3828 const gchar *temp_str;
3830 /* Get info from SHB */
3831 shb_inf = wtap_file_get_shb_info(cf->wth);
3832 if (shb_inf == NULL)
3834 temp_str = shb_inf->opt_comment;
3842 cf_update_capture_comment(capture_file *cf, gchar *comment)
3844 wtapng_section_t *shb_inf;
3846 /* Get info from SHB */
3847 shb_inf = wtap_file_get_shb_info(cf->wth);
3849 /* See if the comment has changed or not */
3850 if (shb_inf && shb_inf->opt_comment) {
3851 if (strcmp(shb_inf->opt_comment, comment) == 0) {
3860 /* The comment has changed, let's update it */
3861 wtap_write_shb_comment(cf->wth, comment);
3862 /* Mark the file as having unsaved changes */
3863 cf->unsaved_changes = TRUE;
3867 cf_update_packet_comment(capture_file *cf, frame_data *fdata, gchar *comment)
3869 if (fdata->opt_comment != NULL) {
3870 /* OK, remove the old comment. */
3871 g_free(fdata->opt_comment);
3872 fdata->opt_comment = NULL;
3873 cf->packet_comment_count--;
3875 if (comment != NULL) {
3876 /* Add the new comment. */
3877 fdata->opt_comment = comment;
3878 cf->packet_comment_count++;
3881 /* OK, we have unsaved changes. */
3882 cf->unsaved_changes = TRUE;
3886 * What types of comments does this capture file have?
3889 cf_comment_types(capture_file *cf)
3891 guint32 comment_types = 0;
3893 if (cf_read_shb_comment(cf) != NULL)
3894 comment_types |= WTAP_COMMENT_PER_SECTION;
3895 if (cf->packet_comment_count != 0)
3896 comment_types |= WTAP_COMMENT_PER_PACKET;
3897 return comment_types;
3904 } save_callback_args_t;
3907 * Save a capture to a file, in a particular format, saving either
3908 * all packets, all currently-displayed packets, or all marked packets.
3910 * Returns TRUE if it succeeds, FALSE otherwise; if it fails, it pops
3911 * up a message box for the failure.
3914 save_packet(capture_file *cf _U_, frame_data *fdata,
3915 struct wtap_pkthdr *phdr, const guint8 *pd,
3918 save_callback_args_t *args = (save_callback_args_t *)argsp;
3919 struct wtap_pkthdr hdr;
3921 gchar *display_basename;
3923 /* init the wtap header for saving */
3924 /* TODO: reuse phdr */
3925 /* XXX - these are the only flags that correspond to data that we have
3926 in the frame_data structure and that matter on a per-packet basis.
3928 For WTAP_HAS_CAP_LEN, either the file format has separate "captured"
3929 and "on the wire" lengths, or it doesn't.
3931 For WTAP_HAS_DROP_COUNT, Wiretap doesn't actually supply the value
3934 For WTAP_HAS_PACK_FLAGS, we currently don't save the FCS length
3935 from the packet flags. */
3936 hdr.presence_flags = 0;
3937 if (fdata->flags.has_ts)
3938 hdr.presence_flags |= WTAP_HAS_TS;
3939 if (fdata->flags.has_if_id)
3940 hdr.presence_flags |= WTAP_HAS_INTERFACE_ID;
3941 if (fdata->flags.has_pack_flags)
3942 hdr.presence_flags |= WTAP_HAS_PACK_FLAGS;
3943 hdr.ts.secs = fdata->abs_ts.secs;
3944 hdr.ts.nsecs = fdata->abs_ts.nsecs;
3945 hdr.caplen = fdata->cap_len;
3946 hdr.len = fdata->pkt_len;
3947 hdr.pkt_encap = fdata->lnk_t;
3949 hdr.interface_id = fdata->interface_id; /* identifier of the interface. */
3951 hdr.pack_flags = fdata->pack_flags;
3952 hdr.opt_comment = fdata->opt_comment; /* NULL if not available */
3954 hdr.pseudo_header = phdr->pseudo_header;
3957 hdr.pack_flags = /* XXX - 0 for now (any value for "we don't have it"?) */
3959 /* and save the packet */
3960 if (!wtap_dump(args->pdh, &hdr, pd, &err)) {
3962 /* Wiretap error. */
3965 case WTAP_ERR_UNSUPPORTED_ENCAP:
3967 * This is a problem with the particular frame we're writing;
3968 * note that, and give the frame number.
3970 simple_error_message_box(
3971 "Frame %u has a network type that can't be saved in a \"%s\" file.",
3972 fdata->num, wtap_file_type_string(args->file_type));
3976 display_basename = g_filename_display_basename(args->fname);
3977 simple_error_message_box(
3978 "An error occurred while writing to the file \"%s\": %s.",
3979 display_basename, wtap_strerror(err));
3980 g_free(display_basename);
3985 write_failure_alert_box(args->fname, err);
3993 * Can this capture file be written out in any format using Wiretap
3994 * rather than by copying the raw data?
3997 cf_can_write_with_wiretap(capture_file *cf)
3999 /* We don't care whether we support the comments in this file or not;
4000 if we can't, we'll offer the user the option of discarding the
4002 return wtap_dump_can_write(cf->linktypes, 0);
4006 * Should we let the user do a save?
4010 * the file has unsaved changes, and we can save it in some
4011 * format through Wiretap
4015 * the file is a temporary file and has no unsaved changes (so
4016 * that "saving" it just means copying it).
4018 * XXX - we shouldn't allow files to be edited if they can't be saved,
4019 * so cf->unsaved_changes should be true only if the file can be saved.
4021 * We don't care whether we support the comments in this file or not;
4022 * if we can't, we'll offer the user the option of discarding the
4026 cf_can_save(capture_file *cf)
4028 if (cf->unsaved_changes && wtap_dump_can_write(cf->linktypes, 0)) {
4029 /* Saved changes, and we can write it out with Wiretap. */
4033 if (cf->is_tempfile && !cf->unsaved_changes) {
4035 * Temporary file with no unsaved changes, so we can just do a
4041 /* Nothing to save. */
4046 * Should we let the user do a "save as"?
4050 * we can save it in some format through Wiretap
4054 * the file is a temporary file and has no unsaved changes (so
4055 * that "saving" it just means copying it).
4057 * XXX - we shouldn't allow files to be edited if they can't be saved,
4058 * so cf->unsaved_changes should be true only if the file can be saved.
4060 * We don't care whether we support the comments in this file or not;
4061 * if we can't, we'll offer the user the option of discarding the
4065 cf_can_save_as(capture_file *cf)
4067 if (wtap_dump_can_write(cf->linktypes, 0)) {
4068 /* We can write it out with Wiretap. */
4072 if (cf->is_tempfile && !cf->unsaved_changes) {
4074 * Temporary file with no unsaved changes, so we can just do a
4080 /* Nothing to save. */
4085 * Does this file have unsaved data?
4088 cf_has_unsaved_data(capture_file *cf)
4091 * If this is a temporary file, or a file with unsaved changes, it
4094 return cf->is_tempfile || cf->unsaved_changes;
4098 * Quick scan to find packet offsets.
4100 static cf_read_status_t
4101 rescan_file(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
4103 const struct wtap_pkthdr *phdr;
4108 progdlg_t *progbar = NULL;
4112 GTimeVal start_time;
4113 gchar status_str[100];
4114 gint64 progbar_nextstep;
4115 gint64 progbar_quantum;
4120 int displayed_once = 0;
4123 /* Close the old handle. */
4124 wtap_close(cf->wth);
4126 /* Open the new file. */
4127 cf->wth = wtap_open_offline(fname, err, &err_info, TRUE);
4128 if (cf->wth == NULL) {
4129 cf_open_failure_alert_box(fname, *err, err_info, FALSE, 0);
4130 return CF_READ_ERROR;
4133 /* We're scanning a file whose contents should be the same as what
4134 we had before, so we don't discard dissection state etc.. */
4137 /* Set the file name because we need it to set the follow stream filter.
4138 XXX - is that still true? We need it for other reasons, though,
4140 cf->filename = g_strdup(fname);
4142 /* Indicate whether it's a permanent or temporary file. */
4143 cf->is_tempfile = is_tempfile;
4145 /* No user changes yet. */
4146 cf->unsaved_changes = FALSE;
4148 cf->cd_t = wtap_file_type(cf->wth);
4149 cf->linktypes = g_array_sized_new(FALSE, FALSE, (guint) sizeof(int), 1);
4151 cf->snap = wtap_snapshot_length(cf->wth);
4152 if (cf->snap == 0) {
4153 /* Snapshot length not known. */
4154 cf->has_snap = FALSE;
4155 cf->snap = WTAP_MAX_PACKET_SIZE;
4157 cf->has_snap = TRUE;
4159 name_ptr = g_filename_display_basename(cf->filename);
4161 cf_callback_invoke(cf_cb_file_rescan_started, cf);
4163 /* Record whether the file is compressed.
4164 XXX - do we know this at open time? */
4165 cf->iscompressed = wtap_iscompressed(cf->wth);
4167 /* Find the size of the file. */
4168 size = wtap_file_size(cf->wth, NULL);
4170 /* Update the progress bar when it gets to this value. */
4171 progbar_nextstep = 0;
4172 /* When we reach the value that triggers a progress bar update,
4173 bump that value by this amount. */
4175 progbar_quantum = size/N_PROGBAR_UPDATES;
4176 if (progbar_quantum < MIN_QUANTUM)
4177 progbar_quantum = MIN_QUANTUM;
4179 progbar_quantum = 0;
4180 /* Progress so far. */
4184 g_get_current_time(&start_time);
4187 phdr = wtap_phdr(cf->wth);
4188 while ((wtap_read(cf->wth, err, &err_info, &data_offset))) {
4190 fdata = frame_data_sequence_find(cf->frames, framenum);
4191 fdata->file_off = data_offset;
4194 file_pos = wtap_read_so_far(cf->wth);
4196 /* Create the progress bar if necessary.
4197 * Check whether it should be created or not every MIN_NUMBER_OF_PACKET
4199 if ((progbar == NULL) && !(count % MIN_NUMBER_OF_PACKET)) {
4200 progbar_val = calc_progbar_val(cf, size, file_pos, status_str, sizeof(status_str));
4201 progbar = delayed_create_progress_dlg(cf->window, "Rescanning", name_ptr,
4202 TRUE, &stop_flag, &start_time, progbar_val);
4205 /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
4206 when we update it, we have to run the GTK+ main loop to get it
4207 to repaint what's pending, and doing so may involve an "ioctl()"
4208 to see if there's any pending input from an X server, and doing
4209 that for every packet can be costly, especially on a big file. */
4210 if (file_pos >= progbar_nextstep) {
4211 if (progbar != NULL) {
4212 progbar_val = calc_progbar_val(cf, size, file_pos, status_str, sizeof(status_str));
4213 /* update the packet bar content on the first run or frequently on very large files */
4215 if (progbar_quantum > 500000 || displayed_once == 0) {
4216 if ((auto_scroll_live || displayed_once == 0 || cf->displayed_count < 1000) && cf->count != 0) {
4218 packets_bar_update();
4221 #endif /* HAVE_LIBPCAP */
4222 update_progress_dlg(progbar, progbar_val, status_str);
4224 progbar_nextstep += progbar_quantum;
4229 /* Well, the user decided to abort the rescan. Sadly, as this
4230 isn't a reread, recovering is difficult, so we'll just
4231 close the current capture. */
4235 /* Add this packet's link-layer encapsulation type to cf->linktypes, if
4236 it's not already there.
4237 XXX - yes, this is O(N), so if every packet had a different
4238 link-layer encapsulation type, it'd be O(N^2) to read the file, but
4239 there are probably going to be a small number of encapsulation types
4241 cf_add_encapsulation_type(cf, phdr->pkt_encap);
4244 /* Free the display name */
4247 /* We're done reading the file; destroy the progress bar if it was created. */
4248 if (progbar != NULL)
4249 destroy_progress_dlg(progbar);
4251 /* We're done reading sequentially through the file. */
4252 cf->state = FILE_READ_DONE;
4254 /* Close the sequential I/O side, to free up memory it requires. */
4255 wtap_sequential_close(cf->wth);
4257 /* compute the time it took to load the file */
4258 compute_elapsed(&start_time);
4260 /* Set the file encapsulation type now; we don't know what it is until
4261 we've looked at all the packets, as we don't know until then whether
4262 there's more than one type (and thus whether it's
4263 WTAP_ENCAP_PER_PACKET). */
4264 cf->lnk_t = wtap_file_encap(cf->wth);
4266 cf_callback_invoke(cf_cb_file_rescan_finished, cf);
4269 /* Our caller will give up at this point. */
4270 return CF_READ_ABORTED;
4274 /* Put up a message box noting that the read failed somewhere along
4275 the line. Don't throw out the stuff we managed to read, though,
4279 case WTAP_ERR_UNSUPPORTED:
4280 simple_error_message_box(
4281 "The capture file contains record data that Wireshark doesn't support.\n(%s)",
4286 case WTAP_ERR_UNSUPPORTED_ENCAP:
4287 simple_error_message_box(
4288 "The capture file has a packet with a network type that Wireshark doesn't support.\n(%s)",
4293 case WTAP_ERR_CANT_READ:
4294 simple_error_message_box(
4295 "An attempt to read from the capture file failed for"
4296 " some unknown reason.");
4299 case WTAP_ERR_SHORT_READ:
4300 simple_error_message_box(
4301 "The capture file appears to have been cut short"
4302 " in the middle of a packet.");
4305 case WTAP_ERR_BAD_FILE:
4306 simple_error_message_box(
4307 "The capture file appears to be damaged or corrupt.\n(%s)",
4312 case WTAP_ERR_DECOMPRESS:
4313 simple_error_message_box(
4314 "The compressed capture file appears to be damaged or corrupt.\n"
4320 simple_error_message_box(
4321 "An error occurred while reading the"
4322 " capture file: %s.", wtap_strerror(*err));
4325 return CF_READ_ERROR;
4331 cf_save_packets(capture_file *cf, const char *fname, guint save_format,
4332 gboolean compressed, gboolean discard_comments,
4333 gboolean dont_reopen)
4336 gchar *fname_new = NULL;
4339 struct addrinfo *addrs;
4343 gchar *display_basename;
4350 save_callback_args_t callback_args;
4352 cf_callback_invoke(cf_cb_file_save_started, (gpointer)fname);
4354 addrs = get_addrinfo_list();
4356 if (save_format == cf->cd_t && compressed == cf->iscompressed
4357 && !discard_comments && !cf->unsaved_changes
4358 && !(addrs && addrs->ai_next &&
4359 wtap_dump_has_name_resolution(save_format))) {
4360 /* We're saving in the format it's already in, and we're
4361 not discarding comments, and there are no changes we have
4362 in memory that aren't saved to the file, and we have no name
4363 resolution blocks to write, so we can just move or copy the raw data. */
4365 if (cf->is_tempfile) {
4366 /* The file being saved is a temporary file from a live
4367 capture, so it doesn't need to stay around under that name;
4368 first, try renaming the capture buffer file to the new name.
4369 This acts as a "safe save", in that, if the file already
4370 exists, the existing file will be removed only if the rename
4373 Sadly, on Windows, as we have the current capture file
4374 open, even MoveFileEx() with MOVEFILE_REPLACE_EXISTING
4375 (to cause the rename to remove an existing target), as
4376 done by ws_stdio_rename() (ws_rename() is #defined to
4377 be ws_stdio_rename() on Windows) will fail.
4379 According to the MSDN documentation for CreateFile(), if,
4380 when we open a capture file, we were to directly do a CreateFile(),
4381 opening with FILE_SHARE_DELETE|FILE_SHARE_READ, and then
4382 convert it to a file descriptor with _open_osfhandle(),
4383 that would allow the file to be renamed out from under us.
4385 However, that doesn't work in practice. Perhaps the problem
4386 is that the process doing the rename is the process that
4387 has the file open. */
4389 if (ws_rename(cf->filename, fname) == 0) {
4390 /* That succeeded - there's no need to copy the source file. */
4391 how_to_save = SAVE_WITH_MOVE;
4393 if (errno == EXDEV) {
4394 /* They're on different file systems, so we have to copy the
4396 how_to_save = SAVE_WITH_COPY;
4398 /* The rename failed, but not because they're on different
4399 file systems - put up an error message. (Or should we
4400 just punt and try to copy? The only reason why I'd
4401 expect the rename to fail and the copy to succeed would
4402 be if we didn't have permission to remove the file from
4403 the temporary directory, and that might be fixable - but
4404 is it worth requiring the user to go off and fix it?) */
4405 cf_rename_failure_alert_box(fname, errno);
4410 how_to_save = SAVE_WITH_COPY;
4413 /* It's a permanent file, so we should copy it, and not remove the
4415 how_to_save = SAVE_WITH_COPY;
4418 if (how_to_save == SAVE_WITH_COPY) {
4419 /* Copy the file, if we haven't moved it. If we're overwriting
4420 an existing file, we do it with a "safe save", by writing
4421 to a new file and, if the write succeeds, renaming the
4422 new file on top of the old file. */
4423 if (file_exists(fname)) {
4424 fname_new = g_strdup_printf("%s~", fname);
4425 if (!copy_file_binary_mode(cf->filename, fname_new))
4428 if (!copy_file_binary_mode(cf->filename, fname))
4433 /* Either we're saving in a different format or we're saving changes,
4434 such as added, modified, or removed comments, that haven't yet
4435 been written to the underlying file; we can't do that by copying
4436 or moving the capture file, we have to do it by writing the packets
4439 wtapng_section_t *shb_hdr = NULL;
4440 wtapng_iface_descriptions_t *idb_inf = NULL;
4443 shb_hdr = wtap_file_get_shb_info(cf->wth);
4444 idb_inf = wtap_file_get_idb_info(cf->wth);
4446 /* Determine what file encapsulation type we should use. */
4447 encap = wtap_dump_file_encap_type(cf->linktypes);
4449 if (file_exists(fname)) {
4450 /* We're overwriting an existing file; write out to a new file,
4451 and, if that succeeds, rename the new file on top of the
4452 old file. That makes this a "safe save", so that we don't
4453 lose the old file if we have a problem writing out the new
4454 file. (If the existing file is the current capture file,
4455 we *HAVE* to do that, otherwise we're overwriting the file
4456 from which we're reading the packets that we're writing!) */
4457 fname_new = g_strdup_printf("%s~", fname);
4458 pdh = wtap_dump_open_ng(fname_new, save_format, encap, cf->snap,
4459 compressed, shb_hdr, idb_inf, &err);
4461 pdh = wtap_dump_open_ng(fname, save_format, encap, cf->snap,
4462 compressed, shb_hdr, idb_inf, &err);
4468 cf_open_failure_alert_box(fname, err, NULL, TRUE, save_format);
4472 /* Add address resolution */
4473 wtap_dump_set_addrinfo_list(pdh, addrs);
4475 /* Iterate through the list of packets, processing all the packets. */
4476 callback_args.pdh = pdh;
4477 callback_args.fname = fname;
4478 callback_args.file_type = save_format;
4479 switch (process_specified_packets(cf, NULL, "Saving", "packets",
4480 TRUE, save_packet, &callback_args)) {
4483 /* Completed successfully. */
4487 /* The user decided to abort the saving.
4488 If we're writing to a temporary file, remove it.
4489 XXX - should we do so even if we're not writing to a
4491 wtap_dump_close(pdh, &err);
4492 if (fname_new != NULL)
4493 ws_unlink(fname_new);
4494 cf_callback_invoke(cf_cb_file_save_stopped, NULL);
4495 return CF_WRITE_ABORTED;
4498 /* Error while saving.
4499 If we're writing to a temporary file, remove it. */
4500 if (fname_new != NULL)
4501 ws_unlink(fname_new);
4502 wtap_dump_close(pdh, &err);
4506 if (!wtap_dump_close(pdh, &err)) {
4507 cf_close_failure_alert_box(fname, err);
4511 how_to_save = SAVE_WITH_WTAP;
4514 if (fname_new != NULL) {
4515 /* We wrote out to fname_new, and should rename it on top of
4516 fname. fname_new is now closed, so that should be possible even
4517 on Windows. However, on Windows, we first need to close whatever
4518 file descriptors we have open for fname. */
4520 wtap_fdclose(cf->wth);
4522 /* Now do the rename. */
4523 if (ws_rename(fname_new, fname) == -1) {
4524 /* Well, the rename failed. */
4525 cf_rename_failure_alert_box(fname, errno);
4527 /* Attempt to reopen the random file descriptor using the
4528 current file's filename. (At this point, the sequential
4529 file descriptor is closed.) */
4530 if (!wtap_fdreopen(cf->wth, cf->filename, &err)) {
4531 /* Oh, well, we're screwed. */
4532 display_basename = g_filename_display_basename(cf->filename);
4533 simple_error_message_box(
4534 file_open_error_message(err, FALSE), display_basename);
4535 g_free(display_basename);
4542 cf_callback_invoke(cf_cb_file_save_finished, NULL);
4543 cf->unsaved_changes = FALSE;
4546 switch (how_to_save) {
4548 case SAVE_WITH_MOVE:
4549 /* We just moved the file, so the wtap structure refers to the
4550 new file, and all the information other than the filename
4551 and the "is temporary" status applies to the new file; just
4553 g_free(cf->filename);
4554 cf->filename = g_strdup(fname);
4555 cf->is_tempfile = FALSE;
4556 cf_callback_invoke(cf_cb_file_fast_save_finished, cf);
4559 case SAVE_WITH_COPY:
4560 /* We just copied the file, s all the information other than
4561 the wtap structure, the filename, and the "is temporary"
4562 status applies to the new file; just update that. */
4563 wtap_close(cf->wth);
4564 cf->wth = wtap_open_offline(fname, &err, &err_info, TRUE);
4565 if (cf->wth == NULL) {
4566 cf_open_failure_alert_box(fname, err, err_info, FALSE, 0);
4569 g_free(cf->filename);
4570 cf->filename = g_strdup(fname);
4571 cf->is_tempfile = FALSE;
4573 cf_callback_invoke(cf_cb_file_fast_save_finished, cf);
4576 case SAVE_WITH_WTAP:
4577 /* Open and read the file we saved to.
4579 XXX - this is somewhat of a waste; we already have the
4580 packets, all this gets us is updated file type information
4581 (which we could just stuff into "cf"), and having the new
4582 file be the one we have opened and from which we're reading
4583 the data, and it means we have to spend time opening and
4584 reading the file, which could be a significant amount of
4585 time if the file is large.
4587 If the capture-file-writing code were to return the
4588 seek offset of each packet it writes, we could save that
4589 in the frame_data structure for the frame, and just open
4590 the file without reading it again...
4592 ...as long as, for gzipped files, the process of writing
4593 out the file *also* generates the information needed to
4594 support fast random access to the compressed file. */
4595 if (rescan_file(cf, fname, FALSE, &err) != CF_READ_OK) {
4596 /* The rescan failed; just close the file. Either
4597 a dialog was popped up for the failure, so the
4598 user knows what happened, or they stopped the
4599 rescan, in which case they know what happened. */
4605 /* If we were told to discard the comments, do so. */
4606 if (discard_comments) {
4607 /* Remove SHB comment, if any. */
4608 wtap_write_shb_comment(cf->wth, NULL);
4610 /* Remove packet comments. */
4611 for (framenum = 1; framenum <= cf->count; framenum++) {
4612 fdata = frame_data_sequence_find(cf->frames, framenum);
4613 if (fdata->opt_comment) {
4614 g_free(fdata->opt_comment);
4615 fdata->opt_comment = NULL;
4616 cf->packet_comment_count--;
4624 if (fname_new != NULL) {
4625 /* We were trying to write to a temporary file; get rid of it if it
4626 exists. (We don't care whether this fails, as, if it fails,
4627 there's not much we can do about it. I guess if it failed for
4628 a reason other than "it doesn't exist", we could report an
4629 error, so the user knows there's a junk file that they might
4630 want to clean up.) */
4631 ws_unlink(fname_new);
4634 cf_callback_invoke(cf_cb_file_save_failed, NULL);
4635 return CF_WRITE_ERROR;
4639 cf_export_specified_packets(capture_file *cf, const char *fname,
4640 packet_range_t *range, guint save_format,
4641 gboolean compressed)
4643 gchar *fname_new = NULL;
4646 save_callback_args_t callback_args;
4647 wtapng_section_t *shb_hdr;
4648 wtapng_iface_descriptions_t *idb_inf;
4651 cf_callback_invoke(cf_cb_file_export_specified_packets_started, (gpointer)fname);
4653 packet_range_process_init(range);
4655 /* We're writing out specified packets from the specified capture
4656 file to another file. Even if all captured packets are to be
4657 written, don't special-case the operation - read each packet
4658 and then write it out if it's one of the specified ones. */
4660 shb_hdr = wtap_file_get_shb_info(cf->wth);
4661 idb_inf = wtap_file_get_idb_info(cf->wth);
4663 /* Determine what file encapsulation type we should use. */
4664 encap = wtap_dump_file_encap_type(cf->linktypes);
4666 if (file_exists(fname)) {
4667 /* We're overwriting an existing file; write out to a new file,
4668 and, if that succeeds, rename the new file on top of the
4669 old file. That makes this a "safe save", so that we don't
4670 lose the old file if we have a problem writing out the new
4671 file. (If the existing file is the current capture file,
4672 we *HAVE* to do that, otherwise we're overwriting the file
4673 from which we're reading the packets that we're writing!) */
4674 fname_new = g_strdup_printf("%s~", fname);
4675 pdh = wtap_dump_open_ng(fname_new, save_format, encap, cf->snap,
4676 compressed, shb_hdr, idb_inf, &err);
4678 pdh = wtap_dump_open_ng(fname, save_format, encap, cf->snap,
4679 compressed, shb_hdr, idb_inf, &err);
4685 cf_open_failure_alert_box(fname, err, NULL, TRUE, save_format);
4689 /* Add address resolution */
4690 wtap_dump_set_addrinfo_list(pdh, get_addrinfo_list());
4692 /* Iterate through the list of packets, processing the packets we were
4695 XXX - we've already called "packet_range_process_init(range)", but
4696 "process_specified_packets()" will do it again. Fortunately,
4697 that's harmless in this case, as we haven't done anything to
4698 "range" since we initialized it. */
4699 callback_args.pdh = pdh;
4700 callback_args.fname = fname;
4701 callback_args.file_type = save_format;
4702 switch (process_specified_packets(cf, range, "Writing", "specified packets",
4703 TRUE, save_packet, &callback_args)) {
4706 /* Completed successfully. */
4710 /* The user decided to abort the saving.
4711 If we're writing to a temporary file, remove it.
4712 XXX - should we do so even if we're not writing to a
4714 wtap_dump_close(pdh, &err);
4715 if (fname_new != NULL)
4716 ws_unlink(fname_new);
4717 cf_callback_invoke(cf_cb_file_export_specified_packets_stopped, NULL);
4718 return CF_WRITE_ABORTED;
4722 /* Error while saving.
4723 If we're writing to a temporary file, remove it. */
4724 if (fname_new != NULL)
4725 ws_unlink(fname_new);
4726 wtap_dump_close(pdh, &err);
4730 if (!wtap_dump_close(pdh, &err)) {
4731 cf_close_failure_alert_box(fname, err);
4735 if (fname_new != NULL) {
4736 /* We wrote out to fname_new, and should rename it on top of
4737 fname; fname is now closed, so that should be possible even
4738 on Windows. Do the rename. */
4739 if (ws_rename(fname_new, fname) == -1) {
4740 /* Well, the rename failed. */
4741 cf_rename_failure_alert_box(fname, errno);
4746 cf_callback_invoke(cf_cb_file_export_specified_packets_finished, NULL);
4750 if (fname_new != NULL) {
4751 /* We were trying to write to a temporary file; get rid of it if it
4752 exists. (We don't care whether this fails, as, if it fails,
4753 there's not much we can do about it. I guess if it failed for
4754 a reason other than "it doesn't exist", we could report an
4755 error, so the user knows there's a junk file that they might
4756 want to clean up.) */
4757 ws_unlink(fname_new);
4760 cf_callback_invoke(cf_cb_file_export_specified_packets_failed, NULL);
4761 return CF_WRITE_ERROR;
4765 cf_open_failure_alert_box(const char *filename, int err, gchar *err_info,
4766 gboolean for_writing, int file_type)
4768 gchar *display_basename;
4771 /* Wiretap error. */
4772 display_basename = g_filename_display_basename(filename);
4775 case WTAP_ERR_NOT_REGULAR_FILE:
4776 simple_error_message_box(
4777 "The file \"%s\" is a \"special file\" or socket or other non-regular file.",
4781 case WTAP_ERR_RANDOM_OPEN_PIPE:
4782 /* Seen only when opening a capture file for reading. */
4783 simple_error_message_box(
4784 "The file \"%s\" is a pipe or FIFO; Wireshark can't read pipe or FIFO files.\n"
4785 "To capture from a pipe or FIFO use wireshark -i -",
4789 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
4790 /* Seen only when opening a capture file for reading. */
4791 simple_error_message_box(
4792 "The file \"%s\" isn't a capture file in a format Wireshark understands.",
4796 case WTAP_ERR_UNSUPPORTED:
4797 /* Seen only when opening a capture file for reading. */
4798 simple_error_message_box(
4799 "The file \"%s\" isn't a capture file in a format Wireshark understands.\n"
4801 display_basename, err_info);
4805 case WTAP_ERR_CANT_WRITE_TO_PIPE:
4806 /* Seen only when opening a capture file for writing. */
4807 simple_error_message_box(
4808 "The file \"%s\" is a pipe, and %s capture files can't be "
4809 "written to a pipe.",
4810 display_basename, wtap_file_type_string(file_type));
4813 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
4814 /* Seen only when opening a capture file for writing. */
4815 simple_error_message_box(
4816 "Wireshark doesn't support writing capture files in that format.");
4819 case WTAP_ERR_UNSUPPORTED_ENCAP:
4821 simple_error_message_box("Wireshark can't save this capture in that format.");
4823 simple_error_message_box(
4824 "The file \"%s\" is a capture for a network type that Wireshark doesn't support.\n"
4826 display_basename, err_info);
4831 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
4833 simple_error_message_box(
4834 "Wireshark can't save this capture in that format.");
4836 simple_error_message_box(
4837 "The file \"%s\" is a capture for a network type that Wireshark doesn't support.",
4842 case WTAP_ERR_BAD_FILE:
4843 /* Seen only when opening a capture file for reading. */
4844 simple_error_message_box(
4845 "The file \"%s\" appears to be damaged or corrupt.\n"
4847 display_basename, err_info);
4851 case WTAP_ERR_CANT_OPEN:
4853 simple_error_message_box(
4854 "The file \"%s\" could not be created for some unknown reason.",
4857 simple_error_message_box(
4858 "The file \"%s\" could not be opened for some unknown reason.",
4863 case WTAP_ERR_SHORT_READ:
4864 simple_error_message_box(
4865 "The file \"%s\" appears to have been cut short"
4866 " in the middle of a packet or other data.",
4870 case WTAP_ERR_SHORT_WRITE:
4871 simple_error_message_box(
4872 "A full header couldn't be written to the file \"%s\".",
4876 case WTAP_ERR_COMPRESSION_NOT_SUPPORTED:
4877 simple_error_message_box(
4878 "This file type cannot be written as a compressed file.");
4881 case WTAP_ERR_DECOMPRESS:
4882 simple_error_message_box(
4883 "The compressed file \"%s\" appears to be damaged or corrupt.\n"
4884 "(%s)", display_basename, err_info);
4889 simple_error_message_box(
4890 "The file \"%s\" could not be %s: %s.",
4892 for_writing ? "created" : "opened",
4893 wtap_strerror(err));
4896 g_free(display_basename);
4899 open_failure_alert_box(filename, err, for_writing);
4904 * XXX - whether we mention the source pathname, the target pathname,
4905 * or both depends on the error and on what we find if we look for
4906 * one or both of them.
4909 cf_rename_failure_alert_box(const char *filename, int err)
4911 gchar *display_basename;
4913 display_basename = g_filename_display_basename(filename);
4917 /* XXX - should check whether the source exists and, if not,
4918 report it as the problem and, if so, report the destination
4920 simple_error_message_box("The path to the file \"%s\" doesn't exist.",
4925 /* XXX - if we're doing a rename after a safe save, we should
4926 probably say something else. */
4927 simple_error_message_box("You don't have permission to move the capture file to \"%s\".",
4932 /* XXX - this should probably mention both the source and destination
4934 simple_error_message_box("The file \"%s\" could not be moved: %s.",
4935 display_basename, wtap_strerror(err));
4938 g_free(display_basename);
4941 /* Check for write errors - if the file is being written to an NFS server,
4942 a write error may not show up until the file is closed, as NFS clients
4943 might not send writes to the server until the "write()" call finishes,
4944 so that the write may fail on the server but the "write()" may succeed. */
4946 cf_close_failure_alert_box(const char *filename, int err)
4948 gchar *display_basename;
4951 /* Wiretap error. */
4952 display_basename = g_filename_display_basename(filename);
4955 case WTAP_ERR_CANT_CLOSE:
4956 simple_error_message_box(
4957 "The file \"%s\" couldn't be closed for some unknown reason.",
4961 case WTAP_ERR_SHORT_WRITE:
4962 simple_error_message_box(
4963 "Not all the packets could be written to the file \"%s\".",
4968 simple_error_message_box(
4969 "An error occurred while closing the file \"%s\": %s.",
4970 display_basename, wtap_strerror(err));
4973 g_free(display_basename);
4976 We assume that a close error from the OS is really a write error. */
4977 write_failure_alert_box(filename, err);
4981 /* Reload the current capture file. */
4983 cf_reload(capture_file *cf) {
4985 gboolean is_tempfile;
4988 /* If the file could be opened, "cf_open()" calls "cf_close()"
4989 to get rid of state for the old capture file before filling in state
4990 for the new capture file. "cf_close()" will remove the file if
4991 it's a temporary file; we don't want that to happen (for one thing,
4992 it'd prevent subsequent reopens from working). Remember whether it's
4993 a temporary file, mark it as not being a temporary file, and then
4994 reopen it as the type of file it was.
4996 Also, "cf_close()" will free "cf->filename", so we must make
4997 a copy of it first. */
4998 filename = g_strdup(cf->filename);
4999 is_tempfile = cf->is_tempfile;
5000 cf->is_tempfile = FALSE;
5001 if (cf_open(cf, filename, is_tempfile, &err) == CF_OK) {
5002 switch (cf_read(cf, TRUE)) {
5006 /* Just because we got an error, that doesn't mean we were unable
5007 to read any of the file; we handle what we could get from the
5011 case CF_READ_ABORTED:
5012 /* The user bailed out of re-reading the capture file; the
5013 capture file has been closed - just free the capture file name
5014 string and return (without changing the last containing
5020 /* The open failed, so "cf->is_tempfile" wasn't set to "is_tempfile".
5021 Instead, the file was left open, so we should restore "cf->is_tempfile"
5024 XXX - change the menu? Presumably "cf_open()" will do that;
5025 make sure it does! */
5026 cf->is_tempfile = is_tempfile;
5028 /* "cf_open()" made a copy of the file name we handed it, so
5029 we should free up our copy. */
5039 * indent-tabs-mode: nil
5042 * ex: set shiftwidth=2 tabstop=8 expandtab:
5043 * :indentSize=2:tabSize=8:noTabs=true: