Add a Buffer to wtap_pkthdr to hold file-type-specific packet metadata.
[metze/wireshark/wip.git] / tshark.c
index 78104cada9fd2c1c9f4648c49d1c4273413c24f6..d3f31f181d21bedf8f559e5a7f2825541bc585e3 100644 (file)
--- a/tshark.c
+++ b/tshark.c
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  */
 
-#include "config.h"
+#include <config.h>
 
 #include <stdlib.h>
 #include <stdio.h>
 #include <string.h>
-#include <ctype.h>
 #include <locale.h>
 #include <limits.h>
 
 # include <sys/stat.h>
 #endif
 
+#ifdef HAVE_LIBZ
+#include <zlib.h>      /* to get the libz version number */
+#endif
+
+#ifdef HAVE_LIBCAP
+# include <sys/capability.h>
+#endif
+
 #ifndef HAVE_GETOPT
 #include "wsutil/wsgetopt.h"
 #endif
 #include <epan/exceptions.h>
 #include <epan/epan-int.h>
 #include <epan/epan.h>
+
+#include <wsutil/clopts_common.h>
+#include <wsutil/cmdarg_err.h>
 #include <wsutil/crash_info.h>
 #include <wsutil/privileges.h>
 #include <wsutil/file_util.h>
 #include <wsutil/filesystem.h>
 #include <wsutil/report_err.h>
+#include <wsutil/copyright_info.h>
+#include <wsutil/os_version_info.h>
+#include <wsutil/ws_version_info.h>
 
 #include "globals.h"
 #include <epan/timestamp.h>
 #include <epan/column.h>
 #include <epan/print.h>
 #include <epan/addr_resolv.h>
+#ifdef HAVE_LIBPCAP
+#include "ui/capture_ui_utils.h"
+#endif
 #include "ui/util.h"
 #include "ui/ui_util.h"
-#include "clopts_common.h"
-#include "cmdarg_err.h"
+#include "ui/cli/tshark-tap.h"
 #include "version_info.h"
 #include "register.h"
 #include <epan/epan_dissect.h>
 #include <epan/tap.h>
-#include <epan/stat_cmd_args.h>
+#include <epan/stat_tap_ui.h>
 #include <epan/timestamp.h>
+#include <epan/conversation_table.h>
 #include <epan/ex-opt.h>
 
 #include "capture_opts.h"
 
+#include "caputils/capture-pcap-util.h"
+
 #ifdef HAVE_LIBPCAP
-#include "capture_ui_utils.h"
-#include "capture_ifinfo.h"
-#include "capture-pcap-util.h"
+#include "caputils/capture_ifinfo.h"
 #ifdef _WIN32
-#include "capture-wpcap.h"
+#include "caputils/capture-wpcap.h"
 #include <wsutil/unicode-utils.h>
 #endif /* _WIN32 */
-#include "capture_session.h"
-#include "capture_sync.h"
+#include <capchild/capture_session.h>
+#include <capchild/capture_sync.h>
 #include "capture_opts.h"
 #endif /* HAVE_LIBPCAP */
 #include "log.h"
@@ -181,6 +197,11 @@ static void capture_cleanup(int);
 static void report_counts_siginfo(int);
 #endif /* SIGINFO */
 #endif /* _WIN32 */
+
+#else /* HAVE_LIBPCAP */
+
+static char *output_file_name;
+
 #endif /* HAVE_LIBPCAP */
 
 static int load_cap_file(capture_file *, char *, int, gboolean, int, gint64);
@@ -200,9 +221,12 @@ static void open_failure_message(const char *filename, int err,
 static void failure_message(const char *msg_format, va_list ap);
 static void read_failure_message(const char *filename, int err);
 static void write_failure_message(const char *filename, int err);
+static void failure_message_cont(const char *msg_format, va_list ap);
 
 capture_file cfile;
 
+static GHashTable *output_only_tables = NULL;
+
 struct string_elem {
   const char *sstr;   /* The short string */
   const char *lstr;   /* The long string */
@@ -267,22 +291,8 @@ list_read_capture_types(void) {
 }
 
 static void
-print_usage(gboolean print_ver)
+print_usage(FILE *output)
 {
-  FILE *output;
-
-  if (print_ver) {
-    output = stdout;
-    fprintf(output,
-        "TShark " VERSION "%s\n"
-        "Dump and analyze network traffic.\n"
-        "See http://www.wireshark.org for more information.\n"
-        "\n"
-        "%s",
-         wireshark_gitversion, get_copyright_info());
-  } else {
-    output = stderr;
-  }
   fprintf(output, "\n");
   fprintf(output, "Usage: tshark [options] ...\n");
   fprintf(output, "\n");
@@ -320,7 +330,7 @@ print_usage(gboolean print_ver)
 #endif
   /*fprintf(output, "\n");*/
   fprintf(output, "Input file:\n");
-  fprintf(output, "  -r <infile>              set the filename to read from (no stdin!)\n");
+  fprintf(output, "  -r <infile>              set the filename to read from (- to read from stdin)\n");
 
   fprintf(output, "\n");
   fprintf(output, "Processing:\n");
@@ -385,11 +395,11 @@ print_usage(gboolean print_ver)
   fprintf(output, "                           default report=\"fields\"\n");
   fprintf(output, "                           use \"-G ?\" for more help\n");
 #ifdef __linux__
-    fprintf(output, "\n");
-    fprintf(output, "WARNING: dumpcap will enable kernel BPF JIT compiler if available.\n");
-    fprintf(output, "You might want to reset it\n");
-    fprintf(output, "By doing \"echo 0 > /proc/sys/net/core/bpf_jit_enable\"\n");
-    fprintf(output, "\n");
+  fprintf(output, "\n");
+  fprintf(output, "WARNING: dumpcap will enable kernel BPF JIT compiler if available.\n");
+  fprintf(output, "You might want to reset it\n");
+  fprintf(output, "By doing \"echo 0 > /proc/sys/net/core/bpf_jit_enable\"\n");
+  fprintf(output, "\n");
 #endif
 
 }
@@ -401,7 +411,7 @@ glossary_option_help(void)
 
   output = stdout;
 
-  fprintf(output, "TShark " VERSION "%s\n", wireshark_gitversion);
+  fprintf(output, "TShark (Wireshark) %s\n", get_ws_vcs_version_info());
 
   fprintf(output, "\n");
   fprintf(output, "Usage: tshark -G [report]\n");
@@ -409,6 +419,7 @@ glossary_option_help(void)
   fprintf(output, "Glossary table reports:\n");
   fprintf(output, "  -G column-formats        dump column format codes and exit\n");
   fprintf(output, "  -G decodes               dump \"layer type\"/\"decode as\" associations and exit\n");
+  fprintf(output, "  -G dissector-tables      dump dissector table names, types, and properties\n");
   fprintf(output, "  -G fields                dump fields glossary and exit\n");
   fprintf(output, "  -G ftypes                dump field type basic and descriptive names\n");
   fprintf(output, "  -G heuristic-decodes     dump heuristic dissector tables\n");
@@ -889,30 +900,56 @@ print_current_user(void) {
   }
 }
 
-static void
-check_capture_privs(void) {
-#ifdef _WIN32
-  load_wpcap();
-  /* Warn the user if npf.sys isn't loaded. */
-  if (!npf_sys_is_running() && get_os_major_version() >= 6) {
-    fprintf(stderr, "The NPF driver isn't running.  You may have trouble "
-      "capturing or\nlisting interfaces.\n");
-  }
-#endif
-}
-
 static void
 show_version(GString *comp_info_str, GString *runtime_info_str)
 {
-  printf("TShark " VERSION "%s\n"
+  printf("TShark (Wireshark) %s\n"
          "\n"
          "%s"
          "\n"
          "%s"
          "\n"
          "%s",
-         wireshark_gitversion, get_copyright_info(), comp_info_str->str,
-         runtime_info_str->str);
+         get_ws_vcs_version_info(), get_copyright_info(),
+         comp_info_str->str, runtime_info_str->str);
+}
+
+static void
+get_tshark_compiled_version_info(GString *str)
+{
+  /* Capture libraries */
+  get_compiled_caplibs_version(str);
+
+  /* LIBZ */
+  g_string_append(str, ", ");
+#ifdef HAVE_LIBZ
+  g_string_append(str, "with libz ");
+#ifdef ZLIB_VERSION
+  g_string_append(str, ZLIB_VERSION);
+#else /* ZLIB_VERSION */
+  g_string_append(str, "(version unknown)");
+#endif /* ZLIB_VERSION */
+#else /* HAVE_LIBZ */
+  g_string_append(str, "without libz");
+#endif /* HAVE_LIBZ */
+}
+
+static void
+get_tshark_runtime_version_info(GString *str)
+{
+#ifdef HAVE_LIBPCAP
+    /* Capture libraries */
+    g_string_append(str, ", ");
+    get_runtime_caplibs_version(str);
+#endif
+
+    /* zlib */
+#if defined(HAVE_LIBZ) && !defined(_WIN32)
+    g_string_append_printf(str, ", with libz %s", zlibVersion());
+#endif
+
+    /* stuff used by libwireshark */
+    epan_get_runtime_version_info(str);
 }
 
 int
@@ -923,10 +960,9 @@ main(int argc, char *argv[])
   char                *init_progfile_dir_error;
   int                  opt;
   static const struct option long_options[] = {
-    {(char *)"capture-comment", required_argument, NULL, LONGOPT_NUM_CAP_COMMENT },
     {(char *)"help", no_argument, NULL, 'h'},
     {(char *)"version", no_argument, NULL, 'v'},
-    LONGOPT_CAPTURE_COMMON,
+    LONGOPT_CAPTURE_COMMON
     {0, 0, 0, 0 }
   };
   gboolean             arg_error = FALSE;
@@ -974,10 +1010,6 @@ main(int argc, char *argv[])
   int                  optind_initial;
   gchar               *output_only = NULL;
 
-#ifndef HAVE_LIBPCAP
-#define OPTSTRING_B ""
-#endif  /* HAVE_LIBPCAP */
-
 /* the leading - ensures that getopt() does not permute the argv[] entries
    we have to make sure that the first getopt() preserves the content of argv[]
    for the subsequent getopt_long() call */
@@ -985,21 +1017,7 @@ main(int argc, char *argv[])
 
   static const char    optstring[] = OPTSTRING;
 
-  /* Assemble the compile-time version information string */
-  comp_info_str = g_string_new("Compiled ");
-  get_compiled_version_info(comp_info_str, NULL, epan_get_compiled_version_info);
-
-  /* Assemble the run-time version information string */
-  runtime_info_str = g_string_new("Running ");
-  get_runtime_version_info(runtime_info_str, NULL);
-
-  /* Add it to the information to be reported on a crash. */
-  ws_add_crash_info("TShark " VERSION "%s\n"
-         "\n"
-         "%s"
-         "\n"
-         "%s",
-      wireshark_gitversion, comp_info_str->str, runtime_info_str->str);
+  cmdarg_err_init(failure_message, failure_message_cont);
 
 #ifdef _WIN32
   arg_list_utf_16to8(argc, argv);
@@ -1010,9 +1028,13 @@ main(int argc, char *argv[])
 #endif /* _WIN32 */
 
   /*
-   * Get credential information for later use.
+   * Get credential information for later use, and drop privileges
+   * before doing anything else.
+   * Let the user know if anything happened.
    */
   init_process_policies();
+  relinquish_special_privs_perm();
+  print_current_user();
 
   /*
    * Attempt to get the pathname of the executable file.
@@ -1023,6 +1045,36 @@ main(int argc, char *argv[])
             init_progfile_dir_error);
   }
 
+  initialize_funnel_ops();
+
+#ifdef _WIN32
+  /* Load wpcap if possible. Do this before collecting the run-time version information */
+  load_wpcap();
+
+  /* Warn the user if npf.sys isn't loaded. */
+  if (!npf_sys_is_running() && get_windows_major_version() >= 6) {
+    fprintf(stderr, "The NPF driver isn't running.  You may have trouble "
+      "capturing or\nlisting interfaces.\n");
+  }
+#endif
+
+  /* Assemble the compile-time version information string */
+  comp_info_str = g_string_new("Compiled ");
+  get_compiled_version_info(comp_info_str, get_tshark_compiled_version_info,
+                            epan_get_compiled_version_info);
+
+  /* Assemble the run-time version information string */
+  runtime_info_str = g_string_new("Running ");
+  get_runtime_version_info(runtime_info_str, get_tshark_runtime_version_info);
+
+  /* Add it to the information to be reported on a crash. */
+  ws_add_crash_info("TShark (Wireshark) %s\n"
+         "\n"
+         "%s"
+         "\n"
+         "%s",
+      get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
+
   /*
    * In order to have the -X opts assigned before the wslua machine starts
    * we need to call getopts before epan_init() gets called.
@@ -1107,8 +1159,6 @@ main(int argc, char *argv[])
                     tshark_log_handler, NULL /* user_data */);
 #endif
 
-  initialize_funnel_ops();
-
   init_report_err(failure_message, open_failure_message, read_failure_message,
                   write_failure_message);
 
@@ -1152,6 +1202,8 @@ main(int argc, char *argv[])
   register_all_plugin_tap_listeners();
 #endif
   register_all_tap_listeners();
+  conversation_table_set_gui_info(init_iousers);
+  hostlist_table_set_gui_info(NULL);  /* XXX - TODO: Provide "GUI" function for TShark */
 
   /* If invoked with the "-G" flag, we dump out information based on
      the argument to the "-G" flag; if no argument is specified,
@@ -1178,6 +1230,8 @@ main(int argc, char *argv[])
         dissector_dump_decodes();
       else if (strcmp(argv[2], "defaultprefs") == 0)
         write_prefs(NULL);
+      else if (strcmp(argv[2], "dissector-tables") == 0)
+        dissector_dump_dissector_tables();
       else if (strcmp(argv[2], "fields") == 0)
         proto_registrar_dump_fields();
       else if (strcmp(argv[2], "ftypes") == 0)
@@ -1264,8 +1318,6 @@ main(int argc, char *argv[])
     g_free(dp_path);
   }
 
-  check_capture_privs();
-
   cap_file_init(&cfile);
 
   /* Print format defaults to this. */
@@ -1305,8 +1357,16 @@ main(int argc, char *argv[])
         return status;
       }
 #else
