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