If we save a temporary file by copying or writing, remove it when we're done.
[metze/wireshark/wip.git] / file.c
1 /* file.c
2  * File I/O routines
3  *
4  * Wireshark - Network traffic analyzer
5  * By Gerald Combs <gerald@wireshark.org>
6  * Copyright 1998 Gerald Combs
7  *
8  * SPDX-License-Identifier: GPL-2.0+
9  */
10
11 #include <config.h>
12
13 #include <time.h>
14
15 #include <stdlib.h>
16 #include <stdio.h>
17 #include <string.h>
18 #include <ctype.h>
19 #include <errno.h>
20
21 #include <wsutil/tempfile.h>
22 #include <wsutil/file_util.h>
23 #include <wsutil/filesystem.h>
24 #include <version_info.h>
25
26 #include <wiretap/merge.h>
27
28 #include <epan/exceptions.h>
29 #include <epan/epan.h>
30 #include <epan/column.h>
31 #include <epan/packet.h>
32 #include <epan/column-utils.h>
33 #include <epan/expert.h>
34 #include <epan/prefs.h>
35 #include <epan/dfilter/dfilter.h>
36 #include <epan/epan_dissect.h>
37 #include <epan/tap.h>
38 #include <epan/dissectors/packet-ber.h>
39 #include <epan/timestamp.h>
40 #include <epan/dfilter/dfilter-macro.h>
41 #include <epan/strutil.h>
42 #include <epan/addr_resolv.h>
43 #include <epan/color_filters.h>
44
45 #include "cfile.h"
46 #include "file.h"
47 #include "fileset.h"
48 #include "frame_tvbuff.h"
49
50 #include "ui/alert_box.h"
51 #include "ui/simple_dialog.h"
52 #include "ui/main_statusbar.h"
53 #include "ui/progress_dlg.h"
54 #include "ui/ws_ui_util.h"
55
56 /* Needed for addrinfo */
57 #ifdef HAVE_SYS_TYPES_H
58 # include <sys/types.h>
59 #endif
60
61 #ifdef HAVE_SYS_SOCKET_H
62 #include <sys/socket.h>
63 #endif
64
65 #ifdef HAVE_NETINET_IN_H
66 # include <netinet/in.h>
67 #endif
68
69 #ifdef _WIN32
70 # include <winsock2.h>
71 # include <ws2tcpip.h>
72 #endif
73
74 #ifdef HAVE_LIBPCAP
75 gboolean auto_scroll_live; /* GTK+ only? */
76 #endif
77
78 static int read_packet(capture_file *cf, dfilter_t *dfcode, epan_dissect_t *edt,
79     column_info *cinfo, gint64 offset);
80
81 static void rescan_packets(capture_file *cf, const char *action, const char *action_item, gboolean redissect);
82
83 typedef enum {
84   MR_NOTMATCHED,
85   MR_MATCHED,
86   MR_ERROR
87 } match_result;
88 static match_result match_protocol_tree(capture_file *cf, frame_data *fdata,
89     void *criterion);
90 static void match_subtree_text(proto_node *node, gpointer data);
91 static match_result match_summary_line(capture_file *cf, frame_data *fdata,
92     void *criterion);
93 static match_result match_narrow_and_wide(capture_file *cf, frame_data *fdata,
94     void *criterion);
95 static match_result match_narrow(capture_file *cf, frame_data *fdata,
96     void *criterion);
97 static match_result match_wide(capture_file *cf, frame_data *fdata,
98     void *criterion);
99 static match_result match_binary(capture_file *cf, frame_data *fdata,
100     void *criterion);
101 static match_result match_regex(capture_file *cf, frame_data *fdata,
102     void *criterion);
103 static match_result match_dfilter(capture_file *cf, frame_data *fdata,
104     void *criterion);
105 static match_result match_marked(capture_file *cf, frame_data *fdata,
106     void *criterion);
107 static match_result match_time_reference(capture_file *cf, frame_data *fdata,
108     void *criterion);
109 static gboolean find_packet(capture_file *cf,
110     match_result (*match_function)(capture_file *, frame_data *, void *),
111     void *criterion, search_direction dir);
112
113 static void cf_rename_failure_alert_box(const char *filename, int err);
114 static void ref_time_packets(capture_file *cf);
115
116 /* Seconds spent processing packets between pushing UI updates. */
117 #define PROGBAR_UPDATE_INTERVAL 0.150
118
119 /* Show the progress bar after this many seconds. */
120 #define PROGBAR_SHOW_DELAY 0.5
121
122 /*
123  * We could probably use g_signal_...() instead of the callbacks below but that
124  * would require linking our CLI programs to libgobject and creating an object
125  * instance for the signals.
126  */
127 typedef struct {
128   cf_callback_t cb_fct;
129   gpointer      user_data;
130 } cf_callback_data_t;
131
132 static GList *cf_callbacks = NULL;
133
134 static void
135 cf_callback_invoke(int event, gpointer data)
136 {
137   cf_callback_data_t *cb;
138   GList              *cb_item = cf_callbacks;
139
140   /* there should be at least one interested */
141   g_assert(cb_item != NULL);
142
143   while (cb_item != NULL) {
144     cb = (cf_callback_data_t *)cb_item->data;
145     cb->cb_fct(event, data, cb->user_data);
146     cb_item = g_list_next(cb_item);
147   }
148 }
149
150
151 void
152 cf_callback_add(cf_callback_t func, gpointer user_data)
153 {
154   cf_callback_data_t *cb;
155
156   cb = g_new(cf_callback_data_t,1);
157   cb->cb_fct = func;
158   cb->user_data = user_data;
159
160   cf_callbacks = g_list_prepend(cf_callbacks, cb);
161 }
162
163 void
164 cf_callback_remove(cf_callback_t func, gpointer user_data)
165 {
166   cf_callback_data_t *cb;
167   GList              *cb_item = cf_callbacks;
168
169   while (cb_item != NULL) {
170     cb = (cf_callback_data_t *)cb_item->data;
171     if (cb->cb_fct == func && cb->user_data == user_data) {
172       cf_callbacks = g_list_remove(cf_callbacks, cb);
173       g_free(cb);
174       return;
175     }
176     cb_item = g_list_next(cb_item);
177   }
178
179   g_assert_not_reached();
180 }
181
182 void
183 cf_timestamp_auto_precision(capture_file *cf)
184 {
185   int i;
186
187   /* don't try to get the file's precision if none is opened */
188   if (cf->state == FILE_CLOSED) {
189     return;
190   }
191
192   /* Set the column widths of those columns that show the time in
193      "command-line-specified" format. */
194   for (i = 0; i < cf->cinfo.num_cols; i++) {
195     if (col_has_time_fmt(&cf->cinfo, i)) {
196       packet_list_resize_column(i);
197     }
198   }
199 }
200
201 gulong
202 cf_get_computed_elapsed(capture_file *cf)
203 {
204   return cf->computed_elapsed;
205 }
206
207 /*
208  * GLIB_CHECK_VERSION(2,28,0) adds g_get_real_time which could minimize or
209  * replace this
210  */
211 static void compute_elapsed(capture_file *cf, GTimeVal *start_time)
212 {
213   gdouble  delta_time;
214   GTimeVal time_now;
215
216   g_get_current_time(&time_now);
217
218   delta_time = (time_now.tv_sec - start_time->tv_sec) * 1e6 +
219     time_now.tv_usec - start_time->tv_usec;
220
221   cf->computed_elapsed = (gulong) (delta_time / 1000); /* ms */
222 }
223
224 static const nstime_t *
225 ws_get_frame_ts(struct packet_provider_data *prov, guint32 frame_num)
226 {
227   if (prov->prev_dis && prov->prev_dis->num == frame_num)
228     return &prov->prev_dis->abs_ts;
229
230   if (prov->prev_cap && prov->prev_cap->num == frame_num)
231     return &prov->prev_cap->abs_ts;
232
233   if (prov->frames) {
234     frame_data *fd = frame_data_sequence_find(prov->frames, frame_num);
235
236     return (fd) ? &fd->abs_ts : NULL;
237   }
238
239   return NULL;
240 }
241
242 static epan_t *
243 ws_epan_new(capture_file *cf)
244 {
245   static const struct packet_provider_funcs funcs = {
246     ws_get_frame_ts,
247     cap_file_provider_get_interface_name,
248     cap_file_provider_get_interface_description,
249     cap_file_provider_get_user_comment
250   };
251
252   return epan_new(&cf->provider, &funcs);
253 }
254
255 cf_status_t
256 cf_open(capture_file *cf, const char *fname, unsigned int type, gboolean is_tempfile, int *err)
257 {
258   wtap  *wth;
259   gchar *err_info;
260
261   wth = wtap_open_offline(fname, type, err, &err_info, TRUE);
262   if (wth == NULL)
263     goto fail;
264
265   /* The open succeeded.  Close whatever capture file we had open,
266      and fill in the information for this file. */
267   cf_close(cf);
268
269   /* Initialize the packet header. */
270   wtap_phdr_init(&cf->phdr);
271
272   /* XXX - we really want to initialize this after we've read all
273      the packets, so we know how much we'll ultimately need. */
274   ws_buffer_init(&cf->buf, 1500);
275
276   /* Create new epan session for dissection.
277    * (The old one was freed in cf_close().)
278    */
279   cf->epan = ws_epan_new(cf);
280
281   /* We're about to start reading the file. */
282   cf->state = FILE_READ_IN_PROGRESS;
283
284   cf->provider.wth = wth;
285   cf->f_datalen = 0;
286
287   /* Set the file name because we need it to set the follow stream filter.
288      XXX - is that still true?  We need it for other reasons, though,
289      in any case. */
290   cf->filename = g_strdup(fname);
291
292   /* Indicate whether it's a permanent or temporary file. */
293   cf->is_tempfile = is_tempfile;
294
295   /* No user changes yet. */
296   cf->unsaved_changes = FALSE;
297
298   cf->computed_elapsed = 0;
299
300   cf->cd_t        = wtap_file_type_subtype(cf->provider.wth);
301   cf->open_type   = type;
302   cf->linktypes = g_array_sized_new(FALSE, FALSE, (guint) sizeof(int), 1);
303   cf->count     = 0;
304   cf->packet_comment_count = 0;
305   cf->displayed_count = 0;
306   cf->marked_count = 0;
307   cf->ignored_count = 0;
308   cf->ref_time_count = 0;
309   cf->drops_known = FALSE;
310   cf->drops     = 0;
311   cf->snap      = wtap_snapshot_length(cf->provider.wth);
312
313   /* Allocate a frame_data_sequence for the frames in this file */
314   cf->provider.frames = new_frame_data_sequence();
315
316   nstime_set_zero(&cf->elapsed_time);
317   cf->provider.ref = NULL;
318   cf->provider.prev_dis = NULL;
319   cf->provider.prev_cap = NULL;
320   cf->cum_bytes = 0;
321
322   packet_list_queue_draw();
323   cf_callback_invoke(cf_cb_file_opened, cf);
324
325   if (cf->cd_t == WTAP_FILE_TYPE_SUBTYPE_BER) {
326     /* tell the BER dissector the file name */
327     ber_set_filename(cf->filename);
328   }
329
330   wtap_set_cb_new_ipv4(cf->provider.wth, add_ipv4_name);
331   wtap_set_cb_new_ipv6(cf->provider.wth, (wtap_new_ipv6_callback_t) add_ipv6_name);
332
333   return CF_OK;
334
335 fail:
336   cfile_open_failure_alert_box(fname, *err, err_info);
337   return CF_ERROR;
338 }
339
340 /*
341  * Add an encapsulation type to cf->linktypes.
342  */
343 static void
344 cf_add_encapsulation_type(capture_file *cf, int encap)
345 {
346   guint i;
347
348   for (i = 0; i < cf->linktypes->len; i++) {
349     if (g_array_index(cf->linktypes, gint, i) == encap)
350       return; /* it's already there */
351   }
352   /* It's not already there - add it. */
353   g_array_append_val(cf->linktypes, encap);
354 }
355
356 /* Reset everything to a pristine state */
357 void
358 cf_close(capture_file *cf)
359 {
360   cf->stop_flag = FALSE;
361   if (cf->state == FILE_CLOSED)
362     return; /* Nothing to do */
363
364   /* Die if we're in the middle of reading a file. */
365   g_assert(cf->state != FILE_READ_IN_PROGRESS);
366
367   cf_callback_invoke(cf_cb_file_closing, cf);
368
369   /* close things, if not already closed before */
370   color_filters_cleanup();
371
372   if (cf->provider.wth) {
373     wtap_close(cf->provider.wth);
374     cf->provider.wth = NULL;
375   }
376   /* We have no file open... */
377   if (cf->filename != NULL) {
378     /* If it's a temporary file, remove it. */
379     if (cf->is_tempfile)
380       ws_unlink(cf->filename);
381     g_free(cf->filename);
382     cf->filename = NULL;
383   }
384   /* ...which means we have no changes to that file to save. */
385   cf->unsaved_changes = FALSE;
386
387   /* no open_routine type */
388   cf->open_type = WTAP_TYPE_AUTO;
389
390   /* Clean up the packet header. */
391   wtap_phdr_cleanup(&cf->phdr);
392
393   /* Free up the packet buffer. */
394   ws_buffer_free(&cf->buf);
395
396   dfilter_free(cf->rfcode);
397   cf->rfcode = NULL;
398   if (cf->provider.frames != NULL) {
399     free_frame_data_sequence(cf->provider.frames);
400     cf->provider.frames = NULL;
401   }
402   if (cf->provider.frames_user_comments) {
403     g_tree_destroy(cf->provider.frames_user_comments);
404     cf->provider.frames_user_comments = NULL;
405   }
406   cf_unselect_packet(cf);   /* nothing to select */
407   cf->first_displayed = 0;
408   cf->last_displayed = 0;
409
410   /* No frames, no frame selected, no field in that frame selected. */
411   cf->count = 0;
412   cf->current_frame = 0;
413   cf->current_row = 0;
414   cf->finfo_selected = NULL;
415
416   /* No frame link-layer types, either. */
417   if (cf->linktypes != NULL) {
418     g_array_free(cf->linktypes, TRUE);
419     cf->linktypes = NULL;
420   }
421
422   /* Clear the packet list. */
423   packet_list_freeze();
424   packet_list_clear();
425   packet_list_thaw();
426
427   cf->f_datalen = 0;
428   nstime_set_zero(&cf->elapsed_time);
429
430   reset_tap_listeners();
431
432   epan_free(cf->epan);
433   cf->epan = NULL;
434
435   /* We have no file open. */
436   cf->state = FILE_CLOSED;
437
438   cf_callback_invoke(cf_cb_file_closed, cf);
439 }
440
441 /*
442  * TRUE if the progress dialog doesn't exist and it looks like we'll
443  * take > 2s to load, FALSE otherwise.
444  */
445 static inline gboolean
446 progress_is_slow(progdlg_t *progdlg, GTimer *prog_timer, gint64 size, gint64 pos)
447 {
448   double elapsed;
449
450   if (progdlg) return FALSE;
451   elapsed = g_timer_elapsed(prog_timer, NULL);
452   if ((elapsed / 2 > PROGBAR_SHOW_DELAY && (size / pos) > 2) /* It looks like we're going to be slow. */
453       || elapsed > PROGBAR_SHOW_DELAY) { /* We are indeed slow. */
454     return TRUE;
455   }
456   return FALSE;
457 }
458
459 static float
460 calc_progbar_val(capture_file *cf, gint64 size, gint64 file_pos, gchar *status_str, gulong status_size)
461 {
462   float progbar_val;
463
464   progbar_val = (gfloat) file_pos / (gfloat) size;
465   if (progbar_val > 1.0) {
466
467     /*  The file probably grew while we were reading it.
468      *  Update file size, and try again.
469      */
470     size = wtap_file_size(cf->provider.wth, NULL);
471
472     if (size >= 0)
473       progbar_val = (gfloat) file_pos / (gfloat) size;
474
475     /*  If it's still > 1, either "wtap_file_size()" failed (in which
476      *  case there's not much we can do about it), or the file
477      *  *shrank* (in which case there's not much we can do about
478      *  it); just clip the progress value at 1.0.
479      */
480     if (progbar_val > 1.0f)
481       progbar_val = 1.0f;
482   }
483
484   g_snprintf(status_str, status_size,
485              "%" G_GINT64_MODIFIER "dKB of %" G_GINT64_MODIFIER "dKB",
486              file_pos / 1024, size / 1024);
487
488   return progbar_val;
489 }
490
491 cf_read_status_t
492 cf_read(capture_file *cf, gboolean reloading)
493 {
494   int                  err = 0;
495   gchar               *err_info = NULL;
496   gchar               *name_ptr;
497   progdlg_t           *volatile progbar = NULL;
498   GTimer              *prog_timer = g_timer_new();
499   GTimeVal             start_time;
500   epan_dissect_t       edt;
501   dfilter_t           *dfcode;
502   volatile gboolean    create_proto_tree;
503   guint                tap_flags;
504   gboolean             compiled;
505   volatile gboolean    is_read_aborted = FALSE;
506
507   /* Compile the current display filter.
508    * We assume this will not fail since cf->dfilter is only set in
509    * cf_filter IFF the filter was valid.
510    */
511   compiled = dfilter_compile(cf->dfilter, &dfcode, NULL);
512   g_assert(!cf->dfilter || (compiled && dfcode));
513
514   /* Get the union of the flags for all tap listeners. */
515   tap_flags = union_of_tap_listener_flags();
516
517   /*
518    * Determine whether we need to create a protocol tree.
519    * We do if:
520    *
521    *    we're going to apply a display filter;
522    *
523    *    one of the tap listeners is going to apply a filter;
524    *
525    *    one of the tap listeners requires a protocol tree;
526    *
527    *    a postdissector wants field values or protocols on
528    *    the first pass.
529    */
530   create_proto_tree =
531     (dfcode != NULL || have_filtering_tap_listeners() ||
532      (tap_flags & TL_REQUIRES_PROTO_TREE) || postdissectors_want_hfids());
533
534   reset_tap_listeners();
535
536   name_ptr = g_filename_display_basename(cf->filename);
537
538   if (reloading)
539     cf_callback_invoke(cf_cb_file_reload_started, cf);
540   else
541     cf_callback_invoke(cf_cb_file_read_started, cf);
542
543   /* Record whether the file is compressed.
544      XXX - do we know this at open time? */
545   cf->iscompressed = wtap_iscompressed(cf->provider.wth);
546
547   /* The packet list window will be empty until the file is completly loaded */
548   packet_list_freeze();
549
550   cf->stop_flag = FALSE;
551   g_get_current_time(&start_time);
552
553   epan_dissect_init(&edt, cf->epan, create_proto_tree, FALSE);
554
555   TRY {
556     int     count             = 0;
557
558     gint64  size;
559     gint64  file_pos;
560     gint64  data_offset;
561
562     float   progbar_val;
563     gchar   status_str[100];
564
565     column_info *cinfo;
566
567     /* If any tap listeners require the columns, construct them. */
568     cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
569
570     /* Find the size of the file. */
571     size = wtap_file_size(cf->provider.wth, NULL);
572
573     g_timer_start(prog_timer);
574
575     while ((wtap_read(cf->provider.wth, &err, &err_info, &data_offset))) {
576       if (size >= 0) {
577         count++;
578         file_pos = wtap_read_so_far(cf->provider.wth);
579
580         /* Create the progress bar if necessary. */
581         if (progress_is_slow(progbar, prog_timer, size, file_pos)) {
582           progbar_val = calc_progbar_val(cf, size, file_pos, status_str, sizeof(status_str));
583           if (reloading)
584             progbar = delayed_create_progress_dlg(cf->window, "Reloading", name_ptr,
585                 TRUE, &cf->stop_flag, &start_time, progbar_val);
586           else
587             progbar = delayed_create_progress_dlg(cf->window, "Loading", name_ptr,
588                 TRUE, &cf->stop_flag, &start_time, progbar_val);
589         }
590
591         /*
592          * Update the progress bar, but do it only after
593          * PROGBAR_UPDATE_INTERVAL has elapsed. Calling update_progress_dlg
594          * and packets_bar_update will likely trigger UI paint events, which
595          * might take a while depending on the platform and display. Reset
596          * our timer *after* painting.
597          */
598         if (progbar && g_timer_elapsed(prog_timer, NULL) > PROGBAR_UPDATE_INTERVAL) {
599           progbar_val = calc_progbar_val(cf, size, file_pos, status_str, sizeof(status_str));
600           /* update the packet bar content on the first run or frequently on very large files */
601           update_progress_dlg(progbar, progbar_val, status_str);
602           compute_elapsed(cf, &start_time);
603           packets_bar_update();
604           g_timer_start(prog_timer);
605         }
606       }
607
608       if (cf->state == FILE_READ_ABORTED) {
609         /* Well, the user decided to exit Wireshark.  Break out of the
610            loop, and let the code below (which is called even if there
611            aren't any packets left to read) exit. */
612         is_read_aborted = TRUE;
613         break;
614       }
615       if (cf->stop_flag) {
616         /* Well, the user decided to abort the read. He/She will be warned and
617            it might be enough for him/her to work with the already loaded
618            packets.
619            This is especially true for very large capture files, where you don't
620            want to wait loading the whole file (which may last minutes or even
621            hours even on fast machines) just to see that it was the wrong file. */
622         break;
623       }
624       read_packet(cf, dfcode, &edt, cinfo, data_offset);
625     }
626   }
627   CATCH(OutOfMemoryError) {
628     simple_message_box(ESD_TYPE_ERROR, NULL,
629                    "More information and workarounds can be found at\n"
630                    "https://wiki.wireshark.org/KnownBugs/OutOfMemory",
631                    "Sorry, but Wireshark has run out of memory and has to terminate now.");
632 #if 0
633     /* Could we close the current capture and free up memory from that? */
634 #else
635     /* we have to terminate, as we cannot recover from the memory error */
636     exit(1);
637 #endif
638   }
639   ENDTRY;
640
641   /* Free the display name */
642   g_free(name_ptr);
643
644   /* Cleanup and release all dfilter resources */
645   dfilter_free(dfcode);
646
647   epan_dissect_cleanup(&edt);
648
649   /* We're done reading the file; destroy the progress bar if it was created. */
650   if (progbar != NULL)
651     destroy_progress_dlg(progbar);
652   g_timer_destroy(prog_timer);
653
654   /* We're done reading sequentially through the file. */
655   cf->state = FILE_READ_DONE;
656
657   /* Close the sequential I/O side, to free up memory it requires. */
658   wtap_sequential_close(cf->provider.wth);
659
660   /* Allow the protocol dissectors to free up memory that they
661    * don't need after the sequential run-through of the packets. */
662   postseq_cleanup_all_protocols();
663
664   /* compute the time it took to load the file */
665   compute_elapsed(cf, &start_time);
666
667   /* Set the file encapsulation type now; we don't know what it is until
668      we've looked at all the packets, as we don't know until then whether
669      there's more than one type (and thus whether it's
670      WTAP_ENCAP_PER_PACKET). */
671   cf->lnk_t = wtap_file_encap(cf->provider.wth);
672
673   cf->current_frame = frame_data_sequence_find(cf->provider.frames, cf->first_displayed);
674   cf->current_row = 0;
675
676   packet_list_thaw();
677   if (reloading)
678     cf_callback_invoke(cf_cb_file_reload_finished, cf);
679   else
680     cf_callback_invoke(cf_cb_file_read_finished, cf);
681
682   /* If we have any displayed packets to select, select the first of those
683      packets by making the first row the selected row. */
684   if (cf->first_displayed != 0) {
685     packet_list_select_first_row();
686   }
687
688   if (is_read_aborted) {
689     /*
690      * Well, the user decided to exit Wireshark while reading this *offline*
691      * capture file (Live captures are handled by something like
692      * cf_continue_tail). Clean up accordingly.
693      */
694     cf_close(cf);
695     return CF_READ_ABORTED;
696   }
697
698   if (cf->stop_flag) {
699     simple_message_box(ESD_TYPE_WARN, NULL,
700                   "The remaining packets in the file were discarded.\n"
701                   "\n"
702                   "As a lot of packets from the original file will be missing,\n"
703                   "remember to be careful when saving the current content to a file.\n",
704                   "File loading was cancelled.");
705     return CF_READ_ERROR;
706   }
707
708   if (err != 0) {
709     /* Put up a message box noting that the read failed somewhere along
710        the line.  Don't throw out the stuff we managed to read, though,
711        if any. */
712     cfile_read_failure_alert_box(NULL, err, err_info);
713     return CF_READ_ERROR;
714   } else
715     return CF_READ_OK;
716 }
717
718 #ifdef HAVE_LIBPCAP
719 cf_read_status_t
720 cf_continue_tail(capture_file *cf, volatile int to_read, int *err)
721 {
722   gchar            *err_info;
723   volatile int      newly_displayed_packets = 0;
724   dfilter_t        *dfcode;
725   epan_dissect_t    edt;
726   gboolean          create_proto_tree;
727   guint             tap_flags;
728   gboolean          compiled;
729
730   /* Compile the current display filter.
731    * We assume this will not fail since cf->dfilter is only set in
732    * cf_filter IFF the filter was valid.
733    */
734   compiled = dfilter_compile(cf->dfilter, &dfcode, NULL);
735   g_assert(!cf->dfilter || (compiled && dfcode));
736
737   /* Get the union of the flags for all tap listeners. */
738   tap_flags = union_of_tap_listener_flags();
739
740   /*
741    * Determine whether we need to create a protocol tree.
742    * We do if:
743    *
744    *    we're going to apply a display filter;
745    *
746    *    one of the tap listeners is going to apply a filter;
747    *
748    *    one of the tap listeners requires a protocol tree;
749    *
750    *    a postdissector wants field values or protocols on
751    *    the first pass.
752    */
753   create_proto_tree =
754     (dfcode != NULL || have_filtering_tap_listeners() ||
755      (tap_flags & TL_REQUIRES_PROTO_TREE) || postdissectors_want_hfids());
756
757   *err = 0;
758
759   packet_list_check_end();
760   /* Don't freeze/thaw the list when doing live capture */
761   /*packet_list_freeze();*/
762
763   /*g_log(NULL, G_LOG_LEVEL_MESSAGE, "cf_continue_tail: %u new: %u", cf->count, to_read);*/
764
765   epan_dissect_init(&edt, cf->epan, create_proto_tree, FALSE);
766
767   TRY {
768     gint64 data_offset = 0;
769     column_info *cinfo;
770
771     /* If any tap listeners require the columns, construct them. */
772     cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
773
774     while (to_read != 0) {
775       wtap_cleareof(cf->provider.wth);
776       if (!wtap_read(cf->provider.wth, err, &err_info, &data_offset)) {
777         break;
778       }
779       if (cf->state == FILE_READ_ABORTED) {
780         /* Well, the user decided to exit Wireshark.  Break out of the
781            loop, and let the code below (which is called even if there
782            aren't any packets left to read) exit. */
783         break;
784       }
785       if (read_packet(cf, dfcode, &edt, (column_info *) cinfo, data_offset) != -1) {
786         newly_displayed_packets++;
787       }
788       to_read--;
789     }
790   }
791   CATCH(OutOfMemoryError) {
792     simple_message_box(ESD_TYPE_ERROR, NULL,
793                    "More information and workarounds can be found at\n"
794                    "https://wiki.wireshark.org/KnownBugs/OutOfMemory",
795                    "Sorry, but Wireshark has run out of memory and has to terminate now.");
796 #if 0
797     /* Could we close the current capture and free up memory from that? */
798     return CF_READ_ABORTED;
799 #else
800     /* we have to terminate, as we cannot recover from the memory error */
801     exit(1);
802 #endif
803   }
804   ENDTRY;
805
806   /* Update the file encapsulation; it might have changed based on the
807      packets we've read. */
808   cf->lnk_t = wtap_file_encap(cf->provider.wth);
809
810   /* Cleanup and release all dfilter resources */
811   dfilter_free(dfcode);
812
813   epan_dissect_cleanup(&edt);
814
815   /*g_log(NULL, G_LOG_LEVEL_MESSAGE, "cf_continue_tail: count %u state: %u err: %u",
816     cf->count, cf->state, *err);*/
817
818   /* Don't freeze/thaw the list when doing live capture */
819   /*packet_list_thaw();*/
820   /* With the new packet list the first packet
821    * isn't automatically selected.
822    */
823   if (!cf->current_frame)
824     packet_list_select_first_row();
825
826   /* moving to the end of the packet list - if the user requested so and
827      we have some new packets. */
828   if (newly_displayed_packets && auto_scroll_live && cf->count != 0)
829       packet_list_moveto_end();
830
831   if (cf->state == FILE_READ_ABORTED) {
832     /* Well, the user decided to exit Wireshark.  Return CF_READ_ABORTED
833        so that our caller can kill off the capture child process;
834        this will cause an EOF on the pipe from the child, so
835        "cf_finish_tail()" will be called, and it will clean up
836        and exit. */
837     return CF_READ_ABORTED;
838   } else if (*err != 0) {
839     /* We got an error reading the capture file.
840        XXX - pop up a dialog box instead? */
841     if (err_info != NULL) {
842       g_warning("Error \"%s\" while reading \"%s\" (\"%s\")",
843                 wtap_strerror(*err), cf->filename, err_info);
844       g_free(err_info);
845     } else {
846       g_warning("Error \"%s\" while reading \"%s\"",
847                 wtap_strerror(*err), cf->filename);
848     }
849     return CF_READ_ERROR;
850   } else
851     return CF_READ_OK;
852 }
853
854 void
855 cf_fake_continue_tail(capture_file *cf) {
856   cf->state = FILE_READ_DONE;
857 }
858
859 cf_read_status_t
860 cf_finish_tail(capture_file *cf, int *err)
861 {
862   gchar     *err_info;
863   gint64     data_offset;
864   dfilter_t *dfcode;
865   column_info *cinfo;
866   epan_dissect_t edt;
867   gboolean   create_proto_tree;
868   guint      tap_flags;
869   gboolean   compiled;
870
871   /* Compile the current display filter.
872    * We assume this will not fail since cf->dfilter is only set in
873    * cf_filter IFF the filter was valid.
874    */
875   compiled = dfilter_compile(cf->dfilter, &dfcode, NULL);
876   g_assert(!cf->dfilter || (compiled && dfcode));
877
878   /* Get the union of the flags for all tap listeners. */
879   tap_flags = union_of_tap_listener_flags();
880
881   /* If any tap listeners require the columns, construct them. */
882   cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
883
884   /*
885    * Determine whether we need to create a protocol tree.
886    * We do if:
887    *
888    *    we're going to apply a display filter;
889    *
890    *    one of the tap listeners is going to apply a filter;
891    *
892    *    one of the tap listeners requires a protocol tree;
893    *
894    *    a postdissector wants field values or protocols on
895    *    the first pass.
896    */
897   create_proto_tree =
898     (dfcode != NULL || have_filtering_tap_listeners() ||
899      (tap_flags & TL_REQUIRES_PROTO_TREE) || postdissectors_want_hfids());
900
901   if (cf->provider.wth == NULL) {
902     cf_close(cf);
903     return CF_READ_ERROR;
904   }
905
906   packet_list_check_end();
907   /* Don't freeze/thaw the list when doing live capture */
908   /*packet_list_freeze();*/
909
910   epan_dissect_init(&edt, cf->epan, create_proto_tree, FALSE);
911
912   while ((wtap_read(cf->provider.wth, err, &err_info, &data_offset))) {
913     if (cf->state == FILE_READ_ABORTED) {
914       /* Well, the user decided to abort the read.  Break out of the
915          loop, and let the code below (which is called even if there
916          aren't any packets left to read) exit. */
917       break;
918     }
919     read_packet(cf, dfcode, &edt, cinfo, data_offset);
920   }
921
922   /* Cleanup and release all dfilter resources */
923   dfilter_free(dfcode);
924
925   epan_dissect_cleanup(&edt);
926
927   /* Don't freeze/thaw the list when doing live capture */
928   /*packet_list_thaw();*/
929
930   if (cf->state == FILE_READ_ABORTED) {
931     /* Well, the user decided to abort the read.  We're only called
932        when the child capture process closes the pipe to us (meaning
933        it's probably exited), so we can just close the capture
934        file; we return CF_READ_ABORTED so our caller can do whatever
935        is appropriate when that happens. */
936     cf_close(cf);
937     return CF_READ_ABORTED;
938   }
939
940   if (auto_scroll_live && cf->count != 0)
941     packet_list_moveto_end();
942
943   /* We're done reading sequentially through the file. */
944   cf->state = FILE_READ_DONE;
945
946   /* We're done reading sequentially through the file; close the
947      sequential I/O side, to free up memory it requires. */
948   wtap_sequential_close(cf->provider.wth);
949
950   /* Allow the protocol dissectors to free up memory that they
951    * don't need after the sequential run-through of the packets. */
952   postseq_cleanup_all_protocols();
953
954   /* Update the file encapsulation; it might have changed based on the
955      packets we've read. */
956   cf->lnk_t = wtap_file_encap(cf->provider.wth);
957
958   /* Update the details in the file-set dialog, as the capture file
959    * has likely grown since we first stat-ed it */
960   fileset_update_file(cf->filename);
961
962   if (*err != 0) {
963     /* We got an error reading the capture file.
964        XXX - pop up a dialog box? */
965     if (err_info != NULL) {
966       g_warning("Error \"%s\" while reading \"%s\" (\"%s\")",
967                 wtap_strerror(*err), cf->filename, err_info);
968       g_free(err_info);
969     } else {
970       g_warning("Error \"%s\" while reading \"%s\"",
971                 wtap_strerror(*err), cf->filename);
972     }
973     return CF_READ_ERROR;
974   } else {
975     return CF_READ_OK;
976   }
977 }
978 #endif /* HAVE_LIBPCAP */
979
980 gchar *
981 cf_get_display_name(capture_file *cf)
982 {
983   gchar *displayname;
984
985   /* Return a name to use in displays */
986   if (!cf->is_tempfile) {
987     /* Get the last component of the file name, and use that. */
988     if (cf->filename) {
989       displayname = g_filename_display_basename(cf->filename);
990     } else {
991       displayname=g_strdup("(No file)");
992     }
993   } else {
994     /* The file we read is a temporary file from a live capture or
995        a merge operation; we don't mention its name, but, if it's
996        from a capture, give the source of the capture. */
997     if (cf->source) {
998       displayname = g_strdup(cf->source);
999     } else {
1000       displayname = g_strdup("(Untitled)");
1001     }
1002   }
1003   return displayname;
1004 }
1005
1006 void cf_set_tempfile_source(capture_file *cf, gchar *source) {
1007   if (cf->source) {
1008     g_free(cf->source);
1009   }
1010
1011   if (source) {
1012     cf->source = g_strdup(source);
1013   } else {
1014     cf->source = g_strdup("");
1015   }
1016 }
1017
1018 const gchar *cf_get_tempfile_source(capture_file *cf) {
1019   if (!cf->source) {
1020     return "";
1021   }
1022
1023   return cf->source;
1024 }
1025
1026 /* XXX - use a macro instead? */
1027 int
1028 cf_get_packet_count(capture_file *cf)
1029 {
1030   return cf->count;
1031 }
1032
1033 /* XXX - use a macro instead? */
1034 gboolean
1035 cf_is_tempfile(capture_file *cf)
1036 {
1037   return cf->is_tempfile;
1038 }
1039
1040 void cf_set_tempfile(capture_file *cf, gboolean is_tempfile)
1041 {
1042   cf->is_tempfile = is_tempfile;
1043 }
1044
1045
1046 /* XXX - use a macro instead? */
1047 void cf_set_drops_known(capture_file *cf, gboolean drops_known)
1048 {
1049   cf->drops_known = drops_known;
1050 }
1051
1052 /* XXX - use a macro instead? */
1053 void cf_set_drops(capture_file *cf, guint32 drops)
1054 {
1055   cf->drops = drops;
1056 }
1057
1058 /* XXX - use a macro instead? */
1059 gboolean cf_get_drops_known(capture_file *cf)
1060 {
1061   return cf->drops_known;
1062 }
1063
1064 /* XXX - use a macro instead? */
1065 guint32 cf_get_drops(capture_file *cf)
1066 {
1067   return cf->drops;
1068 }
1069
1070 void cf_set_rfcode(capture_file *cf, dfilter_t *rfcode)
1071 {
1072   cf->rfcode = rfcode;
1073 }
1074
1075 static int
1076 add_packet_to_packet_list(frame_data *fdata, capture_file *cf,
1077     epan_dissect_t *edt, dfilter_t *dfcode, column_info *cinfo,
1078     struct wtap_pkthdr *phdr, const guint8 *buf, gboolean add_to_packet_list)
1079 {
1080   gint            row               = -1;
1081
1082   frame_data_set_before_dissect(fdata, &cf->elapsed_time,
1083                                 &cf->provider.ref, cf->provider.prev_dis);
1084   cf->provider.prev_cap = fdata;
1085
1086   if (dfcode != NULL) {
1087       epan_dissect_prime_with_dfilter(edt, dfcode);
1088   }
1089 #if 0
1090   /* Prepare coloring rules, this ensures that display filter rules containing
1091    * frame.color_rule references are still processed.
1092    * TODO: actually detect that situation or maybe apply other optimizations? */
1093   if (edt->tree && color_filters_used()) {
1094     color_filters_prime_edt(edt);
1095     fdata->flags.need_colorize = 1;
1096   }
1097 #endif
1098
1099   if (!fdata->flags.visited) {
1100     /* This is the first pass, so prime the epan_dissect_t with the
1101        hfids postdissectors want on the first pass. */
1102     prime_epan_dissect_with_postdissector_wanted_hfids(edt);
1103   }
1104
1105   /* Dissect the frame. */
1106   epan_dissect_run_with_taps(edt, cf->cd_t, phdr,
1107                              frame_tvbuff_new(&cf->provider, fdata, buf),
1108                              fdata, cinfo);
1109
1110   /* If we don't have a display filter, set "passed_dfilter" to 1. */
1111   if (dfcode != NULL) {
1112     fdata->flags.passed_dfilter = dfilter_apply_edt(dfcode, edt) ? 1 : 0;
1113
1114     if (fdata->flags.passed_dfilter) {
1115       /* This frame passed the display filter but it may depend on other
1116        * (potentially not displayed) frames.  Find those frames and mark them
1117        * as depended upon.
1118        */
1119       g_slist_foreach(edt->pi.dependent_frames, find_and_mark_frame_depended_upon, cf->provider.frames);
1120     }
1121   } else
1122     fdata->flags.passed_dfilter = 1;
1123
1124   if (fdata->flags.passed_dfilter || fdata->flags.ref_time)
1125     cf->displayed_count++;
1126
1127   if (add_to_packet_list) {
1128     /* We fill the needed columns from new_packet_list */
1129       row = packet_list_append(cinfo, fdata);
1130   }
1131
1132   if (fdata->flags.passed_dfilter || fdata->flags.ref_time)
1133   {
1134     frame_data_set_after_dissect(fdata, &cf->cum_bytes);
1135     cf->provider.prev_dis = fdata;
1136
1137     /* If we haven't yet seen the first frame, this is it. */
1138     if (cf->first_displayed == 0)
1139       cf->first_displayed = fdata->num;
1140
1141     /* This is the last frame we've seen so far. */
1142     cf->last_displayed = fdata->num;
1143   }
1144
1145   epan_dissect_reset(edt);
1146   return row;
1147 }
1148
1149 /* read in a new packet */
1150 /* returns the row of the new packet in the packet list or -1 if not displayed */
1151 static int
1152 read_packet(capture_file *cf, dfilter_t *dfcode, epan_dissect_t *edt,
1153             column_info *cinfo, gint64 offset)
1154 {
1155   struct wtap_pkthdr *phdr = wtap_phdr(cf->provider.wth);
1156   const guint8 *buf = wtap_buf_ptr(cf->provider.wth);
1157   frame_data    fdlocal;
1158   guint32       framenum;
1159   frame_data   *fdata;
1160   gboolean      passed = TRUE;
1161   int           row = -1;
1162
1163   /* Add this packet's link-layer encapsulation type to cf->linktypes, if
1164      it's not already there.
1165      XXX - yes, this is O(N), so if every packet had a different
1166      link-layer encapsulation type, it'd be O(N^2) to read the file, but
1167      there are probably going to be a small number of encapsulation types
1168      in a file. */
1169   cf_add_encapsulation_type(cf, phdr->pkt_encap);
1170
1171   /* The frame number of this packet is one more than the count of
1172      frames in the file so far. */
1173   framenum = cf->count + 1;
1174
1175   frame_data_init(&fdlocal, framenum, phdr, offset, cf->cum_bytes);
1176
1177   if (cf->rfcode) {
1178     epan_dissect_t rf_edt;
1179
1180     epan_dissect_init(&rf_edt, cf->epan, TRUE, FALSE);
1181     epan_dissect_prime_with_dfilter(&rf_edt, cf->rfcode);
1182     epan_dissect_run(&rf_edt, cf->cd_t, phdr,
1183                      frame_tvbuff_new(&cf->provider, &fdlocal, buf),
1184                      &fdlocal, NULL);
1185     passed = dfilter_apply_edt(cf->rfcode, &rf_edt);
1186     epan_dissect_cleanup(&rf_edt);
1187   }
1188
1189   if (passed) {
1190     /* This does a shallow copy of fdlocal, which is good enough. */
1191     fdata = frame_data_sequence_add(cf->provider.frames, &fdlocal);
1192
1193     cf->count++;
1194     if (phdr->opt_comment != NULL)
1195       cf->packet_comment_count++;
1196     cf->f_datalen = offset + fdlocal.cap_len;
1197
1198     if (!cf->redissecting) {
1199       row = add_packet_to_packet_list(fdata, cf, edt, dfcode,
1200                                       cinfo, phdr, buf, TRUE);
1201     }
1202   }
1203
1204   return row;
1205 }
1206
1207
1208 typedef struct _callback_data_t {
1209   gpointer         pd_window;
1210   gint64           f_len;
1211   GTimeVal         start_time;
1212   progdlg_t       *progbar;
1213   GTimer          *prog_timer;
1214   gboolean         stop_flag;
1215 } callback_data_t;
1216
1217
1218 static gboolean
1219 merge_callback(merge_event event, int num _U_,
1220                const merge_in_file_t in_files[], const guint in_file_count,
1221                void *data)
1222 {
1223   guint i;
1224   callback_data_t *cb_data = (callback_data_t*) data;
1225
1226   g_assert(cb_data != NULL);
1227
1228   switch (event) {
1229
1230     case MERGE_EVENT_INPUT_FILES_OPENED:
1231       /* do nothing */
1232       break;
1233
1234     case MERGE_EVENT_FRAME_TYPE_SELECTED:
1235       /* do nothing */
1236       break;
1237
1238     case MERGE_EVENT_READY_TO_MERGE:
1239       /* Get the sum of the sizes of all the files. */
1240       for (i = 0; i < in_file_count; i++)
1241         cb_data->f_len += in_files[i].size;
1242
1243       cb_data->prog_timer = g_timer_new();
1244       g_timer_start(cb_data->prog_timer);
1245
1246       g_get_current_time(&cb_data->start_time);
1247       break;
1248
1249     case MERGE_EVENT_PACKET_WAS_READ:
1250       {
1251         gint64 data_offset = 0;
1252
1253         /* Get the sum of the data offsets in all of the files. */
1254         data_offset = 0;
1255         for (i = 0; i < in_file_count; i++)
1256           data_offset += in_files[i].data_offset;
1257
1258         /* Create the progress bar if necessary.
1259            We check on every iteration of the loop, so that it takes no
1260            longer than the standard time to create it (otherwise, for a
1261            large file, we might take considerably longer than that standard
1262            time in order to get to the next progress bar step). */
1263         if (cb_data->progbar == NULL) {
1264           cb_data->progbar = delayed_create_progress_dlg(cb_data->pd_window, "Merging", "files",
1265             FALSE, &cb_data->stop_flag, &cb_data->start_time, 0.0f);
1266         }
1267
1268         /*
1269          * Update the progress bar, but do it only after
1270          * PROGBAR_UPDATE_INTERVAL has elapsed. Calling update_progress_dlg
1271          * and packets_bar_update will likely trigger UI paint events, which
1272          * might take a while depending on the platform and display. Reset
1273          * our timer *after* painting.
1274          */
1275         if (g_timer_elapsed(cb_data->prog_timer, NULL) > PROGBAR_UPDATE_INTERVAL) {
1276             float  progbar_val;
1277             gint64 file_pos = 0;
1278             /* Get the sum of the seek positions in all of the files. */
1279             for (i = 0; i < in_file_count; i++)
1280               file_pos += wtap_read_so_far(in_files[i].wth);
1281
1282             progbar_val = (gfloat) file_pos / (gfloat) cb_data->f_len;
1283             if (progbar_val > 1.0f) {
1284               /* Some file probably grew while we were reading it.
1285                  That "shouldn't happen", so we'll just clip the progress
1286                  value at 1.0. */
1287               progbar_val = 1.0f;
1288             }
1289
1290             if (cb_data->progbar != NULL) {
1291               gchar status_str[100];
1292               g_snprintf(status_str, sizeof(status_str),
1293                          "%" G_GINT64_MODIFIER "dKB of %" G_GINT64_MODIFIER "dKB",
1294                          file_pos / 1024, cb_data->f_len / 1024);
1295               update_progress_dlg(cb_data->progbar, progbar_val, status_str);
1296             }
1297             g_timer_start(cb_data->prog_timer);
1298         }
1299       }
1300       break;
1301
1302     case MERGE_EVENT_DONE:
1303       /* We're done merging the files; destroy the progress bar if it was created. */
1304       if (cb_data->progbar != NULL)
1305         destroy_progress_dlg(cb_data->progbar);
1306       g_timer_destroy(cb_data->prog_timer);
1307       break;
1308   }
1309
1310   return cb_data->stop_flag;
1311 }
1312
1313
1314
1315 cf_status_t
1316 cf_merge_files_to_tempfile(gpointer pd_window, char **out_filenamep,
1317                            int in_file_count, char *const *in_filenames,
1318                            int file_type, gboolean do_append)
1319 {
1320   int                        err      = 0;
1321   gchar                     *err_info = NULL;
1322   guint                      err_fileno;
1323   guint32                    err_framenum;
1324   merge_result               status;
1325   merge_progress_callback_t  cb;
1326   callback_data_t           *cb_data = g_new0(callback_data_t, 1);
1327
1328   /* prepare our callback routine */
1329   cb_data->pd_window = pd_window;
1330   cb.callback_func = merge_callback;
1331   cb.data = cb_data;
1332
1333   cf_callback_invoke(cf_cb_file_merge_started, NULL);
1334
1335   /* merge the files */
1336   status = merge_files_to_tempfile(out_filenamep, "wireshark", file_type,
1337                                    (const char *const *) in_filenames,
1338                                    in_file_count, do_append,
1339                                    IDB_MERGE_MODE_ALL_SAME, 0 /* snaplen */,
1340                                    "Wireshark", &cb, &err, &err_info,
1341                                    &err_fileno, &err_framenum);
1342
1343   g_free(cb.data);
1344
1345   switch (status) {
1346     case MERGE_OK:
1347       break;
1348
1349     case MERGE_USER_ABORTED:
1350       /* this isn't really an error, though we will return CF_ERROR later */
1351       break;
1352
1353     case MERGE_ERR_CANT_OPEN_INFILE:
1354       cfile_open_failure_alert_box(in_filenames[err_fileno], err, err_info);
1355       break;
1356
1357     case MERGE_ERR_CANT_OPEN_OUTFILE:
1358       cfile_dump_open_failure_alert_box(*out_filenamep, err, file_type);
1359       break;
1360
1361     case MERGE_ERR_CANT_READ_INFILE:
1362       cfile_read_failure_alert_box(in_filenames[err_fileno], err, err_info);
1363       break;
1364
1365     case MERGE_ERR_BAD_PHDR_INTERFACE_ID:
1366       simple_error_message_box("Record %u of \"%s\" has an interface ID that does not match any IDB in its file.",
1367                                err_framenum, in_filenames[err_fileno]);
1368       break;
1369
1370     case MERGE_ERR_CANT_WRITE_OUTFILE:
1371        cfile_write_failure_alert_box(in_filenames[err_fileno],
1372                                      *out_filenamep, err, err_info,
1373                                      err_framenum, file_type);
1374        break;
1375
1376     case MERGE_ERR_CANT_CLOSE_OUTFILE:
1377         cfile_close_failure_alert_box(*out_filenamep, err);
1378         break;
1379
1380     default:
1381       simple_error_message_box("Unknown merge_files error %d", status);
1382       break;
1383   }
1384
1385   cf_callback_invoke(cf_cb_file_merge_finished, NULL);
1386
1387   if (status != MERGE_OK) {
1388     /* Callers aren't expected to treat an error or an explicit abort
1389        differently - we put up error dialogs ourselves, so they don't
1390        have to. */
1391     return CF_ERROR;
1392   } else
1393     return CF_OK;
1394 }
1395
1396 cf_status_t
1397 cf_filter_packets(capture_file *cf, gchar *dftext, gboolean force)
1398 {
1399   const char *filter_new = dftext ? dftext : "";
1400   const char *filter_old = cf->dfilter ? cf->dfilter : "";
1401   dfilter_t  *dfcode;
1402   gchar      *err_msg;
1403   GTimeVal    start_time;
1404
1405   /* if new filter equals old one, do nothing unless told to do so */
1406   if (!force && strcmp(filter_new, filter_old) == 0) {
1407     return CF_OK;
1408   }
1409
1410   dfcode=NULL;
1411
1412   if (dftext == NULL) {
1413     /* The new filter is an empty filter (i.e., display all packets).
1414      * so leave dfcode==NULL
1415      */
1416   } else {
1417     /*
1418      * We have a filter; make a copy of it (as we'll be saving it),
1419      * and try to compile it.
1420      */
1421     dftext = g_strdup(dftext);
1422     if (!dfilter_compile(dftext, &dfcode, &err_msg)) {
1423       /* The attempt failed; report an error. */
1424       simple_message_box(ESD_TYPE_ERROR, NULL,
1425           "See the help for a description of the display filter syntax.",
1426           "\"%s\" isn't a valid display filter: %s",
1427           dftext, err_msg);
1428       g_free(err_msg);
1429       g_free(dftext);
1430       return CF_ERROR;
1431     }
1432
1433     /* Was it empty? */
1434     if (dfcode == NULL) {
1435       /* Yes - free the filter text, and set it to null. */
1436       g_free(dftext);
1437       dftext = NULL;
1438     }
1439   }
1440
1441   /* We have a valid filter.  Replace the current filter. */
1442   g_free(cf->dfilter);
1443   cf->dfilter = dftext;
1444   g_get_current_time(&start_time);
1445
1446
1447   /* Now rescan the packet list, applying the new filter, but not
1448      throwing away information constructed on a previous pass. */
1449   if (cf->state != FILE_CLOSED) {
1450     if (dftext == NULL) {
1451       rescan_packets(cf, "Resetting", "Filter", FALSE);
1452     } else {
1453       rescan_packets(cf, "Filtering", dftext, FALSE);
1454     }
1455   }
1456
1457   /* Cleanup and release all dfilter resources */
1458   dfilter_free(dfcode);
1459
1460   return CF_OK;
1461 }
1462
1463 void
1464 cf_reftime_packets(capture_file *cf)
1465 {
1466   ref_time_packets(cf);
1467 }
1468
1469 void
1470 cf_redissect_packets(capture_file *cf)
1471 {
1472   if (cf->state != FILE_CLOSED) {
1473     rescan_packets(cf, "Reprocessing", "all packets", TRUE);
1474   }
1475 }
1476
1477 gboolean
1478 cf_read_record_r(capture_file *cf, const frame_data *fdata,
1479                  struct wtap_pkthdr *phdr, Buffer *buf)
1480 {
1481   int    err;
1482   gchar *err_info;
1483
1484   if (!wtap_seek_read(cf->provider.wth, fdata->file_off, phdr, buf, &err, &err_info)) {
1485     cfile_read_failure_alert_box(cf->filename, err, err_info);
1486     return FALSE;
1487   }
1488   return TRUE;
1489 }
1490
1491 gboolean
1492 cf_read_record(capture_file *cf, frame_data *fdata)
1493 {
1494   return cf_read_record_r(cf, fdata, &cf->phdr, &cf->buf);
1495 }
1496
1497 /* Rescan the list of packets, reconstructing the CList.
1498
1499    "action" describes why we're doing this; it's used in the progress
1500    dialog box.
1501
1502    "action_item" describes what we're doing; it's used in the progress
1503    dialog box.
1504
1505    "redissect" is TRUE if we need to make the dissectors reconstruct
1506    any state information they have (because a preference that affects
1507    some dissector has changed, meaning some dissector might construct
1508    its state differently from the way it was constructed the last time). */
1509 static void
1510 rescan_packets(capture_file *cf, const char *action, const char *action_item, gboolean redissect)
1511 {
1512   /* Rescan packets new packet list */
1513   guint32     framenum;
1514   frame_data *fdata;
1515   progdlg_t  *progbar = NULL;
1516   GTimer     *prog_timer = g_timer_new();
1517   int         count;
1518   frame_data *selected_frame, *preceding_frame, *following_frame, *prev_frame;
1519   int         selected_frame_num, preceding_frame_num, following_frame_num, prev_frame_num;
1520   gboolean    selected_frame_seen;
1521   float       progbar_val;
1522   GTimeVal    start_time;
1523   gchar       status_str[100];
1524   epan_dissect_t  edt;
1525   dfilter_t  *dfcode;
1526   column_info *cinfo;
1527   gboolean    create_proto_tree;
1528   guint       tap_flags;
1529   gboolean    add_to_packet_list = FALSE;
1530   gboolean    compiled;
1531   guint32     frames_count;
1532
1533   /* Compile the current display filter.
1534    * We assume this will not fail since cf->dfilter is only set in
1535    * cf_filter IFF the filter was valid.
1536    */
1537   compiled = dfilter_compile(cf->dfilter, &dfcode, NULL);
1538   g_assert(!cf->dfilter || (compiled && dfcode));
1539
1540   /* Get the union of the flags for all tap listeners. */
1541   tap_flags = union_of_tap_listener_flags();
1542
1543   /* If any tap listeners require the columns, construct them. */
1544   cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
1545
1546   /*
1547    * Determine whether we need to create a protocol tree.
1548    * We do if:
1549    *
1550    *    we're going to apply a display filter;
1551    *
1552    *    one of the tap listeners is going to apply a filter;
1553    *
1554    *    one of the tap listeners requires a protocol tree;
1555    *
1556    *    we're redissecting and a postdissector wants field
1557    *    values or protocols on the first pass.
1558    */
1559   create_proto_tree =
1560     (dfcode != NULL || have_filtering_tap_listeners() ||
1561      (tap_flags & TL_REQUIRES_PROTO_TREE) ||
1562      (redissect && postdissectors_want_hfids()));
1563
1564   reset_tap_listeners();
1565   /* Which frame, if any, is the currently selected frame?
1566      XXX - should the selected frame or the focus frame be the "current"
1567      frame, that frame being the one from which "Find Frame" searches
1568      start? */
1569   selected_frame = cf->current_frame;
1570
1571   /* Mark frame num as not found */
1572   selected_frame_num = -1;
1573
1574   /* Freeze the packet list while we redo it, so we don't get any
1575      screen updates while it happens. */
1576   packet_list_freeze();
1577
1578   if (redissect) {
1579     /* We need to re-initialize all the state information that protocols
1580        keep, because some preference that controls a dissector has changed,
1581        which might cause the state information to be constructed differently
1582        by that dissector. */
1583
1584     /* We might receive new packets while redissecting, and we don't
1585        want to dissect those before their time. */
1586     cf->redissecting = TRUE;
1587
1588     /* 'reset' dissection session */
1589     epan_free(cf->epan);
1590     if (cf->edt && cf->edt->pi.fd) {
1591       /* All pointers in "per frame proto data" for the currently selected
1592          packet are allocated in wmem_file_scope() and deallocated in epan_free().
1593          Free them here to avoid unintended usage in packet_list_clear(). */
1594       frame_data_destroy(cf->edt->pi.fd);
1595     }
1596     cf->epan = ws_epan_new(cf);
1597     cf->cinfo.epan = cf->epan;
1598
1599     /* A new Lua tap listener may be registered in lua_prime_all_fields()
1600        called via epan_new() / init_dissection() when reloading Lua plugins. */
1601     if (!create_proto_tree && have_filtering_tap_listeners()) {
1602       create_proto_tree = TRUE;
1603     }
1604
1605     /* We need to redissect the packets so we have to discard our old
1606      * packet list store. */
1607     packet_list_clear();
1608     add_to_packet_list = TRUE;
1609   }
1610
1611   /* We don't yet know which will be the first and last frames displayed. */
1612   cf->first_displayed = 0;
1613   cf->last_displayed = 0;
1614
1615   /* We currently don't display any packets */
1616   cf->displayed_count = 0;
1617
1618   /* Iterate through the list of frames.  Call a routine for each frame
1619      to check whether it should be displayed and, if so, add it to
1620      the display list. */
1621   cf->provider.ref = NULL;
1622   cf->provider.prev_dis = NULL;
1623   cf->provider.prev_cap = NULL;
1624   cf->cum_bytes = 0;
1625
1626   cf_callback_invoke(cf_cb_file_rescan_started, cf);
1627
1628   g_timer_start(prog_timer);
1629   /* Count of packets at which we've looked. */
1630   count = 0;
1631   /* Progress so far. */
1632   progbar_val = 0.0f;
1633
1634   cf->stop_flag = FALSE;
1635   g_get_current_time(&start_time);
1636
1637   /* no previous row yet */
1638   prev_frame_num = -1;
1639   prev_frame = NULL;
1640
1641   preceding_frame_num = -1;
1642   preceding_frame = NULL;
1643   following_frame_num = -1;
1644   following_frame = NULL;
1645
1646   selected_frame_seen = FALSE;
1647
1648   frames_count = cf->count;
1649
1650   epan_dissect_init(&edt, cf->epan, create_proto_tree, FALSE);
1651
1652   for (framenum = 1; framenum <= frames_count; framenum++) {
1653     fdata = frame_data_sequence_find(cf->provider.frames, framenum);
1654
1655     /* Create the progress bar if necessary.
1656        We check on every iteration of the loop, so that it takes no
1657        longer than the standard time to create it (otherwise, for a
1658        large file, we might take considerably longer than that standard
1659        time in order to get to the next progress bar step). */
1660     if (progbar == NULL)
1661       progbar = delayed_create_progress_dlg(cf->window, action, action_item, TRUE,
1662                                             &cf->stop_flag,
1663                                             &start_time,
1664                                             progbar_val);
1665
1666     /*
1667      * Update the progress bar, but do it only after PROGBAR_UPDATE_INTERVAL
1668      * has elapsed. Calling update_progress_dlg and packets_bar_update will
1669      * likely trigger UI paint events, which might take a while depending on
1670      * the platform and display. Reset our timer *after* painting.
1671      */
1672     if (g_timer_elapsed(prog_timer, NULL) > PROGBAR_UPDATE_INTERVAL) {
1673       /* let's not divide by zero. I should never be started
1674        * with count == 0, so let's assert that
1675        */
1676       g_assert(cf->count > 0);
1677       progbar_val = (gfloat) count / frames_count;
1678
1679       if (progbar != NULL) {
1680         g_snprintf(status_str, sizeof(status_str),
1681                   "%4u of %u frames", count, frames_count);
1682         update_progress_dlg(progbar, progbar_val, status_str);
1683       }
1684
1685       g_timer_start(prog_timer);
1686     }
1687
1688     if (cf->stop_flag) {
1689       /* Well, the user decided to abort the filtering.  Just stop.
1690
1691          XXX - go back to the previous filter?  Users probably just
1692          want not to wait for a filtering operation to finish;
1693          unless we cancel by having no filter, reverting to the
1694          previous filter will probably be even more expensive than
1695          continuing the filtering, as it involves going back to the
1696          beginning and filtering, and even with no filter we currently
1697          have to re-generate the entire clist, which is also expensive.
1698
1699          I'm not sure what Network Monitor does, but it doesn't appear
1700          to give you an unfiltered display if you cancel. */
1701       break;
1702     }
1703
1704     count++;
1705
1706     if (redissect) {
1707       /* Since all state for the frame was destroyed, mark the frame
1708        * as not visited, free the GSList referring to the state
1709        * data (the per-frame data itself was freed by
1710        * "init_dissection()"), and null out the GSList pointer. */
1711       frame_data_reset(fdata);
1712       frames_count = cf->count;
1713     }
1714
1715     /* Frame dependencies from the previous dissection/filtering are no longer valid. */
1716     fdata->flags.dependent_of_displayed = 0;
1717
1718     if (!cf_read_record(cf, fdata))
1719       break; /* error reading the frame */
1720
1721     /* If the previous frame is displayed, and we haven't yet seen the
1722        selected frame, remember that frame - it's the closest one we've
1723        yet seen before the selected frame. */
1724     if (prev_frame_num != -1 && !selected_frame_seen && prev_frame->flags.passed_dfilter) {
1725       preceding_frame_num = prev_frame_num;
1726       preceding_frame = prev_frame;
1727     }
1728
1729     add_packet_to_packet_list(fdata, cf, &edt, dfcode,
1730                                     cinfo, &cf->phdr,
1731                                     ws_buffer_start_ptr(&cf->buf),
1732                                     add_to_packet_list);
1733
1734     /* If this frame is displayed, and this is the first frame we've
1735        seen displayed after the selected frame, remember this frame -
1736        it's the closest one we've yet seen at or after the selected
1737        frame. */
1738     if (fdata->flags.passed_dfilter && selected_frame_seen && following_frame_num == -1) {
1739       following_frame_num = fdata->num;
1740       following_frame = fdata;
1741     }
1742     if (fdata == selected_frame) {
1743       selected_frame_seen = TRUE;
1744       if (fdata->flags.passed_dfilter)
1745           selected_frame_num = fdata->num;
1746     }
1747
1748     /* Remember this frame - it'll be the previous frame
1749        on the next pass through the loop. */
1750     prev_frame_num = fdata->num;
1751     prev_frame = fdata;
1752   }
1753
1754   epan_dissect_cleanup(&edt);
1755
1756   /* We are done redissecting the packet list. */
1757   cf->redissecting = FALSE;
1758
1759   if (redissect) {
1760       frames_count = cf->count;
1761     /* Clear out what remains of the visited flags and per-frame data
1762        pointers.
1763
1764        XXX - that may cause various forms of bogosity when dissecting
1765        these frames, as they won't have been seen by this sequential
1766        pass, but the only alternative I see is to keep scanning them
1767        even though the user requested that the scan stop, and that
1768        would leave the user stuck with an Wireshark grinding on
1769        until it finishes.  Should we just stick them with that? */
1770     for (; framenum <= frames_count; framenum++) {
1771       fdata = frame_data_sequence_find(cf->provider.frames, framenum);
1772       frame_data_reset(fdata);
1773     }
1774   }
1775
1776   /* We're done filtering the packets; destroy the progress bar if it
1777      was created. */
1778   if (progbar != NULL)
1779     destroy_progress_dlg(progbar);
1780   g_timer_destroy(prog_timer);
1781
1782   /* Unfreeze the packet list. */
1783   if (!add_to_packet_list)
1784     packet_list_recreate_visible_rows();
1785
1786   /* Compute the time it took to filter the file */
1787   compute_elapsed(cf, &start_time);
1788
1789   packet_list_thaw();
1790
1791   cf_callback_invoke(cf_cb_file_rescan_finished, cf);
1792
1793   if (selected_frame_num == -1) {
1794     /* The selected frame didn't pass the filter. */
1795     if (selected_frame == NULL) {
1796       /* That's because there *was* no selected frame.  Make the first
1797          displayed frame the current frame. */
1798       selected_frame_num = 0;
1799     } else {
1800       /* Find the nearest displayed frame to the selected frame (whether
1801          it's before or after that frame) and make that the current frame.
1802          If the next and previous displayed frames are equidistant from the
1803          selected frame, choose the next one. */
1804       g_assert(following_frame == NULL ||
1805                following_frame->num >= selected_frame->num);
1806       g_assert(preceding_frame == NULL ||
1807                preceding_frame->num <= selected_frame->num);
1808       if (following_frame == NULL) {
1809         /* No frame after the selected frame passed the filter, so we
1810            have to select the last displayed frame before the selected
1811            frame. */
1812         selected_frame_num = preceding_frame_num;
1813         selected_frame = preceding_frame;
1814       } else if (preceding_frame == NULL) {
1815         /* No frame before the selected frame passed the filter, so we
1816            have to select the first displayed frame after the selected
1817            frame. */
1818         selected_frame_num = following_frame_num;
1819         selected_frame = following_frame;
1820       } else {
1821         /* Frames before and after the selected frame passed the filter, so
1822            we'll select the previous frame */
1823         selected_frame_num = preceding_frame_num;
1824         selected_frame = preceding_frame;
1825       }
1826     }
1827   }
1828
1829   if (selected_frame_num == -1) {
1830     /* There are no frames displayed at all. */
1831     cf_unselect_packet(cf);
1832   } else {
1833     /* Either the frame that was selected passed the filter, or we've
1834        found the nearest displayed frame to that frame.  Select it, make
1835        it the focus row, and make it visible. */
1836     /* Set to invalid to force update of packet list and packet details */
1837     cf->current_row = -1;
1838     if (selected_frame_num == 0) {
1839       packet_list_select_first_row();
1840     }else{
1841       if (!packet_list_select_row_from_data(selected_frame)) {
1842         /* We didn't find a row corresponding to this frame.
1843            This means that the frame isn't being displayed currently,
1844            so we can't select it. */
1845         simple_message_box(ESD_TYPE_INFO, NULL,
1846                            "The capture file is probably not fully dissected.",
1847                            "End of capture exceeded.");
1848       }
1849     }
1850   }
1851
1852   /* Cleanup and release all dfilter resources */
1853   dfilter_free(dfcode);
1854 }
1855
1856
1857 /*
1858  * Scan through all frame data and recalculate the ref time
1859  * without rereading the file.
1860  * XXX - do we need a progres bar or is this fast enough?
1861  */
1862 static void
1863 ref_time_packets(capture_file *cf)
1864 {
1865   guint32     framenum;
1866   frame_data *fdata;
1867   nstime_t rel_ts;
1868
1869   cf->provider.ref = NULL;
1870   cf->provider.prev_dis = NULL;
1871   cf->cum_bytes = 0;
1872
1873   for (framenum = 1; framenum <= cf->count; framenum++) {
1874     fdata = frame_data_sequence_find(cf->provider.frames, framenum);
1875
1876     /* just add some value here until we know if it is being displayed or not */
1877     fdata->cum_bytes = cf->cum_bytes + fdata->pkt_len;
1878
1879     /*
1880      *Timestamps
1881      */
1882
1883     /* If we don't have the time stamp of the first packet in the
1884      capture, it's because this is the first packet.  Save the time
1885      stamp of this packet as the time stamp of the first packet. */
1886     if (cf->provider.ref == NULL)
1887         cf->provider.ref = fdata;
1888       /* if this frames is marked as a reference time frame, reset
1889         firstsec and firstusec to this frame */
1890     if (fdata->flags.ref_time)
1891         cf->provider.ref = fdata;
1892
1893     /* If we don't have the time stamp of the previous displayed packet,
1894      it's because this is the first displayed packet.  Save the time
1895      stamp of this packet as the time stamp of the previous displayed
1896      packet. */
1897     if (cf->provider.prev_dis == NULL) {
1898         cf->provider.prev_dis = fdata;
1899     }
1900
1901     /* Get the time elapsed between the first packet and this packet. */
1902     fdata->frame_ref_num = (fdata != cf->provider.ref) ? cf->provider.ref->num : 0;
1903     nstime_delta(&rel_ts, &fdata->abs_ts, &cf->provider.ref->abs_ts);
1904
1905     /* If it's greater than the current elapsed time, set the elapsed time
1906      to it (we check for "greater than" so as not to be confused by
1907      time moving backwards). */
1908     if ((gint32)cf->elapsed_time.secs < rel_ts.secs
1909         || ((gint32)cf->elapsed_time.secs == rel_ts.secs && (gint32)cf->elapsed_time.nsecs < rel_ts.nsecs)) {
1910         cf->elapsed_time = rel_ts;
1911     }
1912
1913     /* If this frame is displayed, get the time elapsed between the
1914      previous displayed packet and this packet. */
1915     if ( fdata->flags.passed_dfilter ) {
1916         fdata->prev_dis_num = cf->provider.prev_dis->num;
1917         cf->provider.prev_dis = fdata;
1918     }
1919
1920     /*
1921      * Byte counts
1922      */
1923     if ( (fdata->flags.passed_dfilter) || (fdata->flags.ref_time) ) {
1924         /* This frame either passed the display filter list or is marked as
1925         a time reference frame.  All time reference frames are displayed
1926         even if they don't pass the display filter */
1927         if (fdata->flags.ref_time) {
1928             /* if this was a TIME REF frame we should reset the cum_bytes field */
1929             cf->cum_bytes = fdata->pkt_len;
1930             fdata->cum_bytes = cf->cum_bytes;
1931         } else {
1932             /* increase cum_bytes with this packets length */
1933             cf->cum_bytes += fdata->pkt_len;
1934         }
1935     }
1936   }
1937 }
1938
1939 typedef enum {
1940   PSP_FINISHED,
1941   PSP_STOPPED,
1942   PSP_FAILED
1943 } psp_return_t;
1944
1945 static psp_return_t
1946 process_specified_records(capture_file *cf, packet_range_t *range,
1947     const char *string1, const char *string2, gboolean terminate_is_stop,
1948     gboolean (*callback)(capture_file *, frame_data *,
1949                          struct wtap_pkthdr *, const guint8 *, void *),
1950     void *callback_args,
1951     gboolean show_progress_bar)
1952 {
1953   guint32          framenum;
1954   frame_data      *fdata;
1955   Buffer           buf;
1956   psp_return_t     ret     = PSP_FINISHED;
1957
1958   progdlg_t       *progbar = NULL;
1959   GTimer          *prog_timer = g_timer_new();
1960   int              progbar_count;
1961   float            progbar_val;
1962   GTimeVal         progbar_start_time;
1963   gchar            progbar_status_str[100];
1964   range_process_e  process_this;
1965   struct wtap_pkthdr phdr;
1966
1967   wtap_phdr_init(&phdr);
1968   ws_buffer_init(&buf, 1500);
1969
1970   g_timer_start(prog_timer);
1971   /* Count of packets at which we've looked. */
1972   progbar_count = 0;
1973   /* Progress so far. */
1974   progbar_val = 0.0f;
1975
1976   cf->stop_flag = FALSE;
1977   g_get_current_time(&progbar_start_time);
1978
1979   if (range != NULL)
1980     packet_range_process_init(range);
1981
1982   /* Iterate through all the packets, printing the packets that
1983      were selected by the current display filter.  */
1984   for (framenum = 1; framenum <= cf->count; framenum++) {
1985     fdata = frame_data_sequence_find(cf->provider.frames, framenum);
1986
1987     /* Create the progress bar if necessary.
1988        We check on every iteration of the loop, so that it takes no
1989        longer than the standard time to create it (otherwise, for a
1990        large file, we might take considerably longer than that standard
1991        time in order to get to the next progress bar step). */
1992     if (show_progress_bar && progbar == NULL)
1993       progbar = delayed_create_progress_dlg(cf->window, string1, string2,
1994                                             terminate_is_stop,
1995                                             &cf->stop_flag,
1996                                             &progbar_start_time,
1997                                             progbar_val);
1998
1999     /*
2000      * Update the progress bar, but do it only after PROGBAR_UPDATE_INTERVAL
2001      * has elapsed. Calling update_progress_dlg and packets_bar_update will
2002      * likely trigger UI paint events, which might take a while depending on
2003      * the platform and display. Reset our timer *after* painting.
2004      */
2005     if (progbar && g_timer_elapsed(prog_timer, NULL) > PROGBAR_UPDATE_INTERVAL) {
2006       /* let's not divide by zero. I should never be started
2007        * with count == 0, so let's assert that
2008        */
2009       g_assert(cf->count > 0);
2010       progbar_val = (gfloat) progbar_count / cf->count;
2011
2012       g_snprintf(progbar_status_str, sizeof(progbar_status_str),
2013                   "%4u of %u packets", progbar_count, cf->count);
2014       update_progress_dlg(progbar, progbar_val, progbar_status_str);
2015
2016       g_timer_start(prog_timer);
2017     }
2018
2019     if (cf->stop_flag) {
2020       /* Well, the user decided to abort the operation.  Just stop,
2021          and arrange to return PSP_STOPPED to our caller, so they know
2022          it was stopped explicitly. */
2023       ret = PSP_STOPPED;
2024       break;
2025     }
2026
2027     progbar_count++;
2028
2029     if (range != NULL) {
2030       /* do we have to process this packet? */
2031       process_this = packet_range_process_packet(range, fdata);
2032       if (process_this == range_process_next) {
2033         /* this packet uninteresting, continue with next one */
2034         continue;
2035       } else if (process_this == range_processing_finished) {
2036         /* all interesting packets processed, stop the loop */
2037         break;
2038       }
2039     }
2040
2041     /* Get the packet */
2042     if (!cf_read_record_r(cf, fdata, &phdr, &buf)) {
2043       /* Attempt to get the packet failed. */
2044       ret = PSP_FAILED;
2045       break;
2046     }
2047     /* Process the packet */
2048     if (!callback(cf, fdata, &phdr, ws_buffer_start_ptr(&buf), callback_args)) {
2049       /* Callback failed.  We assume it reported the error appropriately. */
2050       ret = PSP_FAILED;
2051       break;
2052     }
2053   }
2054
2055   /* We're done printing the packets; destroy the progress bar if
2056      it was created. */
2057   if (progbar != NULL)
2058     destroy_progress_dlg(progbar);
2059   g_timer_destroy(prog_timer);
2060
2061   wtap_phdr_cleanup(&phdr);
2062   ws_buffer_free(&buf);
2063
2064   return ret;
2065 }
2066
2067 typedef struct {
2068   epan_dissect_t edt;
2069   column_info *cinfo;
2070 } retap_callback_args_t;
2071
2072 static gboolean
2073 retap_packet(capture_file *cf, frame_data *fdata,
2074              struct wtap_pkthdr *phdr, const guint8 *pd,
2075              void *argsp)
2076 {
2077   retap_callback_args_t *args = (retap_callback_args_t *)argsp;
2078
2079   epan_dissect_run_with_taps(&args->edt, cf->cd_t, phdr,
2080                              frame_tvbuff_new(&cf->provider, fdata, pd),
2081                              fdata, args->cinfo);
2082   epan_dissect_reset(&args->edt);
2083
2084   return TRUE;
2085 }
2086
2087 cf_read_status_t
2088 cf_retap_packets(capture_file *cf)
2089 {
2090   packet_range_t        range;
2091   retap_callback_args_t callback_args;
2092   gboolean              create_proto_tree;
2093   guint                 tap_flags;
2094   psp_return_t          ret;
2095
2096   /* Presumably the user closed the capture file. */
2097   if (cf == NULL) {
2098     return CF_READ_ABORTED;
2099   }
2100
2101   cf_callback_invoke(cf_cb_file_retap_started, cf);
2102
2103   /* Get the union of the flags for all tap listeners. */
2104   tap_flags = union_of_tap_listener_flags();
2105
2106   /* If any tap listeners require the columns, construct them. */
2107   callback_args.cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
2108
2109   /*
2110    * Determine whether we need to create a protocol tree.
2111    * We do if:
2112    *
2113    *    one of the tap listeners is going to apply a filter;
2114    *
2115    *    one of the tap listeners requires a protocol tree.
2116    */
2117   create_proto_tree =
2118     (have_filtering_tap_listeners() || (tap_flags & TL_REQUIRES_PROTO_TREE));
2119
2120   /* Reset the tap listeners. */
2121   reset_tap_listeners();
2122
2123   epan_dissect_init(&callback_args.edt, cf->epan, create_proto_tree, FALSE);
2124
2125   /* Iterate through the list of packets, dissecting all packets and
2126      re-running the taps. */
2127   packet_range_init(&range, cf);
2128   packet_range_process_init(&range);
2129
2130   ret = process_specified_records(cf, &range, "Recalculating statistics on",
2131                                   "all packets", TRUE, retap_packet,
2132                                   &callback_args, TRUE);
2133
2134   epan_dissect_cleanup(&callback_args.edt);
2135
2136   cf_callback_invoke(cf_cb_file_retap_finished, cf);
2137
2138   switch (ret) {
2139   case PSP_FINISHED:
2140     /* Completed successfully. */
2141     return CF_READ_OK;
2142
2143   case PSP_STOPPED:
2144     /* Well, the user decided to abort the refiltering.
2145        Return CF_READ_ABORTED so our caller knows they did that. */
2146     return CF_READ_ABORTED;
2147
2148   case PSP_FAILED:
2149     /* Error while retapping. */
2150     return CF_READ_ERROR;
2151   }
2152
2153   g_assert_not_reached();
2154   return CF_READ_OK;
2155 }
2156
2157 typedef struct {
2158   print_args_t *print_args;
2159   gboolean      print_header_line;
2160   char         *header_line_buf;
2161   int           header_line_buf_len;
2162   gboolean      print_formfeed;
2163   gboolean      print_separator;
2164   char         *line_buf;
2165   int           line_buf_len;
2166   gint         *col_widths;
2167   int           num_visible_cols;
2168   gint         *visible_cols;
2169   epan_dissect_t edt;
2170 } print_callback_args_t;
2171
2172 static gboolean
2173 print_packet(capture_file *cf, frame_data *fdata,
2174              struct wtap_pkthdr *phdr, const guint8 *pd,
2175              void *argsp)
2176 {
2177   print_callback_args_t *args = (print_callback_args_t *)argsp;
2178   int             i;
2179   char           *cp;
2180   int             line_len;
2181   int             column_len;
2182   int             cp_off;
2183   char            bookmark_name[9+10+1];  /* "__frameNNNNNNNNNN__\0" */
2184   char            bookmark_title[6+10+1]; /* "Frame NNNNNNNNNN__\0"  */
2185   col_item_t*     col_item;
2186
2187   /* Fill in the column information if we're printing the summary
2188      information. */
2189   if (args->print_args->print_summary) {
2190     col_custom_prime_edt(&args->edt, &cf->cinfo);
2191     epan_dissect_run(&args->edt, cf->cd_t, phdr,
2192                      frame_tvbuff_new(&cf->provider, fdata, pd),
2193                      fdata, &cf->cinfo);
2194     epan_dissect_fill_in_columns(&args->edt, FALSE, TRUE);
2195   } else
2196     epan_dissect_run(&args->edt, cf->cd_t, phdr,
2197                      frame_tvbuff_new(&cf->provider, fdata, pd), fdata, NULL);
2198
2199   if (args->print_formfeed) {
2200     if (!new_page(args->print_args->stream))
2201       goto fail;
2202   } else {
2203       if (args->print_separator) {
2204         if (!print_line(args->print_args->stream, 0, ""))
2205           goto fail;
2206       }
2207   }
2208
2209   /*
2210    * We generate bookmarks, if the output format supports them.
2211    * The name is "__frameN__".
2212    */
2213   g_snprintf(bookmark_name, sizeof bookmark_name, "__frame%u__", fdata->num);
2214
2215   if (args->print_args->print_summary) {
2216     if (!args->print_args->print_col_headings)
2217         args->print_header_line = FALSE;
2218     if (args->print_header_line) {
2219       if (!print_line(args->print_args->stream, 0, args->header_line_buf))
2220         goto fail;
2221       args->print_header_line = FALSE;  /* we might not need to print any more */
2222     }
2223     cp = &args->line_buf[0];
2224     line_len = 0;
2225     for (i = 0; i < args->num_visible_cols; i++) {
2226       col_item = &cf->cinfo.columns[args->visible_cols[i]];
2227       /* Find the length of the string for this column. */
2228       column_len = (int) strlen(col_item->col_data);
2229       if (args->col_widths[i] > column_len)
2230          column_len = args->col_widths[i];
2231
2232       /* Make sure there's room in the line buffer for the column; if not,
2233          double its length. */
2234       line_len += column_len + 1;   /* "+1" for space */
2235       if (line_len > args->line_buf_len) {
2236         cp_off = (int) (cp - args->line_buf);
2237         args->line_buf_len = 2 * line_len;
2238         args->line_buf = (char *)g_realloc(args->line_buf, args->line_buf_len + 1);
2239         cp = args->line_buf + cp_off;
2240       }
2241
2242       /* Right-justify the packet number column. */
2243       if (col_item->col_fmt == COL_NUMBER)
2244         g_snprintf(cp, column_len+1, "%*s", args->col_widths[i], col_item->col_data);
2245       else
2246         g_snprintf(cp, column_len+1, "%-*s", args->col_widths[i], col_item->col_data);
2247       cp += column_len;
2248       if (i != args->num_visible_cols - 1)
2249         *cp++ = ' ';
2250     }
2251     *cp = '\0';
2252
2253     /*
2254      * Generate a bookmark, using the summary line as the title.
2255      */
2256     if (!print_bookmark(args->print_args->stream, bookmark_name,
2257                         args->line_buf))
2258       goto fail;
2259
2260     if (!print_line(args->print_args->stream, 0, args->line_buf))
2261       goto fail;
2262   } else {
2263     /*
2264      * Generate a bookmark, using "Frame N" as the title, as we're not
2265      * printing the summary line.
2266      */
2267     g_snprintf(bookmark_title, sizeof bookmark_title, "Frame %u", fdata->num);
2268     if (!print_bookmark(args->print_args->stream, bookmark_name,
2269                         bookmark_title))
2270       goto fail;
2271   } /* if (print_summary) */
2272
2273   if (args->print_args->print_dissections != print_dissections_none) {
2274     if (args->print_args->print_summary) {
2275       /* Separate the summary line from the tree with a blank line. */
2276       if (!print_line(args->print_args->stream, 0, ""))
2277         goto fail;
2278     }
2279
2280     /* Print the information in that tree. */
2281     if (!proto_tree_print(args->print_args->print_dissections,
2282                           args->print_args->print_hex, &args->edt, NULL,
2283                           args->print_args->stream))
2284       goto fail;
2285
2286     /* Print a blank line if we print anything after this (aka more than one packet). */
2287     args->print_separator = TRUE;
2288
2289     /* Print a header line if we print any more packet summaries */
2290     if (args->print_args->print_col_headings)
2291         args->print_header_line = TRUE;
2292   }
2293
2294   if (args->print_args->print_hex) {
2295     if (args->print_args->print_summary || (args->print_args->print_dissections != print_dissections_none)) {
2296       if (!print_line(args->print_args->stream, 0, ""))
2297         goto fail;
2298     }
2299     /* Print the full packet data as hex. */
2300     if (!print_hex_data(args->print_args->stream, &args->edt))
2301       goto fail;
2302
2303     /* Print a blank line if we print anything after this (aka more than one packet). */
2304     args->print_separator = TRUE;
2305
2306     /* Print a header line if we print any more packet summaries */
2307     if (args->print_args->print_col_headings)
2308         args->print_header_line = TRUE;
2309   } /* if (args->print_args->print_dissections != print_dissections_none) */
2310
2311   epan_dissect_reset(&args->edt);
2312
2313   /* do we want to have a formfeed between each packet from now on? */
2314   if (args->print_args->print_formfeed) {
2315     args->print_formfeed = TRUE;
2316   }
2317
2318   return TRUE;
2319
2320 fail:
2321   epan_dissect_reset(&args->edt);
2322   return FALSE;
2323 }
2324
2325 cf_print_status_t
2326 cf_print_packets(capture_file *cf, print_args_t *print_args,
2327                  gboolean show_progress_bar)
2328 {
2329   print_callback_args_t callback_args;
2330   gint          data_width;
2331   char         *cp;
2332   int           i, cp_off, column_len, line_len;
2333   int           num_visible_col = 0, last_visible_col = 0, visible_col_count;
2334   psp_return_t  ret;
2335   GList        *clp;
2336   fmt_data     *cfmt;
2337   gboolean      proto_tree_needed;
2338
2339   callback_args.print_args = print_args;
2340   callback_args.print_header_line = print_args->print_col_headings;
2341   callback_args.header_line_buf = NULL;
2342   callback_args.header_line_buf_len = 256;
2343   callback_args.print_formfeed = FALSE;
2344   callback_args.print_separator = FALSE;
2345   callback_args.line_buf = NULL;
2346   callback_args.line_buf_len = 256;
2347   callback_args.col_widths = NULL;
2348   callback_args.num_visible_cols = 0;
2349   callback_args.visible_cols = NULL;
2350
2351   if (!print_preamble(print_args->stream, cf->filename, get_ws_vcs_version_info())) {
2352     destroy_print_stream(print_args->stream);
2353     return CF_PRINT_WRITE_ERROR;
2354   }
2355
2356   if (print_args->print_summary) {
2357     /* We're printing packet summaries.  Allocate the header line buffer
2358        and get the column widths. */
2359     callback_args.header_line_buf = (char *)g_malloc(callback_args.header_line_buf_len + 1);
2360
2361     /* Find the number of visible columns and the last visible column */
2362     for (i = 0; i < prefs.num_cols; i++) {
2363
2364         clp = g_list_nth(prefs.col_list, i);
2365         if (clp == NULL) /* Sanity check, Invalid column requested */
2366             continue;
2367
2368         cfmt = (fmt_data *) clp->data;
2369         if (cfmt->visible) {
2370             num_visible_col++;
2371             last_visible_col = i;
2372         }
2373     }
2374
2375     /* Find the widths for each of the columns - maximum of the
2376        width of the title and the width of the data - and construct
2377        a buffer with a line containing the column titles. */
2378     callback_args.num_visible_cols = num_visible_col;
2379     callback_args.col_widths = (gint *) g_malloc(sizeof(gint) * num_visible_col);
2380     callback_args.visible_cols = (gint *) g_malloc(sizeof(gint) * num_visible_col);
2381     cp = &callback_args.header_line_buf[0];
2382     line_len = 0;
2383     visible_col_count = 0;
2384     for (i = 0; i < cf->cinfo.num_cols; i++) {
2385
2386       clp = g_list_nth(prefs.col_list, i);
2387       if (clp == NULL) /* Sanity check, Invalid column requested */
2388           continue;
2389
2390       cfmt = (fmt_data *) clp->data;
2391       if (cfmt->visible == FALSE)
2392           continue;
2393
2394       /* Save the order of visible columns */
2395       callback_args.visible_cols[visible_col_count] = i;
2396
2397       /* Don't pad the last column. */
2398       if (i == last_visible_col)
2399         callback_args.col_widths[visible_col_count] = 0;
2400       else {
2401         callback_args.col_widths[visible_col_count] = (gint) strlen(cf->cinfo.columns[i].col_title);
2402         data_width = get_column_char_width(get_column_format(i));
2403         if (data_width > callback_args.col_widths[visible_col_count])
2404           callback_args.col_widths[visible_col_count] = data_width;
2405       }
2406
2407       /* Find the length of the string for this column. */
2408       column_len = (int) strlen(cf->cinfo.columns[i].col_title);
2409       if (callback_args.col_widths[i] > column_len)
2410         column_len = callback_args.col_widths[visible_col_count];
2411
2412       /* Make sure there's room in the line buffer for the column; if not,
2413          double its length. */
2414       line_len += column_len + 1;   /* "+1" for space */
2415       if (line_len > callback_args.header_line_buf_len) {
2416         cp_off = (int) (cp - callback_args.header_line_buf);
2417         callback_args.header_line_buf_len = 2 * line_len;
2418         callback_args.header_line_buf = (char *)g_realloc(callback_args.header_line_buf,
2419                                                   callback_args.header_line_buf_len + 1);
2420         cp = callback_args.header_line_buf + cp_off;
2421       }
2422
2423       /* Right-justify the packet number column. */
2424 /*      if (cf->cinfo.col_fmt[i] == COL_NUMBER)
2425         g_snprintf(cp, column_len+1, "%*s", callback_args.col_widths[visible_col_count], cf->cinfo.columns[i].col_title);
2426       else*/
2427       g_snprintf(cp, column_len+1, "%-*s", callback_args.col_widths[visible_col_count], cf->cinfo.columns[i].col_title);
2428       cp += column_len;
2429       if (i != cf->cinfo.num_cols - 1)
2430         *cp++ = ' ';
2431
2432       visible_col_count++;
2433     }
2434     *cp = '\0';
2435
2436     /* Now start out the main line buffer with the same length as the
2437        header line buffer. */
2438     callback_args.line_buf_len = callback_args.header_line_buf_len;
2439     callback_args.line_buf = (char *)g_malloc(callback_args.line_buf_len + 1);
2440   } /* if (print_summary) */
2441
2442   /* Create the protocol tree, and make it visible, if we're printing
2443      the dissection or the hex data.
2444      XXX - do we need it if we're just printing the hex data? */
2445   proto_tree_needed =
2446       callback_args.print_args->print_dissections != print_dissections_none ||
2447       callback_args.print_args->print_hex ||
2448       have_custom_cols(&cf->cinfo) || have_field_extractors();
2449   epan_dissect_init(&callback_args.edt, cf->epan, proto_tree_needed, proto_tree_needed);
2450
2451   /* Iterate through the list of packets, printing the packets we were
2452      told to print. */
2453   ret = process_specified_records(cf, &print_args->range, "Printing",
2454                                   "selected packets", TRUE, print_packet,
2455                                   &callback_args, show_progress_bar);
2456   epan_dissect_cleanup(&callback_args.edt);
2457   g_free(callback_args.header_line_buf);
2458   g_free(callback_args.line_buf);
2459   g_free(callback_args.col_widths);
2460   g_free(callback_args.visible_cols);
2461
2462   switch (ret) {
2463
2464   case PSP_FINISHED:
2465     /* Completed successfully. */
2466     break;
2467
2468   case PSP_STOPPED:
2469     /* Well, the user decided to abort the printing.
2470
2471        XXX - note that what got generated before they did that
2472        will get printed if we're piping to a print program; we'd
2473        have to write to a file and then hand that to the print
2474        program to make it actually not print anything. */
2475     break;
2476
2477   case PSP_FAILED:
2478     /* Error while printing.
2479
2480        XXX - note that what got generated before they did that
2481        will get printed if we're piping to a print program; we'd
2482        have to write to a file and then hand that to the print
2483        program to make it actually not print anything. */
2484     destroy_print_stream(print_args->stream);
2485     return CF_PRINT_WRITE_ERROR;
2486   }
2487
2488   if (!print_finale(print_args->stream)) {
2489     destroy_print_stream(print_args->stream);
2490     return CF_PRINT_WRITE_ERROR;
2491   }
2492
2493   if (!destroy_print_stream(print_args->stream))
2494     return CF_PRINT_WRITE_ERROR;
2495
2496   return CF_PRINT_OK;
2497 }
2498
2499 typedef struct {
2500   FILE *fh;
2501   epan_dissect_t edt;
2502   print_args_t *print_args;
2503 } write_packet_callback_args_t;
2504
2505 static gboolean
2506 write_pdml_packet(capture_file *cf, frame_data *fdata,
2507                   struct wtap_pkthdr *phdr, const guint8 *pd,
2508           void *argsp)
2509 {
2510   write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
2511
2512   /* Create the protocol tree, but don't fill in the column information. */
2513   epan_dissect_run(&args->edt, cf->cd_t, phdr,
2514                    frame_tvbuff_new(&cf->provider, fdata, pd), fdata, NULL);
2515
2516   /* Write out the information in that tree. */
2517   write_pdml_proto_tree(NULL, NULL, PF_NONE, &args->edt, args->fh, FALSE);
2518
2519   epan_dissect_reset(&args->edt);
2520
2521   return !ferror(args->fh);
2522 }
2523
2524 cf_print_status_t
2525 cf_write_pdml_packets(capture_file *cf, print_args_t *print_args)
2526 {
2527   write_packet_callback_args_t callback_args;
2528   FILE         *fh;
2529   psp_return_t  ret;
2530
2531   fh = ws_fopen(print_args->file, "w");
2532   if (fh == NULL)
2533     return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2534
2535   write_pdml_preamble(fh, cf->filename);
2536   if (ferror(fh)) {
2537     fclose(fh);
2538     return CF_PRINT_WRITE_ERROR;
2539   }
2540
2541   callback_args.fh = fh;
2542   callback_args.print_args = print_args;
2543   epan_dissect_init(&callback_args.edt, cf->epan, TRUE, TRUE);
2544
2545   /* Iterate through the list of packets, printing the packets we were
2546      told to print. */
2547   ret = process_specified_records(cf, &print_args->range, "Writing PDML",
2548                                   "selected packets", TRUE,
2549                                   write_pdml_packet, &callback_args, TRUE);
2550
2551   epan_dissect_cleanup(&callback_args.edt);
2552
2553   switch (ret) {
2554
2555   case PSP_FINISHED:
2556     /* Completed successfully. */
2557     break;
2558
2559   case PSP_STOPPED:
2560     /* Well, the user decided to abort the printing. */
2561     break;
2562
2563   case PSP_FAILED:
2564     /* Error while printing. */
2565     fclose(fh);
2566     return CF_PRINT_WRITE_ERROR;
2567   }
2568
2569   write_pdml_finale(fh);
2570   if (ferror(fh)) {
2571     fclose(fh);
2572     return CF_PRINT_WRITE_ERROR;
2573   }
2574
2575   /* XXX - check for an error */
2576   fclose(fh);
2577
2578   return CF_PRINT_OK;
2579 }
2580
2581 static gboolean
2582 write_psml_packet(capture_file *cf, frame_data *fdata,
2583                   struct wtap_pkthdr *phdr, const guint8 *pd,
2584           void *argsp)
2585 {
2586   write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
2587
2588   /* Fill in the column information */
2589   col_custom_prime_edt(&args->edt, &cf->cinfo);
2590   epan_dissect_run(&args->edt, cf->cd_t, phdr,
2591                    frame_tvbuff_new(&cf->provider, fdata, pd),
2592                    fdata, &cf->cinfo);
2593   epan_dissect_fill_in_columns(&args->edt, FALSE, TRUE);
2594
2595   /* Write out the column information. */
2596   write_psml_columns(&args->edt, args->fh, FALSE);
2597
2598   epan_dissect_reset(&args->edt);
2599
2600   return !ferror(args->fh);
2601 }
2602
2603 cf_print_status_t
2604 cf_write_psml_packets(capture_file *cf, print_args_t *print_args)
2605 {
2606   write_packet_callback_args_t callback_args;
2607   FILE         *fh;
2608   psp_return_t  ret;
2609
2610   gboolean proto_tree_needed;
2611
2612   fh = ws_fopen(print_args->file, "w");
2613   if (fh == NULL)
2614     return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2615
2616   write_psml_preamble(&cf->cinfo, fh);
2617   if (ferror(fh)) {
2618     fclose(fh);
2619     return CF_PRINT_WRITE_ERROR;
2620   }
2621
2622   callback_args.fh = fh;
2623   callback_args.print_args = print_args;
2624
2625   /* Fill in the column information, only create the protocol tree
2626      if having custom columns or field extractors. */
2627   proto_tree_needed = have_custom_cols(&cf->cinfo) || have_field_extractors();
2628   epan_dissect_init(&callback_args.edt, cf->epan, proto_tree_needed, proto_tree_needed);
2629
2630   /* Iterate through the list of packets, printing the packets we were
2631      told to print. */
2632   ret = process_specified_records(cf, &print_args->range, "Writing PSML",
2633                                   "selected packets", TRUE,
2634                                   write_psml_packet, &callback_args, TRUE);
2635
2636   epan_dissect_cleanup(&callback_args.edt);
2637
2638   switch (ret) {
2639
2640   case PSP_FINISHED:
2641     /* Completed successfully. */
2642     break;
2643
2644   case PSP_STOPPED:
2645     /* Well, the user decided to abort the printing. */
2646     break;
2647
2648   case PSP_FAILED:
2649     /* Error while printing. */
2650     fclose(fh);
2651     return CF_PRINT_WRITE_ERROR;
2652   }
2653
2654   write_psml_finale(fh);
2655   if (ferror(fh)) {
2656     fclose(fh);
2657     return CF_PRINT_WRITE_ERROR;
2658   }
2659
2660   /* XXX - check for an error */
2661   fclose(fh);
2662
2663   return CF_PRINT_OK;
2664 }
2665
2666 static gboolean
2667 write_csv_packet(capture_file *cf, frame_data *fdata,
2668                  struct wtap_pkthdr *phdr, const guint8 *pd,
2669                  void *argsp)
2670 {
2671   write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
2672
2673   /* Fill in the column information */
2674   col_custom_prime_edt(&args->edt, &cf->cinfo);
2675   epan_dissect_run(&args->edt, cf->cd_t, phdr,
2676                    frame_tvbuff_new(&cf->provider, fdata, pd),
2677                    fdata, &cf->cinfo);
2678   epan_dissect_fill_in_columns(&args->edt, FALSE, TRUE);
2679
2680   /* Write out the column information. */
2681   write_csv_columns(&args->edt, args->fh);
2682
2683   epan_dissect_reset(&args->edt);
2684
2685   return !ferror(args->fh);
2686 }
2687
2688 cf_print_status_t
2689 cf_write_csv_packets(capture_file *cf, print_args_t *print_args)
2690 {
2691   write_packet_callback_args_t callback_args;
2692   gboolean        proto_tree_needed;
2693   FILE         *fh;
2694   psp_return_t  ret;
2695
2696   fh = ws_fopen(print_args->file, "w");
2697   if (fh == NULL)
2698     return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2699
2700   write_csv_column_titles(&cf->cinfo, fh);
2701   if (ferror(fh)) {
2702     fclose(fh);
2703     return CF_PRINT_WRITE_ERROR;
2704   }
2705
2706   callback_args.fh = fh;
2707   callback_args.print_args = print_args;
2708
2709   /* only create the protocol tree if having custom columns or field extractors. */
2710   proto_tree_needed = have_custom_cols(&cf->cinfo) || have_field_extractors();
2711   epan_dissect_init(&callback_args.edt, cf->epan, proto_tree_needed, proto_tree_needed);
2712
2713   /* Iterate through the list of packets, printing the packets we were
2714      told to print. */
2715   ret = process_specified_records(cf, &print_args->range, "Writing CSV",
2716                                   "selected packets", TRUE,
2717                                   write_csv_packet, &callback_args, TRUE);
2718
2719   epan_dissect_cleanup(&callback_args.edt);
2720
2721   switch (ret) {
2722
2723   case PSP_FINISHED:
2724     /* Completed successfully. */
2725     break;
2726
2727   case PSP_STOPPED:
2728     /* Well, the user decided to abort the printing. */
2729     break;
2730
2731   case PSP_FAILED:
2732     /* Error while printing. */
2733     fclose(fh);
2734     return CF_PRINT_WRITE_ERROR;
2735   }
2736
2737   /* XXX - check for an error */
2738   fclose(fh);
2739
2740   return CF_PRINT_OK;
2741 }
2742
2743 static gboolean
2744 carrays_write_packet(capture_file *cf, frame_data *fdata,
2745              struct wtap_pkthdr *phdr,
2746              const guint8 *pd, void *argsp)
2747 {
2748   write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
2749
2750   epan_dissect_run(&args->edt, cf->cd_t, phdr,
2751                    frame_tvbuff_new(&cf->provider, fdata, pd), fdata, NULL);
2752   write_carrays_hex_data(fdata->num, args->fh, &args->edt);
2753   epan_dissect_reset(&args->edt);
2754
2755   return !ferror(args->fh);
2756 }
2757
2758 cf_print_status_t
2759 cf_write_carrays_packets(capture_file *cf, print_args_t *print_args)
2760 {
2761   write_packet_callback_args_t callback_args;
2762   FILE         *fh;
2763   psp_return_t  ret;
2764
2765   fh = ws_fopen(print_args->file, "w");
2766
2767   if (fh == NULL)
2768     return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2769
2770   if (ferror(fh)) {
2771     fclose(fh);
2772     return CF_PRINT_WRITE_ERROR;
2773   }
2774
2775   callback_args.fh = fh;
2776   callback_args.print_args = print_args;
2777   epan_dissect_init(&callback_args.edt, cf->epan, TRUE, TRUE);
2778
2779   /* Iterate through the list of packets, printing the packets we were
2780      told to print. */
2781   ret = process_specified_records(cf, &print_args->range,
2782                                   "Writing C Arrays",
2783                                   "selected packets", TRUE,
2784                                   carrays_write_packet, &callback_args, TRUE);
2785
2786   epan_dissect_cleanup(&callback_args.edt);
2787
2788   switch (ret) {
2789   case PSP_FINISHED:
2790     /* Completed successfully. */
2791     break;
2792   case PSP_STOPPED:
2793     /* Well, the user decided to abort the printing. */
2794     break;
2795   case PSP_FAILED:
2796     /* Error while printing. */
2797     fclose(fh);
2798     return CF_PRINT_WRITE_ERROR;
2799   }
2800
2801   fclose(fh);
2802   return CF_PRINT_OK;
2803 }
2804
2805 static gboolean
2806 write_json_packet(capture_file *cf, frame_data *fdata,
2807                   struct wtap_pkthdr *phdr, const guint8 *pd,
2808           void *argsp)
2809 {
2810   write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
2811
2812   /* Create the protocol tree, but don't fill in the column information. */
2813   epan_dissect_run(&args->edt, cf->cd_t, phdr,
2814                    frame_tvbuff_new(&cf->provider, fdata, pd), fdata, NULL);
2815
2816   /* Write out the information in that tree. */
2817   write_json_proto_tree(NULL, args->print_args->print_dissections,
2818                         args->print_args->print_hex, NULL, PF_NONE,
2819                         &args->edt, proto_node_group_children_by_unique, args->fh);
2820
2821   epan_dissect_reset(&args->edt);
2822
2823   return !ferror(args->fh);
2824 }
2825
2826 cf_print_status_t
2827 cf_write_json_packets(capture_file *cf, print_args_t *print_args)
2828 {
2829   write_packet_callback_args_t callback_args;
2830   FILE         *fh;
2831   psp_return_t  ret;
2832
2833   fh = ws_fopen(print_args->file, "w");
2834   if (fh == NULL)
2835     return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2836
2837   write_json_preamble(fh);
2838   if (ferror(fh)) {
2839     fclose(fh);
2840     return CF_PRINT_WRITE_ERROR;
2841   }
2842
2843   callback_args.fh = fh;
2844   callback_args.print_args = print_args;
2845   epan_dissect_init(&callback_args.edt, cf->epan, TRUE, TRUE);
2846
2847   /* Iterate through the list of packets, printing the packets we were
2848      told to print. */
2849   ret = process_specified_records(cf, &print_args->range, "Writing PDML",
2850                                   "selected packets", TRUE,
2851                                   write_json_packet, &callback_args, TRUE);
2852
2853   epan_dissect_cleanup(&callback_args.edt);
2854
2855   switch (ret) {
2856
2857   case PSP_FINISHED:
2858     /* Completed successfully. */
2859     break;
2860
2861   case PSP_STOPPED:
2862     /* Well, the user decided to abort the printing. */
2863     break;
2864
2865   case PSP_FAILED:
2866     /* Error while printing. */
2867     fclose(fh);
2868     return CF_PRINT_WRITE_ERROR;
2869   }
2870
2871   write_json_finale(fh);
2872   if (ferror(fh)) {
2873     fclose(fh);
2874     return CF_PRINT_WRITE_ERROR;
2875   }
2876
2877   /* XXX - check for an error */
2878   fclose(fh);
2879
2880   return CF_PRINT_OK;
2881 }
2882
2883 gboolean
2884 cf_find_packet_protocol_tree(capture_file *cf, const char *string,
2885                              search_direction dir)
2886 {
2887   match_data mdata;
2888
2889   mdata.string = string;
2890   mdata.string_len = strlen(string);
2891   return find_packet(cf, match_protocol_tree, &mdata, dir);
2892 }
2893
2894 gboolean
2895 cf_find_string_protocol_tree(capture_file *cf, proto_tree *tree,  match_data *mdata)
2896 {
2897   mdata->frame_matched = FALSE;
2898   mdata->string = convert_string_case(cf->sfilter, cf->case_type);
2899   mdata->string_len = strlen(mdata->string);
2900   mdata->cf = cf;
2901   /* Iterate through all the nodes looking for matching text */
2902   proto_tree_children_foreach(tree, match_subtree_text, mdata);
2903   return mdata->frame_matched ? MR_MATCHED : MR_NOTMATCHED;
2904 }
2905
2906 static match_result
2907 match_protocol_tree(capture_file *cf, frame_data *fdata, void *criterion)
2908 {
2909   match_data     *mdata = (match_data *)criterion;
2910   epan_dissect_t  edt;
2911
2912   /* Load the frame's data. */
2913   if (!cf_read_record(cf, fdata)) {
2914     /* Attempt to get the packet failed. */
2915     return MR_ERROR;
2916   }
2917
2918   /* Construct the protocol tree, including the displayed text */
2919   epan_dissect_init(&edt, cf->epan, TRUE, TRUE);
2920   /* We don't need the column information */
2921   epan_dissect_run(&edt, cf->cd_t, &cf->phdr,
2922                    frame_tvbuff_new_buffer(&cf->provider, fdata, &cf->buf),
2923                    fdata, NULL);
2924
2925   /* Iterate through all the nodes, seeing if they have text that matches. */
2926   mdata->cf = cf;
2927   mdata->frame_matched = FALSE;
2928   proto_tree_children_foreach(edt.tree, match_subtree_text, mdata);
2929   epan_dissect_cleanup(&edt);
2930   return mdata->frame_matched ? MR_MATCHED : MR_NOTMATCHED;
2931 }
2932
2933 static void
2934 match_subtree_text(proto_node *node, gpointer data)
2935 {
2936   match_data   *mdata      = (match_data *) data;
2937   const gchar  *string     = mdata->string;
2938   size_t        string_len = mdata->string_len;
2939   capture_file *cf         = mdata->cf;
2940   field_info   *fi         = PNODE_FINFO(node);
2941   gchar         label_str[ITEM_LABEL_LENGTH];
2942   gchar        *label_ptr;
2943   size_t        label_len;
2944   guint32       i;
2945   guint8        c_char;
2946   size_t        c_match    = 0;
2947
2948   /* dissection with an invisible proto tree? */
2949   g_assert(fi);
2950
2951   if (mdata->frame_matched) {
2952     /* We already had a match; don't bother doing any more work. */
2953     return;
2954   }
2955
2956   /* Don't match invisible entries. */
2957   if (PROTO_ITEM_IS_HIDDEN(node))
2958     return;
2959
2960   /* was a free format label produced? */
2961   if (fi->rep) {
2962     label_ptr = fi->rep->representation;
2963   } else {
2964     /* no, make a generic label */
2965     label_ptr = label_str;
2966     proto_item_fill_label(fi, label_str);
2967   }
2968
2969   if (cf->regex) {
2970     if (g_regex_match(cf->regex, label_ptr, (GRegexMatchFlags) 0, NULL)) {
2971       mdata->frame_matched = TRUE;
2972       mdata->finfo = fi;
2973       return;
2974     }
2975   } else {
2976     /* Does that label match? */
2977     label_len = strlen(label_ptr);
2978     for (i = 0; i < label_len; i++) {
2979       c_char = label_ptr[i];
2980       if (cf->case_type)
2981         c_char = g_ascii_toupper(c_char);
2982       if (c_char == string[c_match]) {
2983         c_match++;
2984         if (c_match == string_len) {
2985           /* No need to look further; we have a match */
2986           mdata->frame_matched = TRUE;
2987           mdata->finfo = fi;
2988           return;
2989         }
2990       } else
2991         c_match = 0;
2992     }
2993   }
2994
2995   /* Recurse into the subtree, if it exists */
2996   if (node->first_child != NULL)
2997     proto_tree_children_foreach(node, match_subtree_text, mdata);
2998 }
2999
3000 gboolean
3001 cf_find_packet_summary_line(capture_file *cf, const char *string,
3002                             search_direction dir)
3003 {
3004   match_data mdata;
3005
3006   mdata.string = string;
3007   mdata.string_len = strlen(string);
3008   return find_packet(cf, match_summary_line, &mdata, dir);
3009 }
3010
3011 static match_result
3012 match_summary_line(capture_file *cf, frame_data *fdata, void *criterion)
3013 {
3014   match_data     *mdata      = (match_data *)criterion;
3015   const gchar    *string     = mdata->string;
3016   size_t          string_len = mdata->string_len;
3017   epan_dissect_t  edt;
3018   const char     *info_column;
3019   size_t          info_column_len;
3020   match_result    result     = MR_NOTMATCHED;
3021   gint            colx;
3022   guint32         i;
3023   guint8          c_char;
3024   size_t          c_match    = 0;
3025
3026   /* Load the frame's data. */
3027   if (!cf_read_record(cf, fdata)) {
3028     /* Attempt to get the packet failed. */
3029     return MR_ERROR;
3030   }
3031
3032   /* Don't bother constructing the protocol tree */
3033   epan_dissect_init(&edt, cf->epan, FALSE, FALSE);
3034   /* Get the column information */
3035   epan_dissect_run(&edt, cf->cd_t, &cf->phdr,
3036                    frame_tvbuff_new_buffer(&cf->provider, fdata, &cf->buf),
3037                    fdata, &cf->cinfo);
3038
3039   /* Find the Info column */
3040   for (colx = 0; colx < cf->cinfo.num_cols; colx++) {
3041     if (cf->cinfo.columns[colx].fmt_matx[COL_INFO]) {
3042       /* Found it.  See if we match. */
3043       info_column = edt.pi.cinfo->columns[colx].col_data;
3044       info_column_len = strlen(info_column);
3045       if (cf->regex) {
3046         if (g_regex_match(cf->regex, info_column, (GRegexMatchFlags) 0, NULL)) {
3047           result = MR_MATCHED;
3048           break;
3049         }
3050       } else {
3051         for (i = 0; i < info_column_len; i++) {
3052           c_char = info_column[i];
3053           if (cf->case_type)
3054             c_char = g_ascii_toupper(c_char);
3055           if (c_char == string[c_match]) {
3056             c_match++;
3057             if (c_match == string_len) {
3058               result = MR_MATCHED;
3059               break;
3060             }
3061           } else
3062             c_match = 0;
3063         }
3064       }
3065       break;
3066     }
3067   }
3068   epan_dissect_cleanup(&edt);
3069   return result;
3070 }
3071
3072 typedef struct {
3073     const guint8 *data;
3074     size_t        data_len;
3075 } cbs_t;    /* "Counted byte string" */
3076
3077
3078 /*
3079  * The current match_* routines only support ASCII case insensitivity and don't
3080  * convert UTF-8 inputs to UTF-16 for matching.
3081  *
3082  * We could modify them to use the GLib Unicode routines or the International
3083  * Components for Unicode library but it's not apparent that we could do so
3084  * without consuming a lot more CPU and memory or that searching would be
3085  * significantly better.
3086  */
3087
3088 gboolean
3089 cf_find_packet_data(capture_file *cf, const guint8 *string, size_t string_size,
3090                     search_direction dir)
3091 {
3092   cbs_t info;
3093
3094   info.data = string;
3095   info.data_len = string_size;
3096
3097   /* Regex, String or hex search? */
3098   if (cf->regex) {
3099     /* Regular Expression search */
3100     return find_packet(cf, match_regex, NULL, dir);
3101   } else if (cf->string) {
3102     /* String search - what type of string? */
3103     switch (cf->scs_type) {
3104
3105     case SCS_NARROW_AND_WIDE:
3106       return find_packet(cf, match_narrow_and_wide, &info, dir);
3107
3108     case SCS_NARROW:
3109       return find_packet(cf, match_narrow, &info, dir);
3110
3111     case SCS_WIDE:
3112       return find_packet(cf, match_wide, &info, dir);
3113
3114     default:
3115       g_assert_not_reached();
3116       return FALSE;
3117     }
3118   } else
3119     return find_packet(cf, match_binary, &info, dir);
3120 }
3121
3122 static match_result
3123 match_narrow_and_wide(capture_file *cf, frame_data *fdata, void *criterion)
3124 {
3125   cbs_t        *info       = (cbs_t *)criterion;
3126   const guint8 *ascii_text = info->data;
3127   size_t        textlen    = info->data_len;
3128   match_result  result;
3129   guint32       buf_len;
3130   guint8       *pd;
3131   guint32       i;
3132   guint8        c_char;
3133   size_t        c_match    = 0;
3134
3135   /* Load the frame's data. */
3136   if (!cf_read_record(cf, fdata)) {
3137     /* Attempt to get the packet failed. */
3138     return MR_ERROR;
3139   }
3140
3141   result = MR_NOTMATCHED;
3142   buf_len = fdata->cap_len;
3143   pd = ws_buffer_start_ptr(&cf->buf);
3144   i = 0;
3145   while (i < buf_len) {
3146     c_char = pd[i];
3147     if (cf->case_type)
3148       c_char = g_ascii_toupper(c_char);
3149     if (c_char != '\0') {
3150       if (c_char == ascii_text[c_match]) {
3151         c_match += 1;
3152         if (c_match == textlen) {
3153           result = MR_MATCHED;
3154           cf->search_pos = i; /* Save the position of the last character
3155                                  for highlighting the field. */
3156           cf->search_len = (guint32)textlen;
3157           break;
3158         }
3159       }
3160       else {
3161         g_assert(i>=c_match);
3162         i -= (guint32)c_match;
3163         c_match = 0;
3164       }
3165     }
3166     i += 1;
3167   }
3168   return result;
3169 }
3170
3171 static match_result
3172 match_narrow(capture_file *cf, frame_data *fdata, void *criterion)
3173 {
3174   guint8       *pd;
3175   cbs_t        *info       = (cbs_t *)criterion;
3176   const guint8 *ascii_text = info->data;
3177   size_t        textlen    = info->data_len;
3178   match_result  result;
3179   guint32       buf_len;
3180   guint32       i;
3181   guint8        c_char;
3182   size_t        c_match    = 0;
3183
3184   /* Load the frame's data. */
3185   if (!cf_read_record(cf, fdata)) {
3186     /* Attempt to get the packet failed. */
3187     return MR_ERROR;
3188   }
3189
3190   result = MR_NOTMATCHED;
3191   buf_len = fdata->cap_len;
3192   pd = ws_buffer_start_ptr(&cf->buf);
3193   i = 0;
3194   while (i < buf_len) {
3195     c_char = pd[i];
3196     if (cf->case_type)
3197       c_char = g_ascii_toupper(c_char);
3198     if (c_char == ascii_text[c_match]) {
3199       c_match += 1;
3200       if (c_match == textlen) {
3201         result = MR_MATCHED;
3202         cf->search_pos = i; /* Save the position of the last character
3203                                for highlighting the field. */
3204         cf->search_len = (guint32)textlen;
3205         break;
3206       }
3207     }
3208     else {
3209       g_assert(i>=c_match);
3210       i -= (guint32)c_match;
3211       c_match = 0;
3212     }
3213     i += 1;
3214   }
3215
3216   return result;
3217 }
3218
3219 static match_result
3220 match_wide(capture_file *cf, frame_data *fdata, void *criterion)
3221 {
3222   cbs_t        *info       = (cbs_t *)criterion;
3223   const guint8 *ascii_text = info->data;
3224   size_t        textlen    = info->data_len;
3225   match_result  result;
3226   guint32       buf_len;
3227   guint8       *pd;
3228   guint32       i;
3229   guint8        c_char;
3230   size_t        c_match    = 0;
3231
3232   /* Load the frame's data. */
3233   if (!cf_read_record(cf, fdata)) {
3234     /* Attempt to get the packet failed. */
3235     return MR_ERROR;
3236   }
3237
3238   result = MR_NOTMATCHED;
3239   buf_len = fdata->cap_len;
3240   pd = ws_buffer_start_ptr(&cf->buf);
3241   i = 0;
3242   while (i < buf_len) {
3243     c_char = pd[i];
3244     if (cf->case_type)
3245       c_char = g_ascii_toupper(c_char);
3246     if (c_char == ascii_text[c_match]) {
3247       c_match += 1;
3248       if (c_match == textlen) {
3249         result = MR_MATCHED;
3250         cf->search_pos = i; /* Save the position of the last character
3251                                for highlighting the field. */
3252         cf->search_len = (guint32)textlen;
3253         break;
3254       }
3255       i += 1;
3256     }
3257     else {
3258       g_assert(i>=(c_match*2));
3259       i -= (guint32)c_match*2;
3260       c_match = 0;
3261     }
3262     i += 1;
3263   }
3264   return result;
3265 }
3266
3267 static match_result
3268 match_binary(capture_file *cf, frame_data *fdata, void *criterion)
3269 {
3270   cbs_t        *info        = (cbs_t *)criterion;
3271   const guint8 *binary_data = info->data;
3272   size_t        datalen     = info->data_len;
3273   match_result  result;
3274   guint32       buf_len;
3275   guint8       *pd;
3276   guint32       i;
3277   size_t        c_match     = 0;
3278
3279   /* Load the frame's data. */
3280   if (!cf_read_record(cf, fdata)) {
3281     /* Attempt to get the packet failed. */
3282     return MR_ERROR;
3283   }
3284
3285   result = MR_NOTMATCHED;
3286   buf_len = fdata->cap_len;
3287   pd = ws_buffer_start_ptr(&cf->buf);
3288   i = 0;
3289   while (i < buf_len) {
3290     if (pd[i] == binary_data[c_match]) {
3291       c_match += 1;
3292       if (c_match == datalen) {
3293         result = MR_MATCHED;
3294         cf->search_pos = i; /* Save the position of the last character
3295                                for highlighting the field. */
3296         cf->search_len = (guint32)datalen;
3297         break;
3298       }
3299     }
3300     else {
3301       g_assert(i>=c_match);
3302       i -= (guint32)c_match;
3303       c_match = 0;
3304     }
3305     i += 1;
3306   }
3307   return result;
3308 }
3309
3310 static match_result
3311 match_regex(capture_file *cf, frame_data *fdata, void *criterion _U_)
3312 {
3313     match_result  result = MR_NOTMATCHED;
3314     GMatchInfo   *match_info = NULL;
3315
3316     /* Load the frame's data. */
3317     if (!cf_read_record(cf, fdata)) {
3318         /* Attempt to get the packet failed. */
3319         return MR_ERROR;
3320     }
3321
3322     if (g_regex_match_full(cf->regex, (const gchar *)ws_buffer_start_ptr(&cf->buf), fdata->cap_len,
3323                            0, (GRegexMatchFlags) 0, &match_info, NULL))
3324     {
3325         gint start_pos = 0, end_pos = 0;
3326         g_match_info_fetch_pos (match_info, 0, &start_pos, &end_pos);
3327         cf->search_pos = end_pos - 1;
3328         cf->search_len = end_pos - start_pos;
3329         result = MR_MATCHED;
3330     }
3331     return result;
3332 }
3333
3334 gboolean
3335 cf_find_packet_dfilter(capture_file *cf, dfilter_t *sfcode,
3336                        search_direction dir)
3337 {
3338   return find_packet(cf, match_dfilter, sfcode, dir);
3339 }
3340
3341 gboolean
3342 cf_find_packet_dfilter_string(capture_file *cf, const char *filter,
3343                               search_direction dir)
3344 {
3345   dfilter_t *sfcode;
3346   gboolean   result;
3347
3348   if (!dfilter_compile(filter, &sfcode, NULL)) {
3349      /*
3350       * XXX - this shouldn't happen, as the filter string is machine
3351       * generated
3352       */
3353     return FALSE;
3354   }
3355   if (sfcode == NULL) {
3356     /*
3357      * XXX - this shouldn't happen, as the filter string is machine
3358      * generated.
3359      */
3360     return FALSE;
3361   }
3362   result = find_packet(cf, match_dfilter, sfcode, dir);
3363   dfilter_free(sfcode);
3364   return result;
3365 }
3366
3367 static match_result
3368 match_dfilter(capture_file *cf, frame_data *fdata, void *criterion)
3369 {
3370   dfilter_t      *sfcode = (dfilter_t *)criterion;
3371   epan_dissect_t  edt;
3372   match_result    result;
3373
3374   /* Load the frame's data. */
3375   if (!cf_read_record(cf, fdata)) {
3376     /* Attempt to get the packet failed. */
3377     return MR_ERROR;
3378   }
3379
3380   epan_dissect_init(&edt, cf->epan, TRUE, FALSE);
3381   epan_dissect_prime_with_dfilter(&edt, sfcode);
3382   epan_dissect_run(&edt, cf->cd_t, &cf->phdr,
3383                    frame_tvbuff_new_buffer(&cf->provider, fdata, &cf->buf),
3384                    fdata, NULL);
3385   result = dfilter_apply_edt(sfcode, &edt) ? MR_MATCHED : MR_NOTMATCHED;
3386   epan_dissect_cleanup(&edt);
3387   return result;
3388 }
3389
3390 gboolean
3391 cf_find_packet_marked(capture_file *cf, search_direction dir)
3392 {
3393   return find_packet(cf, match_marked, NULL, dir);
3394 }
3395
3396 static match_result
3397 match_marked(capture_file *cf _U_, frame_data *fdata, void *criterion _U_)
3398 {
3399   return fdata->flags.marked ? MR_MATCHED : MR_NOTMATCHED;
3400 }
3401
3402 gboolean
3403 cf_find_packet_time_reference(capture_file *cf, search_direction dir)
3404 {
3405   return find_packet(cf, match_time_reference, NULL, dir);
3406 }
3407
3408 static match_result
3409 match_time_reference(capture_file *cf _U_, frame_data *fdata, void *criterion _U_)
3410 {
3411   return fdata->flags.ref_time ? MR_MATCHED : MR_NOTMATCHED;
3412 }
3413
3414 static gboolean
3415 find_packet(capture_file *cf,
3416             match_result (*match_function)(capture_file *, frame_data *, void *),
3417             void *criterion, search_direction dir)
3418 {
3419   frame_data  *start_fd;
3420   guint32      framenum;
3421   frame_data  *fdata;
3422   frame_data  *new_fd = NULL;
3423   progdlg_t   *progbar = NULL;
3424   GTimer      *prog_timer = g_timer_new();
3425   int          count;
3426   gboolean     found;
3427   float        progbar_val;
3428   GTimeVal     start_time;
3429   gchar        status_str[100];
3430   const char  *title;
3431   match_result result;
3432
3433   start_fd = cf->current_frame;
3434   if (start_fd != NULL)  {
3435     /* Iterate through the list of packets, starting at the packet we've
3436        picked, calling a routine to run the filter on the packet, see if
3437        it matches, and stop if so.  */
3438     count = 0;
3439     framenum = start_fd->num;
3440
3441     g_timer_start(prog_timer);
3442     /* Progress so far. */
3443     progbar_val = 0.0f;
3444
3445     cf->stop_flag = FALSE;
3446     g_get_current_time(&start_time);
3447
3448     title = cf->sfilter?cf->sfilter:"";
3449     for (;;) {
3450       /* Create the progress bar if necessary.
3451          We check on every iteration of the loop, so that it takes no
3452          longer than the standard time to create it (otherwise, for a
3453          large file, we might take considerably longer than that standard
3454          time in order to get to the next progress bar step). */
3455       if (progbar == NULL)
3456          progbar = delayed_create_progress_dlg(cf->window, "Searching", title,
3457            FALSE, &cf->stop_flag, &start_time, progbar_val);
3458
3459       /*
3460        * Update the progress bar, but do it only after PROGBAR_UPDATE_INTERVAL
3461        * has elapsed. Calling update_progress_dlg and packets_bar_update will
3462        * likely trigger UI paint events, which might take a while depending on
3463        * the platform and display. Reset our timer *after* painting.
3464        */
3465       if (g_timer_elapsed(prog_timer, NULL) > PROGBAR_UPDATE_INTERVAL) {
3466         /* let's not divide by zero. I should never be started
3467          * with count == 0, so let's assert that
3468          */
3469         g_assert(cf->count > 0);
3470
3471         progbar_val = (gfloat) count / cf->count;
3472
3473         g_snprintf(status_str, sizeof(status_str),
3474                     "%4u of %u packets", count, cf->count);
3475         update_progress_dlg(progbar, progbar_val, status_str);
3476
3477         g_timer_start(prog_timer);
3478       }
3479
3480       if (cf->stop_flag) {
3481         /* Well, the user decided to abort the search.  Go back to the
3482            frame where we started. */
3483         new_fd = start_fd;
3484         break;
3485       }
3486
3487       /* Go past the current frame. */
3488       if (dir == SD_BACKWARD) {
3489         /* Go on to the previous frame. */
3490         if (framenum == 1) {
3491           /*
3492            * XXX - other apps have a bit more of a detailed message
3493            * for this, and instead of offering "OK" and "Cancel",
3494            * they offer things such as "Continue" and "Cancel";
3495            * we need an API for popping up alert boxes with
3496            * {Verb} and "Cancel".
3497            */
3498
3499           if (prefs.gui_find_wrap)
3500           {
3501               statusbar_push_temporary_msg("Search reached the beginning. Continuing at end.");
3502               framenum = cf->count;     /* wrap around */
3503           }
3504           else
3505           {
3506               statusbar_push_temporary_msg("Search reached the beginning.");
3507               framenum = start_fd->num; /* stay on previous packet */
3508           }
3509         } else
3510           framenum--;
3511       } else {
3512         /* Go on to the next frame. */
3513         if (framenum == cf->count) {
3514           if (prefs.gui_find_wrap)
3515           {
3516               statusbar_push_temporary_msg("Search reached the end. Continuing at beginning.");
3517               framenum = 1;             /* wrap around */
3518           }
3519           else
3520           {
3521               statusbar_push_temporary_msg("Search reached the end.");
3522               framenum = start_fd->num; /* stay on previous packet */
3523           }
3524         } else
3525           framenum++;
3526       }
3527       fdata = frame_data_sequence_find(cf->provider.frames, framenum);
3528
3529       count++;
3530
3531       /* Is this packet in the display? */
3532       if (fdata->flags.passed_dfilter) {
3533         /* Yes.  Does it match the search criterion? */
3534         result = (*match_function)(cf, fdata, criterion);
3535         if (result == MR_ERROR) {
3536           /* Error; our caller has reported the error.  Go back to the frame
3537              where we started. */
3538           new_fd = start_fd;
3539           break;
3540         } else if (result == MR_MATCHED) {
3541           /* Yes.  Go to the new frame. */
3542           new_fd = fdata;
3543           break;
3544         }
3545       }
3546
3547       if (fdata == start_fd) {
3548         /* We're back to the frame we were on originally, and that frame
3549            doesn't match the search filter.  The search failed. */
3550         break;
3551       }
3552     }
3553
3554     /* We're done scanning the packets; destroy the progress bar if it
3555        was created. */
3556     if (progbar != NULL)
3557       destroy_progress_dlg(progbar);
3558     g_timer_destroy(prog_timer);
3559   }
3560
3561   if (new_fd != NULL) {
3562     /* Find and select */
3563     cf->search_in_progress = TRUE;
3564     found = packet_list_select_row_from_data(new_fd);
3565     cf->search_in_progress = FALSE;
3566     cf->search_pos = 0; /* Reset the position */
3567     cf->search_len = 0; /* Reset length */
3568     if (!found) {
3569       /* We didn't find a row corresponding to this frame.
3570          This means that the frame isn't being displayed currently,
3571          so we can't select it. */
3572       simple_message_box(ESD_TYPE_INFO, NULL,
3573                          "The capture file is probably not fully dissected.",
3574                          "End of capture exceeded.");
3575       return FALSE;
3576     }
3577     return TRUE;    /* success */
3578   } else
3579     return FALSE;   /* failure */
3580 }
3581
3582 gboolean
3583 cf_goto_frame(capture_file *cf, guint fnumber)
3584 {
3585   frame_data *fdata;
3586
3587   if (cf == NULL || cf->provider.frames == NULL) {
3588     /* we don't have a loaded capture file - fix for bugs 11810 & 11989 */
3589     statusbar_push_temporary_msg("There is no file loaded");
3590     return FALSE;   /* we failed to go to that packet */
3591   }
3592
3593   fdata = frame_data_sequence_find(cf->provider.frames, fnumber);
3594
3595   if (fdata == NULL) {
3596     /* we didn't find a packet with that packet number */
3597     statusbar_push_temporary_msg("There is no packet number %u.", fnumber);
3598     return FALSE;   /* we failed to go to that packet */
3599   }
3600   if (!fdata->flags.passed_dfilter) {
3601     /* that packet currently isn't displayed */
3602     /* XXX - add it to the set of displayed packets? */
3603     statusbar_push_temporary_msg("Packet number %u isn't displayed.", fnumber);
3604     return FALSE;   /* we failed to go to that packet */
3605   }
3606
3607   if (!packet_list_select_row_from_data(fdata)) {
3608     /* We didn't find a row corresponding to this frame.
3609        This means that the frame isn't being displayed currently,
3610        so we can't select it. */
3611     simple_message_box(ESD_TYPE_INFO, NULL,
3612                        "The capture file is probably not fully dissected.",
3613                        "End of capture exceeded.");
3614     return FALSE;
3615   }
3616   return TRUE;  /* we got to that packet */
3617 }
3618
3619 /*
3620  * Go to frame specified by currently selected protocol tree item.
3621  */
3622 gboolean
3623 cf_goto_framenum(capture_file *cf)
3624 {
3625   header_field_info *hfinfo;
3626   guint32            framenum;
3627
3628   if (cf->finfo_selected) {
3629     hfinfo = cf->finfo_selected->hfinfo;
3630     g_assert(hfinfo);
3631     if (hfinfo->type == FT_FRAMENUM) {
3632       framenum = fvalue_get_uinteger(&cf->finfo_selected->value);
3633       if (framenum != 0)
3634         return cf_goto_frame(cf, framenum);
3635       }
3636   }
3637
3638   return FALSE;
3639 }
3640
3641 /* Select the packet on a given row. */
3642 void
3643 cf_select_packet(capture_file *cf, int row)
3644 {
3645   epan_dissect_t *old_edt;
3646   frame_data     *fdata;
3647
3648   /* Get the frame data struct pointer for this frame */
3649   fdata = packet_list_get_row_data(row);
3650
3651   if (fdata == NULL) {
3652     return;
3653   }
3654
3655   /* Get the data in that frame. */
3656   if (!cf_read_record (cf, fdata)) {
3657     return;
3658   }
3659
3660   /* Record that this frame is the current frame. */
3661   cf->current_frame = fdata;
3662   cf->current_row = row;
3663
3664   old_edt = cf->edt;
3665   /* Create the logical protocol tree. */
3666   /* We don't need the columns here. */
3667   cf->edt = epan_dissect_new(cf->epan, TRUE, TRUE);
3668
3669   tap_build_interesting(cf->edt);
3670   epan_dissect_run(cf->edt, cf->cd_t, &cf->phdr,
3671                    frame_tvbuff_new_buffer(&cf->provider, cf->current_frame, &cf->buf),
3672                    cf->current_frame, NULL);
3673
3674   dfilter_macro_build_ftv_cache(cf->edt->tree);
3675
3676   cf_callback_invoke(cf_cb_packet_selected, cf);
3677
3678   if (old_edt != NULL)
3679     epan_dissect_free(old_edt);
3680
3681 }
3682
3683 /* Unselect the selected packet, if any. */
3684 void
3685 cf_unselect_packet(capture_file *cf)
3686 {
3687   epan_dissect_t *old_edt = cf->edt;
3688
3689   cf->edt = NULL;
3690
3691   /* No packet is selected. */
3692   cf->current_frame = NULL;
3693   cf->current_row = 0;
3694
3695   cf_callback_invoke(cf_cb_packet_unselected, cf);
3696
3697   /* No protocol tree means no selected field. */
3698   cf_unselect_field(cf);
3699
3700   /* Destroy the epan_dissect_t for the unselected packet. */
3701   if (old_edt != NULL)
3702     epan_dissect_free(old_edt);
3703 }
3704
3705 /* Unset the selected protocol tree field, if any. */
3706 void
3707 cf_unselect_field(capture_file *cf)
3708 {
3709   cf->finfo_selected = NULL;
3710
3711   cf_callback_invoke(cf_cb_field_unselected, cf);
3712 }
3713
3714 /*
3715  * Mark a particular frame.
3716  */
3717 void
3718 cf_mark_frame(capture_file *cf, frame_data *frame)
3719 {
3720   if (! frame->flags.marked) {
3721     frame->flags.marked = TRUE;
3722     if (cf->count > cf->marked_count)
3723       cf->marked_count++;
3724   }
3725 }
3726
3727 /*
3728  * Unmark a particular frame.
3729  */
3730 void
3731 cf_unmark_frame(capture_file *cf, frame_data *frame)
3732 {
3733   if (frame->flags.marked) {
3734     frame->flags.marked = FALSE;
3735     if (cf->marked_count > 0)
3736       cf->marked_count--;
3737   }
3738 }
3739
3740 /*
3741  * Ignore a particular frame.
3742  */
3743 void
3744 cf_ignore_frame(capture_file *cf, frame_data *frame)
3745 {
3746   if (! frame->flags.ignored) {
3747     frame->flags.ignored = TRUE;
3748     if (cf->count > cf->ignored_count)
3749       cf->ignored_count++;
3750   }
3751 }
3752
3753 /*
3754  * Un-ignore a particular frame.
3755  */
3756 void
3757 cf_unignore_frame(capture_file *cf, frame_data *frame)
3758 {
3759   if (frame->flags.ignored) {
3760     frame->flags.ignored = FALSE;
3761     if (cf->ignored_count > 0)
3762       cf->ignored_count--;
3763   }
3764 }
3765
3766 /*
3767  * Read the section comment.
3768  */
3769 const gchar *
3770 cf_read_section_comment(capture_file *cf)
3771 {
3772   wtap_block_t shb_inf;
3773   char *shb_comment;
3774
3775   /* Get the SHB. */
3776   /* XXX - support multiple SHBs */
3777   shb_inf = wtap_file_get_shb(cf->provider.wth);
3778
3779   /* Get the first comment from the SHB. */
3780   /* XXX - support multiple comments */
3781   if (wtap_block_get_nth_string_option_value(shb_inf, OPT_COMMENT, 0, &shb_comment) != WTAP_OPTTYPE_SUCCESS)
3782     return NULL;
3783   return shb_comment;
3784 }
3785
3786 /*
3787  * Modify the section comment.
3788  */
3789 void
3790 cf_update_section_comment(capture_file *cf, gchar *comment)
3791 {
3792   wtap_block_t shb_inf;
3793   gchar *shb_comment;
3794
3795   /* Get the SHB. */
3796   /* XXX - support multiple SHBs */
3797   shb_inf = wtap_file_get_shb(cf->provider.wth);
3798
3799   /* Get the first comment from the SHB. */
3800   /* XXX - support multiple comments */
3801   if (wtap_block_get_nth_string_option_value(shb_inf, OPT_COMMENT, 0, &shb_comment) != WTAP_OPTTYPE_SUCCESS) {
3802     /* There's no comment - add one. */
3803     wtap_block_add_string_option(shb_inf, OPT_COMMENT, comment, strlen(comment));
3804   } else {
3805     /* See if the comment has changed or not */
3806     if (strcmp(shb_comment, comment) == 0) {
3807       g_free(comment);
3808       return;
3809     }
3810
3811     /* The comment has changed, let's update it */
3812     wtap_block_set_nth_string_option_value(shb_inf, OPT_COMMENT, 0, comment, strlen(comment));
3813   }
3814   /* Mark the file as having unsaved changes */
3815   cf->unsaved_changes = TRUE;
3816 }
3817
3818 /*
3819  * Get the comment on a packet (record).
3820  * If the comment has been edited, it returns the result of the edit,
3821  * otherwise it returns the comment from the file.
3822  */
3823 char *
3824 cf_get_packet_comment(capture_file *cf, const frame_data *fd)
3825 {
3826   char *comment;
3827
3828   /* fetch user comment */
3829   if (fd->flags.has_user_comment)
3830     return g_strdup(cap_file_provider_get_user_comment(&cf->provider, fd));
3831
3832   /* fetch phdr comment */
3833   if (fd->flags.has_phdr_comment) {
3834     struct wtap_pkthdr phdr; /* Packet header */
3835     Buffer buf; /* Packet data */
3836
3837     wtap_phdr_init(&phdr);
3838     ws_buffer_init(&buf, 1500);
3839
3840     if (!cf_read_record_r(cf, fd, &phdr, &buf))
3841       { /* XXX, what we can do here? */ }
3842
3843     comment = phdr.opt_comment;
3844     wtap_phdr_cleanup(&phdr);
3845     ws_buffer_free(&buf);
3846     return comment;
3847   }
3848   return NULL;
3849 }
3850
3851 /*
3852  * Update(replace) the comment on a capture from a frame
3853  */
3854 gboolean
3855 cf_set_user_packet_comment(capture_file *cf, frame_data *fd, const gchar *new_comment)
3856 {
3857   char *pkt_comment = cf_get_packet_comment(cf, fd);
3858
3859   /* Check if the comment has changed */
3860   if (!g_strcmp0(pkt_comment, new_comment)) {
3861     g_free(pkt_comment);
3862     return FALSE;
3863   }
3864   g_free(pkt_comment);
3865
3866   if (pkt_comment)
3867     cf->packet_comment_count--;
3868
3869   if (new_comment)
3870     cf->packet_comment_count++;
3871
3872   cap_file_provider_set_user_comment(&cf->provider, fd, new_comment);
3873
3874   expert_update_comment_count(cf->packet_comment_count);
3875
3876   /* OK, we have unsaved changes. */
3877   cf->unsaved_changes = TRUE;
3878   return TRUE;
3879 }
3880
3881 /*
3882  * What types of comments does this capture file have?
3883  */
3884 guint32
3885 cf_comment_types(capture_file *cf)
3886 {
3887   guint32 comment_types = 0;
3888
3889   if (cf_read_section_comment(cf) != NULL)
3890     comment_types |= WTAP_COMMENT_PER_SECTION;
3891   if (cf->packet_comment_count != 0)
3892     comment_types |= WTAP_COMMENT_PER_PACKET;
3893   return comment_types;
3894 }
3895
3896 /*
3897  * Add a resolved address to this file's list of resolved addresses.
3898  */
3899 gboolean
3900 cf_add_ip_name_from_string(capture_file *cf, const char *addr, const char *name)
3901 {
3902   /*
3903    * XXX - support multiple resolved address lists, and add to the one
3904    * attached to this file?
3905    */
3906   if (!add_ip_name_from_string(addr, name))
3907     return FALSE;
3908
3909   /* OK, we have unsaved changes. */
3910   cf->unsaved_changes = TRUE;
3911   return TRUE;
3912 }
3913
3914 typedef struct {
3915   wtap_dumper *pdh;
3916   const char  *fname;
3917   int          file_type;
3918 } save_callback_args_t;
3919
3920 /*
3921  * Save a capture to a file, in a particular format, saving either
3922  * all packets, all currently-displayed packets, or all marked packets.
3923  *
3924  * Returns TRUE if it succeeds, FALSE otherwise; if it fails, it pops
3925  * up a message box for the failure.
3926  */
3927 static gboolean
3928 save_record(capture_file *cf, frame_data *fdata,
3929             struct wtap_pkthdr *phdr, const guint8 *pd,
3930             void *argsp)
3931 {
3932   save_callback_args_t *args = (save_callback_args_t *)argsp;
3933   struct wtap_pkthdr    hdr;
3934   int           err;
3935   gchar        *err_info;
3936   const char   *pkt_comment;
3937
3938   if (fdata->flags.has_user_comment)
3939     pkt_comment = cap_file_provider_get_user_comment(&cf->provider, fdata);
3940   else
3941     pkt_comment = phdr->opt_comment;
3942
3943   /* init the wtap header for saving */
3944   /* TODO: reuse phdr */
3945   /* XXX - these are the only flags that correspond to data that we have
3946      in the frame_data structure and that matter on a per-packet basis.
3947
3948      For WTAP_HAS_CAP_LEN, either the file format has separate "captured"
3949      and "on the wire" lengths, or it doesn't.
3950
3951      For WTAP_HAS_DROP_COUNT, Wiretap doesn't actually supply the value
3952      to its callers.
3953
3954      For WTAP_HAS_PACK_FLAGS, we currently don't save the FCS length
3955      from the packet flags. */
3956   hdr.rec_type = phdr->rec_type;
3957   hdr.presence_flags = 0;
3958   if (fdata->flags.has_ts)
3959     hdr.presence_flags |= WTAP_HAS_TS;
3960   if (phdr->presence_flags & WTAP_HAS_INTERFACE_ID)
3961     hdr.presence_flags |= WTAP_HAS_INTERFACE_ID;
3962   if (phdr->presence_flags & WTAP_HAS_PACK_FLAGS)
3963     hdr.presence_flags |= WTAP_HAS_PACK_FLAGS;
3964   hdr.ts           = phdr->ts;
3965   hdr.caplen       = phdr->caplen;
3966   hdr.len          = phdr->len;
3967   hdr.pkt_encap    = phdr->pkt_encap;
3968   /* pcapng */
3969   hdr.interface_id = phdr->interface_id;   /* identifier of the interface. */
3970   /* options */
3971   hdr.pack_flags   = phdr->pack_flags;
3972   hdr.opt_comment  = g_strdup(pkt_comment);
3973   hdr.has_comment_changed = fdata->flags.has_user_comment ? TRUE : FALSE;
3974
3975   /* pseudo */
3976   hdr.pseudo_header = phdr->pseudo_header;
3977 #if 0
3978   hdr.drop_count   =
3979   hdr.pack_flags   =     /* XXX - 0 for now (any value for "we don't have it"?) */
3980 #endif
3981   /* and save the packet */
3982   if (!wtap_dump(args->pdh, &hdr, pd, &err, &err_info)) {
3983     cfile_write_failure_alert_box(NULL, args->fname, err, err_info, fdata->num,
3984                                   args->file_type);
3985     return FALSE;
3986   }
3987
3988   g_free(hdr.opt_comment);
3989   return TRUE;
3990 }
3991
3992 /*
3993  * Can this capture file be written out in any format using Wiretap
3994  * rather than by copying the raw data?
3995  */
3996 gboolean
3997 cf_can_write_with_wiretap(capture_file *cf)
3998 {
3999   /* We don't care whether we support the comments in this file or not;
4000      if we can't, we'll offer the user the option of discarding the
4001      comments. */
4002   return wtap_dump_can_write(cf->linktypes, 0);
4003 }
4004
4005 /*
4006  * Should we let the user do a save?
4007  *
4008  * We should if:
4009  *
4010  *  the file has unsaved changes, and we can save it in some
4011  *  format through Wiretap
4012  *
4013  * or
4014  *
4015  *  the file is a temporary file and has no unsaved changes (so
4016  *  that "saving" it just means copying it).
4017  *
4018  * XXX - we shouldn't allow files to be edited if they can't be saved,
4019  * so cf->unsaved_changes should be true only if the file can be saved.
4020  *
4021  * We don't care whether we support the comments in this file or not;
4022  * if we can't, we'll offer the user the option of discarding the
4023  * comments.
4024  */
4025 gboolean
4026 cf_can_save(capture_file *cf)
4027 {
4028   if (cf->unsaved_changes && wtap_dump_can_write(cf->linktypes, 0)) {
4029     /* Saved changes, and we can write it out with Wiretap. */
4030     return TRUE;
4031   }
4032
4033   if (cf->is_tempfile && !cf->unsaved_changes) {
4034     /*
4035      * Temporary file with no unsaved changes, so we can just do a
4036      * raw binary copy.
4037      */
4038     return TRUE;
4039   }
4040
4041   /* Nothing to save. */
4042   return FALSE;
4043 }
4044
4045 /*
4046  * Should we let the user do a "save as"?
4047  *
4048  * That's true if:
4049  *
4050  *  we can save it in some format through Wiretap
4051  *
4052  * or
4053  *
4054  *  the file is a temporary file and has no unsaved changes (so
4055  *  that "saving" it just means copying it).
4056  *
4057  * XXX - we shouldn't allow files to be edited if they can't be saved,
4058  * so cf->unsaved_changes should be true only if the file can be saved.
4059  *
4060  * We don't care whether we support the comments in this file or not;
4061  * if we can't, we'll offer the user the option of discarding the
4062  * comments.
4063  */
4064 gboolean
4065 cf_can_save_as(capture_file *cf)
4066 {
4067   if (wtap_dump_can_write(cf->linktypes, 0)) {
4068     /* We can write it out with Wiretap. */
4069     return TRUE;
4070   }
4071
4072   if (cf->is_tempfile && !cf->unsaved_changes) {
4073     /*
4074      * Temporary file with no unsaved changes, so we can just do a
4075      * raw binary copy.
4076      */
4077     return TRUE;
4078   }
4079
4080   /* Nothing to save. */
4081   return FALSE;
4082 }
4083
4084 /*
4085  * Does this file have unsaved data?
4086  */
4087 gboolean
4088 cf_has_unsaved_data(capture_file *cf)
4089 {
4090   /*
4091    * If this is a temporary file, or a file with unsaved changes, it
4092    * has unsaved data.
4093    */
4094   return (cf->is_tempfile && cf->count>0) || cf->unsaved_changes;
4095 }
4096
4097 /*
4098  * Quick scan to find packet offsets.
4099  */
4100 static cf_read_status_t
4101 rescan_file(capture_file *cf, const char *fname, gboolean is_tempfile)
4102 {
4103   const struct wtap_pkthdr *phdr;
4104   int                  err;
4105   gchar               *err_info;
4106   gchar               *name_ptr;
4107   gint64               data_offset;
4108   progdlg_t           *progbar        = NULL;
4109   GTimer              *prog_timer = g_timer_new();
4110   gint64               size;
4111   float                progbar_val;
4112   GTimeVal             start_time;
4113   gchar                status_str[100];
4114   guint32              framenum;
4115   frame_data          *fdata;
4116   int                  count          = 0;
4117
4118   /* Close the old handle. */
4119   wtap_close(cf->provider.wth);
4120
4121   /* Open the new file. */
4122   /* XXX: this will go through all open_routines for a matching one. But right
4123      now rescan_file() is only used when a file is being saved to a different
4124      format than the original, and the user is not given a choice of which
4125      reader to use (only which format to save it in), so doing this makes
4126      sense for now. */
4127   cf->provider.wth = wtap_open_offline(fname, WTAP_TYPE_AUTO, &err, &err_info, TRUE);
4128   if (cf->provider.wth == NULL) {
4129     cfile_open_failure_alert_box(fname, err, err_info);
4130     return CF_READ_ERROR;
4131   }
4132
4133   /* We're scanning a file whose contents should be the same as what
4134      we had before, so we don't discard dissection state etc.. */
4135   cf->f_datalen = 0;
4136
4137   /* Set the file name because we need it to set the follow stream filter.
4138      XXX - is that still true?  We need it for other reasons, though,
4139      in any case. */
4140   cf->filename = g_strdup(fname);
4141
4142   /* Indicate whether it's a permanent or temporary file. */
4143   cf->is_tempfile = is_tempfile;
4144
4145   /* No user changes yet. */
4146   cf->unsaved_changes = FALSE;
4147
4148   cf->cd_t        = wtap_file_type_subtype(cf->provider.wth);
4149   cf->linktypes = g_array_sized_new(FALSE, FALSE, (guint) sizeof(int), 1);
4150
4151   cf->snap      = wtap_snapshot_length(cf->provider.wth);
4152
4153   name_ptr = g_filename_display_basename(cf->filename);
4154
4155   cf_callback_invoke(cf_cb_file_rescan_started, cf);
4156
4157   /* Record whether the file is compressed.
4158      XXX - do we know this at open time? */
4159   cf->iscompressed = wtap_iscompressed(cf->provider.wth);
4160
4161   /* Find the size of the file. */
4162   size = wtap_file_size(cf->provider.wth, NULL);
4163
4164   g_timer_start(prog_timer);
4165
4166   cf->stop_flag = FALSE;
4167   g_get_current_time(&start_time);
4168
4169   framenum = 0;
4170   phdr = wtap_phdr(cf->provider.wth);
4171   while ((wtap_read(cf->provider.wth, &err, &err_info, &data_offset))) {
4172     framenum++;
4173     fdata = frame_data_sequence_find(cf->provider.frames, framenum);
4174     fdata->file_off = data_offset;
4175     if (size >= 0) {
4176       count++;
4177       cf->f_datalen = wtap_read_so_far(cf->provider.wth);
4178
4179       /* Create the progress bar if necessary. */
4180       if (progress_is_slow(progbar, prog_timer, size, cf->f_datalen)) {
4181         progbar_val = calc_progbar_val(cf, size, cf->f_datalen, status_str, sizeof(status_str));
4182         progbar = delayed_create_progress_dlg(cf->window, "Rescanning", name_ptr,
4183                                               TRUE, &cf->stop_flag, &start_time, progbar_val);
4184       }
4185
4186       /*
4187        * Update the progress bar, but do it only after PROGBAR_UPDATE_INTERVAL
4188        * has elapsed. Calling update_progress_dlg and packets_bar_update will
4189        * likely trigger UI paint events, which might take a while depending on
4190        * the platform and display. Reset our timer *after* painting.
4191        */
4192       if (progbar && g_timer_elapsed(prog_timer, NULL) > PROGBAR_UPDATE_INTERVAL) {
4193         progbar_val = calc_progbar_val(cf, size, cf->f_datalen, status_str, sizeof(status_str));
4194         /* update the packet bar content on the first run or frequently on very large files */
4195         update_progress_dlg(progbar, progbar_val, status_str);
4196         compute_elapsed(cf, &start_time);
4197         packets_bar_update();
4198         g_timer_start(prog_timer);
4199       }
4200     }
4201
4202     if (cf->stop_flag) {
4203       /* Well, the user decided to abort the rescan.  Sadly, as this
4204          isn't a reread, recovering is difficult, so we'll just
4205          close the current capture. */
4206       break;
4207     }
4208
4209     /* Add this packet's link-layer encapsulation type to cf->linktypes, if
4210        it's not already there.
4211        XXX - yes, this is O(N), so if every packet had a different
4212        link-layer encapsulation type, it'd be O(N^2) to read the file, but
4213        there are probably going to be a small number of encapsulation types
4214        in a file. */
4215     cf_add_encapsulation_type(cf, phdr->pkt_encap);
4216   }
4217
4218   /* Free the display name */
4219   g_free(name_ptr);
4220
4221   /* We're done reading the file; destroy the progress bar if it was created. */
4222   if (progbar != NULL)
4223     destroy_progress_dlg(progbar);
4224   g_timer_destroy(prog_timer);
4225
4226   /* We're done reading sequentially through the file. */
4227   cf->state = FILE_READ_DONE;
4228
4229   /* Close the sequential I/O side, to free up memory it requires. */
4230   wtap_sequential_close(cf->provider.wth);
4231
4232   /* compute the time it took to load the file */
4233   compute_elapsed(cf, &start_time);
4234
4235   /* Set the file encapsulation type now; we don't know what it is until
4236      we've looked at all the packets, as we don't know until then whether
4237      there's more than one type (and thus whether it's
4238      WTAP_ENCAP_PER_PACKET). */
4239   cf->lnk_t = wtap_file_encap(cf->provider.wth);
4240
4241   cf_callback_invoke(cf_cb_file_rescan_finished, cf);
4242
4243   if (cf->stop_flag) {
4244     /* Our caller will give up at this point. */
4245     return CF_READ_ABORTED;
4246   }
4247
4248   if (err != 0) {
4249     /* Put up a message box noting that the read failed somewhere along
4250        the line.  Don't throw out the stuff we managed to read, though,
4251        if any. */
4252     cfile_read_failure_alert_box(NULL, err, err_info);
4253     return CF_READ_ERROR;
4254   } else
4255     return CF_READ_OK;
4256 }
4257
4258 cf_write_status_t
4259 cf_save_records(capture_file *cf, const char *fname, guint save_format,
4260                 gboolean compressed, gboolean discard_comments,
4261                 gboolean dont_reopen)
4262 {
4263   gchar           *err_info;
4264   gchar           *fname_new = NULL;
4265   wtap_dumper     *pdh;
4266   frame_data      *fdata;
4267   addrinfo_lists_t *addr_lists;
4268   guint            framenum;
4269   int              err;
4270 #ifdef _WIN32
4271   gchar           *display_basename;
4272 #endif
4273   enum {
4274      SAVE_WITH_MOVE,
4275      SAVE_WITH_COPY,
4276      SAVE_WITH_WTAP
4277   }                    how_to_save;
4278   save_callback_args_t callback_args;
4279   gboolean needs_reload = FALSE;
4280
4281   cf_callback_invoke(cf_cb_file_save_started, (gpointer)fname);
4282
4283   addr_lists = get_addrinfo_list();
4284
4285   if (save_format == cf->cd_t && compressed == cf->iscompressed
4286       && !discard_comments && !cf->unsaved_changes
4287       && !(addr_lists && wtap_dump_has_name_resolution(save_format))) {
4288     /* We're saving in the format it's already in, and we're
4289        not discarding comments, and there are no changes we have
4290        in memory that aren't saved to the file, and we have no name
4291        resolution blocks to write, so we can just move or copy the raw data. */
4292
4293     if (cf->is_tempfile) {
4294       /* The file being saved is a temporary file from a live
4295          capture, so it doesn't need to stay around under that name;
4296          first, try renaming the capture buffer file to the new name.
4297          This acts as a "safe save", in that, if the file already
4298          exists, the existing file will be removed only if the rename
4299          succeeds.
4300
4301          Sadly, on Windows, as we have the current capture file
4302          open, even MoveFileEx() with MOVEFILE_REPLACE_EXISTING
4303          (to cause the rename to remove an existing target), as
4304          done by ws_stdio_rename() (ws_rename() is #defined to
4305          be ws_stdio_rename() on Windows) will fail.
4306
4307          According to the MSDN documentation for CreateFile(), if,
4308          when we open a capture file, we were to directly do a CreateFile(),
4309          opening with FILE_SHARE_DELETE|FILE_SHARE_READ, and then
4310          convert it to a file descriptor with _open_osfhandle(),
4311          that would allow the file to be renamed out from under us.
4312
4313          However, that doesn't work in practice.  Perhaps the problem
4314          is that the process doing the rename is the process that
4315          has the file open. */
4316 #ifndef _WIN32
4317       if (ws_rename(cf->filename, fname) == 0) {
4318         /* That succeeded - there's no need to copy the source file. */
4319         how_to_save = SAVE_WITH_MOVE;
4320       } else {
4321         if (errno == EXDEV) {
4322           /* They're on different file systems, so we have to copy the
4323              file. */
4324           how_to_save = SAVE_WITH_COPY;
4325         } else {
4326           /* The rename failed, but not because they're on different
4327              file systems - put up an error message.  (Or should we
4328              just punt and try to copy?  The only reason why I'd
4329              expect the rename to fail and the copy to succeed would
4330              be if we didn't have permission to remove the file from
4331              the temporary directory, and that might be fixable - but
4332              is it worth requiring the user to go off and fix it?) */
4333           cf_rename_failure_alert_box(fname, errno);
4334           goto fail;
4335         }
4336       }
4337 #else
4338       /* Windows - copy the file to its new location. */
4339       how_to_save = SAVE_WITH_COPY;
4340 #endif
4341     } else {
4342       /* It's a permanent file, so we should copy it, and not remove the
4343          original. */
4344       how_to_save = SAVE_WITH_COPY;
4345     }
4346
4347     if (how_to_save == SAVE_WITH_COPY) {
4348       /* Copy the file, if we haven't moved it.  If we're overwriting
4349          an existing file, we do it with a "safe save", by writing
4350          to a new file and, if the write succeeds, renaming the
4351          new file on top of the old file. */
4352       if (file_exists(fname)) {
4353         fname_new = g_strdup_printf("%s~", fname);
4354         if (!copy_file_binary_mode(cf->filename, fname_new))
4355           goto fail;
4356       } else {
4357         if (!copy_file_binary_mode(cf->filename, fname))
4358           goto fail;
4359       }
4360     }
4361   } else {
4362     /* Either we're saving in a different format or we're saving changes,
4363        such as added, modified, or removed comments, that haven't yet
4364        been written to the underlying file; we can't do that by copying
4365        or moving the capture file, we have to do it by writing the packets
4366        out in Wiretap. */
4367
4368     GArray                      *shb_hdrs = NULL;
4369     wtapng_iface_descriptions_t *idb_inf = NULL;
4370     GArray                      *nrb_hdrs = NULL;
4371     int encap;
4372
4373     /* XXX: what free's this shb_hdr? */
4374     shb_hdrs = wtap_file_get_shb_for_new_file(cf->provider.wth);
4375     idb_inf = wtap_file_get_idb_info(cf->provider.wth);
4376     nrb_hdrs = wtap_file_get_nrb_for_new_file(cf->provider.wth);
4377
4378     /* Determine what file encapsulation type we should use. */
4379     encap = wtap_dump_file_encap_type(cf->linktypes);
4380
4381     if (file_exists(fname)) {
4382       /* We're overwriting an existing file; write out to a new file,
4383          and, if that succeeds, rename the new file on top of the
4384          old file.  That makes this a "safe save", so that we don't
4385          lose the old file if we have a problem writing out the new
4386          file.  (If the existing file is the current capture file,
4387          we *HAVE* to do that, otherwise we're overwriting the file
4388          from which we're reading the packets that we're writing!) */
4389       fname_new = g_strdup_printf("%s~", fname);
4390       pdh = wtap_dump_open_ng(fname_new, save_format, encap, cf->snap,
4391                               compressed, shb_hdrs, idb_inf, nrb_hdrs, &err);
4392     } else {
4393       pdh = wtap_dump_open_ng(fname, save_format, encap, cf->snap,
4394                               compressed, shb_hdrs, idb_inf, nrb_hdrs, &err);
4395     }
4396     g_free(idb_inf);
4397     idb_inf = NULL;
4398
4399     if (pdh == NULL) {
4400       cfile_dump_open_failure_alert_box(fname, err, save_format);
4401       goto fail;
4402     }
4403
4404     /* Add address resolution */
4405     wtap_dump_set_addrinfo_list(pdh, addr_lists);
4406
4407     /* Iterate through the list of packets, processing all the packets. */
4408     callback_args.pdh = pdh;
4409     callback_args.fname = fname;
4410     callback_args.file_type = save_format;
4411     switch (process_specified_records(cf, NULL, "Saving", "packets",
4412                                       TRUE, save_record, &callback_args, TRUE)) {
4413
4414     case PSP_FINISHED:
4415       /* Completed successfully. */
4416       break;
4417
4418     case PSP_STOPPED:
4419       /* The user decided to abort the saving.
4420          If we're writing to a temporary file, remove it.
4421          XXX - should we do so even if we're not writing to a
4422          temporary file? */
4423       wtap_dump_close(pdh, &err);
4424       if (fname_new != NULL)
4425         ws_unlink(fname_new);
4426       cf_callback_invoke(cf_cb_file_save_stopped, NULL);
4427       return CF_WRITE_ABORTED;
4428
4429     case PSP_FAILED:
4430       /* Error while saving.
4431          If we're writing to a temporary file, remove it. */
4432       if (fname_new != NULL)
4433         ws_unlink(fname_new);
4434       wtap_dump_close(pdh, &err);
4435       goto fail;
4436     }
4437
4438     needs_reload = wtap_dump_get_needs_reload(pdh);
4439
4440     if (!wtap_dump_close(pdh, &err)) {
4441       cfile_close_failure_alert_box(fname, err);
4442       goto fail;
4443     }
4444
4445     how_to_save = SAVE_WITH_WTAP;
4446   }
4447
4448   if (fname_new != NULL) {
4449     /* We wrote out to fname_new, and should rename it on top of
4450        fname.  fname_new is now closed, so that should be possible even
4451        on Windows.  However, on Windows, we first need to close whatever
4452        file descriptors we have open for fname. */
4453 #ifdef _WIN32
4454     wtap_fdclose(cf->provider.wth);
4455 #endif
4456     /* Now do the rename. */
4457     if (ws_rename(fname_new, fname) == -1) {
4458       /* Well, the rename failed. */
4459       cf_rename_failure_alert_box(fname, errno);
4460 #ifdef _WIN32
4461       /* Attempt to reopen the random file descriptor using the
4462          current file's filename.  (At this point, the sequential
4463          file descriptor is closed.) */
4464       if (!wtap_fdreopen(cf->provider.wth, cf->filename, &err)) {
4465         /* Oh, well, we're screwed. */
4466         display_basename = g_filename_display_basename(cf->filename);
4467         simple_error_message_box(
4468                       file_open_error_message(err, FALSE), display_basename);
4469         g_free(display_basename);
4470       }
4471 #endif
4472       goto fail;
4473     }
4474   }
4475
4476   /* If this was a temporary file, and we didn't do the save by doing
4477      a move, so the tempoary file is still around under its old name,
4478      remove it. */
4479   if (cf->is_tempfile) {
4480     /* If this fails, there's not much we can do, so just ignore errors. */
4481     ws_unlink(cf->filename);
4482   }
4483
4484   cf_callback_invoke(cf_cb_file_save_finished, NULL);
4485   cf->unsaved_changes = FALSE;
4486
4487   if (!dont_reopen) {
4488     switch (how_to_save) {
4489
4490     case SAVE_WITH_MOVE:
4491       /* We just moved the file, so the wtap structure refers to the
4492          new file, and all the information other than the filename
4493          and the "is temporary" status applies to the new file; just
4494          update that. */
4495       g_free(cf->filename);
4496       cf->filename = g_strdup(fname);
4497       cf->is_tempfile = FALSE;
4498       cf_callback_invoke(cf_cb_file_fast_save_finished, cf);
4499       break;
4500
4501     case SAVE_WITH_COPY:
4502       /* We just copied the file, so all the information other than
4503          the wtap structure, the filename, and the "is temporary"
4504          status applies to the new file; just update that. */
4505       wtap_close(cf->provider.wth);
4506       /* Although we're just "copying" and then opening the copy, it will
4507          try all open_routine readers to open the copy, so we need to
4508          reset the cfile's open_type. */
4509       cf->open_type = WTAP_TYPE_AUTO;
4510       cf->provider.wth = wtap_open_offline(fname, WTAP_TYPE_AUTO, &err, &err_info, TRUE);
4511       if (cf->provider.wth == NULL) {
4512         cfile_open_failure_alert_box(fname, err, err_info);
4513         cf_close(cf);
4514       } else {
4515         g_free(cf->filename);
4516         cf->filename = g_strdup(fname);
4517         cf->is_tempfile = FALSE;
4518       }
4519       cf_callback_invoke(cf_cb_file_fast_save_finished, cf);
4520       break;
4521
4522     case SAVE_WITH_WTAP:
4523       /* Open and read the file we saved to.
4524
4525          XXX - this is somewhat of a waste; we already have the
4526          packets, all this gets us is updated file type information
4527          (which we could just stuff into "cf"), and having the new
4528          file be the one we have opened and from which we're reading
4529          the data, and it means we have to spend time opening and
4530          reading the file, which could be a significant amount of
4531          time if the file is large.
4532
4533          If the capture-file-writing code were to return the
4534          seek offset of each packet it writes, we could save that
4535          in the frame_data structure for the frame, and just open
4536          the file without reading it again...
4537
4538          ...as long as, for gzipped files, the process of writing
4539          out the file *also* generates the information needed to
4540          support fast random access to the compressed file. */
4541       /* rescan_file will cause us to try all open_routines, so
4542          reset cfile's open_type */
4543       cf->open_type = WTAP_TYPE_AUTO;
4544       /* There are cases when SAVE_WITH_WTAP can result in new packets
4545          being written to the file, e.g ERF records
4546          In that case, we need to reload the whole file */
4547       if(needs_reload) {
4548         if (cf_open(cf, fname, WTAP_TYPE_AUTO, FALSE, &err) == CF_OK) {
4549           if (cf_read(cf, TRUE) != CF_READ_OK) {
4550              /* The rescan failed; just close the file.  Either
4551                a dialog was popped up for the failure, so the
4552                user knows what happened, or they stopped the
4553                rescan, in which case they know what happened.  */
4554             /* XXX: This is inconsistent with normal open/reload behaviour. */
4555             cf_close(cf);
4556           }
4557         }
4558       }
4559       else {
4560         if (rescan_file(cf, fname, FALSE) != CF_READ_OK) {
4561            /* The rescan failed; just close the file.  Either
4562              a dialog was popped up for the failure, so the
4563              user knows what happened, or they stopped the
4564              rescan, in which case they know what happened.  */
4565           cf_close(cf);
4566         }
4567       }
4568       break;
4569     }
4570
4571     /* If we were told to discard the comments, do so. */
4572     if (discard_comments) {
4573       /* Remove SHB comment, if any. */
4574       wtap_write_shb_comment(cf->provider.wth, NULL);
4575
4576       /* remove all user comments */
4577       for (framenum = 1; framenum <= cf->count; framenum++) {
4578         fdata = frame_data_sequence_find(cf->provider.frames, framenum);
4579
4580         fdata->flags.has_phdr_comment = FALSE;
4581         fdata->flags.has_user_comment = FALSE;
4582       }
4583
4584       if (cf->provider.frames_user_comments) {
4585         g_tree_destroy(cf->provider.frames_user_comments);
4586         cf->provider.frames_user_comments = NULL;
4587       }
4588
4589       cf->packet_comment_count = 0;
4590     }
4591   }
4592   return CF_WRITE_OK;
4593
4594 fail:
4595   if (fname_new != NULL) {
4596     /* We were trying to write to a temporary file; get rid of it if it
4597        exists.  (We don't care whether this fails, as, if it fails,
4598        there's not much we can do about it.  I guess if it failed for
4599        a reason other than "it doesn't exist", we could report an
4600        error, so the user knows there's a junk file that they might
4601        want to clean up.) */
4602     ws_unlink(fname_new);
4603     g_free(fname_new);
4604   }
4605   cf_callback_invoke(cf_cb_file_save_failed, NULL);
4606   return CF_WRITE_ERROR;
4607 }
4608
4609 cf_write_status_t
4610 cf_export_specified_packets(capture_file *cf, const char *fname,
4611                             packet_range_t *range, guint save_format,
4612                             gboolean compressed)
4613 {
4614   gchar                       *fname_new = NULL;
4615   int                          err;
4616   wtap_dumper                 *pdh;
4617   save_callback_args_t         callback_args;
4618   GArray                      *shb_hdrs = NULL;
4619   wtapng_iface_descriptions_t *idb_inf = NULL;
4620   GArray                      *nrb_hdrs = NULL;
4621   int                          encap;
4622
4623   cf_callback_invoke(cf_cb_file_export_specified_packets_started, (gpointer)fname);
4624
4625   packet_range_process_init(range);
4626
4627   /* We're writing out specified packets from the specified capture
4628      file to another file.  Even if all captured packets are to be
4629      written, don't special-case the operation - read each packet
4630      and then write it out if it's one of the specified ones. */
4631
4632   /* XXX: what free's this shb_hdr? */
4633   shb_hdrs = wtap_file_get_shb_for_new_file(cf->provider.wth);
4634   idb_inf = wtap_file_get_idb_info(cf->provider.wth);
4635   nrb_hdrs = wtap_file_get_nrb_for_new_file(cf->provider.wth);
4636
4637   /* Determine what file encapsulation type we should use. */
4638   encap = wtap_dump_file_encap_type(cf->linktypes);
4639
4640   if (file_exists(fname)) {
4641     /* We're overwriting an existing file; write out to a new file,
4642        and, if that succeeds, rename the new file on top of the
4643        old file.  That makes this a "safe save", so that we don't
4644        lose the old file if we have a problem writing out the new
4645        file.  (If the existing file is the current capture file,
4646        we *HAVE* to do that, otherwise we're overwriting the file
4647        from which we're reading the packets that we're writing!) */
4648     fname_new = g_strdup_printf("%s~", fname);
4649     pdh = wtap_dump_open_ng(fname_new, save_format, encap, cf->snap,
4650                             compressed, shb_hdrs, idb_inf, nrb_hdrs, &err);
4651   } else {
4652     pdh = wtap_dump_open_ng(fname, save_format, encap, cf->snap,
4653                             compressed, shb_hdrs, idb_inf, nrb_hdrs, &err);
4654   }
4655   g_free(idb_inf);
4656   idb_inf = NULL;
4657
4658   if (pdh == NULL) {
4659     cfile_dump_open_failure_alert_box(fname, err, save_format);
4660     goto fail;
4661   }
4662
4663   /* Add address resolution */
4664   wtap_dump_set_addrinfo_list(pdh, get_addrinfo_list());
4665
4666   /* Iterate through the list of packets, processing the packets we were
4667      told to process.
4668
4669      XXX - we've already called "packet_range_process_init(range)", but
4670      "process_specified_records()" will do it again.  Fortunately,
4671      that's harmless in this case, as we haven't done anything to
4672      "range" since we initialized it. */
4673   callback_args.pdh = pdh;
4674   callback_args.fname = fname;
4675   callback_args.file_type = save_format;
4676   switch (process_specified_records(cf, range, "Writing", "specified records",
4677                                     TRUE, save_record, &callback_args, TRUE)) {
4678
4679   case PSP_FINISHED:
4680     /* Completed successfully. */
4681     break;
4682
4683   case PSP_STOPPED:
4684       /* The user decided to abort the saving.
4685          If we're writing to a temporary file, remove it.
4686          XXX - should we do so even if we're not writing to a
4687          temporary file? */
4688       wtap_dump_close(pdh, &err);
4689       if (fname_new != NULL)
4690         ws_unlink(fname_new);
4691       cf_callback_invoke(cf_cb_file_export_specified_packets_stopped, NULL);
4692       return CF_WRITE_ABORTED;
4693     break;
4694
4695   case PSP_FAILED:
4696     /* Error while saving.
4697        If we're writing to a temporary file, remove it. */
4698     if (fname_new != NULL)
4699       ws_unlink(fname_new);
4700     wtap_dump_close(pdh, &err);
4701     goto fail;
4702   }
4703
4704   if (!wtap_dump_close(pdh, &err)) {
4705     cfile_close_failure_alert_box(fname, err);
4706     goto fail;
4707   }
4708
4709   if (fname_new != NULL) {
4710     /* We wrote out to fname_new, and should rename it on top of
4711        fname; fname is now closed, so that should be possible even
4712        on Windows.  Do the rename. */
4713     if (ws_rename(fname_new, fname) == -1) {
4714       /* Well, the rename failed. */
4715       cf_rename_failure_alert_box(fname, errno);
4716       goto fail;
4717     }
4718   }
4719
4720   cf_callback_invoke(cf_cb_file_export_specified_packets_finished, NULL);
4721   return CF_WRITE_OK;
4722
4723 fail:
4724   if (fname_new != NULL) {
4725     /* We were trying to write to a temporary file; get rid of it if it
4726        exists.  (We don't care whether this fails, as, if it fails,
4727        there's not much we can do about it.  I guess if it failed for
4728        a reason other than "it doesn't exist", we could report an
4729        error, so the user knows there's a junk file that they might
4730        want to clean up.) */
4731     ws_unlink(fname_new);
4732     g_free(fname_new);
4733   }
4734   cf_callback_invoke(cf_cb_file_export_specified_packets_failed, NULL);
4735   return CF_WRITE_ERROR;
4736 }
4737
4738 /*
4739  * XXX - whether we mention the source pathname, the target pathname,
4740  * or both depends on the error and on what we find if we look for
4741  * one or both of them.
4742  */
4743 static void
4744 cf_rename_failure_alert_box(const char *filename, int err)
4745 {
4746   gchar *display_basename;
4747
4748   display_basename = g_filename_display_basename(filename);
4749   switch (err) {
4750
4751   case ENOENT:
4752     /* XXX - should check whether the source exists and, if not,
4753        report it as the problem and, if so, report the destination
4754        as the problem. */
4755     simple_error_message_box("The path to the file \"%s\" doesn't exist.",
4756                              display_basename);
4757     break;
4758
4759   case EACCES:
4760     /* XXX - if we're doing a rename after a safe save, we should
4761        probably say something else. */
4762     simple_error_message_box("You don't have permission to move the capture file to \"%s\".",
4763                              display_basename);
4764     break;
4765
4766   default:
4767     /* XXX - this should probably mention both the source and destination
4768        pathnames. */
4769     simple_error_message_box("The file \"%s\" could not be moved: %s.",
4770                              display_basename, wtap_strerror(err));
4771     break;
4772   }
4773   g_free(display_basename);
4774 }
4775
4776 /* Reload the current capture file. */
4777 void
4778 cf_reload(capture_file *cf) {
4779   gchar    *filename;
4780   gboolean  is_tempfile;
4781   int       err;
4782
4783   /* If the file could be opened, "cf_open()" calls "cf_close()"
4784      to get rid of state for the old capture file before filling in state
4785      for the new capture file.  "cf_close()" will remove the file if
4786      it's a temporary file; we don't want that to happen (for one thing,
4787      it'd prevent subsequent reopens from working).  Remember whether it's
4788      a temporary file, mark it as not being a temporary file, and then
4789      reopen it as the type of file it was.
4790
4791      Also, "cf_close()" will free "cf->filename", so we must make
4792      a copy of it first. */
4793   filename = g_strdup(cf->filename);
4794   is_tempfile = cf->is_tempfile;
4795   cf->is_tempfile = FALSE;
4796   if (cf_open(cf, filename, cf->open_type, is_tempfile, &err) == CF_OK) {
4797     switch (cf_read(cf, TRUE)) {
4798
4799     case CF_READ_OK:
4800     case CF_READ_ERROR:
4801       /* Just because we got an error, that doesn't mean we were unable
4802          to read any of the file; we handle what we could get from the
4803          file. */
4804       break;
4805
4806     case CF_READ_ABORTED:
4807       /* The user bailed out of re-reading the capture file; the
4808          capture file has been closed - just free the capture file name
4809          string and return (without changing the last containing
4810          directory). */
4811       g_free(filename);
4812       return;
4813     }
4814   } else {
4815     /* The open failed, so "cf->is_tempfile" wasn't set to "is_tempfile".
4816        Instead, the file was left open, so we should restore "cf->is_tempfile"
4817        ourselves.
4818
4819        XXX - change the menu?  Presumably "cf_open()" will do that;
4820        make sure it does! */
4821     cf->is_tempfile = is_tempfile;
4822   }
4823   /* "cf_open()" made a copy of the file name we handed it, so
4824      we should free up our copy. */
4825   g_free(filename);
4826 }
4827
4828 /*
4829  * Editor modelines
4830  *
4831  * Local Variables:
4832  * c-basic-offset: 2
4833  * tab-width: 8
4834  * indent-tabs-mode: nil
4835  * End:
4836  *
4837  * ex: set shiftwidth=2 tabstop=8 expandtab:
4838  * :indentSize=2:tabSize=8:noTabs=true:
4839  */