-      capture_option_specified = TRUE;
-      arg_error = TRUE;
+      if (opt == 'w') {
+        /*
+         * Output file name, if we're reading a file and writing to another
+         * file.
+         */
+        output_file_name = optarg;
+      } else {
+        capture_option_specified = TRUE;
+        arg_error = TRUE;
+      }
 #endif
       break;
     case 'C':
@@ -1325,16 +1385,11 @@ main(int argc, char *argv[])
 #ifdef HAVE_LIBPCAP
       if_list = capture_interface_list(&err, &err_str,NULL);
       if (if_list == NULL) {
-        switch (err) {
-        case CANT_GET_INTERFACE_LIST:
-        case DONT_HAVE_PCAP:
+        if (err == 0)
+          cmdarg_err("There are no interfaces on which a capture can be done");
+        else {
           cmdarg_err("%s", err_str);
           g_free(err_str);
-          break;
-
-        case NO_INTERFACES_FOUND:
-          cmdarg_err("There are no interfaces on which a capture can be done");
-          break;
         }
         return 2;
       }
@@ -1386,7 +1441,11 @@ main(int argc, char *argv[])
       break;
 
     case 'h':        /* Print help and exit */
-      print_usage(TRUE);
+      printf("TShark (Wireshark) %s\n"
+             "Dump and analyze network traffic.\n"
+             "See http://www.wireshark.org for more information.\n",
+             get_ws_vcs_version_info());
+      print_usage(stdout);
       return 0;
       break;
     case 'l':        /* "Line-buffer" standard output */
@@ -1591,12 +1650,12 @@ main(int argc, char *argv[])
          by the preferences set callback) from being used as
          part of a tap filter.  Instead, we just add the argument
          to a list of stat arguments. */
+      if (strcmp("help", optarg) == 0) {
+        fprintf(stderr, "tshark: The available statistics for the \"-z\" option are:\n");
+        list_stat_cmd_args();
+        return 0;
+      }
       if (!process_stat_cmd_arg(optarg)) {
-        if (strcmp("help", optarg)==0) {
-          fprintf(stderr, "tshark: The available statistics for the \"-z\" option are:\n");
-          list_stat_cmd_args();
-          return 0;
-        }
         cmdarg_err("Invalid -z argument \"%s\"; it must be one of:", optarg);
         list_stat_cmd_args();
         return 1;
@@ -1609,7 +1668,7 @@ main(int argc, char *argv[])
         list_capture_types();
         break;
       default:
-        print_usage(TRUE);
+        print_usage(stderr);
       }
       return 1;
       break;
@@ -1699,7 +1758,7 @@ main(int argc, char *argv[])
     cmdarg_err("This version of TShark was not built with support for capturing packets.");
 #endif
   if (arg_error) {
-    print_usage(FALSE);
+    print_usage(stderr);
     return 1;
   }
 
@@ -1892,6 +1951,14 @@ main(int argc, char *argv[])
      of the filter.  We can now process all the "-z" arguments. */
   start_requested_stats();
 
+  /* At this point MATE will have registered its field array so we can
+     check if the fields specified by the user are all good.
+   */
+  if (!output_fields_valid(output_fields)) {
+    cmdarg_err("Some fields aren't valid");
+    return 1;
+  }
+
 #ifdef HAVE_LIBPCAP
   /* We currently don't support taps, or printing dissected packets,
      if we're writing to a pipe. */
