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