20310aa4cd8ca51bf0eb2c91d22502cd5475486a
[metze/wireshark/wip.git] / file.c
1 /* file.c
2  * File I/O routines
3  *
4  * $Id: file.c,v 1.305 2003/09/03 10:49:01 sahlberg 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     /* XXX - do something with "err" */
1085     wtap_seek_read (cf->wth, fdata->file_off, &cf->pseudo_header,
1086         cf->pd, fdata->cap_len, &err);
1087
1088     row = add_packet_to_packet_list(fdata, cf, &cf->pseudo_header, cf->pd,
1089                                         refilter);
1090     if (fdata == selected_frame)
1091       selected_row = row;
1092   }
1093
1094   if (redissect) {
1095     /* Clear out what remains of the visited flags and per-frame data
1096        pointers.
1097
1098        XXX - that may cause various forms of bogosity when dissecting
1099        these frames, as they won't have been seen by this sequential
1100        pass, but the only alternative I see is to keep scanning them
1101        even though the user requested that the scan stop, and that
1102        would leave the user stuck with an Ethereal grinding on
1103        until it finishes.  Should we just stick them with that? */
1104     for (; fdata != NULL; fdata = fdata->next) {
1105       fdata->flags.visited = 0;
1106       if (fdata->pfd) {
1107         g_slist_free(fdata->pfd);
1108         fdata->pfd = NULL;
1109       }
1110     }
1111   }
1112
1113   /* We're done filtering the packets; destroy the progress bar if it
1114      was created. */
1115   if (progbar != NULL)
1116     destroy_progress_dlg(progbar);
1117
1118   /* Unfreeze the packet list. */
1119   packet_list_thaw();
1120
1121   if (selected_row != -1) {
1122     /* The frame that was selected passed the filter; select it, make it
1123        the focus row, and make it visible. */
1124     packet_list_set_selected_row(selected_row);
1125     finfo_selected = NULL;
1126   } else {
1127     /* The selected frame didn't pass the filter; make the first frame
1128        the current frame, and leave it unselected. */
1129     unselect_packet(cf);
1130     cf->current_frame = cf->first_displayed;
1131   }
1132 }
1133
1134 int
1135 print_packets(capture_file *cf, print_args_t *print_args)
1136 {
1137   int         i;
1138   frame_data *fdata;
1139   progdlg_t  *progbar = NULL;
1140   gboolean    stop_flag;
1141   int         count;
1142   int         err;
1143   gint       *col_widths = NULL;
1144   gint        data_width;
1145   gboolean    print_separator;
1146   char       *line_buf = NULL;
1147   int         line_buf_len = 256;
1148   char        *cp;
1149   int         cp_off;
1150   int         column_len;
1151   int         line_len;
1152   epan_dissect_t *edt = NULL;
1153   float       prog_val;
1154   GTimeVal    start_time;
1155   gchar       status_str[100];
1156
1157   cf->print_fh = open_print_dest(print_args->to_file, print_args->dest);
1158   if (cf->print_fh == NULL)
1159     return FALSE;       /* attempt to open destination failed */
1160
1161   print_preamble(cf->print_fh, print_args->format);
1162
1163   if (print_args->print_summary) {
1164     /* We're printing packet summaries.  Allocate the line buffer at
1165        its initial length. */
1166     line_buf = g_malloc(line_buf_len + 1);
1167
1168     /* Find the widths for each of the columns - maximum of the
1169        width of the title and the width of the data - and print
1170        the column titles. */
1171     col_widths = (gint *) g_malloc(sizeof(gint) * cf->cinfo.num_cols);
1172     cp = &line_buf[0];
1173     line_len = 0;
1174     for (i = 0; i < cf->cinfo.num_cols; i++) {
1175       /* Don't pad the last column. */
1176       if (i == cf->cinfo.num_cols - 1)
1177         col_widths[i] = 0;
1178       else {
1179         col_widths[i] = strlen(cf->cinfo.col_title[i]);
1180         data_width = get_column_char_width(get_column_format(i));
1181         if (data_width > col_widths[i])
1182           col_widths[i] = data_width;
1183       }
1184
1185       /* Find the length of the string for this column. */
1186       column_len = strlen(cf->cinfo.col_title[i]);
1187       if (col_widths[i] > column_len)
1188         column_len = col_widths[i];
1189
1190       /* Make sure there's room in the line buffer for the column; if not,
1191          double its length. */
1192       line_len += column_len + 1;       /* "+1" for space */
1193       if (line_len > line_buf_len) {
1194         cp_off = cp - line_buf;
1195         line_buf_len = 2 * line_len;
1196         line_buf = g_realloc(line_buf, line_buf_len + 1);
1197         cp = line_buf + cp_off;
1198       }
1199
1200       /* Right-justify the packet number column. */
1201       if (cf->cinfo.col_fmt[i] == COL_NUMBER)
1202         sprintf(cp, "%*s", col_widths[i], cf->cinfo.col_title[i]);
1203       else
1204         sprintf(cp, "%-*s", col_widths[i], cf->cinfo.col_title[i]);
1205       cp += column_len;
1206       if (i != cf->cinfo.num_cols - 1)
1207         *cp++ = ' ';
1208     }
1209     *cp = '\0';
1210     print_line(cf->print_fh, 0, print_args->format, line_buf);
1211   }
1212
1213   print_separator = FALSE;
1214
1215   /* Update the progress bar when it gets to this value. */
1216   cf->progbar_nextstep = 0;
1217   /* When we reach the value that triggers a progress bar update,
1218      bump that value by this amount. */
1219   cf->progbar_quantum = cf->count/N_PROGBAR_UPDATES;
1220   /* Count of packets at which we've looked. */
1221   count = 0;
1222
1223   stop_flag = FALSE;
1224   g_get_current_time(&start_time);
1225
1226   /* Iterate through the list of packets, printing the packets that
1227      were selected by the current display filter.  */
1228   for (fdata = cf->plist; fdata != NULL; fdata = fdata->next) {
1229     /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
1230        when we update it, we have to run the GTK+ main loop to get it
1231        to repaint what's pending, and doing so may involve an "ioctl()"
1232        to see if there's any pending input from an X server, and doing
1233        that for every packet can be costly, especially on a big file. */
1234     if (count >= cf->progbar_nextstep) {
1235       /* let's not divide by zero. I should never be started
1236        * with count == 0, so let's assert that
1237        */
1238       g_assert(cf->count > 0);
1239       prog_val = (gfloat) count / cf->count;
1240
1241       if (progbar == NULL)
1242         /* Create the progress bar if necessary */
1243         progbar = delayed_create_progress_dlg("Printing", "selected frames", "Stop", &stop_flag,
1244           &start_time, prog_val);
1245
1246       if (progbar != NULL) {
1247         g_snprintf(status_str, sizeof(status_str),
1248                    "%4u of %u frames", count, cf->count);
1249         update_progress_dlg(progbar, prog_val, status_str);
1250       }
1251
1252       cf->progbar_nextstep += cf->progbar_quantum;
1253     }
1254
1255     if (stop_flag) {
1256       /* Well, the user decided to abort the printing.  Just stop.
1257
1258          XXX - note that what got generated before they did that
1259          will get printed, as we're piping to a print program; we'd
1260          have to write to a file and then hand that to the print
1261          program to make it actually not print anything. */
1262       break;
1263     }
1264
1265     count++;
1266     /* Check to see if we are suppressing unmarked packets, if so,
1267      * suppress them and then proceed to check for visibility.
1268      */
1269     if (((print_args->suppress_unmarked && fdata->flags.marked ) ||
1270         !(print_args->suppress_unmarked)) && fdata->flags.passed_dfilter) {
1271       /* XXX - do something with "err" */
1272       wtap_seek_read (cf->wth, fdata->file_off, &cf->pseudo_header,
1273                         cf->pd, fdata->cap_len, &err);
1274       if (print_args->print_summary) {
1275         /* Fill in the column information, but don't bother creating
1276            the logical protocol tree. */
1277         edt = epan_dissect_new(FALSE, FALSE);
1278         epan_dissect_run(edt, &cf->pseudo_header, cf->pd, fdata, &cf->cinfo);
1279         epan_dissect_fill_in_columns(edt);
1280         cp = &line_buf[0];
1281         line_len = 0;
1282         for (i = 0; i < cf->cinfo.num_cols; i++) {
1283           /* Find the length of the string for this column. */
1284           column_len = strlen(cf->cinfo.col_data[i]);
1285           if (col_widths[i] > column_len)
1286             column_len = col_widths[i];
1287
1288           /* Make sure there's room in the line buffer for the column; if not,
1289              double its length. */
1290           line_len += column_len + 1;   /* "+1" for space */
1291           if (line_len > line_buf_len) {
1292             cp_off = cp - line_buf;
1293             line_buf_len = 2 * line_len;
1294             line_buf = g_realloc(line_buf, line_buf_len + 1);
1295             cp = line_buf + cp_off;
1296           }
1297
1298           /* Right-justify the packet number column. */
1299           if (cf->cinfo.col_fmt[i] == COL_NUMBER)
1300             sprintf(cp, "%*s", col_widths[i], cf->cinfo.col_data[i]);
1301           else
1302             sprintf(cp, "%-*s", col_widths[i], cf->cinfo.col_data[i]);
1303           cp += column_len;
1304           if (i != cf->cinfo.num_cols - 1)
1305             *cp++ = ' ';
1306         }
1307         *cp = '\0';
1308         print_line(cf->print_fh, 0, print_args->format, line_buf);
1309       } else {
1310         if (print_separator)
1311           print_line(cf->print_fh, 0, print_args->format, "");
1312
1313         /* Create the logical protocol tree, complete with the display
1314            representation of the items; we don't need the columns here,
1315            however. */
1316         edt = epan_dissect_new(TRUE, TRUE);
1317         epan_dissect_run(edt, &cf->pseudo_header, cf->pd, fdata, NULL);
1318
1319         /* Print the information in that tree. */
1320         proto_tree_print(print_args, edt, cf->print_fh);
1321
1322         if (print_args->print_hex) {
1323           /* Print the full packet data as hex. */
1324           print_hex_data(cf->print_fh, print_args->format, edt);
1325         }
1326
1327         /* Print a blank line if we print anything after this. */
1328         print_separator = TRUE;
1329       }
1330       epan_dissect_free(edt);
1331     }
1332   }
1333
1334   /* We're done printing the packets; destroy the progress bar if
1335      it was created. */
1336   if (progbar != NULL)
1337     destroy_progress_dlg(progbar);
1338
1339   if (col_widths != NULL)
1340     g_free(col_widths);
1341   if (line_buf != NULL)
1342     g_free(line_buf);
1343
1344   print_finale(cf->print_fh, print_args->format);
1345
1346   close_print_dest(print_args->to_file, cf->print_fh);
1347
1348   cf->print_fh = NULL;
1349
1350   return TRUE;
1351 }
1352
1353 /* Scan through the packet list and change all columns that use the
1354    "command-line-specified" time stamp format to use the current
1355    value of that format. */
1356 void
1357 change_time_formats(capture_file *cf)
1358 {
1359   frame_data *fdata;
1360   progdlg_t  *progbar = NULL;
1361   gboolean    stop_flag;
1362   int         count;
1363   int         row;
1364   int         i;
1365   float       prog_val;
1366   GTimeVal    start_time;
1367   gchar       status_str[100];
1368
1369   /* Are there any columns with time stamps in the "command-line-specified"
1370      format?
1371
1372      XXX - we have to force the "column is writable" flag on, as it
1373      might be off from the last frame that was dissected. */
1374   col_set_writable(&cf->cinfo, TRUE);
1375   if (!check_col(&cf->cinfo, COL_CLS_TIME)) {
1376     /* No, there aren't any columns in that format, so we have no work
1377        to do. */
1378     return;
1379   }
1380
1381   /* Freeze the packet list while we redo it, so we don't get any
1382      screen updates while it happens. */
1383   freeze_plist(cf);
1384
1385   /* Update the progress bar when it gets to this value. */
1386   cf->progbar_nextstep = 0;
1387   /* When we reach the value that triggers a progress bar update,
1388      bump that value by this amount. */
1389   cf->progbar_quantum = cf->count/N_PROGBAR_UPDATES;
1390   /* Count of packets at which we've looked. */
1391   count = 0;
1392
1393   stop_flag = FALSE;
1394   g_get_current_time(&start_time);
1395
1396   /* Iterate through the list of packets, checking whether the packet
1397      is in a row of the summary list and, if so, whether there are
1398      any columns that show the time in the "command-line-specified"
1399      format and, if so, update that row. */
1400   for (fdata = cf->plist; fdata != NULL; fdata = fdata->next) {
1401     /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
1402        when we update it, we have to run the GTK+ main loop to get it
1403        to repaint what's pending, and doing so may involve an "ioctl()"
1404        to see if there's any pending input from an X server, and doing
1405        that for every packet can be costly, especially on a big file. */
1406     if (count >= cf->progbar_nextstep) {
1407       /* let's not divide by zero. I should never be started
1408        * with count == 0, so let's assert that
1409        */
1410       g_assert(cf->count > 0);
1411
1412       prog_val = (gfloat) count / cf->count;
1413
1414       if (progbar == NULL)
1415         /* Create the progress bar if necessary */
1416         progbar = delayed_create_progress_dlg("Changing", "time display", "Stop",
1417           &stop_flag, &start_time, prog_val);
1418
1419       if (progbar != NULL) {
1420         g_snprintf(status_str, sizeof(status_str),
1421                    "%4u of %u frames", count, cf->count);
1422         update_progress_dlg(progbar, prog_val, status_str);
1423       }
1424
1425       cf->progbar_nextstep += cf->progbar_quantum;
1426     }
1427
1428     if (stop_flag) {
1429       /* Well, the user decided to abort the redisplay.  Just stop.
1430
1431          XXX - this leaves the time field in the old format in
1432          frames we haven't yet processed.  So it goes; should we
1433          simply not offer them the option of stopping? */
1434       break;
1435     }
1436
1437     count++;
1438
1439     /* Find what row this packet is in. */
1440     row = packet_list_find_row_from_data(fdata);
1441
1442     if (row != -1) {
1443       /* This packet is in the summary list, on row "row". */
1444
1445       for (i = 0; i < cf->cinfo.num_cols; i++) {
1446         if (cf->cinfo.fmt_matx[i][COL_CLS_TIME]) {
1447           /* This is one of the columns that shows the time in
1448              "command-line-specified" format; update it. */
1449           cf->cinfo.col_buf[i][0] = '\0';
1450           col_set_cls_time(fdata, &cf->cinfo, i);
1451           packet_list_set_text(row, i, cf->cinfo.col_data[i]);
1452         }
1453       }
1454     }
1455   }
1456
1457   /* We're done redisplaying the packets; destroy the progress bar if it
1458      was created. */
1459   if (progbar != NULL)
1460     destroy_progress_dlg(progbar);
1461
1462   /* Set the column widths of those columns that show the time in
1463      "command-line-specified" format. */
1464   for (i = 0; i < cf->cinfo.num_cols; i++) {
1465     if (cf->cinfo.fmt_matx[i][COL_CLS_TIME]) {
1466       packet_list_set_cls_time_width(i);
1467     }
1468   }
1469
1470   /* Unfreeze the packet list. */
1471   thaw_plist(cf);
1472 }
1473
1474 typedef struct {
1475         const char      *string;
1476         size_t          string_len;
1477         capture_file    *cf;
1478         gboolean        frame_matched;
1479 } match_data;
1480
1481 gboolean
1482 find_packet_protocol_tree(capture_file *cf, const char *string)
1483 {
1484   match_data            mdata;
1485
1486   mdata.string = string;
1487   mdata.string_len = strlen(string);
1488   return find_packet(cf, match_protocol_tree, &mdata);
1489 }
1490
1491 static gboolean
1492 match_protocol_tree(capture_file *cf, frame_data *fdata, void *criterion)
1493 {
1494   match_data            *mdata = criterion;
1495   epan_dissect_t        *edt;
1496
1497   /* Construct the protocol tree, including the displayed text */
1498   edt = epan_dissect_new(TRUE, TRUE);
1499   /* We don't need the column information */
1500   epan_dissect_run(edt, &cf->pseudo_header, cf->pd, fdata, NULL);
1501
1502   /* Iterate through all the nodes, seeing if they have text that matches. */
1503   mdata->cf = cf;
1504   mdata->frame_matched = FALSE;
1505   g_node_children_foreach((GNode*) edt->tree, G_TRAVERSE_ALL,
1506                           match_subtree_text, mdata);
1507   epan_dissect_free(edt);
1508   return mdata->frame_matched;
1509 }
1510
1511 static void
1512 match_subtree_text(GNode *node, gpointer data)
1513 {
1514   match_data    *mdata = (match_data*) data;
1515   const gchar   *string = mdata->string;
1516   size_t        string_len = mdata->string_len;
1517   capture_file  *cf = mdata->cf;
1518   field_info    *fi = PITEM_FINFO(node);
1519   gchar         label_str[ITEM_LABEL_LENGTH];
1520   gchar         *label_ptr;
1521   size_t        label_len;
1522   guint32       i;
1523   guint8        c_char;
1524   size_t        c_match = 0;
1525
1526   if (mdata->frame_matched) {
1527     /* We already had a match; don't bother doing any more work. */
1528     return;
1529   }
1530
1531   /* Don't match invisible entries. */
1532   if (!fi->visible)
1533     return;
1534
1535   /* was a free format label produced? */
1536   if (fi->representation) {
1537     label_ptr = fi->representation;
1538   } else {
1539     /* no, make a generic label */
1540     label_ptr = label_str;
1541     proto_item_fill_label(fi, label_str);
1542   }
1543     
1544   /* Does that label match? */
1545   label_len = strlen(label_ptr);
1546   for (i = 0; i < label_len; i++) {
1547     c_char = label_ptr[i];
1548     if (cf->case_type)
1549       c_char = toupper(c_char);
1550     if (c_char == string[c_match]) {
1551       c_match++;
1552       if (c_match == string_len) {
1553         /* No need to look further; we have a match */
1554         mdata->frame_matched = TRUE;
1555         return;
1556       }
1557     } else
1558       c_match = 0;
1559   }
1560   
1561   /* Recurse into the subtree, if it exists */
1562   if (g_node_n_children(node) > 0)
1563     g_node_children_foreach(node, G_TRAVERSE_ALL, match_subtree_text, mdata);
1564 }
1565
1566 gboolean
1567 find_packet_summary_line(capture_file *cf, const char *string)
1568 {
1569   match_data            mdata;
1570
1571   mdata.string = string;
1572   mdata.string_len = strlen(string);
1573   return find_packet(cf, match_summary_line, &mdata);
1574 }
1575
1576 static gboolean
1577 match_summary_line(capture_file *cf, frame_data *fdata, void *criterion)
1578 {
1579   match_data            *mdata = criterion;
1580   const gchar           *string = mdata->string;
1581   size_t                string_len = mdata->string_len;
1582   epan_dissect_t        *edt;
1583   const char            *info_column;
1584   size_t                info_column_len;
1585   gboolean              frame_matched = FALSE;
1586   gint                  colx;
1587   guint32               i;
1588   guint8                c_char;
1589   size_t                c_match = 0;
1590
1591   /* Don't bother constructing the protocol tree */
1592   edt = epan_dissect_new(FALSE, FALSE);
1593   /* Get the column information */
1594   epan_dissect_run(edt, &cf->pseudo_header, cf->pd, fdata, &cf->cinfo);
1595
1596   /* Find the Info column */
1597   for (colx = 0; colx < cf->cinfo.num_cols; colx++) {
1598     if (cf->cinfo.fmt_matx[colx][COL_INFO]) {
1599       /* Found it.  See if we match. */
1600       info_column = edt->pi.cinfo->col_data[colx];
1601       info_column_len = strlen(info_column);
1602       for (i = 0; i < info_column_len; i++) {
1603         c_char = info_column[i];
1604         if (cf->case_type)
1605           c_char = toupper(c_char);
1606         if (c_char == string[c_match]) {
1607           c_match++;
1608           if (c_match == string_len) {
1609             frame_matched = TRUE;
1610             break;
1611           }
1612         } else
1613           c_match = 0;
1614       }
1615       break;
1616     }
1617   }
1618   epan_dissect_free(edt);
1619   return frame_matched;
1620 }
1621
1622 typedef struct {
1623         const guint8 *data;
1624         size_t data_len;
1625 } cbs_t;        /* "Counted byte string" */
1626
1627 gboolean
1628 find_packet_data(capture_file *cf, const guint8 *string, size_t string_size)
1629 {
1630   cbs_t info;
1631
1632   info.data = string;
1633   info.data_len = string_size;
1634
1635   /* String or hex search? */
1636   if (cf->ascii) {
1637     /* String search - what type of string? */
1638     switch (cf->scs_type) {
1639
1640     case SCS_ASCII_AND_UNICODE:
1641       return find_packet(cf, match_ascii_and_unicode, &info);
1642
1643     case SCS_ASCII:
1644       return find_packet(cf, match_ascii, &info);
1645
1646     case SCS_UNICODE:
1647       return find_packet(cf, match_unicode, &info);
1648
1649     default:
1650       g_assert_not_reached();
1651       return FALSE;
1652     }
1653   } else
1654     return find_packet(cf, match_binary, &info);
1655 }
1656
1657 static gboolean
1658 match_ascii_and_unicode(capture_file *cf, frame_data *fdata, void *criterion)
1659 {
1660   cbs_t         *info = criterion;
1661   const char    *ascii_text = info->data;
1662   size_t        textlen = info->data_len;
1663   gboolean      frame_matched;
1664   guint32       buf_len;
1665   guint32       i;
1666   guint8        c_char;
1667   size_t        c_match = 0;
1668
1669   frame_matched = FALSE;
1670   buf_len = fdata->pkt_len;
1671   for (i = 0; i < buf_len; i++) {
1672     c_char = cf->pd[i];
1673     if (cf->case_type)
1674       c_char = toupper(c_char);
1675     if (c_char != 0) {
1676       if (c_char == ascii_text[c_match]) {
1677         c_match++;
1678         if (c_match == textlen) {
1679           frame_matched = TRUE;
1680           break;
1681         }
1682       } else
1683         c_match = 0;
1684     }
1685   }
1686   return frame_matched;
1687 }
1688
1689 static gboolean
1690 match_ascii(capture_file *cf, frame_data *fdata, void *criterion)
1691 {
1692   cbs_t         *info = criterion;
1693   const char    *ascii_text = info->data;
1694   size_t        textlen = info->data_len;
1695   gboolean      frame_matched;
1696   guint32       buf_len;
1697   guint32       i;
1698   guint8        c_char;
1699   size_t        c_match = 0;
1700
1701   frame_matched = FALSE;
1702   buf_len = fdata->pkt_len;
1703   for (i = 0; i < buf_len; i++) {
1704     c_char = cf->pd[i];
1705     if (cf->case_type)
1706       c_char = toupper(c_char);
1707     if (c_char == ascii_text[c_match]) {
1708       c_match++;
1709       if (c_match == textlen) {
1710         frame_matched = TRUE;
1711         break;
1712       }
1713     } else
1714       c_match = 0;
1715   }
1716   return frame_matched;
1717 }
1718
1719 static gboolean
1720 match_unicode(capture_file *cf, frame_data *fdata, void *criterion)
1721 {
1722   cbs_t         *info = criterion;
1723   const char    *ascii_text = info->data;
1724   size_t        textlen = info->data_len;
1725   gboolean      frame_matched;
1726   guint32       buf_len;
1727   guint32       i;
1728   guint8        c_char;
1729   size_t        c_match = 0;
1730
1731   frame_matched = FALSE;
1732   buf_len = fdata->pkt_len;
1733   for (i = 0; i < buf_len; i++) {
1734     c_char = cf->pd[i];
1735     if (cf->case_type)
1736       c_char = toupper(c_char);
1737     if (c_char == ascii_text[c_match]) {
1738       c_match++;
1739       i++;
1740       if (c_match == textlen) {
1741         frame_matched = TRUE;
1742         break;
1743       }
1744     } else
1745       c_match = 0;
1746   }
1747   return frame_matched;
1748 }
1749
1750 static gboolean
1751 match_binary(capture_file *cf, frame_data *fdata, void *criterion)
1752 {
1753   cbs_t         *info = criterion;
1754   const guint8  *binary_data = info->data;
1755   size_t        datalen = info->data_len;
1756   gboolean      frame_matched;
1757   guint32       buf_len;
1758   guint32       i;
1759   size_t        c_match = 0;
1760
1761   frame_matched = FALSE;
1762   buf_len = fdata->pkt_len;
1763   for (i = 0; i < buf_len; i++) {
1764     if (cf->pd[i] == binary_data[c_match]) {
1765       c_match++;
1766       if (c_match == datalen) {
1767         frame_matched = TRUE;
1768         break;
1769       }
1770     } else
1771       c_match = 0;
1772   }
1773   return frame_matched;
1774 }
1775
1776 gboolean
1777 find_packet_dfilter(capture_file *cf, dfilter_t *sfcode)
1778 {
1779   return find_packet(cf, match_dfilter, sfcode);
1780 }
1781
1782 static gboolean
1783 match_dfilter(capture_file *cf, frame_data *fdata, void *criterion)
1784 {
1785   dfilter_t             *sfcode = criterion;
1786   epan_dissect_t        *edt;
1787   gboolean              frame_matched;
1788
1789   edt = epan_dissect_new(TRUE, FALSE);
1790   epan_dissect_prime_dfilter(edt, sfcode);
1791   epan_dissect_run(edt, &cf->pseudo_header, cf->pd, fdata, NULL);
1792   frame_matched = dfilter_apply_edt(sfcode, edt);
1793   epan_dissect_free(edt);
1794   return frame_matched;
1795 }
1796
1797 static gboolean
1798 find_packet(capture_file *cf,
1799             gboolean (*match_function)(capture_file *, frame_data *, void *),
1800             void *criterion)
1801 {
1802   frame_data *start_fd;
1803   frame_data *fdata;
1804   frame_data *new_fd = NULL;
1805   progdlg_t  *progbar = NULL;
1806   gboolean    stop_flag;
1807   int         count;
1808   int         err;
1809   int         row;
1810   float       prog_val;
1811   GTimeVal    start_time;
1812   gchar       status_str[100];
1813
1814   start_fd = cf->current_frame;
1815   if (start_fd != NULL)  {
1816     /* Iterate through the list of packets, starting at the packet we've
1817        picked, calling a routine to run the filter on the packet, see if
1818        it matches, and stop if so.  */
1819     count = 0;
1820     fdata = start_fd;
1821
1822     cf->progbar_nextstep = 0;
1823     /* When we reach the value that triggers a progress bar update,
1824        bump that value by this amount. */
1825     cf->progbar_quantum = cf->count/N_PROGBAR_UPDATES;
1826
1827     stop_flag = FALSE;
1828     g_get_current_time(&start_time);
1829
1830     fdata = start_fd;
1831     for (;;) {
1832       /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
1833          when we update it, we have to run the GTK+ main loop to get it
1834          to repaint what's pending, and doing so may involve an "ioctl()"
1835          to see if there's any pending input from an X server, and doing
1836          that for every packet can be costly, especially on a big file. */
1837       if (count >= cf->progbar_nextstep) {
1838         /* let's not divide by zero. I should never be started
1839          * with count == 0, so let's assert that
1840          */
1841         g_assert(cf->count > 0);
1842
1843         prog_val = (gfloat) count / cf->count;
1844
1845         /* Create the progress bar if necessary */
1846         if (progbar == NULL)
1847            progbar = delayed_create_progress_dlg("Searching", cf->sfilter, "Cancel",
1848              &stop_flag, &start_time, prog_val);
1849
1850         if (progbar != NULL) {
1851           g_snprintf(status_str, sizeof(status_str),
1852                      "%4u of %u frames", count, cf->count);
1853           update_progress_dlg(progbar, prog_val, status_str);
1854         }
1855
1856         cf->progbar_nextstep += cf->progbar_quantum;
1857       }
1858
1859       if (stop_flag) {
1860         /* Well, the user decided to abort the search.  Go back to the
1861            frame where we started. */
1862         new_fd = start_fd;
1863         break;
1864       }
1865
1866       /* Go past the current frame. */
1867       if (cf->sbackward) {
1868         /* Go on to the previous frame. */
1869         fdata = fdata->prev;
1870         if (fdata == NULL)
1871           fdata = cf->plist_end;        /* wrap around */
1872       } else {
1873         /* Go on to the next frame. */
1874         fdata = fdata->next;
1875         if (fdata == NULL)
1876           fdata = cf->plist;    /* wrap around */
1877       }
1878
1879       count++;
1880
1881       /* Is this packet in the display? */
1882       if (fdata->flags.passed_dfilter) {
1883         /* Yes.  Load its data. */
1884         /* XXX - do something with "err" */
1885         wtap_seek_read(cf->wth, fdata->file_off, &cf->pseudo_header,
1886                         cf->pd, fdata->cap_len, &err);
1887
1888         /* Does it match the search criterion? */
1889         if ((*match_function)(cf, fdata, criterion)) {
1890           new_fd = fdata;
1891           break;        /* found it! */
1892         }
1893       }
1894
1895       if (fdata == start_fd) {
1896         /* We're back to the frame we were on originally, and that frame
1897            doesn't match the search filter.  The search failed. */
1898         break;
1899       }
1900     }
1901
1902     /* We're done scanning the packets; destroy the progress bar if it
1903        was created. */
1904     if (progbar != NULL)
1905       destroy_progress_dlg(progbar);
1906   }
1907
1908   if (new_fd != NULL) {
1909     /* We found a frame.  Find what row it's in. */
1910     row = packet_list_find_row_from_data(new_fd);
1911     g_assert(row != -1);
1912
1913     /* Select that row, make it the focus row, and make it visible. */
1914     packet_list_set_selected_row(row);
1915     return TRUE;        /* success */
1916   } else
1917     return FALSE;       /* failure */
1918 }
1919
1920 gboolean
1921 goto_frame(capture_file *cf, guint fnumber)
1922 {
1923   frame_data *fdata;
1924   int row;
1925
1926   for (fdata = cf->plist; fdata != NULL && fdata->num < fnumber; fdata = fdata->next)
1927     ;
1928
1929   if (fdata == NULL) {
1930     /* we didn't find a frame with that frame number */
1931     simple_dialog(ESD_TYPE_CRIT, NULL,
1932                   "There is no frame with that frame number.");
1933     return FALSE;       /* we failed to go to that frame */
1934   }
1935   if (!fdata->flags.passed_dfilter) {
1936     /* that frame currently isn't displayed */
1937     /* XXX - add it to the set of displayed frames? */
1938     simple_dialog(ESD_TYPE_CRIT, NULL,
1939                   "That frame is not currently being displayed.");
1940     return FALSE;       /* we failed to go to that frame */
1941   }
1942
1943   /* We found that frame, and it's currently being displayed.
1944      Find what row it's in. */
1945   row = packet_list_find_row_from_data(fdata);
1946   g_assert(row != -1);
1947
1948   /* Select that row, make it the focus row, and make it visible. */
1949   packet_list_set_selected_row(row);
1950   return TRUE;  /* we got to that frame */
1951 }
1952
1953 /* Select the packet on a given row. */
1954 void
1955 select_packet(capture_file *cf, int row)
1956 {
1957   frame_data *fdata;
1958   int err;
1959
1960   /* Get the frame data struct pointer for this frame */
1961   fdata = (frame_data *)packet_list_get_row_data(row);
1962
1963   if (fdata == NULL) {
1964     /* XXX - if a GtkCList's selection mode is GTK_SELECTION_BROWSE, when
1965        the first entry is added to it by "real_insert_row()", that row
1966        is selected (see "real_insert_row()", in "gtk/gtkclist.c", in both
1967        our version and the vanilla GTK+ version).
1968
1969        This means that a "select-row" signal is emitted; this causes
1970        "packet_list_select_cb()" to be called, which causes "select_packet()"
1971        to be called.
1972
1973        "select_packet()" fetches, above, the data associated with the
1974        row that was selected; however, as "gtk_clist_append()", which
1975        called "real_insert_row()", hasn't yet returned, we haven't yet
1976        associated any data with that row, so we get back a null pointer.
1977
1978        We can't assume that there's only one frame in the frame list,
1979        either, as we may be filtering the display.
1980
1981        We therefore assume that, if "row" is 0, i.e. the first row
1982        is being selected, and "cf->first_displayed" equals
1983        "cf->last_displayed", i.e. there's only one frame being
1984        displayed, that frame is the frame we want.
1985
1986        This means we have to set "cf->first_displayed" and
1987        "cf->last_displayed" before adding the row to the
1988        GtkCList; see the comment in "add_packet_to_packet_list()". */
1989
1990        if (row == 0 && cf->first_displayed == cf->last_displayed)
1991          fdata = cf->first_displayed;
1992   }
1993
1994   /* Record that this frame is the current frame. */
1995   cf->current_frame = fdata;
1996
1997   /* Get the data in that frame. */
1998   /* XXX - do something with "err" */
1999   wtap_seek_read (cf->wth, fdata->file_off, &cf->pseudo_header,
2000                         cf->pd, fdata->cap_len, &err);
2001
2002   /* Create the logical protocol tree. */
2003   if (cf->edt != NULL) {
2004     epan_dissect_free(cf->edt);
2005     cf->edt = NULL;
2006   }
2007   /* We don't need the columns here. */
2008   cf->edt = epan_dissect_new(TRUE, TRUE);
2009   epan_dissect_run(cf->edt, &cf->pseudo_header, cf->pd, cf->current_frame,
2010           NULL);
2011
2012   /* Display the GUI protocol tree and hex dump.
2013      XXX - why do we dump core if we call "proto_tree_draw()"
2014      before calling "add_byte_views()"? */
2015   add_main_byte_views(cf->edt);
2016   main_proto_tree_draw(cf->edt->tree);
2017
2018   /* A packet is selected. */
2019   set_menus_for_selected_packet(TRUE);
2020 }
2021
2022 /* Unselect the selected packet, if any. */
2023 void
2024 unselect_packet(capture_file *cf)
2025 {
2026   /* Destroy the epan_dissect_t for the unselected packet. */
2027   if (cf->edt != NULL) {
2028     epan_dissect_free(cf->edt);
2029     cf->edt = NULL;
2030   }
2031
2032   /* Clear out the display of that packet. */
2033   clear_tree_and_hex_views();
2034
2035   /* No packet is selected. */
2036   set_menus_for_selected_packet(FALSE);
2037
2038   /* No protocol tree means no selected field. */
2039   unselect_field();
2040 }
2041
2042 /* Unset the selected protocol tree field, if any. */
2043 void
2044 unselect_field(void)
2045 {
2046   statusbar_pop_field_msg();
2047   finfo_selected = NULL;
2048   set_menus_for_selected_tree_row(FALSE);
2049 }
2050
2051 /*
2052  * Mark a particular frame.
2053  */
2054 void
2055 mark_frame(capture_file *cf, frame_data *frame)
2056 {
2057   frame->flags.marked = TRUE;
2058   cf->marked_count++;
2059 }
2060
2061 /*
2062  * Unmark a particular frame.
2063  */
2064 void
2065 unmark_frame(capture_file *cf, frame_data *frame)
2066 {
2067   frame->flags.marked = FALSE;
2068   cf->marked_count--;
2069 }
2070
2071 static void
2072 freeze_plist(capture_file *cf)
2073 {
2074   int i;
2075
2076   /* Make the column sizes static, so they don't adjust while
2077      we're reading the capture file (freezing the clist doesn't
2078      seem to suffice). */
2079   for (i = 0; i < cf->cinfo.num_cols; i++)
2080     packet_list_set_column_auto_resize(i, FALSE);
2081   packet_list_freeze();
2082 }
2083
2084 static void
2085 thaw_plist(capture_file *cf)
2086 {
2087   int i;
2088
2089   for (i = 0; i < cf->cinfo.num_cols; i++) {
2090     if (get_column_resize_type(cf->cinfo.col_fmt[i]) == RESIZE_MANUAL) {
2091       /* Set this column's width to the appropriate value. */
2092       packet_list_set_column_width(i, cf->cinfo.col_width[i]);
2093     } else {
2094       /* Make this column's size dynamic, so that it adjusts to the
2095          appropriate size. */
2096       packet_list_set_column_auto_resize(i, TRUE);
2097     }
2098   }
2099   packet_list_thaw();
2100
2101   /* Hopefully, the columns have now gotten their appropriate sizes;
2102      make them resizeable - a column that auto-resizes cannot be
2103      resized by the user, and *vice versa*. */
2104   for (i = 0; i < cf->cinfo.num_cols; i++)
2105     packet_list_set_column_resizeable(i, TRUE);
2106 }
2107
2108 /*
2109  * Save a capture to a file, in a particular format, saving either
2110  * all packets, all currently-displayed packets, or all marked packets.
2111  *
2112  * Returns TRUE if it succeeds, FALSE otherwise; if it fails, it pops
2113  * up a message box for the failure.
2114  */
2115 gboolean
2116 save_cap_file(char *fname, capture_file *cf, gboolean save_filtered,
2117                 gboolean save_marked, guint save_format)
2118 {
2119   gchar        *from_filename;
2120   gchar        *name_ptr, *save_msg, *save_fmt = " Saving: %s...";
2121   size_t        msg_len;
2122   int           err;
2123   gboolean      do_copy;
2124   wtap_dumper  *pdh;
2125   frame_data   *fdata;
2126   struct wtap_pkthdr hdr;
2127   union wtap_pseudo_header pseudo_header;
2128   guint8        pd[65536];
2129   struct stat   infile, outfile;
2130
2131   name_ptr = get_basename(fname);
2132   msg_len = strlen(name_ptr) + strlen(save_fmt) + 2;
2133   save_msg = g_malloc(msg_len);
2134   snprintf(save_msg, msg_len, save_fmt, name_ptr);
2135   statusbar_push_file_msg(save_msg);
2136   g_free(save_msg);
2137
2138   /*
2139    * Check that the from file is not the same as to file
2140    * We do it here so we catch all cases ...
2141    * Unfortunately, the file requester gives us an absolute file
2142    * name and the read file name may be relative (if supplied on
2143    * the command line). From Joerg Mayer.
2144    */
2145    infile.st_ino = 1;   /* These prevent us from getting equality         */
2146    outfile.st_ino = 2;  /* If one or other of the files is not accessible */
2147    stat(cf->filename, &infile);
2148    stat(fname, &outfile);
2149    if (infile.st_ino == outfile.st_ino) {
2150     simple_dialog(ESD_TYPE_CRIT, NULL,
2151                       "Can't save over current capture file: %s!",
2152                       cf->filename);
2153     goto fail;
2154   }
2155
2156   if (!save_filtered && !save_marked && save_format == cf->cd_t) {
2157     /* We're not filtering packets, and we're saving it in the format
2158        it's already in, so we can just move or copy the raw data. */
2159
2160     if (cf->is_tempfile) {
2161       /* The file being saved is a temporary file from a live
2162          capture, so it doesn't need to stay around under that name;
2163          first, try renaming the capture buffer file to the new name. */
2164 #ifndef WIN32
2165       if (rename(cf->filename, fname) == 0) {
2166         /* That succeeded - there's no need to copy the source file. */
2167         from_filename = NULL;
2168         do_copy = FALSE;
2169       } else {
2170         if (errno == EXDEV) {
2171           /* They're on different file systems, so we have to copy the
2172              file. */
2173           do_copy = TRUE;
2174           from_filename = cf->filename;
2175         } else {
2176           /* The rename failed, but not because they're on different
2177              file systems - put up an error message.  (Or should we
2178              just punt and try to copy?  The only reason why I'd
2179              expect the rename to fail and the copy to succeed would
2180              be if we didn't have permission to remove the file from
2181              the temporary directory, and that might be fixable - but
2182              is it worth requiring the user to go off and fix it?) */
2183           simple_dialog(ESD_TYPE_CRIT, NULL,
2184                                 file_rename_error_message(errno), fname);
2185           goto fail;
2186         }
2187       }
2188 #else
2189       do_copy = TRUE;
2190       from_filename = cf->filename;
2191 #endif
2192     } else {
2193       /* It's a permanent file, so we should copy it, and not remove the
2194          original. */
2195       do_copy = TRUE;
2196       from_filename = cf->filename;
2197     }
2198
2199     if (do_copy) {
2200       /* Copy the file, if we haven't moved it. */
2201       if (!copy_binary_file(from_filename, fname))
2202         goto fail;
2203     }
2204   } else {
2205     /* Either we're filtering packets, or we're saving in a different
2206        format; we can't do that by copying or moving the capture file,
2207        we have to do it by writing the packets out in Wiretap. */
2208     pdh = wtap_dump_open(fname, save_format, cf->lnk_t, cf->snap, &err);
2209     if (pdh == NULL) {
2210       simple_dialog(ESD_TYPE_CRIT, NULL,
2211                         file_open_error_message(err, TRUE, save_format), fname);
2212       goto fail;
2213     }
2214
2215     /* XXX - have a way to save only the packets currently selected by
2216        the display filter or the marked ones.
2217
2218        If we do that, should we make that file the current file?  If so,
2219        it means we can no longer get at the other packets.  What does
2220        NetMon do? */
2221     for (fdata = cf->plist; fdata != NULL; fdata = fdata->next) {
2222       /* XXX - do a progress bar */
2223       if ((!save_filtered && !save_marked) ||
2224           (save_filtered && fdata->flags.passed_dfilter && !save_marked) ||
2225           (save_marked && fdata->flags.marked && !save_filtered) ||
2226           (save_filtered && save_marked && fdata->flags.passed_dfilter &&
2227            fdata->flags.marked)) {
2228         /* Either :
2229            - we're saving all frames, or
2230            - we're saving filtered frames and this one passed the display filter or
2231            - we're saving marked frames (and it has been marked) or
2232            - we're saving filtered _and_ marked frames,
2233            save it. */
2234         hdr.ts.tv_sec = fdata->abs_secs;
2235         hdr.ts.tv_usec = fdata->abs_usecs;
2236         hdr.caplen = fdata->cap_len;
2237         hdr.len = fdata->pkt_len;
2238         hdr.pkt_encap = fdata->lnk_t;
2239         if (!wtap_seek_read(cf->wth, fdata->file_off, &pseudo_header,
2240                 pd, fdata->cap_len, &err)) {
2241           simple_dialog(ESD_TYPE_CRIT, NULL,
2242                                 file_read_error_message(err), cf->filename);
2243           wtap_dump_close(pdh, &err);
2244           goto fail;
2245         }
2246
2247         if (!wtap_dump(pdh, &hdr, &pseudo_header, pd, &err)) {
2248           simple_dialog(ESD_TYPE_CRIT, NULL,
2249                                 file_write_error_message(err), fname);
2250           wtap_dump_close(pdh, &err);
2251           goto fail;
2252         }
2253       }
2254     }
2255
2256     if (!wtap_dump_close(pdh, &err)) {
2257       simple_dialog(ESD_TYPE_WARN, NULL,
2258                 file_close_error_message(err), fname);
2259       goto fail;
2260     }
2261   }
2262
2263   /* Pop the "Saving:" message off the status bar. */
2264   statusbar_pop_file_msg();
2265   if (!save_filtered && !save_marked) {
2266     /* We saved the entire capture, not just some packets from it.
2267        Open and read the file we saved it to.
2268
2269        XXX - this is somewhat of a waste; we already have the
2270        packets, all this gets us is updated file type information
2271        (which we could just stuff into "cf"), and having the new
2272        file be the one we have opened and from which we're reading
2273        the data, and it means we have to spend time opening and
2274        reading the file, which could be a significant amount of
2275        time if the file is large. */
2276     cf->user_saved = TRUE;
2277
2278     if ((err = open_cap_file(fname, FALSE, cf)) == 0) {
2279       /* XXX - report errors if this fails?
2280          What should we return if it fails or is aborted? */
2281       switch (read_cap_file(cf, &err)) {
2282
2283       case READ_SUCCESS:
2284       case READ_ERROR:
2285         /* Just because we got an error, that doesn't mean we were unable
2286            to read any of the file; we handle what we could get from the
2287            file. */
2288         break;
2289
2290       case READ_ABORTED:
2291         /* The user bailed out of re-reading the capture file; the
2292            capture file has been closed - just return (without
2293            changing any menu settings; "close_cap_file()" set them
2294            correctly for the "no capture file open" state). */
2295         break;
2296       }
2297       set_menus_for_unsaved_capture_file(FALSE);
2298     }
2299   }
2300   return TRUE;
2301
2302 fail:
2303   /* Pop the "Saving:" message off the status bar. */
2304   statusbar_pop_file_msg();
2305   return FALSE;
2306 }
2307
2308 char *
2309 file_open_error_message(int err, gboolean for_writing, int file_type)
2310 {
2311   char *errmsg;
2312   static char errmsg_errno[1024+1];
2313
2314   switch (err) {
2315
2316   case WTAP_ERR_NOT_REGULAR_FILE:
2317     errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
2318     break;
2319
2320   case WTAP_ERR_RANDOM_OPEN_PIPE:
2321     /* Seen only when opening a capture file for reading. */
2322     errmsg = "The file \"%s\" is a pipe or FIFO; Ethereal cannot read pipe or FIFO files.";
2323     break;
2324
2325   case WTAP_ERR_FILE_UNKNOWN_FORMAT:
2326   case WTAP_ERR_UNSUPPORTED:
2327     /* Seen only when opening a capture file for reading. */
2328     errmsg = "The file \"%s\" is not a capture file in a format Ethereal understands.";
2329     break;
2330
2331   case WTAP_ERR_CANT_WRITE_TO_PIPE:
2332     /* Seen only when opening a capture file for writing. */
2333     snprintf(errmsg_errno, sizeof(errmsg_errno),
2334              "The file \"%%s\" is a pipe, and %s capture files cannot be "
2335              "written to a pipe.", wtap_file_type_string(file_type));
2336     errmsg = errmsg_errno;
2337     break;
2338
2339   case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2340     /* Seen only when opening a capture file for writing. */
2341     errmsg = "Ethereal does not support writing capture files in that format.";
2342     break;
2343
2344   case WTAP_ERR_UNSUPPORTED_ENCAP:
2345   case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2346     if (for_writing)
2347       errmsg = "Ethereal cannot save this capture in that format.";
2348     else
2349       errmsg = "The file \"%s\" is a capture for a network type that Ethereal doesn't support.";
2350     break;
2351
2352   case WTAP_ERR_BAD_RECORD:
2353     errmsg = "The file \"%s\" appears to be damaged or corrupt.";
2354     break;
2355
2356   case WTAP_ERR_CANT_OPEN:
2357     if (for_writing)
2358       errmsg = "The file \"%s\" could not be created for some unknown reason.";
2359     else
2360       errmsg = "The file \"%s\" could not be opened for some unknown reason.";
2361     break;
2362
2363   case WTAP_ERR_SHORT_READ:
2364     errmsg = "The file \"%s\" appears to have been cut short"
2365              " in the middle of a packet or other data.";
2366     break;
2367
2368   case WTAP_ERR_SHORT_WRITE:
2369     errmsg = "A full header couldn't be written to the file \"%s\".";
2370     break;
2371
2372   case ENOENT:
2373     if (for_writing)
2374       errmsg = "The path to the file \"%s\" does not exist.";
2375     else
2376       errmsg = "The file \"%s\" does not exist.";
2377     break;
2378
2379   case EACCES:
2380     if (for_writing)
2381       errmsg = "You do not have permission to create or write to the file \"%s\".";
2382     else
2383       errmsg = "You do not have permission to read the file \"%s\".";
2384     break;
2385
2386   case EISDIR:
2387     errmsg = "\"%s\" is a directory (folder), not a file.";
2388     break;
2389
2390   default:
2391     snprintf(errmsg_errno, sizeof(errmsg_errno),
2392                     "The file \"%%s\" could not be %s: %s.",
2393                                 for_writing ? "created" : "opened",
2394                                 wtap_strerror(err));
2395     errmsg = errmsg_errno;
2396     break;
2397   }
2398   return errmsg;
2399 }
2400
2401 static char *
2402 file_rename_error_message(int err)
2403 {
2404   char *errmsg;
2405   static char errmsg_errno[1024+1];
2406
2407   switch (err) {
2408
2409   case ENOENT:
2410     errmsg = "The path to the file \"%s\" does not exist.";
2411     break;
2412
2413   case EACCES:
2414     errmsg = "You do not have permission to move the capture file to \"%s\".";
2415     break;
2416
2417   default:
2418     snprintf(errmsg_errno, sizeof(errmsg_errno),
2419                     "The file \"%%s\" could not be moved: %s.",
2420                                 wtap_strerror(err));
2421     errmsg = errmsg_errno;
2422     break;
2423   }
2424   return errmsg;
2425 }
2426
2427 char *
2428 file_read_error_message(int err)
2429 {
2430   static char errmsg_errno[1024+1];
2431
2432   snprintf(errmsg_errno, sizeof(errmsg_errno),
2433                   "An error occurred while reading from the file \"%%s\": %s.",
2434                                 wtap_strerror(err));
2435   return errmsg_errno;
2436 }
2437
2438 char *
2439 file_write_error_message(int err)
2440 {
2441   char *errmsg;
2442   static char errmsg_errno[1024+1];
2443
2444   switch (err) {
2445
2446   case ENOSPC:
2447     errmsg = "The file \"%s\" could not be saved because there is no space left on the file system.";
2448     break;
2449
2450 #ifdef EDQUOT
2451   case EDQUOT:
2452     errmsg = "The file \"%s\" could not be saved because you are too close to, or over, your disk quota.";
2453     break;
2454 #endif
2455
2456   default:
2457     snprintf(errmsg_errno, sizeof(errmsg_errno),
2458                     "An error occurred while writing to the file \"%%s\": %s.",
2459                                 wtap_strerror(err));
2460     errmsg = errmsg_errno;
2461     break;
2462   }
2463   return errmsg;
2464 }
2465
2466 /* Check for write errors - if the file is being written to an NFS server,
2467    a write error may not show up until the file is closed, as NFS clients
2468    might not send writes to the server until the "write()" call finishes,
2469    so that the write may fail on the server but the "write()" may succeed. */
2470 static char *
2471 file_close_error_message(int err)
2472 {
2473   char *errmsg;
2474   static char errmsg_errno[1024+1];
2475
2476   switch (err) {
2477
2478   case WTAP_ERR_CANT_CLOSE:
2479     errmsg = "The file \"%s\" couldn't be closed for some unknown reason.";
2480     break;
2481
2482   case WTAP_ERR_SHORT_WRITE:
2483     errmsg = "Not all the packets could be written to the file \"%s\".";
2484     break;
2485
2486   case ENOSPC:
2487     errmsg = "The file \"%s\" could not be saved because there is no space left on the file system.";
2488     break;
2489
2490 #ifdef EDQUOT
2491   case EDQUOT:
2492     errmsg = "The file \"%s\" could not be saved because you are too close to, or over, your disk quota.";
2493     break;
2494 #endif
2495
2496   default:
2497     snprintf(errmsg_errno, sizeof(errmsg_errno),
2498                     "An error occurred while closing the file \"%%s\": %s.",
2499                                 wtap_strerror(err));
2500     errmsg = errmsg_errno;
2501     break;
2502   }
2503   return errmsg;
2504 }
2505
2506
2507 /* Copies a file in binary mode, for those operating systems that care about
2508  * such things.
2509  * Returns TRUE on success, FALSE on failure. If a failure, it also
2510  * displays a simple dialog window with the error message.
2511  */
2512 static gboolean
2513 copy_binary_file(char *from_filename, char *to_filename)
2514 {
2515         int           from_fd, to_fd, nread, nwritten, err;
2516         guint8        pd[65536]; /* XXX - Hmm, 64K here, 64K in save_cap_file(),
2517                                     perhaps we should make just one 64K buffer. */
2518
2519       /* Copy the raw bytes of the file. */
2520       from_fd = open(from_filename, O_RDONLY | O_BINARY);
2521       if (from_fd < 0) {
2522         err = errno;
2523         simple_dialog(ESD_TYPE_CRIT, NULL,
2524                         file_open_error_message(err, TRUE, 0), from_filename);
2525         goto done;
2526       }
2527
2528       /* Use open() instead of creat() so that we can pass the O_BINARY
2529          flag, which is relevant on Win32; it appears that "creat()"
2530          may open the file in text mode, not binary mode, but we want
2531          to copy the raw bytes of the file, so we need the output file
2532          to be open in binary mode. */
2533       to_fd = open(to_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
2534       if (to_fd < 0) {
2535         err = errno;
2536         simple_dialog(ESD_TYPE_CRIT, NULL,
2537                         file_open_error_message(err, TRUE, 0), to_filename);
2538         close(from_fd);
2539         goto done;
2540       }
2541
2542       while ((nread = read(from_fd, pd, sizeof pd)) > 0) {
2543         nwritten = write(to_fd, pd, nread);
2544         if (nwritten < nread) {
2545           if (nwritten < 0)
2546             err = errno;
2547           else
2548             err = WTAP_ERR_SHORT_WRITE;
2549           simple_dialog(ESD_TYPE_CRIT, NULL,
2550                                 file_write_error_message(err), to_filename);
2551           close(from_fd);
2552           close(to_fd);
2553           goto done;
2554         }
2555       }
2556       if (nread < 0) {
2557         err = errno;
2558         simple_dialog(ESD_TYPE_CRIT, NULL,
2559                         file_read_error_message(err), from_filename);
2560         close(from_fd);
2561         close(to_fd);
2562         goto done;
2563       }
2564       close(from_fd);
2565       if (close(to_fd) < 0) {
2566         err = errno;
2567         simple_dialog(ESD_TYPE_CRIT, NULL,
2568                 file_close_error_message(err), to_filename);
2569         goto done;
2570       }
2571
2572       return TRUE;
2573
2574    done:
2575       return FALSE;
2576 }