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