@@ -2014,45 +2081,11 @@ main(int argc, char *argv[])
     /*
      * We're reading a capture file.
      */
-
-    /*
-     * Immediately relinquish any special privileges we have; we must not
-     * be allowed to read any capture files the user running TShark
-     * can't open.
-     */
-    relinquish_special_privs_perm();
-    print_current_user();
-
     if (cf_open(&cfile, cf_name, in_file_type, FALSE, &err) != CF_OK) {
       epan_cleanup();
       return 2;
     }
 
-    /* Set timestamp precision; there should arguably be a command-line
-       option to let the user set this. */
-    switch(wtap_file_tsprecision(cfile.wth)) {
-    case(WTAP_FILE_TSPREC_SEC):
-      timestamp_set_precision(TS_PREC_AUTO_SEC);
-      break;
-    case(WTAP_FILE_TSPREC_DSEC):
-      timestamp_set_precision(TS_PREC_AUTO_DSEC);
-      break;
-    case(WTAP_FILE_TSPREC_CSEC):
-      timestamp_set_precision(TS_PREC_AUTO_CSEC);
-      break;
-    case(WTAP_FILE_TSPREC_MSEC):
-      timestamp_set_precision(TS_PREC_AUTO_MSEC);
-      break;
-    case(WTAP_FILE_TSPREC_USEC):
-      timestamp_set_precision(TS_PREC_AUTO_USEC);
-      break;
-    case(WTAP_FILE_TSPREC_NSEC):
-      timestamp_set_precision(TS_PREC_AUTO_NSEC);
-      break;
-    default:
-      g_assert_not_reached();
-    }
-
     /* Process the packets in the file */
     TRY {
 #ifdef HAVE_LIBPCAP
@@ -2060,16 +2093,16 @@ main(int argc, char *argv[])
           global_capture_opts.has_autostop_packets ? global_capture_opts.autostop_packets : 0,
           global_capture_opts.has_autostop_filesize ? global_capture_opts.autostop_filesize : 0);
 #else
-      err = load_cap_file(&cfile, NULL, out_file_type, out_file_name_res, 0, 0);
+      err = load_cap_file(&cfile, output_file_name, out_file_type, out_file_name_res, 0, 0);
 #endif
     }
     CATCH(OutOfMemoryError) {
       fprintf(stderr,
-              "Out Of Memory!\n"
+              "Out Of Memory.\n"
               "\n"
-              "Sorry, but TShark has to terminate now!\n"
+              "Sorry, but TShark has to terminate now.\n"
               "\n"
-              "Some infos / workarounds can be found at:\n"
+              "More information and workarounds can be found at\n"
               "http://wiki.wireshark.org/KnownBugs/OutOfMemory\n");
       err = ENOMEM;
     }
