4 * Wireshark - Network traffic analyzer
5 * By Gerald Combs <gerald@wireshark.org>
6 * Copyright 1998 Gerald Combs
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 2
11 * of the License, or (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
41 #include <wsutil/tempfile.h>
42 #include <wsutil/file_util.h>
43 #include <wsutil/filesystem.h>
44 #include <wsutil/ws_version_info.h>
46 #include <wiretap/merge.h>
48 #include <epan/exceptions.h>
49 #include <epan/epan-int.h>
50 #include <epan/epan.h>
51 #include <epan/column.h>
52 #include <epan/packet.h>
53 #include <epan/column-utils.h>
54 #include <epan/expert.h>
55 #include <epan/prefs.h>
56 #include <epan/dfilter/dfilter.h>
57 #include <epan/epan_dissect.h>
59 #include <epan/dissectors/packet-ber.h>
60 #include <epan/timestamp.h>
61 #include <epan/dfilter/dfilter-macro.h>
62 #include <epan/strutil.h>
63 #include <epan/addr_resolv.h>
66 #include "color_filters.h"
70 #include "frame_tvbuff.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; /* GTK+ only? */
107 static int read_packet(capture_file *cf, dfilter_t *dfcode, epan_dissect_t *edt,
108 column_info *cinfo, gint64 offset);
110 static void rescan_packets(capture_file *cf, const char *action, const char *action_item, gboolean redissect);
117 static match_result match_protocol_tree(capture_file *cf, frame_data *fdata,
119 static void match_subtree_text(proto_node *node, gpointer data);
120 static match_result match_summary_line(capture_file *cf, frame_data *fdata,
122 static match_result match_narrow_and_wide(capture_file *cf, frame_data *fdata,
124 static match_result match_narrow(capture_file *cf, frame_data *fdata,
126 static match_result match_wide(capture_file *cf, frame_data *fdata,
128 static match_result match_binary(capture_file *cf, frame_data *fdata,
130 static match_result match_dfilter(capture_file *cf, frame_data *fdata,
132 static match_result match_marked(capture_file *cf, frame_data *fdata,
134 static match_result match_time_reference(capture_file *cf, frame_data *fdata,
136 static gboolean find_packet(capture_file *cf,
137 match_result (*match_function)(capture_file *, frame_data *, void *),
138 void *criterion, search_direction dir);
140 static const char *cf_get_user_packet_comment(capture_file *cf, const frame_data *fd);
142 static void cf_open_failure_alert_box(const char *filename, int err,
143 gchar *err_info, gboolean for_writing,
145 static void cf_rename_failure_alert_box(const char *filename, int err);
146 static void cf_close_failure_alert_box(const char *filename, int err);
147 static void ref_time_packets(capture_file *cf);
148 /* Update the progress bar this many times when reading a file. */
149 #define N_PROGBAR_UPDATES 100
150 /* We read around 200k/100ms don't update the progress bar more often than that */
151 #define MIN_QUANTUM 200000
152 #define MIN_NUMBER_OF_PACKET 1500
155 * We could probably use g_signal_...() instead of the callbacks below but that
156 * would require linking our CLI programs to libgobject and creating an object
157 * instance for the signals.
160 cf_callback_t cb_fct;
162 } cf_callback_data_t;
164 static GList *cf_callbacks = NULL;
167 cf_callback_invoke(int event, gpointer data)
169 cf_callback_data_t *cb;
170 GList *cb_item = cf_callbacks;
172 /* there should be at least one interested */
173 g_assert(cb_item != NULL);
175 while (cb_item != NULL) {
176 cb = (cf_callback_data_t *)cb_item->data;
177 cb->cb_fct(event, data, cb->user_data);
178 cb_item = g_list_next(cb_item);
184 cf_callback_add(cf_callback_t func, gpointer user_data)
186 cf_callback_data_t *cb;
188 cb = g_new(cf_callback_data_t,1);
190 cb->user_data = user_data;
192 cf_callbacks = g_list_prepend(cf_callbacks, cb);
196 cf_callback_remove(cf_callback_t func, gpointer user_data)
198 cf_callback_data_t *cb;
199 GList *cb_item = cf_callbacks;
201 while (cb_item != NULL) {
202 cb = (cf_callback_data_t *)cb_item->data;
203 if (cb->cb_fct == func && cb->user_data == user_data) {
204 cf_callbacks = g_list_remove(cf_callbacks, cb);
208 cb_item = g_list_next(cb_item);
211 g_assert_not_reached();
215 cf_timestamp_auto_precision(capture_file *cf)
219 /* don't try to get the file's precision if none is opened */
220 if (cf->state == FILE_CLOSED) {
224 /* Set the column widths of those columns that show the time in
225 "command-line-specified" format. */
226 for (i = 0; i < cf->cinfo.num_cols; i++) {
227 if (col_has_time_fmt(&cf->cinfo, i)) {
228 packet_list_resize_column(i);
234 cf_get_computed_elapsed(capture_file *cf)
236 return cf->computed_elapsed;
240 * GLIB_CHECK_VERSION(2,28,0) adds g_get_real_time which could minimize or
243 static void compute_elapsed(capture_file *cf, GTimeVal *start_time)
248 g_get_current_time(&time_now);
250 delta_time = (time_now.tv_sec - start_time->tv_sec) * 1e6 +
251 time_now.tv_usec - start_time->tv_usec;
253 cf->computed_elapsed = (gulong) (delta_time / 1000); /* ms */
256 static const nstime_t *
257 ws_get_frame_ts(void *data, guint32 frame_num)
259 capture_file *cf = (capture_file *) data;
261 if (cf->prev_dis && cf->prev_dis->num == frame_num)
262 return &cf->prev_dis->abs_ts;
264 if (cf->prev_cap && cf->prev_cap->num == frame_num)
265 return &cf->prev_cap->abs_ts;
268 frame_data *fd = frame_data_sequence_find(cf->frames, frame_num);
270 return (fd) ? &fd->abs_ts : NULL;
277 ws_get_user_comment(void *data, const frame_data *fd)
279 capture_file *cf = (capture_file *) data;
281 return cf_get_user_packet_comment(cf, fd);
285 ws_epan_new(capture_file *cf)
287 epan_t *epan = epan_new();
290 epan->get_frame_ts = ws_get_frame_ts;
291 epan->get_interface_name = cap_file_get_interface_name;
292 epan->get_user_comment = ws_get_user_comment;
298 cf_open(capture_file *cf, const char *fname, unsigned int type, gboolean is_tempfile, int *err)
303 wth = wtap_open_offline(fname, type, err, &err_info, TRUE);
307 /* The open succeeded. Close whatever capture file we had open,
308 and fill in the information for this file. */
311 /* Initialize the packet header. */
312 wtap_phdr_init(&cf->phdr);
314 /* XXX - we really want to initialize this after we've read all
315 the packets, so we know how much we'll ultimately need. */
316 ws_buffer_init(&cf->buf, 1500);
318 /* Create new epan session for dissection.
319 * (The old one was freed in cf_close().)
321 cf->epan = ws_epan_new(cf);
323 /* We're about to start reading the file. */
324 cf->state = FILE_READ_IN_PROGRESS;
329 /* Set the file name because we need it to set the follow stream filter.
330 XXX - is that still true? We need it for other reasons, though,
332 cf->filename = g_strdup(fname);
334 /* Indicate whether it's a permanent or temporary file. */
335 cf->is_tempfile = is_tempfile;
337 /* No user changes yet. */
338 cf->unsaved_changes = FALSE;
340 cf->computed_elapsed = 0;
342 cf->cd_t = wtap_file_type_subtype(cf->wth);
343 cf->open_type = type;
344 cf->linktypes = g_array_sized_new(FALSE, FALSE, (guint) sizeof(int), 1);
346 cf->packet_comment_count = 0;
347 cf->displayed_count = 0;
348 cf->marked_count = 0;
349 cf->ignored_count = 0;
350 cf->ref_time_count = 0;
351 cf->drops_known = FALSE;
353 cf->snap = wtap_snapshot_length(cf->wth);
355 /* Snapshot length not known. */
356 cf->has_snap = FALSE;
357 cf->snap = WTAP_MAX_PACKET_SIZE;
361 /* Allocate a frame_data_sequence for the frames in this file */
362 cf->frames = new_frame_data_sequence();
364 nstime_set_zero(&cf->elapsed_time);
370 /* Adjust timestamp precision if auto is selected, col width will be adjusted */
371 cf_timestamp_auto_precision(cf);
373 packet_list_queue_draw();
374 cf_callback_invoke(cf_cb_file_opened, cf);
376 if (cf->cd_t == WTAP_FILE_TYPE_SUBTYPE_BER) {
377 /* tell the BER dissector the file name */
378 ber_set_filename(cf->filename);
381 wtap_set_cb_new_ipv4(cf->wth, add_ipv4_name);
382 wtap_set_cb_new_ipv6(cf->wth, (wtap_new_ipv6_callback_t) add_ipv6_name);
387 cf_open_failure_alert_box(fname, *err, err_info, FALSE, 0);
392 * Add an encapsulation type to cf->linktypes.
395 cf_add_encapsulation_type(capture_file *cf, int encap)
399 for (i = 0; i < cf->linktypes->len; i++) {
400 if (g_array_index(cf->linktypes, gint, i) == encap)
401 return; /* it's already there */
403 /* It's not already there - add it. */
404 g_array_append_val(cf->linktypes, encap);
407 /* Reset everything to a pristine state */
409 cf_close(capture_file *cf)
411 cf->stop_flag = FALSE;
412 if (cf->state == FILE_CLOSED)
413 return; /* Nothing to do */
415 /* Die if we're in the middle of reading a file. */
416 g_assert(cf->state != FILE_READ_IN_PROGRESS);
418 cf_callback_invoke(cf_cb_file_closing, cf);
420 /* close things, if not already closed before */
421 color_filters_cleanup();
427 /* We have no file open... */
428 if (cf->filename != NULL) {
429 /* If it's a temporary file, remove it. */
431 ws_unlink(cf->filename);
432 g_free(cf->filename);
435 /* ...which means we have no changes to that file to save. */
436 cf->unsaved_changes = FALSE;
438 /* no open_routine type */
439 cf->open_type = WTAP_TYPE_AUTO;
441 /* Clean up the packet header. */
442 wtap_phdr_cleanup(&cf->phdr);
444 /* Free up the packet buffer. */
445 ws_buffer_free(&cf->buf);
447 dfilter_free(cf->rfcode);
449 if (cf->frames != NULL) {
450 free_frame_data_sequence(cf->frames);
453 #ifdef WANT_PACKET_EDITOR
454 if (cf->edited_frames) {
455 g_tree_destroy(cf->edited_frames);
456 cf->edited_frames = NULL;
459 if (cf->frames_user_comments) {
460 g_tree_destroy(cf->frames_user_comments);
461 cf->frames_user_comments = NULL;
463 cf_unselect_packet(cf); /* nothing to select */
464 cf->first_displayed = 0;
465 cf->last_displayed = 0;
467 /* No frames, no frame selected, no field in that frame selected. */
469 cf->current_frame = 0;
471 cf->finfo_selected = NULL;
473 /* No frame link-layer types, either. */
474 if (cf->linktypes != NULL) {
475 g_array_free(cf->linktypes, TRUE);
476 cf->linktypes = NULL;
479 /* Clear the packet list. */
480 packet_list_freeze();
485 nstime_set_zero(&cf->elapsed_time);
487 reset_tap_listeners();
492 /* We have no file open. */
493 cf->state = FILE_CLOSED;
495 cf_callback_invoke(cf_cb_file_closed, cf);
499 calc_progbar_val(capture_file *cf, gint64 size, gint64 file_pos, gchar *status_str, gulong status_size)
503 progbar_val = (gfloat) file_pos / (gfloat) size;
504 if (progbar_val > 1.0) {
506 /* The file probably grew while we were reading it.
507 * Update file size, and try again.
509 size = wtap_file_size(cf->wth, NULL);
512 progbar_val = (gfloat) file_pos / (gfloat) size;
514 /* If it's still > 1, either "wtap_file_size()" failed (in which
515 * case there's not much we can do about it), or the file
516 * *shrank* (in which case there's not much we can do about
517 * it); just clip the progress value at 1.0.
519 if (progbar_val > 1.0f)
523 g_snprintf(status_str, status_size,
524 "%" G_GINT64_MODIFIER "dKB of %" G_GINT64_MODIFIER "dKB",
525 file_pos / 1024, size / 1024);
531 cf_read(capture_file *cf, gboolean reloading)
536 progdlg_t *progbar = NULL;
540 volatile gboolean create_proto_tree;
544 /* Compile the current display filter.
545 * We assume this will not fail since cf->dfilter is only set in
546 * cf_filter IFF the filter was valid.
548 compiled = dfilter_compile(cf->dfilter, &dfcode, NULL);
549 g_assert(!cf->dfilter || (compiled && dfcode));
551 /* Get the union of the flags for all tap listeners. */
552 tap_flags = union_of_tap_listener_flags();
554 (dfcode != NULL || have_filtering_tap_listeners() || (tap_flags & TL_REQUIRES_PROTO_TREE));
556 reset_tap_listeners();
558 name_ptr = g_filename_display_basename(cf->filename);
561 cf_callback_invoke(cf_cb_file_reload_started, cf);
563 cf_callback_invoke(cf_cb_file_read_started, cf);
565 /* Record whether the file is compressed.
566 XXX - do we know this at open time? */
567 cf->iscompressed = wtap_iscompressed(cf->wth);
569 /* The packet list window will be empty until the file is completly loaded */
570 packet_list_freeze();
572 cf->stop_flag = FALSE;
573 g_get_current_time(&start_time);
575 epan_dissect_init(&edt, cf->epan, create_proto_tree, FALSE);
579 int displayed_once = 0;
587 gint64 progbar_quantum;
588 gint64 progbar_nextstep;
590 gchar status_str[100];
594 cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
596 /* Find the size of the file. */
597 size = wtap_file_size(cf->wth, NULL);
599 /* Update the progress bar when it gets to this value. */
600 progbar_nextstep = 0;
601 /* When we reach the value that triggers a progress bar update,
602 bump that value by this amount. */
604 progbar_quantum = size/N_PROGBAR_UPDATES;
605 if (progbar_quantum < MIN_QUANTUM)
606 progbar_quantum = MIN_QUANTUM;
610 while ((wtap_read(cf->wth, &err, &err_info, &data_offset))) {
613 file_pos = wtap_read_so_far(cf->wth);
615 /* Create the progress bar if necessary.
616 * Check whether it should be created or not every MIN_NUMBER_OF_PACKET
618 if ((progbar == NULL) && !(count % MIN_NUMBER_OF_PACKET)) {
619 progbar_val = calc_progbar_val(cf, size, file_pos, status_str, sizeof(status_str));
621 progbar = delayed_create_progress_dlg(cf->window, "Reloading", name_ptr,
622 TRUE, &cf->stop_flag, &start_time, progbar_val);
624 progbar = delayed_create_progress_dlg(cf->window, "Loading", name_ptr,
625 TRUE, &cf->stop_flag, &start_time, progbar_val);
628 /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
629 when we update it, we have to run the GTK+ main loop to get it
630 to repaint what's pending, and doing so may involve an "ioctl()"
631 to see if there's any pending input from an X server, and doing
632 that for every packet can be costly, especially on a big file. */
633 if (file_pos >= progbar_nextstep) {
634 if (progbar != NULL) {
635 progbar_val = calc_progbar_val(cf, size, file_pos, status_str, sizeof(status_str));
636 /* update the packet bar content on the first run or frequently on very large files */
638 if (progbar_quantum > 500000 || displayed_once == 0) {
639 if ((auto_scroll_live || displayed_once == 0 || cf->displayed_count < 1000) && cf->count != 0) {
641 packets_bar_update();
644 #endif /* HAVE_LIBPCAP */
645 update_progress_dlg(progbar, progbar_val, status_str);
647 progbar_nextstep += progbar_quantum;
652 /* Well, the user decided to abort the read. He/She will be warned and
653 it might be enough for him/her to work with the already loaded
655 This is especially true for very large capture files, where you don't
656 want to wait loading the whole file (which may last minutes or even
657 hours even on fast machines) just to see that it was the wrong file. */
660 read_packet(cf, dfcode, &edt, cinfo, data_offset);
663 CATCH(OutOfMemoryError) {
664 simple_message_box(ESD_TYPE_ERROR, NULL,
665 "More information and workarounds can be found at\n"
666 "https://wiki.wireshark.org/KnownBugs/OutOfMemory",
667 "Sorry, but Wireshark has run out of memory and has to terminate now.");
669 /* Could we close the current capture and free up memory from that? */
671 /* we have to terminate, as we cannot recover from the memory error */
677 /* Free the display name */
680 /* Cleanup and release all dfilter resources */
681 if (dfcode != NULL) {
682 dfilter_free(dfcode);
685 epan_dissect_cleanup(&edt);
687 /* We're done reading the file; destroy the progress bar if it was created. */
689 destroy_progress_dlg(progbar);
691 /* We're done reading sequentially through the file. */
692 cf->state = FILE_READ_DONE;
694 /* Close the sequential I/O side, to free up memory it requires. */
695 wtap_sequential_close(cf->wth);
697 /* Allow the protocol dissectors to free up memory that they
698 * don't need after the sequential run-through of the packets. */
699 postseq_cleanup_all_protocols();
701 /* compute the time it took to load the file */
702 compute_elapsed(cf, &start_time);
704 /* Set the file encapsulation type now; we don't know what it is until
705 we've looked at all the packets, as we don't know until then whether
706 there's more than one type (and thus whether it's
707 WTAP_ENCAP_PER_PACKET). */
708 cf->lnk_t = wtap_file_encap(cf->wth);
710 cf->current_frame = frame_data_sequence_find(cf->frames, cf->first_displayed);
715 cf_callback_invoke(cf_cb_file_reload_finished, cf);
717 cf_callback_invoke(cf_cb_file_read_finished, cf);
719 /* If we have any displayed packets to select, select the first of those
720 packets by making the first row the selected row. */
721 if (cf->first_displayed != 0) {
722 packet_list_select_first_row();
726 simple_message_box(ESD_TYPE_WARN, NULL,
727 "The remaining packets in the file were discarded.\n"
729 "As a lot of packets from the original file will be missing,\n"
730 "remember to be careful when saving the current content to a file.\n",
731 "File loading was cancelled.");
732 return CF_READ_ERROR;
736 /* Put up a message box noting that the read failed somewhere along
737 the line. Don't throw out the stuff we managed to read, though,
741 case WTAP_ERR_UNSUPPORTED:
742 simple_error_message_box(
743 "The capture file contains record data that Wireshark doesn't support.\n(%s)",
744 err_info != NULL ? err_info : "no information supplied");
748 case WTAP_ERR_SHORT_READ:
749 simple_error_message_box(
750 "The capture file appears to have been cut short"
751 " in the middle of a packet.");
754 case WTAP_ERR_BAD_FILE:
755 simple_error_message_box(
756 "The capture file appears to be damaged or corrupt.\n(%s)",
757 err_info != NULL ? err_info : "no information supplied");
761 case WTAP_ERR_DECOMPRESS:
762 simple_error_message_box(
763 "The compressed capture file appears to be damaged or corrupt.\n(%s)",
764 err_info != NULL ? err_info : "no information supplied");
769 simple_error_message_box(
770 "An error occurred while reading the"
771 " capture file: %s.", wtap_strerror(err));
774 return CF_READ_ERROR;
781 cf_continue_tail(capture_file *cf, volatile int to_read, int *err)
784 volatile int newly_displayed_packets = 0;
787 gboolean create_proto_tree;
791 /* Compile the current display filter.
792 * We assume this will not fail since cf->dfilter is only set in
793 * cf_filter IFF the filter was valid.
795 compiled = dfilter_compile(cf->dfilter, &dfcode, NULL);
796 g_assert(!cf->dfilter || (compiled && dfcode));
798 /* Get the union of the flags for all tap listeners. */
799 tap_flags = union_of_tap_listener_flags();
801 (dfcode != NULL || have_filtering_tap_listeners() || (tap_flags & TL_REQUIRES_PROTO_TREE));
805 packet_list_check_end();
806 /* Don't freeze/thaw the list when doing live capture */
807 /*packet_list_freeze();*/
809 /*g_log(NULL, G_LOG_LEVEL_MESSAGE, "cf_continue_tail: %u new: %u", cf->count, to_read);*/
811 epan_dissect_init(&edt, cf->epan, create_proto_tree, FALSE);
814 gint64 data_offset = 0;
817 cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
819 while (to_read != 0) {
820 wtap_cleareof(cf->wth);
821 if (!wtap_read(cf->wth, err, &err_info, &data_offset)) {
824 if (cf->state == FILE_READ_ABORTED) {
825 /* Well, the user decided to exit Wireshark. Break out of the
826 loop, and let the code below (which is called even if there
827 aren't any packets left to read) exit. */
830 if (read_packet(cf, dfcode, &edt, (column_info *) cinfo, data_offset) != -1) {
831 newly_displayed_packets++;
836 CATCH(OutOfMemoryError) {
837 simple_message_box(ESD_TYPE_ERROR, NULL,
838 "More information and workarounds can be found at\n"
839 "https://wiki.wireshark.org/KnownBugs/OutOfMemory",
840 "Sorry, but Wireshark has run out of memory and has to terminate now.");
842 /* Could we close the current capture and free up memory from that? */
843 return CF_READ_ABORTED;
845 /* we have to terminate, as we cannot recover from the memory error */
851 /* Update the file encapsulation; it might have changed based on the
852 packets we've read. */
853 cf->lnk_t = wtap_file_encap(cf->wth);
855 /* Cleanup and release all dfilter resources */
856 if (dfcode != NULL) {
857 dfilter_free(dfcode);
860 epan_dissect_cleanup(&edt);
862 /*g_log(NULL, G_LOG_LEVEL_MESSAGE, "cf_continue_tail: count %u state: %u err: %u",
863 cf->count, cf->state, *err);*/
865 /* Don't freeze/thaw the list when doing live capture */
866 /*packet_list_thaw();*/
867 /* With the new packet list the first packet
868 * isn't automatically selected.
870 if (!cf->current_frame)
871 packet_list_select_first_row();
873 /* moving to the end of the packet list - if the user requested so and
874 we have some new packets. */
875 if (newly_displayed_packets && auto_scroll_live && cf->count != 0)
876 packet_list_moveto_end();
878 if (cf->state == FILE_READ_ABORTED) {
879 /* Well, the user decided to exit Wireshark. Return CF_READ_ABORTED
880 so that our caller can kill off the capture child process;
881 this will cause an EOF on the pipe from the child, so
882 "cf_finish_tail()" will be called, and it will clean up
884 return CF_READ_ABORTED;
885 } else if (*err != 0) {
886 /* We got an error reading the capture file.
887 XXX - pop up a dialog box instead? */
888 if (err_info != NULL) {
889 g_warning("Error \"%s\" while reading \"%s\" (\"%s\")",
890 wtap_strerror(*err), cf->filename, err_info);
893 g_warning("Error \"%s\" while reading \"%s\"",
894 wtap_strerror(*err), cf->filename);
896 return CF_READ_ERROR;
902 cf_fake_continue_tail(capture_file *cf) {
903 cf->state = FILE_READ_DONE;
907 cf_finish_tail(capture_file *cf, int *err)
914 gboolean create_proto_tree;
918 /* Compile the current display filter.
919 * We assume this will not fail since cf->dfilter is only set in
920 * cf_filter IFF the filter was valid.
922 compiled = dfilter_compile(cf->dfilter, &dfcode, NULL);
923 g_assert(!cf->dfilter || (compiled && dfcode));
925 /* Get the union of the flags for all tap listeners. */
926 tap_flags = union_of_tap_listener_flags();
927 cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
929 (dfcode != NULL || have_filtering_tap_listeners() || (tap_flags & TL_REQUIRES_PROTO_TREE));
931 if (cf->wth == NULL) {
933 return CF_READ_ERROR;
936 packet_list_check_end();
937 /* Don't freeze/thaw the list when doing live capture */
938 /*packet_list_freeze();*/
940 epan_dissect_init(&edt, cf->epan, create_proto_tree, FALSE);
942 while ((wtap_read(cf->wth, err, &err_info, &data_offset))) {
943 if (cf->state == FILE_READ_ABORTED) {
944 /* Well, the user decided to abort the read. Break out of the
945 loop, and let the code below (which is called even if there
946 aren't any packets left to read) exit. */
949 read_packet(cf, dfcode, &edt, cinfo, data_offset);
952 /* Cleanup and release all dfilter resources */
953 if (dfcode != NULL) {
954 dfilter_free(dfcode);
957 epan_dissect_cleanup(&edt);
959 /* Don't freeze/thaw the list when doing live capture */
960 /*packet_list_thaw();*/
962 if (cf->state == FILE_READ_ABORTED) {
963 /* Well, the user decided to abort the read. We're only called
964 when the child capture process closes the pipe to us (meaning
965 it's probably exited), so we can just close the capture
966 file; we return CF_READ_ABORTED so our caller can do whatever
967 is appropriate when that happens. */
969 return CF_READ_ABORTED;
972 if (auto_scroll_live && cf->count != 0)
973 packet_list_moveto_end();
975 /* We're done reading sequentially through the file. */
976 cf->state = FILE_READ_DONE;
978 /* We're done reading sequentially through the file; close the
979 sequential I/O side, to free up memory it requires. */
980 wtap_sequential_close(cf->wth);
982 /* Allow the protocol dissectors to free up memory that they
983 * don't need after the sequential run-through of the packets. */
984 postseq_cleanup_all_protocols();
986 /* Update the file encapsulation; it might have changed based on the
987 packets we've read. */
988 cf->lnk_t = wtap_file_encap(cf->wth);
990 /* Update the details in the file-set dialog, as the capture file
991 * has likely grown since we first stat-ed it */
992 fileset_update_file(cf->filename);
995 /* We got an error reading the capture file.
996 XXX - pop up a dialog box? */
997 if (err_info != NULL) {
998 g_warning("Error \"%s\" while reading \"%s\" (\"%s\")",
999 wtap_strerror(*err), cf->filename, err_info);
1002 g_warning("Error \"%s\" while reading \"%s\"",
1003 wtap_strerror(*err), cf->filename);
1005 return CF_READ_ERROR;
1010 #endif /* HAVE_LIBPCAP */
1013 cf_get_display_name(capture_file *cf)
1017 /* Return a name to use in displays */
1018 if (!cf->is_tempfile) {
1019 /* Get the last component of the file name, and use that. */
1021 displayname = g_filename_display_basename(cf->filename);
1023 displayname=g_strdup("(No file)");
1026 /* The file we read is a temporary file from a live capture or
1027 a merge operation; we don't mention its name, but, if it's
1028 from a capture, give the source of the capture. */
1030 displayname = g_strdup(cf->source);
1032 displayname = g_strdup("(Untitled)");
1038 void cf_set_tempfile_source(capture_file *cf, gchar *source) {
1044 cf->source = g_strdup(source);
1046 cf->source = g_strdup("");
1050 const gchar *cf_get_tempfile_source(capture_file *cf) {
1058 /* XXX - use a macro instead? */
1060 cf_get_packet_count(capture_file *cf)
1065 /* XXX - use a macro instead? */
1067 cf_is_tempfile(capture_file *cf)
1069 return cf->is_tempfile;
1072 void cf_set_tempfile(capture_file *cf, gboolean is_tempfile)
1074 cf->is_tempfile = is_tempfile;
1078 /* XXX - use a macro instead? */
1079 void cf_set_drops_known(capture_file *cf, gboolean drops_known)
1081 cf->drops_known = drops_known;
1084 /* XXX - use a macro instead? */
1085 void cf_set_drops(capture_file *cf, guint32 drops)
1090 /* XXX - use a macro instead? */
1091 gboolean cf_get_drops_known(capture_file *cf)
1093 return cf->drops_known;
1096 /* XXX - use a macro instead? */
1097 guint32 cf_get_drops(capture_file *cf)
1102 void cf_set_rfcode(capture_file *cf, dfilter_t *rfcode)
1104 cf->rfcode = rfcode;
1108 add_packet_to_packet_list(frame_data *fdata, capture_file *cf,
1109 epan_dissect_t *edt, dfilter_t *dfcode, column_info *cinfo,
1110 struct wtap_pkthdr *phdr, const guint8 *buf, gboolean add_to_packet_list)
1114 frame_data_set_before_dissect(fdata, &cf->elapsed_time,
1115 &cf->ref, cf->prev_dis);
1116 cf->prev_cap = fdata;
1118 if (dfcode != NULL) {
1119 epan_dissect_prime_dfilter(edt, dfcode);
1122 /* Dissect the frame. */
1123 epan_dissect_run_with_taps(edt, cf->cd_t, phdr, frame_tvbuff_new(fdata, buf), fdata, cinfo);
1125 /* If we don't have a display filter, set "passed_dfilter" to 1. */
1126 if (dfcode != NULL) {
1127 fdata->flags.passed_dfilter = dfilter_apply_edt(dfcode, edt) ? 1 : 0;
1129 if (fdata->flags.passed_dfilter) {
1130 /* This frame passed the display filter but it may depend on other
1131 * (potentially not displayed) frames. Find those frames and mark them
1134 g_slist_foreach(edt->pi.dependent_frames, find_and_mark_frame_depended_upon, cf->frames);
1137 fdata->flags.passed_dfilter = 1;
1139 if (fdata->flags.passed_dfilter || fdata->flags.ref_time)
1140 cf->displayed_count++;
1142 if (add_to_packet_list) {
1143 /* We fill the needed columns from new_packet_list */
1144 row = packet_list_append(cinfo, fdata);
1147 if (fdata->flags.passed_dfilter || fdata->flags.ref_time)
1149 frame_data_set_after_dissect(fdata, &cf->cum_bytes);
1150 cf->prev_dis = fdata;
1152 /* If we haven't yet seen the first frame, this is it.
1154 XXX - we must do this before we add the row to the display,
1155 as, if the display's GtkCList's selection mode is
1156 GTK_SELECTION_BROWSE, when the first entry is added to it,
1157 "cf_select_packet()" will be called, and it will fetch the row
1158 data for the 0th row, and will get a null pointer rather than
1159 "fdata", as "gtk_clist_append()" won't yet have returned and
1160 thus "gtk_clist_set_row_data()" won't yet have been called.
1162 We thus need to leave behind bread crumbs so that
1163 "cf_select_packet()" can find this frame. See the comment
1164 in "cf_select_packet()". */
1165 if (cf->first_displayed == 0)
1166 cf->first_displayed = fdata->num;
1168 /* This is the last frame we've seen so far. */
1169 cf->last_displayed = fdata->num;
1172 epan_dissect_reset(edt);
1176 /* read in a new packet */
1177 /* returns the row of the new packet in the packet list or -1 if not displayed */
1179 read_packet(capture_file *cf, dfilter_t *dfcode, epan_dissect_t *edt,
1180 column_info *cinfo, gint64 offset)
1182 struct wtap_pkthdr *phdr = wtap_phdr(cf->wth);
1183 const guint8 *buf = wtap_buf_ptr(cf->wth);
1190 /* Add this packet's link-layer encapsulation type to cf->linktypes, if
1191 it's not already there.
1192 XXX - yes, this is O(N), so if every packet had a different
1193 link-layer encapsulation type, it'd be O(N^2) to read the file, but
1194 there are probably going to be a small number of encapsulation types
1196 cf_add_encapsulation_type(cf, phdr->pkt_encap);
1198 /* The frame number of this packet is one more than the count of
1199 frames in the file so far. */
1200 framenum = cf->count + 1;
1202 frame_data_init(&fdlocal, framenum, phdr, offset, cf->cum_bytes);
1206 epan_dissect_t rf_edt;
1208 epan_dissect_init(&rf_edt, cf->epan, TRUE, FALSE);
1209 epan_dissect_prime_dfilter(&rf_edt, cf->rfcode);
1210 epan_dissect_run(&rf_edt, cf->cd_t, phdr, frame_tvbuff_new(&fdlocal, buf), &fdlocal, NULL);
1211 passed = dfilter_apply_edt(cf->rfcode, &rf_edt);
1212 epan_dissect_cleanup(&rf_edt);
1216 /* This does a shallow copy of fdlocal, which is good enough. */
1217 fdata = frame_data_sequence_add(cf->frames, &fdlocal);
1220 if (phdr->opt_comment != NULL)
1221 cf->packet_comment_count++;
1222 cf->f_datalen = offset + fdlocal.cap_len;
1224 if (!cf->redissecting) {
1225 row = add_packet_to_packet_list(fdata, cf, edt, dfcode,
1226 cinfo, phdr, buf, TRUE);
1234 typedef struct _callback_data_t {
1236 gint64 progbar_nextstep;
1237 gint64 progbar_quantum;
1238 GTimeVal start_time;
1245 merge_callback(merge_event event, int num _U_,
1246 const merge_in_file_t in_files[], const guint in_file_count,
1250 callback_data_t *cb_data = (callback_data_t*) data;
1252 g_assert(cb_data != NULL);
1256 case MERGE_EVENT_INPUT_FILES_OPENED:
1260 case MERGE_EVENT_FRAME_TYPE_SELECTED:
1264 case MERGE_EVENT_READY_TO_MERGE:
1265 /* Get the sum of the sizes of all the files. */
1266 for (i = 0; i < in_file_count; i++)
1267 cb_data->f_len += in_files[i].size;
1269 /* When we reach the value that triggers a progress bar update,
1270 bump that value by this amount. */
1271 cb_data->progbar_quantum = cb_data->f_len / N_PROGBAR_UPDATES;
1273 g_get_current_time(&cb_data->start_time);
1276 case MERGE_EVENT_PACKET_WAS_READ:
1278 gint64 data_offset = 0;
1280 /* Get the sum of the data offsets in all of the files. */
1282 for (i = 0; i < in_file_count; i++)
1283 data_offset += in_files[i].data_offset;
1285 /* Create the progress bar if necessary.
1286 We check on every iteration of the loop, so that it takes no
1287 longer than the standard time to create it (otherwise, for a
1288 large file, we might take considerably longer than that standard
1289 time in order to get to the next progress bar step). */
1290 if (cb_data->progbar == NULL) {
1291 cb_data->progbar = delayed_create_progress_dlg(NULL, "Merging", "files",
1292 FALSE, &cb_data->stop_flag, &cb_data->start_time, 0.0f);
1295 /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
1296 when we update it, we have to run the GTK+ main loop to get it
1297 to repaint what's pending, and doing so may involve an "ioctl()"
1298 to see if there's any pending input from an X server, and doing
1299 that for every packet can be costly, especially on a big file. */
1300 if (data_offset >= cb_data->progbar_nextstep) {
1302 gint64 file_pos = 0;
1303 /* Get the sum of the seek positions in all of the files. */
1304 for (i = 0; i < in_file_count; i++)
1305 file_pos += wtap_read_so_far(in_files[i].wth);
1307 progbar_val = (gfloat) file_pos / (gfloat) cb_data->f_len;
1308 if (progbar_val > 1.0f) {
1309 /* Some file probably grew while we were reading it.
1310 That "shouldn't happen", so we'll just clip the progress
1315 if (cb_data->progbar != NULL) {
1316 gchar status_str[100];
1317 g_snprintf(status_str, sizeof(status_str),
1318 "%" G_GINT64_MODIFIER "dKB of %" G_GINT64_MODIFIER "dKB",
1319 file_pos / 1024, cb_data->f_len / 1024);
1320 update_progress_dlg(cb_data->progbar, progbar_val, status_str);
1322 cb_data->progbar_nextstep += cb_data->progbar_quantum;
1327 case MERGE_EVENT_DONE:
1328 /* We're done merging the files; destroy the progress bar if it was created. */
1329 if (cb_data->progbar != NULL)
1330 destroy_progress_dlg(cb_data->progbar);
1334 return cb_data->stop_flag;
1340 cf_merge_files(char **out_filenamep, int in_file_count,
1341 char *const *in_filenames, int file_type, gboolean do_append)
1347 gchar *err_info = NULL;
1349 merge_result status;
1350 merge_progress_callback_t cb;
1353 if (*out_filenamep != NULL) {
1354 out_filename = *out_filenamep;
1355 out_fd = ws_open(out_filename, O_CREAT|O_TRUNC|O_BINARY, 0600);
1359 out_fd = create_tempfile(&tmpname, "wireshark");
1362 out_filename = g_strdup(tmpname);
1363 *out_filenamep = out_filename;
1366 cf_open_failure_alert_box(out_filename, err, NULL, TRUE, file_type);
1370 /* prepare our callback routine */
1371 cb.callback_func = merge_callback;
1372 cb.data = g_malloc0(sizeof(callback_data_t));
1374 /* merge the files */
1375 status = merge_files(out_fd, out_filename, file_type,
1376 (const char *const *) in_filenames, in_file_count,
1377 do_append, IDB_MERGE_MODE_ALL_SAME, 0 /* snaplen */,
1378 "Wireshark", &cb, &err, &err_info, &err_fileno);
1386 case MERGE_USER_ABORTED:
1387 /* this isn't really an error, though we will return CF_ERROR later */
1390 case MERGE_ERR_CANT_OPEN_INFILE:
1391 cf_open_failure_alert_box(in_filenames[err_fileno], err, err_info,
1395 case MERGE_ERR_CANT_OPEN_OUTFILE:
1396 cf_open_failure_alert_box(out_filename, err, err_info, TRUE,
1400 case MERGE_ERR_CANT_READ_INFILE: /* fall through */
1401 case MERGE_ERR_BAD_PHDR_INTERFACE_ID:
1402 case MERGE_ERR_CANT_WRITE_OUTFILE:
1403 case MERGE_ERR_CANT_CLOSE_OUTFILE:
1405 simple_error_message_box("%s", err_info ? err_info : "unknown error");
1412 if (status != MERGE_OK) {
1413 /* Callers aren't expected to treat an error or an explicit abort
1414 differently - we put up error dialogs ourselves, so they don't
1422 cf_filter_packets(capture_file *cf, gchar *dftext, gboolean force)
1424 const char *filter_new = dftext ? dftext : "";
1425 const char *filter_old = cf->dfilter ? cf->dfilter : "";
1428 GTimeVal start_time;
1430 /* if new filter equals old one, do nothing unless told to do so */
1431 if (!force && strcmp(filter_new, filter_old) == 0) {
1437 if (dftext == NULL) {
1438 /* The new filter is an empty filter (i.e., display all packets).
1439 * so leave dfcode==NULL
1443 * We have a filter; make a copy of it (as we'll be saving it),
1444 * and try to compile it.
1446 dftext = g_strdup(dftext);
1447 if (!dfilter_compile(dftext, &dfcode, &err_msg)) {
1448 /* The attempt failed; report an error. */
1449 simple_message_box(ESD_TYPE_ERROR, NULL,
1450 "See the help for a description of the display filter syntax.",
1451 "\"%s\" isn't a valid display filter: %s",
1459 if (dfcode == NULL) {
1460 /* Yes - free the filter text, and set it to null. */
1466 /* We have a valid filter. Replace the current filter. */
1467 g_free(cf->dfilter);
1468 cf->dfilter = dftext;
1469 g_get_current_time(&start_time);
1472 /* Now rescan the packet list, applying the new filter, but not
1473 throwing away information constructed on a previous pass. */
1474 if (cf->state != FILE_CLOSED) {
1475 if (dftext == NULL) {
1476 rescan_packets(cf, "Resetting", "Filter", FALSE);
1478 rescan_packets(cf, "Filtering", dftext, FALSE);
1482 /* Cleanup and release all dfilter resources */
1483 dfilter_free(dfcode);
1489 cf_reftime_packets(capture_file *cf)
1491 ref_time_packets(cf);
1495 cf_redissect_packets(capture_file *cf)
1497 if (cf->state != FILE_CLOSED) {
1498 rescan_packets(cf, "Reprocessing", "all packets", TRUE);
1503 cf_read_record_r(capture_file *cf, const frame_data *fdata,
1504 struct wtap_pkthdr *phdr, Buffer *buf)
1508 gchar *display_basename;
1510 #ifdef WANT_PACKET_EDITOR
1511 /* if fdata->file_off == -1 it means packet was edited, and we must find data inside edited_frames tree */
1512 if (G_UNLIKELY(fdata->file_off == -1)) {
1513 const modified_frame_data *frame = (const modified_frame_data *) g_tree_lookup(cf->edited_frames, GINT_TO_POINTER(fdata->num));
1516 simple_error_message_box("fdata->file_off == -1, but can't find modified frame.");
1520 *phdr = frame->phdr;
1521 ws_buffer_assure_space(buf, frame->phdr.caplen);
1522 memcpy(ws_buffer_start_ptr(buf), frame->pd, frame->phdr.caplen);
1527 if (!wtap_seek_read(cf->wth, fdata->file_off, phdr, buf, &err, &err_info)) {
1528 display_basename = g_filename_display_basename(cf->filename);
1531 case WTAP_ERR_BAD_FILE:
1532 simple_error_message_box("An error occurred while reading from the file \"%s\": %s.\n(%s)",
1533 display_basename, wtap_strerror(err),
1534 err_info != NULL ? err_info : "no information supplied");
1539 simple_error_message_box(
1540 "An error occurred while reading from the file \"%s\": %s.",
1541 display_basename, wtap_strerror(err));
1544 g_free(display_basename);
1551 cf_read_record(capture_file *cf, frame_data *fdata)
1553 return cf_read_record_r(cf, fdata, &cf->phdr, &cf->buf);
1556 /* Rescan the list of packets, reconstructing the CList.
1558 "action" describes why we're doing this; it's used in the progress
1561 "action_item" describes what we're doing; it's used in the progress
1564 "redissect" is TRUE if we need to make the dissectors reconstruct
1565 any state information they have (because a preference that affects
1566 some dissector has changed, meaning some dissector might construct
1567 its state differently from the way it was constructed the last time). */
1569 rescan_packets(capture_file *cf, const char *action, const char *action_item, gboolean redissect)
1571 /* Rescan packets new packet list */
1574 progdlg_t *progbar = NULL;
1576 frame_data *selected_frame, *preceding_frame, *following_frame, *prev_frame;
1577 int selected_frame_num, preceding_frame_num, following_frame_num, prev_frame_num;
1578 gboolean selected_frame_seen;
1580 GTimeVal start_time;
1581 gchar status_str[100];
1582 int progbar_nextstep;
1583 int progbar_quantum;
1587 gboolean create_proto_tree;
1589 gboolean add_to_packet_list = FALSE;
1591 guint32 frames_count;
1593 /* Compile the current display filter.
1594 * We assume this will not fail since cf->dfilter is only set in
1595 * cf_filter IFF the filter was valid.
1597 compiled = dfilter_compile(cf->dfilter, &dfcode, NULL);
1598 g_assert(!cf->dfilter || (compiled && dfcode));
1600 /* Get the union of the flags for all tap listeners. */
1601 tap_flags = union_of_tap_listener_flags();
1602 cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
1604 (dfcode != NULL || have_filtering_tap_listeners() || (tap_flags & TL_REQUIRES_PROTO_TREE));
1606 reset_tap_listeners();
1607 /* Which frame, if any, is the currently selected frame?
1608 XXX - should the selected frame or the focus frame be the "current"
1609 frame, that frame being the one from which "Find Frame" searches
1611 selected_frame = cf->current_frame;
1613 /* Mark frame num as not found */
1614 selected_frame_num = -1;
1616 /* Freeze the packet list while we redo it, so we don't get any
1617 screen updates while it happens. */
1618 packet_list_freeze();
1621 /* We need to re-initialize all the state information that protocols
1622 keep, because some preference that controls a dissector has changed,
1623 which might cause the state information to be constructed differently
1624 by that dissector. */
1626 /* We might receive new packets while redissecting, and we don't
1627 want to dissect those before their time. */
1628 cf->redissecting = TRUE;
1630 /* 'reset' dissection session */
1631 epan_free(cf->epan);
1632 cf->epan = ws_epan_new(cf);
1633 cf->cinfo.epan = cf->epan;
1635 /* We need to redissect the packets so we have to discard our old
1636 * packet list store. */
1637 packet_list_clear();
1638 add_to_packet_list = TRUE;
1641 /* We don't yet know which will be the first and last frames displayed. */
1642 cf->first_displayed = 0;
1643 cf->last_displayed = 0;
1645 /* We currently don't display any packets */
1646 cf->displayed_count = 0;
1648 /* Iterate through the list of frames. Call a routine for each frame
1649 to check whether it should be displayed and, if so, add it to
1650 the display list. */
1652 cf->prev_dis = NULL;
1653 cf->prev_cap = NULL;
1656 cf_callback_invoke(cf_cb_file_rescan_started, cf);
1658 /* Update the progress bar when it gets to this value. */
1659 progbar_nextstep = 0;
1660 /* When we reach the value that triggers a progress bar update,
1661 bump that value by this amount. */
1662 progbar_quantum = cf->count/N_PROGBAR_UPDATES;
1663 /* Count of packets at which we've looked. */
1665 /* Progress so far. */
1668 cf->stop_flag = FALSE;
1669 g_get_current_time(&start_time);
1671 /* no previous row yet */
1672 prev_frame_num = -1;
1675 preceding_frame_num = -1;
1676 preceding_frame = NULL;
1677 following_frame_num = -1;
1678 following_frame = NULL;
1680 selected_frame_seen = FALSE;
1682 frames_count = cf->count;
1684 epan_dissect_init(&edt, cf->epan, create_proto_tree, FALSE);
1686 for (framenum = 1; framenum <= frames_count; framenum++) {
1687 fdata = frame_data_sequence_find(cf->frames, framenum);
1689 /* Create the progress bar if necessary.
1690 We check on every iteration of the loop, so that it takes no
1691 longer than the standard time to create it (otherwise, for a
1692 large file, we might take considerably longer than that standard
1693 time in order to get to the next progress bar step). */
1694 if (progbar == NULL)
1695 progbar = delayed_create_progress_dlg(cf->window, action, action_item, TRUE,
1700 /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
1701 when we update it, we have to run the GTK+ main loop to get it
1702 to repaint what's pending, and doing so may involve an "ioctl()"
1703 to see if there's any pending input from an X server, and doing
1704 that for every packet can be costly, especially on a big file. */
1705 if (count >= progbar_nextstep) {
1706 /* let's not divide by zero. I should never be started
1707 * with count == 0, so let's assert that
1709 g_assert(cf->count > 0);
1710 progbar_val = (gfloat) count / frames_count;
1712 if (progbar != NULL) {
1713 g_snprintf(status_str, sizeof(status_str),
1714 "%4u of %u frames", count, frames_count);
1715 update_progress_dlg(progbar, progbar_val, status_str);
1718 progbar_nextstep += progbar_quantum;
1721 if (cf->stop_flag) {
1722 /* Well, the user decided to abort the filtering. Just stop.
1724 XXX - go back to the previous filter? Users probably just
1725 want not to wait for a filtering operation to finish;
1726 unless we cancel by having no filter, reverting to the
1727 previous filter will probably be even more expensive than
1728 continuing the filtering, as it involves going back to the
1729 beginning and filtering, and even with no filter we currently
1730 have to re-generate the entire clist, which is also expensive.
1732 I'm not sure what Network Monitor does, but it doesn't appear
1733 to give you an unfiltered display if you cancel. */
1740 /* Since all state for the frame was destroyed, mark the frame
1741 * as not visited, free the GSList referring to the state
1742 * data (the per-frame data itself was freed by
1743 * "init_dissection()"), and null out the GSList pointer. */
1744 frame_data_reset(fdata);
1745 frames_count = cf->count;
1748 /* Frame dependencies from the previous dissection/filtering are no longer valid. */
1749 fdata->flags.dependent_of_displayed = 0;
1751 if (!cf_read_record(cf, fdata))
1752 break; /* error reading the frame */
1754 /* If the previous frame is displayed, and we haven't yet seen the
1755 selected frame, remember that frame - it's the closest one we've
1756 yet seen before the selected frame. */
1757 if (prev_frame_num != -1 && !selected_frame_seen && prev_frame->flags.passed_dfilter) {
1758 preceding_frame_num = prev_frame_num;
1759 preceding_frame = prev_frame;
1762 add_packet_to_packet_list(fdata, cf, &edt, dfcode,
1764 ws_buffer_start_ptr(&cf->buf),
1765 add_to_packet_list);
1767 /* If this frame is displayed, and this is the first frame we've
1768 seen displayed after the selected frame, remember this frame -
1769 it's the closest one we've yet seen at or after the selected
1771 if (fdata->flags.passed_dfilter && selected_frame_seen && following_frame_num == -1) {
1772 following_frame_num = fdata->num;
1773 following_frame = fdata;
1775 if (fdata == selected_frame) {
1776 selected_frame_seen = TRUE;
1777 if (fdata->flags.passed_dfilter)
1778 selected_frame_num = fdata->num;
1781 /* Remember this frame - it'll be the previous frame
1782 on the next pass through the loop. */
1783 prev_frame_num = fdata->num;
1787 epan_dissect_cleanup(&edt);
1789 /* We are done redissecting the packet list. */
1790 cf->redissecting = FALSE;
1793 frames_count = cf->count;
1794 /* Clear out what remains of the visited flags and per-frame data
1797 XXX - that may cause various forms of bogosity when dissecting
1798 these frames, as they won't have been seen by this sequential
1799 pass, but the only alternative I see is to keep scanning them
1800 even though the user requested that the scan stop, and that
1801 would leave the user stuck with an Wireshark grinding on
1802 until it finishes. Should we just stick them with that? */
1803 for (; framenum <= frames_count; framenum++) {
1804 fdata = frame_data_sequence_find(cf->frames, framenum);
1805 frame_data_reset(fdata);
1809 /* We're done filtering the packets; destroy the progress bar if it
1811 if (progbar != NULL)
1812 destroy_progress_dlg(progbar);
1814 /* Unfreeze the packet list. */
1815 if (!add_to_packet_list)
1816 packet_list_recreate_visible_rows();
1818 /* Compute the time it took to filter the file */
1819 compute_elapsed(cf, &start_time);
1823 cf_callback_invoke(cf_cb_file_rescan_finished, cf);
1825 if (selected_frame_num == -1) {
1826 /* The selected frame didn't pass the filter. */
1827 if (selected_frame == NULL) {
1828 /* That's because there *was* no selected frame. Make the first
1829 displayed frame the current frame. */
1830 selected_frame_num = 0;
1832 /* Find the nearest displayed frame to the selected frame (whether
1833 it's before or after that frame) and make that the current frame.
1834 If the next and previous displayed frames are equidistant from the
1835 selected frame, choose the next one. */
1836 g_assert(following_frame == NULL ||
1837 following_frame->num >= selected_frame->num);
1838 g_assert(preceding_frame == NULL ||
1839 preceding_frame->num <= selected_frame->num);
1840 if (following_frame == NULL) {
1841 /* No frame after the selected frame passed the filter, so we
1842 have to select the last displayed frame before the selected
1844 selected_frame_num = preceding_frame_num;
1845 selected_frame = preceding_frame;
1846 } else if (preceding_frame == NULL) {
1847 /* No frame before the selected frame passed the filter, so we
1848 have to select the first displayed frame after the selected
1850 selected_frame_num = following_frame_num;
1851 selected_frame = following_frame;
1853 /* Frames before and after the selected frame passed the filter, so
1854 we'll select the previous frame */
1855 selected_frame_num = preceding_frame_num;
1856 selected_frame = preceding_frame;
1861 if (selected_frame_num == -1) {
1862 /* There are no frames displayed at all. */
1863 cf_unselect_packet(cf);
1865 /* Either the frame that was selected passed the filter, or we've
1866 found the nearest displayed frame to that frame. Select it, make
1867 it the focus row, and make it visible. */
1868 /* Set to invalid to force update of packet list and packet details */
1869 cf->current_row = -1;
1870 if (selected_frame_num == 0) {
1871 packet_list_select_first_row();
1873 if (!packet_list_select_row_from_data(selected_frame)) {
1874 /* We didn't find a row corresponding to this frame.
1875 This means that the frame isn't being displayed currently,
1876 so we can't select it. */
1877 simple_message_box(ESD_TYPE_INFO, NULL,
1878 "The capture file is probably not fully dissected.",
1879 "End of capture exceeded.");
1884 /* Cleanup and release all dfilter resources */
1885 dfilter_free(dfcode);
1890 * Scan trough all frame data and recalculate the ref time
1891 * without rereading the file.
1892 * XXX - do we need a progres bar or is this fast enough?
1895 ref_time_packets(capture_file *cf)
1902 cf->prev_dis = NULL;
1905 for (framenum = 1; framenum <= cf->count; framenum++) {
1906 fdata = frame_data_sequence_find(cf->frames, framenum);
1908 /* just add some value here until we know if it is being displayed or not */
1909 fdata->cum_bytes = cf->cum_bytes + fdata->pkt_len;
1915 /* If we don't have the time stamp of the first packet in the
1916 capture, it's because this is the first packet. Save the time
1917 stamp of this packet as the time stamp of the first packet. */
1918 if (cf->ref == NULL)
1920 /* if this frames is marked as a reference time frame, reset
1921 firstsec and firstusec to this frame */
1922 if (fdata->flags.ref_time)
1925 /* If we don't have the time stamp of the previous displayed packet,
1926 it's because this is the first displayed packet. Save the time
1927 stamp of this packet as the time stamp of the previous displayed
1929 if (cf->prev_dis == NULL) {
1930 cf->prev_dis = fdata;
1933 /* Get the time elapsed between the first packet and this packet. */
1934 fdata->frame_ref_num = (fdata != cf->ref) ? cf->ref->num : 0;
1935 nstime_delta(&rel_ts, &fdata->abs_ts, &cf->ref->abs_ts);
1937 /* If it's greater than the current elapsed time, set the elapsed time
1938 to it (we check for "greater than" so as not to be confused by
1939 time moving backwards). */
1940 if ((gint32)cf->elapsed_time.secs < rel_ts.secs
1941 || ((gint32)cf->elapsed_time.secs == rel_ts.secs && (gint32)cf->elapsed_time.nsecs < rel_ts.nsecs)) {
1942 cf->elapsed_time = rel_ts;
1945 /* If this frame is displayed, get the time elapsed between the
1946 previous displayed packet and this packet. */
1947 if ( fdata->flags.passed_dfilter ) {
1948 fdata->prev_dis_num = cf->prev_dis->num;
1949 cf->prev_dis = fdata;
1955 if ( (fdata->flags.passed_dfilter) || (fdata->flags.ref_time) ) {
1956 /* This frame either passed the display filter list or is marked as
1957 a time reference frame. All time reference frames are displayed
1958 even if they don't pass the display filter */
1959 if (fdata->flags.ref_time) {
1960 /* if this was a TIME REF frame we should reset the cum_bytes field */
1961 cf->cum_bytes = fdata->pkt_len;
1962 fdata->cum_bytes = cf->cum_bytes;
1964 /* increase cum_bytes with this packets length */
1965 cf->cum_bytes += fdata->pkt_len;
1978 process_specified_records(capture_file *cf, packet_range_t *range,
1979 const char *string1, const char *string2, gboolean terminate_is_stop,
1980 gboolean (*callback)(capture_file *, frame_data *,
1981 struct wtap_pkthdr *, const guint8 *, void *),
1982 void *callback_args)
1987 psp_return_t ret = PSP_FINISHED;
1989 progdlg_t *progbar = NULL;
1992 GTimeVal progbar_start_time;
1993 gchar progbar_status_str[100];
1994 int progbar_nextstep;
1995 int progbar_quantum;
1996 range_process_e process_this;
1997 struct wtap_pkthdr phdr;
1999 wtap_phdr_init(&phdr);
2000 ws_buffer_init(&buf, 1500);
2002 /* Update the progress bar when it gets to this value. */
2003 progbar_nextstep = 0;
2004 /* When we reach the value that triggers a progress bar update,
2005 bump that value by this amount. */
2006 progbar_quantum = cf->count/N_PROGBAR_UPDATES;
2007 /* Count of packets at which we've looked. */
2009 /* Progress so far. */
2012 cf->stop_flag = FALSE;
2013 g_get_current_time(&progbar_start_time);
2016 packet_range_process_init(range);
2018 /* Iterate through all the packets, printing the packets that
2019 were selected by the current display filter. */
2020 for (framenum = 1; framenum <= cf->count; framenum++) {
2021 fdata = frame_data_sequence_find(cf->frames, framenum);
2023 /* Create the progress bar if necessary.
2024 We check on every iteration of the loop, so that it takes no
2025 longer than the standard time to create it (otherwise, for a
2026 large file, we might take considerably longer than that standard
2027 time in order to get to the next progress bar step). */
2028 if (progbar == NULL)
2029 progbar = delayed_create_progress_dlg(cf->window, string1, string2,
2032 &progbar_start_time,
2035 /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
2036 when we update it, we have to run the GTK+ main loop to get it
2037 to repaint what's pending, and doing so may involve an "ioctl()"
2038 to see if there's any pending input from an X server, and doing
2039 that for every packet can be costly, especially on a big file. */
2040 if (progbar_count >= progbar_nextstep) {
2041 /* let's not divide by zero. I should never be started
2042 * with count == 0, so let's assert that
2044 g_assert(cf->count > 0);
2045 progbar_val = (gfloat) progbar_count / cf->count;
2047 if (progbar != NULL) {
2048 g_snprintf(progbar_status_str, sizeof(progbar_status_str),
2049 "%4u of %u packets", progbar_count, cf->count);
2050 update_progress_dlg(progbar, progbar_val, progbar_status_str);
2053 progbar_nextstep += progbar_quantum;
2056 if (cf->stop_flag) {
2057 /* Well, the user decided to abort the operation. Just stop,
2058 and arrange to return PSP_STOPPED to our caller, so they know
2059 it was stopped explicitly. */
2066 if (range != NULL) {
2067 /* do we have to process this packet? */
2068 process_this = packet_range_process_packet(range, fdata);
2069 if (process_this == range_process_next) {
2070 /* this packet uninteresting, continue with next one */
2072 } else if (process_this == range_processing_finished) {
2073 /* all interesting packets processed, stop the loop */
2078 /* Get the packet */
2079 if (!cf_read_record_r(cf, fdata, &phdr, &buf)) {
2080 /* Attempt to get the packet failed. */
2084 /* Process the packet */
2085 if (!callback(cf, fdata, &phdr, ws_buffer_start_ptr(&buf), callback_args)) {
2086 /* Callback failed. We assume it reported the error appropriately. */
2092 /* We're done printing the packets; destroy the progress bar if
2094 if (progbar != NULL)
2095 destroy_progress_dlg(progbar);
2097 wtap_phdr_cleanup(&phdr);
2098 ws_buffer_free(&buf);
2106 } retap_callback_args_t;
2109 retap_packet(capture_file *cf, frame_data *fdata,
2110 struct wtap_pkthdr *phdr, const guint8 *pd,
2113 retap_callback_args_t *args = (retap_callback_args_t *)argsp;
2115 epan_dissect_run_with_taps(&args->edt, cf->cd_t, phdr, frame_tvbuff_new(fdata, pd), fdata, args->cinfo);
2116 epan_dissect_reset(&args->edt);
2122 cf_retap_packets(capture_file *cf)
2124 packet_range_t range;
2125 retap_callback_args_t callback_args;
2126 gboolean construct_protocol_tree;
2127 gboolean filtering_tap_listeners;
2131 /* Presumably the user closed the capture file. */
2133 return CF_READ_ABORTED;
2136 cf_callback_invoke(cf_cb_file_retap_started, cf);
2138 /* Do we have any tap listeners with filters? */
2139 filtering_tap_listeners = have_filtering_tap_listeners();
2141 tap_flags = union_of_tap_listener_flags();
2143 /* If any tap listeners have filters, or require the protocol tree,
2144 construct the protocol tree. */
2145 construct_protocol_tree = filtering_tap_listeners ||
2146 (tap_flags & TL_REQUIRES_PROTO_TREE);
2148 /* If any tap listeners require the columns, construct them. */
2149 callback_args.cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
2151 /* Reset the tap listeners. */
2152 reset_tap_listeners();
2154 epan_dissect_init(&callback_args.edt, cf->epan, construct_protocol_tree, FALSE);
2156 /* Iterate through the list of packets, dissecting all packets and
2157 re-running the taps. */
2158 packet_range_init(&range, cf);
2159 packet_range_process_init(&range);
2161 ret = process_specified_records(cf, &range, "Recalculating statistics on",
2162 "all packets", TRUE, retap_packet,
2165 epan_dissect_cleanup(&callback_args.edt);
2167 cf_callback_invoke(cf_cb_file_retap_finished, cf);
2171 /* Completed successfully. */
2175 /* Well, the user decided to abort the refiltering.
2176 Return CF_READ_ABORTED so our caller knows they did that. */
2177 return CF_READ_ABORTED;
2180 /* Error while retapping. */
2181 return CF_READ_ERROR;
2184 g_assert_not_reached();
2189 print_args_t *print_args;
2190 gboolean print_header_line;
2191 char *header_line_buf;
2192 int header_line_buf_len;
2193 gboolean print_formfeed;
2194 gboolean print_separator;
2198 int num_visible_cols;
2201 } print_callback_args_t;
2204 print_packet(capture_file *cf, frame_data *fdata,
2205 struct wtap_pkthdr *phdr, const guint8 *pd,
2208 print_callback_args_t *args = (print_callback_args_t *)argsp;
2214 char bookmark_name[9+10+1]; /* "__frameNNNNNNNNNN__\0" */
2215 char bookmark_title[6+10+1]; /* "Frame NNNNNNNNNN__\0" */
2216 col_item_t* col_item;
2218 /* Fill in the column information if we're printing the summary
2220 if (args->print_args->print_summary) {
2221 col_custom_prime_edt(&args->edt, &cf->cinfo);
2222 epan_dissect_run(&args->edt, cf->cd_t, phdr, frame_tvbuff_new(fdata, pd), fdata, &cf->cinfo);
2223 epan_dissect_fill_in_columns(&args->edt, FALSE, TRUE);
2225 epan_dissect_run(&args->edt, cf->cd_t, phdr, frame_tvbuff_new(fdata, pd), fdata, NULL);
2227 if (args->print_formfeed) {
2228 if (!new_page(args->print_args->stream))
2231 if (args->print_separator) {
2232 if (!print_line(args->print_args->stream, 0, ""))
2238 * We generate bookmarks, if the output format supports them.
2239 * The name is "__frameN__".
2241 g_snprintf(bookmark_name, sizeof bookmark_name, "__frame%u__", fdata->num);
2243 if (args->print_args->print_summary) {
2244 if (!args->print_args->print_col_headings)
2245 args->print_header_line = FALSE;
2246 if (args->print_header_line) {
2247 if (!print_line(args->print_args->stream, 0, args->header_line_buf))
2249 args->print_header_line = FALSE; /* we might not need to print any more */
2251 cp = &args->line_buf[0];
2253 for (i = 0; i < args->num_visible_cols; i++) {
2254 col_item = &cf->cinfo.columns[args->visible_cols[i]];
2255 /* Find the length of the string for this column. */
2256 column_len = (int) strlen(col_item->col_data);
2257 if (args->col_widths[i] > column_len)
2258 column_len = args->col_widths[i];
2260 /* Make sure there's room in the line buffer for the column; if not,
2261 double its length. */
2262 line_len += column_len + 1; /* "+1" for space */
2263 if (line_len > args->line_buf_len) {
2264 cp_off = (int) (cp - args->line_buf);
2265 args->line_buf_len = 2 * line_len;
2266 args->line_buf = (char *)g_realloc(args->line_buf, args->line_buf_len + 1);
2267 cp = args->line_buf + cp_off;
2270 /* Right-justify the packet number column. */
2271 if (col_item->col_fmt == COL_NUMBER)
2272 g_snprintf(cp, column_len+1, "%*s", args->col_widths[i], col_item->col_data);
2274 g_snprintf(cp, column_len+1, "%-*s", args->col_widths[i], col_item->col_data);
2276 if (i != args->num_visible_cols - 1)
2282 * Generate a bookmark, using the summary line as the title.
2284 if (!print_bookmark(args->print_args->stream, bookmark_name,
2288 if (!print_line(args->print_args->stream, 0, args->line_buf))
2292 * Generate a bookmark, using "Frame N" as the title, as we're not
2293 * printing the summary line.
2295 g_snprintf(bookmark_title, sizeof bookmark_title, "Frame %u", fdata->num);
2296 if (!print_bookmark(args->print_args->stream, bookmark_name,
2299 } /* if (print_summary) */
2301 if (args->print_args->print_dissections != print_dissections_none) {
2302 if (args->print_args->print_summary) {
2303 /* Separate the summary line from the tree with a blank line. */
2304 if (!print_line(args->print_args->stream, 0, ""))
2308 /* Print the information in that tree. */
2309 if (!proto_tree_print(args->print_args, &args->edt, NULL, args->print_args->stream))
2312 /* Print a blank line if we print anything after this (aka more than one packet). */
2313 args->print_separator = TRUE;
2315 /* Print a header line if we print any more packet summaries */
2316 if (args->print_args->print_col_headings)
2317 args->print_header_line = TRUE;
2320 if (args->print_args->print_hex) {
2321 if (args->print_args->print_summary || (args->print_args->print_dissections != print_dissections_none)) {
2322 if (!print_line(args->print_args->stream, 0, ""))
2325 /* Print the full packet data as hex. */
2326 if (!print_hex_data(args->print_args->stream, &args->edt))
2329 /* Print a blank line if we print anything after this (aka more than one packet). */
2330 args->print_separator = TRUE;
2332 /* Print a header line if we print any more packet summaries */
2333 if (args->print_args->print_col_headings)
2334 args->print_header_line = TRUE;
2335 } /* if (args->print_args->print_dissections != print_dissections_none) */
2337 epan_dissect_reset(&args->edt);
2339 /* do we want to have a formfeed between each packet from now on? */
2340 if (args->print_args->print_formfeed) {
2341 args->print_formfeed = TRUE;
2347 epan_dissect_reset(&args->edt);
2352 cf_print_packets(capture_file *cf, print_args_t *print_args)
2354 print_callback_args_t callback_args;
2357 int i, cp_off, column_len, line_len;
2358 int num_visible_col = 0, last_visible_col = 0, visible_col_count;
2362 gboolean proto_tree_needed;
2364 callback_args.print_args = print_args;
2365 callback_args.print_header_line = print_args->print_col_headings;
2366 callback_args.header_line_buf = NULL;
2367 callback_args.header_line_buf_len = 256;
2368 callback_args.print_formfeed = FALSE;
2369 callback_args.print_separator = FALSE;
2370 callback_args.line_buf = NULL;
2371 callback_args.line_buf_len = 256;
2372 callback_args.col_widths = NULL;
2373 callback_args.num_visible_cols = 0;
2374 callback_args.visible_cols = NULL;
2376 if (!print_preamble(print_args->stream, cf->filename, get_ws_vcs_version_info())) {
2377 destroy_print_stream(print_args->stream);
2378 return CF_PRINT_WRITE_ERROR;
2381 if (print_args->print_summary) {
2382 /* We're printing packet summaries. Allocate the header line buffer
2383 and get the column widths. */
2384 callback_args.header_line_buf = (char *)g_malloc(callback_args.header_line_buf_len + 1);
2386 /* Find the number of visible columns and the last visible column */
2387 for (i = 0; i < prefs.num_cols; i++) {
2389 clp = g_list_nth(prefs.col_list, i);
2390 if (clp == NULL) /* Sanity check, Invalid column requested */
2393 cfmt = (fmt_data *) clp->data;
2394 if (cfmt->visible) {
2396 last_visible_col = i;
2400 /* Find the widths for each of the columns - maximum of the
2401 width of the title and the width of the data - and construct
2402 a buffer with a line containing the column titles. */
2403 callback_args.num_visible_cols = num_visible_col;
2404 callback_args.col_widths = (gint *) g_malloc(sizeof(gint) * num_visible_col);
2405 callback_args.visible_cols = (gint *) g_malloc(sizeof(gint) * num_visible_col);
2406 cp = &callback_args.header_line_buf[0];
2408 visible_col_count = 0;
2409 for (i = 0; i < cf->cinfo.num_cols; i++) {
2411 clp = g_list_nth(prefs.col_list, i);
2412 if (clp == NULL) /* Sanity check, Invalid column requested */
2415 cfmt = (fmt_data *) clp->data;
2416 if (cfmt->visible == FALSE)
2419 /* Save the order of visible columns */
2420 callback_args.visible_cols[visible_col_count] = i;
2422 /* Don't pad the last column. */
2423 if (i == last_visible_col)
2424 callback_args.col_widths[visible_col_count] = 0;
2426 callback_args.col_widths[visible_col_count] = (gint) strlen(cf->cinfo.columns[i].col_title);
2427 data_width = get_column_char_width(get_column_format(i));
2428 if (data_width > callback_args.col_widths[visible_col_count])
2429 callback_args.col_widths[visible_col_count] = data_width;
2432 /* Find the length of the string for this column. */
2433 column_len = (int) strlen(cf->cinfo.columns[i].col_title);
2434 if (callback_args.col_widths[i] > column_len)
2435 column_len = callback_args.col_widths[visible_col_count];
2437 /* Make sure there's room in the line buffer for the column; if not,
2438 double its length. */
2439 line_len += column_len + 1; /* "+1" for space */
2440 if (line_len > callback_args.header_line_buf_len) {
2441 cp_off = (int) (cp - callback_args.header_line_buf);
2442 callback_args.header_line_buf_len = 2 * line_len;
2443 callback_args.header_line_buf = (char *)g_realloc(callback_args.header_line_buf,
2444 callback_args.header_line_buf_len + 1);
2445 cp = callback_args.header_line_buf + cp_off;
2448 /* Right-justify the packet number column. */
2449 /* if (cf->cinfo.col_fmt[i] == COL_NUMBER)
2450 g_snprintf(cp, column_len+1, "%*s", callback_args.col_widths[visible_col_count], cf->cinfo.columns[i].col_title);
2452 g_snprintf(cp, column_len+1, "%-*s", callback_args.col_widths[visible_col_count], cf->cinfo.columns[i].col_title);
2454 if (i != cf->cinfo.num_cols - 1)
2457 visible_col_count++;
2461 /* Now start out the main line buffer with the same length as the
2462 header line buffer. */
2463 callback_args.line_buf_len = callback_args.header_line_buf_len;
2464 callback_args.line_buf = (char *)g_malloc(callback_args.line_buf_len + 1);
2465 } /* if (print_summary) */
2467 /* Create the protocol tree, and make it visible, if we're printing
2468 the dissection or the hex data.
2469 XXX - do we need it if we're just printing the hex data? */
2471 callback_args.print_args->print_dissections != print_dissections_none ||
2472 callback_args.print_args->print_hex ||
2473 have_custom_cols(&cf->cinfo);
2474 epan_dissect_init(&callback_args.edt, cf->epan, proto_tree_needed, proto_tree_needed);
2476 /* Iterate through the list of packets, printing the packets we were
2478 ret = process_specified_records(cf, &print_args->range, "Printing",
2479 "selected packets", TRUE, print_packet,
2481 epan_dissect_cleanup(&callback_args.edt);
2482 g_free(callback_args.header_line_buf);
2483 g_free(callback_args.line_buf);
2484 g_free(callback_args.col_widths);
2485 g_free(callback_args.visible_cols);
2490 /* Completed successfully. */
2494 /* Well, the user decided to abort the printing.
2496 XXX - note that what got generated before they did that
2497 will get printed if we're piping to a print program; we'd
2498 have to write to a file and then hand that to the print
2499 program to make it actually not print anything. */
2503 /* Error while printing.
2505 XXX - note that what got generated before they did that
2506 will get printed if we're piping to a print program; we'd
2507 have to write to a file and then hand that to the print
2508 program to make it actually not print anything. */
2509 destroy_print_stream(print_args->stream);
2510 return CF_PRINT_WRITE_ERROR;
2513 if (!print_finale(print_args->stream)) {
2514 destroy_print_stream(print_args->stream);
2515 return CF_PRINT_WRITE_ERROR;
2518 if (!destroy_print_stream(print_args->stream))
2519 return CF_PRINT_WRITE_ERROR;
2527 } write_packet_callback_args_t;
2530 write_pdml_packet(capture_file *cf, frame_data *fdata,
2531 struct wtap_pkthdr *phdr, const guint8 *pd,
2534 write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
2536 /* Create the protocol tree, but don't fill in the column information. */
2537 epan_dissect_run(&args->edt, cf->cd_t, phdr, frame_tvbuff_new(fdata, pd), fdata, NULL);
2539 /* Write out the information in that tree. */
2540 write_pdml_proto_tree(&args->edt, args->fh);
2542 epan_dissect_reset(&args->edt);
2544 return !ferror(args->fh);
2548 cf_write_pdml_packets(capture_file *cf, print_args_t *print_args)
2550 write_packet_callback_args_t callback_args;
2554 fh = ws_fopen(print_args->file, "w");
2556 return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2558 write_pdml_preamble(fh, cf->filename);
2561 return CF_PRINT_WRITE_ERROR;
2564 callback_args.fh = fh;
2565 epan_dissect_init(&callback_args.edt, cf->epan, TRUE, TRUE);
2567 /* Iterate through the list of packets, printing the packets we were
2569 ret = process_specified_records(cf, &print_args->range, "Writing PDML",
2570 "selected packets", TRUE,
2571 write_pdml_packet, &callback_args);
2573 epan_dissect_cleanup(&callback_args.edt);
2578 /* Completed successfully. */
2582 /* Well, the user decided to abort the printing. */
2586 /* Error while printing. */
2588 return CF_PRINT_WRITE_ERROR;
2591 write_pdml_finale(fh);
2594 return CF_PRINT_WRITE_ERROR;
2597 /* XXX - check for an error */
2604 write_psml_packet(capture_file *cf, frame_data *fdata,
2605 struct wtap_pkthdr *phdr, const guint8 *pd,
2608 write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
2610 /* Fill in the column information */
2611 col_custom_prime_edt(&args->edt, &cf->cinfo);
2612 epan_dissect_run(&args->edt, cf->cd_t, phdr, frame_tvbuff_new(fdata, pd), fdata, &cf->cinfo);
2613 epan_dissect_fill_in_columns(&args->edt, FALSE, TRUE);
2615 /* Write out the column information. */
2616 write_psml_columns(&args->edt, args->fh);
2618 epan_dissect_reset(&args->edt);
2620 return !ferror(args->fh);
2624 cf_write_psml_packets(capture_file *cf, print_args_t *print_args)
2626 write_packet_callback_args_t callback_args;
2630 gboolean proto_tree_needed;
2632 fh = ws_fopen(print_args->file, "w");
2634 return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2636 write_psml_preamble(&cf->cinfo, fh);
2639 return CF_PRINT_WRITE_ERROR;
2642 callback_args.fh = fh;
2644 /* Fill in the column information, only create the protocol tree
2645 if having custom columns. */
2646 proto_tree_needed = have_custom_cols(&cf->cinfo);
2647 epan_dissect_init(&callback_args.edt, cf->epan, proto_tree_needed, proto_tree_needed);
2649 /* Iterate through the list of packets, printing the packets we were
2651 ret = process_specified_records(cf, &print_args->range, "Writing PSML",
2652 "selected packets", TRUE,
2653 write_psml_packet, &callback_args);
2655 epan_dissect_cleanup(&callback_args.edt);
2660 /* Completed successfully. */
2664 /* Well, the user decided to abort the printing. */
2668 /* Error while printing. */
2670 return CF_PRINT_WRITE_ERROR;
2673 write_psml_finale(fh);
2676 return CF_PRINT_WRITE_ERROR;
2679 /* XXX - check for an error */
2686 write_csv_packet(capture_file *cf, frame_data *fdata,
2687 struct wtap_pkthdr *phdr, const guint8 *pd,
2690 write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
2692 /* Fill in the column information */
2693 col_custom_prime_edt(&args->edt, &cf->cinfo);
2694 epan_dissect_run(&args->edt, cf->cd_t, phdr, frame_tvbuff_new(fdata, pd), fdata, &cf->cinfo);
2695 epan_dissect_fill_in_columns(&args->edt, FALSE, TRUE);
2697 /* Write out the column information. */
2698 write_csv_columns(&args->edt, args->fh);
2700 epan_dissect_reset(&args->edt);
2702 return !ferror(args->fh);
2706 cf_write_csv_packets(capture_file *cf, print_args_t *print_args)
2708 write_packet_callback_args_t callback_args;
2709 gboolean proto_tree_needed;
2713 fh = ws_fopen(print_args->file, "w");
2715 return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2717 write_csv_column_titles(&cf->cinfo, fh);
2720 return CF_PRINT_WRITE_ERROR;
2723 callback_args.fh = fh;
2725 /* only create the protocol tree if having custom columns. */
2726 proto_tree_needed = have_custom_cols(&cf->cinfo);
2727 epan_dissect_init(&callback_args.edt, cf->epan, proto_tree_needed, proto_tree_needed);
2729 /* Iterate through the list of packets, printing the packets we were
2731 ret = process_specified_records(cf, &print_args->range, "Writing CSV",
2732 "selected packets", TRUE,
2733 write_csv_packet, &callback_args);
2735 epan_dissect_cleanup(&callback_args.edt);
2740 /* Completed successfully. */
2744 /* Well, the user decided to abort the printing. */
2748 /* Error while printing. */
2750 return CF_PRINT_WRITE_ERROR;
2753 /* XXX - check for an error */
2760 carrays_write_packet(capture_file *cf, frame_data *fdata,
2761 struct wtap_pkthdr *phdr,
2762 const guint8 *pd, void *argsp)
2764 write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
2766 epan_dissect_run(&args->edt, cf->cd_t, phdr, frame_tvbuff_new(fdata, pd), fdata, NULL);
2767 write_carrays_hex_data(fdata->num, args->fh, &args->edt);
2768 epan_dissect_reset(&args->edt);
2770 return !ferror(args->fh);
2774 cf_write_carrays_packets(capture_file *cf, print_args_t *print_args)
2776 write_packet_callback_args_t callback_args;
2780 fh = ws_fopen(print_args->file, "w");
2783 return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2787 return CF_PRINT_WRITE_ERROR;
2790 callback_args.fh = fh;
2791 epan_dissect_init(&callback_args.edt, cf->epan, TRUE, TRUE);
2793 /* Iterate through the list of packets, printing the packets we were
2795 ret = process_specified_records(cf, &print_args->range,
2797 "selected packets", TRUE,
2798 carrays_write_packet, &callback_args);
2800 epan_dissect_cleanup(&callback_args.edt);
2804 /* Completed successfully. */
2807 /* Well, the user decided to abort the printing. */
2810 /* Error while printing. */
2812 return CF_PRINT_WRITE_ERROR;
2820 cf_find_packet_protocol_tree(capture_file *cf, const char *string,
2821 search_direction dir)
2825 mdata.string = string;
2826 mdata.string_len = strlen(string);
2827 return find_packet(cf, match_protocol_tree, &mdata, dir);
2831 cf_find_string_protocol_tree(capture_file *cf, proto_tree *tree, match_data *mdata)
2833 mdata->frame_matched = FALSE;
2834 mdata->string = convert_string_case(cf->sfilter, cf->case_type);
2835 mdata->string_len = strlen(mdata->string);
2837 /* Iterate through all the nodes looking for matching text */
2838 proto_tree_children_foreach(tree, match_subtree_text, mdata);
2839 return mdata->frame_matched ? MR_MATCHED : MR_NOTMATCHED;
2843 match_protocol_tree(capture_file *cf, frame_data *fdata, void *criterion)
2845 match_data *mdata = (match_data *)criterion;
2848 /* Load the frame's data. */
2849 if (!cf_read_record(cf, fdata)) {
2850 /* Attempt to get the packet failed. */
2854 /* Construct the protocol tree, including the displayed text */
2855 epan_dissect_init(&edt, cf->epan, TRUE, TRUE);
2856 /* We don't need the column information */
2857 epan_dissect_run(&edt, cf->cd_t, &cf->phdr, frame_tvbuff_new_buffer(fdata, &cf->buf), fdata, NULL);
2859 /* Iterate through all the nodes, seeing if they have text that matches. */
2861 mdata->frame_matched = FALSE;
2862 proto_tree_children_foreach(edt.tree, match_subtree_text, mdata);
2863 epan_dissect_cleanup(&edt);
2864 return mdata->frame_matched ? MR_MATCHED : MR_NOTMATCHED;
2868 match_subtree_text(proto_node *node, gpointer data)
2870 match_data *mdata = (match_data *) data;
2871 const gchar *string = mdata->string;
2872 size_t string_len = mdata->string_len;
2873 capture_file *cf = mdata->cf;
2874 field_info *fi = PNODE_FINFO(node);
2875 gchar label_str[ITEM_LABEL_LENGTH];
2882 /* dissection with an invisible proto tree? */
2885 if (mdata->frame_matched) {
2886 /* We already had a match; don't bother doing any more work. */
2890 /* Don't match invisible entries. */
2891 if (PROTO_ITEM_IS_HIDDEN(node))
2894 /* was a free format label produced? */
2896 label_ptr = fi->rep->representation;
2898 /* no, make a generic label */
2899 label_ptr = label_str;
2900 proto_item_fill_label(fi, label_str);
2903 /* Does that label match? */
2904 label_len = strlen(label_ptr);
2905 for (i = 0; i < label_len; i++) {
2906 c_char = label_ptr[i];
2908 c_char = g_ascii_toupper(c_char);
2909 if (c_char == string[c_match]) {
2911 if (c_match == string_len) {
2912 /* No need to look further; we have a match */
2913 mdata->frame_matched = TRUE;
2921 /* Recurse into the subtree, if it exists */
2922 if (node->first_child != NULL)
2923 proto_tree_children_foreach(node, match_subtree_text, mdata);
2927 cf_find_packet_summary_line(capture_file *cf, const char *string,
2928 search_direction dir)
2932 mdata.string = string;
2933 mdata.string_len = strlen(string);
2934 return find_packet(cf, match_summary_line, &mdata, dir);
2938 match_summary_line(capture_file *cf, frame_data *fdata, void *criterion)
2940 match_data *mdata = (match_data *)criterion;
2941 const gchar *string = mdata->string;
2942 size_t string_len = mdata->string_len;
2944 const char *info_column;
2945 size_t info_column_len;
2946 match_result result = MR_NOTMATCHED;
2952 /* Load the frame's data. */
2953 if (!cf_read_record(cf, fdata)) {
2954 /* Attempt to get the packet failed. */
2958 /* Don't bother constructing the protocol tree */
2959 epan_dissect_init(&edt, cf->epan, FALSE, FALSE);
2960 /* Get the column information */
2961 epan_dissect_run(&edt, cf->cd_t, &cf->phdr, frame_tvbuff_new_buffer(fdata, &cf->buf), fdata,
2964 /* Find the Info column */
2965 for (colx = 0; colx < cf->cinfo.num_cols; colx++) {
2966 if (cf->cinfo.columns[colx].fmt_matx[COL_INFO]) {
2967 /* Found it. See if we match. */
2968 info_column = edt.pi.cinfo->columns[colx].col_data;
2969 info_column_len = strlen(info_column);
2970 for (i = 0; i < info_column_len; i++) {
2971 c_char = info_column[i];
2973 c_char = g_ascii_toupper(c_char);
2974 if (c_char == string[c_match]) {
2976 if (c_match == string_len) {
2977 result = MR_MATCHED;
2986 epan_dissect_cleanup(&edt);
2993 } cbs_t; /* "Counted byte string" */
2997 * The current match_* routines only support ASCII case insensitivity and don't
2998 * convert UTF-8 inputs to UTF-16 for matching.
3000 * We could modify them to use the GLib Unicode routines or the International
3001 * Components for Unicode library but it's not apparent that we could do so
3002 * without consuming a lot more CPU and memory or that searching would be
3003 * significantly better.
3007 cf_find_packet_data(capture_file *cf, const guint8 *string, size_t string_size,
3008 search_direction dir)
3013 info.data_len = string_size;
3015 /* String or hex search? */
3017 /* String search - what type of string? */
3018 switch (cf->scs_type) {
3020 case SCS_NARROW_AND_WIDE:
3021 return find_packet(cf, match_narrow_and_wide, &info, dir);
3024 return find_packet(cf, match_narrow, &info, dir);
3027 return find_packet(cf, match_wide, &info, dir);
3030 g_assert_not_reached();
3034 return find_packet(cf, match_binary, &info, dir);
3038 match_narrow_and_wide(capture_file *cf, frame_data *fdata, void *criterion)
3040 cbs_t *info = (cbs_t *)criterion;
3041 const guint8 *ascii_text = info->data;
3042 size_t textlen = info->data_len;
3043 match_result result;
3050 /* Load the frame's data. */
3051 if (!cf_read_record(cf, fdata)) {
3052 /* Attempt to get the packet failed. */
3056 result = MR_NOTMATCHED;
3057 buf_len = fdata->cap_len;
3058 pd = ws_buffer_start_ptr(&cf->buf);
3060 while (i < buf_len) {
3063 c_char = g_ascii_toupper(c_char);
3064 if (c_char != '\0') {
3065 if (c_char == ascii_text[c_match]) {
3067 if (c_match == textlen) {
3068 result = MR_MATCHED;
3069 cf->search_pos = i; /* Save the position of the last character
3070 for highlighting the field. */
3075 g_assert(i>=c_match);
3076 i -= (guint32)c_match;
3086 match_narrow(capture_file *cf, frame_data *fdata, void *criterion)
3089 cbs_t *info = (cbs_t *)criterion;
3090 const guint8 *ascii_text = info->data;
3091 size_t textlen = info->data_len;
3092 match_result result;
3098 /* Load the frame's data. */
3099 if (!cf_read_record(cf, fdata)) {
3100 /* Attempt to get the packet failed. */
3104 result = MR_NOTMATCHED;
3105 buf_len = fdata->cap_len;
3106 pd = ws_buffer_start_ptr(&cf->buf);
3108 while (i < buf_len) {
3111 c_char = g_ascii_toupper(c_char);
3112 if (c_char == ascii_text[c_match]) {
3114 if (c_match == textlen) {
3115 result = MR_MATCHED;
3116 cf->search_pos = i; /* Save the position of the last character
3117 for highlighting the field. */
3122 g_assert(i>=c_match);
3123 i -= (guint32)c_match;
3133 match_wide(capture_file *cf, frame_data *fdata, void *criterion)
3135 cbs_t *info = (cbs_t *)criterion;
3136 const guint8 *ascii_text = info->data;
3137 size_t textlen = info->data_len;
3138 match_result result;
3145 /* Load the frame's data. */
3146 if (!cf_read_record(cf, fdata)) {
3147 /* Attempt to get the packet failed. */
3151 result = MR_NOTMATCHED;
3152 buf_len = fdata->cap_len;
3153 pd = ws_buffer_start_ptr(&cf->buf);
3155 while (i < buf_len) {
3158 c_char = g_ascii_toupper(c_char);
3159 if (c_char == ascii_text[c_match]) {
3161 if (c_match == textlen) {
3162 result = MR_MATCHED;
3163 cf->search_pos = i; /* Save the position of the last character
3164 for highlighting the field. */
3170 g_assert(i>=(c_match*2));
3171 i -= (guint32)c_match*2;
3180 match_binary(capture_file *cf, frame_data *fdata, void *criterion)
3182 cbs_t *info = (cbs_t *)criterion;
3183 const guint8 *binary_data = info->data;
3184 size_t datalen = info->data_len;
3185 match_result result;
3191 /* Load the frame's data. */
3192 if (!cf_read_record(cf, fdata)) {
3193 /* Attempt to get the packet failed. */
3197 result = MR_NOTMATCHED;
3198 buf_len = fdata->cap_len;
3199 pd = ws_buffer_start_ptr(&cf->buf);
3201 while (i < buf_len) {
3202 if (pd[i] == binary_data[c_match]) {
3204 if (c_match == datalen) {
3205 result = MR_MATCHED;
3206 cf->search_pos = i; /* Save the position of the last character
3207 for highlighting the field. */
3212 g_assert(i>=c_match);
3213 i -= (guint32)c_match;
3222 cf_find_packet_dfilter(capture_file *cf, dfilter_t *sfcode,
3223 search_direction dir)
3225 return find_packet(cf, match_dfilter, sfcode, dir);
3229 cf_find_packet_dfilter_string(capture_file *cf, const char *filter,
3230 search_direction dir)
3235 if (!dfilter_compile(filter, &sfcode, NULL)) {
3237 * XXX - this shouldn't happen, as the filter string is machine
3242 if (sfcode == NULL) {
3244 * XXX - this shouldn't happen, as the filter string is machine
3249 result = find_packet(cf, match_dfilter, sfcode, dir);
3250 dfilter_free(sfcode);
3255 match_dfilter(capture_file *cf, frame_data *fdata, void *criterion)
3257 dfilter_t *sfcode = (dfilter_t *)criterion;
3259 match_result result;
3261 /* Load the frame's data. */
3262 if (!cf_read_record(cf, fdata)) {
3263 /* Attempt to get the packet failed. */
3267 epan_dissect_init(&edt, cf->epan, TRUE, FALSE);
3268 epan_dissect_prime_dfilter(&edt, sfcode);
3269 epan_dissect_run(&edt, cf->cd_t, &cf->phdr, frame_tvbuff_new_buffer(fdata, &cf->buf), fdata, NULL);
3270 result = dfilter_apply_edt(sfcode, &edt) ? MR_MATCHED : MR_NOTMATCHED;
3271 epan_dissect_cleanup(&edt);
3276 cf_find_packet_marked(capture_file *cf, search_direction dir)
3278 return find_packet(cf, match_marked, NULL, dir);
3282 match_marked(capture_file *cf _U_, frame_data *fdata, void *criterion _U_)
3284 return fdata->flags.marked ? MR_MATCHED : MR_NOTMATCHED;
3288 cf_find_packet_time_reference(capture_file *cf, search_direction dir)
3290 return find_packet(cf, match_time_reference, NULL, dir);
3294 match_time_reference(capture_file *cf _U_, frame_data *fdata, void *criterion _U_)
3296 return fdata->flags.ref_time ? MR_MATCHED : MR_NOTMATCHED;
3300 find_packet(capture_file *cf,
3301 match_result (*match_function)(capture_file *, frame_data *, void *),
3302 void *criterion, search_direction dir)
3304 frame_data *start_fd;
3307 frame_data *new_fd = NULL;
3308 progdlg_t *progbar = NULL;
3312 GTimeVal start_time;
3313 gchar status_str[100];
3314 int progbar_nextstep;
3315 int progbar_quantum;
3317 match_result result;
3319 start_fd = cf->current_frame;
3320 if (start_fd != NULL) {
3321 /* Iterate through the list of packets, starting at the packet we've
3322 picked, calling a routine to run the filter on the packet, see if
3323 it matches, and stop if so. */
3325 framenum = start_fd->num;
3327 /* Update the progress bar when it gets to this value. */
3328 progbar_nextstep = 0;
3329 /* When we reach the value that triggers a progress bar update,
3330 bump that value by this amount. */
3331 progbar_quantum = cf->count/N_PROGBAR_UPDATES;
3332 /* Progress so far. */
3335 cf->stop_flag = FALSE;
3336 g_get_current_time(&start_time);
3338 title = cf->sfilter?cf->sfilter:"";
3340 /* Create the progress bar if necessary.
3341 We check on every iteration of the loop, so that it takes no
3342 longer than the standard time to create it (otherwise, for a
3343 large file, we might take considerably longer than that standard
3344 time in order to get to the next progress bar step). */
3345 if (progbar == NULL)
3346 progbar = delayed_create_progress_dlg(cf->window, "Searching", title,
3347 FALSE, &cf->stop_flag, &start_time, progbar_val);
3349 /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
3350 when we update it, we have to run the GTK+ main loop to get it
3351 to repaint what's pending, and doing so may involve an "ioctl()"
3352 to see if there's any pending input from an X server, and doing
3353 that for every packet can be costly, especially on a big file. */
3354 if (count >= progbar_nextstep) {
3355 /* let's not divide by zero. I should never be started
3356 * with count == 0, so let's assert that
3358 g_assert(cf->count > 0);
3360 progbar_val = (gfloat) count / cf->count;
3362 if (progbar != NULL) {
3363 g_snprintf(status_str, sizeof(status_str),
3364 "%4u of %u packets", count, cf->count);
3365 update_progress_dlg(progbar, progbar_val, status_str);
3368 progbar_nextstep += progbar_quantum;
3371 if (cf->stop_flag) {
3372 /* Well, the user decided to abort the search. Go back to the
3373 frame where we started. */
3378 /* Go past the current frame. */
3379 if (dir == SD_BACKWARD) {
3380 /* Go on to the previous frame. */
3381 if (framenum == 1) {
3383 * XXX - other apps have a bit more of a detailed message
3384 * for this, and instead of offering "OK" and "Cancel",
3385 * they offer things such as "Continue" and "Cancel";
3386 * we need an API for popping up alert boxes with
3387 * {Verb} and "Cancel".
3390 if (prefs.gui_find_wrap)
3392 statusbar_push_temporary_msg("Search reached the beginning. Continuing at end.");
3393 framenum = cf->count; /* wrap around */
3397 statusbar_push_temporary_msg("Search reached the beginning.");
3398 framenum = start_fd->num; /* stay on previous packet */
3403 /* Go on to the next frame. */
3404 if (framenum == cf->count) {
3405 if (prefs.gui_find_wrap)
3407 statusbar_push_temporary_msg("Search reached the end. Continuing at beginning.");
3408 framenum = 1; /* wrap around */
3412 statusbar_push_temporary_msg("Search reached the end.");
3413 framenum = start_fd->num; /* stay on previous packet */
3418 fdata = frame_data_sequence_find(cf->frames, framenum);
3422 /* Is this packet in the display? */
3423 if (fdata->flags.passed_dfilter) {
3424 /* Yes. Does it match the search criterion? */
3425 result = (*match_function)(cf, fdata, criterion);
3426 if (result == MR_ERROR) {
3427 /* Error; our caller has reported the error. Go back to the frame
3428 where we started. */
3431 } else if (result == MR_MATCHED) {
3432 /* Yes. Go to the new frame. */
3438 if (fdata == start_fd) {
3439 /* We're back to the frame we were on originally, and that frame
3440 doesn't match the search filter. The search failed. */
3445 /* We're done scanning the packets; destroy the progress bar if it
3447 if (progbar != NULL)
3448 destroy_progress_dlg(progbar);
3451 if (new_fd != NULL) {
3452 /* Find and select */
3453 cf->search_in_progress = TRUE;
3454 found = packet_list_select_row_from_data(new_fd);
3455 cf->search_in_progress = FALSE;
3456 cf->search_pos = 0; /* Reset the position */
3458 /* We didn't find a row corresponding to this frame.
3459 This means that the frame isn't being displayed currently,
3460 so we can't select it. */
3461 simple_message_box(ESD_TYPE_INFO, NULL,
3462 "The capture file is probably not fully dissected.",
3463 "End of capture exceeded.");
3466 return TRUE; /* success */
3468 return FALSE; /* failure */
3472 cf_goto_frame(capture_file *cf, guint fnumber)
3476 fdata = frame_data_sequence_find(cf->frames, fnumber);
3478 if (fdata == NULL) {
3479 /* we didn't find a packet with that packet number */
3480 statusbar_push_temporary_msg("There is no packet number %u.", fnumber);
3481 return FALSE; /* we failed to go to that packet */
3483 if (!fdata->flags.passed_dfilter) {
3484 /* that packet currently isn't displayed */
3485 /* XXX - add it to the set of displayed packets? */
3486 statusbar_push_temporary_msg("Packet number %u isn't displayed.", fnumber);
3487 return FALSE; /* we failed to go to that packet */
3490 if (!packet_list_select_row_from_data(fdata)) {
3491 /* We didn't find a row corresponding to this frame.
3492 This means that the frame isn't being displayed currently,
3493 so we can't select it. */
3494 simple_message_box(ESD_TYPE_INFO, NULL,
3495 "The capture file is probably not fully dissected.",
3496 "End of capture exceeded.");
3499 return TRUE; /* we got to that packet */
3503 cf_goto_top_frame(void)
3505 /* Find and select */
3506 packet_list_select_first_row();
3507 return TRUE; /* we got to that packet */
3511 cf_goto_bottom_frame(void)
3513 /* Find and select */
3514 packet_list_select_last_row();
3515 return TRUE; /* we got to that packet */
3519 * Go to frame specified by currently selected protocol tree item.
3522 cf_goto_framenum(capture_file *cf)
3524 header_field_info *hfinfo;
3527 if (cf->finfo_selected) {
3528 hfinfo = cf->finfo_selected->hfinfo;
3530 if (hfinfo->type == FT_FRAMENUM) {
3531 framenum = fvalue_get_uinteger(&cf->finfo_selected->value);
3533 return cf_goto_frame(cf, framenum);
3540 /* Select the packet on a given row. */
3542 cf_select_packet(capture_file *cf, int row)
3544 epan_dissect_t *old_edt;
3547 /* Get the frame data struct pointer for this frame */
3548 fdata = packet_list_get_row_data(row);
3550 if (fdata == NULL) {
3551 /* XXX - if a GtkCList's selection mode is GTK_SELECTION_BROWSE, when
3552 the first entry is added to it by "real_insert_row()", that row
3553 is selected (see "real_insert_row()", in "ui/gtk/gtkclist.c", in both
3554 our version and the vanilla GTK+ version).
3556 This means that a "select-row" signal is emitted; this causes
3557 "packet_list_select_cb()" to be called, which causes "cf_select_packet()"
3560 "cf_select_packet()" fetches, above, the data associated with the
3561 row that was selected; however, as "gtk_clist_append()", which
3562 called "real_insert_row()", hasn't yet returned, we haven't yet
3563 associated any data with that row, so we get back a null pointer.
3565 We can't assume that there's only one frame in the frame list,
3566 either, as we may be filtering the display.
3568 We therefore assume that, if "row" is 0, i.e. the first row
3569 is being selected, and "cf->first_displayed" equals
3570 "cf->last_displayed", i.e. there's only one frame being
3571 displayed, that frame is the frame we want.
3573 This means we have to set "cf->first_displayed" and
3574 "cf->last_displayed" before adding the row to the
3575 GtkCList; see the comment in "add_packet_to_packet_list()". */
3577 if (row == 0 && cf->first_displayed == cf->last_displayed)
3578 fdata = frame_data_sequence_find(cf->frames, cf->first_displayed);
3581 /* If fdata _still_ isn't set simply give up. */
3582 if (fdata == NULL) {
3586 /* Get the data in that frame. */
3587 if (!cf_read_record (cf, fdata)) {
3591 /* Record that this frame is the current frame. */
3592 cf->current_frame = fdata;
3593 cf->current_row = row;
3596 /* Create the logical protocol tree. */
3597 /* We don't need the columns here. */
3598 cf->edt = epan_dissect_new(cf->epan, TRUE, TRUE);
3600 tap_build_interesting(cf->edt);
3601 epan_dissect_run(cf->edt, cf->cd_t, &cf->phdr, frame_tvbuff_new_buffer(cf->current_frame, &cf->buf),
3602 cf->current_frame, NULL);
3604 dfilter_macro_build_ftv_cache(cf->edt->tree);
3606 cf_callback_invoke(cf_cb_packet_selected, cf);
3608 if (old_edt != NULL)
3609 epan_dissect_free(old_edt);
3613 /* Unselect the selected packet, if any. */
3615 cf_unselect_packet(capture_file *cf)
3617 epan_dissect_t *old_edt = cf->edt;
3621 /* No packet is selected. */
3622 cf->current_frame = NULL;
3623 cf->current_row = 0;
3625 cf_callback_invoke(cf_cb_packet_unselected, cf);
3627 /* No protocol tree means no selected field. */
3628 cf_unselect_field(cf);
3630 /* Destroy the epan_dissect_t for the unselected packet. */
3631 if (old_edt != NULL)
3632 epan_dissect_free(old_edt);
3635 /* Unset the selected protocol tree field, if any. */
3637 cf_unselect_field(capture_file *cf)
3639 cf->finfo_selected = NULL;
3641 cf_callback_invoke(cf_cb_field_unselected, cf);
3645 * Mark a particular frame.
3648 cf_mark_frame(capture_file *cf, frame_data *frame)
3650 if (! frame->flags.marked) {
3651 frame->flags.marked = TRUE;
3652 if (cf->count > cf->marked_count)
3658 * Unmark a particular frame.
3661 cf_unmark_frame(capture_file *cf, frame_data *frame)
3663 if (frame->flags.marked) {
3664 frame->flags.marked = FALSE;
3665 if (cf->marked_count > 0)
3671 * Ignore a particular frame.
3674 cf_ignore_frame(capture_file *cf, frame_data *frame)
3676 if (! frame->flags.ignored) {
3677 frame->flags.ignored = TRUE;
3678 if (cf->count > cf->ignored_count)
3679 cf->ignored_count++;
3684 * Un-ignore a particular frame.
3687 cf_unignore_frame(capture_file *cf, frame_data *frame)
3689 if (frame->flags.ignored) {
3690 frame->flags.ignored = FALSE;
3691 if (cf->ignored_count > 0)
3692 cf->ignored_count--;
3697 * Read the comment in SHB block
3701 cf_read_shb_comment(capture_file *cf)
3703 /* Get info from SHB */
3704 return wtap_file_get_shb_comment(cf->wth);
3708 cf_update_capture_comment(capture_file *cf, gchar *comment)
3710 const gchar *shb_comment;
3712 /* Get info from SHB */
3713 shb_comment = wtap_file_get_shb_comment(cf->wth);
3715 /* See if the comment has changed or not */
3717 if (strcmp(shb_comment, comment) == 0) {
3723 /* The comment has changed, let's update it */
3724 wtap_write_shb_comment(cf->wth, comment);
3725 /* Mark the file as having unsaved changes */
3726 cf->unsaved_changes = TRUE;
3730 cf_get_user_packet_comment(capture_file *cf, const frame_data *fd)
3732 if (cf->frames_user_comments)
3733 return (const char *)g_tree_lookup(cf->frames_user_comments, fd);
3740 cf_get_comment(capture_file *cf, const frame_data *fd)
3744 /* fetch user comment */
3745 if (fd->flags.has_user_comment)
3746 return g_strdup(cf_get_user_packet_comment(cf, fd));
3748 /* fetch phdr comment */
3749 if (fd->flags.has_phdr_comment) {
3750 struct wtap_pkthdr phdr; /* Packet header */
3751 Buffer buf; /* Packet data */
3753 wtap_phdr_init(&phdr);
3754 ws_buffer_init(&buf, 1500);
3756 if (!cf_read_record_r(cf, fd, &phdr, &buf))
3757 { /* XXX, what we can do here? */ }
3759 comment = phdr.opt_comment;
3760 wtap_phdr_cleanup(&phdr);
3761 ws_buffer_free(&buf);
3768 frame_cmp(gconstpointer a, gconstpointer b, gpointer user_data _U_)
3770 const frame_data *fdata1 = (const frame_data *) a;
3771 const frame_data *fdata2 = (const frame_data *) b;
3773 return (fdata1->num < fdata2->num) ? -1 :
3774 (fdata1->num > fdata2->num) ? 1 :
3779 cf_set_user_packet_comment(capture_file *cf, frame_data *fd, const gchar *new_comment)
3781 char *pkt_comment = cf_get_comment(cf, fd);
3783 /* Check if the comment has changed */
3784 if (!g_strcmp0(pkt_comment, new_comment)) {
3785 g_free(pkt_comment);
3788 g_free(pkt_comment);
3791 cf->packet_comment_count--;
3794 cf->packet_comment_count++;
3796 fd->flags.has_user_comment = TRUE;
3798 if (!cf->frames_user_comments)
3799 cf->frames_user_comments = g_tree_new_full(frame_cmp, NULL, NULL, g_free);
3801 /* insert new packet comment */
3802 g_tree_replace(cf->frames_user_comments, fd, g_strdup(new_comment));
3804 expert_update_comment_count(cf->packet_comment_count);
3806 /* OK, we have unsaved changes. */
3807 cf->unsaved_changes = TRUE;
3812 * What types of comments does this capture file have?
3815 cf_comment_types(capture_file *cf)
3817 guint32 comment_types = 0;
3819 if (cf_read_shb_comment(cf) != NULL)
3820 comment_types |= WTAP_COMMENT_PER_SECTION;
3821 if (cf->packet_comment_count != 0)
3822 comment_types |= WTAP_COMMENT_PER_PACKET;
3823 return comment_types;
3826 #ifdef WANT_PACKET_EDITOR
3828 g_direct_compare_func(gconstpointer a, gconstpointer b, gpointer user_data _U_)
3839 modified_frame_data_free(gpointer data)
3841 modified_frame_data *mfd = (modified_frame_data *)data;
3848 * Give a frame new, edited data.
3851 cf_set_frame_edited(capture_file *cf, frame_data *fd,
3852 struct wtap_pkthdr *phdr, guint8 *pd)
3854 modified_frame_data *mfd = (modified_frame_data *)g_malloc(sizeof(modified_frame_data));
3859 if (cf->edited_frames == NULL)
3860 cf->edited_frames = g_tree_new_full(g_direct_compare_func, NULL, NULL,
3861 modified_frame_data_free);
3862 g_tree_insert(cf->edited_frames, GINT_TO_POINTER(fd->num), mfd);
3865 /* Mark the file as having unsaved changes */
3866 cf->unsaved_changes = TRUE;
3874 } save_callback_args_t;
3877 * Save a capture to a file, in a particular format, saving either
3878 * all packets, all currently-displayed packets, or all marked packets.
3880 * Returns TRUE if it succeeds, FALSE otherwise; if it fails, it pops
3881 * up a message box for the failure.
3884 save_record(capture_file *cf, frame_data *fdata,
3885 struct wtap_pkthdr *phdr, const guint8 *pd,
3888 save_callback_args_t *args = (save_callback_args_t *)argsp;
3889 struct wtap_pkthdr hdr;
3892 gchar *display_basename;
3893 const char *pkt_comment;
3895 if (fdata->flags.has_user_comment)
3896 pkt_comment = cf_get_user_packet_comment(cf, fdata);
3898 pkt_comment = phdr->opt_comment;
3900 /* init the wtap header for saving */
3901 /* TODO: reuse phdr */
3902 /* XXX - these are the only flags that correspond to data that we have
3903 in the frame_data structure and that matter on a per-packet basis.
3905 For WTAP_HAS_CAP_LEN, either the file format has separate "captured"
3906 and "on the wire" lengths, or it doesn't.
3908 For WTAP_HAS_DROP_COUNT, Wiretap doesn't actually supply the value
3911 For WTAP_HAS_PACK_FLAGS, we currently don't save the FCS length
3912 from the packet flags. */
3913 hdr.rec_type = phdr->rec_type;
3914 hdr.presence_flags = 0;
3915 if (fdata->flags.has_ts)
3916 hdr.presence_flags |= WTAP_HAS_TS;
3917 if (phdr->presence_flags & WTAP_HAS_INTERFACE_ID)
3918 hdr.presence_flags |= WTAP_HAS_INTERFACE_ID;
3919 if (phdr->presence_flags & WTAP_HAS_PACK_FLAGS)
3920 hdr.presence_flags |= WTAP_HAS_PACK_FLAGS;
3921 hdr.ts.secs = fdata->abs_ts.secs;
3922 hdr.ts.nsecs = fdata->abs_ts.nsecs;
3923 hdr.caplen = phdr->caplen;
3924 hdr.len = phdr->len;
3925 hdr.pkt_encap = fdata->lnk_t;
3927 hdr.interface_id = phdr->interface_id; /* identifier of the interface. */
3929 hdr.pack_flags = phdr->pack_flags;
3930 hdr.opt_comment = g_strdup(pkt_comment);
3933 hdr.pseudo_header = phdr->pseudo_header;
3936 hdr.pack_flags = /* XXX - 0 for now (any value for "we don't have it"?) */
3938 /* and save the packet */
3939 if (!wtap_dump(args->pdh, &hdr, pd, &err, &err_info)) {
3941 /* Wiretap error. */
3944 case WTAP_ERR_UNWRITABLE_ENCAP:
3946 * This is a problem with the particular frame we're writing and
3947 * the file type and subtype we're writing; note that, and report
3948 * the frame number and file type/subtype.
3950 simple_error_message_box(
3951 "Frame %u has a network type that can't be saved in a \"%s\" file.",
3952 fdata->num, wtap_file_type_subtype_string(args->file_type));
3955 case WTAP_ERR_PACKET_TOO_LARGE:
3957 * This is a problem with the particular frame we're writing and
3958 * the file type and subtype we're writing; note that, and report
3959 * the frame number and file type/subtype.
3961 simple_error_message_box(
3962 "Frame %u is larger than Wireshark supports in a \"%s\" file.",
3963 fdata->num, wtap_file_type_subtype_string(args->file_type));
3966 case WTAP_ERR_UNWRITABLE_REC_TYPE:
3968 * This is a problem with the particular record we're writing and
3969 * the file type and subtype we're writing; note that, and report
3970 * the record number and file type/subtype.
3972 simple_error_message_box(
3973 "Record %u has a record type that can't be saved in a \"%s\" file.",
3974 fdata->num, wtap_file_type_subtype_string(args->file_type));
3977 case WTAP_ERR_UNWRITABLE_REC_DATA:
3979 * This is a problem with the particular frame we're writing and
3980 * the file type and subtype we're writing; note that, and report
3981 * the frame number and file type/subtype.
3983 simple_error_message_box(
3984 "Record %u has data that can't be saved in a \"%s\" file.\n(%s)",
3985 fdata->num, wtap_file_type_subtype_string(args->file_type),
3986 err_info != NULL ? err_info : "no information supplied");
3991 display_basename = g_filename_display_basename(args->fname);
3992 simple_error_message_box(
3993 "An error occurred while writing to the file \"%s\": %s.",
3994 display_basename, wtap_strerror(err));
3995 g_free(display_basename);
4000 write_failure_alert_box(args->fname, err);
4005 g_free(hdr.opt_comment);
4010 * Can this capture file be written out in any format using Wiretap
4011 * rather than by copying the raw data?
4014 cf_can_write_with_wiretap(capture_file *cf)
4016 /* We don't care whether we support the comments in this file or not;
4017 if we can't, we'll offer the user the option of discarding the
4019 return wtap_dump_can_write(cf->linktypes, 0);
4023 * Should we let the user do a save?
4027 * the file has unsaved changes, and we can save it in some
4028 * format through Wiretap
4032 * the file is a temporary file and has no unsaved changes (so
4033 * that "saving" it just means copying it).
4035 * XXX - we shouldn't allow files to be edited if they can't be saved,
4036 * so cf->unsaved_changes should be true only if the file can be saved.
4038 * We don't care whether we support the comments in this file or not;
4039 * if we can't, we'll offer the user the option of discarding the
4043 cf_can_save(capture_file *cf)
4045 if (cf->unsaved_changes && wtap_dump_can_write(cf->linktypes, 0)) {
4046 /* Saved changes, and we can write it out with Wiretap. */
4050 if (cf->is_tempfile && !cf->unsaved_changes) {
4052 * Temporary file with no unsaved changes, so we can just do a
4058 /* Nothing to save. */
4063 * Should we let the user do a "save as"?
4067 * we can save it in some format through Wiretap
4071 * the file is a temporary file and has no unsaved changes (so
4072 * that "saving" it just means copying it).
4074 * XXX - we shouldn't allow files to be edited if they can't be saved,
4075 * so cf->unsaved_changes should be true only if the file can be saved.
4077 * We don't care whether we support the comments in this file or not;
4078 * if we can't, we'll offer the user the option of discarding the
4082 cf_can_save_as(capture_file *cf)
4084 if (wtap_dump_can_write(cf->linktypes, 0)) {
4085 /* We can write it out with Wiretap. */
4089 if (cf->is_tempfile && !cf->unsaved_changes) {
4091 * Temporary file with no unsaved changes, so we can just do a
4097 /* Nothing to save. */
4102 * Does this file have unsaved data?
4105 cf_has_unsaved_data(capture_file *cf)
4108 * If this is a temporary file, or a file with unsaved changes, it
4111 return (cf->is_tempfile && cf->count>0) || cf->unsaved_changes;
4115 * Quick scan to find packet offsets.
4117 static cf_read_status_t
4118 rescan_file(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
4120 const struct wtap_pkthdr *phdr;
4124 progdlg_t *progbar = NULL;
4127 GTimeVal start_time;
4128 gchar status_str[100];
4129 gint64 progbar_nextstep;
4130 gint64 progbar_quantum;
4135 int displayed_once = 0;
4138 /* Close the old handle. */
4139 wtap_close(cf->wth);
4141 /* Open the new file. */
4142 /* XXX: this will go through all open_routines for a matching one. But right
4143 now rescan_file() is only used when a file is being saved to a different
4144 format than the original, and the user is not given a choice of which
4145 reader to use (only which format to save it in), so doing this makes
4147 cf->wth = wtap_open_offline(fname, WTAP_TYPE_AUTO, err, &err_info, TRUE);
4148 if (cf->wth == NULL) {
4149 cf_open_failure_alert_box(fname, *err, err_info, FALSE, 0);
4150 return CF_READ_ERROR;
4153 /* We're scanning a file whose contents should be the same as what
4154 we had before, so we don't discard dissection state etc.. */
4157 /* Set the file name because we need it to set the follow stream filter.
4158 XXX - is that still true? We need it for other reasons, though,
4160 cf->filename = g_strdup(fname);
4162 /* Indicate whether it's a permanent or temporary file. */
4163 cf->is_tempfile = is_tempfile;
4165 /* No user changes yet. */
4166 cf->unsaved_changes = FALSE;
4168 cf->cd_t = wtap_file_type_subtype(cf->wth);
4169 cf->linktypes = g_array_sized_new(FALSE, FALSE, (guint) sizeof(int), 1);
4171 cf->snap = wtap_snapshot_length(cf->wth);
4172 if (cf->snap == 0) {
4173 /* Snapshot length not known. */
4174 cf->has_snap = FALSE;
4175 cf->snap = WTAP_MAX_PACKET_SIZE;
4177 cf->has_snap = TRUE;
4179 name_ptr = g_filename_display_basename(cf->filename);
4181 cf_callback_invoke(cf_cb_file_rescan_started, cf);
4183 /* Record whether the file is compressed.
4184 XXX - do we know this at open time? */
4185 cf->iscompressed = wtap_iscompressed(cf->wth);
4187 /* Find the size of the file. */
4188 size = wtap_file_size(cf->wth, NULL);
4190 /* Update the progress bar when it gets to this value. */
4191 progbar_nextstep = 0;
4192 /* When we reach the value that triggers a progress bar update,
4193 bump that value by this amount. */
4195 progbar_quantum = size/N_PROGBAR_UPDATES;
4196 if (progbar_quantum < MIN_QUANTUM)
4197 progbar_quantum = MIN_QUANTUM;
4199 progbar_quantum = 0;
4201 cf->stop_flag = FALSE;
4202 g_get_current_time(&start_time);
4205 phdr = wtap_phdr(cf->wth);
4206 while ((wtap_read(cf->wth, err, &err_info, &data_offset))) {
4208 fdata = frame_data_sequence_find(cf->frames, framenum);
4209 fdata->file_off = data_offset;
4212 cf->f_datalen = wtap_read_so_far(cf->wth);
4214 /* Create the progress bar if necessary.
4215 * Check whether it should be created or not every MIN_NUMBER_OF_PACKET
4217 if ((progbar == NULL) && !(count % MIN_NUMBER_OF_PACKET)) {
4218 progbar_val = calc_progbar_val(cf, size, cf->f_datalen, status_str, sizeof(status_str));
4219 progbar = delayed_create_progress_dlg(cf->window, "Rescanning", name_ptr,
4220 TRUE, &cf->stop_flag, &start_time, progbar_val);
4223 /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
4224 when we update it, we have to run the GTK+ main loop to get it
4225 to repaint what's pending, and doing so may involve an "ioctl()"
4226 to see if there's any pending input from an X server, and doing
4227 that for every packet can be costly, especially on a big file. */
4228 if (cf->f_datalen >= progbar_nextstep) {
4229 if (progbar != NULL) {
4230 progbar_val = calc_progbar_val(cf, size, cf->f_datalen, status_str, sizeof(status_str));
4231 /* update the packet bar content on the first run or frequently on very large files */
4233 if (progbar_quantum > 500000 || displayed_once == 0) {
4234 if ((auto_scroll_live || displayed_once == 0 || cf->displayed_count < 1000) && cf->count != 0) {
4236 packets_bar_update();
4239 #endif /* HAVE_LIBPCAP */
4240 update_progress_dlg(progbar, progbar_val, status_str);
4242 progbar_nextstep += progbar_quantum;
4246 if (cf->stop_flag) {
4247 /* Well, the user decided to abort the rescan. Sadly, as this
4248 isn't a reread, recovering is difficult, so we'll just
4249 close the current capture. */
4253 /* Add this packet's link-layer encapsulation type to cf->linktypes, if
4254 it's not already there.
4255 XXX - yes, this is O(N), so if every packet had a different
4256 link-layer encapsulation type, it'd be O(N^2) to read the file, but
4257 there are probably going to be a small number of encapsulation types
4259 cf_add_encapsulation_type(cf, phdr->pkt_encap);
4262 /* Free the display name */
4265 /* We're done reading the file; destroy the progress bar if it was created. */
4266 if (progbar != NULL)
4267 destroy_progress_dlg(progbar);
4269 /* We're done reading sequentially through the file. */
4270 cf->state = FILE_READ_DONE;
4272 /* Close the sequential I/O side, to free up memory it requires. */
4273 wtap_sequential_close(cf->wth);
4275 /* compute the time it took to load the file */
4276 compute_elapsed(cf, &start_time);
4278 /* Set the file encapsulation type now; we don't know what it is until
4279 we've looked at all the packets, as we don't know until then whether
4280 there's more than one type (and thus whether it's
4281 WTAP_ENCAP_PER_PACKET). */
4282 cf->lnk_t = wtap_file_encap(cf->wth);
4284 cf_callback_invoke(cf_cb_file_rescan_finished, cf);
4286 if (cf->stop_flag) {
4287 /* Our caller will give up at this point. */
4288 return CF_READ_ABORTED;
4292 /* Put up a message box noting that the read failed somewhere along
4293 the line. Don't throw out the stuff we managed to read, though,
4297 case WTAP_ERR_UNSUPPORTED:
4298 simple_error_message_box(
4299 "The capture file contains record data that Wireshark doesn't support.\n(%s)",
4300 err_info != NULL ? err_info : "no information supplied");
4304 case WTAP_ERR_SHORT_READ:
4305 simple_error_message_box(
4306 "The capture file appears to have been cut short"
4307 " in the middle of a packet.");
4310 case WTAP_ERR_BAD_FILE:
4311 simple_error_message_box(
4312 "The capture file appears to be damaged or corrupt.\n(%s)",
4313 err_info != NULL ? err_info : "no information supplied");
4317 case WTAP_ERR_DECOMPRESS:
4318 simple_error_message_box(
4319 "The compressed capture file appears to be damaged or corrupt.\n"
4321 err_info != NULL ? err_info : "no information supplied");
4326 simple_error_message_box(
4327 "An error occurred while reading the"
4328 " capture file: %s.", wtap_strerror(*err));
4331 return CF_READ_ERROR;
4337 cf_save_records(capture_file *cf, const char *fname, guint save_format,
4338 gboolean compressed, gboolean discard_comments,
4339 gboolean dont_reopen)
4342 gchar *fname_new = NULL;
4345 addrinfo_lists_t *addr_lists;
4349 gchar *display_basename;
4356 save_callback_args_t callback_args;
4358 cf_callback_invoke(cf_cb_file_save_started, (gpointer)fname);
4360 addr_lists = get_addrinfo_list();
4362 if (save_format == cf->cd_t && compressed == cf->iscompressed
4363 && !discard_comments && !cf->unsaved_changes
4364 && !(addr_lists && wtap_dump_has_name_resolution(save_format))) {
4365 /* We're saving in the format it's already in, and we're
4366 not discarding comments, and there are no changes we have
4367 in memory that aren't saved to the file, and we have no name
4368 resolution blocks to write, so we can just move or copy the raw data. */
4370 if (cf->is_tempfile) {
4371 /* The file being saved is a temporary file from a live
4372 capture, so it doesn't need to stay around under that name;
4373 first, try renaming the capture buffer file to the new name.
4374 This acts as a "safe save", in that, if the file already
4375 exists, the existing file will be removed only if the rename
4378 Sadly, on Windows, as we have the current capture file
4379 open, even MoveFileEx() with MOVEFILE_REPLACE_EXISTING
4380 (to cause the rename to remove an existing target), as
4381 done by ws_stdio_rename() (ws_rename() is #defined to
4382 be ws_stdio_rename() on Windows) will fail.
4384 According to the MSDN documentation for CreateFile(), if,
4385 when we open a capture file, we were to directly do a CreateFile(),
4386 opening with FILE_SHARE_DELETE|FILE_SHARE_READ, and then
4387 convert it to a file descriptor with _open_osfhandle(),
4388 that would allow the file to be renamed out from under us.
4390 However, that doesn't work in practice. Perhaps the problem
4391 is that the process doing the rename is the process that
4392 has the file open. */
4394 if (ws_rename(cf->filename, fname) == 0) {
4395 /* That succeeded - there's no need to copy the source file. */
4396 how_to_save = SAVE_WITH_MOVE;
4398 if (errno == EXDEV) {
4399 /* They're on different file systems, so we have to copy the
4401 how_to_save = SAVE_WITH_COPY;
4403 /* The rename failed, but not because they're on different
4404 file systems - put up an error message. (Or should we
4405 just punt and try to copy? The only reason why I'd
4406 expect the rename to fail and the copy to succeed would
4407 be if we didn't have permission to remove the file from
4408 the temporary directory, and that might be fixable - but
4409 is it worth requiring the user to go off and fix it?) */
4410 cf_rename_failure_alert_box(fname, errno);
4415 how_to_save = SAVE_WITH_COPY;
4418 /* It's a permanent file, so we should copy it, and not remove the
4420 how_to_save = SAVE_WITH_COPY;
4423 if (how_to_save == SAVE_WITH_COPY) {
4424 /* Copy the file, if we haven't moved it. If we're overwriting
4425 an existing file, we do it with a "safe save", by writing
4426 to a new file and, if the write succeeds, renaming the
4427 new file on top of the old file. */
4428 if (file_exists(fname)) {
4429 fname_new = g_strdup_printf("%s~", fname);
4430 if (!copy_file_binary_mode(cf->filename, fname_new))
4433 if (!copy_file_binary_mode(cf->filename, fname))
4438 /* Either we're saving in a different format or we're saving changes,
4439 such as added, modified, or removed comments, that haven't yet
4440 been written to the underlying file; we can't do that by copying
4441 or moving the capture file, we have to do it by writing the packets
4444 wtapng_section_t *shb_hdr = NULL;
4445 wtapng_iface_descriptions_t *idb_inf = NULL;
4446 wtapng_name_res_t *nrb_hdr = NULL;
4449 /* XXX: what free's this shb_hdr? */
4450 shb_hdr = wtap_file_get_shb_for_new_file(cf->wth);
4451 idb_inf = wtap_file_get_idb_info(cf->wth);
4452 nrb_hdr = wtap_file_get_nrb_for_new_file(cf->wth);
4454 /* Determine what file encapsulation type we should use. */
4455 encap = wtap_dump_file_encap_type(cf->linktypes);
4457 if (file_exists(fname)) {
4458 /* We're overwriting an existing file; write out to a new file,
4459 and, if that succeeds, rename the new file on top of the
4460 old file. That makes this a "safe save", so that we don't
4461 lose the old file if we have a problem writing out the new
4462 file. (If the existing file is the current capture file,
4463 we *HAVE* to do that, otherwise we're overwriting the file
4464 from which we're reading the packets that we're writing!) */
4465 fname_new = g_strdup_printf("%s~", fname);
4466 pdh = wtap_dump_open_ng(fname_new, save_format, encap, cf->snap,
4467 compressed, shb_hdr, idb_inf, nrb_hdr, &err);
4469 pdh = wtap_dump_open_ng(fname, save_format, encap, cf->snap,
4470 compressed, shb_hdr, idb_inf, nrb_hdr, &err);
4476 cf_open_failure_alert_box(fname, err, NULL, TRUE, save_format);
4480 /* Add address resolution */
4481 wtap_dump_set_addrinfo_list(pdh, addr_lists);
4483 /* Iterate through the list of packets, processing all the packets. */
4484 callback_args.pdh = pdh;
4485 callback_args.fname = fname;
4486 callback_args.file_type = save_format;
4487 switch (process_specified_records(cf, NULL, "Saving", "packets",
4488 TRUE, save_record, &callback_args)) {
4491 /* Completed successfully. */
4495 /* The user decided to abort the saving.
4496 If we're writing to a temporary file, remove it.
4497 XXX - should we do so even if we're not writing to a
4499 wtap_dump_close(pdh, &err);
4500 if (fname_new != NULL)
4501 ws_unlink(fname_new);
4502 cf_callback_invoke(cf_cb_file_save_stopped, NULL);
4503 return CF_WRITE_ABORTED;
4506 /* Error while saving.
4507 If we're writing to a temporary file, remove it. */
4508 if (fname_new != NULL)
4509 ws_unlink(fname_new);
4510 wtap_dump_close(pdh, &err);
4514 if (!wtap_dump_close(pdh, &err)) {
4515 cf_close_failure_alert_box(fname, err);
4519 how_to_save = SAVE_WITH_WTAP;
4522 if (fname_new != NULL) {
4523 /* We wrote out to fname_new, and should rename it on top of
4524 fname. fname_new is now closed, so that should be possible even
4525 on Windows. However, on Windows, we first need to close whatever
4526 file descriptors we have open for fname. */
4528 wtap_fdclose(cf->wth);
4530 /* Now do the rename. */
4531 if (ws_rename(fname_new, fname) == -1) {
4532 /* Well, the rename failed. */
4533 cf_rename_failure_alert_box(fname, errno);
4535 /* Attempt to reopen the random file descriptor using the
4536 current file's filename. (At this point, the sequential
4537 file descriptor is closed.) */
4538 if (!wtap_fdreopen(cf->wth, cf->filename, &err)) {
4539 /* Oh, well, we're screwed. */
4540 display_basename = g_filename_display_basename(cf->filename);
4541 simple_error_message_box(
4542 file_open_error_message(err, FALSE), display_basename);
4543 g_free(display_basename);
4550 cf_callback_invoke(cf_cb_file_save_finished, NULL);
4551 cf->unsaved_changes = FALSE;
4554 switch (how_to_save) {
4556 case SAVE_WITH_MOVE:
4557 /* We just moved the file, so the wtap structure refers to the
4558 new file, and all the information other than the filename
4559 and the "is temporary" status applies to the new file; just
4561 g_free(cf->filename);
4562 cf->filename = g_strdup(fname);
4563 cf->is_tempfile = FALSE;
4564 cf_callback_invoke(cf_cb_file_fast_save_finished, cf);
4567 case SAVE_WITH_COPY:
4568 /* We just copied the file, s all the information other than
4569 the wtap structure, the filename, and the "is temporary"
4570 status applies to the new file; just update that. */
4571 wtap_close(cf->wth);
4572 /* Although we're just "copying" and then opening the copy, it will
4573 try all open_routine readers to open the copy, so we need to
4574 reset the cfile's open_type. */
4575 cf->open_type = WTAP_TYPE_AUTO;
4576 cf->wth = wtap_open_offline(fname, WTAP_TYPE_AUTO, &err, &err_info, TRUE);
4577 if (cf->wth == NULL) {
4578 cf_open_failure_alert_box(fname, err, err_info, FALSE, 0);
4581 g_free(cf->filename);
4582 cf->filename = g_strdup(fname);
4583 cf->is_tempfile = FALSE;
4585 cf_callback_invoke(cf_cb_file_fast_save_finished, cf);
4588 case SAVE_WITH_WTAP:
4589 /* Open and read the file we saved to.
4591 XXX - this is somewhat of a waste; we already have the
4592 packets, all this gets us is updated file type information
4593 (which we could just stuff into "cf"), and having the new
4594 file be the one we have opened and from which we're reading
4595 the data, and it means we have to spend time opening and
4596 reading the file, which could be a significant amount of
4597 time if the file is large.
4599 If the capture-file-writing code were to return the
4600 seek offset of each packet it writes, we could save that
4601 in the frame_data structure for the frame, and just open
4602 the file without reading it again...
4604 ...as long as, for gzipped files, the process of writing
4605 out the file *also* generates the information needed to
4606 support fast random access to the compressed file. */
4607 /* rescan_file will cause us to try all open_routines, so
4608 reset cfile's open_type */
4609 cf->open_type = WTAP_TYPE_AUTO;
4610 if (rescan_file(cf, fname, FALSE, &err) != CF_READ_OK) {
4611 /* The rescan failed; just close the file. Either
4612 a dialog was popped up for the failure, so the
4613 user knows what happened, or they stopped the
4614 rescan, in which case they know what happened. */
4620 /* If we were told to discard the comments, do so. */
4621 if (discard_comments) {
4622 /* Remove SHB comment, if any. */
4623 wtap_write_shb_comment(cf->wth, NULL);
4625 /* remove all user comments */
4626 for (framenum = 1; framenum <= cf->count; framenum++) {
4627 fdata = frame_data_sequence_find(cf->frames, framenum);
4629 fdata->flags.has_phdr_comment = FALSE;
4630 fdata->flags.has_user_comment = FALSE;
4633 if (cf->frames_user_comments) {
4634 g_tree_destroy(cf->frames_user_comments);
4635 cf->frames_user_comments = NULL;
4638 cf->packet_comment_count = 0;
4644 if (fname_new != NULL) {
4645 /* We were trying to write to a temporary file; get rid of it if it
4646 exists. (We don't care whether this fails, as, if it fails,
4647 there's not much we can do about it. I guess if it failed for
4648 a reason other than "it doesn't exist", we could report an
4649 error, so the user knows there's a junk file that they might
4650 want to clean up.) */
4651 ws_unlink(fname_new);
4654 cf_callback_invoke(cf_cb_file_save_failed, NULL);
4655 return CF_WRITE_ERROR;
4659 cf_export_specified_packets(capture_file *cf, const char *fname,
4660 packet_range_t *range, guint save_format,
4661 gboolean compressed)
4663 gchar *fname_new = NULL;
4666 save_callback_args_t callback_args;
4667 wtapng_section_t *shb_hdr = NULL;
4668 wtapng_iface_descriptions_t *idb_inf = NULL;
4669 wtapng_name_res_t *nrb_hdr = NULL;
4672 cf_callback_invoke(cf_cb_file_export_specified_packets_started, (gpointer)fname);
4674 packet_range_process_init(range);
4676 /* We're writing out specified packets from the specified capture
4677 file to another file. Even if all captured packets are to be
4678 written, don't special-case the operation - read each packet
4679 and then write it out if it's one of the specified ones. */
4681 /* XXX: what free's this shb_hdr? */
4682 shb_hdr = wtap_file_get_shb_for_new_file(cf->wth);
4683 idb_inf = wtap_file_get_idb_info(cf->wth);
4684 nrb_hdr = wtap_file_get_nrb_for_new_file(cf->wth);
4686 /* Determine what file encapsulation type we should use. */
4687 encap = wtap_dump_file_encap_type(cf->linktypes);
4689 if (file_exists(fname)) {
4690 /* We're overwriting an existing file; write out to a new file,
4691 and, if that succeeds, rename the new file on top of the
4692 old file. That makes this a "safe save", so that we don't
4693 lose the old file if we have a problem writing out the new
4694 file. (If the existing file is the current capture file,
4695 we *HAVE* to do that, otherwise we're overwriting the file
4696 from which we're reading the packets that we're writing!) */
4697 fname_new = g_strdup_printf("%s~", fname);
4698 pdh = wtap_dump_open_ng(fname_new, save_format, encap, cf->snap,
4699 compressed, shb_hdr, idb_inf, nrb_hdr, &err);
4701 pdh = wtap_dump_open_ng(fname, save_format, encap, cf->snap,
4702 compressed, shb_hdr, idb_inf, nrb_hdr, &err);
4708 cf_open_failure_alert_box(fname, err, NULL, TRUE, save_format);
4712 /* Add address resolution */
4713 wtap_dump_set_addrinfo_list(pdh, get_addrinfo_list());
4715 /* Iterate through the list of packets, processing the packets we were
4718 XXX - we've already called "packet_range_process_init(range)", but
4719 "process_specified_records()" will do it again. Fortunately,
4720 that's harmless in this case, as we haven't done anything to
4721 "range" since we initialized it. */
4722 callback_args.pdh = pdh;
4723 callback_args.fname = fname;
4724 callback_args.file_type = save_format;
4725 switch (process_specified_records(cf, range, "Writing", "specified records",
4726 TRUE, save_record, &callback_args)) {
4729 /* Completed successfully. */
4733 /* The user decided to abort the saving.
4734 If we're writing to a temporary file, remove it.
4735 XXX - should we do so even if we're not writing to a
4737 wtap_dump_close(pdh, &err);
4738 if (fname_new != NULL)
4739 ws_unlink(fname_new);
4740 cf_callback_invoke(cf_cb_file_export_specified_packets_stopped, NULL);
4741 return CF_WRITE_ABORTED;
4745 /* Error while saving.
4746 If we're writing to a temporary file, remove it. */
4747 if (fname_new != NULL)
4748 ws_unlink(fname_new);
4749 wtap_dump_close(pdh, &err);
4753 if (!wtap_dump_close(pdh, &err)) {
4754 cf_close_failure_alert_box(fname, err);
4758 if (fname_new != NULL) {
4759 /* We wrote out to fname_new, and should rename it on top of
4760 fname; fname is now closed, so that should be possible even
4761 on Windows. Do the rename. */
4762 if (ws_rename(fname_new, fname) == -1) {
4763 /* Well, the rename failed. */
4764 cf_rename_failure_alert_box(fname, errno);
4769 cf_callback_invoke(cf_cb_file_export_specified_packets_finished, NULL);
4773 if (fname_new != NULL) {
4774 /* We were trying to write to a temporary file; get rid of it if it
4775 exists. (We don't care whether this fails, as, if it fails,
4776 there's not much we can do about it. I guess if it failed for
4777 a reason other than "it doesn't exist", we could report an
4778 error, so the user knows there's a junk file that they might
4779 want to clean up.) */
4780 ws_unlink(fname_new);
4783 cf_callback_invoke(cf_cb_file_export_specified_packets_failed, NULL);
4784 return CF_WRITE_ERROR;
4788 cf_open_failure_alert_box(const char *filename, int err, gchar *err_info,
4789 gboolean for_writing, int file_type)
4791 gchar *display_basename;
4794 /* Wiretap error. */
4795 display_basename = g_filename_display_basename(filename);
4798 case WTAP_ERR_NOT_REGULAR_FILE:
4799 simple_error_message_box(
4800 "The file \"%s\" is a \"special file\" or socket or other non-regular file.",
4804 case WTAP_ERR_RANDOM_OPEN_PIPE:
4805 /* Seen only when opening a capture file for reading. */
4806 simple_error_message_box(
4807 "The file \"%s\" is a pipe or FIFO; Wireshark can't read pipe or FIFO files.\n"
4808 "To capture from a pipe or FIFO use wireshark -i -",
4812 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
4813 /* Seen only when opening a capture file for reading. */
4814 simple_error_message_box(
4815 "The file \"%s\" isn't a capture file in a format Wireshark understands.",
4819 case WTAP_ERR_UNSUPPORTED:
4820 /* Seen only when opening a capture file for reading. */
4821 simple_error_message_box(
4822 "The file \"%s\" contains record data that Wireshark doesn't support.\n"
4825 err_info != NULL ? err_info : "no information supplied");
4829 case WTAP_ERR_CANT_WRITE_TO_PIPE:
4830 /* Seen only when opening a capture file for writing. */
4831 simple_error_message_box(
4832 "The file \"%s\" is a pipe, and %s capture files can't be "
4833 "written to a pipe.",
4834 display_basename, wtap_file_type_subtype_string(file_type));
4837 case WTAP_ERR_UNWRITABLE_FILE_TYPE:
4838 /* Seen only when opening a capture file for writing. */
4839 simple_error_message_box(
4840 "Wireshark doesn't support writing capture files in that format.");
4843 case WTAP_ERR_UNWRITABLE_ENCAP:
4844 /* Seen only when opening a capture file for writing. */
4845 simple_error_message_box("Wireshark can't save this capture in that format.");
4848 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
4850 simple_error_message_box(
4851 "Wireshark can't save this capture in that format.");
4853 simple_error_message_box(
4854 "The file \"%s\" is a capture for a network type that Wireshark doesn't support.",
4859 case WTAP_ERR_BAD_FILE:
4860 /* Seen only when opening a capture file for reading. */
4861 simple_error_message_box(
4862 "The file \"%s\" appears to be damaged or corrupt.\n"
4865 err_info != NULL ? err_info : "no information supplied");
4869 case WTAP_ERR_CANT_OPEN:
4871 simple_error_message_box(
4872 "The file \"%s\" could not be created for some unknown reason.",
4875 simple_error_message_box(
4876 "The file \"%s\" could not be opened for some unknown reason.",
4881 case WTAP_ERR_SHORT_READ:
4882 simple_error_message_box(
4883 "The file \"%s\" appears to have been cut short"
4884 " in the middle of a packet or other data.",
4888 case WTAP_ERR_SHORT_WRITE:
4889 simple_error_message_box(
4890 "A full header couldn't be written to the file \"%s\".",
4894 case WTAP_ERR_COMPRESSION_NOT_SUPPORTED:
4895 simple_error_message_box(
4896 "This file type cannot be written as a compressed file.");
4899 case WTAP_ERR_DECOMPRESS:
4900 simple_error_message_box(
4901 "The compressed file \"%s\" appears to be damaged or corrupt.\n"
4902 "(%s)", display_basename,
4903 err_info != NULL ? err_info : "no information supplied");
4908 simple_error_message_box(
4909 "The file \"%s\" could not be %s: %s.",
4911 for_writing ? "created" : "opened",
4912 wtap_strerror(err));
4915 g_free(display_basename);
4918 open_failure_alert_box(filename, err, for_writing);
4923 * XXX - whether we mention the source pathname, the target pathname,
4924 * or both depends on the error and on what we find if we look for
4925 * one or both of them.
4928 cf_rename_failure_alert_box(const char *filename, int err)
4930 gchar *display_basename;
4932 display_basename = g_filename_display_basename(filename);
4936 /* XXX - should check whether the source exists and, if not,
4937 report it as the problem and, if so, report the destination
4939 simple_error_message_box("The path to the file \"%s\" doesn't exist.",
4944 /* XXX - if we're doing a rename after a safe save, we should
4945 probably say something else. */
4946 simple_error_message_box("You don't have permission to move the capture file to \"%s\".",
4951 /* XXX - this should probably mention both the source and destination
4953 simple_error_message_box("The file \"%s\" could not be moved: %s.",
4954 display_basename, wtap_strerror(err));
4957 g_free(display_basename);
4960 /* Check for write errors - if the file is being written to an NFS server,
4961 a write error may not show up until the file is closed, as NFS clients
4962 might not send writes to the server until the "write()" call finishes,
4963 so that the write may fail on the server but the "write()" may succeed. */
4965 cf_close_failure_alert_box(const char *filename, int err)
4967 gchar *display_basename;
4970 /* Wiretap error. */
4971 display_basename = g_filename_display_basename(filename);
4974 case WTAP_ERR_CANT_CLOSE:
4975 simple_error_message_box(
4976 "The file \"%s\" couldn't be closed for some unknown reason.",
4980 case WTAP_ERR_SHORT_WRITE:
4981 simple_error_message_box(
4982 "Not all the packets could be written to the file \"%s\".",
4987 simple_error_message_box(
4988 "An error occurred while closing the file \"%s\": %s.",
4989 display_basename, wtap_strerror(err));
4992 g_free(display_basename);
4995 We assume that a close error from the OS is really a write error. */
4996 write_failure_alert_box(filename, err);
5000 /* Reload the current capture file. */
5002 cf_reload(capture_file *cf) {
5004 gboolean is_tempfile;
5007 /* If the file could be opened, "cf_open()" calls "cf_close()"
5008 to get rid of state for the old capture file before filling in state
5009 for the new capture file. "cf_close()" will remove the file if
5010 it's a temporary file; we don't want that to happen (for one thing,
5011 it'd prevent subsequent reopens from working). Remember whether it's
5012 a temporary file, mark it as not being a temporary file, and then
5013 reopen it as the type of file it was.
5015 Also, "cf_close()" will free "cf->filename", so we must make
5016 a copy of it first. */
5017 filename = g_strdup(cf->filename);
5018 is_tempfile = cf->is_tempfile;
5019 cf->is_tempfile = FALSE;
5020 if (cf_open(cf, filename, cf->open_type, is_tempfile, &err) == CF_OK) {
5021 switch (cf_read(cf, TRUE)) {
5025 /* Just because we got an error, that doesn't mean we were unable
5026 to read any of the file; we handle what we could get from the
5030 case CF_READ_ABORTED:
5031 /* The user bailed out of re-reading the capture file; the
5032 capture file has been closed - just free the capture file name
5033 string and return (without changing the last containing
5039 /* The open failed, so "cf->is_tempfile" wasn't set to "is_tempfile".
5040 Instead, the file was left open, so we should restore "cf->is_tempfile"
5043 XXX - change the menu? Presumably "cf_open()" will do that;
5044 make sure it does! */
5045 cf->is_tempfile = is_tempfile;
5047 /* "cf_open()" made a copy of the file name we handed it, so
5048 we should free up our copy. */
5058 * indent-tabs-mode: nil
5061 * ex: set shiftwidth=2 tabstop=8 expandtab:
5062 * :indentSize=2:tabSize=8:noTabs=true: