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