@@ -2149,15 +2182,12 @@ main(int argc, char *argv[])
       print_packet_counts = TRUE;
 
     if (print_packet_info) {
-      if (!write_preamble(NULL)) {
+      if (!write_preamble(&cfile)) {
         show_print_file_io_error(errno);
         return 2;
       }
     }
 
-    /* For now, assume libpcap gives microsecond precision. */
-    timestamp_set_precision(TS_PREC_AUTO_USEC);
-
     /*
      * XXX - this returns FALSE if an error occurred, but it also
      * returns FALSE if the capture stops because a time limit
@@ -2363,30 +2393,6 @@ capture(void)
   struct sigaction  action, oldaction;
 #endif
 
-  /*
-   * XXX - dropping privileges is still required, until code cleanup is done
-   *
-   * remove all dependencies to pcap specific code and using only dumpcap is almost done.
-   * when it's done, we don't need special privileges to run tshark at all,
-   * therefore we don't need to drop these privileges
-   * The only thing we might want to keep is a warning if tshark is run as root,
-   * as it's no longer necessary and potentially dangerous.
-   *
-   * THE FOLLOWING IS THE FORMER COMMENT WHICH IS NO LONGER REALLY VALID:
-   * We've opened the capture device, so we shouldn't need any special
-   * privileges any more; relinquish those privileges.
-   *
-   * XXX - if we have saved set-user-ID support, we should give up those
-   * privileges immediately, and then reclaim them long enough to get
-   * a list of network interfaces and to open one, and then give them
-   * up again, so that stuff we do while processing the argument list,
-   * reading the user's preferences, loading and starting plugins
-   * (especially *user* plugins), etc. is done with the user's privileges,
-   * not special privileges.
-   */
-  relinquish_special_privs_perm();
-  print_current_user();
-
   /* Create new dissection section. */
   epan_free(cfile.epan);
   cfile.epan = tshark_epan_new(&cfile);
@@ -2522,11 +2528,11 @@ capture(void)
   }
   CATCH(OutOfMemoryError) {
     fprintf(stderr,
-            "Out Of Memory!\n"
+            "Out Of Memory.\n"
             "\n"
-            "Sorry, but TShark has to terminate now!\n"
+            "Sorry, but TShark has to terminate now.\n"
             "\n"
-            "Some infos / workarounds can be found at:\n"
+            "More information and workarounds can be found at\n"
             "http://wiki.wireshark.org/KnownBugs/OutOfMemory\n");
     exit(1);
   }
