dcerpc-netlogon: let dissect_secchan_verf() set seen.isseen earlier
[wireshark-sm.git] / file.c
blobf42c36a495b4bcddbe50b092226608841836f64d
1 /* file.c
2 * File I/O routines
4 * Wireshark - Network traffic analyzer
5 * By Gerald Combs <gerald@wireshark.org>
6 * Copyright 1998 Gerald Combs
8 * SPDX-License-Identifier: GPL-2.0-or-later
9 */
11 #include <config.h>
12 #define WS_LOG_DOMAIN LOG_DOMAIN_CAPTURE
14 #include <time.h>
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <string.h>
19 #include <ctype.h>
20 #include <errno.h>
22 #include <wsutil/file_util.h>
23 #include <wsutil/filesystem.h>
24 #include <wsutil/json_dumper.h>
25 #include <wsutil/wslog.h>
26 #include <wsutil/ws_assert.h>
27 #include <wsutil/version_info.h>
28 #include <wsutil/report_message.h>
30 #include <wiretap/merge.h>
32 #include <epan/exceptions.h>
33 #include <epan/epan.h>
34 #include <epan/column.h>
35 #include <epan/packet.h>
36 #include <epan/column-utils.h>
37 #include <epan/expert.h>
38 #include <epan/prefs.h>
39 #include <epan/dfilter/dfilter.h>
40 #include <epan/epan_dissect.h>
41 #include <epan/tap.h>
42 #include <epan/timestamp.h>
43 #include <epan/strutil.h>
44 #include <epan/addr_resolv.h>
45 #include <epan/color_filters.h>
46 #include <epan/secrets.h>
48 #include "cfile.h"
49 #include "file.h"
50 #include "fileset.h"
51 #include "frame_tvbuff.h"
53 #include "ui/alert_box.h"
54 #include "ui/simple_dialog.h"
55 #include "ui/main_statusbar.h"
56 #include "ui/progress_dlg.h"
57 #include "ui/urls.h"
58 #include "ui/ws_ui_util.h"
59 #include "ui/packet_list_utils.h"
61 /* Needed for addrinfo */
62 #include <sys/types.h>
64 #ifdef HAVE_SYS_SOCKET_H
65 #include <sys/socket.h>
66 #endif
68 #ifdef HAVE_NETINET_IN_H
69 # include <netinet/in.h>
70 #endif
72 #ifdef _WIN32
73 # include <winsock2.h>
74 # include <ws2tcpip.h>
75 #endif
77 static bool read_record(capture_file *cf, wtap_rec *rec, Buffer *buf,
78 dfilter_t *dfcode, epan_dissect_t *edt, column_info *cinfo, int64_t offset,
79 fifo_string_cache_t *frame_dup_cache, GChecksum *frame_cksum);
81 static void rescan_packets(capture_file *cf, const char *action, const char *action_item, bool redissect);
83 typedef enum {
84 MR_NOTMATCHED,
85 MR_MATCHED,
86 MR_ERROR
87 } match_result;
88 typedef match_result (*ws_match_function)(capture_file *, frame_data *,
89 wtap_rec *, Buffer *, void *);
90 static match_result match_protocol_tree(capture_file *cf, frame_data *fdata,
91 wtap_rec *, Buffer *, void *criterion);
92 static void match_subtree_text(proto_node *node, void *data);
93 static void match_subtree_text_reverse(proto_node *node, void *data);
94 static match_result match_summary_line(capture_file *cf, frame_data *fdata,
95 wtap_rec *, Buffer *, void *criterion);
96 static match_result match_narrow_and_wide(capture_file *cf, frame_data *fdata,
97 wtap_rec *, Buffer *, void *criterion);
98 static match_result match_narrow_and_wide_reverse(capture_file *cf, frame_data *fdata,
99 wtap_rec *, Buffer *, void *criterion);
100 static match_result match_narrow_and_wide_case(capture_file *cf, frame_data *fdata,
101 wtap_rec *, Buffer *, void *criterion);
102 static match_result match_narrow_and_wide_case_reverse(capture_file *cf, frame_data *fdata,
103 wtap_rec *, Buffer *, void *criterion);
104 static match_result match_narrow_case(capture_file *cf, frame_data *fdata,
105 wtap_rec *, Buffer *, void *criterion);
106 static match_result match_narrow_case_reverse(capture_file *cf, frame_data *fdata,
107 wtap_rec *, Buffer *, void *criterion);
108 static match_result match_wide(capture_file *cf, frame_data *fdata,
109 wtap_rec *, Buffer *, void *criterion);
110 static match_result match_wide_reverse(capture_file *cf, frame_data *fdata,
111 wtap_rec *, Buffer *, void *criterion);
112 static match_result match_wide_case(capture_file *cf, frame_data *fdata,
113 wtap_rec *, Buffer *, void *criterion);
114 static match_result match_wide_case_reverse(capture_file *cf, frame_data *fdata,
115 wtap_rec *, Buffer *, void *criterion);
116 static match_result match_binary(capture_file *cf, frame_data *fdata,
117 wtap_rec *, Buffer *, void *criterion);
118 static match_result match_binary_reverse(capture_file *cf, frame_data *fdata,
119 wtap_rec *, Buffer *, void *criterion);
120 static match_result match_regex(capture_file *cf, frame_data *fdata,
121 wtap_rec *, Buffer *, void *criterion);
122 static match_result match_regex_reverse(capture_file *cf, frame_data *fdata,
123 wtap_rec *, Buffer *, void *criterion);
124 static match_result match_dfilter(capture_file *cf, frame_data *fdata,
125 wtap_rec *, Buffer *, void *criterion);
126 static match_result match_marked(capture_file *cf, frame_data *fdata,
127 wtap_rec *, Buffer *, void *criterion);
128 static match_result match_time_reference(capture_file *cf, frame_data *fdata,
129 wtap_rec *, Buffer *, void *criterion);
130 static bool find_packet(capture_file *cf, ws_match_function match_function,
131 void *criterion, search_direction dir);
133 static void cf_rename_failure_alert_box(const char *filename, int err);
135 /* Seconds spent processing packets between pushing UI updates. */
136 #define PROGBAR_UPDATE_INTERVAL 0.150
138 /* Show the progress bar after this many seconds. */
139 #define PROGBAR_SHOW_DELAY 0.5
142 * Maximum number of records we support in a file.
144 * It is, at most, the maximum value of a uint32_t, as we use a uint32_t
145 * for the frame number.
147 * We allow it to be set to a lower value; see issue #16908 for why
148 * we're doing this. Thanks, Qt!
150 static uint32_t max_records = UINT32_MAX;
152 void
153 cf_set_max_records(unsigned max_records_arg)
155 max_records = max_records_arg;
159 * We could probably use g_signal_...() instead of the callbacks below but that
160 * would require linking our CLI programs to libgobject and creating an object
161 * instance for the signals.
163 typedef struct {
164 cf_callback_t cb_fct;
165 void * user_data;
166 } cf_callback_data_t;
168 static GList *cf_callbacks;
170 static void
171 cf_callback_invoke(int event, void *data)
173 cf_callback_data_t *cb;
174 GList *cb_item = cf_callbacks;
176 /* there should be at least one interested */
177 ws_assert(cb_item != NULL);
179 while (cb_item != NULL) {
180 cb = (cf_callback_data_t *)cb_item->data;
181 cb->cb_fct(event, data, cb->user_data);
182 cb_item = g_list_next(cb_item);
186 void
187 cf_callback_add(cf_callback_t func, void *user_data)
189 cf_callback_data_t *cb;
191 cb = g_new(cf_callback_data_t,1);
192 cb->cb_fct = func;
193 cb->user_data = user_data;
195 cf_callbacks = g_list_prepend(cf_callbacks, cb);
198 void
199 cf_callback_remove(cf_callback_t func, void *user_data)
201 cf_callback_data_t *cb;
202 GList *cb_item = cf_callbacks;
204 while (cb_item != NULL) {
205 cb = (cf_callback_data_t *)cb_item->data;
206 if (cb->cb_fct == func && cb->user_data == user_data) {
207 cf_callbacks = g_list_remove(cf_callbacks, cb);
208 g_free(cb);
209 return;
211 cb_item = g_list_next(cb_item);
214 ws_assert_not_reached();
217 unsigned long
218 cf_get_computed_elapsed(capture_file *cf)
220 return cf->computed_elapsed;
223 static void
224 compute_elapsed(capture_file *cf, int64_t start_time)
226 int64_t delta_time = g_get_monotonic_time() - start_time;
228 cf->computed_elapsed = (unsigned long) (delta_time / 1000); /* ms */
231 static epan_t *
232 ws_epan_new(capture_file *cf)
234 static const struct packet_provider_funcs funcs = {
235 cap_file_provider_get_frame_ts,
236 cap_file_provider_get_interface_name,
237 cap_file_provider_get_interface_description,
238 cap_file_provider_get_modified_block
241 return epan_new(&cf->provider, &funcs);
244 cf_status_t
245 cf_open(capture_file *cf, const char *fname, unsigned int type, bool is_tempfile, int *err)
247 wtap *wth;
248 char *err_info;
250 wth = wtap_open_offline(fname, type, err, &err_info, true);
251 if (wth == NULL)
252 goto fail;
254 /* The open succeeded. Close whatever capture file we had open,
255 and fill in the information for this file. */
256 cf_close(cf);
258 /* Initialize the record metadata. */
259 wtap_rec_init(&cf->rec);
261 /* XXX - we really want to initialize this after we've read all
262 the packets, so we know how much we'll ultimately need. */
263 ws_buffer_init(&cf->buf, 1514);
265 /* We're about to start reading the file. */
266 cf->state = FILE_READ_IN_PROGRESS;
268 /* If there was a pending redissection for the old file (there
269 * shouldn't be), clear it. cf_close() should have failed if the
270 * old file's read lock was held, but it doesn't hurt to clear it. */
271 cf->read_lock = false;
272 cf->redissection_queued = RESCAN_NONE;
274 cf->provider.wth = wth;
275 cf->f_datalen = 0;
277 /* Set the file name because we need it to set the follow stream filter.
278 XXX - is that still true? We need it for other reasons, though,
279 in any case. */
280 cf->filename = g_strdup(fname);
282 /* Indicate whether it's a permanent or temporary file. */
283 cf->is_tempfile = is_tempfile;
285 /* No user changes yet. */
286 cf->unsaved_changes = false;
288 cf->computed_elapsed = 0;
290 cf->cd_t = wtap_file_type_subtype(cf->provider.wth);
291 cf->open_type = type;
292 cf->linktypes = g_array_sized_new(FALSE, FALSE, (unsigned) sizeof(int), 1);
293 cf->count = 0;
294 cf->packet_comment_count = 0;
295 cf->displayed_count = 0;
296 cf->marked_count = 0;
297 cf->ignored_count = 0;
298 cf->ref_time_count = 0;
299 cf->drops_known = false;
300 cf->drops = 0;
301 cf->snap = wtap_snapshot_length(cf->provider.wth);
303 /* Allocate a frame_data_sequence for the frames in this file */
304 cf->provider.frames = new_frame_data_sequence();
306 nstime_set_zero(&cf->elapsed_time);
307 cf->provider.ref = NULL;
308 cf->provider.prev_dis = NULL;
309 cf->provider.prev_cap = NULL;
310 cf->cum_bytes = 0;
312 /* Create new epan session for dissection.
313 * (The old one was freed in cf_close().)
315 cf->epan = ws_epan_new(cf);
317 packet_list_queue_draw();
318 cf_callback_invoke(cf_cb_file_opened, cf);
320 wtap_set_cb_new_ipv4(cf->provider.wth, add_ipv4_name);
321 wtap_set_cb_new_ipv6(cf->provider.wth, (wtap_new_ipv6_callback_t) add_ipv6_name);
322 wtap_set_cb_new_secrets(cf->provider.wth, secrets_wtap_callback);
324 return CF_OK;
326 fail:
327 cfile_open_failure_alert_box(fname, *err, err_info);
328 return CF_ERROR;
332 * Add an encapsulation type to cf->linktypes.
334 static void
335 cf_add_encapsulation_type(capture_file *cf, int encap)
337 unsigned i;
339 for (i = 0; i < cf->linktypes->len; i++) {
340 if (g_array_index(cf->linktypes, int, i) == encap)
341 return; /* it's already there */
343 /* It's not already there - add it. */
344 g_array_append_val(cf->linktypes, encap);
347 /* Reset everything to a pristine state */
348 void
349 cf_close(capture_file *cf)
351 cf->stop_flag = false;
352 if (cf->state == FILE_CLOSED || cf->state == FILE_READ_PENDING)
353 return; /* Nothing to do */
355 /* Die if we're in the middle of reading a file. */
356 ws_assert(cf->state != FILE_READ_IN_PROGRESS);
357 ws_assert(!cf->read_lock);
359 cf_callback_invoke(cf_cb_file_closing, cf);
361 /* close things, if not already closed before */
362 color_filters_cleanup();
364 if (cf->provider.wth) {
365 wtap_close(cf->provider.wth);
366 cf->provider.wth = NULL;
368 /* We have no file open... */
369 if (cf->filename != NULL) {
370 /* If it's a temporary file, remove it. */
371 if (cf->is_tempfile)
372 ws_unlink(cf->filename);
373 g_free(cf->filename);
374 cf->filename = NULL;
376 /* ...which means we have no changes to that file to save. */
377 cf->unsaved_changes = false;
379 /* no open_routine type */
380 cf->open_type = WTAP_TYPE_AUTO;
382 /* Clean up the record metadata. */
383 wtap_rec_cleanup(&cf->rec);
385 /* Clear the packet list. */
386 packet_list_freeze();
387 packet_list_clear();
388 packet_list_thaw();
390 /* Free up the packet buffer. */
391 ws_buffer_free(&cf->buf);
393 dfilter_free(cf->rfcode);
394 cf->rfcode = NULL;
395 if (cf->provider.frames != NULL) {
396 free_frame_data_sequence(cf->provider.frames);
397 cf->provider.frames = NULL;
399 if (cf->provider.frames_modified_blocks) {
400 g_tree_destroy(cf->provider.frames_modified_blocks);
401 cf->provider.frames_modified_blocks = NULL;
403 cf_unselect_packet(cf); /* nothing to select */
404 cf->first_displayed = 0;
405 cf->last_displayed = 0;
407 /* No frames, no frame selected, no field in that frame selected. */
408 cf->count = 0;
409 cf->current_frame = NULL;
410 cf->finfo_selected = NULL;
412 /* No frame link-layer types, either. */
413 if (cf->linktypes != NULL) {
414 g_array_free(cf->linktypes, TRUE);
415 cf->linktypes = NULL;
418 cf->f_datalen = 0;
419 nstime_set_zero(&cf->elapsed_time);
421 reset_tap_listeners();
423 epan_free(cf->epan);
424 cf->epan = NULL;
426 /* We have no file open. */
427 cf->state = FILE_CLOSED;
429 cf_callback_invoke(cf_cb_file_closed, cf);
433 * true if the progress dialog doesn't exist and it looks like we'll
434 * take > PROGBAR_SHOW_DELAY (500ms) to load, false otherwise.
436 static inline bool
437 progress_is_slow(progdlg_t *progdlg, GTimer *prog_timer, int64_t size, int64_t pos)
439 double elapsed;
441 if (progdlg) return false;
442 elapsed = g_timer_elapsed(prog_timer, NULL);
443 /* This only gets checked between reading records, which doesn't help if
444 * a single record takes a very long time, e.g., the first TLS packet if
445 * the SSLKEYLOGFILE is very large. (#17051) */
446 if ((elapsed * 2 > PROGBAR_SHOW_DELAY && (size / pos) >= 2) /* It looks like we're going to be slow. */
447 || elapsed > PROGBAR_SHOW_DELAY) { /* We are indeed slow. */
448 return true;
450 return false;
453 static float
454 calc_progbar_val(capture_file *cf, int64_t size, int64_t file_pos, char *status_str, unsigned long status_size)
456 float progbar_val;
458 progbar_val = (float) file_pos / (float) size;
459 if (progbar_val > 1.0) {
461 /* The file probably grew while we were reading it.
462 * Update file size, and try again.
464 size = wtap_file_size(cf->provider.wth, NULL);
466 if (size >= 0)
467 progbar_val = (float) file_pos / (float) size;
469 /* If it's still > 1, either "wtap_file_size()" failed (in which
470 * case there's not much we can do about it), or the file
471 * *shrank* (in which case there's not much we can do about
472 * it); just clip the progress value at 1.0.
474 if (progbar_val > 1.0f)
475 progbar_val = 1.0f;
478 snprintf(status_str, status_size,
479 "%" PRId64 "KB of %" PRId64 "KB",
480 file_pos / 1024, size / 1024);
482 return progbar_val;
485 cf_read_status_t
486 cf_read(capture_file *cf, bool reloading)
488 int err = 0;
489 char *err_info = NULL;
490 volatile bool too_many_records = false;
491 char *name_ptr;
492 progdlg_t *volatile progbar = NULL;
493 GTimer *prog_timer = g_timer_new();
494 int64_t size;
495 int64_t start_time;
496 epan_dissect_t edt;
497 wtap_rec rec;
498 Buffer buf;
499 dfilter_t *dfcode = NULL;
500 column_info *cinfo;
501 volatile bool create_proto_tree;
502 unsigned tap_flags;
503 bool compiled _U_;
504 volatile bool is_read_aborted = false;
506 /* The update_progress_dlg call below might end up accepting a user request to
507 * trigger redissection/rescans which can modify/destroy the dissection
508 * context ("cf->epan"). That condition should be prevented by callers, but in
509 * case it occurs let's fail gracefully.
511 if (cf->read_lock) {
512 ws_warning("Failing due to recursive cf_read(\"%s\", %d) call!",
513 cf->filename, reloading);
514 return CF_READ_ERROR;
516 /* This is a full dissection, so clear any pending request for one. */
517 cf->redissection_queued = RESCAN_NONE;
518 cf->read_lock = true;
520 /* Compile the current display filter.
521 * The code it compiles to might have changed, e.g. if a display
522 * filter macro used has changed.
524 * We assume this will not fail since cf->dfilter is only set in
525 * cf_filter IFF the filter was valid.
526 * XXX - This is not necessarily true, if the filter has a FT_IPv4
527 * or FT_IPv6 field compared to a resolved hostname in it, because
528 * we do a new host lookup, and that *could* timeout this time
529 * (though with the read lock above we shouldn't have many lookups at
530 * once, reducing the chances of that)... (#19612)
532 if (cf->dfilter) {
533 compiled = dfilter_compile(cf->dfilter, &dfcode, NULL);
534 ws_assert(compiled && dfcode);
537 dfilter_free(cf->dfcode);
538 cf->dfcode = dfcode;
540 /* The compiled dfilter might have a field reference; recompiling it
541 * means that the field references won't match anything. That's what
542 * we want since this is a new sequential read and we don't have
543 * a selected frame with a tree. (Will taps with filters with display
544 * references also have cleared display references?)
547 /* Get the union of the flags for all tap listeners. */
548 tap_flags = union_of_tap_listener_flags();
551 * Determine whether we need to create a protocol tree.
552 * We do if:
554 * we're going to apply a display filter;
556 * one of the tap listeners is going to apply a filter;
558 * one of the tap listeners requires a protocol tree;
560 * a postdissector wants field values or protocols on
561 * the first pass.
563 create_proto_tree =
564 (cf->dfcode != NULL || have_filtering_tap_listeners() ||
565 (tap_flags & TL_REQUIRES_PROTO_TREE) || postdissectors_want_hfids());
567 reset_tap_listeners();
569 name_ptr = g_filename_display_basename(cf->filename);
571 if (reloading)
572 cf_callback_invoke(cf_cb_file_reload_started, cf);
573 else
574 cf_callback_invoke(cf_cb_file_read_started, cf);
576 /* Record the file's compression type.
577 XXX - do we know this at open time? */
578 cf->compression_type = wtap_get_compression_type(cf->provider.wth);
580 /* The packet list window will be empty until the file is completely loaded */
581 packet_list_freeze();
583 cf->stop_flag = false;
584 start_time = g_get_monotonic_time();
586 epan_dissect_init(&edt, cf->epan, create_proto_tree, false);
588 /* If the display filter or any tap listeners require the columns,
589 * construct them. */
590 cinfo = (tap_listeners_require_columns() ||
591 dfilter_requires_columns(cf->dfcode)) ? &cf->cinfo : NULL;
593 /* Find the size of the file. */
594 size = wtap_file_size(cf->provider.wth, NULL);
596 /* If we are to ignore duplicate frames, we need a container to store
597 * hashes frame contents */
598 fifo_string_cache_t frame_dup_cache;
599 GChecksum *volatile cksum = NULL;
601 if (prefs.ignore_dup_frames) {
602 fifo_string_cache_init(&frame_dup_cache, prefs.ignore_dup_frames_cache_entries, g_free);
603 cksum = g_checksum_new(G_CHECKSUM_SHA256);
606 g_timer_start(prog_timer);
608 wtap_rec_init(&rec);
609 ws_buffer_init(&buf, 1514);
611 TRY {
612 int64_t file_pos;
613 int64_t data_offset;
615 float progbar_val;
616 char status_str[100];
618 while ((wtap_read(cf->provider.wth, &rec, &buf, &err, &err_info,
619 &data_offset))) {
620 if (size >= 0) {
621 if (cf->count == max_records) {
623 * Quit if we've already read the maximum number of
624 * records allowed.
626 too_many_records = true;
627 break;
629 file_pos = wtap_read_so_far(cf->provider.wth);
631 /* Create the progress bar if necessary. */
632 if (progress_is_slow(progbar, prog_timer, size, file_pos)) {
633 progbar_val = calc_progbar_val(cf, size, file_pos, status_str, sizeof(status_str));
634 progbar = delayed_create_progress_dlg(cf->window, NULL, NULL, true,
635 &cf->stop_flag, progbar_val);
639 * Update the progress bar, but do it only after
640 * PROGBAR_UPDATE_INTERVAL has elapsed. Calling update_progress_dlg
641 * and packets_bar_update will likely trigger UI paint events, which
642 * might take a while depending on the platform and display. Reset
643 * our timer *after* painting.
645 if (progbar && g_timer_elapsed(prog_timer, NULL) > PROGBAR_UPDATE_INTERVAL) {
646 progbar_val = calc_progbar_val(cf, size, file_pos, status_str, sizeof(status_str));
647 /* update the packet bar content on the first run or frequently on very large files */
648 update_progress_dlg(progbar, progbar_val, status_str);
649 compute_elapsed(cf, start_time);
650 packets_bar_update();
651 g_timer_start(prog_timer);
654 * The previous GUI triggers should not have destroyed the running
655 * session. If that did happen, it could blow up when read_record tries
656 * to use the destroyed edt.session, so detect it right here.
658 ws_assert(edt.session == cf->epan);
661 if (cf->state == FILE_READ_ABORTED) {
662 /* Well, the user decided to exit Wireshark. Break out of the
663 loop, and let the code below (which is called even if there
664 aren't any packets left to read) exit. */
665 is_read_aborted = true;
666 break;
668 if (cf->stop_flag) {
669 /* Well, the user decided to abort the read. He/She will be warned and
670 it might be enough for him/her to work with the already loaded
671 packets.
672 This is especially true for very large capture files, where you don't
673 want to wait loading the whole file (which may last minutes or even
674 hours even on fast machines) just to see that it was the wrong file. */
675 break;
677 read_record(cf, &rec, &buf, cf->dfcode, &edt, cinfo, data_offset, &frame_dup_cache, cksum);
678 wtap_rec_reset(&rec);
681 CATCH(OutOfMemoryError) {
682 simple_message_box(ESD_TYPE_ERROR, NULL,
683 "More information and workarounds can be found at\n"
684 WS_WIKI_URL("KnownBugs/OutOfMemory"),
685 "Sorry, but Wireshark has run out of memory and has to terminate now.");
686 #if 0
687 /* Could we close the current capture and free up memory from that? */
688 #else
689 /* we have to terminate, as we cannot recover from the memory error */
690 exit(1);
691 #endif
693 ENDTRY;
695 // If we're ignoring duplicate frames, clear the data structures.
696 // We really could look at prefs.ignore_dup_frames here, but it's even
697 // safer to check if we had allocated 'cksum'.
698 if (cksum != NULL) {
699 fifo_string_cache_free(&frame_dup_cache);
700 g_checksum_free(cksum);
703 /* We're done reading sequentially through the file. */
704 cf->state = FILE_READ_DONE;
706 /* Destroy the progress bar if it was created. */
707 if (progbar != NULL)
708 destroy_progress_dlg(progbar);
709 g_timer_destroy(prog_timer);
711 /* Free the display name */
712 g_free(name_ptr);
714 epan_dissect_cleanup(&edt);
715 wtap_rec_cleanup(&rec);
716 ws_buffer_free(&buf);
718 /* Close the sequential I/O side, to free up memory it requires. */
719 wtap_sequential_close(cf->provider.wth);
721 /* Allow the protocol dissectors to free up memory that they
722 * don't need after the sequential run-through of the packets. */
723 postseq_cleanup_all_protocols();
725 /* compute the time it took to load the file */
726 compute_elapsed(cf, start_time);
728 /* Set the file encapsulation type now; we don't know what it is until
729 we've looked at all the packets, as we don't know until then whether
730 there's more than one type (and thus whether it's
731 WTAP_ENCAP_PER_PACKET). */
732 cf->lnk_t = wtap_file_encap(cf->provider.wth);
734 cf->current_frame = frame_data_sequence_find(cf->provider.frames, cf->first_displayed);
736 packet_list_thaw();
738 /* It is safe again to execute redissections or sort. */
739 ws_assert(cf->read_lock);
740 cf->read_lock = false;
742 if (reloading)
743 cf_callback_invoke(cf_cb_file_reload_finished, cf);
744 else
745 cf_callback_invoke(cf_cb_file_read_finished, cf);
747 /* If we have any displayed packets to select, select the first of those
748 packets by making the first row the selected row. */
749 if (cf->first_displayed != 0) {
750 packet_list_select_row_from_data(NULL);
753 if (is_read_aborted) {
755 * Well, the user decided to exit Wireshark while reading this *offline*
756 * capture file (Live captures are handled by something like
757 * cf_continue_tail). Clean up accordingly.
759 cf_close(cf);
760 cf->redissection_queued = RESCAN_NONE;
761 return CF_READ_ABORTED;
764 if (cf->redissection_queued != RESCAN_NONE) {
765 /* Redissection was queued up. Clear the request and perform it now. */
766 bool redissect = cf->redissection_queued == RESCAN_REDISSECT;
767 rescan_packets(cf, NULL, NULL, redissect);
770 if (cf->stop_flag) {
771 simple_message_box(ESD_TYPE_WARN, NULL,
772 "The remaining packets in the file were discarded.\n"
773 "\n"
774 "As a lot of packets from the original file will be missing,\n"
775 "remember to be careful when saving the current content to a file.\n",
776 "File loading was cancelled.");
777 return CF_READ_ERROR;
780 if (err != 0) {
781 /* Put up a message box noting that the read failed somewhere along
782 the line. Don't throw out the stuff we managed to read, though,
783 if any. */
784 cfile_read_failure_alert_box(NULL, err, err_info);
785 return CF_READ_ERROR;
786 } else if (too_many_records) {
787 simple_message_box(ESD_TYPE_WARN, NULL,
788 "The remaining packets in the file were discarded.\n"
789 "\n"
790 "As a lot of packets from the original file will be missing,\n"
791 "remember to be careful when saving the current content to a file.\n"
792 "\n"
793 "The command-line utility editcap can be used to split "
794 "the file into multiple smaller files",
795 "The file contains more records than the maximum "
796 "supported number of records, %u.", max_records);
797 return CF_READ_ERROR;
798 } else
799 return CF_READ_OK;
802 #ifdef HAVE_LIBPCAP
803 cf_read_status_t
804 cf_continue_tail(capture_file *cf, volatile int to_read, wtap_rec *rec,
805 Buffer *buf, int *err, fifo_string_cache_t *frame_dup_cache, GChecksum *frame_cksum)
807 char *err_info;
808 volatile int newly_displayed_packets = 0;
809 epan_dissect_t edt;
810 bool create_proto_tree;
811 unsigned tap_flags;
813 /* Don't compile the current display filter. The current display filter
814 * text might compile to different code than when the capture started:
816 * If it has a IP address resolved name, calling get_host_ipaddr every
817 * time new packets arrive can mean a *lot* of gethostbyname calls
818 * in flight at once, eventually leading to a timeout (#19612).
819 * addr_resolv.c says that ares_gethostbyname is "usually interactive",
820 * unlike ares_gethostbyaddr (used in dissection), and violating that
821 * expectation is bad.
823 * If it has a display filter macro, the definition might have changed.
825 * If it has a field reference, the selected frame / current proto tree
826 * might have changed, and we don't have the old one. If we recompile,
827 * we can't set the field references to the old values.
829 * For a rescan, redissection, reload, retap, or opening a new file, we
830 * want to compile. What about here, when new frames have arrived in a live
831 * capture? We might be able to cache the host lookup, and a user might want
832 * the new display filter macro definition, but the user almost surely wants
833 * the field references to refer to values from the proto tree when the
834 * filter was applied, not whatever it happens to be now if the user has
835 * clicked on a different packet.
837 * To get the new compiled filter, the user should refilter.
840 /* Get the union of the flags for all tap listeners. */
841 tap_flags = union_of_tap_listener_flags();
844 * Determine whether we need to create a protocol tree.
845 * We do if:
847 * we're going to apply a display filter;
849 * one of the tap listeners is going to apply a filter;
851 * one of the tap listeners requires a protocol tree;
853 * a postdissector wants field values or protocols on
854 * the first pass.
856 create_proto_tree =
857 (cf->dfcode != NULL || have_filtering_tap_listeners() ||
858 (tap_flags & TL_REQUIRES_PROTO_TREE) || postdissectors_want_hfids());
860 *err = 0;
862 /* Don't freeze/thaw the list when doing live capture */
863 /*packet_list_freeze();*/
865 epan_dissect_init(&edt, cf->epan, create_proto_tree, false);
867 TRY {
868 int64_t data_offset = 0;
869 column_info *cinfo;
871 /* If the display filter or any tap listeners require the columns,
872 * construct them. */
873 cinfo = (tap_listeners_require_columns() ||
874 dfilter_requires_columns(cf->dfcode)) ? &cf->cinfo : NULL;
876 while (to_read != 0) {
877 wtap_cleareof(cf->provider.wth);
878 if (!wtap_read(cf->provider.wth, rec, buf, err, &err_info,
879 &data_offset)) {
880 break;
882 if (cf->state == FILE_READ_ABORTED) {
883 /* Well, the user decided to exit Wireshark. Break out of the
884 loop, and let the code below (which is called even if there
885 aren't any packets left to read) exit. */
886 break;
888 if (read_record(cf, rec, buf, cf->dfcode, &edt, cinfo, data_offset, frame_dup_cache, frame_cksum)) {
889 newly_displayed_packets++;
891 to_read--;
893 wtap_rec_reset(rec);
895 CATCH(OutOfMemoryError) {
896 simple_message_box(ESD_TYPE_ERROR, NULL,
897 "More information and workarounds can be found at\n"
898 WS_WIKI_URL("KnownBugs/OutOfMemory"),
899 "Sorry, but Wireshark has run out of memory and has to terminate now.");
900 #if 0
901 /* Could we close the current capture and free up memory from that? */
902 return CF_READ_ABORTED;
903 #else
904 /* we have to terminate, as we cannot recover from the memory error */
905 exit(1);
906 #endif
908 ENDTRY;
910 /* Update the file encapsulation; it might have changed based on the
911 packets we've read. */
912 cf->lnk_t = wtap_file_encap(cf->provider.wth);
914 epan_dissect_cleanup(&edt);
916 /* Don't freeze/thaw the list when doing live capture */
917 /*packet_list_thaw();*/
918 /* With the new packet list the first packet
919 * isn't automatically selected.
921 if (!cf->current_frame && !packet_list_multi_select_active())
922 packet_list_select_row_from_data(NULL);
924 if (cf->state == FILE_READ_ABORTED) {
925 /* Well, the user decided to exit Wireshark. Return CF_READ_ABORTED
926 so that our caller can kill off the capture child process;
927 this will cause an EOF on the pipe from the child, so
928 "cf_finish_tail()" will be called, and it will clean up
929 and exit. */
930 return CF_READ_ABORTED;
931 } else if (*err != 0) {
932 /* We got an error reading the capture file.
933 XXX - pop up a dialog box instead? */
934 if (err_info != NULL) {
935 ws_warning("Error \"%s\" while reading \"%s\" (\"%s\")",
936 wtap_strerror(*err), cf->filename, err_info);
937 g_free(err_info);
938 } else {
939 ws_warning("Error \"%s\" while reading \"%s\"",
940 wtap_strerror(*err), cf->filename);
942 return CF_READ_ERROR;
943 } else
944 return CF_READ_OK;
947 void
948 cf_fake_continue_tail(capture_file *cf)
950 if (cf->state == FILE_CLOSED) {
951 cf->state = FILE_READ_PENDING;
955 cf_read_status_t
956 cf_finish_tail(capture_file *cf, wtap_rec *rec, Buffer *buf, int *err,
957 fifo_string_cache_t *frame_dup_cache, GChecksum *frame_cksum)
959 char *err_info;
960 int64_t data_offset;
961 column_info *cinfo;
962 epan_dissect_t edt;
963 bool create_proto_tree;
964 unsigned tap_flags;
966 /* All the comments above in cf_continue_tail apply regarding the
967 * current display filter.
970 /* Get the union of the flags for all tap listeners. */
971 tap_flags = union_of_tap_listener_flags();
973 /* If the display filter or any tap listeners require the columns,
974 * construct them. */
975 cinfo = (tap_listeners_require_columns() ||
976 dfilter_requires_columns(cf->dfcode)) ? &cf->cinfo : NULL;
979 * Determine whether we need to create a protocol tree.
980 * We do if:
982 * we're going to apply a display filter;
984 * one of the tap listeners is going to apply a filter;
986 * one of the tap listeners requires a protocol tree;
988 * a postdissector wants field values or protocols on
989 * the first pass.
991 create_proto_tree =
992 (cf->dfcode != NULL || have_filtering_tap_listeners() ||
993 (tap_flags & TL_REQUIRES_PROTO_TREE) || postdissectors_want_hfids());
995 if (cf->provider.wth == NULL) {
996 cf_close(cf);
997 return CF_READ_ERROR;
1000 /* Don't freeze/thaw the list when doing live capture */
1001 /*packet_list_freeze();*/
1003 epan_dissect_init(&edt, cf->epan, create_proto_tree, false);
1005 while ((wtap_read(cf->provider.wth, rec, buf, err, &err_info, &data_offset))) {
1006 if (cf->state == FILE_READ_ABORTED) {
1007 /* Well, the user decided to abort the read. Break out of the
1008 loop, and let the code below (which is called even if there
1009 aren't any packets left to read) exit. */
1010 break;
1012 read_record(cf, rec, buf, cf->dfcode, &edt, cinfo, data_offset, frame_dup_cache, frame_cksum);
1013 wtap_rec_reset(rec);
1016 epan_dissect_cleanup(&edt);
1018 /* Don't freeze/thaw the list when doing live capture */
1019 /*packet_list_thaw();*/
1021 if (cf->state == FILE_READ_ABORTED) {
1022 /* Well, the user decided to abort the read. We're only called
1023 when the child capture process closes the pipe to us (meaning
1024 it's probably exited), so we can just close the capture
1025 file; we return CF_READ_ABORTED so our caller can do whatever
1026 is appropriate when that happens. */
1027 cf_close(cf);
1028 return CF_READ_ABORTED;
1031 /* We're done reading sequentially through the file. */
1032 cf->state = FILE_READ_DONE;
1034 /* We're done reading sequentially through the file; close the
1035 sequential I/O side, to free up memory it requires. */
1036 wtap_sequential_close(cf->provider.wth);
1038 /* Allow the protocol dissectors to free up memory that they
1039 * don't need after the sequential run-through of the packets. */
1040 postseq_cleanup_all_protocols();
1042 /* Update the file encapsulation; it might have changed based on the
1043 packets we've read. */
1044 cf->lnk_t = wtap_file_encap(cf->provider.wth);
1046 /* Update the details in the file-set dialog, as the capture file
1047 * has likely grown since we first stat-ed it */
1048 fileset_update_file(cf->filename);
1050 if (*err != 0) {
1051 /* We got an error reading the capture file.
1052 XXX - pop up a dialog box? */
1053 if (err_info != NULL) {
1054 ws_warning("Error \"%s\" while reading \"%s\" (\"%s\")",
1055 wtap_strerror(*err), cf->filename, err_info);
1056 g_free(err_info);
1057 } else {
1058 ws_warning("Error \"%s\" while reading \"%s\"",
1059 wtap_strerror(*err), cf->filename);
1061 return CF_READ_ERROR;
1062 } else {
1063 return CF_READ_OK;
1066 #endif /* HAVE_LIBPCAP */
1068 char *
1069 cf_get_display_name(capture_file *cf)
1071 char *displayname;
1073 /* Return a name to use in displays */
1074 if (!cf->is_tempfile) {
1075 /* Get the last component of the file name, and use that. */
1076 if (cf->filename) {
1077 displayname = g_filename_display_basename(cf->filename);
1078 } else {
1079 displayname=g_strdup("(No file)");
1081 } else {
1082 /* The file we read is a temporary file from a live capture or
1083 a merge operation; we don't mention its name, but, if it's
1084 from a capture, give the source of the capture. */
1085 if (cf->source) {
1086 displayname = g_strdup(cf->source);
1087 } else {
1088 displayname = g_strdup("(Untitled)");
1091 return displayname;
1094 char *
1095 cf_get_basename(capture_file *cf)
1097 char *displayname;
1099 /* Return a name to use in the GUI for the basename for files to
1100 which we save statistics */
1101 if (!cf->is_tempfile) {
1102 /* Get the last component of the file name, and use that. */
1103 if (cf->filename) {
1104 displayname = g_filename_display_basename(cf->filename);
1106 /* If the file name ends with any extension that corresponds
1107 to a file type we support - including compressed versions
1108 of those files - strip it off. */
1109 size_t displayname_len = strlen(displayname);
1110 GSList *extensions = wtap_get_all_file_extensions_list();
1111 GSList *suffix;
1112 for (suffix = extensions; suffix != NULL; suffix = g_slist_next(suffix)) {
1113 /* Does the file name end with that extension? */
1114 const char *extension = (char *)suffix->data;
1115 size_t extension_len = strlen(extension);
1116 if (displayname_len > extension_len &&
1117 displayname[displayname_len - extension_len - 1] == '.' &&
1118 strcmp(&displayname[displayname_len - extension_len], extension) == 0) {
1119 /* Yes. Strip the extension off, and return the result. */
1120 displayname[displayname_len - extension_len - 1] = '\0';
1121 break;
1124 wtap_free_extensions_list(extensions);
1125 } else {
1126 displayname=g_strdup("");
1128 } else {
1129 /* The file we read is a temporary file from a live capture or
1130 a merge operation; we don't mention its name, but, if it's
1131 from a capture, give the source of the capture. */
1132 if (cf->source) {
1133 displayname = g_strdup(cf->source);
1134 } else {
1135 displayname = g_strdup("");
1138 return displayname;
1141 void
1142 cf_set_tempfile_source(capture_file *cf, char *source)
1144 if (cf->source) {
1145 g_free(cf->source);
1148 if (source) {
1149 cf->source = g_strdup(source);
1150 } else {
1151 cf->source = g_strdup("");
1155 const char *
1156 cf_get_tempfile_source(capture_file *cf)
1158 if (!cf->source) {
1159 return "";
1162 return cf->source;
1165 /* XXX - use a macro instead? */
1167 cf_get_packet_count(capture_file *cf)
1169 return cf->count;
1172 /* XXX - use a macro instead? */
1173 bool
1174 cf_is_tempfile(capture_file *cf)
1176 return cf->is_tempfile;
1179 void
1180 cf_set_tempfile(capture_file *cf, bool is_tempfile)
1182 cf->is_tempfile = is_tempfile;
1186 /* XXX - use a macro instead? */
1187 void
1188 cf_set_drops_known(capture_file *cf, bool drops_known)
1190 cf->drops_known = drops_known;
1193 /* XXX - use a macro instead? */
1194 void
1195 cf_set_drops(capture_file *cf, uint32_t drops)
1197 cf->drops = drops;
1200 /* XXX - use a macro instead? */
1201 bool
1202 cf_get_drops_known(capture_file *cf)
1204 return cf->drops_known;
1207 /* XXX - use a macro instead? */
1208 uint32_t
1209 cf_get_drops(capture_file *cf)
1211 return cf->drops;
1214 void
1215 cf_set_rfcode(capture_file *cf, dfilter_t *rfcode)
1217 cf->rfcode = rfcode;
1220 static void
1221 add_packet_to_packet_list(frame_data *fdata, capture_file *cf,
1222 epan_dissect_t *edt, dfilter_t *dfcode, column_info *cinfo,
1223 wtap_rec *rec, Buffer *buf, bool add_to_packet_list)
1225 frame_data_set_before_dissect(fdata, &cf->elapsed_time,
1226 &cf->provider.ref, cf->provider.prev_dis);
1227 cf->provider.prev_cap = fdata;
1229 if (dfcode != NULL) {
1230 epan_dissect_prime_with_dfilter(edt, dfcode);
1232 #if 0
1233 /* Prepare coloring rules, this ensures that display filter rules containing
1234 * frame.color_rule references are still processed.
1235 * TODO: actually detect that situation or maybe apply other optimizations? */
1236 if (edt->tree && color_filters_used()) {
1237 color_filters_prime_edt(edt);
1238 fdata->need_colorize = 1;
1240 #endif
1242 if (!fdata->visited) {
1243 /* This is the first pass, so prime the epan_dissect_t with the
1244 hfids postdissectors want on the first pass. */
1245 prime_epan_dissect_with_postdissector_wanted_hfids(edt);
1248 /* Initialize passed_dfilter here so that dissectors can hide packets. */
1249 /* XXX We might want to add a separate "visible" bit to frame_data instead. */
1250 fdata->passed_dfilter = 1;
1252 /* Dissect the frame. */
1253 epan_dissect_run_with_taps(edt, cf->cd_t, rec,
1254 frame_tvbuff_new_buffer(&cf->provider, fdata, buf),
1255 fdata, cinfo);
1257 if (fdata->passed_dfilter && dfcode != NULL) {
1258 fdata->passed_dfilter = dfilter_apply_edt(dfcode, edt) ? 1 : 0;
1260 if (fdata->passed_dfilter && edt->pi.fd->dependent_frames) {
1261 /* This frame passed the display filter but it may depend on other
1262 * (potentially not displayed) frames. Find those frames and mark them
1263 * as depended upon.
1265 g_hash_table_foreach(edt->pi.fd->dependent_frames, find_and_mark_frame_depended_upon, cf->provider.frames);
1269 if (fdata->passed_dfilter || fdata->ref_time)
1270 cf->displayed_count++;
1272 if (add_to_packet_list) {
1273 /* We fill the needed columns from new_packet_list */
1274 packet_list_append(cinfo, fdata);
1277 if (fdata->passed_dfilter || fdata->ref_time)
1279 frame_data_set_after_dissect(fdata, &cf->cum_bytes);
1280 /* The only way we use prev_dis is to get the time stamp of
1281 * the previous displayed frame, so ignore it if it doesn't
1282 * have a time stamp, because we're presumably interested in
1283 * the timestamp of the previously displayed frame with a
1284 * time. XXX: What if in the future we want to use the previously
1285 * displayed frame for something else, too?
1287 if (fdata->has_ts) {
1288 cf->provider.prev_dis = fdata;
1291 /* If we haven't yet seen the first frame, this is it. */
1292 if (cf->first_displayed == 0)
1293 cf->first_displayed = fdata->num;
1295 /* This is the last frame we've seen so far. */
1296 cf->last_displayed = fdata->num;
1299 epan_dissect_reset(edt);
1303 * Read in a new record.
1304 * Returns true if the packet was added to the packet (record) list,
1305 * false otherwise.
1307 static bool
1308 read_record(capture_file *cf, wtap_rec *rec, Buffer *buf, dfilter_t *dfcode,
1309 epan_dissect_t *edt, column_info *cinfo, int64_t offset,
1310 fifo_string_cache_t *frame_dup_cache, GChecksum *frame_cksum)
1312 frame_data fdlocal;
1313 frame_data *fdata;
1314 bool passed = true;
1315 bool added = false;
1316 const char *cksum_string;
1317 bool was_in_cache;
1319 /* Add this packet's link-layer encapsulation type to cf->linktypes, if
1320 it's not already there.
1321 XXX - yes, this is O(N), so if every packet had a different
1322 link-layer encapsulation type, it'd be O(N^2) to read the file, but
1323 there are probably going to be a small number of encapsulation types
1324 in a file. */
1325 if (rec->rec_type == REC_TYPE_PACKET) {
1326 cf_add_encapsulation_type(cf, rec->rec_header.packet_header.pkt_encap);
1329 /* The frame number of this packet, if we add it to the set of frames,
1330 would be one more than the count of frames in the file so far. */
1331 frame_data_init(&fdlocal, cf->count + 1, rec, offset, cf->cum_bytes);
1333 if (cf->rfcode) {
1334 epan_dissect_t rf_edt;
1335 column_info *rf_cinfo = NULL;
1337 epan_dissect_init(&rf_edt, cf->epan, true, false);
1338 epan_dissect_prime_with_dfilter(&rf_edt, cf->rfcode);
1339 if (dfilter_requires_columns(cf->rfcode)) {
1340 rf_cinfo = &cf->cinfo;
1342 epan_dissect_run(&rf_edt, cf->cd_t, rec,
1343 frame_tvbuff_new_buffer(&cf->provider, &fdlocal, buf),
1344 &fdlocal, rf_cinfo);
1345 passed = dfilter_apply_edt(cf->rfcode, &rf_edt);
1346 epan_dissect_cleanup(&rf_edt);
1349 if (passed) {
1350 added = true;
1352 /* This does a shallow copy of fdlocal, which is good enough. */
1353 fdata = frame_data_sequence_add(cf->provider.frames, &fdlocal);
1355 cf->count++;
1356 if (rec->block != NULL)
1357 cf->packet_comment_count += wtap_block_count_option(rec->block, OPT_COMMENT);
1358 cf->f_datalen = offset + fdlocal.cap_len;
1360 // Should we check if the frame data is a duplicate, and thus, ignore
1361 // this frame?
1362 if (frame_cksum != NULL && rec->rec_type == REC_TYPE_PACKET) {
1363 g_checksum_reset(frame_cksum);
1364 g_checksum_update(frame_cksum, ws_buffer_start_ptr(buf), ws_buffer_length(buf));
1365 cksum_string = g_strdup(g_checksum_get_string(frame_cksum));
1366 was_in_cache = fifo_string_cache_insert(frame_dup_cache, cksum_string);
1367 if (was_in_cache) {
1368 g_free((void *)cksum_string);
1369 fdata->ignored = true;
1370 cf->ignored_count++;
1374 /* When a redissection is in progress (or queued), do not process packets.
1375 * This will be done once all (new) packets have been scanned. */
1376 if (!cf->redissecting && cf->redissection_queued == RESCAN_NONE) {
1377 add_packet_to_packet_list(fdata, cf, edt, dfcode, cinfo, rec, buf, true);
1381 return added;
1385 typedef struct _callback_data_t {
1386 void * pd_window;
1387 int64_t f_len;
1388 progdlg_t *progbar;
1389 GTimer *prog_timer;
1390 bool stop_flag;
1391 } callback_data_t;
1394 static bool
1395 merge_callback(merge_event event, int num _U_,
1396 const merge_in_file_t in_files[], const unsigned in_file_count,
1397 void *data)
1399 unsigned i;
1400 callback_data_t *cb_data = (callback_data_t*) data;
1402 ws_assert(cb_data != NULL);
1404 switch (event) {
1406 case MERGE_EVENT_INPUT_FILES_OPENED:
1407 /* do nothing */
1408 break;
1410 case MERGE_EVENT_FRAME_TYPE_SELECTED:
1411 /* do nothing */
1412 break;
1414 case MERGE_EVENT_READY_TO_MERGE:
1415 /* Get the sum of the sizes of all the files. */
1416 for (i = 0; i < in_file_count; i++)
1417 cb_data->f_len += in_files[i].size;
1419 cb_data->prog_timer = g_timer_new();
1420 g_timer_start(cb_data->prog_timer);
1421 break;
1423 case MERGE_EVENT_RECORD_WAS_READ:
1425 /* Create the progress bar if necessary.
1426 We check on every iteration of the loop, so that it takes no
1427 longer than the standard time to create it (otherwise, for a
1428 large file, we might take considerably longer than that standard
1429 time in order to get to the next progress bar step). */
1430 if (cb_data->progbar == NULL) {
1431 cb_data->progbar = delayed_create_progress_dlg(cb_data->pd_window, NULL, NULL,
1432 false, &cb_data->stop_flag, 0.0f);
1436 * Update the progress bar, but do it only after
1437 * PROGBAR_UPDATE_INTERVAL has elapsed. Calling update_progress_dlg
1438 * and packets_bar_update will likely trigger UI paint events, which
1439 * might take a while depending on the platform and display. Reset
1440 * our timer *after* painting.
1442 if (g_timer_elapsed(cb_data->prog_timer, NULL) > PROGBAR_UPDATE_INTERVAL) {
1443 float progbar_val;
1444 int64_t file_pos = 0;
1445 /* Get the sum of the seek positions in all of the files. */
1446 for (i = 0; i < in_file_count; i++)
1447 file_pos += wtap_read_so_far(in_files[i].wth);
1449 progbar_val = (float) file_pos / (float) cb_data->f_len;
1450 if (progbar_val > 1.0f) {
1451 /* Some file probably grew while we were reading it.
1452 That "shouldn't happen", so we'll just clip the progress
1453 value at 1.0. */
1454 progbar_val = 1.0f;
1457 if (cb_data->progbar != NULL) {
1458 char status_str[100];
1459 snprintf(status_str, sizeof(status_str),
1460 "%" PRId64 "KB of %" PRId64 "KB",
1461 file_pos / 1024, cb_data->f_len / 1024);
1462 update_progress_dlg(cb_data->progbar, progbar_val, status_str);
1464 g_timer_start(cb_data->prog_timer);
1467 break;
1469 case MERGE_EVENT_DONE:
1470 /* We're done merging the files; destroy the progress bar if it was created. */
1471 if (cb_data->progbar != NULL)
1472 destroy_progress_dlg(cb_data->progbar);
1473 g_timer_destroy(cb_data->prog_timer);
1474 break;
1477 return cb_data->stop_flag;
1482 cf_status_t
1483 cf_merge_files_to_tempfile(void *pd_window, const char *temp_dir, char **out_filenamep,
1484 int in_file_count, const char *const *in_filenames,
1485 int file_type, bool do_append)
1487 bool status;
1488 merge_progress_callback_t cb;
1489 callback_data_t *cb_data = g_new0(callback_data_t, 1);
1491 /* prepare our callback routine */
1492 cb_data->pd_window = pd_window;
1493 cb.callback_func = merge_callback;
1494 cb.data = cb_data;
1496 cf_callback_invoke(cf_cb_file_merge_started, NULL);
1498 /* merge the files */
1499 status = merge_files_to_tempfile(temp_dir, out_filenamep, "wireshark", file_type,
1500 in_filenames,
1501 in_file_count, do_append,
1502 IDB_MERGE_MODE_ALL_SAME, 0 /* snaplen */,
1503 "Wireshark", &cb);
1505 g_free(cb.data);
1507 cf_callback_invoke(cf_cb_file_merge_finished, NULL);
1509 if (!status) {
1510 /* Callers aren't expected to treat an error or an explicit abort
1511 differently - the merge code puts up error dialogs itself, so
1512 they don't have to. */
1513 return CF_ERROR;
1514 } else
1515 return CF_OK;
1518 cf_status_t
1519 cf_filter_packets(capture_file *cf, char *dftext, bool force)
1521 const char *filter_new = dftext ? dftext : "";
1522 const char *filter_old = cf->dfilter ? cf->dfilter : "";
1523 dfilter_t *dfcode;
1524 df_error_t *df_err;
1526 /* if new filter equals old one, do nothing unless told to do so */
1527 /* XXX - The text can be the same without compiling to the same code.
1528 * (Macros, field references, etc.)
1530 if (!force && strcmp(filter_new, filter_old) == 0) {
1531 return CF_OK;
1534 dfcode=NULL;
1536 if (dftext == NULL) {
1537 /* The new filter is an empty filter (i.e., display all packets).
1538 * so leave dfcode==NULL
1540 } else {
1542 * We have a filter; make a copy of it (as we'll be saving it),
1543 * and try to compile it.
1545 dftext = g_strdup(dftext);
1546 if (!dfilter_compile(dftext, &dfcode, &df_err)) {
1547 /* The attempt failed; report an error. */
1548 simple_message_box(ESD_TYPE_ERROR, NULL,
1549 "See the help for a description of the display filter syntax.",
1550 "\"%s\" isn't a valid display filter: %s",
1551 dftext, df_err->msg);
1552 df_error_free(&df_err);
1553 g_free(dftext);
1554 return CF_ERROR;
1557 /* Was it empty? */
1558 if (dfcode == NULL) {
1559 /* Yes - free the filter text, and set it to null. */
1560 g_free(dftext);
1561 dftext = NULL;
1565 /* We have a valid filter. Replace the current filter. */
1566 g_free(cf->dfilter);
1567 cf->dfilter = dftext;
1569 /* We'll recompile this when the rescan starts, or in cf_read()
1570 * if no file is open currently. However, if no file is open and
1571 * we start a new capture, we want to use this rather than
1572 * recompiling in cf_continue_tail() */
1573 dfilter_free(cf->dfcode);
1574 cf->dfcode = dfcode;
1576 /* Now rescan the packet list, applying the new filter, but not
1577 * throwing away information constructed on a previous pass.
1578 * If a dissection is already in progress, queue it.
1580 if (cf->redissection_queued == RESCAN_NONE) {
1581 if (cf->read_lock) {
1582 cf->redissection_queued = RESCAN_SCAN;
1583 } else if (cf->state != FILE_CLOSED) {
1584 if (dftext == NULL) {
1585 rescan_packets(cf, "Resetting", "filter", false);
1586 } else {
1587 rescan_packets(cf, "Filtering", dftext, false);
1592 return CF_OK;
1595 void
1596 cf_redissect_packets(capture_file *cf)
1598 if (cf->read_lock || cf->redissection_queued == RESCAN_SCAN) {
1599 /* Dissection in progress, signal redissection rather than rescanning. That
1600 * would destroy the current (in-progress) dissection in "cf_read" which
1601 * will cause issues when "cf_read" tries to add packets to the list.
1602 * If a previous rescan was requested, "upgrade" it to a full redissection.
1604 cf->redissection_queued = RESCAN_REDISSECT;
1606 if (cf->redissection_queued != RESCAN_NONE) {
1607 /* Redissection is (already) queued, wait for "cf_read" to finish. */
1608 /* XXX - what if whatever set and later clears read_lock is *not*
1609 * cf_read, e.g. process_specified_records ? We need to handle a
1610 * queued redissection there too like we do in cf_read.
1612 return;
1615 if (cf->state != FILE_CLOSED) {
1616 /* Restart dissection in case no cf_read is pending. */
1617 rescan_packets(cf, "Reprocessing", "all packets", true);
1621 bool
1622 cf_read_record(capture_file *cf, const frame_data *fdata,
1623 wtap_rec *rec, Buffer *buf)
1625 int err;
1626 char *err_info;
1628 if (!wtap_seek_read(cf->provider.wth, fdata->file_off, rec, buf, &err, &err_info)) {
1629 cfile_read_failure_alert_box(cf->filename, err, err_info);
1630 return false;
1632 return true;
1635 bool
1636 cf_read_record_no_alert(capture_file *cf, const frame_data *fdata,
1637 wtap_rec *rec, Buffer *buf)
1639 int err;
1640 char *err_info;
1642 if (!wtap_seek_read(cf->provider.wth, fdata->file_off, rec, buf, &err, &err_info)) {
1643 g_free(err_info);
1644 return false;
1646 return true;
1649 bool
1650 cf_read_current_record(capture_file *cf)
1652 return cf_read_record(cf, cf->current_frame, &cf->rec, &cf->buf);
1655 /* Rescan the list of packets, reconstructing the CList.
1657 "action" describes why we're doing this; it's used in the progress
1658 dialog box.
1660 "action_item" describes what we're doing; it's used in the progress
1661 dialog box.
1663 "redissect" is true if we need to make the dissectors reconstruct
1664 any state information they have (because a preference that affects
1665 some dissector has changed, meaning some dissector might construct
1666 its state differently from the way it was constructed the last time). */
1667 static void
1668 rescan_packets(capture_file *cf, const char *action, const char *action_item, bool redissect)
1670 /* Rescan packets new packet list */
1671 uint32_t framenum;
1672 frame_data *fdata;
1673 wtap_rec rec;
1674 Buffer buf;
1675 progdlg_t *progbar = NULL;
1676 GTimer *prog_timer = g_timer_new();
1677 int count;
1678 frame_data *selected_frame, *preceding_frame, *following_frame, *prev_frame;
1679 int selected_frame_num, preceding_frame_num, following_frame_num, prev_frame_num;
1680 bool selected_frame_seen;
1681 float progbar_val;
1682 int64_t start_time;
1683 char status_str[100];
1684 epan_dissect_t edt;
1685 dfilter_t *dfcode = NULL;
1686 column_info *cinfo;
1687 bool create_proto_tree;
1688 bool filtering_tap_listeners = false;
1689 unsigned tap_flags;
1690 bool add_to_packet_list = false;
1691 bool compiled _U_;
1692 uint32_t frames_count;
1693 rescan_type queued_rescan_type = RESCAN_NONE;
1695 if (cf->state == FILE_CLOSED || cf->state == FILE_READ_PENDING) {
1696 return;
1699 /* Rescan in progress, clear pending actions. */
1700 cf->redissection_queued = RESCAN_NONE;
1701 ws_assert(!cf->read_lock);
1702 cf->read_lock = true;
1704 wtap_rec_init(&rec);
1705 ws_buffer_init(&buf, 1514);
1707 /* Compile the current display filter.
1708 * The code it compiles to might have changed, e.g. if a display
1709 * filter macro used has changed.
1711 * We assume this will not fail since cf->dfilter is only set in
1712 * cf_filter IFF the filter was valid.
1713 * XXX - This is not necessarily true, if the filter has a FT_IPv4
1714 * or FT_IPv6 field compared to a resolved hostname in it, because
1715 * we do a new host lookup, and that *could* timeout this time
1716 * (though with the read lock above we shouldn't have many lookups at
1717 * once, reducing the chances of that)... (#19612)
1719 if (cf->dfilter) {
1720 compiled = dfilter_compile(cf->dfilter, &dfcode, NULL);
1721 ws_assert(compiled && dfcode);
1724 dfilter_free(cf->dfcode);
1725 cf->dfcode = dfcode;
1727 /* Do we have any tap listeners with filters? */
1728 filtering_tap_listeners = have_filtering_tap_listeners();
1730 /* Update references in filters (if any) for the protocol
1731 * tree corresponding to the currently selected frame in the GUI. */
1732 if (cf->edt != NULL && cf->edt->tree != NULL) {
1733 if (cf->dfcode)
1734 dfilter_load_field_references(cf->dfcode, cf->edt->tree);
1735 if (filtering_tap_listeners)
1736 tap_listeners_load_field_references(cf->edt);
1739 if (cf->dfcode != NULL) {
1740 dfilter_log_full(LOG_DOMAIN_DFILTER, LOG_LEVEL_NOISY, NULL, -1, NULL,
1741 cf->dfcode, "Rescanning packets with display filter");
1744 /* Get the union of the flags for all tap listeners. */
1745 tap_flags = union_of_tap_listener_flags();
1747 /* If the display filter or any tap listeners require the columns,
1748 * construct them. */
1749 cinfo = (tap_listeners_require_columns() ||
1750 dfilter_requires_columns(cf->dfcode)) ? &cf->cinfo : NULL;
1753 * Determine whether we need to create a protocol tree.
1754 * We do if:
1756 * we're going to apply a display filter;
1758 * one of the tap listeners is going to apply a filter;
1760 * one of the tap listeners requires a protocol tree;
1762 * we're redissecting and a postdissector wants field
1763 * values or protocols on the first pass.
1765 create_proto_tree =
1766 (cf->dfcode != NULL || filtering_tap_listeners ||
1767 (tap_flags & TL_REQUIRES_PROTO_TREE) ||
1768 (redissect && postdissectors_want_hfids()));
1770 reset_tap_listeners();
1771 /* Which frame, if any, is the currently selected frame?
1772 XXX - should the selected frame or the focus frame be the "current"
1773 frame, that frame being the one from which "Find Frame" searches
1774 start? */
1775 selected_frame = cf->current_frame;
1777 /* Mark frame num as not found */
1778 selected_frame_num = -1;
1780 /* Freeze the packet list while we redo it, so we don't get any
1781 screen updates while it happens. */
1782 packet_list_freeze();
1784 if (redissect) {
1785 /* We need to re-initialize all the state information that protocols
1786 keep, because some preference that controls a dissector has changed,
1787 which might cause the state information to be constructed differently
1788 by that dissector. */
1790 /* We might receive new packets while redissecting, and we don't
1791 want to dissect those before their time. */
1792 cf->redissecting = true;
1794 /* 'reset' dissection session */
1795 epan_free(cf->epan);
1796 if (cf->edt && cf->edt->pi.fd) {
1797 /* All pointers in "per frame proto data" for the currently selected
1798 packet are allocated in wmem_file_scope() and deallocated in epan_free().
1799 Free them here to avoid unintended usage in packet_list_clear(). */
1800 frame_data_destroy(cf->edt->pi.fd);
1802 cf->epan = ws_epan_new(cf);
1803 cf->cinfo.epan = cf->epan;
1805 /* A new Lua tap listener may be registered in lua_prime_all_fields()
1806 called via epan_new() / init_dissection() when reloading Lua plugins. */
1807 if (!create_proto_tree && have_filtering_tap_listeners()) {
1808 create_proto_tree = true;
1810 if (!cinfo && tap_listeners_require_columns()) {
1811 cinfo = &cf->cinfo;
1814 /* We need to redissect the packets so we have to discard our old
1815 * packet list store. */
1816 packet_list_clear();
1817 add_to_packet_list = true;
1820 /* We don't yet know which will be the first and last frames displayed. */
1821 cf->first_displayed = 0;
1822 cf->last_displayed = 0;
1824 /* We currently don't display any packets */
1825 cf->displayed_count = 0;
1827 /* Iterate through the list of frames. Call a routine for each frame
1828 to check whether it should be displayed and, if so, add it to
1829 the display list. */
1830 cf->provider.ref = NULL;
1831 cf->provider.prev_dis = NULL;
1832 cf->provider.prev_cap = NULL;
1833 cf->cum_bytes = 0;
1835 cf_callback_invoke(cf_cb_file_rescan_started, cf);
1837 g_timer_start(prog_timer);
1838 /* Count of packets at which we've looked. */
1839 count = 0;
1840 /* Progress so far. */
1841 progbar_val = 0.0f;
1843 cf->stop_flag = false;
1844 start_time = g_get_monotonic_time();
1846 /* no previous row yet */
1847 prev_frame_num = -1;
1848 prev_frame = NULL;
1850 preceding_frame_num = -1;
1851 preceding_frame = NULL;
1852 following_frame_num = -1;
1853 following_frame = NULL;
1855 selected_frame_seen = false;
1857 frames_count = cf->count;
1859 epan_dissect_init(&edt, cf->epan, create_proto_tree, false);
1861 if (redissect) {
1863 * Decryption secrets and name resolution blocks are read while
1864 * sequentially processing records and then passed to the dissector.
1865 * During redissection, the previous information is lost (see epan_free
1866 * above), but they are not read again from the file as only packet
1867 * records are re-read. Therefore reset the wtap secrets and name
1868 * resolution callbacks such that wtap resupplies the callbacks with
1869 * previously read information.
1871 wtap_set_cb_new_ipv4(cf->provider.wth, add_ipv4_name);
1872 wtap_set_cb_new_ipv6(cf->provider.wth, (wtap_new_ipv6_callback_t) add_ipv6_name);
1873 wtap_set_cb_new_secrets(cf->provider.wth, secrets_wtap_callback);
1876 for (framenum = 1; framenum <= frames_count; framenum++) {
1877 fdata = frame_data_sequence_find(cf->provider.frames, framenum);
1879 /* Create the progress bar if necessary.
1880 We check on every iteration of the loop, so that it takes no
1881 longer than the standard time to create it (otherwise, for a
1882 large file, we might take considerably longer than that standard
1883 time in order to get to the next progress bar step). */
1884 if (progbar == NULL)
1885 progbar = delayed_create_progress_dlg(cf->window, action, action_item, true,
1886 &cf->stop_flag,
1887 progbar_val);
1890 * Update the progress bar, but do it only after PROGBAR_UPDATE_INTERVAL
1891 * has elapsed. Calling update_progress_dlg and packets_bar_update will
1892 * likely trigger UI paint events, which might take a while depending on
1893 * the platform and display. Reset our timer *after* painting.
1895 if (g_timer_elapsed(prog_timer, NULL) > PROGBAR_UPDATE_INTERVAL) {
1896 /* let's not divide by zero. I should never be started
1897 * with count == 0, so let's assert that
1899 ws_assert(cf->count > 0);
1900 progbar_val = (float) count / frames_count;
1902 if (progbar != NULL) {
1903 snprintf(status_str, sizeof(status_str),
1904 "%4u of %u frames", count, frames_count);
1905 update_progress_dlg(progbar, progbar_val, status_str);
1908 g_timer_start(prog_timer);
1911 queued_rescan_type = cf->redissection_queued;
1912 if (queued_rescan_type != RESCAN_NONE) {
1913 /* A redissection was requested while an existing redissection was
1914 * pending. */
1915 break;
1918 if (cf->stop_flag) {
1919 /* Well, the user decided to abort the filtering. Just stop.
1921 XXX - go back to the previous filter? Users probably just
1922 want not to wait for a filtering operation to finish;
1923 unless we cancel by having no filter, reverting to the
1924 previous filter will probably be even more expensive than
1925 continuing the filtering, as it involves going back to the
1926 beginning and filtering, and even with no filter we currently
1927 have to re-generate the entire clist, which is also expensive.
1929 I'm not sure what Network Monitor does, but it doesn't appear
1930 to give you an unfiltered display if you cancel. */
1931 break;
1934 count++;
1936 if (redissect) {
1937 /* Since all state for the frame was destroyed, mark the frame
1938 * as not visited, free the GSList referring to the state
1939 * data (the per-frame data itself was freed by
1940 * "init_dissection()"), and null out the GSList pointer. */
1941 frame_data_reset(fdata);
1942 frames_count = cf->count;
1945 /* Frame dependencies from the previous dissection/filtering are no longer valid. */
1946 fdata->dependent_of_displayed = 0;
1948 if (!cf_read_record(cf, fdata, &rec, &buf))
1949 break; /* error reading the frame */
1951 /* If the previous frame is displayed, and we haven't yet seen the
1952 selected frame, remember that frame - it's the closest one we've
1953 yet seen before the selected frame. */
1954 if (prev_frame_num != -1 && !selected_frame_seen && prev_frame->passed_dfilter) {
1955 preceding_frame_num = prev_frame_num;
1956 preceding_frame = prev_frame;
1959 add_packet_to_packet_list(fdata, cf, &edt, cf->dfcode,
1960 cinfo, &rec, &buf,
1961 add_to_packet_list);
1963 /* If this frame is displayed, and this is the first frame we've
1964 seen displayed after the selected frame, remember this frame -
1965 it's the closest one we've yet seen at or after the selected
1966 frame. */
1967 if (fdata->passed_dfilter && selected_frame_seen && following_frame_num == -1) {
1968 following_frame_num = fdata->num;
1969 following_frame = fdata;
1971 if (fdata == selected_frame) {
1972 selected_frame_seen = true;
1973 if (fdata->passed_dfilter)
1974 selected_frame_num = fdata->num;
1977 /* Remember this frame - it'll be the previous frame
1978 on the next pass through the loop. */
1979 prev_frame_num = fdata->num;
1980 prev_frame = fdata;
1981 wtap_rec_reset(&rec);
1984 epan_dissect_cleanup(&edt);
1985 wtap_rec_cleanup(&rec);
1986 ws_buffer_free(&buf);
1988 /* We are done redissecting the packet list. */
1989 cf->redissecting = false;
1991 if (redissect) {
1992 frames_count = cf->count;
1993 /* Clear out what remains of the visited flags and per-frame data
1994 pointers.
1996 XXX - that may cause various forms of bogosity when dissecting
1997 these frames, as they won't have been seen by this sequential
1998 pass, but the only alternative I see is to keep scanning them
1999 even though the user requested that the scan stop, and that
2000 would leave the user stuck with an Wireshark grinding on
2001 until it finishes. Should we just stick them with that? */
2002 for (; framenum <= frames_count; framenum++) {
2003 fdata = frame_data_sequence_find(cf->provider.frames, framenum);
2004 frame_data_reset(fdata);
2008 /* We're done filtering the packets; destroy the progress bar if it
2009 was created. */
2010 if (progbar != NULL)
2011 destroy_progress_dlg(progbar);
2012 g_timer_destroy(prog_timer);
2014 /* Unfreeze the packet list. */
2015 if (!add_to_packet_list)
2016 packet_list_recreate_visible_rows();
2018 /* Compute the time it took to filter the file */
2019 compute_elapsed(cf, start_time);
2021 packet_list_thaw();
2023 /* It is safe again to execute redissections or sort. */
2024 ws_assert(cf->read_lock);
2025 cf->read_lock = false;
2027 cf_callback_invoke(cf_cb_file_rescan_finished, cf);
2029 if (selected_frame_num == -1) {
2030 /* The selected frame didn't pass the filter. */
2031 if (selected_frame == NULL) {
2032 /* That's because there *was* no selected frame. Make the first
2033 displayed frame the current frame. */
2034 selected_frame_num = 0;
2035 } else {
2036 /* Find the nearest displayed frame to the selected frame (whether
2037 it's before or after that frame) and make that the current frame.
2038 If the next and previous displayed frames are equidistant from the
2039 selected frame, choose the next one. */
2040 ws_assert(following_frame == NULL ||
2041 following_frame->num >= selected_frame->num);
2042 ws_assert(preceding_frame == NULL ||
2043 preceding_frame->num <= selected_frame->num);
2044 if (following_frame == NULL) {
2045 /* No frame after the selected frame passed the filter, so we
2046 have to select the last displayed frame before the selected
2047 frame. */
2048 selected_frame_num = preceding_frame_num;
2049 selected_frame = preceding_frame;
2050 } else if (preceding_frame == NULL) {
2051 /* No frame before the selected frame passed the filter, so we
2052 have to select the first displayed frame after the selected
2053 frame. */
2054 selected_frame_num = following_frame_num;
2055 selected_frame = following_frame;
2056 } else {
2057 /* Frames before and after the selected frame passed the filter, so
2058 we'll select the previous frame */
2059 selected_frame_num = preceding_frame_num;
2060 selected_frame = preceding_frame;
2065 if (selected_frame_num == -1) {
2066 /* There are no frames displayed at all. */
2067 cf_unselect_packet(cf);
2068 } else {
2069 /* Either the frame that was selected passed the filter, or we've
2070 found the nearest displayed frame to that frame. Select it, make
2071 it the focus row, and make it visible. */
2072 /* Set to invalid to force update of packet list and packet details */
2073 if (selected_frame_num == 0) {
2074 packet_list_select_row_from_data(NULL);
2075 }else{
2076 if (!packet_list_select_row_from_data(selected_frame)) {
2077 /* We didn't find a row corresponding to this frame.
2078 This means that the frame isn't being displayed currently,
2079 so we can't select it. */
2080 simple_message_box(ESD_TYPE_INFO, NULL,
2081 "The capture file is probably not fully dissected.",
2082 "End of capture exceeded.");
2087 /* If another rescan (due to dfilter change) or redissection (due to profile
2088 * change) was requested, the rescan above is aborted and restarted here. */
2089 if (queued_rescan_type != RESCAN_NONE) {
2090 redissect = redissect || queued_rescan_type == RESCAN_REDISSECT;
2091 rescan_packets(cf, "Reprocessing", "all packets", redissect);
2097 * Scan through all frame data and recalculate the ref time
2098 * without rereading the file.
2099 * XXX - do we need a progress bar or is this fast enough?
2101 void
2102 cf_reftime_packets(capture_file* cf)
2104 uint32_t framenum;
2105 frame_data *fdata;
2106 nstime_t rel_ts;
2108 cf->provider.ref = NULL;
2109 cf->provider.prev_dis = NULL;
2110 cf->cum_bytes = 0;
2112 for (framenum = 1; framenum <= cf->count; framenum++) {
2113 fdata = frame_data_sequence_find(cf->provider.frames, framenum);
2115 /* just add some value here until we know if it is being displayed or not */
2116 fdata->cum_bytes = cf->cum_bytes + fdata->pkt_len;
2119 * Timestamps
2122 if (fdata->has_ts) {
2123 /* If we don't have the time stamp of the first packet in the
2124 capture, it's because this is the first packet. Save the time
2125 stamp of this packet as the time stamp of the first packet. */
2126 if (cf->provider.ref == NULL)
2127 cf->provider.ref = fdata;
2128 /* if this frames is marked as a reference time frame, reset
2129 firstsec and firstusec to this frame */
2130 if (fdata->ref_time)
2131 cf->provider.ref = fdata;
2133 /* Get the time elapsed between the first packet and this one. */
2134 fdata->frame_ref_num = (fdata != cf->provider.ref) ? cf->provider.ref->num : 0;
2135 nstime_delta(&rel_ts, &fdata->abs_ts, &cf->provider.ref->abs_ts);
2137 /* If it's greater than the current elapsed time, set the elapsed
2138 time to it (we check for "greater than" so as not to be
2139 confused by time moving backwards). */
2140 if ((int32_t)cf->elapsed_time.secs < rel_ts.secs
2141 || ((int32_t)cf->elapsed_time.secs == rel_ts.secs && (int32_t)cf->elapsed_time.nsecs < rel_ts.nsecs)) {
2142 cf->elapsed_time = rel_ts;
2145 /* If this frame is displayed, get the time elapsed between the
2146 previous displayed packet and this packet. */
2147 /* XXX: What if in the future we want to use the previously
2148 * displayed frame for something else, too? Then we'd want
2149 * to store this frame as prev_dis even if it doesn't have a
2150 * timestamp. */
2151 if ( fdata->passed_dfilter ) {
2152 /* If we don't have the time stamp of the previous displayed
2153 packet, it's because this is the first displayed packet.
2154 Save the time stamp of this packet as the time stamp of
2155 the previous displayed packet. */
2156 if (cf->provider.prev_dis == NULL) {
2157 cf->provider.prev_dis = fdata;
2160 fdata->prev_dis_num = cf->provider.prev_dis->num;
2161 cf->provider.prev_dis = fdata;
2163 } else {
2164 /* If this frame doesn't have a timestamp, don't calculate
2165 anything with relative times. */
2166 /* However, if this frame is marked as a reference time frame,
2167 clear the reference frame so that the next frame with a
2168 timestamp becomes the reference frame. */
2169 if (fdata->ref_time) {
2170 cf->provider.ref = NULL;
2175 * Byte counts
2177 if ( (fdata->passed_dfilter) || (fdata->ref_time) ) {
2178 /* This frame either passed the display filter list or is marked as
2179 a time reference frame. All time reference frames are displayed
2180 even if they don't pass the display filter */
2181 if (fdata->ref_time) {
2182 /* if this was a TIME REF frame we should reset the cum_bytes field */
2183 cf->cum_bytes = fdata->pkt_len;
2184 fdata->cum_bytes = cf->cum_bytes;
2185 } else {
2186 /* increase cum_bytes with this packets length */
2187 cf->cum_bytes += fdata->pkt_len;
2193 typedef enum {
2194 PSP_FINISHED,
2195 PSP_STOPPED,
2196 PSP_FAILED
2197 } psp_return_t;
2199 static psp_return_t
2200 process_specified_records(capture_file *cf, packet_range_t *range,
2201 const char *string1, const char *string2, bool terminate_is_stop,
2202 bool (*callback)(capture_file *, frame_data *,
2203 wtap_rec *, Buffer *, void *),
2204 void *callback_args,
2205 bool show_progress_bar)
2207 uint32_t framenum;
2208 frame_data *fdata;
2209 wtap_rec rec;
2210 Buffer buf;
2211 psp_return_t ret = PSP_FINISHED;
2213 progdlg_t *progbar = NULL;
2214 GTimer *prog_timer = g_timer_new();
2215 int progbar_count;
2216 float progbar_val;
2217 char progbar_status_str[100];
2218 range_process_e process_this;
2220 wtap_rec_init(&rec);
2221 ws_buffer_init(&buf, 1514);
2223 g_timer_start(prog_timer);
2224 /* Count of packets at which we've looked. */
2225 progbar_count = 0;
2226 /* Progress so far. */
2227 progbar_val = 0.0f;
2229 /* XXX - It should be ok to have multiple readers, so long as nothing
2230 * frees the epan context, e.g. rescan_packets with redissect true,
2231 * or anything that closes the file (including reload and certain forms
2232 * of saving.) This is mostly to stop cf_save_records but should probably
2233 * be handled by callers in order to allow multiple readers (e.g.,
2234 * restarting taps after adding or changing one.) We should probably
2235 * make this a real reader-writer lock.
2237 if (cf->read_lock) {
2238 ws_warning("Failing due to nested process_specified_records(\"%s\") call!", cf->filename);
2239 return PSP_FAILED;
2241 cf->read_lock = true;
2243 cf->stop_flag = false;
2245 if (range != NULL)
2246 packet_range_process_init(range);
2248 /* Iterate through all the packets, printing the packets that
2249 were selected by the current display filter. */
2250 for (framenum = 1; framenum <= cf->count; framenum++) {
2251 fdata = frame_data_sequence_find(cf->provider.frames, framenum);
2253 /* Create the progress bar if necessary.
2254 We check on every iteration of the loop, so that it takes no
2255 longer than the standard time to create it (otherwise, for a
2256 large file, we might take considerably longer than that standard
2257 time in order to get to the next progress bar step). */
2258 if (show_progress_bar && progbar == NULL)
2259 progbar = delayed_create_progress_dlg(cf->window, string1, string2,
2260 terminate_is_stop,
2261 &cf->stop_flag,
2262 progbar_val);
2265 * Update the progress bar, but do it only after PROGBAR_UPDATE_INTERVAL
2266 * has elapsed. Calling update_progress_dlg and packets_bar_update will
2267 * likely trigger UI paint events, which might take a while depending on
2268 * the platform and display. Reset our timer *after* painting.
2270 if (progbar && g_timer_elapsed(prog_timer, NULL) > PROGBAR_UPDATE_INTERVAL) {
2271 /* let's not divide by zero. I should never be started
2272 * with count == 0, so let's assert that
2274 ws_assert(cf->count > 0);
2275 progbar_val = (float) progbar_count / cf->count;
2277 snprintf(progbar_status_str, sizeof(progbar_status_str),
2278 "%4u of %u packets", progbar_count, cf->count);
2279 update_progress_dlg(progbar, progbar_val, progbar_status_str);
2281 g_timer_start(prog_timer);
2284 if (cf->stop_flag) {
2285 /* Well, the user decided to abort the operation. Just stop,
2286 and arrange to return PSP_STOPPED to our caller, so they know
2287 it was stopped explicitly. */
2288 ret = PSP_STOPPED;
2289 break;
2292 progbar_count++;
2294 if (range != NULL) {
2295 /* do we have to process this packet? */
2296 process_this = packet_range_process_packet(range, fdata);
2297 if (process_this == range_process_next) {
2298 /* this packet uninteresting, continue with next one */
2299 continue;
2300 } else if (process_this == range_processing_finished) {
2301 /* all interesting packets processed, stop the loop */
2302 break;
2306 /* Get the packet */
2307 if (!cf_read_record(cf, fdata, &rec, &buf)) {
2308 /* Attempt to get the packet failed. */
2309 ret = PSP_FAILED;
2310 break;
2312 /* Process the packet */
2313 if (!callback(cf, fdata, &rec, &buf, callback_args)) {
2314 /* Callback failed. We assume it reported the error appropriately. */
2315 ret = PSP_FAILED;
2316 break;
2318 wtap_rec_reset(&rec);
2321 /* We're done printing the packets; destroy the progress bar if
2322 it was created. */
2323 if (progbar != NULL)
2324 destroy_progress_dlg(progbar);
2325 g_timer_destroy(prog_timer);
2327 ws_assert(cf->read_lock);
2328 cf->read_lock = false;
2330 wtap_rec_cleanup(&rec);
2331 ws_buffer_free(&buf);
2333 return ret;
2336 typedef struct {
2337 epan_dissect_t edt;
2338 column_info *cinfo;
2339 } retap_callback_args_t;
2341 static bool
2342 retap_packet(capture_file *cf, frame_data *fdata, wtap_rec *rec, Buffer *buf,
2343 void *argsp)
2345 retap_callback_args_t *args = (retap_callback_args_t *)argsp;
2347 epan_dissect_run_with_taps(&args->edt, cf->cd_t, rec,
2348 frame_tvbuff_new_buffer(&cf->provider, fdata, buf),
2349 fdata, args->cinfo);
2350 epan_dissect_reset(&args->edt);
2352 return true;
2355 cf_read_status_t
2356 cf_retap_packets(capture_file *cf)
2358 packet_range_t range;
2359 retap_callback_args_t callback_args;
2360 bool create_proto_tree;
2361 bool filtering_tap_listeners;
2362 unsigned tap_flags;
2363 psp_return_t ret;
2365 /* Presumably the user closed the capture file. */
2366 if (cf == NULL) {
2367 return CF_READ_ABORTED;
2370 /* XXX - If cf->read_lock is true, process_specified_records will fail
2371 * due to a nested call. We fail here so that we don't reset the tap
2372 * listeners if this tap isn't going to succeed.
2374 if (cf->read_lock) {
2375 ws_warning("Failing due to nested process_specified_records(\"%s\") call!", cf->filename);
2376 return CF_READ_ERROR;
2379 cf_callback_invoke(cf_cb_file_retap_started, cf);
2381 /* Do we have any tap listeners with filters? */
2382 filtering_tap_listeners = have_filtering_tap_listeners();
2384 /* Update references in filters (if any) for the protocol
2385 * tree corresponding to the currently selected frame in the GUI. */
2386 /* XXX - What if we *don't* have a currently selected frame in the GUI,
2387 * but we did the last time we loaded field references? Then they'll
2388 * match something instead of nothing (unless they've been recompiled).
2389 * Should we have a way to clear the field references even with a NULL tree?
2391 if (cf->edt != NULL && cf->edt->tree != NULL) {
2392 if (filtering_tap_listeners)
2393 tap_listeners_load_field_references(cf->edt);
2396 /* Get the union of the flags for all tap listeners. */
2397 tap_flags = union_of_tap_listener_flags();
2399 /* If any tap listeners require the columns, construct them. */
2400 callback_args.cinfo = (tap_listeners_require_columns()) ? &cf->cinfo : NULL;
2403 * Determine whether we need to create a protocol tree.
2404 * We do if:
2406 * one of the tap listeners is going to apply a filter;
2408 * one of the tap listeners requires a protocol tree.
2410 create_proto_tree =
2411 (filtering_tap_listeners || (tap_flags & TL_REQUIRES_PROTO_TREE));
2413 /* Reset the tap listeners. */
2414 reset_tap_listeners();
2415 uint32_t count = cf->count;
2417 epan_dissect_init(&callback_args.edt, cf->epan, create_proto_tree, false);
2419 /* Iterate through the list of packets, dissecting all packets and
2420 re-running the taps. */
2421 packet_range_init(&range, cf);
2422 packet_range_process_init(&range);
2424 if (cf->state == FILE_READ_IN_PROGRESS) {
2425 /* We're not done with the sequential read of the file and might
2426 * add more frames while process_specified_records is going. We
2427 * don't want to tap new frames twice, so limit the range to the
2428 * frames already here.
2430 * cf_read sets read_lock so we don't tap in case of an offline
2431 * file, but cf_continue_tail and cf_finish_tail don't, and we
2432 * don't want them to, because tapping new packets in a live
2433 * capture is a common use case.
2435 * Note that most other users of process_specified_records (saving,
2436 * printing) do want to process new packets, unlike taps.
2438 if (count) {
2439 char* range_str = g_strdup_printf("-%u", count);
2440 packet_range_convert_str(&range, range_str);
2441 g_free(range_str);
2442 } else {
2443 /* range_t treats a missing number as meaning 1, not 0, and
2444 * reverses the order if backwards; thus the syntax -0 means
2445 * 0-1, so to only take zero packets we do this.
2447 packet_range_convert_str(&range, "0");
2449 range.process = range_process_user_range;
2452 ret = process_specified_records(cf, &range, "Recalculating statistics on",
2453 "all packets", true, retap_packet,
2454 &callback_args, true);
2456 packet_range_cleanup(&range);
2457 epan_dissect_cleanup(&callback_args.edt);
2459 cf_callback_invoke(cf_cb_file_retap_finished, cf);
2461 switch (ret) {
2462 case PSP_FINISHED:
2463 /* Completed successfully. */
2464 return CF_READ_OK;
2466 case PSP_STOPPED:
2467 /* Well, the user decided to abort the refiltering.
2468 Return CF_READ_ABORTED so our caller knows they did that. */
2469 return CF_READ_ABORTED;
2471 case PSP_FAILED:
2472 /* Error while retapping. */
2473 return CF_READ_ERROR;
2476 ws_assert_not_reached();
2477 return CF_READ_OK;
2480 typedef struct {
2481 print_args_t *print_args;
2482 bool print_header_line;
2483 char *header_line_buf;
2484 int header_line_buf_len;
2485 bool print_formfeed;
2486 bool print_separator;
2487 char *line_buf;
2488 int line_buf_len;
2489 int *col_widths;
2490 int num_visible_cols;
2491 int *visible_cols;
2492 epan_dissect_t edt;
2493 } print_callback_args_t;
2495 static bool
2496 print_packet(capture_file *cf, frame_data *fdata, wtap_rec *rec, Buffer *buf,
2497 void *argsp)
2499 print_callback_args_t *args = (print_callback_args_t *)argsp;
2500 int i;
2501 char *cp;
2502 int line_len;
2503 int column_len;
2504 int cp_off;
2505 char bookmark_name[9+10+1]; /* "__frameNNNNNNNNNN__\0" */
2506 char bookmark_title[6+10+1]; /* "Frame NNNNNNNNNN__\0" */
2507 col_item_t* col_item;
2508 const char* col_text;
2510 /* Fill in the column information if we're printing the summary
2511 information. */
2512 if (args->print_args->print_summary) {
2513 col_custom_prime_edt(&args->edt, &cf->cinfo);
2514 epan_dissect_run(&args->edt, cf->cd_t, rec,
2515 frame_tvbuff_new_buffer(&cf->provider, fdata, buf),
2516 fdata, &cf->cinfo);
2517 epan_dissect_fill_in_columns(&args->edt, false, true);
2518 } else
2519 epan_dissect_run(&args->edt, cf->cd_t, rec,
2520 frame_tvbuff_new_buffer(&cf->provider, fdata, buf),
2521 fdata, NULL);
2523 if (args->print_formfeed) {
2524 if (!new_page(args->print_args->stream))
2525 goto fail;
2528 * Print another header line if we print a packet summary on the
2529 * new page.
2531 if (args->print_args->print_col_headings)
2532 args->print_header_line = true;
2533 } else {
2534 if (args->print_separator) {
2535 if (!print_line(args->print_args->stream, 0, ""))
2536 goto fail;
2541 * We generate bookmarks, if the output format supports them.
2542 * The name is "__frameN__".
2544 snprintf(bookmark_name, sizeof bookmark_name, "__frame%u__", fdata->num);
2546 if (args->print_args->print_summary) {
2547 if (!args->print_args->print_col_headings)
2548 args->print_header_line = false;
2549 if (args->print_header_line) {
2550 if (!print_line(args->print_args->stream, 0, args->header_line_buf))
2551 goto fail;
2552 args->print_header_line = false; /* we might not need to print any more */
2554 cp = &args->line_buf[0];
2555 line_len = 0;
2556 for (i = 0; i < args->num_visible_cols; i++) {
2557 col_item = &cf->cinfo.columns[args->visible_cols[i]];
2558 col_text = get_column_text(&cf->cinfo, args->visible_cols[i]);
2559 /* Find the length of the string for this column. */
2560 column_len = (int) strlen(col_text);
2561 if (args->col_widths[i] > column_len)
2562 column_len = args->col_widths[i];
2564 /* Make sure there's room in the line buffer for the column; if not,
2565 double its length. */
2566 line_len += column_len + 1; /* "+1" for space */
2567 if (line_len > args->line_buf_len) {
2568 cp_off = (int) (cp - args->line_buf);
2569 args->line_buf_len = 2 * line_len;
2570 args->line_buf = (char *)g_realloc(args->line_buf, args->line_buf_len + 1);
2571 cp = args->line_buf + cp_off;
2574 /* Right-justify the packet number column. */
2575 if (col_item->col_fmt == COL_NUMBER)
2576 snprintf(cp, column_len+1, "%*s", args->col_widths[i], col_text);
2577 else
2578 snprintf(cp, column_len+1, "%-*s", args->col_widths[i], col_text);
2579 cp += column_len;
2580 if (i != args->num_visible_cols - 1)
2581 *cp++ = ' ';
2583 *cp = '\0';
2586 * Generate a bookmark, using the summary line as the title.
2588 if (!print_bookmark(args->print_args->stream, bookmark_name,
2589 args->line_buf))
2590 goto fail;
2592 if (!print_line(args->print_args->stream, 0, args->line_buf))
2593 goto fail;
2594 } else {
2596 * Generate a bookmark, using "Frame N" as the title, as we're not
2597 * printing the summary line.
2599 snprintf(bookmark_title, sizeof bookmark_title, "Frame %u", fdata->num);
2600 if (!print_bookmark(args->print_args->stream, bookmark_name,
2601 bookmark_title))
2602 goto fail;
2603 } /* if (print_summary) */
2605 if (args->print_args->print_dissections != print_dissections_none) {
2606 if (args->print_args->print_summary) {
2607 /* Separate the summary line from the tree with a blank line. */
2608 if (!print_line(args->print_args->stream, 0, ""))
2609 goto fail;
2612 /* Print the information in that tree. */
2613 if (!proto_tree_print(args->print_args->print_dissections,
2614 args->print_args->print_hex, &args->edt, NULL,
2615 args->print_args->stream))
2616 goto fail;
2618 /* Print a blank line if we print anything after this (aka more than one packet). */
2619 args->print_separator = true;
2621 /* Print a header line if we print any more packet summaries */
2622 if (args->print_args->print_col_headings)
2623 args->print_header_line = true;
2626 if (args->print_args->print_hex) {
2627 if (args->print_args->print_summary || (args->print_args->print_dissections != print_dissections_none)) {
2628 if (!print_line(args->print_args->stream, 0, ""))
2629 goto fail;
2631 /* Print the full packet data as hex. */
2632 if (!print_hex_data(args->print_args->stream, &args->edt, args->print_args->hexdump_options))
2633 goto fail;
2635 /* Print a blank line if we print anything after this (aka more than one packet). */
2636 args->print_separator = true;
2638 /* Print a header line if we print any more packet summaries */
2639 if (args->print_args->print_col_headings)
2640 args->print_header_line = true;
2641 } /* if (args->print_args->print_dissections != print_dissections_none) */
2643 epan_dissect_reset(&args->edt);
2645 /* do we want to have a formfeed between each packet from now on? */
2646 if (args->print_args->print_formfeed) {
2647 args->print_formfeed = true;
2650 return true;
2652 fail:
2653 epan_dissect_reset(&args->edt);
2654 return false;
2657 cf_print_status_t
2658 cf_print_packets(capture_file *cf, print_args_t *print_args,
2659 bool show_progress_bar)
2661 print_callback_args_t callback_args;
2662 int data_width;
2663 char *cp;
2664 int i, cp_off, column_len, line_len;
2665 int num_visible_col = 0, last_visible_col = 0, visible_col_count;
2666 psp_return_t ret;
2667 GList *clp;
2668 fmt_data *cfmt;
2669 bool proto_tree_needed;
2671 callback_args.print_args = print_args;
2672 callback_args.print_header_line = print_args->print_col_headings;
2673 callback_args.header_line_buf = NULL;
2674 callback_args.header_line_buf_len = 256;
2675 callback_args.print_formfeed = false;
2676 callback_args.print_separator = false;
2677 callback_args.line_buf = NULL;
2678 callback_args.line_buf_len = 256;
2679 callback_args.col_widths = NULL;
2680 callback_args.num_visible_cols = 0;
2681 callback_args.visible_cols = NULL;
2683 if (!print_preamble(print_args->stream, cf->filename, get_ws_vcs_version_info())) {
2684 destroy_print_stream(print_args->stream);
2685 return CF_PRINT_WRITE_ERROR;
2688 if (print_args->print_summary) {
2689 /* We're printing packet summaries. Allocate the header line buffer
2690 and get the column widths. */
2691 callback_args.header_line_buf = (char *)g_malloc(callback_args.header_line_buf_len + 1);
2693 /* Find the number of visible columns and the last visible column */
2694 for (i = 0; i < prefs.num_cols; i++) {
2696 clp = g_list_nth(prefs.col_list, i);
2697 if (clp == NULL) /* Sanity check, Invalid column requested */
2698 continue;
2700 cfmt = (fmt_data *) clp->data;
2701 if (cfmt->visible) {
2702 num_visible_col++;
2703 last_visible_col = i;
2707 /* if num_visible_col is 0, we are done */
2708 if (num_visible_col == 0) {
2709 g_free(callback_args.header_line_buf);
2710 return CF_PRINT_OK;
2713 /* Find the widths for each of the columns - maximum of the
2714 width of the title and the width of the data - and construct
2715 a buffer with a line containing the column titles. */
2716 callback_args.num_visible_cols = num_visible_col;
2717 callback_args.col_widths = g_new(int, num_visible_col);
2718 callback_args.visible_cols = g_new(int, num_visible_col);
2719 cp = &callback_args.header_line_buf[0];
2720 line_len = 0;
2721 visible_col_count = 0;
2722 for (i = 0; i < cf->cinfo.num_cols; i++) {
2724 clp = g_list_nth(prefs.col_list, i);
2725 if (clp == NULL) /* Sanity check, Invalid column requested */
2726 continue;
2728 cfmt = (fmt_data *) clp->data;
2729 if (cfmt->visible == false)
2730 continue;
2732 /* Save the order of visible columns */
2733 callback_args.visible_cols[visible_col_count] = i;
2735 /* Don't pad the last column. */
2736 if (i == last_visible_col)
2737 callback_args.col_widths[visible_col_count] = 0;
2738 else {
2739 callback_args.col_widths[visible_col_count] = (int) strlen(cf->cinfo.columns[i].col_title);
2740 data_width = get_column_char_width(get_column_format(i));
2741 if (data_width > callback_args.col_widths[visible_col_count])
2742 callback_args.col_widths[visible_col_count] = data_width;
2745 /* Find the length of the string for this column. */
2746 column_len = (int) strlen(cf->cinfo.columns[i].col_title);
2747 if (callback_args.col_widths[visible_col_count] > column_len)
2748 column_len = callback_args.col_widths[visible_col_count];
2750 /* Make sure there's room in the line buffer for the column; if not,
2751 double its length. */
2752 line_len += column_len + 1; /* "+1" for space */
2753 if (line_len > callback_args.header_line_buf_len) {
2754 cp_off = (int) (cp - callback_args.header_line_buf);
2755 callback_args.header_line_buf_len = 2 * line_len;
2756 callback_args.header_line_buf = (char *)g_realloc(callback_args.header_line_buf,
2757 callback_args.header_line_buf_len + 1);
2758 cp = callback_args.header_line_buf + cp_off;
2761 /* Right-justify the packet number column. */
2762 /* if (cf->cinfo.col_fmt[i] == COL_NUMBER)
2763 snprintf(cp, column_len+1, "%*s", callback_args.col_widths[visible_col_count], cf->cinfo.columns[i].col_title);
2764 else*/
2765 snprintf(cp, column_len+1, "%-*s", callback_args.col_widths[visible_col_count], cf->cinfo.columns[i].col_title);
2766 cp += column_len;
2767 if (i != cf->cinfo.num_cols - 1)
2768 *cp++ = ' ';
2770 visible_col_count++;
2772 *cp = '\0';
2774 /* Now start out the main line buffer with the same length as the
2775 header line buffer. */
2776 callback_args.line_buf_len = callback_args.header_line_buf_len;
2777 callback_args.line_buf = (char *)g_malloc(callback_args.line_buf_len + 1);
2778 } /* if (print_summary) */
2780 /* Create the protocol tree, and make it visible, if we're printing
2781 the dissection or the hex data.
2782 XXX - do we need it if we're just printing the hex data? */
2783 proto_tree_needed =
2784 callback_args.print_args->print_dissections != print_dissections_none ||
2785 callback_args.print_args->print_hex ||
2786 have_custom_cols(&cf->cinfo) || have_field_extractors();
2787 epan_dissect_init(&callback_args.edt, cf->epan, proto_tree_needed, proto_tree_needed);
2789 /* Iterate through the list of packets, printing the packets we were
2790 told to print. */
2791 ret = process_specified_records(cf, &print_args->range, "Printing",
2792 "selected packets", true, print_packet,
2793 &callback_args, show_progress_bar);
2794 epan_dissect_cleanup(&callback_args.edt);
2795 g_free(callback_args.header_line_buf);
2796 g_free(callback_args.line_buf);
2797 g_free(callback_args.col_widths);
2798 g_free(callback_args.visible_cols);
2800 switch (ret) {
2802 case PSP_FINISHED:
2803 /* Completed successfully. */
2804 break;
2806 case PSP_STOPPED:
2807 /* Well, the user decided to abort the printing.
2809 XXX - note that what got generated before they did that
2810 will get printed if we're piping to a print program; we'd
2811 have to write to a file and then hand that to the print
2812 program to make it actually not print anything. */
2813 break;
2815 case PSP_FAILED:
2816 /* Error while printing.
2818 XXX - note that what got generated before they did that
2819 will get printed if we're piping to a print program; we'd
2820 have to write to a file and then hand that to the print
2821 program to make it actually not print anything. */
2822 destroy_print_stream(print_args->stream);
2823 return CF_PRINT_WRITE_ERROR;
2826 if (!print_finale(print_args->stream)) {
2827 destroy_print_stream(print_args->stream);
2828 return CF_PRINT_WRITE_ERROR;
2831 if (!destroy_print_stream(print_args->stream))
2832 return CF_PRINT_WRITE_ERROR;
2834 return CF_PRINT_OK;
2837 typedef struct {
2838 FILE *fh;
2839 epan_dissect_t edt;
2840 print_args_t *print_args;
2841 json_dumper jdumper;
2842 } write_packet_callback_args_t;
2844 static bool
2845 write_pdml_packet(capture_file *cf, frame_data *fdata, wtap_rec *rec,
2846 Buffer *buf, void *argsp)
2848 write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
2850 /* Create the protocol tree, but don't fill in the column information. */
2851 epan_dissect_run(&args->edt, cf->cd_t, rec,
2852 frame_tvbuff_new_buffer(&cf->provider, fdata, buf),
2853 fdata, NULL);
2855 /* Write out the information in that tree. */
2856 write_pdml_proto_tree(NULL, &args->edt, &cf->cinfo, args->fh, false);
2858 epan_dissect_reset(&args->edt);
2860 return !ferror(args->fh);
2863 cf_print_status_t
2864 cf_write_pdml_packets(capture_file *cf, print_args_t *print_args)
2866 write_packet_callback_args_t callback_args;
2867 FILE *fh;
2868 psp_return_t ret;
2870 fh = ws_fopen(print_args->file, "w");
2871 if (fh == NULL)
2872 return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2874 write_pdml_preamble(fh, cf->filename);
2875 if (ferror(fh)) {
2876 fclose(fh);
2877 return CF_PRINT_WRITE_ERROR;
2880 callback_args.fh = fh;
2881 callback_args.print_args = print_args;
2882 epan_dissect_init(&callback_args.edt, cf->epan, true, true);
2884 /* Iterate through the list of packets, printing the packets we were
2885 told to print. */
2886 ret = process_specified_records(cf, &print_args->range, "Writing PDML",
2887 "selected packets", true,
2888 write_pdml_packet, &callback_args, true);
2890 epan_dissect_cleanup(&callback_args.edt);
2892 switch (ret) {
2894 case PSP_FINISHED:
2895 /* Completed successfully. */
2896 break;
2898 case PSP_STOPPED:
2899 /* Well, the user decided to abort the printing. */
2900 break;
2902 case PSP_FAILED:
2903 /* Error while printing. */
2904 fclose(fh);
2905 return CF_PRINT_WRITE_ERROR;
2908 write_pdml_finale(fh);
2909 if (ferror(fh)) {
2910 fclose(fh);
2911 return CF_PRINT_WRITE_ERROR;
2914 /* XXX - check for an error */
2915 fclose(fh);
2917 return CF_PRINT_OK;
2920 static bool
2921 write_psml_packet(capture_file *cf, frame_data *fdata, wtap_rec *rec,
2922 Buffer *buf, void *argsp)
2924 write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
2926 /* Fill in the column information */
2927 col_custom_prime_edt(&args->edt, &cf->cinfo);
2928 epan_dissect_run(&args->edt, cf->cd_t, rec,
2929 frame_tvbuff_new_buffer(&cf->provider, fdata, buf),
2930 fdata, &cf->cinfo);
2931 epan_dissect_fill_in_columns(&args->edt, false, true);
2933 /* Write out the column information. */
2934 write_psml_columns(&args->edt, args->fh, false);
2936 epan_dissect_reset(&args->edt);
2938 return !ferror(args->fh);
2941 cf_print_status_t
2942 cf_write_psml_packets(capture_file *cf, print_args_t *print_args)
2944 write_packet_callback_args_t callback_args;
2945 FILE *fh;
2946 psp_return_t ret;
2948 bool proto_tree_needed;
2950 fh = ws_fopen(print_args->file, "w");
2951 if (fh == NULL)
2952 return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2954 write_psml_preamble(&cf->cinfo, fh);
2955 if (ferror(fh)) {
2956 fclose(fh);
2957 return CF_PRINT_WRITE_ERROR;
2960 callback_args.fh = fh;
2961 callback_args.print_args = print_args;
2963 /* Fill in the column information, only create the protocol tree
2964 if having custom columns or field extractors. */
2965 proto_tree_needed = have_custom_cols(&cf->cinfo) || have_field_extractors();
2966 epan_dissect_init(&callback_args.edt, cf->epan, proto_tree_needed, proto_tree_needed);
2968 /* Iterate through the list of packets, printing the packets we were
2969 told to print. */
2970 ret = process_specified_records(cf, &print_args->range, "Writing PSML",
2971 "selected packets", true,
2972 write_psml_packet, &callback_args, true);
2974 epan_dissect_cleanup(&callback_args.edt);
2976 switch (ret) {
2978 case PSP_FINISHED:
2979 /* Completed successfully. */
2980 break;
2982 case PSP_STOPPED:
2983 /* Well, the user decided to abort the printing. */
2984 break;
2986 case PSP_FAILED:
2987 /* Error while printing. */
2988 fclose(fh);
2989 return CF_PRINT_WRITE_ERROR;
2992 write_psml_finale(fh);
2993 if (ferror(fh)) {
2994 fclose(fh);
2995 return CF_PRINT_WRITE_ERROR;
2998 /* XXX - check for an error */
2999 fclose(fh);
3001 return CF_PRINT_OK;
3004 static bool
3005 write_csv_packet(capture_file *cf, frame_data *fdata, wtap_rec *rec,
3006 Buffer *buf, void *argsp)
3008 write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
3010 /* Fill in the column information */
3011 col_custom_prime_edt(&args->edt, &cf->cinfo);
3012 epan_dissect_run(&args->edt, cf->cd_t, rec,
3013 frame_tvbuff_new_buffer(&cf->provider, fdata, buf),
3014 fdata, &cf->cinfo);
3015 epan_dissect_fill_in_columns(&args->edt, false, true);
3017 /* Write out the column information. */
3018 write_csv_columns(&args->edt, args->fh);
3020 epan_dissect_reset(&args->edt);
3022 return !ferror(args->fh);
3025 cf_print_status_t
3026 cf_write_csv_packets(capture_file *cf, print_args_t *print_args)
3028 write_packet_callback_args_t callback_args;
3029 bool proto_tree_needed;
3030 FILE *fh;
3031 psp_return_t ret;
3033 fh = ws_fopen(print_args->file, "w");
3034 if (fh == NULL)
3035 return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
3037 write_csv_column_titles(&cf->cinfo, fh);
3038 if (ferror(fh)) {
3039 fclose(fh);
3040 return CF_PRINT_WRITE_ERROR;
3043 callback_args.fh = fh;
3044 callback_args.print_args = print_args;
3046 /* only create the protocol tree if having custom columns or field extractors. */
3047 proto_tree_needed = have_custom_cols(&cf->cinfo) || have_field_extractors();
3048 epan_dissect_init(&callback_args.edt, cf->epan, proto_tree_needed, proto_tree_needed);
3050 /* Iterate through the list of packets, printing the packets we were
3051 told to print. */
3052 ret = process_specified_records(cf, &print_args->range, "Writing CSV",
3053 "selected packets", true,
3054 write_csv_packet, &callback_args, true);
3056 epan_dissect_cleanup(&callback_args.edt);
3058 switch (ret) {
3060 case PSP_FINISHED:
3061 /* Completed successfully. */
3062 break;
3064 case PSP_STOPPED:
3065 /* Well, the user decided to abort the printing. */
3066 break;
3068 case PSP_FAILED:
3069 /* Error while printing. */
3070 fclose(fh);
3071 return CF_PRINT_WRITE_ERROR;
3074 /* XXX - check for an error */
3075 fclose(fh);
3077 return CF_PRINT_OK;
3080 static bool
3081 carrays_write_packet(capture_file *cf, frame_data *fdata, wtap_rec *rec,
3082 Buffer *buf, void *argsp)
3084 write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
3086 epan_dissect_run(&args->edt, cf->cd_t, rec,
3087 frame_tvbuff_new_buffer(&cf->provider, fdata, buf),
3088 fdata, NULL);
3089 write_carrays_hex_data(fdata->num, args->fh, &args->edt);
3090 epan_dissect_reset(&args->edt);
3092 return !ferror(args->fh);
3095 cf_print_status_t
3096 cf_write_carrays_packets(capture_file *cf, print_args_t *print_args)
3098 write_packet_callback_args_t callback_args;
3099 FILE *fh;
3100 psp_return_t ret;
3102 fh = ws_fopen(print_args->file, "w");
3104 if (fh == NULL)
3105 return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
3107 if (ferror(fh)) {
3108 fclose(fh);
3109 return CF_PRINT_WRITE_ERROR;
3112 callback_args.fh = fh;
3113 callback_args.print_args = print_args;
3114 epan_dissect_init(&callback_args.edt, cf->epan, true, true);
3116 /* Iterate through the list of packets, printing the packets we were
3117 told to print. */
3118 ret = process_specified_records(cf, &print_args->range,
3119 "Writing C Arrays",
3120 "selected packets", true,
3121 carrays_write_packet, &callback_args, true);
3123 epan_dissect_cleanup(&callback_args.edt);
3125 switch (ret) {
3126 case PSP_FINISHED:
3127 /* Completed successfully. */
3128 break;
3129 case PSP_STOPPED:
3130 /* Well, the user decided to abort the printing. */
3131 break;
3132 case PSP_FAILED:
3133 /* Error while printing. */
3134 fclose(fh);
3135 return CF_PRINT_WRITE_ERROR;
3138 fclose(fh);
3139 return CF_PRINT_OK;
3142 static bool
3143 write_json_packet(capture_file *cf, frame_data *fdata, wtap_rec *rec,
3144 Buffer *buf, void *argsp)
3146 write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
3148 /* Create the protocol tree, but don't fill in the column information. */
3149 epan_dissect_run(&args->edt, cf->cd_t, rec,
3150 frame_tvbuff_new_buffer(&cf->provider, fdata, buf),
3151 fdata, NULL);
3153 /* Write out the information in that tree. */
3154 write_json_proto_tree(NULL, args->print_args->print_dissections,
3155 args->print_args->print_hex,
3156 &args->edt, &cf->cinfo, proto_node_group_children_by_unique,
3157 &args->jdumper);
3159 epan_dissect_reset(&args->edt);
3161 return !ferror(args->fh);
3164 cf_print_status_t
3165 cf_write_json_packets(capture_file *cf, print_args_t *print_args)
3167 write_packet_callback_args_t callback_args;
3168 FILE *fh;
3169 psp_return_t ret;
3171 fh = ws_fopen(print_args->file, "w");
3172 if (fh == NULL)
3173 return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
3175 callback_args.jdumper = write_json_preamble(fh);
3176 if (ferror(fh)) {
3177 fclose(fh);
3178 return CF_PRINT_WRITE_ERROR;
3181 callback_args.fh = fh;
3182 callback_args.print_args = print_args;
3183 epan_dissect_init(&callback_args.edt, cf->epan, true, true);
3185 /* Iterate through the list of packets, printing the packets we were
3186 told to print. */
3187 ret = process_specified_records(cf, &print_args->range, "Writing JSON",
3188 "selected packets", true,
3189 write_json_packet, &callback_args, true);
3191 epan_dissect_cleanup(&callback_args.edt);
3193 switch (ret) {
3195 case PSP_FINISHED:
3196 /* Completed successfully. */
3197 break;
3199 case PSP_STOPPED:
3200 /* Well, the user decided to abort the printing. */
3201 break;
3203 case PSP_FAILED:
3204 /* Error while printing. */
3205 fclose(fh);
3206 return CF_PRINT_WRITE_ERROR;
3209 write_json_finale(&callback_args.jdumper);
3210 if (ferror(fh)) {
3211 fclose(fh);
3212 return CF_PRINT_WRITE_ERROR;
3215 /* XXX - check for an error */
3216 fclose(fh);
3218 return CF_PRINT_OK;
3221 bool
3222 cf_find_packet_protocol_tree(capture_file *cf, const char *string,
3223 search_direction dir, bool multiple)
3225 match_data mdata;
3227 mdata.frame_matched = false;
3228 mdata.halt = false;
3229 mdata.string = string;
3230 mdata.string_len = strlen(string);
3231 mdata.cf = cf;
3232 mdata.prev_finfo = cf->finfo_selected;
3233 if (multiple && cf->finfo_selected && cf->edt) {
3234 if (dir == SD_FORWARD) {
3235 proto_tree_children_foreach(cf->edt->tree, match_subtree_text, &mdata);
3236 } else {
3237 proto_tree_children_foreach(cf->edt->tree, match_subtree_text_reverse, &mdata);
3239 if (mdata.frame_matched) {
3240 packet_list_select_finfo(mdata.finfo);
3241 return true;
3244 return find_packet(cf, match_protocol_tree, &mdata, dir);
3247 field_info*
3248 cf_find_string_protocol_tree(capture_file *cf, proto_tree *tree)
3250 match_data mdata;
3251 mdata.frame_matched = false;
3252 mdata.halt = false;
3253 mdata.string = convert_string_case(cf->sfilter, cf->case_type);
3254 mdata.string_len = strlen(mdata.string);
3255 mdata.cf = cf;
3256 mdata.prev_finfo = NULL;
3257 /* Iterate through all the nodes looking for matching text */
3258 if (cf->dir == SD_FORWARD) {
3259 proto_tree_children_foreach(tree, match_subtree_text, &mdata);
3260 } else {
3261 proto_tree_children_foreach(tree, match_subtree_text_reverse, &mdata);
3263 g_free((char *)mdata.string);
3264 return mdata.frame_matched ? mdata.finfo : NULL;
3267 static match_result
3268 match_protocol_tree(capture_file *cf, frame_data *fdata,
3269 wtap_rec *rec, Buffer *buf, void *criterion)
3271 match_data *mdata = (match_data *)criterion;
3272 epan_dissect_t edt;
3274 /* Load the frame's data. */
3275 if (!cf_read_record(cf, fdata, rec, buf)) {
3276 /* Attempt to get the packet failed. */
3277 return MR_ERROR;
3280 /* Construct the protocol tree, including the displayed text */
3281 epan_dissect_init(&edt, cf->epan, true, true);
3282 /* We don't need the column information */
3283 epan_dissect_run(&edt, cf->cd_t, rec,
3284 frame_tvbuff_new_buffer(&cf->provider, fdata, buf),
3285 fdata, NULL);
3287 /* Iterate through all the nodes, seeing if they have text that matches. */
3288 mdata->cf = cf;
3289 mdata->frame_matched = false;
3290 mdata->halt = false;
3291 mdata->prev_finfo = NULL;
3292 /* We don't care about the direction here, because we're just looking
3293 * for one match and we'll destroy this tree anyway. (We find the actual
3294 * field later in PacketList::selectionChanged().) Forwards is faster.
3296 proto_tree_children_foreach(edt.tree, match_subtree_text, mdata);
3297 epan_dissect_cleanup(&edt);
3298 return mdata->frame_matched ? MR_MATCHED : MR_NOTMATCHED;
3301 static void
3302 match_subtree_text(proto_node *node, void *data)
3304 match_data *mdata = (match_data *) data;
3305 const char *string = mdata->string;
3306 size_t string_len = mdata->string_len;
3307 capture_file *cf = mdata->cf;
3308 field_info *fi = PNODE_FINFO(node);
3309 char label_str[ITEM_LABEL_LENGTH];
3310 char *label_ptr;
3311 size_t label_len;
3312 uint32_t i, i_restart;
3313 uint8_t c_char;
3314 size_t c_match = 0;
3316 /* dissection with an invisible proto tree? */
3317 ws_assert(fi);
3319 if (mdata->frame_matched) {
3320 /* We already had a match; don't bother doing any more work. */
3321 return;
3324 /* Don't match invisible entries. */
3325 if (proto_item_is_hidden(node))
3326 return;
3328 if (mdata->prev_finfo) {
3329 /* Haven't found the old match, so don't match this node. */
3330 if (fi == mdata->prev_finfo) {
3331 /* Found the old match, look for the next one after this. */
3332 mdata->prev_finfo = NULL;
3334 } else {
3335 /* was a free format label produced? */
3336 if (fi->rep) {
3337 label_ptr = fi->rep->representation;
3338 } else {
3339 /* no, make a generic label */
3340 label_ptr = label_str;
3341 proto_item_fill_label(fi, label_str);
3344 if (cf->regex) {
3345 if (ws_regex_matches(cf->regex, label_ptr)) {
3346 mdata->frame_matched = true;
3347 mdata->finfo = fi;
3348 return;
3350 } else if (cf->case_type) {
3351 /* Case insensitive match */
3352 label_len = strlen(label_ptr);
3353 i_restart = 0;
3354 for (i = 0; i < label_len; i++) {
3355 if (i_restart == 0 && c_match == 0 && (label_len - i < string_len))
3356 break;
3357 c_char = label_ptr[i];
3358 c_char = g_ascii_toupper(c_char);
3359 /* If c_match is non-zero, save candidate for retrying full match. */
3360 if (c_match > 0 && i_restart == 0 && c_char == string[0])
3361 i_restart = i;
3362 if (c_char == string[c_match]) {
3363 c_match++;
3364 if (c_match == string_len) {
3365 mdata->frame_matched = true;
3366 mdata->finfo = fi;
3367 /* No need to look further; we have a match */
3368 return;
3370 } else if (i_restart) {
3371 i = i_restart;
3372 c_match = 1;
3373 i_restart = 0;
3374 } else
3375 c_match = 0;
3377 } else if (strstr(label_ptr, string) != NULL) {
3378 /* Case sensitive match */
3379 mdata->frame_matched = true;
3380 mdata->finfo = fi;
3381 return;
3385 /* Recurse into the subtree, if it exists */
3386 if (node->first_child != NULL)
3387 proto_tree_children_foreach(node, match_subtree_text, mdata);
3390 static void
3391 match_subtree_text_reverse(proto_node *node, void *data)
3393 match_data *mdata = (match_data *) data;
3394 const char *string = mdata->string;
3395 size_t string_len = mdata->string_len;
3396 capture_file *cf = mdata->cf;
3397 field_info *fi = PNODE_FINFO(node);
3398 char label_str[ITEM_LABEL_LENGTH];
3399 char *label_ptr;
3400 size_t label_len;
3401 uint32_t i, i_restart;
3402 uint8_t c_char;
3403 size_t c_match = 0;
3405 /* dissection with an invisible proto tree? */
3406 ws_assert(fi);
3408 /* We don't have an easy way to search backwards in the tree
3409 * (see also, proto_find_field_from_offset()) because we don't
3410 * have a previous node pointer, so we search backwards by
3411 * searching forwards, only stopping if we see the old match
3412 * (if we have one).
3415 if (mdata->halt) {
3416 return;
3419 /* Don't match invisible entries. */
3420 if (proto_item_is_hidden(node))
3421 return;
3423 if (mdata->prev_finfo && fi == mdata->prev_finfo) {
3424 /* Found the old match, use the previous match. */
3425 mdata->halt = true;
3426 return;
3429 /* was a free format label produced? */
3430 if (fi->rep) {
3431 label_ptr = fi->rep->representation;
3432 } else {
3433 /* no, make a generic label */
3434 label_ptr = label_str;
3435 proto_item_fill_label(fi, label_str);
3438 if (cf->regex) {
3439 if (ws_regex_matches(cf->regex, label_ptr)) {
3440 mdata->frame_matched = true;
3441 mdata->finfo = fi;
3443 } else if (cf->case_type) {
3444 /* Case insensitive match */
3445 label_len = strlen(label_ptr);
3446 i_restart = 0;
3447 for (i = 0; i < label_len; i++) {
3448 if (i_restart == 0 && c_match == 0 && (label_len - i < string_len))
3449 break;
3450 c_char = label_ptr[i];
3451 c_char = g_ascii_toupper(c_char);
3452 /* If c_match is non-zero, save candidate for retrying full match. */
3453 if (c_match > 0 && i_restart == 0 && c_char == string[0])
3454 i_restart = i;
3455 if (c_char == string[c_match]) {
3456 c_match++;
3457 if (c_match == string_len) {
3458 mdata->frame_matched = true;
3459 mdata->finfo = fi;
3460 break;
3462 } else if (i_restart) {
3463 i = i_restart;
3464 c_match = 1;
3465 i_restart = 0;
3466 } else
3467 c_match = 0;
3469 } else if (strstr(label_ptr, string) != NULL) {
3470 /* Case sensitive match */
3471 mdata->frame_matched = true;
3472 mdata->finfo = fi;
3475 /* Recurse into the subtree, if it exists */
3476 if (node->first_child != NULL)
3477 proto_tree_children_foreach(node, match_subtree_text_reverse, mdata);
3480 bool
3481 cf_find_packet_summary_line(capture_file *cf, const char *string,
3482 search_direction dir)
3484 match_data mdata;
3486 mdata.string = string;
3487 mdata.string_len = strlen(string);
3488 return find_packet(cf, match_summary_line, &mdata, dir);
3491 static match_result
3492 match_summary_line(capture_file *cf, frame_data *fdata,
3493 wtap_rec *rec, Buffer *buf, void *criterion)
3495 match_data *mdata = (match_data *)criterion;
3496 const char *string = mdata->string;
3497 size_t string_len = mdata->string_len;
3498 epan_dissect_t edt;
3499 const char *info_column;
3500 size_t info_column_len;
3501 match_result result = MR_NOTMATCHED;
3502 int colx;
3503 uint32_t i, i_restart;
3504 uint8_t c_char;
3505 size_t c_match = 0;
3507 /* Load the frame's data. */
3508 if (!cf_read_record(cf, fdata, rec, buf)) {
3509 /* Attempt to get the packet failed. */
3510 return MR_ERROR;
3513 /* Don't bother constructing the protocol tree */
3514 epan_dissect_init(&edt, cf->epan, false, false);
3515 /* Get the column information */
3516 epan_dissect_run(&edt, cf->cd_t, rec,
3517 frame_tvbuff_new_buffer(&cf->provider, fdata, buf),
3518 fdata, &cf->cinfo);
3520 /* Find the Info column */
3521 for (colx = 0; colx < cf->cinfo.num_cols; colx++) {
3522 if (cf->cinfo.columns[colx].fmt_matx[COL_INFO]) {
3523 /* Found it. See if we match. */
3524 info_column = get_column_text(edt.pi.cinfo, colx);
3525 info_column_len = strlen(info_column);
3526 if (cf->regex) {
3527 if (ws_regex_matches(cf->regex, info_column)) {
3528 result = MR_MATCHED;
3529 break;
3531 } else if (cf->case_type) {
3532 /* Case insensitive match */
3533 i_restart = 0;
3534 for (i = 0; i < info_column_len; i++) {
3535 if (i_restart == 0 && c_match == 0 && (info_column_len - i < string_len))
3536 break;
3537 c_char = info_column[i];
3538 c_char = g_ascii_toupper(c_char);
3539 /* If c_match is non-zero, save candidate for retrying full match. */
3540 if (c_match > 0 && i_restart == 0 && c_char == string[0])
3541 i_restart = i;
3542 if (c_char == string[c_match]) {
3543 c_match++;
3544 if (c_match == string_len) {
3545 result = MR_MATCHED;
3546 break;
3548 } else if (i_restart) {
3549 i = i_restart;
3550 c_match = 1;
3551 i_restart = 0;
3552 } else
3553 c_match = 0;
3555 } else if (strstr(info_column, string) != NULL) {
3556 /* Case sensitive match */
3557 result = MR_MATCHED;
3559 break;
3562 epan_dissect_cleanup(&edt);
3563 return result;
3566 typedef struct {
3567 const uint8_t *data;
3568 size_t data_len;
3569 ws_mempbrk_pattern *pattern;
3570 } cbs_t; /* "Counted byte string" */
3574 * The current match_* routines only support ASCII case insensitivity and don't
3575 * convert UTF-8 inputs to UTF-16 for matching. The UTF-16 support just
3576 * interleaves with \0 bytes, which works for 7 bit ASCII.
3578 * We could modify them to use the GLib Unicode routines or the International
3579 * Components for Unicode library but it's not apparent that we could do so
3580 * without consuming a lot more CPU and memory or that searching would be
3581 * significantly better.
3583 * XXX: We could test the search string to see if it's all ASCII, and if not
3584 * use Unicode aware routines for case insensitive searches or any UTF-16
3585 * search.
3588 bool
3589 cf_find_packet_data(capture_file *cf, const uint8_t *string, size_t string_size,
3590 search_direction dir, bool multiple)
3592 cbs_t info;
3593 uint8_t needles[3];
3594 ws_mempbrk_pattern pattern = {0};
3595 ws_match_function match_function;
3597 info.data = string;
3598 info.data_len = string_size;
3600 /* Regex, String or hex search? */
3601 if (cf->regex) {
3602 /* Regular Expression search */
3603 match_function = (cf->dir == SD_FORWARD) ? match_regex : match_regex_reverse;
3604 } else if (cf->string) {
3605 /* String search - what type of string? */
3606 if (cf->case_type) {
3607 needles[0] = string[0];
3608 needles[1] = g_ascii_tolower(needles[0]);
3609 needles[2] = '\0';
3610 ws_mempbrk_compile(&pattern, needles);
3611 info.pattern = &pattern;
3612 switch (cf->scs_type) {
3614 case SCS_NARROW_AND_WIDE:
3615 match_function = (cf->dir == SD_FORWARD) ? match_narrow_and_wide_case : match_narrow_and_wide_case_reverse;
3616 break;
3618 case SCS_NARROW:
3619 match_function = (cf->dir == SD_FORWARD) ? match_narrow_case : match_narrow_case_reverse;
3620 break;
3622 case SCS_WIDE:
3623 match_function = (cf->dir == SD_FORWARD) ? match_wide_case : match_wide_case_reverse;
3624 break;
3626 default:
3627 ws_assert_not_reached();
3628 return false;
3631 } else {
3632 switch (cf->scs_type) {
3634 case SCS_NARROW_AND_WIDE:
3635 match_function = (cf->dir == SD_FORWARD) ? match_narrow_and_wide : match_narrow_and_wide_reverse;
3636 break;
3638 case SCS_NARROW:
3639 /* Narrow, case-sensitive match is the same as looking
3640 * for a converted hexstring. */
3641 match_function = (cf->dir == SD_FORWARD) ? match_binary : match_binary_reverse;
3642 break;
3644 case SCS_WIDE:
3645 match_function = (cf->dir == SD_FORWARD) ? match_wide : match_wide_reverse;
3646 break;
3648 default:
3649 ws_assert_not_reached();
3650 return false;
3653 } else {
3654 match_function = (cf->dir == SD_FORWARD) ? match_binary : match_binary_reverse;
3657 if (multiple && cf->current_frame && (cf->search_pos || cf->search_len)) {
3658 /* Use the current frame (this will perform the equivalent of
3659 * cf_read_current_record() in match_function).
3661 if (match_function(cf, cf->current_frame, &cf->rec, &cf->buf, &info)) {
3662 cf->search_in_progress = true;
3663 if (cf->edt) {
3664 field_info *fi = NULL;
3665 /* The regex match can match an empty string. */
3666 if (cf->search_len) {
3667 fi = proto_find_field_from_offset(cf->edt->tree, cf->search_pos + cf->search_len - 1, cf->edt->tvb);
3669 packet_list_select_finfo(fi);
3670 } else {
3671 packet_list_select_row_from_data(cf->current_frame);
3673 cf->search_in_progress = false;
3674 return true;
3677 cf->search_pos = 0; /* Reset the position */
3678 cf->search_len = 0; /* Reset length */
3679 return find_packet(cf, match_function, &info, dir);
3682 static match_result
3683 match_narrow_and_wide(capture_file *cf, frame_data *fdata,
3684 wtap_rec *rec, Buffer *buf, void *criterion)
3686 cbs_t *info = (cbs_t *)criterion;
3687 const uint8_t *ascii_text = info->data;
3688 size_t textlen = info->data_len;
3689 match_result result;
3690 uint32_t buf_len;
3691 uint8_t *pd, *buf_start, *buf_end;
3692 uint32_t i;
3693 uint8_t c_char;
3694 size_t c_match = 0;
3696 /* Load the frame's data. */
3697 if (!cf_read_record(cf, fdata, rec, buf)) {
3698 /* Attempt to get the packet failed. */
3699 return MR_ERROR;
3702 result = MR_NOTMATCHED;
3703 buf_len = fdata->cap_len;
3704 buf_start = ws_buffer_start_ptr(buf);
3705 buf_end = buf_start + buf_len;
3706 pd = buf_start;
3707 if (cf->search_len || cf->search_pos) {
3708 /* we want to start searching one byte past the previous match start */
3709 pd += cf->search_pos + 1;
3711 for (; pd < buf_end; pd++) {
3712 pd = (uint8_t *)memchr(pd, ascii_text[0], buf_end - pd);
3713 if (pd == NULL) break;
3714 /* Try narrow match at this start location */
3715 c_match = 0;
3716 for (i = 0; pd + i < buf_end; i++) {
3717 c_char = pd[i];
3718 if (c_char == ascii_text[c_match]) {
3719 c_match++;
3720 if (c_match == textlen) {
3721 result = MR_MATCHED;
3722 /* Save position and length for highlighting the field. */
3723 cf->search_pos = (uint32_t)(pd - buf_start);
3724 cf->search_len = (uint32_t)(i + 1);
3725 goto done;
3727 } else {
3728 break;
3732 /* Now try wide match at the same start location. */
3733 c_match = 0;
3734 for (i = 0; pd + i < buf_end; i++) {
3735 c_char = pd[i];
3736 if (c_char == ascii_text[c_match]) {
3737 c_match++;
3738 if (c_match == textlen) {
3739 result = MR_MATCHED;
3740 /* Save position and length for highlighting the field. */
3741 cf->search_pos = (uint32_t)(pd - buf_start);
3742 cf->search_len = (uint32_t)(i + 1);
3743 goto done;
3745 i++;
3746 if (pd + i >= buf_end || pd[i] != '\0') break;
3747 } else {
3748 break;
3753 done:
3754 return result;
3757 static match_result
3758 match_narrow_and_wide_reverse(capture_file *cf, frame_data *fdata,
3759 wtap_rec *rec, Buffer *buf, void *criterion)
3761 cbs_t *info = (cbs_t *)criterion;
3762 const uint8_t *ascii_text = info->data;
3763 size_t textlen = info->data_len;
3764 match_result result;
3765 uint32_t buf_len;
3766 uint8_t *pd, *buf_start, *buf_end;
3767 uint32_t i;
3768 uint8_t c_char;
3769 size_t c_match = 0;
3771 /* Load the frame's data. */
3772 if (!cf_read_record(cf, fdata, rec, buf)) {
3773 /* Attempt to get the packet failed. */
3774 return MR_ERROR;
3777 result = MR_NOTMATCHED;
3778 /* Has to be room to hold the sought data. */
3779 if (textlen > fdata->cap_len) {
3780 return result;
3782 buf_len = fdata->cap_len;
3783 buf_start = ws_buffer_start_ptr(buf);
3784 buf_end = buf_start + buf_len;
3785 pd = buf_end - textlen;
3786 if (cf->search_len || cf->search_pos) {
3787 /* we want to start searching one byte before the previous match start */
3788 pd = buf_start + cf->search_pos - 1;
3790 for (; pd < buf_end; pd++) {
3791 pd = (uint8_t *)ws_memrchr(buf_start, ascii_text[0], pd - buf_start + 1);
3792 if (pd == NULL) break;
3793 /* Try narrow match at this start location */
3794 c_match = 0;
3795 for (i = 0; pd + i < buf_end; i++) {
3796 c_char = pd[i];
3797 if (c_char == ascii_text[c_match]) {
3798 c_match++;
3799 if (c_match == textlen) {
3800 result = MR_MATCHED;
3801 /* Save position and length for highlighting the field. */
3802 cf->search_pos = (uint32_t)(pd - buf_start);
3803 cf->search_len = (uint32_t)(i + 1);
3804 goto done;
3806 } else {
3807 break;
3811 /* Now try wide match at the same start location. */
3812 c_match = 0;
3813 for (i = 0; pd + i < buf_end; i++) {
3814 c_char = pd[i];
3815 if (c_char == ascii_text[c_match]) {
3816 c_match++;
3817 if (c_match == textlen) {
3818 result = MR_MATCHED;
3819 /* Save position and length for highlighting the field. */
3820 cf->search_pos = (uint32_t)(pd - buf_start);
3821 cf->search_len = (uint32_t)(i + 1);
3822 goto done;
3824 i++;
3825 if (pd + i >= buf_end || pd[i] != '\0') break;
3826 } else {
3827 break;
3832 done:
3833 return result;
3836 /* Case insensitive match */
3837 static match_result
3838 match_narrow_and_wide_case(capture_file *cf, frame_data *fdata,
3839 wtap_rec *rec, Buffer *buf, void *criterion)
3841 cbs_t *info = (cbs_t *)criterion;
3842 const uint8_t *ascii_text = info->data;
3843 size_t textlen = info->data_len;
3844 ws_mempbrk_pattern *pattern = info->pattern;
3845 match_result result;
3846 uint32_t buf_len;
3847 uint8_t *pd, *buf_start, *buf_end;
3848 uint32_t i;
3849 uint8_t c_char;
3850 size_t c_match = 0;
3852 /* Load the frame's data. */
3853 if (!cf_read_record(cf, fdata, rec, buf)) {
3854 /* Attempt to get the packet failed. */
3855 return MR_ERROR;
3858 ws_assert(pattern != NULL);
3860 result = MR_NOTMATCHED;
3861 buf_len = fdata->cap_len;
3862 buf_start = ws_buffer_start_ptr(buf);
3863 buf_end = buf_start + buf_len;
3864 pd = buf_start;
3865 if (cf->search_len || cf->search_pos) {
3866 /* we want to start searching one byte past the previous match start */
3867 pd += cf->search_pos + 1;
3869 for (; pd < buf_end; pd++) {
3870 pd = (uint8_t *)ws_mempbrk_exec(pd, buf_end - pd, pattern, &c_char);
3871 if (pd == NULL) break;
3872 /* Try narrow match at this start location */
3873 c_match = 0;
3874 for (i = 0; pd + i < buf_end; i++) {
3875 c_char = g_ascii_toupper(pd[i]);
3876 if (c_char == ascii_text[c_match]) {
3877 c_match++;
3878 if (c_match == textlen) {
3879 result = MR_MATCHED;
3880 /* Save position and length for highlighting the field. */
3881 cf->search_pos = (uint32_t)(pd - buf_start);
3882 cf->search_len = (uint32_t)(i + 1);
3883 goto done;
3885 } else {
3886 break;
3890 /* Now try wide match at the same start location. */
3891 c_match = 0;
3892 for (i = 0; pd + i < buf_end; i++) {
3893 c_char = g_ascii_toupper(pd[i]);
3894 if (c_char == ascii_text[c_match]) {
3895 c_match++;
3896 if (c_match == textlen) {
3897 result = MR_MATCHED;
3898 /* Save position and length for highlighting the field. */
3899 cf->search_pos = (uint32_t)(pd - buf_start);
3900 cf->search_len = (uint32_t)(i + 1);
3901 goto done;
3903 i++;
3904 if (pd + i >= buf_end || pd[i] != '\0') break;
3905 } else {
3906 break;
3911 done:
3912 return result;
3915 static match_result
3916 match_narrow_and_wide_case_reverse(capture_file *cf, frame_data *fdata,
3917 wtap_rec *rec, Buffer *buf, void *criterion)
3919 cbs_t *info = (cbs_t *)criterion;
3920 const uint8_t *ascii_text = info->data;
3921 size_t textlen = info->data_len;
3922 ws_mempbrk_pattern *pattern = info->pattern;
3923 match_result result;
3924 uint32_t buf_len;
3925 uint8_t *pd, *buf_start, *buf_end;
3926 uint32_t i;
3927 uint8_t c_char;
3928 size_t c_match = 0;
3930 /* Load the frame's data. */
3931 if (!cf_read_record(cf, fdata, rec, buf)) {
3932 /* Attempt to get the packet failed. */
3933 return MR_ERROR;
3936 ws_assert(pattern != NULL);
3938 result = MR_NOTMATCHED;
3939 /* Has to be room to hold the sought data. */
3940 if (textlen > fdata->cap_len) {
3941 return result;
3943 buf_len = fdata->cap_len;
3944 buf_start = ws_buffer_start_ptr(buf);
3945 buf_end = buf_start + buf_len;
3946 pd = buf_end - textlen;
3947 if (cf->search_len || cf->search_pos) {
3948 /* we want to start searching one byte before the previous match start */
3949 pd = buf_start + cf->search_pos - 1;
3951 for (; pd >= buf_start; pd--) {
3952 pd = (uint8_t *)ws_memrpbrk_exec(buf_start, pd - buf_start + 1, pattern, &c_char);
3953 if (pd == NULL) break;
3954 /* Try narrow match at this start location */
3955 c_match = 0;
3956 for (i = 0; pd + i < buf_end; i++) {
3957 c_char = g_ascii_toupper(pd[i]);
3958 if (c_char == ascii_text[c_match]) {
3959 c_match++;
3960 if (c_match == textlen) {
3961 result = MR_MATCHED;
3962 /* Save position and length for highlighting the field. */
3963 cf->search_pos = (uint32_t)(pd - buf_start);
3964 cf->search_len = (uint32_t)(i + 1);
3965 goto done;
3967 } else {
3968 break;
3972 /* Now try wide match at the same start location. */
3973 c_match = 0;
3974 for (i = 0; pd + i < buf_end; i++) {
3975 c_char = g_ascii_toupper(pd[i]);
3976 if (c_char == ascii_text[c_match]) {
3977 c_match++;
3978 if (c_match == textlen) {
3979 result = MR_MATCHED;
3980 /* Save position and length for highlighting the field. */
3981 cf->search_pos = (uint32_t)(pd - buf_start);
3982 cf->search_len = (uint32_t)(i + 1);
3983 goto done;
3985 i++;
3986 if (pd + i >= buf_end || pd[i] != '\0') break;
3987 } else {
3988 break;
3993 done:
3994 return result;
3997 /* Case insensitive match */
3998 static match_result
3999 match_narrow_case(capture_file *cf, frame_data *fdata,
4000 wtap_rec *rec, Buffer *buf, void *criterion)
4002 cbs_t *info = (cbs_t *)criterion;
4003 const uint8_t *ascii_text = info->data;
4004 size_t textlen = info->data_len;
4005 ws_mempbrk_pattern *pattern = info->pattern;
4006 match_result result;
4007 uint32_t buf_len;
4008 uint8_t *pd, *buf_start, *buf_end;
4009 uint32_t i;
4010 uint8_t c_char;
4011 size_t c_match = 0;
4013 /* Load the frame's data. */
4014 if (!cf_read_record(cf, fdata, rec, buf)) {
4015 /* Attempt to get the packet failed. */
4016 return MR_ERROR;
4019 ws_assert(pattern != NULL);
4021 result = MR_NOTMATCHED;
4022 buf_len = fdata->cap_len;
4023 buf_start = ws_buffer_start_ptr(buf);
4024 buf_end = buf_start + buf_len;
4025 pd = buf_start;
4026 if (cf->search_len || cf->search_pos) {
4027 /* we want to start searching one byte past the previous match start */
4028 pd += cf->search_pos + 1;
4030 for (; pd < buf_end; pd++) {
4031 pd = (uint8_t *)ws_mempbrk_exec(pd, buf_end - pd, pattern, &c_char);
4032 if (pd == NULL) break;
4033 c_match = 0;
4034 for (i = 0; pd + i < buf_end; i++) {
4035 c_char = g_ascii_toupper(pd[i]);
4036 if (c_char == ascii_text[c_match]) {
4037 c_match++;
4038 if (c_match == textlen) {
4039 /* Save position and length for highlighting the field. */
4040 result = MR_MATCHED;
4041 cf->search_pos = (uint32_t)(pd - buf_start);
4042 cf->search_len = (uint32_t)(i + 1);
4043 goto done;
4045 } else {
4046 break;
4051 done:
4052 return result;
4055 static match_result
4056 match_narrow_case_reverse(capture_file *cf, frame_data *fdata,
4057 wtap_rec *rec, Buffer *buf, void *criterion)
4059 cbs_t *info = (cbs_t *)criterion;
4060 const uint8_t *ascii_text = info->data;
4061 size_t textlen = info->data_len;
4062 ws_mempbrk_pattern *pattern = info->pattern;
4063 match_result result;
4064 uint32_t buf_len;
4065 uint8_t *pd, *buf_start, *buf_end;
4066 uint32_t i;
4067 uint8_t c_char;
4068 size_t c_match = 0;
4070 /* Load the frame's data. */
4071 if (!cf_read_record(cf, fdata, rec, buf)) {
4072 /* Attempt to get the packet failed. */
4073 return MR_ERROR;
4076 ws_assert(pattern != NULL);
4078 result = MR_NOTMATCHED;
4079 /* Has to be room to hold the sought data. */
4080 if (textlen > fdata->cap_len) {
4081 return result;
4083 buf_len = fdata->cap_len;
4084 buf_start = ws_buffer_start_ptr(buf);
4085 buf_end = buf_start + buf_len;
4086 pd = buf_end - textlen;
4087 if (cf->search_len || cf->search_pos) {
4088 /* we want to start searching one byte before the previous match start */
4089 pd = buf_start + cf->search_pos - 1;
4091 for (; pd >= buf_start; pd--) {
4092 pd = (uint8_t *)ws_memrpbrk_exec(buf_start, pd - buf_start + 1, pattern, &c_char);
4093 if (pd == NULL) break;
4094 c_match = 0;
4095 for (i = 0; pd + i < buf_end; i++) {
4096 c_char = g_ascii_toupper(pd[i]);
4097 if (c_char == ascii_text[c_match]) {
4098 c_match++;
4099 if (c_match == textlen) {
4100 /* Save position and length for highlighting the field. */
4101 result = MR_MATCHED;
4102 cf->search_pos = (uint32_t)(pd - buf_start);
4103 cf->search_len = (uint32_t)(i + 1);
4104 goto done;
4106 } else {
4107 break;
4112 done:
4113 return result;
4116 static match_result
4117 match_wide(capture_file *cf, frame_data *fdata,
4118 wtap_rec *rec, Buffer *buf, void *criterion)
4120 cbs_t *info = (cbs_t *)criterion;
4121 const uint8_t *ascii_text = info->data;
4122 size_t textlen = info->data_len;
4123 match_result result;
4124 uint32_t buf_len;
4125 uint8_t *pd, *buf_start, *buf_end;
4126 uint32_t i;
4127 uint8_t c_char;
4128 size_t c_match = 0;
4130 /* Load the frame's data. */
4131 if (!cf_read_record(cf, fdata, rec, buf)) {
4132 /* Attempt to get the packet failed. */
4133 return MR_ERROR;
4136 result = MR_NOTMATCHED;
4137 buf_len = fdata->cap_len;
4138 buf_start = ws_buffer_start_ptr(buf);
4139 buf_end = buf_start + buf_len;
4140 pd = buf_start;
4141 if (cf->search_len || cf->search_pos) {
4142 /* we want to start searching one byte past the previous match start */
4143 pd += cf->search_pos + 1;
4145 for (; pd < buf_end; pd++) {
4146 pd = (uint8_t *)memchr(pd, ascii_text[0], buf_end - pd);
4147 if (pd == NULL) break;
4148 c_match = 0;
4149 for (i = 0; pd + i < buf_end; i++) {
4150 c_char = pd[i];
4151 if (c_char == ascii_text[c_match]) {
4152 c_match++;
4153 if (c_match == textlen) {
4154 result = MR_MATCHED;
4155 /* Save position and length for highlighting the field. */
4156 cf->search_pos = (uint32_t)(pd - buf_start);
4157 cf->search_len = (uint32_t)(i + 1);
4158 goto done;
4160 i++;
4161 if (pd + i >= buf_end || pd[i] != '\0') break;
4162 } else {
4163 break;
4168 done:
4169 return result;
4172 static match_result
4173 match_wide_reverse(capture_file *cf, frame_data *fdata,
4174 wtap_rec *rec, Buffer *buf, void *criterion)
4176 cbs_t *info = (cbs_t *)criterion;
4177 const uint8_t *ascii_text = info->data;
4178 size_t textlen = info->data_len;
4179 match_result result;
4180 uint32_t buf_len;
4181 uint8_t *pd, *buf_start, *buf_end;
4182 uint32_t i;
4183 uint8_t c_char;
4184 size_t c_match = 0;
4186 /* Load the frame's data. */
4187 if (!cf_read_record(cf, fdata, rec, buf)) {
4188 /* Attempt to get the packet failed. */
4189 return MR_ERROR;
4192 result = MR_NOTMATCHED;
4193 /* Has to be room to hold the sought data. */
4194 if (textlen > fdata->cap_len) {
4195 return result;
4197 buf_len = fdata->cap_len;
4198 buf_start = ws_buffer_start_ptr(buf);
4199 buf_end = buf_start + buf_len;
4200 pd = buf_end - textlen;
4201 if (cf->search_len || cf->search_pos) {
4202 /* we want to start searching one byte before the previous match start */
4203 pd = buf_start + cf->search_pos - 1;
4205 for (; pd < buf_end; pd++) {
4206 pd = (uint8_t *)ws_memrchr(buf_start, ascii_text[0], pd - buf_start + 1);
4207 if (pd == NULL) break;
4208 c_match = 0;
4209 for (i = 0; pd + i < buf_end; i++) {
4210 c_char = pd[i];
4211 if (c_char == ascii_text[c_match]) {
4212 c_match++;
4213 if (c_match == textlen) {
4214 result = MR_MATCHED;
4215 /* Save position and length for highlighting the field. */
4216 cf->search_pos = (uint32_t)(pd - buf_start);
4217 cf->search_len = (uint32_t)(i + 1);
4218 goto done;
4220 i++;
4221 if (pd + i >= buf_end || pd[i] != '\0') break;
4222 } else {
4223 break;
4228 done:
4229 return result;
4232 /* Case insensitive match */
4233 static match_result
4234 match_wide_case(capture_file *cf, frame_data *fdata,
4235 wtap_rec *rec, Buffer *buf, void *criterion)
4237 cbs_t *info = (cbs_t *)criterion;
4238 const uint8_t *ascii_text = info->data;
4239 size_t textlen = info->data_len;
4240 ws_mempbrk_pattern *pattern = info->pattern;
4241 match_result result;
4242 uint32_t buf_len;
4243 uint8_t *pd, *buf_start, *buf_end;
4244 uint32_t i;
4245 uint8_t c_char;
4246 size_t c_match = 0;
4248 /* Load the frame's data. */
4249 if (!cf_read_record(cf, fdata, rec, buf)) {
4250 /* Attempt to get the packet failed. */
4251 return MR_ERROR;
4254 ws_assert(pattern != NULL);
4256 result = MR_NOTMATCHED;
4257 buf_len = fdata->cap_len;
4258 buf_start = ws_buffer_start_ptr(buf);
4259 buf_end = buf_start + buf_len;
4260 pd = buf_start;
4261 if (cf->search_len || cf->search_pos) {
4262 /* we want to start searching one byte past the previous match start */
4263 pd += cf->search_pos + 1;
4265 for (; pd < buf_end; pd++) {
4266 pd = (uint8_t *)ws_mempbrk_exec(pd, buf_end - pd, pattern, &c_char);
4267 if (pd == NULL) break;
4268 c_match = 0;
4269 for (i = 0; pd + i < buf_end; i++) {
4270 c_char = g_ascii_toupper(pd[i]);
4271 if (c_char == ascii_text[c_match]) {
4272 c_match++;
4273 if (c_match == textlen) {
4274 result = MR_MATCHED;
4275 /* Save position and length for highlighting the field. */
4276 cf->search_pos = (uint32_t)(pd - buf_start);
4277 cf->search_len = (uint32_t)(i + 1);
4278 goto done;
4280 i++;
4281 if (pd + i >= buf_end || pd[i] != '\0') break;
4282 } else {
4283 break;
4288 done:
4289 return result;
4292 /* Case insensitive match */
4293 static match_result
4294 match_wide_case_reverse(capture_file *cf, frame_data *fdata,
4295 wtap_rec *rec, Buffer *buf, void *criterion)
4297 cbs_t *info = (cbs_t *)criterion;
4298 const uint8_t *ascii_text = info->data;
4299 size_t textlen = info->data_len;
4300 ws_mempbrk_pattern *pattern = info->pattern;
4301 match_result result;
4302 uint32_t buf_len;
4303 uint8_t *pd, *buf_start, *buf_end;
4304 uint32_t i;
4305 uint8_t c_char;
4306 size_t c_match = 0;
4308 /* Load the frame's data. */
4309 if (!cf_read_record(cf, fdata, rec, buf)) {
4310 /* Attempt to get the packet failed. */
4311 return MR_ERROR;
4314 ws_assert(pattern != NULL);
4316 result = MR_NOTMATCHED;
4317 /* Has to be room to hold the sought data. */
4318 if (textlen > fdata->cap_len) {
4319 return result;
4321 buf_len = fdata->cap_len;
4322 buf_start = ws_buffer_start_ptr(buf);
4323 buf_end = buf_start + buf_len;
4324 pd = buf_end - textlen;
4325 if (cf->search_len || cf->search_pos) {
4326 /* we want to start searching one byte before the previous match start */
4327 pd = buf_start + cf->search_pos - 1;
4329 for (; pd >= buf_start; pd--) {
4330 pd = (uint8_t *)ws_memrpbrk_exec(buf_start, pd - buf_start + 1, pattern, &c_char);
4331 if (pd == NULL) break;
4332 c_match = 0;
4333 for (i = 0; pd + i < buf_end; i++) {
4334 c_char = g_ascii_toupper(pd[i]);
4335 if (c_char == ascii_text[c_match]) {
4336 c_match++;
4337 if (c_match == textlen) {
4338 result = MR_MATCHED;
4339 /* Save position and length for highlighting the field. */
4340 cf->search_pos = (uint32_t)(pd - buf_start);
4341 cf->search_len = (uint32_t)(i + 1);
4342 goto done;
4344 i++;
4345 if (pd + i >= buf_end || pd[i] != '\0') break;
4346 } else {
4347 break;
4352 done:
4353 return result;
4356 static match_result
4357 match_binary(capture_file *cf, frame_data *fdata,
4358 wtap_rec *rec, Buffer *buf, void *criterion)
4360 cbs_t *info = (cbs_t *)criterion;
4361 size_t datalen = info->data_len;
4362 match_result result;
4363 const uint8_t *pd = NULL, *buf_start;
4365 /* Load the frame's data. */
4366 if (!cf_read_record(cf, fdata, rec, buf)) {
4367 /* Attempt to get the packet failed. */
4368 return MR_ERROR;
4371 result = MR_NOTMATCHED;
4372 buf_start = ws_buffer_start_ptr(buf);
4373 size_t offset = 0;
4374 if (cf->search_len || cf->search_pos) {
4375 /* we want to start searching one byte past the previous match start */
4376 offset = cf->search_pos + 1;
4378 if (offset < fdata->cap_len) {
4379 pd = ws_memmem(buf_start + offset, fdata->cap_len - offset, info->data, datalen);
4381 if (pd != NULL) {
4382 result = MR_MATCHED;
4383 /* Save position and length for highlighting the field. */
4384 cf->search_pos = (uint32_t)(pd - buf_start);
4385 cf->search_len = (uint32_t)datalen;
4388 return result;
4391 static match_result
4392 match_binary_reverse(capture_file *cf, frame_data *fdata,
4393 wtap_rec *rec, Buffer *buf, void *criterion)
4395 cbs_t *info = (cbs_t *)criterion;
4396 size_t datalen = info->data_len;
4397 match_result result;
4398 const uint8_t *pd = NULL, *buf_start;
4400 /* Load the frame's data. */
4401 if (!cf_read_record(cf, fdata, rec, buf)) {
4402 /* Attempt to get the packet failed. */
4403 return MR_ERROR;
4406 result = MR_NOTMATCHED;
4407 buf_start = ws_buffer_start_ptr(buf);
4408 /* Has to be room to hold the sought data. */
4409 if (datalen > fdata->cap_len) {
4410 return result;
4412 pd = buf_start + fdata->cap_len - datalen;
4413 if (cf->search_len || cf->search_pos) {
4414 /* we want to start searching one byte before the previous match start */
4415 pd = buf_start + cf->search_pos - 1;
4417 for (; pd >= buf_start; pd--) {
4418 pd = (uint8_t *)ws_memrchr(buf_start, info->data[0], pd - buf_start + 1);
4419 if (pd == NULL) break;
4420 if (memcmp(pd, info->data, datalen) == 0) {
4421 result = MR_MATCHED;
4422 /* Save position and length for highlighting the field. */
4423 cf->search_pos = (uint32_t)(pd - buf_start);
4424 cf->search_len = (uint32_t)datalen;
4425 break;
4429 return result;
4432 static match_result
4433 match_regex(capture_file *cf, frame_data *fdata,
4434 wtap_rec *rec, Buffer *buf, void *criterion _U_)
4436 match_result result = MR_NOTMATCHED;
4437 size_t result_pos[2] = {0, 0};
4439 /* Load the frame's data. */
4440 if (!cf_read_record(cf, fdata, rec, buf)) {
4441 /* Attempt to get the packet failed. */
4442 return MR_ERROR;
4445 size_t offset = 0;
4446 if (cf->search_len || cf->search_pos) {
4447 /* we want to start searching one byte past the previous match start */
4448 offset = cf->search_pos + 1;
4450 if (offset < fdata->cap_len) {
4451 if (ws_regex_matches_pos(cf->regex,
4452 (const char *)ws_buffer_start_ptr(buf),
4453 fdata->cap_len, offset,
4454 result_pos)) {
4455 //TODO: A chosen regex can match the empty string (zero length)
4456 // which doesn't make a lot of sense for searching the packet bytes.
4457 // Should we search with the PCRE2_NOTEMPTY option?
4458 //TODO: Fix cast.
4459 /* Save position and length for highlighting the field. */
4460 cf->search_pos = (uint32_t)(result_pos[0]);
4461 cf->search_len = (uint32_t)(result_pos[1] - result_pos[0]);
4462 result = MR_MATCHED;
4465 return result;
4468 static match_result
4469 match_regex_reverse(capture_file *cf, frame_data *fdata,
4470 wtap_rec *rec, Buffer *buf, void *criterion _U_)
4472 match_result result = MR_NOTMATCHED;
4473 size_t result_pos[2] = {0, 0};
4475 /* Load the frame's data. */
4476 if (!cf_read_record(cf, fdata, rec, buf)) {
4477 /* Attempt to get the packet failed. */
4478 return MR_ERROR;
4481 size_t offset = fdata->cap_len - 1;
4482 if (cf->search_pos) {
4483 /* we want to start searching one byte before the previous match */
4484 offset = cf->search_pos - 1;
4486 for (; offset > 0; offset--) {
4487 if (ws_regex_matches_pos(cf->regex,
4488 (const char *)ws_buffer_start_ptr(buf),
4489 fdata->cap_len, offset,
4490 result_pos)) {
4491 //TODO: A chosen regex can match the empty string (zero length)
4492 // which doesn't make a lot of sense for searching the packet bytes.
4493 // Should we search with the PCRE2_NOTEMPTY option?
4494 //TODO: Fix cast.
4495 /* Save position and length for highlighting the field. */
4496 cf->search_pos = (uint32_t)(result_pos[0]);
4497 cf->search_len = (uint32_t)(result_pos[1] - result_pos[0]);
4498 result = MR_MATCHED;
4499 break;
4502 return result;
4505 bool
4506 cf_find_packet_dfilter(capture_file *cf, dfilter_t *sfcode,
4507 search_direction dir)
4509 return find_packet(cf, match_dfilter, sfcode, dir);
4512 bool
4513 cf_find_packet_dfilter_string(capture_file *cf, const char *filter,
4514 search_direction dir)
4516 dfilter_t *sfcode;
4517 bool result;
4519 if (!dfilter_compile(filter, &sfcode, NULL)) {
4521 * XXX - this shouldn't happen, as the filter string is machine
4522 * generated
4524 return false;
4526 if (sfcode == NULL) {
4528 * XXX - this shouldn't happen, as the filter string is machine
4529 * generated.
4531 return false;
4533 result = find_packet(cf, match_dfilter, sfcode, dir);
4534 dfilter_free(sfcode);
4535 return result;
4538 static match_result
4539 match_dfilter(capture_file *cf, frame_data *fdata,
4540 wtap_rec *rec, Buffer *buf, void *criterion)
4542 dfilter_t *sfcode = (dfilter_t *)criterion;
4543 epan_dissect_t edt;
4544 match_result result;
4546 /* Load the frame's data. */
4547 if (!cf_read_record(cf, fdata, rec, buf)) {
4548 /* Attempt to get the packet failed. */
4549 return MR_ERROR;
4552 epan_dissect_init(&edt, cf->epan, true, false);
4553 epan_dissect_prime_with_dfilter(&edt, sfcode);
4554 epan_dissect_run(&edt, cf->cd_t, rec,
4555 frame_tvbuff_new_buffer(&cf->provider, fdata, buf),
4556 fdata, NULL);
4557 result = dfilter_apply_edt(sfcode, &edt) ? MR_MATCHED : MR_NOTMATCHED;
4558 epan_dissect_cleanup(&edt);
4559 return result;
4562 bool
4563 cf_find_packet_marked(capture_file *cf, search_direction dir)
4565 return find_packet(cf, match_marked, NULL, dir);
4568 static match_result
4569 match_marked(capture_file *cf _U_, frame_data *fdata, wtap_rec *rec _U_,
4570 Buffer *buf _U_, void *criterion _U_)
4572 return fdata->marked ? MR_MATCHED : MR_NOTMATCHED;
4575 bool
4576 cf_find_packet_time_reference(capture_file *cf, search_direction dir)
4578 return find_packet(cf, match_time_reference, NULL, dir);
4581 static match_result
4582 match_time_reference(capture_file *cf _U_, frame_data *fdata, wtap_rec *rec _U_,
4583 Buffer *buf _U_, void *criterion _U_)
4585 return fdata->ref_time ? MR_MATCHED : MR_NOTMATCHED;
4588 static bool
4589 find_packet(capture_file *cf, ws_match_function match_function,
4590 void *criterion, search_direction dir)
4592 frame_data *start_fd;
4593 uint32_t framenum;
4594 uint32_t prev_framenum;
4595 frame_data *fdata;
4596 wtap_rec rec;
4597 Buffer buf;
4598 frame_data *new_fd = NULL;
4599 progdlg_t *progbar = NULL;
4600 GTimer *prog_timer = g_timer_new();
4601 int count;
4602 bool succeeded;
4603 float progbar_val;
4604 char status_str[100];
4605 match_result result;
4607 wtap_rec_init(&rec);
4608 ws_buffer_init(&buf, 1514);
4610 start_fd = cf->current_frame;
4611 if (start_fd != NULL) {
4612 prev_framenum = start_fd->num;
4613 } else {
4614 prev_framenum = 0; /* No start packet selected. */
4617 /* Iterate through the list of packets, starting at the packet we've
4618 picked, calling a routine to run the filter on the packet, see if
4619 it matches, and stop if so. */
4620 count = 0;
4621 framenum = prev_framenum;
4623 g_timer_start(prog_timer);
4624 /* Progress so far. */
4625 progbar_val = 0.0f;
4627 cf->stop_flag = false;
4629 for (;;) {
4630 /* Create the progress bar if necessary.
4631 We check on every iteration of the loop, so that it takes no
4632 longer than the standard time to create it (otherwise, for a
4633 large file, we might take considerably longer than that standard
4634 time in order to get to the next progress bar step). */
4635 if (progbar == NULL)
4636 progbar = delayed_create_progress_dlg(cf->window, NULL, NULL,
4637 false, &cf->stop_flag, progbar_val);
4640 * Update the progress bar, but do it only after PROGBAR_UPDATE_INTERVAL
4641 * has elapsed. Calling update_progress_dlg and packets_bar_update will
4642 * likely trigger UI paint events, which might take a while depending on
4643 * the platform and display. Reset our timer *after* painting.
4645 if (g_timer_elapsed(prog_timer, NULL) > PROGBAR_UPDATE_INTERVAL) {
4646 /* let's not divide by zero. I should never be started
4647 * with count == 0, so let's assert that
4649 ws_assert(cf->count > 0);
4651 progbar_val = (float) count / cf->count;
4653 snprintf(status_str, sizeof(status_str),
4654 "%4u of %u packets", count, cf->count);
4655 update_progress_dlg(progbar, progbar_val, status_str);
4657 g_timer_start(prog_timer);
4660 if (cf->stop_flag) {
4661 /* Well, the user decided to abort the search. Go back to the
4662 frame where we started. */
4663 new_fd = start_fd;
4664 break;
4667 /* Go past the current frame. */
4668 if (dir == SD_BACKWARD) {
4669 /* Go on to the previous frame. */
4670 if (framenum <= 1) {
4672 * XXX - other apps have a bit more of a detailed message
4673 * for this, and instead of offering "OK" and "Cancel",
4674 * they offer things such as "Continue" and "Cancel";
4675 * we need an API for popping up alert boxes with
4676 * {Verb} and "Cancel".
4679 if (prefs.gui_find_wrap) {
4680 statusbar_push_temporary_msg("Search reached the beginning. Continuing at end.");
4681 framenum = cf->count; /* wrap around */
4682 } else {
4683 statusbar_push_temporary_msg("Search reached the beginning.");
4684 framenum = prev_framenum; /* stay on previous packet */
4686 } else
4687 framenum--;
4688 } else {
4689 /* Go on to the next frame. */
4690 if (framenum == cf->count) {
4691 if (prefs.gui_find_wrap) {
4692 statusbar_push_temporary_msg("Search reached the end. Continuing at beginning.");
4693 framenum = 1; /* wrap around */
4694 } else {
4695 statusbar_push_temporary_msg("Search reached the end.");
4696 framenum = prev_framenum; /* stay on previous packet */
4698 } else
4699 framenum++;
4702 fdata = frame_data_sequence_find(cf->provider.frames, framenum);
4703 count++;
4705 /* Is this packet in the display? */
4706 if (fdata && fdata->passed_dfilter) {
4707 /* Yes. Does it match the search criterion? */
4708 result = (*match_function)(cf, fdata, &rec, &buf, criterion);
4709 if (result == MR_ERROR) {
4710 /* Error; our caller has reported the error. Go back to the frame
4711 where we started. */
4712 new_fd = start_fd;
4713 break;
4714 } else if (result == MR_MATCHED) {
4715 /* Yes. Go to the new frame. */
4716 new_fd = fdata;
4717 break;
4719 wtap_rec_reset(&rec);
4722 if (fdata == start_fd) {
4723 /* We're back to the frame we were on originally, and that frame
4724 doesn't match the search filter. The search failed. */
4725 break;
4729 /* We're done scanning the packets; destroy the progress bar if it
4730 was created. */
4731 if (progbar != NULL)
4732 destroy_progress_dlg(progbar);
4733 g_timer_destroy(prog_timer);
4735 if (new_fd != NULL) {
4736 /* We found a frame that's displayed and that matches.
4737 Try to find and select the packet summary list row for that frame. */
4738 bool found_row;
4740 cf->search_in_progress = true;
4741 found_row = packet_list_select_row_from_data(new_fd);
4742 cf->search_in_progress = false;
4743 if (!found_row) {
4744 /* We didn't find a row corresponding to this frame.
4745 This means that the frame isn't being displayed currently,
4746 so we can't select it. */
4747 cf->search_pos = 0; /* Reset the position */
4748 cf->search_len = 0; /* Reset length */
4749 simple_message_box(ESD_TYPE_INFO, NULL,
4750 "The capture file is probably not fully dissected.",
4751 "End of capture exceeded.");
4752 succeeded = false; /* The search succeeded but we didn't find the row */
4753 } else
4754 succeeded = true; /* The search succeeded and we found the row */
4755 } else
4756 succeeded = false; /* The search failed */
4757 wtap_rec_cleanup(&rec);
4758 ws_buffer_free(&buf);
4759 return succeeded;
4762 bool
4763 cf_goto_frame(capture_file *cf, unsigned fnumber, bool exact)
4765 frame_data *fdata;
4767 if (cf == NULL || cf->provider.frames == NULL) {
4768 /* we don't have a loaded capture file - fix for bugs 11810 & 11989 */
4769 statusbar_push_temporary_msg("There is no file loaded");
4770 return false; /* we failed to go to that packet */
4773 fdata = frame_data_sequence_find(cf->provider.frames, fnumber);
4775 if (fdata == NULL) {
4776 /* we didn't find a packet with that packet number */
4777 statusbar_push_temporary_msg("There is no packet number %u.", fnumber);
4778 return false; /* we failed to go to that packet */
4780 if (!fdata->passed_dfilter) {
4781 /* that packet currently isn't displayed */
4782 /* XXX - add it to the set of displayed packets? */
4783 if (cf->first_displayed == 0 || exact) {
4784 /* We only want that exact frame, or no frames are displayed. */
4785 statusbar_push_temporary_msg("Packet number %u isn't displayed.", fnumber);
4786 return false; /* we failed to go to that packet */
4788 if (fdata->prev_dis_num == 0) {
4789 /* There is no previous displayed frame, so this frame is
4790 * before the first displayed frame. Go to the first line,
4791 * which is the closest frame.
4793 fdata = NULL; /* This will select the first row. */
4794 statusbar_push_temporary_msg("Packet number %u isn't displayed, going to the first displayed packet, %u.", fnumber, cf->first_displayed);
4795 } else {
4796 uint32_t delta = fnumber - fdata->prev_dis_num;
4797 /* The next displayed frame might be closer, we can do an
4798 * O(log n) binary search for the earliest displayed frame
4799 * in the open interval (fnumber, fnumber + delta).
4801 * This is possibly overkill, we could just go to the previous
4802 * displayed frame.
4804 frame_data *fdata2;
4805 uint32_t lower_bound = fnumber + 1;
4806 uint32_t upper_bound = fnumber + delta - 1;
4807 bool found = false;
4808 while (lower_bound <= upper_bound) {
4809 uint32_t middle = (lower_bound + upper_bound) / 2;
4810 fdata2 = frame_data_sequence_find(cf->provider.frames, middle);
4811 if (fdata2 == NULL) {
4812 /* We don't have a frame of that number, so search before it. */
4813 upper_bound = middle - 1;
4814 continue;
4816 /* We have a frame of that number. What's the displayed
4817 * frame before it? */
4818 if (fdata2->prev_dis_num > fnumber) {
4819 /* The previous frame that passed the filter is also after
4820 * our target, so our answer is no later than that.
4822 upper_bound = fdata2->prev_dis_num;
4823 } else {
4824 /* The previous displayed frame is before fnumber.
4825 * (We already know fnumber itself is not displayed.)
4826 * Is this frame itself displayed?
4828 if (fdata2->passed_dfilter) {
4829 /* Yes. So this is our answer. */
4830 found = true;
4831 break;
4833 /* No. So our answer, if any, is after this frame. */
4834 lower_bound = middle + 1;
4837 if (found) {
4838 fdata = fdata2;
4839 statusbar_push_temporary_msg("Packet number %u isn't displayed, going to the next displayed packet, %u.", fnumber, fdata->num);
4840 } else {
4841 statusbar_push_temporary_msg("Packet number %u isn't displayed, going to the previous displayed packet, %u.", fnumber, fdata->prev_dis_num);
4842 fdata = frame_data_sequence_find(cf->provider.frames, fdata->prev_dis_num);
4847 if (!packet_list_select_row_from_data(fdata)) {
4848 /* We didn't find a row corresponding to this frame.
4849 This means that the frame isn't being displayed currently,
4850 so we can't select it. */
4851 simple_message_box(ESD_TYPE_INFO, NULL,
4852 "The capture file is probably not fully dissected.",
4853 "End of capture exceeded.");
4854 return false;
4856 return true; /* we got to that packet */
4860 * Go to frame specified by currently selected protocol tree item.
4862 bool
4863 cf_goto_framenum(capture_file *cf)
4865 const header_field_info *hfinfo;
4866 uint32_t framenum;
4868 if (cf->finfo_selected) {
4869 hfinfo = cf->finfo_selected->hfinfo;
4870 ws_assert(hfinfo);
4871 if (hfinfo->type == FT_FRAMENUM) {
4872 framenum = fvalue_get_uinteger(cf->finfo_selected->value);
4873 if (framenum != 0) {
4874 /* We probably only want to go to the exact match,
4875 * even though "Go to Previous Packet in History" exists.
4877 return cf_goto_frame(cf, framenum, true);
4882 return false;
4885 /* Select the packet on a given row. */
4886 void
4887 cf_select_packet(capture_file *cf, frame_data *fdata)
4889 epan_dissect_t *old_edt;
4891 /* check the frame data struct pointer for this frame */
4892 if (fdata == NULL) {
4893 return;
4896 /* Get the data in that frame. */
4897 if (!cf_read_record(cf, fdata, &cf->rec, &cf->buf)) {
4898 return;
4901 /* Record that this frame is the current frame. */
4902 cf->current_frame = fdata;
4905 * The change to defer freeing the current epan_dissect_t was in
4906 * commit a2bb94c3b33d53f42534aceb7cc67aab1d1fb1f9; to quote
4907 * that commit's comment:
4909 * Clear GtkTreeStore before freeing edt
4911 * When building current data for packet details treeview we store two
4912 * things.
4913 * - Generated string with item label
4914 * - Pointer to node field_info structure
4916 * After epan_dissect_{free, cleanup} pointer to field_info node is no
4917 * longer valid so we should clear GtkTreeStore before freeing.
4919 * XXX - we're no longer using GTK+; is there a way to ensure that
4920 * *nothing* refers to any of the current frame information before
4921 * we replace it?
4923 old_edt = cf->edt;
4924 /* Create the logical protocol tree. */
4925 /* We don't need the columns here. */
4926 cf->edt = epan_dissect_new(cf->epan, true, true);
4928 tap_build_interesting(cf->edt);
4929 epan_dissect_run(cf->edt, cf->cd_t, &cf->rec,
4930 frame_tvbuff_new_buffer(&cf->provider, cf->current_frame, &cf->buf),
4931 cf->current_frame, NULL);
4933 if (old_edt != NULL)
4934 epan_dissect_free(old_edt);
4937 /* Unselect the selected packet, if any. */
4938 void
4939 cf_unselect_packet(capture_file *cf)
4941 epan_dissect_t *old_edt = cf->edt;
4944 * See the comment in cf_select_packet() about deferring the freeing
4945 * of the old cf->edt.
4947 cf->edt = NULL;
4949 /* No packet is selected. */
4950 cf->current_frame = NULL;
4952 /* Destroy the epan_dissect_t for the unselected packet. */
4953 if (old_edt != NULL)
4954 epan_dissect_free(old_edt);
4958 * Mark a particular frame.
4960 void
4961 cf_mark_frame(capture_file *cf, frame_data *frame)
4963 if (! frame->marked) {
4964 frame->marked = true;
4965 if (cf->count > cf->marked_count)
4966 cf->marked_count++;
4971 * Unmark a particular frame.
4973 void
4974 cf_unmark_frame(capture_file *cf, frame_data *frame)
4976 if (frame->marked) {
4977 frame->marked = false;
4978 if (cf->marked_count > 0)
4979 cf->marked_count--;
4984 * Ignore a particular frame.
4986 void
4987 cf_ignore_frame(capture_file *cf, frame_data *frame)
4989 if (! frame->ignored) {
4990 frame->ignored = true;
4991 if (cf->count > cf->ignored_count)
4992 cf->ignored_count++;
4997 * Un-ignore a particular frame.
4999 void
5000 cf_unignore_frame(capture_file *cf, frame_data *frame)
5002 if (frame->ignored) {
5003 frame->ignored = false;
5004 if (cf->ignored_count > 0)
5005 cf->ignored_count--;
5010 * Modify the section comment.
5012 void
5013 cf_update_section_comment(capture_file *cf, char *comment)
5015 wtap_block_t shb_inf;
5016 char *shb_comment;
5018 /* Get the first SHB. */
5019 /* XXX - support multiple SHBs */
5020 shb_inf = wtap_file_get_shb(cf->provider.wth, 0);
5022 /* Get the first comment from the SHB. */
5023 /* XXX - support multiple comments */
5024 if (wtap_block_get_nth_string_option_value(shb_inf, OPT_COMMENT, 0, &shb_comment) != WTAP_OPTTYPE_SUCCESS) {
5025 /* There's no comment - add one. */
5026 wtap_block_add_string_option(shb_inf, OPT_COMMENT, comment, strlen(comment));
5027 } else {
5028 /* See if the comment has changed or not */
5029 if (strcmp(shb_comment, comment) == 0) {
5030 g_free(comment);
5031 return;
5034 /* The comment has changed, let's update it */
5035 wtap_block_set_nth_string_option_value(shb_inf, OPT_COMMENT, 0, comment, strlen(comment));
5037 /* Mark the file as having unsaved changes */
5038 cf->unsaved_changes = true;
5042 * Modify the section comments for a given section.
5044 void
5045 cf_update_section_comments(capture_file *cf, unsigned shb_idx, char **comments)
5047 wtap_block_t shb_inf;
5048 char *shb_comment;
5050 shb_inf = wtap_file_get_shb(cf->provider.wth, shb_idx);
5051 if (shb_inf == NULL) {
5052 /* Shouldn't happen. XXX: Report it if it does? */
5053 return;
5056 unsigned n_comments = g_strv_length(comments);
5057 unsigned i;
5058 char* comment;
5060 for (i = 0; i < n_comments; i++) {
5061 comment = comments[i];
5062 if (wtap_block_get_nth_string_option_value(shb_inf, OPT_COMMENT, i, &shb_comment) != WTAP_OPTTYPE_SUCCESS) {
5063 /* There's no comment - add one. */
5064 wtap_block_add_string_option_owned(shb_inf, OPT_COMMENT, comment);
5065 cf->unsaved_changes = true;
5066 } else {
5067 /* See if the comment has changed or not */
5068 if (strcmp(shb_comment, comment) != 0) {
5069 /* The comment has changed, let's update it */
5070 wtap_block_set_nth_string_option_value(shb_inf, OPT_COMMENT, 0, comment, strlen(comment));
5071 cf->unsaved_changes = true;
5073 g_free(comment);
5076 /* We either transferred ownership of the comments or freed them
5077 * above, so free the array of strings but not the strings themselves. */
5078 g_free(comments);
5080 /* If there are extra old comments, remove them. Start at the end. */
5081 for (i = wtap_block_count_option(shb_inf, OPT_COMMENT); i > n_comments; i--) {
5082 wtap_block_remove_nth_option_instance(shb_inf, OPT_COMMENT, i - 1);
5083 cf->unsaved_changes = true;
5088 * Get the packet block for a packet (record).
5089 * If the block has been edited, it returns the result of the edit,
5090 * otherwise it returns the block from the file.
5091 * NB. Caller must wtap_block_unref() the result when done.
5093 wtap_block_t
5094 cf_get_packet_block(capture_file *cf, const frame_data *fd)
5096 /* If this block has been modified, fetch the modified version */
5097 if (fd->has_modified_block)
5098 return wtap_block_ref(cap_file_provider_get_modified_block(&cf->provider, fd));
5099 else {
5100 wtap_rec rec; /* Record metadata */
5101 Buffer buf; /* Record data */
5102 wtap_block_t block;
5104 /* fetch record block */
5105 wtap_rec_init(&rec);
5106 ws_buffer_init(&buf, 1514);
5108 if (!cf_read_record(cf, fd, &rec, &buf))
5109 { /* XXX, what we can do here? */ }
5111 /* rec.block is owned by the record, steal it before it is gone. */
5112 block = wtap_block_ref(rec.block);
5114 wtap_rec_cleanup(&rec);
5115 ws_buffer_free(&buf);
5116 return block;
5121 * Update(replace) the block on a capture from a frame
5123 bool
5124 cf_set_modified_block(capture_file *cf, frame_data *fd, const wtap_block_t new_block)
5126 wtap_block_t pkt_block = cf_get_packet_block(cf, fd);
5128 /* It's possible to further modify the modified block "in place" by doing
5129 * a call to cf_get_packet_block() that returns an already created modified
5130 * block, modifying that, and calling this function.
5131 * If the caller did that, then the block pointers will be equal.
5133 if (pkt_block == new_block) {
5134 /* No need to save anything here, the caller changes went right
5135 * onto the block.
5136 * Unfortunately we don't have a way to know how many comments were
5137 * in the block before the caller modified it, so tell the caller
5138 * it is its responsibility to update the comment count.
5140 return false;
5142 else {
5143 if (pkt_block)
5144 cf->packet_comment_count -= wtap_block_count_option(pkt_block, OPT_COMMENT);
5146 if (new_block)
5147 cf->packet_comment_count += wtap_block_count_option(new_block, OPT_COMMENT);
5149 cap_file_provider_set_modified_block(&cf->provider, fd, new_block);
5151 expert_update_comment_count(cf->packet_comment_count);
5154 /* Either way, we have unsaved changes. */
5155 wtap_block_unref(pkt_block);
5156 cf->unsaved_changes = true;
5157 return true;
5161 * What types of comments does this capture file have?
5163 uint32_t
5164 cf_comment_types(capture_file *cf)
5166 uint32_t comment_types = 0;
5169 * Does this file have any sections with at least one comment?
5171 for (unsigned section_number = 0;
5172 section_number < wtap_file_get_num_shbs(cf->provider.wth);
5173 section_number++) {
5174 wtap_block_t shb_inf;
5175 char *shb_comment;
5177 shb_inf = wtap_file_get_shb(cf->provider.wth, section_number);
5179 /* Try to get the first comment from that SHB. */
5180 if (wtap_block_get_nth_string_option_value(shb_inf, OPT_COMMENT, 0,
5181 &shb_comment) == WTAP_OPTTYPE_SUCCESS) {
5182 /* We succeeded, so this file has at least one section comment. */
5183 comment_types |= WTAP_COMMENT_PER_SECTION;
5185 /* We don't need to search any more. */
5186 break;
5189 if (cf->packet_comment_count != 0)
5190 comment_types |= WTAP_COMMENT_PER_PACKET;
5191 return comment_types;
5195 * Add a resolved address to this file's list of resolved addresses.
5197 bool
5198 cf_add_ip_name_from_string(capture_file *cf, const char *addr, const char *name)
5201 * XXX - support multiple resolved address lists, and add to the one
5202 * attached to this file?
5204 if (!add_ip_name_from_string(addr, name))
5205 return false;
5207 /* OK, we have unsaved changes. */
5208 cf->unsaved_changes = true;
5209 return true;
5212 typedef struct {
5213 wtap_dumper *pdh;
5214 const char *fname;
5215 int file_type;
5216 bool export;
5217 } save_callback_args_t;
5220 * Save a capture to a file, in a particular format, saving either
5221 * all packets, all currently-displayed packets, or all marked packets.
5223 * Returns true if it succeeds, false otherwise; if it fails, it pops
5224 * up a message box for the failure.
5226 static bool
5227 save_record(capture_file *cf, frame_data *fdata, wtap_rec *rec,
5228 Buffer *buf, void *argsp)
5230 save_callback_args_t *args = (save_callback_args_t *)argsp;
5231 wtap_rec new_rec;
5232 int err;
5233 char *err_info;
5234 wtap_block_t pkt_block;
5236 /* Copy the record information from what was read in from the file. */
5237 new_rec = *rec;
5239 /* Make changes based on anything that the user has done but that
5240 hasn't been saved yet. */
5241 if (fdata->has_modified_block)
5242 pkt_block = cap_file_provider_get_modified_block(&cf->provider, fdata);
5243 else
5244 pkt_block = rec->block;
5245 new_rec.block = pkt_block;
5246 new_rec.block_was_modified = fdata->has_modified_block ? true : false;
5248 if (!nstime_is_zero(&fdata->shift_offset)) {
5249 if (new_rec.presence_flags & WTAP_HAS_TS) {
5250 nstime_add(&new_rec.ts, &fdata->shift_offset);
5254 /* and save the packet */
5255 if (!wtap_dump(args->pdh, &new_rec, ws_buffer_start_ptr(buf), &err, &err_info)) {
5256 cfile_write_failure_alert_box(NULL, args->fname, err, err_info, fdata->num,
5257 args->file_type);
5258 return false;
5261 /* If we are saving (i.e., replacing the current file with the one we're
5262 * writing), then update the frame data to clear the shift offset.
5263 * This keeps us from having to re-read the entire file.
5264 * We could do this in rescan_file(), but
5265 * 1) Ideally we shouldn't have to call rescan_file if all we're doing
5266 * is changing the timestamps, since that shouldn't change the offsets.
5267 * 2) The long term goal is to try to do the offset adjustment here
5268 * instead of using rescan_file, which should be faster (#1257).
5270 * If we're exporting to a different file, then don't do that.
5272 if (!args->export && new_rec.presence_flags & WTAP_HAS_TS) {
5273 nstime_set_zero(&fdata->shift_offset);
5276 return true;
5280 * Can this capture file be written out in any format using Wiretap
5281 * rather than by copying the raw data?
5283 bool
5284 cf_can_write_with_wiretap(capture_file *cf)
5286 /* We don't care whether we support the comments in this file or not;
5287 if we can't, we'll offer the user the option of discarding the
5288 comments. */
5289 return wtap_dump_can_write(cf->linktypes, 0);
5293 * Should we let the user do a save?
5295 * We should if:
5297 * the file has unsaved changes, and we can save it in some
5298 * format through Wiretap
5300 * or
5302 * the file is a temporary file and has no unsaved changes (so
5303 * that "saving" it just means copying it).
5305 * XXX - we shouldn't allow files to be edited if they can't be saved,
5306 * so cf->unsaved_changes should be true only if the file can be saved.
5308 * We don't care whether we support the comments in this file or not;
5309 * if we can't, we'll offer the user the option of discarding the
5310 * comments.
5312 bool
5313 cf_can_save(capture_file *cf)
5315 if (cf->unsaved_changes && wtap_dump_can_write(cf->linktypes, 0)) {
5316 /* Saved changes, and we can write it out with Wiretap. */
5317 return true;
5320 if (cf->is_tempfile && !cf->unsaved_changes) {
5322 * Temporary file with no unsaved changes, so we can just do a
5323 * raw binary copy.
5325 return true;
5328 /* Nothing to save. */
5329 return false;
5333 * Should we let the user do a "save as"?
5335 * That's true if:
5337 * we can save it in some format through Wiretap
5339 * or
5341 * the file is a temporary file and has no unsaved changes (so
5342 * that "saving" it just means copying it).
5344 * XXX - we shouldn't allow files to be edited if they can't be saved,
5345 * so cf->unsaved_changes should be true only if the file can be saved.
5347 * We don't care whether we support the comments in this file or not;
5348 * if we can't, we'll offer the user the option of discarding the
5349 * comments.
5351 bool
5352 cf_can_save_as(capture_file *cf)
5354 if (wtap_dump_can_write(cf->linktypes, 0)) {
5355 /* We can write it out with Wiretap. */
5356 return true;
5359 if (cf->is_tempfile && !cf->unsaved_changes) {
5361 * Temporary file with no unsaved changes, so we can just do a
5362 * raw binary copy.
5364 return true;
5367 /* Nothing to save. */
5368 return false;
5372 * Does this file have unsaved data?
5374 bool
5375 cf_has_unsaved_data(capture_file *cf)
5378 * If this is a temporary file, or a file with unsaved changes, it
5379 * has unsaved data.
5381 return (cf->is_tempfile && cf->count>0) || cf->unsaved_changes;
5385 * Quick scan to find packet offsets.
5387 static cf_read_status_t
5388 rescan_file(capture_file *cf, const char *fname, bool is_tempfile)
5390 wtap_rec rec;
5391 Buffer buf;
5392 int err;
5393 char *err_info;
5394 char *name_ptr;
5395 int64_t data_offset;
5396 progdlg_t *progbar = NULL;
5397 GTimer *prog_timer = g_timer_new();
5398 int64_t size;
5399 float progbar_val;
5400 int64_t start_time;
5401 char status_str[100];
5402 uint32_t framenum;
5403 frame_data *fdata;
5405 /* Close the old handle. */
5406 wtap_close(cf->provider.wth);
5408 /* Open the new file. */
5409 /* XXX: this will go through all open_routines for a matching one. But right
5410 now rescan_file() is only used when a file is being saved to a different
5411 format than the original, and the user is not given a choice of which
5412 reader to use (only which format to save it in), so doing this makes
5413 sense for now. (XXX: Now it is also used when saving a changed file,
5414 e.g. comments or time-shifted frames.) */
5415 cf->provider.wth = wtap_open_offline(fname, WTAP_TYPE_AUTO, &err, &err_info, true);
5416 if (cf->provider.wth == NULL) {
5417 cfile_open_failure_alert_box(fname, err, err_info);
5418 return CF_READ_ERROR;
5421 /* We're scanning a file whose contents should be the same as what
5422 we had before, so we don't discard dissection state etc.. */
5423 cf->f_datalen = 0;
5425 /* Set the file name because we need it to set the follow stream filter.
5426 XXX - is that still true? We need it for other reasons, though,
5427 in any case. */
5428 if (cf->filename != NULL) {
5429 g_free(cf->filename);
5431 cf->filename = g_strdup(fname);
5433 /* Indicate whether it's a permanent or temporary file. */
5434 cf->is_tempfile = is_tempfile;
5436 /* No user changes yet. */
5437 cf->unsaved_changes = false;
5439 cf->cd_t = wtap_file_type_subtype(cf->provider.wth);
5440 if (cf->linktypes != NULL) {
5441 g_array_free(cf->linktypes, TRUE);
5443 cf->linktypes = g_array_sized_new(FALSE, FALSE, (unsigned) sizeof(int), 1);
5445 cf->snap = wtap_snapshot_length(cf->provider.wth);
5447 name_ptr = g_filename_display_basename(cf->filename);
5449 cf_callback_invoke(cf_cb_file_rescan_started, cf);
5451 /* Record the file's compression type.
5452 XXX - do we know this at open time? */
5453 cf->compression_type = wtap_get_compression_type(cf->provider.wth);
5455 /* Find the size of the file. */
5456 size = wtap_file_size(cf->provider.wth, NULL);
5458 g_timer_start(prog_timer);
5460 cf->stop_flag = false;
5461 start_time = g_get_monotonic_time();
5463 framenum = 0;
5464 wtap_rec_init(&rec);
5465 ws_buffer_init(&buf, 1514);
5466 while ((wtap_read(cf->provider.wth, &rec, &buf, &err, &err_info,
5467 &data_offset))) {
5468 framenum++;
5469 fdata = frame_data_sequence_find(cf->provider.frames, framenum);
5470 if (G_LIKELY(fdata != NULL)) {
5471 fdata->file_off = data_offset;
5473 if (size >= 0) {
5474 cf->f_datalen = wtap_read_so_far(cf->provider.wth);
5476 /* Create the progress bar if necessary. */
5477 if (progress_is_slow(progbar, prog_timer, size, cf->f_datalen)) {
5478 progbar_val = calc_progbar_val(cf, size, cf->f_datalen, status_str, sizeof(status_str));
5479 progbar = delayed_create_progress_dlg(cf->window, NULL, NULL,
5480 true, &cf->stop_flag, progbar_val);
5484 * Update the progress bar, but do it only after PROGBAR_UPDATE_INTERVAL
5485 * has elapsed. Calling update_progress_dlg and packets_bar_update will
5486 * likely trigger UI paint events, which might take a while depending on
5487 * the platform and display. Reset our timer *after* painting.
5489 if (progbar && g_timer_elapsed(prog_timer, NULL) > PROGBAR_UPDATE_INTERVAL) {
5490 progbar_val = calc_progbar_val(cf, size, cf->f_datalen, status_str, sizeof(status_str));
5491 /* update the packet bar content on the first run or frequently on very large files */
5492 update_progress_dlg(progbar, progbar_val, status_str);
5493 compute_elapsed(cf, start_time);
5494 packets_bar_update();
5495 g_timer_start(prog_timer);
5499 if (cf->stop_flag) {
5500 /* Well, the user decided to abort the rescan. Sadly, as this
5501 isn't a reread, recovering is difficult, so we'll just
5502 close the current capture. */
5503 break;
5506 /* Add this packet's link-layer encapsulation type to cf->linktypes, if
5507 it's not already there.
5508 XXX - yes, this is O(N), so if every packet had a different
5509 link-layer encapsulation type, it'd be O(N^2) to read the file, but
5510 there are probably going to be a small number of encapsulation types
5511 in a file. */
5512 if (rec.rec_type == REC_TYPE_PACKET) {
5513 cf_add_encapsulation_type(cf, rec.rec_header.packet_header.pkt_encap);
5515 wtap_rec_reset(&rec);
5517 wtap_rec_cleanup(&rec);
5518 ws_buffer_free(&buf);
5520 /* Free the display name */
5521 g_free(name_ptr);
5523 /* We're done reading the file; destroy the progress bar if it was created. */
5524 if (progbar != NULL)
5525 destroy_progress_dlg(progbar);
5526 g_timer_destroy(prog_timer);
5528 /* We're done reading sequentially through the file. */
5529 cf->state = FILE_READ_DONE;
5531 /* Close the sequential I/O side, to free up memory it requires. */
5532 wtap_sequential_close(cf->provider.wth);
5534 /* compute the time it took to load the file */
5535 compute_elapsed(cf, start_time);
5537 /* Set the file encapsulation type now; we don't know what it is until
5538 we've looked at all the packets, as we don't know until then whether
5539 there's more than one type (and thus whether it's
5540 WTAP_ENCAP_PER_PACKET). */
5541 cf->lnk_t = wtap_file_encap(cf->provider.wth);
5543 cf_callback_invoke(cf_cb_file_rescan_finished, cf);
5545 if (cf->stop_flag) {
5546 /* Our caller will give up at this point. */
5547 return CF_READ_ABORTED;
5550 if (err != 0) {
5551 /* Put up a message box noting that the read failed somewhere along
5552 the line. Don't throw out the stuff we managed to read, though,
5553 if any. */
5554 cfile_read_failure_alert_box(NULL, err, err_info);
5555 return CF_READ_ERROR;
5556 } else
5557 return CF_READ_OK;
5560 cf_write_status_t
5561 cf_save_records(capture_file *cf, const char *fname, unsigned save_format,
5562 wtap_compression_type compression_type,
5563 bool discard_comments, bool dont_reopen)
5565 char *err_info = "Unknown error";
5566 char *fname_new = NULL;
5567 wtap_dumper *pdh;
5568 frame_data *fdata;
5569 addrinfo_lists_t *addr_lists;
5570 unsigned framenum;
5571 int err;
5572 #ifdef _WIN32
5573 char *display_basename;
5574 #endif
5575 enum {
5576 SAVE_WITH_MOVE,
5577 SAVE_WITH_COPY,
5578 SAVE_WITH_WTAP
5579 } how_to_save;
5580 save_callback_args_t callback_args;
5581 callback_args.export = false;
5582 bool needs_reload = false;
5584 /* XXX caller should avoid saving the file while a read is pending
5585 * (e.g. by delaying the save action) */
5586 if (cf->read_lock) {
5587 ws_warning("cf_save_records(\"%s\") while the file is being read, potential crash ahead", fname);
5590 cf_callback_invoke(cf_cb_file_save_started, (void *)fname);
5592 addr_lists = get_addrinfo_list();
5594 if (save_format == cf->cd_t && compression_type == cf->compression_type
5595 && !discard_comments && !cf->unsaved_changes
5596 && (wtap_addrinfo_list_empty(addr_lists) || wtap_file_type_subtype_supports_block(save_format, WTAP_BLOCK_NAME_RESOLUTION) == BLOCK_NOT_SUPPORTED)) {
5597 /* We're saving in the format it's already in, and we're not discarding
5598 comments, and there are no changes we have in memory that aren't saved
5599 to the file, and we have no name resolution information to write or
5600 the file format we're saving in doesn't support writing name
5601 resolution information, so we can just move or copy the raw data. */
5603 if (cf->is_tempfile) {
5604 /* The file being saved is a temporary file from a live
5605 capture, so it doesn't need to stay around under that name;
5606 first, try renaming the capture buffer file to the new name.
5607 This acts as a "safe save", in that, if the file already
5608 exists, the existing file will be removed only if the rename
5609 succeeds.
5611 Sadly, on Windows, as we have the current capture file
5612 open, even MoveFileEx() with MOVEFILE_REPLACE_EXISTING
5613 (to cause the rename to remove an existing target), as
5614 done by ws_stdio_rename() (ws_rename() is #defined to
5615 be ws_stdio_rename() on Windows) will fail.
5617 According to the MSDN documentation for CreateFile(), if,
5618 when we open a capture file, we were to directly do a CreateFile(),
5619 opening with FILE_SHARE_DELETE|FILE_SHARE_READ, and then
5620 convert it to a file descriptor with _open_osfhandle(),
5621 that would allow the file to be renamed out from under us.
5623 However, that doesn't work in practice. Perhaps the problem
5624 is that the process doing the rename is the process that
5625 has the file open. */
5626 #ifndef _WIN32
5627 if (ws_rename(cf->filename, fname) == 0) {
5628 /* That succeeded - there's no need to copy the source file. */
5629 how_to_save = SAVE_WITH_MOVE;
5630 } else {
5631 if (errno == EXDEV) {
5632 /* They're on different file systems, so we have to copy the
5633 file. */
5634 how_to_save = SAVE_WITH_COPY;
5635 } else {
5636 /* The rename failed, but not because they're on different
5637 file systems - put up an error message. (Or should we
5638 just punt and try to copy? The only reason why I'd
5639 expect the rename to fail and the copy to succeed would
5640 be if we didn't have permission to remove the file from
5641 the temporary directory, and that might be fixable - but
5642 is it worth requiring the user to go off and fix it?) */
5643 cf_rename_failure_alert_box(fname, errno);
5644 goto fail;
5647 #else
5648 /* Windows - copy the file to its new location. */
5649 how_to_save = SAVE_WITH_COPY;
5650 #endif
5651 } else {
5652 /* It's a permanent file, so we should copy it, and not remove the
5653 original. */
5654 how_to_save = SAVE_WITH_COPY;
5657 if (how_to_save == SAVE_WITH_COPY) {
5658 /* Copy the file, if we haven't moved it. If we're overwriting
5659 an existing file, we do it with a "safe save", by writing
5660 to a new file and, if the write succeeds, renaming the
5661 new file on top of the old file. */
5662 if (file_exists(fname)) {
5663 fname_new = ws_strdup_printf("%s~", fname);
5664 if (!copy_file_binary_mode(cf->filename, fname_new))
5665 goto fail;
5666 } else {
5667 if (!copy_file_binary_mode(cf->filename, fname))
5668 goto fail;
5671 } else {
5672 /* Either we're saving in a different format or we're saving changes,
5673 such as added, modified, or removed comments, that haven't yet
5674 been written to the underlying file; we can't do that by copying
5675 or moving the capture file, we have to do it by writing the packets
5676 out in Wiretap. */
5678 wtap_dump_params params;
5679 int encap;
5681 how_to_save = SAVE_WITH_WTAP;
5682 wtap_dump_params_init(&params, cf->provider.wth);
5684 /* Determine what file encapsulation type we should use. */
5685 encap = wtap_dump_required_file_encap_type(cf->linktypes);
5686 params.encap = encap;
5688 /* Use the snaplen from cf (XXX - does wtap_dump_params_init handle that?) */
5689 params.snaplen = cf->snap;
5691 if (file_exists(fname)) {
5692 /* We're overwriting an existing file; write out to a new file,
5693 and, if that succeeds, rename the new file on top of the
5694 old file. That makes this a "safe save", so that we don't
5695 lose the old file if we have a problem writing out the new
5696 file. (If the existing file is the current capture file,
5697 we *HAVE* to do that, otherwise we're overwriting the file
5698 from which we're reading the packets that we're writing!) */
5699 fname_new = ws_strdup_printf("%s~", fname);
5700 pdh = wtap_dump_open(fname_new, save_format, compression_type, &params,
5701 &err, &err_info);
5702 } else {
5703 pdh = wtap_dump_open(fname, save_format, compression_type, &params,
5704 &err, &err_info);
5706 /* XXX idb_inf is documented to be used until wtap_dump_close. */
5707 g_free(params.idb_inf);
5708 params.idb_inf = NULL;
5710 if (pdh == NULL) {
5711 cfile_dump_open_failure_alert_box(fname, err, err_info, save_format);
5712 goto fail;
5715 /* Add address resolution */
5716 wtap_dump_set_addrinfo_list(pdh, addr_lists);
5718 /* Iterate through the list of packets, processing all the packets. */
5719 callback_args.pdh = pdh;
5720 callback_args.fname = fname;
5721 callback_args.file_type = save_format;
5722 switch (process_specified_records(cf, NULL, "Saving", "packets",
5723 true, save_record, &callback_args, true)) {
5725 case PSP_FINISHED:
5726 /* Completed successfully. */
5727 break;
5729 case PSP_STOPPED:
5730 /* The user decided to abort the saving.
5731 If we're writing to a temporary file, remove it.
5732 XXX - should we do so even if we're not writing to a
5733 temporary file? */
5734 wtap_dump_close(pdh, NULL, &err, &err_info);
5735 if (fname_new != NULL)
5736 ws_unlink(fname_new);
5737 cf_callback_invoke(cf_cb_file_save_stopped, NULL);
5738 wtap_dump_params_cleanup(&params);
5739 return CF_WRITE_ABORTED;
5741 case PSP_FAILED:
5742 /* Error while saving.
5743 If we're writing to a temporary file, remove it. */
5744 if (fname_new != NULL)
5745 ws_unlink(fname_new);
5746 wtap_dump_close(pdh, NULL, &err, &err_info);
5747 wtap_dump_params_cleanup(&params);
5748 goto fail;
5751 if (!wtap_dump_close(pdh, &needs_reload, &err, &err_info)) {
5752 cfile_close_failure_alert_box(fname, err, err_info);
5753 wtap_dump_params_cleanup(&params);
5754 goto fail;
5757 wtap_dump_params_cleanup(&params);
5760 if (fname_new != NULL) {
5761 /* We wrote out to fname_new, and should rename it on top of
5762 fname. fname_new is now closed, so that should be possible even
5763 on Windows. However, on Windows, we first need to close whatever
5764 file descriptors we have open for fname. */
5765 #ifdef _WIN32
5766 wtap_fdclose(cf->provider.wth);
5767 #endif
5768 /* Now do the rename. */
5769 if (ws_rename(fname_new, fname) == -1) {
5770 /* Well, the rename failed. */
5771 cf_rename_failure_alert_box(fname, errno);
5772 #ifdef _WIN32
5773 /* Attempt to reopen the random file descriptor using the
5774 current file's filename. (At this point, the sequential
5775 file descriptor is closed.) */
5776 if (!wtap_fdreopen(cf->provider.wth, cf->filename, &err)) {
5777 /* Oh, well, we're screwed. */
5778 display_basename = g_filename_display_basename(cf->filename);
5779 simple_error_message_box(
5780 file_open_error_message(err, false), display_basename);
5781 g_free(display_basename);
5783 #endif
5784 goto fail;
5786 g_free(fname_new);
5789 /* If this was a temporary file, and we didn't do the save by doing
5790 a move, so the tempoary file is still around under its old name,
5791 remove it. */
5792 if (cf->is_tempfile && how_to_save != SAVE_WITH_MOVE) {
5793 /* If this fails, there's not much we can do, so just ignore errors. */
5794 ws_unlink(cf->filename);
5797 cf_callback_invoke(cf_cb_file_save_finished, NULL);
5798 cf->unsaved_changes = false;
5800 if (!dont_reopen) {
5801 switch (how_to_save) {
5803 case SAVE_WITH_MOVE:
5804 /* We just moved the file, so the wtap structure refers to the
5805 new file, and all the information other than the filename
5806 and the "is temporary" status applies to the new file; just
5807 update that. */
5808 g_free(cf->filename);
5809 cf->filename = g_strdup(fname);
5810 cf->is_tempfile = false;
5811 cf_callback_invoke(cf_cb_file_fast_save_finished, cf);
5812 break;
5814 case SAVE_WITH_COPY:
5815 /* We just copied the file, so all the information other than
5816 the file descriptors, the filename, and the "is temporary"
5817 status applies to the new file; just update that. */
5818 wtap_fdclose(cf->provider.wth);
5819 /* Attempt to reopen the random file descriptor using the
5820 new file's filename. (At this point, the sequential
5821 file descriptor is closed.) */
5822 if (!wtap_fdreopen(cf->provider.wth, fname, &err)) {
5823 cfile_open_failure_alert_box(fname, err, err_info);
5824 cf_close(cf);
5825 } else {
5826 g_free(cf->filename);
5827 cf->filename = g_strdup(fname);
5828 cf->is_tempfile = false;
5830 cf_callback_invoke(cf_cb_file_fast_save_finished, cf);
5831 break;
5833 case SAVE_WITH_WTAP:
5834 /* Open and read the file we saved to.
5836 XXX - this is somewhat of a waste; we already have the
5837 packets, all this gets us is updated file type information
5838 (which we could just stuff into "cf"), and having the new
5839 file be the one we have opened and from which we're reading
5840 the data, and it means we have to spend time opening and
5841 reading the file, which could be a significant amount of
5842 time if the file is large.
5844 If the capture-file-writing code were to return the
5845 seek offset of each packet it writes, we could save that
5846 in the frame_data structure for the frame, and just open
5847 the file without reading it again...
5849 ...as long as, for gzipped files, the process of writing
5850 out the file *also* generates the information needed to
5851 support fast random access to the compressed file. */
5852 /* rescan_file will cause us to try all open_routines, so
5853 reset cfile's open_type */
5854 cf->open_type = WTAP_TYPE_AUTO;
5855 /* There are cases when SAVE_WITH_WTAP can result in new packets
5856 being written to the file, e.g ERF records
5857 In that case, we need to reload the whole file */
5858 if(needs_reload) {
5859 if (cf_open(cf, fname, WTAP_TYPE_AUTO, false, &err) == CF_OK) {
5860 if (cf_read(cf, /*reloading=*/true) != CF_READ_OK) {
5861 /* The rescan failed; just close the file. Either
5862 a dialog was popped up for the failure, so the
5863 user knows what happened, or they stopped the
5864 rescan, in which case they know what happened. */
5865 /* XXX: This is inconsistent with normal open/reload behaviour. */
5866 cf_close(cf);
5870 else {
5871 if (rescan_file(cf, fname, false) != CF_READ_OK) {
5872 /* The rescan failed; just close the file. Either
5873 a dialog was popped up for the failure, so the
5874 user knows what happened, or they stopped the
5875 rescan, in which case they know what happened. */
5876 cf_close(cf);
5879 break;
5882 /* If we were told to discard the comments, do so. */
5883 if (discard_comments) {
5884 /* Remove SHB comment, if any. */
5885 wtap_write_shb_comment(cf->provider.wth, NULL);
5887 /* remove all user comments */
5888 for (framenum = 1; framenum <= cf->count; framenum++) {
5889 fdata = frame_data_sequence_find(cf->provider.frames, framenum);
5891 // XXX: This also ignores non-comment options like verdict
5892 fdata->has_modified_block = false;
5895 if (cf->provider.frames_modified_blocks) {
5896 g_tree_destroy(cf->provider.frames_modified_blocks);
5897 cf->provider.frames_modified_blocks = NULL;
5900 cf->packet_comment_count = 0;
5903 return CF_WRITE_OK;
5905 fail:
5906 if (fname_new != NULL) {
5907 /* We were trying to write to a temporary file; get rid of it if it
5908 exists. (We don't care whether this fails, as, if it fails,
5909 there's not much we can do about it. I guess if it failed for
5910 a reason other than "it doesn't exist", we could report an
5911 error, so the user knows there's a junk file that they might
5912 want to clean up.) */
5913 ws_unlink(fname_new);
5914 g_free(fname_new);
5916 cf_callback_invoke(cf_cb_file_save_failed, NULL);
5917 return CF_WRITE_ERROR;
5920 cf_write_status_t
5921 cf_export_specified_packets(capture_file *cf, const char *fname,
5922 packet_range_t *range, unsigned save_format,
5923 wtap_compression_type compression_type)
5925 char *fname_new = NULL;
5926 int err;
5927 char *err_info;
5928 wtap_dumper *pdh;
5929 save_callback_args_t callback_args;
5930 wtap_dump_params params;
5931 int encap;
5933 callback_args.export = true;
5934 packet_range_process_init(range);
5936 /* We're writing out specified packets from the specified capture
5937 file to another file. Even if all captured packets are to be
5938 written, don't special-case the operation - read each packet
5939 and then write it out if it's one of the specified ones. */
5941 wtap_dump_params_init(&params, cf->provider.wth);
5943 /* Determine what file encapsulation type we should use. */
5944 encap = wtap_dump_required_file_encap_type(cf->linktypes);
5945 params.encap = encap;
5947 /* Use the snaplen from cf (XXX - does wtap_dump_params_init handle that?) */
5948 params.snaplen = cf->snap;
5950 if (file_exists(fname)) {
5951 /* We're overwriting an existing file; write out to a new file,
5952 and, if that succeeds, rename the new file on top of the
5953 old file. That makes this a "safe save", so that we don't
5954 lose the old file if we have a problem writing out the new
5955 file. (If the existing file is the current capture file,
5956 we *HAVE* to do that, otherwise we're overwriting the file
5957 from which we're reading the packets that we're writing!) */
5958 fname_new = ws_strdup_printf("%s~", fname);
5959 pdh = wtap_dump_open(fname_new, save_format, compression_type, &params,
5960 &err, &err_info);
5961 } else {
5962 pdh = wtap_dump_open(fname, save_format, compression_type, &params,
5963 &err, &err_info);
5965 /* XXX idb_inf is documented to be used until wtap_dump_close. */
5966 g_free(params.idb_inf);
5967 params.idb_inf = NULL;
5969 if (pdh == NULL) {
5970 cfile_dump_open_failure_alert_box(fname, err, err_info, save_format);
5971 goto fail;
5974 /* Add address resolution */
5975 wtap_dump_set_addrinfo_list(pdh, get_addrinfo_list());
5977 /* Iterate through the list of packets, processing the packets we were
5978 told to process.
5980 XXX - we've already called "packet_range_process_init(range)", but
5981 "process_specified_records()" will do it again. Fortunately,
5982 that's harmless in this case, as we haven't done anything to
5983 "range" since we initialized it. */
5984 callback_args.pdh = pdh;
5985 callback_args.fname = fname;
5986 callback_args.file_type = save_format;
5987 switch (process_specified_records(cf, range, "Writing", "specified records",
5988 true, save_record, &callback_args, true)) {
5990 case PSP_FINISHED:
5991 /* Completed successfully. */
5992 break;
5994 case PSP_STOPPED:
5995 /* The user decided to abort the saving.
5996 If we're writing to a temporary file, remove it.
5997 XXX - should we do so even if we're not writing to a
5998 temporary file? */
5999 wtap_dump_close(pdh, NULL, &err, &err_info);
6000 if (fname_new != NULL) {
6001 ws_unlink(fname_new);
6002 g_free(fname_new);
6004 wtap_dump_params_cleanup(&params);
6006 return CF_WRITE_ABORTED;
6008 case PSP_FAILED:
6009 /* Error while saving. */
6010 wtap_dump_close(pdh, NULL, &err, &err_info);
6012 * We don't report any error from closing; the error that caused
6013 * process_specified_records() to fail has already been reported.
6015 goto fail;
6018 if (!wtap_dump_close(pdh, NULL, &err, &err_info)) {
6019 cfile_close_failure_alert_box(fname, err, err_info);
6020 goto fail;
6023 if (fname_new != NULL) {
6024 /* We wrote out to fname_new, and should rename it on top of
6025 fname; fname is now closed, so that should be possible even
6026 on Windows. Do the rename. */
6027 if (ws_rename(fname_new, fname) == -1) {
6028 /* Well, the rename failed. */
6029 cf_rename_failure_alert_box(fname, errno);
6030 goto fail;
6032 g_free(fname_new);
6034 wtap_dump_params_cleanup(&params);
6036 return CF_WRITE_OK;
6038 fail:
6039 if (fname_new != NULL) {
6040 /* We were trying to write to a temporary file; get rid of it if it
6041 exists. (We don't care whether this fails, as, if it fails,
6042 there's not much we can do about it. I guess if it failed for
6043 a reason other than "it doesn't exist", we could report an
6044 error, so the user knows there's a junk file that they might
6045 want to clean up.) */
6046 ws_unlink(fname_new);
6047 g_free(fname_new);
6049 wtap_dump_params_cleanup(&params);
6051 return CF_WRITE_ERROR;
6055 * XXX - whether we mention the source pathname, the target pathname,
6056 * or both depends on the error and on what we find if we look for
6057 * one or both of them.
6059 static void
6060 cf_rename_failure_alert_box(const char *filename, int err)
6062 char *display_basename;
6064 display_basename = g_filename_display_basename(filename);
6065 switch (err) {
6067 case ENOENT:
6068 /* XXX - should check whether the source exists and, if not,
6069 report it as the problem and, if so, report the destination
6070 as the problem. */
6071 simple_error_message_box("The path to the file \"%s\" doesn't exist.",
6072 display_basename);
6073 break;
6075 case EACCES:
6076 /* XXX - if we're doing a rename after a safe save, we should
6077 probably say something else. */
6078 simple_error_message_box("You don't have permission to move the capture file to \"%s\".",
6079 display_basename);
6080 break;
6082 default:
6083 /* XXX - this should probably mention both the source and destination
6084 pathnames. */
6085 simple_error_message_box("The file \"%s\" could not be moved: %s.",
6086 display_basename, wtap_strerror(err));
6087 break;
6089 g_free(display_basename);
6092 /* Reload the current capture file. */
6093 cf_status_t
6094 cf_reload(capture_file *cf)
6096 char *filename;
6097 bool is_tempfile;
6098 cf_status_t cf_status = CF_OK;
6099 int err;
6101 if (cf->read_lock) {
6102 ws_warning("Failing cf_reload(\"%s\") since a read is in progress", cf->filename);
6103 return CF_ERROR;
6106 /* If the file could be opened, "cf_open()" calls "cf_close()"
6107 to get rid of state for the old capture file before filling in state
6108 for the new capture file. "cf_close()" will remove the file if
6109 it's a temporary file; we don't want that to happen (for one thing,
6110 it'd prevent subsequent reopens from working). Remember whether it's
6111 a temporary file, mark it as not being a temporary file, and then
6112 reopen it as the type of file it was.
6114 Also, "cf_close()" will free "cf->filename", so we must make
6115 a copy of it first. */
6116 filename = g_strdup(cf->filename);
6117 is_tempfile = cf->is_tempfile;
6118 cf->is_tempfile = false;
6119 if (cf_open(cf, filename, cf->open_type, is_tempfile, &err) == CF_OK) {
6120 switch (cf_read(cf, /*reloading=*/true)) {
6122 case CF_READ_OK:
6123 case CF_READ_ERROR:
6124 /* Just because we got an error, that doesn't mean we were unable
6125 to read any of the file; we handle what we could get from the
6126 file. */
6127 break;
6129 case CF_READ_ABORTED:
6130 /* The user bailed out of re-reading the capture file; the
6131 capture file has been closed. */
6132 break;
6134 } else {
6135 /* The open failed, so "cf->is_tempfile" wasn't set to "is_tempfile".
6136 Instead, the file was left open, so we should restore "cf->is_tempfile"
6137 ourselves.
6139 XXX - change the menu? Presumably "cf_open()" will do that;
6140 make sure it does! */
6141 cf->is_tempfile = is_tempfile;
6142 cf_status = CF_ERROR;
6144 /* "cf_open()" made a copy of the file name we handed it, so
6145 we should free up our copy. */
6146 g_free(filename);
6147 return cf_status;