From Martin Regner: fix dissection of non-standard parameters.
[obnox/wireshark/wip.git] / file.c
1 /* file.c
2  * File I/O routines
3  *
4  * $Id: file.c,v 1.307 2003/09/03 23:40:06 guy Exp $
5  *
6  * Ethereal - Network traffic analyzer
7  * By Gerald Combs <gerald@ethereal.com>
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 #include <gtk/gtk.h>
33 #include <gtk/keys.h>
34 #include <gtk/compat_macros.h>
35
36 #include <time.h>
37
38 #ifdef HAVE_IO_H
39 #include <io.h>
40 #endif
41
42 #include <stdlib.h>
43 #include <stdio.h>
44 #include <string.h>
45 #include <ctype.h>
46 #include <errno.h>
47 #include <signal.h>
48
49 #ifdef HAVE_SYS_STAT_H
50 #include <sys/stat.h>
51 #endif
52
53 #ifdef HAVE_FCNTL_H
54 #include <fcntl.h>
55 #endif
56
57 #ifdef NEED_SNPRINTF_H
58 # include "snprintf.h"
59 #endif
60
61 #ifdef NEED_STRERROR_H
62 #include "strerror.h"
63 #endif
64
65 #include <epan/epan.h>
66 #include <epan/filesystem.h>
67
68 #include "color.h"
69 #include "column.h"
70 #include <epan/packet.h>
71 #include "print.h"
72 #include "file.h"
73 #include "menu.h"
74 #include "util.h"
75 #include "simple_dialog.h"
76 #include "progress_dlg.h"
77 #include "ui_util.h"
78 #include "statusbar.h"
79 #include "prefs.h"
80 #include <epan/dfilter/dfilter.h>
81 #include <epan/conversation.h>
82 #include "globals.h"
83 #include <epan/epan_dissect.h>
84 #include "tap.h"
85 #include "packet-data.h"
86
87 #ifdef HAVE_LIBPCAP
88 gboolean auto_scroll_live;
89 #endif
90
91 #define MAX_DECODE_BUFFER_SIZE 16536
92
93 static guint32 firstsec, firstusec;
94 static guint32 prevsec, prevusec;
95 static guint32 cul_bytes = 0;
96
97 static void read_packet(capture_file *cf, long offset);
98
99 static void rescan_packets(capture_file *cf, const char *action, const char *action_item,
100         gboolean refilter, gboolean redissect);
101
102 static gboolean match_protocol_tree(capture_file *cf, frame_data *fdata,
103         void *criterion);
104 static void match_subtree_text(GNode *node, gpointer data);
105 static gboolean match_summary_line(capture_file *cf, frame_data *fdata,
106         void *criterion);
107 static gboolean match_ascii_and_unicode(capture_file *cf, frame_data *fdata,
108         void *criterion);
109 static gboolean match_ascii(capture_file *cf, frame_data *fdata,
110         void *criterion);
111 static gboolean match_unicode(capture_file *cf, frame_data *fdata,
112         void *criterion);
113 static gboolean match_binary(capture_file *cf, frame_data *fdata,
114         void *criterion);
115 static gboolean match_dfilter(capture_file *cf, frame_data *fdata,
116         void *criterion);
117 static gboolean find_packet(capture_file *cf,
118         gboolean (*match_function)(capture_file *, frame_data *, void *),
119         void *criterion);
120
121 static void freeze_plist(capture_file *cf);
122 static void thaw_plist(capture_file *cf);
123
124 static char *file_rename_error_message(int err);
125 static char *file_close_error_message(int err);
126 static gboolean copy_binary_file(char *from_filename, char *to_filename);
127
128 /* Update the progress bar this many times when reading a file. */
129 #define N_PROGBAR_UPDATES       100
130
131 /* Number of "frame_data" structures per memory chunk.
132    XXX - is this the right number? */
133 #define FRAME_DATA_CHUNK_SIZE   1024
134
135
136 typedef struct {
137         int             level;
138         FILE            *fh;
139         GSList          *src_list;
140         gboolean        print_all_levels;
141         gboolean        print_hex_for_data;
142         char_enc        encoding;
143         gint            format;         /* text or PostScript */
144 } print_data;
145
146
147 int
148 open_cap_file(char *fname, gboolean is_tempfile, capture_file *cf)
149 {
150   wtap       *wth;
151   int         err;
152   int         fd;
153   struct stat cf_stat;
154
155   wth = wtap_open_offline(fname, &err, TRUE);
156   if (wth == NULL)
157     goto fail;
158
159   /* Find the size of the file. */
160   fd = wtap_fd(wth);
161   if (fstat(fd, &cf_stat) < 0) {
162     err = errno;
163     wtap_close(wth);
164     goto fail;
165   }
166
167   /* The open succeeded.  Close whatever capture file we had open,
168      and fill in the information for this file. */
169   close_cap_file(cf);
170
171   /* Initialize all data structures used for dissection. */
172   init_dissection();
173
174   /* We're about to start reading the file. */
175   cf->state = FILE_READ_IN_PROGRESS;
176
177   cf->wth = wth;
178   cf->filed = fd;
179   cf->f_len = cf_stat.st_size;
180
181   /* Set the file name because we need it to set the follow stream filter.
182      XXX - is that still true?  We need it for other reasons, though,
183      in any case. */
184   cf->filename = g_strdup(fname);
185
186   /* Indicate whether it's a permanent or temporary file. */
187   cf->is_tempfile = is_tempfile;
188
189   /* If it's a temporary capture buffer file, mark it as not saved. */
190   cf->user_saved = !is_tempfile;
191
192   cf->cd_t      = wtap_file_type(cf->wth);
193   cf->count     = 0;
194   cf->marked_count = 0;
195   cf->drops_known = FALSE;
196   cf->drops     = 0;
197   cf->esec      = 0;
198   cf->eusec     = 0;
199   cf->snap      = wtap_snapshot_length(cf->wth);
200   if (cf->snap == 0) {
201     /* Snapshot length not known. */
202     cf->has_snap = FALSE;
203     cf->snap = WTAP_MAX_PACKET_SIZE;
204   } else
205     cf->has_snap = TRUE;
206   cf->progbar_quantum = 0;
207   cf->progbar_nextstep = 0;
208   firstsec = 0, firstusec = 0;
209   prevsec = 0, prevusec = 0;
210
211   cf->plist_chunk = g_mem_chunk_new("frame_data_chunk",
212         sizeof(frame_data),
213         FRAME_DATA_CHUNK_SIZE * sizeof(frame_data),
214         G_ALLOC_AND_FREE);
215   g_assert(cf->plist_chunk);
216
217   return (0);
218
219 fail:
220   simple_dialog(ESD_TYPE_CRIT, NULL,
221                         file_open_error_message(err, FALSE, 0), fname);
222   return (err);
223 }
224
225 /* Reset everything to a pristine state */
226 void
227 close_cap_file(capture_file *cf)
228 {
229   /* Die if we're in the middle of reading a file. */
230   g_assert(cf->state != FILE_READ_IN_PROGRESS);
231
232   /* Destroy all popup packet windows, as they refer to packets in the
233      capture file we're closing. */
234   destroy_packet_wins();
235
236   if (cf->wth) {
237     wtap_close(cf->wth);
238     cf->wth = NULL;
239   }
240   /* We have no file open... */
241   if (cf->filename != NULL) {
242     /* If it's a temporary file, remove it. */
243     if (cf->is_tempfile)
244       unlink(cf->filename);
245     g_free(cf->filename);
246     cf->filename = NULL;
247   }
248   /* ...which means we have nothing to save. */
249   cf->user_saved = FALSE;
250
251   if (cf->plist_chunk != NULL) {
252     g_mem_chunk_destroy(cf->plist_chunk);
253     cf->plist_chunk = NULL;
254   }
255   if (cf->rfcode != NULL) {
256     dfilter_free(cf->rfcode);
257     cf->rfcode = NULL;
258   }
259   cf->plist = NULL;
260   cf->plist_end = NULL;
261   unselect_packet(cf);  /* nothing to select */
262   cf->first_displayed = NULL;
263   cf->last_displayed = NULL;
264
265   /* Clear the packet list. */
266   packet_list_freeze();
267   packet_list_clear();
268   packet_list_thaw();
269
270   /* Clear any file-related status bar messages.
271      XXX - should be "clear *ALL* file-related status bar messages;
272      will there ever be more than one on the stack? */
273   statusbar_pop_file_msg();
274
275   /* Restore the standard title bar message. */
276   set_main_window_name("The Ethereal Network Analyzer");
277
278   /* Disable all menu items that make sense only if you have a capture. */
279   set_menus_for_capture_file(FALSE);
280   set_menus_for_unsaved_capture_file(FALSE);
281   set_menus_for_captured_packets(FALSE);
282   set_menus_for_selected_packet(FALSE);
283   set_menus_for_capture_in_progress(FALSE);
284   set_menus_for_selected_tree_row(FALSE);
285
286   /* We have no file open. */
287   cf->state = FILE_CLOSED;
288 }
289
290 /* Set the file name in the status line, in the name for the main window,
291    and in the name for the main window's icon. */
292 static void
293 set_display_filename(capture_file *cf)
294 {
295   gchar  *name_ptr;
296   size_t  msg_len;
297   static const gchar done_fmt_nodrops[] = " File: %s";
298   static const gchar done_fmt_drops[] = " File: %s  Drops: %u";
299   gchar  *done_msg;
300   gchar  *win_name_fmt = "%s - Ethereal";
301   gchar  *win_name;
302
303   if (!cf->is_tempfile) {
304     /* Get the last component of the file name, and put that in the
305        status bar. */
306     name_ptr = get_basename(cf->filename);
307   } else {
308     /* The file we read is a temporary file from a live capture;
309        we don't mention its name in the status bar. */
310     name_ptr = "<capture>";
311   }
312
313   if (cf->drops_known) {
314     msg_len = strlen(name_ptr) + strlen(done_fmt_drops) + 64;
315     done_msg = g_malloc(msg_len);
316     snprintf(done_msg, msg_len, done_fmt_drops, name_ptr, cf->drops);
317   } else {
318     msg_len = strlen(name_ptr) + strlen(done_fmt_nodrops);
319     done_msg = g_malloc(msg_len);
320     snprintf(done_msg, msg_len, done_fmt_nodrops, name_ptr);
321   }
322   statusbar_push_file_msg(done_msg);
323   g_free(done_msg);
324
325   msg_len = strlen(name_ptr) + strlen(win_name_fmt) + 1;
326   win_name = g_malloc(msg_len);
327   snprintf(win_name, msg_len, win_name_fmt, name_ptr);
328   set_main_window_name(win_name);
329   g_free(win_name);
330 }
331
332 read_status_t
333 read_cap_file(capture_file *cf, int *err)
334 {
335   gchar      *name_ptr, *load_msg, *load_fmt = "%s";
336   size_t      msg_len;
337   char       *errmsg;
338   char        errmsg_errno[1024+1];
339   gchar       err_str[2048+1];
340   long        data_offset;
341   progdlg_t  *progbar = NULL;
342   gboolean    stop_flag;
343   /*
344    * XXX - should be "off_t", but Wiretap would need more work to handle
345    * the full size of "off_t" on platforms where it's more than a "long"
346    * as well.
347    */
348   long        file_pos;
349   float       prog_val;
350   int         fd;
351   struct stat cf_stat;
352   GTimeVal    start_time;
353   gchar       status_str[100];
354
355   cul_bytes=0;
356   reset_tap_listeners();
357   name_ptr = get_basename(cf->filename);
358
359   msg_len = strlen(name_ptr) + strlen(load_fmt) + 2;
360   load_msg = g_malloc(msg_len);
361   snprintf(load_msg, msg_len, load_fmt, name_ptr);
362   statusbar_push_file_msg(load_msg);
363
364   /* Update the progress bar when it gets to this value. */
365   cf->progbar_nextstep = 0;
366   /* When we reach the value that triggers a progress bar update,
367      bump that value by this amount. */
368   cf->progbar_quantum = cf->f_len/N_PROGBAR_UPDATES;
369
370 #ifndef O_BINARY
371 #define O_BINARY        0
372 #endif
373
374   freeze_plist(cf);
375
376   stop_flag = FALSE;
377   g_get_current_time(&start_time);
378
379   while ((wtap_read(cf->wth, err, &data_offset))) {
380     /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
381        when we update it, we have to run the GTK+ main loop to get it
382        to repaint what's pending, and doing so may involve an "ioctl()"
383        to see if there's any pending input from an X server, and doing
384        that for every packet can be costly, especially on a big file. */
385     if (data_offset >= cf->progbar_nextstep) {
386         file_pos = lseek(cf->filed, 0, SEEK_CUR);
387         prog_val = (gfloat) file_pos / (gfloat) cf->f_len;
388         if (prog_val > 1.0) {
389           /* The file probably grew while we were reading it.
390              Update "cf->f_len", and try again. */
391           fd = wtap_fd(cf->wth);
392           if (fstat(fd, &cf_stat) >= 0) {
393             cf->f_len = cf_stat.st_size;
394             prog_val = (gfloat) file_pos / (gfloat) cf->f_len;
395           }
396           /* If it's still > 1, either the "fstat()" failed (in which
397              case there's not much we can do about it), or the file
398              *shrank* (in which case there's not much we can do about
399              it); just clip the progress value at 1.0. */
400           if (prog_val > 1.0)
401             prog_val = 1.0;
402         }
403         if (progbar == NULL) {
404           /* Create the progress bar if necessary */
405           progbar = delayed_create_progress_dlg("Loading", load_msg, "Stop",
406             &stop_flag, &start_time, prog_val);
407           if (progbar != NULL)
408             g_free(load_msg);
409         }
410         if (progbar != NULL) {
411           g_snprintf(status_str, sizeof(status_str),
412                      "%luKB of %luKB", file_pos / 1024, cf->f_len / 1024);
413           update_progress_dlg(progbar, prog_val, status_str);
414         }
415         cf->progbar_nextstep += cf->progbar_quantum;
416     }
417
418     if (stop_flag) {
419       /* Well, the user decided to abort the read.  Destroy the progress
420          bar, close the capture file, and return READ_ABORTED so our caller
421          can do whatever is appropriate when that happens. */
422       destroy_progress_dlg(progbar);
423       cf->state = FILE_READ_ABORTED;    /* so that we're allowed to close it */
424       packet_list_thaw();               /* undo our freeze */
425       close_cap_file(cf);
426       return (READ_ABORTED);
427     }
428     read_packet(cf, data_offset);
429   }
430
431   /* We're done reading the file; destroy the progress bar if it was created. */
432   if (progbar == NULL)
433     g_free(load_msg);
434   else
435     destroy_progress_dlg(progbar);
436
437   /* We're done reading sequentially through the file. */
438   cf->state = FILE_READ_DONE;
439
440   /* Close the sequential I/O side, to free up memory it requires. */
441   wtap_sequential_close(cf->wth);
442
443   /* Allow the protocol dissectors to free up memory that they
444    * don't need after the sequential run-through of the packets. */
445   postseq_cleanup_all_protocols();
446
447   /* Set the file encapsulation type now; we don't know what it is until
448      we've looked at all the packets, as we don't know until then whether
449      there's more than one type (and thus whether it's
450      WTAP_ENCAP_PER_PACKET). */
451   cf->lnk_t = wtap_file_encap(cf->wth);
452
453   cf->current_frame = cf->first_displayed;
454   thaw_plist(cf);
455
456   statusbar_pop_file_msg();
457   set_display_filename(cf);
458
459   /* Enable menu items that make sense if you have a capture file you've
460      finished reading. */
461   set_menus_for_capture_file(TRUE);
462   set_menus_for_unsaved_capture_file(!cf->user_saved);
463
464   /* Enable menu items that make sense if you have some captured packets. */
465   set_menus_for_captured_packets(TRUE);
466
467   /* If we have any displayed packets to select, select the first of those
468      packets by making the first row the selected row. */
469   if (cf->first_displayed != NULL)
470     packet_list_select_row(0);
471
472   if (*err != 0) {
473     /* Put up a message box noting that the read failed somewhere along
474        the line.  Don't throw out the stuff we managed to read, though,
475        if any. */
476     switch (*err) {
477
478     case WTAP_ERR_UNSUPPORTED_ENCAP:
479       errmsg = "The capture file is for a network type that Ethereal doesn't support.";
480       break;
481
482     case WTAP_ERR_CANT_READ:
483       errmsg = "An attempt to read from the file failed for"
484                " some unknown reason.";
485       break;
486
487     case WTAP_ERR_SHORT_READ:
488       errmsg = "The capture file appears to have been cut short"
489                " in the middle of a packet.";
490       break;
491
492     case WTAP_ERR_BAD_RECORD:
493       errmsg = "The capture file appears to be damaged or corrupt.";
494       break;
495
496     default:
497       snprintf(errmsg_errno, sizeof(errmsg_errno),
498                "An error occurred while reading the"
499                " capture file: %s.", wtap_strerror(*err));
500       errmsg = errmsg_errno;
501       break;
502     }
503     snprintf(err_str, sizeof err_str, errmsg);
504     simple_dialog(ESD_TYPE_CRIT, NULL, err_str);
505     return (READ_ERROR);
506   } else
507     return (READ_SUCCESS);
508 }
509
510 #ifdef HAVE_LIBPCAP
511 int
512 start_tail_cap_file(char *fname, gboolean is_tempfile, capture_file *cf)
513 {
514   int     err;
515   int     i;
516
517   err = open_cap_file(fname, is_tempfile, cf);
518   if (err == 0) {
519     /* Disable menu items that make no sense if you're currently running
520        a capture. */
521     set_menus_for_capture_in_progress(TRUE);
522
523     /* Enable menu items that make sense if you have some captured
524        packets (yes, I know, we don't have any *yet*). */
525     set_menus_for_captured_packets(TRUE);
526
527     for (i = 0; i < cf->cinfo.num_cols; i++) {
528       if (get_column_resize_type(cf->cinfo.col_fmt[i]) == RESIZE_LIVE)
529         packet_list_set_column_auto_resize(i, TRUE);
530       else {
531         packet_list_set_column_auto_resize(i, FALSE);
532         packet_list_set_column_width(i, cf->cinfo.col_width[i]);
533         packet_list_set_column_resizeable(i, TRUE);
534       }
535     }
536
537     statusbar_push_file_msg(" <live capture in progress>");
538   }
539   return err;
540 }
541
542 read_status_t
543 continue_tail_cap_file(capture_file *cf, int to_read, int *err)
544 {
545   long data_offset = 0;
546
547   *err = 0;
548
549   packet_list_freeze();
550
551   while (to_read != 0 && (wtap_read(cf->wth, err, &data_offset))) {
552     if (cf->state == FILE_READ_ABORTED) {
553       /* Well, the user decided to exit Ethereal.  Break out of the
554          loop, and let the code below (which is called even if there
555          aren't any packets left to read) exit. */
556       break;
557     }
558     read_packet(cf, data_offset);
559     to_read--;
560   }
561
562   packet_list_thaw();
563
564   /* XXX - this cheats and looks inside the packet list to find the final
565      row number. */
566   if (auto_scroll_live && cf->plist_end != NULL)
567     packet_list_moveto_end();
568
569   if (cf->state == FILE_READ_ABORTED) {
570     /* Well, the user decided to exit Ethereal.  Return READ_ABORTED
571        so that our caller can kill off the capture child process;
572        this will cause an EOF on the pipe from the child, so
573        "finish_tail_cap_file()" will be called, and it will clean up
574        and exit. */
575     return READ_ABORTED;
576   } else if (*err != 0) {
577     /* We got an error reading the capture file.
578        XXX - pop up a dialog box? */
579     return (READ_ERROR);
580   } else
581     return (READ_SUCCESS);
582 }
583
584 read_status_t
585 finish_tail_cap_file(capture_file *cf, int *err)
586 {
587   long data_offset;
588
589   packet_list_freeze();
590
591   while ((wtap_read(cf->wth, err, &data_offset))) {
592     if (cf->state == FILE_READ_ABORTED) {
593       /* Well, the user decided to abort the read.  Break out of the
594          loop, and let the code below (which is called even if there
595          aren't any packets left to read) exit. */
596       break;
597     }
598     read_packet(cf, data_offset);
599   }
600
601   if (cf->state == FILE_READ_ABORTED) {
602     /* Well, the user decided to abort the read.  We're only called
603        when the child capture process closes the pipe to us (meaning
604        it's probably exited), so we can just close the capture
605        file; we return READ_ABORTED so our caller can do whatever
606        is appropriate when that happens. */
607     close_cap_file(cf);
608     return READ_ABORTED;
609   }
610
611   thaw_plist(cf);
612   if (auto_scroll_live && cf->plist_end != NULL)
613     /* XXX - this cheats and looks inside the packet list to find the final
614        row number. */
615     packet_list_moveto_end();
616
617   /* We're done reading sequentially through the file. */
618   cf->state = FILE_READ_DONE;
619
620   /* We're done reading sequentially through the file; close the
621      sequential I/O side, to free up memory it requires. */
622   wtap_sequential_close(cf->wth);
623
624   /* Allow the protocol dissectors to free up memory that they
625    * don't need after the sequential run-through of the packets. */
626   postseq_cleanup_all_protocols();
627
628   /* Set the file encapsulation type now; we don't know what it is until
629      we've looked at all the packets, as we don't know until then whether
630      there's more than one type (and thus whether it's
631      WTAP_ENCAP_PER_PACKET). */
632   cf->lnk_t = wtap_file_encap(cf->wth);
633
634   /* Pop the "<live capture in progress>" message off the status bar. */
635   statusbar_pop_file_msg();
636
637   set_display_filename(cf);
638
639   /* Enable menu items that make sense if you're not currently running
640      a capture. */
641   set_menus_for_capture_in_progress(FALSE);
642
643   /* Enable menu items that make sense if you have a capture file
644      you've finished reading. */
645   set_menus_for_capture_file(TRUE);
646   set_menus_for_unsaved_capture_file(!cf->user_saved);
647
648   if (*err != 0) {
649     /* We got an error reading the capture file.
650        XXX - pop up a dialog box? */
651     return (READ_ERROR);
652   } else
653     return (READ_SUCCESS);
654 }
655 #endif /* HAVE_LIBPCAP */
656
657 typedef struct {
658   color_filter_t *colorf;
659   epan_dissect_t *edt;
660 } apply_color_filter_args;
661
662 /*
663  * If no color filter has been applied, apply this one.
664  * (The "if no color filter has been applied" is to handle the case where
665  * more than one color filter matches the packet.)
666  */
667 static void
668 apply_color_filter(gpointer filter_arg, gpointer argp)
669 {
670   color_filter_t *colorf = filter_arg;
671   apply_color_filter_args *args = argp;
672
673   if (colorf->c_colorfilter != NULL && args->colorf == NULL) {
674     if (dfilter_apply_edt(colorf->c_colorfilter, args->edt))
675       args->colorf = colorf;
676   }
677 }
678
679 static int
680 add_packet_to_packet_list(frame_data *fdata, capture_file *cf,
681         union wtap_pseudo_header *pseudo_header, const guchar *buf,
682         gboolean refilter)
683 {
684   apply_color_filter_args args;
685   gint          row;
686   gboolean      create_proto_tree = FALSE;
687   epan_dissect_t *edt;
688
689   /* We don't yet have a color filter to apply. */
690   args.colorf = NULL;
691
692   /* If we don't have the time stamp of the first packet in the
693      capture, it's because this is the first packet.  Save the time
694      stamp of this packet as the time stamp of the first packet. */
695   if (!firstsec && !firstusec) {
696     firstsec  = fdata->abs_secs;
697     firstusec = fdata->abs_usecs;
698   }
699
700   /* If we don't have the time stamp of the previous displayed packet,
701      it's because this is the first displayed packet.  Save the time
702      stamp of this packet as the time stamp of the previous displayed
703      packet. */
704   if (!prevsec && !prevusec) {
705     prevsec  = fdata->abs_secs;
706     prevusec = fdata->abs_usecs;
707   }
708
709   /* Get the time elapsed between the first packet and this packet. */
710   compute_timestamp_diff(&fdata->rel_secs, &fdata->rel_usecs,
711      fdata->abs_secs, fdata->abs_usecs, firstsec, firstusec);
712
713   /* If it's greater than the current elapsed time, set the elapsed time
714      to it (we check for "greater than" so as not to be confused by
715      time moving backwards). */
716   if ((gint32)cf->esec < fdata->rel_secs
717   || ((gint32)cf->esec == fdata->rel_secs && (gint32)cf->eusec < fdata->rel_usecs)) {
718     cf->esec = fdata->rel_secs;
719     cf->eusec = fdata->rel_usecs;
720   }
721
722   /* Get the time elapsed between the previous displayed packet and
723      this packet. */
724   compute_timestamp_diff(&fdata->del_secs, &fdata->del_usecs,
725         fdata->abs_secs, fdata->abs_usecs, prevsec, prevusec);
726
727   /* If either
728
729         we have a display filter and are re-applying it;
730
731         we have a list of color filters;
732
733         we have tap listeners;
734
735      allocate a protocol tree root node, so that we'll construct
736      a protocol tree against which a filter expression can be
737      evaluated. */
738   if ((cf->dfcode != NULL && refilter) || filter_list != NULL
739         || num_tap_filters != 0)
740           create_proto_tree = TRUE;
741
742   /* Dissect the frame. */
743   edt = epan_dissect_new(create_proto_tree, FALSE);
744
745   if (cf->dfcode != NULL && refilter) {
746       epan_dissect_prime_dfilter(edt, cf->dfcode);
747   }
748   if (filter_list) {
749       filter_list_prime_edt(edt);
750   }
751   tap_queue_init(edt);
752   epan_dissect_run(edt, pseudo_header, buf, fdata, &cf->cinfo);
753   tap_push_tapped_queue(edt);
754
755   /* If we have a display filter, apply it if we're refiltering, otherwise
756      leave the "passed_dfilter" flag alone.
757
758      If we don't have a display filter, set "passed_dfilter" to 1. */
759   if (cf->dfcode != NULL) {
760     if (refilter) {
761       if (cf->dfcode != NULL)
762         fdata->flags.passed_dfilter = dfilter_apply_edt(cf->dfcode, edt) ? 1 : 0;
763       else
764         fdata->flags.passed_dfilter = 1;
765     }
766   } else
767     fdata->flags.passed_dfilter = 1;
768
769   /* If we have color filters, and the frame is to be displayed, apply
770      the color filters. */
771   if (fdata->flags.passed_dfilter) {
772     if (filter_list != NULL) {
773       args.edt = edt;
774       g_slist_foreach(filter_list, apply_color_filter, &args);
775     }
776   }
777
778
779   if (fdata->flags.passed_dfilter) {
780     /* This frame passed the display filter, so add it to the clist. */
781
782     epan_dissect_fill_in_columns(edt);
783
784     /* If we haven't yet seen the first frame, this is it.
785
786        XXX - we must do this before we add the row to the display,
787        as, if the display's GtkCList's selection mode is
788        GTK_SELECTION_BROWSE, when the first entry is added to it,
789        "select_packet()" will be called, and it will fetch the row
790        data for the 0th row, and will get a null pointer rather than
791        "fdata", as "gtk_clist_append()" won't yet have returned and
792        thus "gtk_clist_set_row_data()" won't yet have been called.
793
794        We thus need to leave behind bread crumbs so that
795        "select_packet()" can find this frame.  See the comment
796        in "select_packet()". */
797     if (cf->first_displayed == NULL)
798       cf->first_displayed = fdata;
799
800     /* This is the last frame we've seen so far. */
801     cf->last_displayed = fdata;
802
803     row = packet_list_append(cf->cinfo.col_data, fdata);
804
805     if (fdata->flags.marked) {
806         packet_list_set_colors(row, &prefs.gui_marked_fg, &prefs.gui_marked_bg);
807     } else if (filter_list != NULL && (args.colorf != NULL)) {
808         packet_list_set_colors(row, &args.colorf->fg_color,
809                                &args.colorf->bg_color);
810     }
811
812     /* Set the time of the previous displayed frame to the time of this
813        frame. */
814     prevsec = fdata->abs_secs;
815     prevusec = fdata->abs_usecs;
816   } else {
817     /* This frame didn't pass the display filter, so it's not being added
818        to the clist, and thus has no row. */
819     row = -1;
820   }
821   epan_dissect_free(edt);
822   return row;
823 }
824
825 static void
826 read_packet(capture_file *cf, long offset)
827 {
828   const struct wtap_pkthdr *phdr = wtap_phdr(cf->wth);
829   union wtap_pseudo_header *pseudo_header = wtap_pseudoheader(cf->wth);
830   const guchar *buf = wtap_buf_ptr(cf->wth);
831   frame_data   *fdata;
832   int           passed;
833   frame_data   *plist_end;
834   epan_dissect_t *edt;
835
836   /* Allocate the next list entry, and add it to the list. */
837   fdata = g_mem_chunk_alloc(cf->plist_chunk);
838
839   fdata->next = NULL;
840   fdata->prev = NULL;
841   fdata->pfd  = NULL;
842   fdata->pkt_len  = phdr->len;
843   cul_bytes += phdr->len;
844   fdata->cul_bytes  = cul_bytes;
845   fdata->cap_len  = phdr->caplen;
846   fdata->file_off = offset;
847   fdata->lnk_t = phdr->pkt_encap;
848   fdata->abs_secs  = phdr->ts.tv_sec;
849   fdata->abs_usecs = phdr->ts.tv_usec;
850   fdata->flags.encoding = CHAR_ASCII;
851   fdata->flags.visited = 0;
852   fdata->flags.marked = 0;
853
854   passed = TRUE;
855   if (cf->rfcode) {
856     edt = epan_dissect_new(TRUE, FALSE);
857     epan_dissect_prime_dfilter(edt, cf->rfcode);
858     epan_dissect_run(edt, pseudo_header, buf, fdata, NULL);
859     passed = dfilter_apply_edt(cf->rfcode, edt);
860     epan_dissect_free(edt);
861   }
862   if (passed) {
863     plist_end = cf->plist_end;
864     fdata->prev = plist_end;
865     if (plist_end != NULL)
866       plist_end->next = fdata;
867     else
868       cf->plist = fdata;
869     cf->plist_end = fdata;
870
871     cf->count++;
872     fdata->num = cf->count;
873     add_packet_to_packet_list(fdata, cf, pseudo_header, buf, TRUE);
874   } else {
875     /* XXX - if we didn't have read filters, or if we could avoid
876        allocating the "frame_data" structure until we knew whether
877        the frame passed the read filter, we could use a G_ALLOC_ONLY
878        memory chunk...
879
880        ...but, at least in one test I did, where I just made the chunk
881        a G_ALLOC_ONLY chunk and read in a huge capture file, it didn't
882        seem to save a noticeable amount of time or space. */
883     g_mem_chunk_free(cf->plist_chunk, fdata);
884   }
885 }
886
887 int
888 filter_packets(capture_file *cf, gchar *dftext)
889 {
890   dfilter_t *dfcode;
891
892   if (dftext == NULL) {
893     /* The new filter is an empty filter (i.e., display all packets). */
894     dfcode = NULL;
895   } else {
896     /*
897      * We have a filter; make a copy of it (as we'll be saving it),
898      * and try to compile it.
899      */
900     dftext = g_strdup(dftext);
901     if (!dfilter_compile(dftext, &dfcode)) {
902       /* The attempt failed; report an error. */
903       simple_dialog(ESD_TYPE_CRIT, NULL, dfilter_error_msg);
904       return 0;
905     }
906
907     /* Was it empty? */
908     if (dfcode == NULL) {
909       /* Yes - free the filter text, and set it to null. */
910       g_free(dftext);
911       dftext = NULL;
912     }
913   }
914
915   /* We have a valid filter.  Replace the current filter. */
916   if (cf->dfilter != NULL)
917     g_free(cf->dfilter);
918   cf->dfilter = dftext;
919   if (cf->dfcode != NULL)
920     dfilter_free(cf->dfcode);
921   cf->dfcode = dfcode;
922
923   /* Now rescan the packet list, applying the new filter, but not
924      throwing away information constructed on a previous pass. */
925   if (dftext == NULL) {
926     rescan_packets(cf, "Resetting", "Filter", TRUE, FALSE);
927   } else {
928     rescan_packets(cf, "Filtering", dftext, TRUE, FALSE);
929   }
930   return 1;
931 }
932
933 void
934 colorize_packets(capture_file *cf)
935 {
936   rescan_packets(cf, "Colorizing", "all frames", FALSE, FALSE);
937 }
938
939 void
940 redissect_packets(capture_file *cf)
941 {
942   rescan_packets(cf, "Reprocessing", "all frames", TRUE, TRUE);
943 }
944
945 /* Rescan the list of packets, reconstructing the CList.
946
947    "action" describes why we're doing this; it's used in the progress
948    dialog box.
949
950    "action_item" describes what we're doing; it's used in the progress
951    dialog box.
952
953    "refilter" is TRUE if we need to re-evaluate the filter expression.
954
955    "redissect" is TRUE if we need to make the dissectors reconstruct
956    any state information they have (because a preference that affects
957    some dissector has changed, meaning some dissector might construct
958    its state differently from the way it was constructed the last time). */
959 static void
960 rescan_packets(capture_file *cf, const char *action, const char *action_item,
961                 gboolean refilter, gboolean redissect)
962 {
963   frame_data *fdata;
964   progdlg_t  *progbar = NULL;
965   gboolean    stop_flag;
966   int         count;
967   int         err;
968   frame_data *selected_frame;
969   int         selected_row;
970   int         row;
971   float       prog_val;
972   GTimeVal    start_time;
973   gchar       status_str[100];
974
975   cul_bytes=0;
976   reset_tap_listeners();
977   /* Which frame, if any, is the currently selected frame?
978      XXX - should the selected frame or the focus frame be the "current"
979      frame, that frame being the one from which "Find Frame" searches
980      start? */
981   selected_frame = cf->current_frame;
982
983   /* We don't yet know what row that frame will be on, if any, after we
984      rebuild the clist, however. */
985   selected_row = -1;
986
987   if (redissect) {
988     /* We need to re-initialize all the state information that protocols
989        keep, because some preference that controls a dissector has changed,
990        which might cause the state information to be constructed differently
991        by that dissector. */
992
993     /* Initialize all data structures used for dissection. */
994     init_dissection();
995   }
996
997   /* Freeze the packet list while we redo it, so we don't get any
998      screen updates while it happens. */
999   packet_list_freeze();
1000
1001   /* Clear it out. */
1002   packet_list_clear();
1003
1004   /* We don't yet know which will be the first and last frames displayed. */
1005   cf->first_displayed = NULL;
1006   cf->last_displayed = NULL;
1007
1008   /* Iterate through the list of frames.  Call a routine for each frame
1009      to check whether it should be displayed and, if so, add it to
1010      the display list. */
1011   firstsec = 0;
1012   firstusec = 0;
1013   prevsec = 0;
1014   prevusec = 0;
1015
1016   /* Update the progress bar when it gets to this value. */
1017   cf->progbar_nextstep = 0;
1018   /* When we reach the value that triggers a progress bar update,
1019      bump that value by this amount. */
1020   cf->progbar_quantum = cf->count/N_PROGBAR_UPDATES;
1021   /* Count of packets at which we've looked. */
1022   count = 0;
1023
1024   stop_flag = FALSE;
1025   g_get_current_time(&start_time);
1026
1027   for (fdata = cf->plist; fdata != NULL; fdata = fdata->next) {
1028     /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
1029        when we update it, we have to run the GTK+ main loop to get it
1030        to repaint what's pending, and doing so may involve an "ioctl()"
1031        to see if there's any pending input from an X server, and doing
1032        that for every packet can be costly, especially on a big file. */
1033     if (count >= cf->progbar_nextstep) {
1034       /* let's not divide by zero. I should never be started
1035        * with count == 0, so let's assert that
1036        */
1037       g_assert(cf->count > 0);
1038       prog_val = (gfloat) count / cf->count;
1039
1040       if (progbar == NULL)
1041         /* Create the progress bar if necessary */
1042         progbar = delayed_create_progress_dlg(action, action_item, "Stop", &stop_flag,
1043           &start_time, prog_val);
1044
1045       if (progbar != NULL) {
1046         g_snprintf(status_str, sizeof(status_str),
1047                   "%4u of %u frames", count, cf->count);
1048         update_progress_dlg(progbar, prog_val, status_str);
1049       }
1050
1051       cf->progbar_nextstep += cf->progbar_quantum;
1052     }
1053
1054     if (stop_flag) {
1055       /* Well, the user decided to abort the filtering.  Just stop.
1056
1057          XXX - go back to the previous filter?  Users probably just
1058          want not to wait for a filtering operation to finish;
1059          unless we cancel by having no filter, reverting to the
1060          previous filter will probably be even more expensive than
1061          continuing the filtering, as it involves going back to the
1062          beginning and filtering, and even with no filter we currently
1063          have to re-generate the entire clist, which is also expensive.
1064
1065          I'm not sure what Network Monitor does, but it doesn't appear
1066          to give you an unfiltered display if you cancel. */
1067       break;
1068     }
1069
1070     count++;
1071
1072     if (redissect) {
1073       /* Since all state for the frame was destroyed, mark the frame
1074        * as not visited, free the GSList referring to the state
1075        * data (the per-frame data itself was freed by
1076        * "init_dissection()"), and null out the GSList pointer. */
1077       fdata->flags.visited = 0;
1078       if (fdata->pfd) {
1079         g_slist_free(fdata->pfd);
1080         fdata->pfd = NULL;
1081       }
1082     }
1083
1084     if (!wtap_seek_read (cf->wth, fdata->file_off, &cf->pseudo_header,
1085         cf->pd, fdata->cap_len, &err)) {
1086         simple_dialog(ESD_TYPE_CRIT, NULL,
1087                       file_read_error_message(err), cf->filename);
1088         break;
1089     }
1090
1091     row = add_packet_to_packet_list(fdata, cf, &cf->pseudo_header, cf->pd,
1092                                         refilter);
1093     if (fdata == selected_frame)
1094       selected_row = row;
1095   }
1096
1097   if (redissect) {
1098     /* Clear out what remains of the visited flags and per-frame data
1099        pointers.
1100
1101        XXX - that may cause various forms of bogosity when dissecting
1102        these frames, as they won't have been seen by this sequential
1103        pass, but the only alternative I see is to keep scanning them
1104        even though the user requested that the scan stop, and that
1105        would leave the user stuck with an Ethereal grinding on
1106        until it finishes.  Should we just stick them with that? */
1107     for (; fdata != NULL; fdata = fdata->next) {
1108       fdata->flags.visited = 0;
1109       if (fdata->pfd) {
1110         g_slist_free(fdata->pfd);
1111         fdata->pfd = NULL;
1112       }
1113     }
1114   }
1115
1116   /* We're done filtering the packets; destroy the progress bar if it
1117      was created. */
1118   if (progbar != NULL)
1119     destroy_progress_dlg(progbar);
1120
1121   /* Unfreeze the packet list. */
1122   packet_list_thaw();
1123
1124   if (selected_row != -1) {
1125     /* The frame that was selected passed the filter; select it, make it
1126        the focus row, and make it visible. */
1127     packet_list_set_selected_row(selected_row);
1128     finfo_selected = NULL;
1129   } else {
1130     /* The selected frame didn't pass the filter; make the first frame
1131        the current frame, and leave it unselected. */
1132     unselect_packet(cf);
1133     cf->current_frame = cf->first_displayed;
1134   }
1135 }
1136
1137 int
1138 print_packets(capture_file *cf, print_args_t *print_args)
1139 {
1140   int         i;
1141   frame_data *fdata;
1142   progdlg_t  *progbar = NULL;
1143   gboolean    stop_flag;
1144   int         count;
1145   int         err;
1146   gint       *col_widths = NULL;
1147   gint        data_width;
1148   gboolean    print_separator;
1149   char       *line_buf = NULL;
1150   int         line_buf_len = 256;
1151   char        *cp;
1152   int         cp_off;
1153   int         column_len;
1154   int         line_len;
1155   epan_dissect_t *edt = NULL;
1156   float       prog_val;
1157   GTimeVal    start_time;
1158   gchar       status_str[100];
1159
1160   cf->print_fh = open_print_dest(print_args->to_file, print_args->dest);
1161   if (cf->print_fh == NULL)
1162     return FALSE;       /* attempt to open destination failed */
1163
1164   print_preamble(cf->print_fh, print_args->format);
1165
1166   if (print_args->print_summary) {
1167     /* We're printing packet summaries.  Allocate the line buffer at
1168        its initial length. */
1169     line_buf = g_malloc(line_buf_len + 1);
1170
1171     /* Find the widths for each of the columns - maximum of the
1172        width of the title and the width of the data - and print
1173        the column titles. */
1174     col_widths = (gint *) g_malloc(sizeof(gint) * cf->cinfo.num_cols);
1175     cp = &line_buf[0];
1176     line_len = 0;
1177     for (i = 0; i < cf->cinfo.num_cols; i++) {
1178       /* Don't pad the last column. */
1179       if (i == cf->cinfo.num_cols - 1)
1180         col_widths[i] = 0;
1181       else {
1182         col_widths[i] = strlen(cf->cinfo.col_title[i]);
1183         data_width = get_column_char_width(get_column_format(i));
1184         if (data_width > col_widths[i])
1185           col_widths[i] = data_width;
1186       }
1187
1188       /* Find the length of the string for this column. */
1189       column_len = strlen(cf->cinfo.col_title[i]);
1190       if (col_widths[i] > column_len)
1191         column_len = col_widths[i];
1192
1193       /* Make sure there's room in the line buffer for the column; if not,
1194          double its length. */
1195       line_len += column_len + 1;       /* "+1" for space */
1196       if (line_len > line_buf_len) {
1197         cp_off = cp - line_buf;
1198         line_buf_len = 2 * line_len;
1199         line_buf = g_realloc(line_buf, line_buf_len + 1);
1200         cp = line_buf + cp_off;
1201       }
1202
1203       /* Right-justify the packet number column. */
1204       if (cf->cinfo.col_fmt[i] == COL_NUMBER)
1205         sprintf(cp, "%*s", col_widths[i], cf->cinfo.col_title[i]);
1206       else
1207         sprintf(cp, "%-*s", col_widths[i], cf->cinfo.col_title[i]);
1208       cp += column_len;
1209       if (i != cf->cinfo.num_cols - 1)
1210         *cp++ = ' ';
1211     }
1212     *cp = '\0';
1213     print_line(cf->print_fh, 0, print_args->format, line_buf);
1214   }
1215
1216   print_separator = FALSE;
1217
1218   /* Update the progress bar when it gets to this value. */
1219   cf->progbar_nextstep = 0;
1220   /* When we reach the value that triggers a progress bar update,
1221      bump that value by this amount. */
1222   cf->progbar_quantum = cf->count/N_PROGBAR_UPDATES;
1223   /* Count of packets at which we've looked. */
1224   count = 0;
1225
1226   stop_flag = FALSE;
1227   g_get_current_time(&start_time);
1228
1229   /* Iterate through the list of packets, printing the packets that
1230      were selected by the current display filter.  */
1231   for (fdata = cf->plist; fdata != NULL; fdata = fdata->next) {
1232     /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
1233        when we update it, we have to run the GTK+ main loop to get it
1234        to repaint what's pending, and doing so may involve an "ioctl()"
1235        to see if there's any pending input from an X server, and doing
1236        that for every packet can be costly, especially on a big file. */
1237     if (count >= cf->progbar_nextstep) {
1238       /* let's not divide by zero. I should never be started
1239        * with count == 0, so let's assert that
1240        */
1241       g_assert(cf->count > 0);
1242       prog_val = (gfloat) count / cf->count;
1243
1244       if (progbar == NULL)
1245         /* Create the progress bar if necessary */
1246         progbar = delayed_create_progress_dlg("Printing", "selected frames", "Stop", &stop_flag,
1247           &start_time, prog_val);
1248
1249       if (progbar != NULL) {
1250         g_snprintf(status_str, sizeof(status_str),
1251                    "%4u of %u frames", count, cf->count);
1252         update_progress_dlg(progbar, prog_val, status_str);
1253       }
1254
1255       cf->progbar_nextstep += cf->progbar_quantum;
1256     }
1257
1258     if (stop_flag) {
1259       /* Well, the user decided to abort the printing.  Just stop.
1260
1261          XXX - note that what got generated before they did that
1262          will get printed, as we're piping to a print program; we'd
1263          have to write to a file and then hand that to the print
1264          program to make it actually not print anything. */
1265       break;
1266     }
1267
1268     count++;
1269     /* Check to see if we are suppressing unmarked packets, if so,
1270      * suppress them and then proceed to check for visibility.
1271      */
1272     if (((print_args->suppress_unmarked && fdata->flags.marked ) ||
1273         !(print_args->suppress_unmarked)) && fdata->flags.passed_dfilter) {
1274       if (!wtap_seek_read (cf->wth, fdata->file_off, &cf->pseudo_header,
1275                            cf->pd, fdata->cap_len, &err)) {
1276         simple_dialog(ESD_TYPE_CRIT, NULL,
1277                       file_read_error_message(err), cf->filename);
1278         break;
1279       }
1280       if (print_args->print_summary) {
1281         /* Fill in the column information, but don't bother creating
1282            the logical protocol tree. */
1283         edt = epan_dissect_new(FALSE, FALSE);
1284         epan_dissect_run(edt, &cf->pseudo_header, cf->pd, fdata, &cf->cinfo);
1285         epan_dissect_fill_in_columns(edt);
1286         cp = &line_buf[0];
1287         line_len = 0;
1288         for (i = 0; i < cf->cinfo.num_cols; i++) {
1289           /* Find the length of the string for this column. */
1290           column_len = strlen(cf->cinfo.col_data[i]);
1291           if (col_widths[i] > column_len)
1292             column_len = col_widths[i];
1293
1294           /* Make sure there's room in the line buffer for the column; if not,
1295              double its length. */
1296           line_len += column_len + 1;   /* "+1" for space */
1297           if (line_len > line_buf_len) {
1298             cp_off = cp - line_buf;
1299             line_buf_len = 2 * line_len;
1300             line_buf = g_realloc(line_buf, line_buf_len + 1);
1301             cp = line_buf + cp_off;
1302           }
1303
1304           /* Right-justify the packet number column. */
1305           if (cf->cinfo.col_fmt[i] == COL_NUMBER)
1306             sprintf(cp, "%*s", col_widths[i], cf->cinfo.col_data[i]);
1307           else
1308             sprintf(cp, "%-*s", col_widths[i], cf->cinfo.col_data[i]);
1309           cp += column_len;
1310           if (i != cf->cinfo.num_cols - 1)
1311             *cp++ = ' ';
1312         }
1313         *cp = '\0';
1314         print_line(cf->print_fh, 0, print_args->format, line_buf);
1315       } else {
1316         if (print_separator)
1317           print_line(cf->print_fh, 0, print_args->format, "");
1318
1319         /* Create the logical protocol tree, complete with the display
1320            representation of the items; we don't need the columns here,
1321            however. */
1322         edt = epan_dissect_new(TRUE, TRUE);
1323         epan_dissect_run(edt, &cf->pseudo_header, cf->pd, fdata, NULL);
1324
1325         /* Print the information in that tree. */
1326         proto_tree_print(print_args, edt, cf->print_fh);
1327
1328         if (print_args->print_hex) {
1329           /* Print the full packet data as hex. */
1330           print_hex_data(cf->print_fh, print_args->format, edt);
1331         }
1332
1333         /* Print a blank line if we print anything after this. */
1334         print_separator = TRUE;
1335       }
1336       epan_dissect_free(edt);
1337     }
1338   }
1339
1340   /* We're done printing the packets; destroy the progress bar if
1341      it was created. */
1342   if (progbar != NULL)
1343     destroy_progress_dlg(progbar);
1344
1345   if (col_widths != NULL)
1346     g_free(col_widths);
1347   if (line_buf != NULL)
1348     g_free(line_buf);
1349
1350   print_finale(cf->print_fh, print_args->format);
1351
1352   close_print_dest(print_args->to_file, cf->print_fh);
1353
1354   cf->print_fh = NULL;
1355
1356   return TRUE;
1357 }
1358
1359 /* Scan through the packet list and change all columns that use the
1360    "command-line-specified" time stamp format to use the current
1361    value of that format. */
1362 void
1363 change_time_formats(capture_file *cf)
1364 {
1365   frame_data *fdata;
1366   progdlg_t  *progbar = NULL;
1367   gboolean    stop_flag;
1368   int         count;
1369   int         row;
1370   int         i;
1371   float       prog_val;
1372   GTimeVal    start_time;
1373   gchar       status_str[100];
1374
1375   /* Are there any columns with time stamps in the "command-line-specified"
1376      format?
1377
1378      XXX - we have to force the "column is writable" flag on, as it
1379      might be off from the last frame that was dissected. */
1380   col_set_writable(&cf->cinfo, TRUE);
1381   if (!check_col(&cf->cinfo, COL_CLS_TIME)) {
1382     /* No, there aren't any columns in that format, so we have no work
1383        to do. */
1384     return;
1385   }
1386
1387   /* Freeze the packet list while we redo it, so we don't get any
1388      screen updates while it happens. */
1389   freeze_plist(cf);
1390
1391   /* Update the progress bar when it gets to this value. */
1392   cf->progbar_nextstep = 0;
1393   /* When we reach the value that triggers a progress bar update,
1394      bump that value by this amount. */
1395   cf->progbar_quantum = cf->count/N_PROGBAR_UPDATES;
1396   /* Count of packets at which we've looked. */
1397   count = 0;
1398
1399   stop_flag = FALSE;
1400   g_get_current_time(&start_time);
1401
1402   /* Iterate through the list of packets, checking whether the packet
1403      is in a row of the summary list and, if so, whether there are
1404      any columns that show the time in the "command-line-specified"
1405      format and, if so, update that row. */
1406   for (fdata = cf->plist; fdata != NULL; fdata = fdata->next) {
1407     /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
1408        when we update it, we have to run the GTK+ main loop to get it
1409        to repaint what's pending, and doing so may involve an "ioctl()"
1410        to see if there's any pending input from an X server, and doing
1411        that for every packet can be costly, especially on a big file. */
1412     if (count >= cf->progbar_nextstep) {
1413       /* let's not divide by zero. I should never be started
1414        * with count == 0, so let's assert that
1415        */
1416       g_assert(cf->count > 0);
1417
1418       prog_val = (gfloat) count / cf->count;
1419
1420       if (progbar == NULL)
1421         /* Create the progress bar if necessary */
1422         progbar = delayed_create_progress_dlg("Changing", "time display", "Stop",
1423           &stop_flag, &start_time, prog_val);
1424
1425       if (progbar != NULL) {
1426         g_snprintf(status_str, sizeof(status_str),
1427                    "%4u of %u frames", count, cf->count);
1428         update_progress_dlg(progbar, prog_val, status_str);
1429       }
1430
1431       cf->progbar_nextstep += cf->progbar_quantum;
1432     }
1433
1434     if (stop_flag) {
1435       /* Well, the user decided to abort the redisplay.  Just stop.
1436
1437          XXX - this leaves the time field in the old format in
1438          frames we haven't yet processed.  So it goes; should we
1439          simply not offer them the option of stopping? */
1440       break;
1441     }
1442
1443     count++;
1444
1445     /* Find what row this packet is in. */
1446     row = packet_list_find_row_from_data(fdata);
1447
1448     if (row != -1) {
1449       /* This packet is in the summary list, on row "row". */
1450
1451       for (i = 0; i < cf->cinfo.num_cols; i++) {
1452         if (cf->cinfo.fmt_matx[i][COL_CLS_TIME]) {
1453           /* This is one of the columns that shows the time in
1454              "command-line-specified" format; update it. */
1455           cf->cinfo.col_buf[i][0] = '\0';
1456           col_set_cls_time(fdata, &cf->cinfo, i);
1457           packet_list_set_text(row, i, cf->cinfo.col_data[i]);
1458         }
1459       }
1460     }
1461   }
1462
1463   /* We're done redisplaying the packets; destroy the progress bar if it
1464      was created. */
1465   if (progbar != NULL)
1466     destroy_progress_dlg(progbar);
1467
1468   /* Set the column widths of those columns that show the time in
1469      "command-line-specified" format. */
1470   for (i = 0; i < cf->cinfo.num_cols; i++) {
1471     if (cf->cinfo.fmt_matx[i][COL_CLS_TIME]) {
1472       packet_list_set_cls_time_width(i);
1473     }
1474   }
1475
1476   /* Unfreeze the packet list. */
1477   thaw_plist(cf);
1478 }
1479
1480 typedef struct {
1481         const char      *string;
1482         size_t          string_len;
1483         capture_file    *cf;
1484         gboolean        frame_matched;
1485 } match_data;
1486
1487 gboolean
1488 find_packet_protocol_tree(capture_file *cf, const char *string)
1489 {
1490   match_data            mdata;
1491
1492   mdata.string = string;
1493   mdata.string_len = strlen(string);
1494   return find_packet(cf, match_protocol_tree, &mdata);
1495 }
1496
1497 static gboolean
1498 match_protocol_tree(capture_file *cf, frame_data *fdata, void *criterion)
1499 {
1500   match_data            *mdata = criterion;
1501   epan_dissect_t        *edt;
1502
1503   /* Construct the protocol tree, including the displayed text */
1504   edt = epan_dissect_new(TRUE, TRUE);
1505   /* We don't need the column information */
1506   epan_dissect_run(edt, &cf->pseudo_header, cf->pd, fdata, NULL);
1507
1508   /* Iterate through all the nodes, seeing if they have text that matches. */
1509   mdata->cf = cf;
1510   mdata->frame_matched = FALSE;
1511   g_node_children_foreach((GNode*) edt->tree, G_TRAVERSE_ALL,
1512                           match_subtree_text, mdata);
1513   epan_dissect_free(edt);
1514   return mdata->frame_matched;
1515 }
1516
1517 static void
1518 match_subtree_text(GNode *node, gpointer data)
1519 {
1520   match_data    *mdata = (match_data*) data;
1521   const gchar   *string = mdata->string;
1522   size_t        string_len = mdata->string_len;
1523   capture_file  *cf = mdata->cf;
1524   field_info    *fi = PITEM_FINFO(node);
1525   gchar         label_str[ITEM_LABEL_LENGTH];
1526   gchar         *label_ptr;
1527   size_t        label_len;
1528   guint32       i;
1529   guint8        c_char;
1530   size_t        c_match = 0;
1531
1532   if (mdata->frame_matched) {
1533     /* We already had a match; don't bother doing any more work. */
1534     return;
1535   }
1536
1537   /* Don't match invisible entries. */
1538   if (!fi->visible)
1539     return;
1540
1541   /* was a free format label produced? */
1542   if (fi->representation) {
1543     label_ptr = fi->representation;
1544   } else {
1545     /* no, make a generic label */
1546     label_ptr = label_str;
1547     proto_item_fill_label(fi, label_str);
1548   }
1549     
1550   /* Does that label match? */
1551   label_len = strlen(label_ptr);
1552   for (i = 0; i < label_len; i++) {
1553     c_char = label_ptr[i];
1554     if (cf->case_type)
1555       c_char = toupper(c_char);
1556     if (c_char == string[c_match]) {
1557       c_match++;
1558       if (c_match == string_len) {
1559         /* No need to look further; we have a match */
1560         mdata->frame_matched = TRUE;
1561         return;
1562       }
1563     } else
1564       c_match = 0;
1565   }
1566   
1567   /* Recurse into the subtree, if it exists */
1568   if (g_node_n_children(node) > 0)
1569     g_node_children_foreach(node, G_TRAVERSE_ALL, match_subtree_text, mdata);
1570 }
1571
1572 gboolean
1573 find_packet_summary_line(capture_file *cf, const char *string)
1574 {
1575   match_data            mdata;
1576
1577   mdata.string = string;
1578   mdata.string_len = strlen(string);
1579   return find_packet(cf, match_summary_line, &mdata);
1580 }
1581
1582 static gboolean
1583 match_summary_line(capture_file *cf, frame_data *fdata, void *criterion)
1584 {
1585   match_data            *mdata = criterion;
1586   const gchar           *string = mdata->string;
1587   size_t                string_len = mdata->string_len;
1588   epan_dissect_t        *edt;
1589   const char            *info_column;
1590   size_t                info_column_len;
1591   gboolean              frame_matched = FALSE;
1592   gint                  colx;
1593   guint32               i;
1594   guint8                c_char;
1595   size_t                c_match = 0;
1596
1597   /* Don't bother constructing the protocol tree */
1598   edt = epan_dissect_new(FALSE, FALSE);
1599   /* Get the column information */
1600   epan_dissect_run(edt, &cf->pseudo_header, cf->pd, fdata, &cf->cinfo);
1601
1602   /* Find the Info column */
1603   for (colx = 0; colx < cf->cinfo.num_cols; colx++) {
1604     if (cf->cinfo.fmt_matx[colx][COL_INFO]) {
1605       /* Found it.  See if we match. */
1606       info_column = edt->pi.cinfo->col_data[colx];
1607       info_column_len = strlen(info_column);
1608       for (i = 0; i < info_column_len; i++) {
1609         c_char = info_column[i];
1610         if (cf->case_type)
1611           c_char = toupper(c_char);
1612         if (c_char == string[c_match]) {
1613           c_match++;
1614           if (c_match == string_len) {
1615             frame_matched = TRUE;
1616             break;
1617           }
1618         } else
1619           c_match = 0;
1620       }
1621       break;
1622     }
1623   }
1624   epan_dissect_free(edt);
1625   return frame_matched;
1626 }
1627
1628 typedef struct {
1629         const guint8 *data;
1630         size_t data_len;
1631 } cbs_t;        /* "Counted byte string" */
1632
1633 gboolean
1634 find_packet_data(capture_file *cf, const guint8 *string, size_t string_size)
1635 {
1636   cbs_t info;
1637
1638   info.data = string;
1639   info.data_len = string_size;
1640
1641   /* String or hex search? */
1642   if (cf->ascii) {
1643     /* String search - what type of string? */
1644     switch (cf->scs_type) {
1645
1646     case SCS_ASCII_AND_UNICODE:
1647       return find_packet(cf, match_ascii_and_unicode, &info);
1648
1649     case SCS_ASCII:
1650       return find_packet(cf, match_ascii, &info);
1651
1652     case SCS_UNICODE:
1653       return find_packet(cf, match_unicode, &info);
1654
1655     default:
1656       g_assert_not_reached();
1657       return FALSE;
1658     }
1659   } else
1660     return find_packet(cf, match_binary, &info);
1661 }
1662
1663 static gboolean
1664 match_ascii_and_unicode(capture_file *cf, frame_data *fdata, void *criterion)
1665 {
1666   cbs_t         *info = criterion;
1667   const char    *ascii_text = info->data;
1668   size_t        textlen = info->data_len;
1669   gboolean      frame_matched;
1670   guint32       buf_len;
1671   guint32       i;
1672   guint8        c_char;
1673   size_t        c_match = 0;
1674
1675   frame_matched = FALSE;
1676   buf_len = fdata->pkt_len;
1677   for (i = 0; i < buf_len; i++) {
1678     c_char = cf->pd[i];
1679     if (cf->case_type)
1680       c_char = toupper(c_char);
1681     if (c_char != 0) {
1682       if (c_char == ascii_text[c_match]) {
1683         c_match++;
1684         if (c_match == textlen) {
1685           frame_matched = TRUE;
1686           break;
1687         }
1688       } else
1689         c_match = 0;
1690     }
1691   }
1692   return frame_matched;
1693 }
1694
1695 static gboolean
1696 match_ascii(capture_file *cf, frame_data *fdata, void *criterion)
1697 {
1698   cbs_t         *info = criterion;
1699   const char    *ascii_text = info->data;
1700   size_t        textlen = info->data_len;
1701   gboolean      frame_matched;
1702   guint32       buf_len;
1703   guint32       i;
1704   guint8        c_char;
1705   size_t        c_match = 0;
1706
1707   frame_matched = FALSE;
1708   buf_len = fdata->pkt_len;
1709   for (i = 0; i < buf_len; i++) {
1710     c_char = cf->pd[i];
1711     if (cf->case_type)
1712       c_char = toupper(c_char);
1713     if (c_char == ascii_text[c_match]) {
1714       c_match++;
1715       if (c_match == textlen) {
1716         frame_matched = TRUE;
1717         break;
1718       }
1719     } else
1720       c_match = 0;
1721   }
1722   return frame_matched;
1723 }
1724
1725 static gboolean
1726 match_unicode(capture_file *cf, frame_data *fdata, void *criterion)
1727 {
1728   cbs_t         *info = criterion;
1729   const char    *ascii_text = info->data;
1730   size_t        textlen = info->data_len;
1731   gboolean      frame_matched;
1732   guint32       buf_len;
1733   guint32       i;
1734   guint8        c_char;
1735   size_t        c_match = 0;
1736
1737   frame_matched = FALSE;
1738   buf_len = fdata->pkt_len;
1739   for (i = 0; i < buf_len; i++) {
1740     c_char = cf->pd[i];
1741     if (cf->case_type)
1742       c_char = toupper(c_char);
1743     if (c_char == ascii_text[c_match]) {
1744       c_match++;
1745       i++;
1746       if (c_match == textlen) {
1747         frame_matched = TRUE;
1748         break;
1749       }
1750     } else
1751       c_match = 0;
1752   }
1753   return frame_matched;
1754 }
1755
1756 static gboolean
1757 match_binary(capture_file *cf, frame_data *fdata, void *criterion)
1758 {
1759   cbs_t         *info = criterion;
1760   const guint8  *binary_data = info->data;
1761   size_t        datalen = info->data_len;
1762   gboolean      frame_matched;
1763   guint32       buf_len;
1764   guint32       i;
1765   size_t        c_match = 0;
1766
1767   frame_matched = FALSE;
1768   buf_len = fdata->pkt_len;
1769   for (i = 0; i < buf_len; i++) {
1770     if (cf->pd[i] == binary_data[c_match]) {
1771       c_match++;
1772       if (c_match == datalen) {
1773         frame_matched = TRUE;
1774         break;
1775       }
1776     } else
1777       c_match = 0;
1778   }
1779   return frame_matched;
1780 }
1781
1782 gboolean
1783 find_packet_dfilter(capture_file *cf, dfilter_t *sfcode)
1784 {
1785   return find_packet(cf, match_dfilter, sfcode);
1786 }
1787
1788 static gboolean
1789 match_dfilter(capture_file *cf, frame_data *fdata, void *criterion)
1790 {
1791   dfilter_t             *sfcode = criterion;
1792   epan_dissect_t        *edt;
1793   gboolean              frame_matched;
1794
1795   edt = epan_dissect_new(TRUE, FALSE);
1796   epan_dissect_prime_dfilter(edt, sfcode);
1797   epan_dissect_run(edt, &cf->pseudo_header, cf->pd, fdata, NULL);
1798   frame_matched = dfilter_apply_edt(sfcode, edt);
1799   epan_dissect_free(edt);
1800   return frame_matched;
1801 }
1802
1803 static gboolean
1804 find_packet(capture_file *cf,
1805             gboolean (*match_function)(capture_file *, frame_data *, void *),
1806             void *criterion)
1807 {
1808   frame_data *start_fd;
1809   frame_data *fdata;
1810   frame_data *new_fd = NULL;
1811   progdlg_t  *progbar = NULL;
1812   gboolean    stop_flag;
1813   int         count;
1814   int         err;
1815   int         row;
1816   float       prog_val;
1817   GTimeVal    start_time;
1818   gchar       status_str[100];
1819
1820   start_fd = cf->current_frame;
1821   if (start_fd != NULL)  {
1822     /* Iterate through the list of packets, starting at the packet we've
1823        picked, calling a routine to run the filter on the packet, see if
1824        it matches, and stop if so.  */
1825     count = 0;
1826     fdata = start_fd;
1827
1828     cf->progbar_nextstep = 0;
1829     /* When we reach the value that triggers a progress bar update,
1830        bump that value by this amount. */
1831     cf->progbar_quantum = cf->count/N_PROGBAR_UPDATES;
1832
1833     stop_flag = FALSE;
1834     g_get_current_time(&start_time);
1835
1836     fdata = start_fd;
1837     for (;;) {
1838       /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
1839          when we update it, we have to run the GTK+ main loop to get it
1840          to repaint what's pending, and doing so may involve an "ioctl()"
1841          to see if there's any pending input from an X server, and doing
1842          that for every packet can be costly, especially on a big file. */
1843       if (count >= cf->progbar_nextstep) {
1844         /* let's not divide by zero. I should never be started
1845          * with count == 0, so let's assert that
1846          */
1847         g_assert(cf->count > 0);
1848
1849         prog_val = (gfloat) count / cf->count;
1850
1851         /* Create the progress bar if necessary */
1852         if (progbar == NULL)
1853            progbar = delayed_create_progress_dlg("Searching", cf->sfilter, "Cancel",
1854              &stop_flag, &start_time, prog_val);
1855
1856         if (progbar != NULL) {
1857           g_snprintf(status_str, sizeof(status_str),
1858                      "%4u of %u frames", count, cf->count);
1859           update_progress_dlg(progbar, prog_val, status_str);
1860         }
1861
1862         cf->progbar_nextstep += cf->progbar_quantum;
1863       }
1864
1865       if (stop_flag) {
1866         /* Well, the user decided to abort the search.  Go back to the
1867            frame where we started. */
1868         new_fd = start_fd;
1869         break;
1870       }
1871
1872       /* Go past the current frame. */
1873       if (cf->sbackward) {
1874         /* Go on to the previous frame. */
1875         fdata = fdata->prev;
1876         if (fdata == NULL)
1877           fdata = cf->plist_end;        /* wrap around */
1878       } else {
1879         /* Go on to the next frame. */
1880         fdata = fdata->next;
1881         if (fdata == NULL)
1882           fdata = cf->plist;    /* wrap around */
1883       }
1884
1885       count++;
1886
1887       /* Is this packet in the display? */
1888       if (fdata->flags.passed_dfilter) {
1889         /* Yes.  Load its data. */
1890         if (!wtap_seek_read(cf->wth, fdata->file_off, &cf->pseudo_header,
1891                         cf->pd, fdata->cap_len, &err)) {
1892           /* Read error.  Report the error, and go back to the frame
1893              where we started. */
1894           simple_dialog(ESD_TYPE_CRIT, NULL,
1895                         file_read_error_message(err), cf->filename);
1896           new_fd = start_fd;
1897           break;
1898         }
1899
1900         /* Does it match the search criterion? */
1901         if ((*match_function)(cf, fdata, criterion)) {
1902           new_fd = fdata;
1903           break;        /* found it! */
1904         }
1905       }
1906
1907       if (fdata == start_fd) {
1908         /* We're back to the frame we were on originally, and that frame
1909            doesn't match the search filter.  The search failed. */
1910         break;
1911       }
1912     }
1913
1914     /* We're done scanning the packets; destroy the progress bar if it
1915        was created. */
1916     if (progbar != NULL)
1917       destroy_progress_dlg(progbar);
1918   }
1919
1920   if (new_fd != NULL) {
1921     /* We found a frame.  Find what row it's in. */
1922     row = packet_list_find_row_from_data(new_fd);
1923     g_assert(row != -1);
1924
1925     /* Select that row, make it the focus row, and make it visible. */
1926     packet_list_set_selected_row(row);
1927     return TRUE;        /* success */
1928   } else
1929     return FALSE;       /* failure */
1930 }
1931
1932 gboolean
1933 goto_frame(capture_file *cf, guint fnumber)
1934 {
1935   frame_data *fdata;
1936   int row;
1937
1938   for (fdata = cf->plist; fdata != NULL && fdata->num < fnumber; fdata = fdata->next)
1939     ;
1940
1941   if (fdata == NULL) {
1942     /* we didn't find a frame with that frame number */
1943     simple_dialog(ESD_TYPE_CRIT, NULL,
1944                   "There is no frame with that frame number.");
1945     return FALSE;       /* we failed to go to that frame */
1946   }
1947   if (!fdata->flags.passed_dfilter) {
1948     /* that frame currently isn't displayed */
1949     /* XXX - add it to the set of displayed frames? */
1950     simple_dialog(ESD_TYPE_CRIT, NULL,
1951                   "That frame is not currently being displayed.");
1952     return FALSE;       /* we failed to go to that frame */
1953   }
1954
1955   /* We found that frame, and it's currently being displayed.
1956      Find what row it's in. */
1957   row = packet_list_find_row_from_data(fdata);
1958   g_assert(row != -1);
1959
1960   /* Select that row, make it the focus row, and make it visible. */
1961   packet_list_set_selected_row(row);
1962   return TRUE;  /* we got to that frame */
1963 }
1964
1965 /* Select the packet on a given row. */
1966 void
1967 select_packet(capture_file *cf, int row)
1968 {
1969   frame_data *fdata;
1970   int err;
1971
1972   /* Get the frame data struct pointer for this frame */
1973   fdata = (frame_data *)packet_list_get_row_data(row);
1974
1975   if (fdata == NULL) {
1976     /* XXX - if a GtkCList's selection mode is GTK_SELECTION_BROWSE, when
1977        the first entry is added to it by "real_insert_row()", that row
1978        is selected (see "real_insert_row()", in "gtk/gtkclist.c", in both
1979        our version and the vanilla GTK+ version).
1980
1981        This means that a "select-row" signal is emitted; this causes
1982        "packet_list_select_cb()" to be called, which causes "select_packet()"
1983        to be called.
1984
1985        "select_packet()" fetches, above, the data associated with the
1986        row that was selected; however, as "gtk_clist_append()", which
1987        called "real_insert_row()", hasn't yet returned, we haven't yet
1988        associated any data with that row, so we get back a null pointer.
1989
1990        We can't assume that there's only one frame in the frame list,
1991        either, as we may be filtering the display.
1992
1993        We therefore assume that, if "row" is 0, i.e. the first row
1994        is being selected, and "cf->first_displayed" equals
1995        "cf->last_displayed", i.e. there's only one frame being
1996        displayed, that frame is the frame we want.
1997
1998        This means we have to set "cf->first_displayed" and
1999        "cf->last_displayed" before adding the row to the
2000        GtkCList; see the comment in "add_packet_to_packet_list()". */
2001
2002        if (row == 0 && cf->first_displayed == cf->last_displayed)
2003          fdata = cf->first_displayed;
2004   }
2005
2006   /* Get the data in that frame. */
2007   if (!wtap_seek_read (cf->wth, fdata->file_off, &cf->pseudo_header,
2008                        cf->pd, fdata->cap_len, &err)) {
2009     simple_dialog(ESD_TYPE_CRIT, NULL,
2010                   file_read_error_message(err), cf->filename);
2011     return;
2012   }
2013
2014   /* Record that this frame is the current frame. */
2015   cf->current_frame = fdata;
2016
2017   /* Create the logical protocol tree. */
2018   if (cf->edt != NULL) {
2019     epan_dissect_free(cf->edt);
2020     cf->edt = NULL;
2021   }
2022   /* We don't need the columns here. */
2023   cf->edt = epan_dissect_new(TRUE, TRUE);
2024   epan_dissect_run(cf->edt, &cf->pseudo_header, cf->pd, cf->current_frame,
2025           NULL);
2026
2027   /* Display the GUI protocol tree and hex dump.
2028      XXX - why do we dump core if we call "proto_tree_draw()"
2029      before calling "add_byte_views()"? */
2030   add_main_byte_views(cf->edt);
2031   main_proto_tree_draw(cf->edt->tree);
2032
2033   /* A packet is selected. */
2034   set_menus_for_selected_packet(TRUE);
2035 }
2036
2037 /* Unselect the selected packet, if any. */
2038 void
2039 unselect_packet(capture_file *cf)
2040 {
2041   /* Destroy the epan_dissect_t for the unselected packet. */
2042   if (cf->edt != NULL) {
2043     epan_dissect_free(cf->edt);
2044     cf->edt = NULL;
2045   }
2046
2047   /* Clear out the display of that packet. */
2048   clear_tree_and_hex_views();
2049
2050   /* No packet is selected. */
2051   set_menus_for_selected_packet(FALSE);
2052
2053   /* No protocol tree means no selected field. */
2054   unselect_field();
2055 }
2056
2057 /* Unset the selected protocol tree field, if any. */
2058 void
2059 unselect_field(void)
2060 {
2061   statusbar_pop_field_msg();
2062   finfo_selected = NULL;
2063   set_menus_for_selected_tree_row(FALSE);
2064 }
2065
2066 /*
2067  * Mark a particular frame.
2068  */
2069 void
2070 mark_frame(capture_file *cf, frame_data *frame)
2071 {
2072   frame->flags.marked = TRUE;
2073   cf->marked_count++;
2074 }
2075
2076 /*
2077  * Unmark a particular frame.
2078  */
2079 void
2080 unmark_frame(capture_file *cf, frame_data *frame)
2081 {
2082   frame->flags.marked = FALSE;
2083   cf->marked_count--;
2084 }
2085
2086 static void
2087 freeze_plist(capture_file *cf)
2088 {
2089   int i;
2090
2091   /* Make the column sizes static, so they don't adjust while
2092      we're reading the capture file (freezing the clist doesn't
2093      seem to suffice). */
2094   for (i = 0; i < cf->cinfo.num_cols; i++)
2095     packet_list_set_column_auto_resize(i, FALSE);
2096   packet_list_freeze();
2097 }
2098
2099 static void
2100 thaw_plist(capture_file *cf)
2101 {
2102   int i;
2103
2104   for (i = 0; i < cf->cinfo.num_cols; i++) {
2105     if (get_column_resize_type(cf->cinfo.col_fmt[i]) == RESIZE_MANUAL) {
2106       /* Set this column's width to the appropriate value. */
2107       packet_list_set_column_width(i, cf->cinfo.col_width[i]);
2108     } else {
2109       /* Make this column's size dynamic, so that it adjusts to the
2110          appropriate size. */
2111       packet_list_set_column_auto_resize(i, TRUE);
2112     }
2113   }
2114   packet_list_thaw();
2115
2116   /* Hopefully, the columns have now gotten their appropriate sizes;
2117      make them resizeable - a column that auto-resizes cannot be
2118      resized by the user, and *vice versa*. */
2119   for (i = 0; i < cf->cinfo.num_cols; i++)
2120     packet_list_set_column_resizeable(i, TRUE);
2121 }
2122
2123 /*
2124  * Save a capture to a file, in a particular format, saving either
2125  * all packets, all currently-displayed packets, or all marked packets.
2126  *
2127  * Returns TRUE if it succeeds, FALSE otherwise; if it fails, it pops
2128  * up a message box for the failure.
2129  */
2130 gboolean
2131 save_cap_file(char *fname, capture_file *cf, gboolean save_filtered,
2132                 gboolean save_marked, guint save_format)
2133 {
2134   gchar        *from_filename;
2135   gchar        *name_ptr, *save_msg, *save_fmt = " Saving: %s...";
2136   size_t        msg_len;
2137   int           err;
2138   gboolean      do_copy;
2139   wtap_dumper  *pdh;
2140   frame_data   *fdata;
2141   struct wtap_pkthdr hdr;
2142   union wtap_pseudo_header pseudo_header;
2143   guint8        pd[65536];
2144   struct stat   infile, outfile;
2145
2146   name_ptr = get_basename(fname);
2147   msg_len = strlen(name_ptr) + strlen(save_fmt) + 2;
2148   save_msg = g_malloc(msg_len);
2149   snprintf(save_msg, msg_len, save_fmt, name_ptr);
2150   statusbar_push_file_msg(save_msg);
2151   g_free(save_msg);
2152
2153   /*
2154    * Check that the from file is not the same as to file
2155    * We do it here so we catch all cases ...
2156    * Unfortunately, the file requester gives us an absolute file
2157    * name and the read file name may be relative (if supplied on
2158    * the command line). From Joerg Mayer.
2159    */
2160    infile.st_ino = 1;   /* These prevent us from getting equality         */
2161    outfile.st_ino = 2;  /* If one or other of the files is not accessible */
2162    stat(cf->filename, &infile);
2163    stat(fname, &outfile);
2164    if (infile.st_ino == outfile.st_ino) {
2165     simple_dialog(ESD_TYPE_CRIT, NULL,
2166                       "Can't save over current capture file: %s!",
2167                       cf->filename);
2168     goto fail;
2169   }
2170
2171   if (!save_filtered && !save_marked && save_format == cf->cd_t) {
2172     /* We're not filtering packets, and we're saving it in the format
2173        it's already in, so we can just move or copy the raw data. */
2174
2175     if (cf->is_tempfile) {
2176       /* The file being saved is a temporary file from a live
2177          capture, so it doesn't need to stay around under that name;
2178          first, try renaming the capture buffer file to the new name. */
2179 #ifndef WIN32
2180       if (rename(cf->filename, fname) == 0) {
2181         /* That succeeded - there's no need to copy the source file. */
2182         from_filename = NULL;
2183         do_copy = FALSE;
2184       } else {
2185         if (errno == EXDEV) {
2186           /* They're on different file systems, so we have to copy the
2187              file. */
2188           do_copy = TRUE;
2189           from_filename = cf->filename;
2190         } else {
2191           /* The rename failed, but not because they're on different
2192              file systems - put up an error message.  (Or should we
2193              just punt and try to copy?  The only reason why I'd
2194              expect the rename to fail and the copy to succeed would
2195              be if we didn't have permission to remove the file from
2196              the temporary directory, and that might be fixable - but
2197              is it worth requiring the user to go off and fix it?) */
2198           simple_dialog(ESD_TYPE_CRIT, NULL,
2199                                 file_rename_error_message(errno), fname);
2200           goto fail;
2201         }
2202       }
2203 #else
2204       do_copy = TRUE;
2205       from_filename = cf->filename;
2206 #endif
2207     } else {
2208       /* It's a permanent file, so we should copy it, and not remove the
2209          original. */
2210       do_copy = TRUE;
2211       from_filename = cf->filename;
2212     }
2213
2214     if (do_copy) {
2215       /* Copy the file, if we haven't moved it. */
2216       if (!copy_binary_file(from_filename, fname))
2217         goto fail;
2218     }
2219   } else {
2220     /* Either we're filtering packets, or we're saving in a different
2221        format; we can't do that by copying or moving the capture file,
2222        we have to do it by writing the packets out in Wiretap. */
2223     pdh = wtap_dump_open(fname, save_format, cf->lnk_t, cf->snap, &err);
2224     if (pdh == NULL) {
2225       simple_dialog(ESD_TYPE_CRIT, NULL,
2226                         file_open_error_message(err, TRUE, save_format), fname);
2227       goto fail;
2228     }
2229
2230     /* XXX - have a way to save only the packets currently selected by
2231        the display filter or the marked ones.
2232
2233        If we do that, should we make that file the current file?  If so,
2234        it means we can no longer get at the other packets.  What does
2235        NetMon do? */
2236     for (fdata = cf->plist; fdata != NULL; fdata = fdata->next) {
2237       /* XXX - do a progress bar */
2238       if ((!save_filtered && !save_marked) ||
2239           (save_filtered && fdata->flags.passed_dfilter && !save_marked) ||
2240           (save_marked && fdata->flags.marked && !save_filtered) ||
2241           (save_filtered && save_marked && fdata->flags.passed_dfilter &&
2242            fdata->flags.marked)) {
2243         /* Either :
2244            - we're saving all frames, or
2245            - we're saving filtered frames and this one passed the display filter or
2246            - we're saving marked frames (and it has been marked) or
2247            - we're saving filtered _and_ marked frames,
2248            save it. */
2249         hdr.ts.tv_sec = fdata->abs_secs;
2250         hdr.ts.tv_usec = fdata->abs_usecs;
2251         hdr.caplen = fdata->cap_len;
2252         hdr.len = fdata->pkt_len;
2253         hdr.pkt_encap = fdata->lnk_t;
2254         if (!wtap_seek_read(cf->wth, fdata->file_off, &pseudo_header,
2255                 pd, fdata->cap_len, &err)) {
2256           simple_dialog(ESD_TYPE_CRIT, NULL,
2257                                 file_read_error_message(err), cf->filename);
2258           wtap_dump_close(pdh, &err);
2259           goto fail;
2260         }
2261
2262         if (!wtap_dump(pdh, &hdr, &pseudo_header, pd, &err)) {
2263           simple_dialog(ESD_TYPE_CRIT, NULL,
2264                                 file_write_error_message(err), fname);
2265           wtap_dump_close(pdh, &err);
2266           goto fail;
2267         }
2268       }
2269     }
2270
2271     if (!wtap_dump_close(pdh, &err)) {
2272       simple_dialog(ESD_TYPE_WARN, NULL,
2273                 file_close_error_message(err), fname);
2274       goto fail;
2275     }
2276   }
2277
2278   /* Pop the "Saving:" message off the status bar. */
2279   statusbar_pop_file_msg();
2280   if (!save_filtered && !save_marked) {
2281     /* We saved the entire capture, not just some packets from it.
2282        Open and read the file we saved it to.
2283
2284        XXX - this is somewhat of a waste; we already have the
2285        packets, all this gets us is updated file type information
2286        (which we could just stuff into "cf"), and having the new
2287        file be the one we have opened and from which we're reading
2288        the data, and it means we have to spend time opening and
2289        reading the file, which could be a significant amount of
2290        time if the file is large. */
2291     cf->user_saved = TRUE;
2292
2293     if ((err = open_cap_file(fname, FALSE, cf)) == 0) {
2294       /* XXX - report errors if this fails?
2295          What should we return if it fails or is aborted? */
2296       switch (read_cap_file(cf, &err)) {
2297
2298       case READ_SUCCESS:
2299       case READ_ERROR:
2300         /* Just because we got an error, that doesn't mean we were unable
2301            to read any of the file; we handle what we could get from the
2302            file. */
2303         break;
2304
2305       case READ_ABORTED:
2306         /* The user bailed out of re-reading the capture file; the
2307            capture file has been closed - just return (without
2308            changing any menu settings; "close_cap_file()" set them
2309            correctly for the "no capture file open" state). */
2310         break;
2311       }
2312       set_menus_for_unsaved_capture_file(FALSE);
2313     }
2314   }
2315   return TRUE;
2316
2317 fail:
2318   /* Pop the "Saving:" message off the status bar. */
2319   statusbar_pop_file_msg();
2320   return FALSE;
2321 }
2322
2323 char *
2324 file_open_error_message(int err, gboolean for_writing, int file_type)
2325 {
2326   char *errmsg;
2327   static char errmsg_errno[1024+1];
2328
2329   switch (err) {
2330
2331   case WTAP_ERR_NOT_REGULAR_FILE:
2332     errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
2333     break;
2334
2335   case WTAP_ERR_RANDOM_OPEN_PIPE:
2336     /* Seen only when opening a capture file for reading. */
2337     errmsg = "The file \"%s\" is a pipe or FIFO; Ethereal cannot read pipe or FIFO files.";
2338     break;
2339
2340   case WTAP_ERR_FILE_UNKNOWN_FORMAT:
2341   case WTAP_ERR_UNSUPPORTED:
2342     /* Seen only when opening a capture file for reading. */
2343     errmsg = "The file \"%s\" is not a capture file in a format Ethereal understands.";
2344     break;
2345
2346   case WTAP_ERR_CANT_WRITE_TO_PIPE:
2347     /* Seen only when opening a capture file for writing. */
2348     snprintf(errmsg_errno, sizeof(errmsg_errno),
2349              "The file \"%%s\" is a pipe, and %s capture files cannot be "
2350              "written to a pipe.", wtap_file_type_string(file_type));
2351     errmsg = errmsg_errno;
2352     break;
2353
2354   case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2355     /* Seen only when opening a capture file for writing. */
2356     errmsg = "Ethereal does not support writing capture files in that format.";
2357     break;
2358
2359   case WTAP_ERR_UNSUPPORTED_ENCAP:
2360   case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2361     if (for_writing)
2362       errmsg = "Ethereal cannot save this capture in that format.";
2363     else
2364       errmsg = "The file \"%s\" is a capture for a network type that Ethereal doesn't support.";
2365     break;
2366
2367   case WTAP_ERR_BAD_RECORD:
2368     errmsg = "The file \"%s\" appears to be damaged or corrupt.";
2369     break;
2370
2371   case WTAP_ERR_CANT_OPEN:
2372     if (for_writing)
2373       errmsg = "The file \"%s\" could not be created for some unknown reason.";
2374     else
2375       errmsg = "The file \"%s\" could not be opened for some unknown reason.";
2376     break;
2377
2378   case WTAP_ERR_SHORT_READ:
2379     errmsg = "The file \"%s\" appears to have been cut short"
2380              " in the middle of a packet or other data.";
2381     break;
2382
2383   case WTAP_ERR_SHORT_WRITE:
2384     errmsg = "A full header couldn't be written to the file \"%s\".";
2385     break;
2386
2387   case ENOENT:
2388     if (for_writing)
2389       errmsg = "The path to the file \"%s\" does not exist.";
2390     else
2391       errmsg = "The file \"%s\" does not exist.";
2392     break;
2393
2394   case EACCES:
2395     if (for_writing)
2396       errmsg = "You do not have permission to create or write to the file \"%s\".";
2397     else
2398       errmsg = "You do not have permission to read the file \"%s\".";
2399     break;
2400
2401   case EISDIR:
2402     errmsg = "\"%s\" is a directory (folder), not a file.";
2403     break;
2404
2405   default:
2406     snprintf(errmsg_errno, sizeof(errmsg_errno),
2407                     "The file \"%%s\" could not be %s: %s.",
2408                                 for_writing ? "created" : "opened",
2409                                 wtap_strerror(err));
2410     errmsg = errmsg_errno;
2411     break;
2412   }
2413   return errmsg;
2414 }
2415
2416 static char *
2417 file_rename_error_message(int err)
2418 {
2419   char *errmsg;
2420   static char errmsg_errno[1024+1];
2421
2422   switch (err) {
2423
2424   case ENOENT:
2425     errmsg = "The path to the file \"%s\" does not exist.";
2426     break;
2427
2428   case EACCES:
2429     errmsg = "You do not have permission to move the capture file to \"%s\".";
2430     break;
2431
2432   default:
2433     snprintf(errmsg_errno, sizeof(errmsg_errno),
2434                     "The file \"%%s\" could not be moved: %s.",
2435                                 wtap_strerror(err));
2436     errmsg = errmsg_errno;
2437     break;
2438   }
2439   return errmsg;
2440 }
2441
2442 char *
2443 file_read_error_message(int err)
2444 {
2445   static char errmsg_errno[1024+1];
2446
2447   snprintf(errmsg_errno, sizeof(errmsg_errno),
2448                   "An error occurred while reading from the file \"%%s\": %s.",
2449                                 wtap_strerror(err));
2450   return errmsg_errno;
2451 }
2452
2453 char *
2454 file_write_error_message(int err)
2455 {
2456   char *errmsg;
2457   static char errmsg_errno[1024+1];
2458
2459   switch (err) {
2460
2461   case ENOSPC:
2462     errmsg = "The file \"%s\" could not be saved because there is no space left on the file system.";
2463     break;
2464
2465 #ifdef EDQUOT
2466   case EDQUOT:
2467     errmsg = "The file \"%s\" could not be saved because you are too close to, or over, your disk quota.";
2468     break;
2469 #endif
2470
2471   default:
2472     snprintf(errmsg_errno, sizeof(errmsg_errno),
2473                     "An error occurred while writing to the file \"%%s\": %s.",
2474                                 wtap_strerror(err));
2475     errmsg = errmsg_errno;
2476     break;
2477   }
2478   return errmsg;
2479 }
2480
2481 /* Check for write errors - if the file is being written to an NFS server,
2482    a write error may not show up until the file is closed, as NFS clients
2483    might not send writes to the server until the "write()" call finishes,
2484    so that the write may fail on the server but the "write()" may succeed. */
2485 static char *
2486 file_close_error_message(int err)
2487 {
2488   char *errmsg;
2489   static char errmsg_errno[1024+1];
2490
2491   switch (err) {
2492
2493   case WTAP_ERR_CANT_CLOSE:
2494     errmsg = "The file \"%s\" couldn't be closed for some unknown reason.";
2495     break;
2496
2497   case WTAP_ERR_SHORT_WRITE:
2498     errmsg = "Not all the packets could be written to the file \"%s\".";
2499     break;
2500
2501   case ENOSPC:
2502     errmsg = "The file \"%s\" could not be saved because there is no space left on the file system.";
2503     break;
2504
2505 #ifdef EDQUOT
2506   case EDQUOT:
2507     errmsg = "The file \"%s\" could not be saved because you are too close to, or over, your disk quota.";
2508     break;
2509 #endif
2510
2511   default:
2512     snprintf(errmsg_errno, sizeof(errmsg_errno),
2513                     "An error occurred while closing the file \"%%s\": %s.",
2514                                 wtap_strerror(err));
2515     errmsg = errmsg_errno;
2516     break;
2517   }
2518   return errmsg;
2519 }
2520
2521
2522 /* Copies a file in binary mode, for those operating systems that care about
2523  * such things.
2524  * Returns TRUE on success, FALSE on failure. If a failure, it also
2525  * displays a simple dialog window with the error message.
2526  */
2527 static gboolean
2528 copy_binary_file(char *from_filename, char *to_filename)
2529 {
2530         int           from_fd, to_fd, nread, nwritten, err;
2531         guint8        pd[65536]; /* XXX - Hmm, 64K here, 64K in save_cap_file(),
2532                                     perhaps we should make just one 64K buffer. */
2533
2534       /* Copy the raw bytes of the file. */
2535       from_fd = open(from_filename, O_RDONLY | O_BINARY);
2536       if (from_fd < 0) {
2537         err = errno;
2538         simple_dialog(ESD_TYPE_CRIT, NULL,
2539                         file_open_error_message(err, TRUE, 0), from_filename);
2540         goto done;
2541       }
2542
2543       /* Use open() instead of creat() so that we can pass the O_BINARY
2544          flag, which is relevant on Win32; it appears that "creat()"
2545          may open the file in text mode, not binary mode, but we want
2546          to copy the raw bytes of the file, so we need the output file
2547          to be open in binary mode. */
2548       to_fd = open(to_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
2549       if (to_fd < 0) {
2550         err = errno;
2551         simple_dialog(ESD_TYPE_CRIT, NULL,
2552                         file_open_error_message(err, TRUE, 0), to_filename);
2553         close(from_fd);
2554         goto done;
2555       }
2556
2557       while ((nread = read(from_fd, pd, sizeof pd)) > 0) {
2558         nwritten = write(to_fd, pd, nread);
2559         if (nwritten < nread) {
2560           if (nwritten < 0)
2561             err = errno;
2562           else
2563             err = WTAP_ERR_SHORT_WRITE;
2564           simple_dialog(ESD_TYPE_CRIT, NULL,
2565                                 file_write_error_message(err), to_filename);
2566           close(from_fd);
2567           close(to_fd);
2568           goto done;
2569         }
2570       }
2571       if (nread < 0) {
2572         err = errno;
2573         simple_dialog(ESD_TYPE_CRIT, NULL,
2574                         file_read_error_message(err), from_filename);
2575         close(from_fd);
2576         close(to_fd);
2577         goto done;
2578       }
2579       close(from_fd);
2580       if (close(to_fd) < 0) {
2581         err = errno;
2582         simple_dialog(ESD_TYPE_CRIT, NULL,
2583                 file_close_error_message(err), to_filename);
2584         goto done;
2585       }
2586
2587       return TRUE;
2588
2589    done:
2590       return FALSE;
2591 }