@@ -2556,7 +2562,7 @@ capture_input_cfilter_error_message(capture_session *cap_session, guint i, char
 
   if (dfilter_compile(interface_opts.cfilter, &rfcode) && rfcode != NULL) {
     cmdarg_err(
-      "Invalid capture filter \"%s\" for interface '%s'!\n"
+      "Invalid capture filter \"%s\" for interface '%s'.\n"
       "\n"
       "That string looks like a valid display filter; however, it isn't a valid\n"
       "capture filter (%s).\n"
@@ -2569,7 +2575,7 @@ capture_input_cfilter_error_message(capture_session *cap_session, guint i, char
     dfilter_free(rfcode);
   } else {
     cmdarg_err(
-      "Invalid capture filter \"%s\" for interface '%s'!\n"
+      "Invalid capture filter \"%s\" for interface '%s'.\n"
       "\n"
       "That string isn't a valid capture filter (%s).\n"
       "See the User's Guide for a description of the capture filter syntax.",
@@ -2583,11 +2589,12 @@ gboolean
 capture_input_new_file(capture_session *cap_session, gchar *new_file)
 {
   capture_options *capture_opts = cap_session->capture_opts;
+  capture_file *cf = (capture_file *) cap_session->cf;
   gboolean is_tempfile;
   int      err;
 
   if (cap_session->state == CAPTURE_PREPARING) {
-    g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "Capture started!");
+    g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "Capture started.");
   }
   g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "File: \"%s\"", new_file);
 
@@ -2597,16 +2604,19 @@ capture_input_new_file(capture_session *cap_session, gchar *new_file)
   if (capture_opts->save_file != NULL) {
 
     /* we start a new capture file, close the old one (if we had one before) */
-    if ( ((capture_file *) cap_session->cf)->state != FILE_CLOSED) {
-      if ( ((capture_file *) cap_session->cf)->wth != NULL) {
-        wtap_close(((capture_file *) cap_session->cf)->wth);
-       ((capture_file *) cap_session->cf)->wth = NULL;
+    if (cf->state != FILE_CLOSED) {
+      if (cf->wth != NULL) {
+        wtap_close(cf->wth);
+        cf->wth = NULL;
       }
-      ((capture_file *) cap_session->cf)->state = FILE_CLOSED;
+      cf->state = FILE_CLOSED;
     }
 
     g_free(capture_opts->save_file);
     is_tempfile = FALSE;
+
+    epan_free(cf->epan);
+    cf->epan = tshark_epan_new(cf);
   } else {
     /* we didn't had a save_file before, must be a tempfile */
     is_tempfile = TRUE;
@@ -3062,7 +3072,7 @@ load_cap_file(capture_file *cf, char *save_file, int out_file_type,
   Buffer       buf;
   epan_dissect_t *edt = NULL;
 
-  memset(&phdr, 0, sizeof(struct wtap_pkthdr));
+  wtap_phdr_init(&phdr);
 
   shb_hdr = wtap_file_get_shb_info(cf->wth);
   idb_inf = wtap_file_get_idb_info(cf->wth);
@@ -3087,7 +3097,7 @@ load_cap_file(capture_file *cf, char *save_file, int out_file_type,
     }
     /* If we don't have an application name add Tshark */
     if (shb_hdr->shb_user_appl == NULL) {
-        g_snprintf(appname, sizeof(appname), "TShark " VERSION "%s", wireshark_gitversion);
+        g_snprintf(appname, sizeof(appname), "TShark (Wireshark) %s", get_ws_vcs_version_info());
         shb_hdr->shb_user_appl = appname;
     }
 
@@ -3146,13 +3156,6 @@ load_cap_file(capture_file *cf, char *save_file, int out_file_type,
     pdh = NULL;
   }
 
-  if (pdh && out_file_name_res) {
-    if (!wtap_dump_set_addrinfo_list(pdh, get_addrinfo_list())) {
-      cmdarg_err("The file format \"%s\" doesn't support name resolution information.",
-                 wtap_file_type_subtype_short_string(out_file_type));
-    }
-  }
-
   /* Do we have any tap listeners with filters? */
   filtering_tap_listeners = have_filtering_tap_listeners();
 
@@ -3207,7 +3210,7 @@ load_cap_file(capture_file *cf, char *save_file, int out_file_type,
 
     prev_dis = NULL;
     prev_cap = NULL;
-    buffer_init(&buf, 1500);
+    ws_buffer_init(&buf, 1500);
 
     if (do_dissection) {
       gboolean create_proto_tree;
@@ -3235,7 +3238,7 @@ load_cap_file(capture_file *cf, char *save_file, int out_file_type,
              filter, so, if we're writing to a capture file, write
              this packet out. */
           if (pdh != NULL) {
-            if (!wtap_dump(pdh, &phdr, buffer_start_ptr(&buf), &err)) {
+            if (!wtap_dump(pdh, &phdr, ws_buffer_start_ptr(&buf), &err)) {
               /* Error writing to a capture file */
               switch (err) {
 
@@ -3287,7 +3290,7 @@ load_cap_file(capture_file *cf, char *save_file, int out_file_type,
       edt = NULL;
     }
 
-    buffer_free(&buf);
+    ws_buffer_free(&buf);
   }
   else {
     framenum = 0;
@@ -3373,6 +3376,8 @@ load_cap_file(capture_file *cf, char *save_file, int out_file_type,
     }
   }
 
+  wtap_phdr_cleanup(&phdr);
+
   if (err != 0) {
     /*
      * Print a message noting that the read failed somewhere along the line.
@@ -3387,9 +3392,9 @@ load_cap_file(capture_file *cf, char *save_file, int out_file_type,
      */
 #ifndef _WIN32
     if (print_packet_info) {
-      struct stat stat_stdout, stat_stderr;
+      ws_statb64 stat_stdout, stat_stderr;
 
-      if (fstat(1, &stat_stdout) == 0 && fstat(2, &stat_stderr) == 0) {
+      if (ws_fstat64(1, &stat_stdout) == 0 && ws_fstat64(2, &stat_stderr) == 0) {
         if (stat_stdout.st_dev == stat_stderr.st_dev &&
             stat_stdout.st_ino == stat_stderr.st_ino) {
           fflush(stdout);
@@ -3412,11 +3417,6 @@ load_cap_file(capture_file *cf, char *save_file, int out_file_type,
       g_free(err_info);
       break;
 
-    case WTAP_ERR_CANT_READ:
-      cmdarg_err("An attempt to read from the file \"%s\" failed for some unknown reason.",
-                 cf->filename);
-      break;
-
     case WTAP_ERR_SHORT_READ:
       cmdarg_err("The file \"%s\" appears to have been cut short in the middle of a packet.",
                  cf->filename);
@@ -3431,6 +3431,7 @@ load_cap_file(capture_file *cf, char *save_file, int out_file_type,
     case WTAP_ERR_DECOMPRESS:
       cmdarg_err("The compressed file \"%s\" appears to be damaged or corrupt.\n"
                  "(%s)", cf->filename, err_info);
+      g_free(err_info);
       break;
 
     default:
@@ -3445,6 +3446,12 @@ load_cap_file(capture_file *cf, char *save_file, int out_file_type,
     }
   } else {
     if (save_file != NULL) {
+      if (pdh && out_file_name_res) {
+        if (!wtap_dump_set_addrinfo_list(pdh, get_addrinfo_list())) {
+          cmdarg_err("The file format \"%s\" doesn't support name resolution information.",
+                     wtap_file_type_subtype_short_string(out_file_type));
+        }
+      }
       /* Now close the capture file. */
       if (!wtap_dump_close(pdh, &err))
         show_capture_file_io_error(save_file, err, TRUE);
@@ -3587,13 +3594,13 @@ write_preamble(capture_file *cf)
   switch (output_action) {
 
   case WRITE_TEXT:
-    return print_preamble(print_stream, cf ? cf->filename : NULL, wireshark_gitversion);
+    return print_preamble(print_stream, cf->filename, get_ws_vcs_version_info());
 
   case WRITE_XML:
     if (print_details)
-      write_pdml_preamble(stdout, cf ? cf->filename : NULL);
+      write_pdml_preamble(stdout, cf->filename);
     else
-      write_psml_preamble(stdout);
+      write_psml_preamble(&cf->cinfo, stdout);
     return !ferror(stdout);
 
   case WRITE_FIELDS:
@@ -3898,7 +3905,7 @@ print_packet(capture_file *cf, epan_dissect_t *edt)
         break;
 
       case WRITE_XML:
-        proto_tree_write_psml(edt, stdout);
+        write_psml_columns(edt, stdout);
         return !ferror(stdout);
       case WRITE_FIELDS: /*No non-verbose "fields" format */
         g_assert_not_reached();
@@ -3923,7 +3930,7 @@ print_packet(capture_file *cf, epan_dissect_t *edt)
       print_args.print_hex = print_hex;
       print_args.print_dissections = print_details ? print_dissections_expanded : print_dissections_none;
 
-      if (!proto_tree_print(&print_args, edt, print_stream))
+      if (!proto_tree_print(&print_args, edt, output_only_tables, print_stream))
         return FALSE;
       if (!print_hex) {
         if (!print_line(print_stream, 0, separator))
@@ -3932,11 +3939,11 @@ print_packet(capture_file *cf, epan_dissect_t *edt)
       break;
 
     case WRITE_XML:
-      proto_tree_write_pdml(edt, stdout);
+      write_pdml_proto_tree(edt, stdout);
       printf("\n");
       return !ferror(stdout);
     case WRITE_FIELDS:
-      proto_tree_write_fields(output_fields, edt, &cf->cinfo, stdout);
+      write_fields_proto_tree(output_fields, edt, &cf->cinfo, stdout);
       printf("\n");
       return !ferror(stdout);
     }
@@ -4244,7 +4251,6 @@ open_failure_message(const char *filename, int err, gboolean for_writing)
   fprintf(stderr, "\n");
 }
 
-
 /*
  * General errors are reported with an console message in TShark.
  */
@@ -4276,34 +4282,16 @@ write_failure_message(const char *filename, int err)
           filename, g_strerror(err));
 }
 
-/*
- * Report an error in command-line arguments.
- */
-void
-cmdarg_err(const char *fmt, ...)
-{
-  va_list ap;
-
-  va_start(ap, fmt);
-  failure_message(fmt, ap);
-  va_end(ap);
-}
-
 /*
  * Report additional information for an error in command-line arguments.
  */
-void
-cmdarg_err_cont(const char *fmt, ...)
+static void
+failure_message_cont(const char *msg_format, va_list ap)
 {
-  va_list ap;
-
-  va_start(ap, fmt);
-  vfprintf(stderr, fmt, ap);
+  vfprintf(stderr, msg_format, ap);
   fprintf(stderr, "\n");
-  va_end(ap);
 }
 
-
 /*
  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
  *