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