Reassemble: fix premature free
[metze/wireshark/wip.git] / tfshark.c
index 2d4315d9a2943789dbeaffc64b9ab5571225adfa..292158ee6a47990c1c557edee63506954992fa2f 100644 (file)
--- a/tfshark.c
+++ b/tfshark.c
 #include <locale.h>
 #include <limits.h>
 
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-
 #ifdef HAVE_GETOPT_H
 #include <getopt.h>
 #endif
 
 #include <errno.h>
 
-#ifdef HAVE_FCNTL_H
-#include <fcntl.h>
-#endif
-
-#include <signal.h>
-
-#ifdef HAVE_SYS_STAT_H
-# include <sys/stat.h>
-#endif
-
-#ifdef HAVE_LIBZ
-#include <zlib.h>      /* to get the libz version number */
-#endif
-
-#ifndef HAVE_GETOPT
+#ifndef HAVE_GETOPT_LONG
 #include "wsutil/wsgetopt.h"
 #endif
 
 #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/file_util.h>
+#include <wsutil/privileges.h>
 #include <wsutil/report_err.h>
-#include <wsutil/copyright_info.h>
-#include <wsutil/ws_version_info.h>
+#include <ws_version_info.h>
 
 #include "globals.h"
 #include <epan/timestamp.h>
 #include <epan/print.h>
 #include <epan/addr_resolv.h>
 #include "ui/util.h"
-#include "version_info.h"
+#include "ui/decode_as_utils.h"
+#include "ui/dissect_opts.h"
 #include "register.h"
 #include <epan/epan_dissect.h>
 #include <epan/tap.h>
 #include <epan/stat_tap_ui.h>
-#include <epan/timestamp.h>
 #include <epan/ex-opt.h>
+
+#ifdef HAVE_EXTCAP
+#include "extcap.h"
+#endif
+
 #include <wiretap/wtap-int.h>
 #include <wiretap/file_wrappers.h>
 
 #include <wsutil/plugins.h>
 #endif
 
-/*
- * This is the template for the decode as option; it is shared between the
- * various functions that output the usage for this parameter.
- */
-static const gchar decode_as_arg_template[] = "<layer_type>==<selector>,<decode_as_protocol>";
-
 static guint32 cum_bytes;
 static const frame_data *ref;
 static frame_data ref_frame;
@@ -122,8 +102,6 @@ static frame_data prev_dis_frame;
 static frame_data *prev_cap;
 static frame_data prev_cap_frame;
 
-static const char* prev_display_dissector_name = NULL;
-
 static gboolean perform_two_pass_analysis;
 
 /*
@@ -213,7 +191,7 @@ print_usage(FILE *output)
   fprintf(output, "  -R <read filter>         packet Read filter in Wireshark display filter syntax\n");
   fprintf(output, "  -Y <display filter>      packet displaY filter in Wireshark display filter\n");
   fprintf(output, "                           syntax\n");
-  fprintf(output, "  -d %s ...\n", decode_as_arg_template);
+  fprintf(output, "  -d %s ...\n", DECODE_AS_ARG_TEMPLATE);
   fprintf(output, "                           \"Decode As\", see the man page for details\n");
   fprintf(output, "                           Example: tcp.port==8888,http\n");
 
@@ -285,413 +263,6 @@ glossary_option_help(void)
   fprintf(output, "\n");
 }
 
-/*
- * For a dissector table, print on the stream described by output,
- * its short name (which is what's used in the "-d" option) and its
- * descriptive name.
- */
-static void
-display_dissector_table_names(const char *table_name, const char *ui_name,
-                              gpointer output)
-{
-  if ((prev_display_dissector_name == NULL) ||
-      (strcmp(prev_display_dissector_name, table_name) != 0)) {
-     fprintf((FILE *)output, "\t%s (%s)\n", table_name, ui_name);
-     prev_display_dissector_name = table_name;
-  }
-}
-
-/*
- * For a dissector handle, print on the stream described by output,
- * the filter name (which is what's used in the "-d" option) and the full
- * name for the protocol that corresponds to this handle.
- */
-static void
-display_dissector_names(const gchar *table _U_, gpointer handle, gpointer output)
-{
-  int          proto_id;
-  const gchar *proto_filter_name;
-  const gchar *proto_ui_name;
-
-  proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
-
-  if (proto_id != -1) {
-    proto_filter_name = proto_get_protocol_filter_name(proto_id);
-    proto_ui_name =  proto_get_protocol_name(proto_id);
-    g_assert(proto_filter_name != NULL);
-    g_assert(proto_ui_name != NULL);
-
-    if ((prev_display_dissector_name == NULL) ||
-        (strcmp(prev_display_dissector_name, proto_filter_name) != 0)) {
-      fprintf((FILE *)output, "\t%s (%s)\n",
-              proto_filter_name,
-              proto_ui_name);
-       prev_display_dissector_name = proto_filter_name;
-    }
-  }
-}
-
-/*
- * The protocol_name_search structure is used by find_protocol_name_func()
- * to pass parameters and store results
- */
-struct protocol_name_search{
-  gchar              *searched_name;  /* Protocol filter name we are looking for */
-  dissector_handle_t  matched_handle; /* Handle for a dissector whose protocol has the specified filter name */
-  guint               nb_match;       /* How many dissectors matched searched_name */
-};
-typedef struct protocol_name_search *protocol_name_search_t;
-
-/*
- * This function parses all dissectors associated with a table to find the
- * one whose protocol has the specified filter name.  It is called
- * as a reference function in a call to dissector_table_foreach_handle.
- * The name we are looking for, as well as the results, are stored in the
- * protocol_name_search struct pointed to by user_data.
- * If called using dissector_table_foreach_handle, we actually parse the
- * whole list of dissectors.
- */
-static void
-find_protocol_name_func(const gchar *table _U_, gpointer handle, gpointer user_data)
-
-{
-  int                     proto_id;
-  const gchar            *protocol_filter_name;
-  protocol_name_search_t  search_info;
-
-  g_assert(handle);
-
-  search_info = (protocol_name_search_t)user_data;
-
-  proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
-  if (proto_id != -1) {
-    protocol_filter_name = proto_get_protocol_filter_name(proto_id);
-    g_assert(protocol_filter_name != NULL);
-    if (strcmp(protocol_filter_name, search_info->searched_name) == 0) {
-      /* Found a match */
-      if (search_info->nb_match == 0) {
-        /* Record this handle only if this is the first match */
-        search_info->matched_handle = (dissector_handle_t)handle; /* Record the handle for this matching dissector */
-      }
-      search_info->nb_match++;
-    }
-  }
-}
-
-/*
- * Allow dissector key names to be sorted alphabetically
- */
-
-static gint
-compare_dissector_key_name(gconstpointer dissector_a, gconstpointer dissector_b)
-{
-  return strcmp((const char*)dissector_a, (const char*)dissector_b);
-}
-
-/*
- * Print all layer type names supported.
- * We send the output to the stream described by the handle output.
- */
-
-static void
-fprint_all_layer_types(FILE *output)
-
-{
-  prev_display_dissector_name = NULL;
-  dissector_all_tables_foreach_table(display_dissector_table_names, (gpointer)output, (GCompareFunc)compare_dissector_key_name);
-}
-
-/*
- * Print all protocol names supported for a specific layer type.
- * table_name contains the layer type name in which the search is performed.
- * We send the output to the stream described by the handle output.
- */
-
-static void
-fprint_all_protocols_for_layer_types(FILE *output, gchar *table_name)
-
-{
-  prev_display_dissector_name = NULL;
-  dissector_table_foreach_handle(table_name,
-                                 display_dissector_names,
-                                 (gpointer)output);
-}
-
-/*
- * The function below parses the command-line parameters for the decode as
- * feature (a string pointer by cl_param).
- * It checks the format of the command-line, searches for a matching table
- * and dissector.  If a table/dissector match is not found, we display a
- * summary of the available tables/dissectors (on stderr) and return FALSE.
- * If everything is fine, we get the "Decode as" preference activated,
- * then we return TRUE.
- */
-static gboolean
-add_decode_as(const gchar *cl_param)
-{
-  gchar                        *table_name;
-  guint32                       selector, selector2;
-  gchar                        *decoded_param;
-  gchar                        *remaining_param;
-  gchar                        *selector_str;
-  gchar                        *dissector_str;
-  dissector_handle_t            dissector_matching;
-  dissector_table_t             table_matching;
-  ftenum_t                      dissector_table_selector_type;
-  struct protocol_name_search   user_protocol_name;
-  guint64                       i;
-  char                          op;
-
-  /* The following code will allocate and copy the command-line options in a string pointed by decoded_param */
-
-  g_assert(cl_param);
-  decoded_param = g_strdup(cl_param);
-  g_assert(decoded_param);
-
-
-  /* The lines below will parse this string (modifying it) to extract all
-    necessary information.  Note that decoded_param is still needed since
-    strings are not copied - we just save pointers. */
-
-  /* This section extracts a layer type (table_name) from decoded_param */
-  table_name = decoded_param; /* Layer type string starts from beginning */
-
-  remaining_param = strchr(table_name, '=');
-  if (remaining_param == NULL) {
-    cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
-    /* If the argument does not follow the template, carry on anyway to check
-       if the table name is at least correct.  If remaining_param is NULL,
-       we'll exit anyway further down */
-  }
-  else {
-    *remaining_param = '\0'; /* Terminate the layer type string (table_name) where '=' was detected */
-  }
-
-  /* Remove leading and trailing spaces from the table name */
-  while ( table_name[0] == ' ' )
-    table_name++;
-  while ( table_name[strlen(table_name) - 1] == ' ' )
-    table_name[strlen(table_name) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
-
-/* The following part searches a table matching with the layer type specified */
-  table_matching = NULL;
-
-/* Look for the requested table */
-  if ( !(*(table_name)) ) { /* Is the table name empty, if so, don't even search for anything, display a message */
-    cmdarg_err("No layer type specified"); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
-  }
-  else {
-    table_matching = find_dissector_table(table_name);
-    if (!table_matching) {
-      cmdarg_err("Unknown layer type -- %s", table_name); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
-    }
-  }
-
-  if (!table_matching) {
-    /* Display a list of supported layer types to help the user, if the
-       specified layer type was not found */
-    cmdarg_err("Valid layer types are:");
-    fprint_all_layer_types(stderr);
-  }
-  if (remaining_param == NULL || !table_matching) {
-    /* Exit if the layer type was not found, or if no '=' separator was found
-       (see above) */
-    g_free(decoded_param);
-    return FALSE;
-  }
-
-  if (*(remaining_param + 1) != '=') { /* Check for "==" and not only '=' */
-    cmdarg_err("WARNING: -d requires \"==\" instead of \"=\". Option will be treated as \"%s==%s\"", table_name, remaining_param + 1);
-  }
-  else {
-    remaining_param++; /* Move to the second '=' */
-    *remaining_param = '\0'; /* Remove the second '=' */
-  }
-  remaining_param++; /* Position after the layer type string */
-
-  /* This section extracts a selector value (selector_str) from decoded_param */
-
-  selector_str = remaining_param; /* Next part starts with the selector number */
-
-  remaining_param = strchr(selector_str, ',');
-  if (remaining_param == NULL) {
-    cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
-    /* If the argument does not follow the template, carry on anyway to check
-       if the selector value is at least correct.  If remaining_param is NULL,
-       we'll exit anyway further down */
-  }
-  else {
-    *remaining_param = '\0'; /* Terminate the selector number string (selector_str) where ',' was detected */
-  }
-
-  dissector_table_selector_type = get_dissector_table_selector_type(table_name);
-
-  switch (dissector_table_selector_type) {
-
-  case FT_UINT8:
-  case FT_UINT16:
-  case FT_UINT24:
-  case FT_UINT32:
-    /* The selector for this table is an unsigned number.  Parse it as such.
-       There's no need to remove leading and trailing spaces from the
-       selector number string, because sscanf will do that for us. */
-    switch (sscanf(selector_str, "%u%c%u", &selector, &op, &selector2)) {
-      case 1:
-        op = '\0';
-        break;
-      case 3:
-        if (op != ':' && op != '-') {
-            cmdarg_err("Invalid selector numeric range \"%s\"", selector_str);
-            g_free(decoded_param);
-            return FALSE;
-        }
-        if (op == ':') {
-            if ((selector2 == 0) || ((guint64)selector + selector2 - 1) > G_MAXUINT32) {
-                cmdarg_err("Invalid selector numeric range \"%s\"", selector_str);
-                g_free(decoded_param);
-                return FALSE;
-            }
-        }
-        else if (selector2 < selector) {
-            /* We could swap them for the user, but maybe it's better to call
-             * this out as an error in case it's not what was intended? */
-            cmdarg_err("Invalid selector numeric range \"%s\"", selector_str);
-            g_free(decoded_param);
-            return FALSE;
-        }
-        break;
-      default:
-        cmdarg_err("Invalid selector number \"%s\"", selector_str);
-        g_free(decoded_param);
-        return FALSE;
-    }
-    break;
-
-  case FT_STRING:
-  case FT_STRINGZ:
-  case FT_UINT_STRING:
-  case FT_STRINGZPAD:
-    /* The selector for this table is a string. */
-    break;
-
-  default:
-    /* There are currently no dissector tables with any types other
-       than the ones listed above. */
-    g_assert_not_reached();
-  }
-
-  if (remaining_param == NULL) {
-    /* Exit if no ',' separator was found (see above) */
-    cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
-    fprint_all_protocols_for_layer_types(stderr, table_name);
-    g_free(decoded_param);
-    return FALSE;
-  }
-
-  remaining_param++; /* Position after the selector number string */
-
-  /* This section extracts a protocol filter name (dissector_str) from decoded_param */
-
-  dissector_str = remaining_param; /* All the rest of the string is the dissector (decode as protocol) name */
-
-  /* Remove leading and trailing spaces from the dissector name */
-  while ( dissector_str[0] == ' ' )
-    dissector_str++;
-  while ( dissector_str[strlen(dissector_str) - 1] == ' ' )
-    dissector_str[strlen(dissector_str) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
-
-  dissector_matching = NULL;
-
-  /* We now have a pointer to the handle for the requested table inside the variable table_matching */
-  if ( ! (*dissector_str) ) { /* Is the dissector name empty, if so, don't even search for a matching dissector and display all dissectors found for the selected table */
-    cmdarg_err("No protocol name specified"); /* Note, we don't exit here, but dissector_matching will remain NULL, so we exit below */
-  }
-  else {
-    user_protocol_name.nb_match = 0;
-    user_protocol_name.searched_name = dissector_str;
-    user_protocol_name.matched_handle = NULL;
-
-    dissector_table_foreach_handle(table_name, find_protocol_name_func, &user_protocol_name); /* Go and perform the search for this dissector in the this table's dissectors' names and shortnames */
-
-    if (user_protocol_name.nb_match != 0) {
-      dissector_matching = user_protocol_name.matched_handle;
-      if (user_protocol_name.nb_match > 1) {
-        cmdarg_err("WARNING: Protocol \"%s\" matched %u dissectors, first one will be used", dissector_str, user_protocol_name.nb_match);
-      }
-    }
-    else {
-      /* OK, check whether the problem is that there isn't any such
-         protocol, or that there is but it's not specified as a protocol
-         that's valid for that dissector table.
-         Note, we don't exit here, but dissector_matching will remain NULL,
-         so we exit below */
-      if (proto_get_id_by_filter_name(dissector_str) == -1) {
-        /* No such protocol */
-        cmdarg_err("Unknown protocol -- \"%s\"", dissector_str);
-      } else {
-        cmdarg_err("Protocol \"%s\" isn't valid for layer type \"%s\"",
-                   dissector_str, table_name);
-      }
-    }
-  }
-
-  if (!dissector_matching) {
-    cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
-    fprint_all_protocols_for_layer_types(stderr, table_name);
-    g_free(decoded_param);
-    return FALSE;
-  }
-
-/* This is the end of the code that parses the command-line options.
-   All information is now stored in the variables:
-   table_name
-   selector
-   dissector_matching
-   The above variables that are strings are still pointing to areas within
-   decoded_parm.  decoded_parm thus still needs to be kept allocated in
-   until we stop needing these variables
-   decoded_param will be deallocated at each exit point of this function */
-
-
-  /* We now have a pointer to the handle for the requested dissector
-     (requested protocol) inside the variable dissector_matching */
-  switch (dissector_table_selector_type) {
-
-  case FT_UINT8:
-  case FT_UINT16:
-  case FT_UINT24:
-  case FT_UINT32:
-    /* The selector for this table is an unsigned number. */
-    if (op == '\0') {
-      dissector_change_uint(table_name, selector, dissector_matching);
-    } else if (op == ':') {
-      for (i = selector; i < (guint64)selector + selector2; i++) {
-        dissector_change_uint(table_name, (guint32)i, dissector_matching);
-      }
-    } else { /* op == '-' */
-      for (i = selector; i <= selector2; i++) {
-        dissector_change_uint(table_name, (guint32)i, dissector_matching);
-      }
-    }
-    break;
-
-  case FT_STRING:
-  case FT_STRINGZ:
-  case FT_UINT_STRING:
-  case FT_STRINGZPAD:
-    /* The selector for this table is a string. */
-    dissector_change_string(table_name, selector_str, dissector_matching);
-    break;
-
-  default:
-    /* There are currently no dissector tables with any types other
-       than the ones listed above. */
-    g_assert_not_reached();
-  }
-  g_free(decoded_param); /* "Decode As" rule has been successfully added */
-  return TRUE;
-}
-
 static void
 tfshark_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
     const gchar *message, gpointer user_data)
@@ -736,44 +307,9 @@ print_current_user(void) {
   }
 }
 
-static void
-show_version(GString *comp_info_str, GString *runtime_info_str)
-{
-  printf("TFShark (Wireshark) %s\n"
-         "\n"
-         "%s"
-         "\n"
-         "%s"
-         "\n"
-         "%s",
-         get_ws_vcs_version_info(), get_copyright_info(), comp_info_str->str,
-         runtime_info_str->str);
-}
-
-static void
-get_tfshark_compiled_version_info(GString *str)
-{
-  /* LIBZ */
-#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_tfshark_runtime_version_info(GString *str)
 {
-  /* 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);
 }
@@ -786,8 +322,8 @@ main(int argc, char *argv[])
   char                *init_progfile_dir_error;
   int                  opt;
   static const struct option long_options[] = {
-    {(char *)"help", no_argument, NULL, 'h'},
-    {(char *)"version", no_argument, NULL, 'v'},
+    {"help", no_argument, NULL, 'h'},
+    {"version", no_argument, NULL, 'v'},
     {0, 0, 0, 0 }
   };
   gboolean             arg_error = FALSE;
@@ -806,18 +342,37 @@ main(int argc, char *argv[])
   gchar               *dfilter = NULL;
   dfilter_t           *rfcode = NULL;
   dfilter_t           *dfcode = NULL;
+  gchar               *err_msg;
   e_prefs             *prefs_p;
   int                  log_flags;
-  int                  optind_initial;
   gchar               *output_only = NULL;
 
-/* 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 */
-#define OPTSTRING "-2C:d:e:E:hK:lo:O:qQr:R:S:t:T:u:vVxX:Y:z:"
+/*
+ * The leading + ensures that getopt_long() does not permute the argv[]
+ * entries.
+ *
+ * We have to make sure that the first getopt_long() preserves the content
+ * of argv[] for the subsequent getopt_long() call.
+ *
+ * We use getopt_long() in both cases to ensure that we're using a routine
+ * whose permutation behavior we can control in the same fashion on all
+ * platforms, and so that, if we ever need to process a long argument before
+ * doing further initialization, we can do so.
+ *
+ * Glibc and Solaris libc document that a leading + disables permutation
+ * of options, regardless of whether POSIXLY_CORRECT is set or not; *BSD
+ * and OS X don't document it, but do so anyway.
+ *
+ * We do *not* use a leading - because the behavior of a leading - is
+ * platform-dependent.
+ */
+#define OPTSTRING "+2C:d:e:E:hK:lo:O:qQr:R:S:t:T:u:vVxX:Y:z:"
 
   static const char    optstring[] = OPTSTRING;
 
+  /* Set the C-language locale to the native environment. */
+  setlocale(LC_ALL, "");
+
   cmdarg_err_init(failure_message, failure_message_cont);
 
 #ifdef _WIN32
@@ -848,14 +403,11 @@ main(int argc, char *argv[])
 
   initialize_funnel_ops();
 
-  /* Assemble the compile-time version information string */
-  comp_info_str = g_string_new("Compiled ");
-  get_compiled_version_info(comp_info_str, get_tfshark_compiled_version_info,
-                            epan_get_compiled_version_info);
+  /* Get the compile-time version information string */
+  comp_info_str = get_compiled_version_info(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, get_tfshark_runtime_version_info);
+  /* Get the run-time version information string */
+  runtime_info_str = get_runtime_version_info(get_tfshark_runtime_version_info);
 
   /* Add it to the information to be reported on a crash. */
   ws_add_crash_info("TFShark (Wireshark) %s\n"
@@ -864,15 +416,24 @@ main(int argc, char *argv[])
          "\n"
          "%s",
       get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
+  g_string_free(comp_info_str, TRUE);
+  g_string_free(runtime_info_str, TRUE);
 
   /*
    * In order to have the -X opts assigned before the wslua machine starts
    * we need to call getopts before epan_init() gets called.
+   *
+   * In order to handle, for example, -o options, we also need to call it
+   * *after* epan_init() gets called, so that the dissectors have had a
+   * chance to register their preferences.
+   *
+   * XXX - can we do this all with one getopt_long() call, saving the
+   * arguments we can't handle until after initializing libwireshark,
+   * and then process them after initializing libwireshark?
    */
   opterr = 0;
-  optind_initial = optind;
 
-  while ((opt = getopt(argc, argv, optstring)) != -1) {
+  while ((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
     switch (opt) {
     case 'C':        /* Configuration Profile */
       if (profile_exists (optarg, FALSE)) {
@@ -913,11 +474,6 @@ main(int argc, char *argv[])
   if (print_summary == -1)
     print_summary = (print_details || print_hex) ? FALSE : TRUE;
 
-  optind = optind_initial;
-  opterr = 1;
-
-
-
 /** Send All g_log messages to our own handler **/
 
   log_flags =
@@ -951,7 +507,7 @@ main(int argc, char *argv[])
 
   /* Scan for plugins.  This does *not* call their registration routines;
      that's done later. */
-  scan_plugins();
+  scan_plugins(REPORT_LOAD_FAILURE);
 
 #endif
 
@@ -959,7 +515,9 @@ main(int argc, char *argv[])
      "-G" flag, as the "-G" flag dumps information registered by the
      dissectors, and we must do it before we read the preferences, in
      case any dissectors register preferences. */
-  epan_init(register_all_protocols, register_all_protocol_handoffs, NULL, NULL);
+  if (!epan_init(register_all_protocols, register_all_protocol_handoffs, NULL,
+                 NULL))
+    return 2;
 
   /* Register all tap listeners; we do this before we parse the arguments,
      as the "-z" argument can specify a registered tap. */
@@ -1033,9 +591,6 @@ main(int argc, char *argv[])
     return 0;
   }
 
-  /* Set the C-language locale to the native environment. */
-  setlocale(LC_ALL, "");
-
   prefs_p = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
                      &pf_open_errno, &pf_read_errno, &pf_path);
   if (gpf_path != NULL) {
@@ -1064,6 +619,8 @@ main(int argc, char *argv[])
   /* Read the disabled protocols file. */
   read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
                             &dp_path, &dp_open_errno, &dp_read_errno);
+  read_disabled_heur_dissector_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
+                            &dp_path, &dp_open_errno, &dp_read_errno);
   if (gdp_path != NULL) {
     if (gdp_open_errno != 0) {
       cmdarg_err("Could not open global disabled protocols file\n\"%s\": %s.",
@@ -1096,6 +653,28 @@ main(int argc, char *argv[])
 
   output_fields = output_fields_new();
 
+  /*
+   * To reset the options parser, set optreset to 1 on platforms that
+   * have optreset (documented in *BSD and OS X, apparently present but
+   * not documented in Solaris - the Illumos repository seems to
+   * suggest that the first Solaris getopt_long(), at least as of 2004,
+   * was based on the NetBSD one, it had optreset) and set optind to 1,
+   * and set optind to 0 otherwise (documented as working in the GNU
+   * getopt_long().  Setting optind to 0 didn't originally work in the
+   * NetBSD one, but that was added later - we don't want to depend on
+   * it if we have optreset).
+   *
+   * Also reset opterr to 1, so that error messages are printed by
+   * getopt_long().
+   */
+#ifdef HAVE_OPTRESET
+  optreset = 1;
+  optind = 1;
+#else
+  optind = 0;
+#endif
+  opterr = 1;
+
   /* Now get our args */
   while ((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
     switch (opt) {
@@ -1103,17 +682,8 @@ main(int argc, char *argv[])
       perform_two_pass_analysis = TRUE;
       break;
     case 'C':
-      /* Configuration profile settings were already processed just ignore them this time*/
-      break;
-    case 'd':        /* Decode as rule */
-      if (!add_decode_as(optarg))
-        return 1;
-      break;
-#if defined(HAVE_HEIMDAL_KERBEROS) || defined(HAVE_MIT_KERBEROS)
-    case 'K':        /* Kerberos keytab file */
-      read_keytab_file(optarg);
+      /* already processed; just ignore it now */
       break;
-#endif
     case 'e':
       /* Field entry */
       output_fields_add(output_fields, optarg);
@@ -1130,7 +700,7 @@ main(int argc, char *argv[])
     case 'h':        /* Print help and exit */
       printf("TFShark (Wireshark) %s\n"
              "Dump and analyze network traffic.\n"
-             "See http://www.wireshark.org for more information.\n",
+             "See https://www.wireshark.org for more information.\n",
              get_ws_vcs_version_info());
       print_usage(stdout);
       return 0;
@@ -1184,42 +754,6 @@ main(int argc, char *argv[])
     case 'S':        /* Set the line Separator to be printed between packets */
       separator = g_strdup(optarg);
       break;
-    case 't':        /* Time stamp type */
-      if (strcmp(optarg, "r") == 0)
-        timestamp_set_type(TS_RELATIVE);
-      else if (strcmp(optarg, "a") == 0)
-        timestamp_set_type(TS_ABSOLUTE);
-      else if (strcmp(optarg, "ad") == 0)
-        timestamp_set_type(TS_ABSOLUTE_WITH_YMD);
-      else if (strcmp(optarg, "adoy") == 0)
-        timestamp_set_type(TS_ABSOLUTE_WITH_YDOY);
-      else if (strcmp(optarg, "d") == 0)
-        timestamp_set_type(TS_DELTA);
-      else if (strcmp(optarg, "dd") == 0)
-        timestamp_set_type(TS_DELTA_DIS);
-      else if (strcmp(optarg, "e") == 0)
-        timestamp_set_type(TS_EPOCH);
-      else if (strcmp(optarg, "u") == 0)
-        timestamp_set_type(TS_UTC);
-      else if (strcmp(optarg, "ud") == 0)
-        timestamp_set_type(TS_UTC_WITH_YMD);
-      else if (strcmp(optarg, "udoy") == 0)
-        timestamp_set_type(TS_UTC_WITH_YDOY);
-      else {
-        cmdarg_err("Invalid time stamp type \"%s\"; it must be one of:", optarg);
-        cmdarg_err_cont("\t\"a\"    for absolute\n"
-                        "\t\"ad\"   for absolute with YYYY-MM-DD date\n"
-                        "\t\"adoy\" for absolute with YYYY/DOY date\n"
-                        "\t\"d\"    for delta\n"
-                        "\t\"dd\"   for delta displayed\n"
-                        "\t\"e\"    for epoch\n"
-                        "\t\"r\"    for relative\n"
-                        "\t\"u\"    for absolute UTC\n"
-                        "\t\"ud\"   for absolute UTC with YYYY-MM-DD date\n"
-                        "\t\"udoy\" for absolute UTC with YYYY/DOY date");
-        return 1;
-      }
-      break;
     case 'T':        /* printing Type */
       if (strcmp(optarg, "text") == 0) {
         output_action = WRITE_TEXT;
@@ -1260,21 +794,10 @@ main(int argc, char *argv[])
         return 1;
       }
       break;
-    case 'u':        /* Seconds type */
-      if (strcmp(optarg, "s") == 0)
-        timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
-      else if (strcmp(optarg, "hms") == 0)
-        timestamp_set_seconds_type(TS_SECONDS_HOUR_MIN_SEC);
-      else {
-        cmdarg_err("Invalid seconds type \"%s\"; it must be one of:", optarg);
-        cmdarg_err_cont("\t\"s\"   for seconds\n"
-                        "\t\"hms\" for hours, minutes and seconds");
-        return 1;
-      }
-      break;
     case 'v':         /* Show version and exit */
-    {
-      show_version(comp_info_str, runtime_info_str);
+      comp_info_str = get_compiled_version_info(NULL, epan_get_compiled_version_info);
+      runtime_info_str = get_runtime_version_info(get_tfshark_runtime_version_info);
+      show_version("TFShark (Wireshark)", comp_info_str, runtime_info_str);
       g_string_free(comp_info_str, TRUE);
       g_string_free(runtime_info_str, TRUE);
       /* We don't really have to cleanup here, but it's a convenient way to test
@@ -1283,8 +806,10 @@ main(int argc, char *argv[])
        * $ ./tools/valgrind-wireshark -n
        * much more useful. */
       epan_cleanup();
+#ifdef HAVE_EXTCAP
+      extcap_cleanup();
+#endif
       return 0;
-    }
     case 'O':        /* Only output these protocols */
       /* already processed; just ignore it now */
       break;
@@ -1295,6 +820,7 @@ main(int argc, char *argv[])
       /* already processed; just ignore it now */
       break;
     case 'X':
+      /* already processed; just ignore it now */
       break;
     case 'Y':
       dfilter = optarg;
@@ -1316,6 +842,13 @@ main(int argc, char *argv[])
         return 1;
       }
       break;
+    case 'd':        /* Decode as rule */
+    case 'K':        /* Kerberos keytab file */
+    case 't':        /* Time stamp type */
+    case 'u':        /* Seconds type */
+      if (!dissect_opts_handle_opt(opt, optarg))
+          return 1;
+      break;
     default:
     case '?':        /* Bad flag - print usage message */
       print_usage(stderr);
@@ -1399,24 +932,33 @@ main(int argc, char *argv[])
   /* disabled protocols as per configuration file */
   if (gdp_path == NULL && dp_path == NULL) {
     set_disabled_protos_list();
+    set_disabled_heur_dissector_list();
   }
 
   /* Build the column format array */
   build_column_format_array(&cfile.cinfo, prefs_p->num_cols, TRUE);
 
   if (rfilter != NULL) {
-    if (!dfilter_compile(rfilter, &rfcode)) {
-      cmdarg_err("%s", dfilter_error_msg);
+    if (!dfilter_compile(rfilter, &rfcode, &err_msg)) {
+      cmdarg_err("%s", err_msg);
+      g_free(err_msg);
       epan_cleanup();
+#ifdef HAVE_EXTCAP
+      extcap_cleanup();
+#endif
       return 2;
     }
   }
   cfile.rfcode = rfcode;
 
   if (dfilter != NULL) {
-    if (!dfilter_compile(dfilter, &dfcode)) {
-      cmdarg_err("%s", dfilter_error_msg);
+    if (!dfilter_compile(dfilter, &dfcode, &err_msg)) {
+      cmdarg_err("%s", err_msg);
+      g_free(err_msg);
       epan_cleanup();
+#ifdef HAVE_EXTCAP
+      extcap_cleanup();
+#endif
       return 2;
     }
   }
@@ -1462,6 +1004,9 @@ main(int argc, char *argv[])
        open_routine reader to use, then the following needs to change. */
     if (cf_open(&cfile, cf_name, WTAP_TYPE_AUTO, FALSE, &err) != CF_OK) {
       epan_cleanup();
+#ifdef HAVE_EXTCAP
+      extcap_cleanup();
+#endif
       return 2;
     }
 
@@ -1477,7 +1022,7 @@ main(int argc, char *argv[])
               "Sorry, but TFShark has to terminate now!\n"
               "\n"
               "Some infos / workarounds can be found at:\n"
-              "http://wiki.wireshark.org/KnownBugs/OutOfMemory\n");
+              "https://wiki.wireshark.org/KnownBugs/OutOfMemory\n");
       err = ENOMEM;
     }
     ENDTRY;
@@ -1500,6 +1045,9 @@ main(int argc, char *argv[])
   funnel_dump_all_text_windows();
   epan_free(cfile.epan);
   epan_cleanup();
+#ifdef HAVE_EXTCAP
+  extcap_cleanup();
+#endif
 
   output_fields_free(output_fields);
   output_fields = NULL;
@@ -1713,7 +1261,7 @@ process_packet_second_pass(capture_file *cf, epan_dissect_t *edt, frame_data *fd
   return passed || fdata->flags.dependent_of_displayed;
 }
 
-gboolean
+static gboolean
 local_wtap_read(capture_file *cf, struct wtap_pkthdr* file_phdr _U_, int *err, gchar **err_info _U_, gint64 *data_offset _U_, guint8** data_buffer)
 {
     /* int bytes_read; */
@@ -1810,7 +1358,7 @@ load_cap_file(capture_file *cf, int max_packet_count, gint64 max_byte_count)
   /* Get the union of the flags for all tap listeners. */
   tap_flags = union_of_tap_listener_flags();
 
-  memset(&file_phdr, 0, sizeof(file_phdr));
+  wtap_phdr_init(&file_phdr);
 
   /* XXX - TEMPORARY HACK TO ELF DISSECTOR */
   file_phdr.pkt_encap = 1234;
@@ -1945,6 +1493,8 @@ load_cap_file(capture_file *cf, int max_packet_count, gint64 max_byte_count)
     }
   }
 
+  wtap_phdr_cleanup(&file_phdr);
+
   if (err != 0) {
     /*
      * Print a message noting that the read failed somewhere along the line.
@@ -2142,13 +1692,13 @@ write_preamble(capture_file *cf)
   switch (output_action) {
 
   case WRITE_TEXT:
-    return print_preamble(print_stream, cf ? cf->filename : NULL, get_ws_vcs_version_info());
+    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(cf, stdout);
+      write_psml_preamble(&cf->cinfo, stdout);
     return !ferror(stdout);
 
   case WRITE_FIELDS:
@@ -2221,21 +1771,23 @@ print_columns(capture_file *cf)
   size_t  buf_offset;
   size_t  column_len;
   size_t  col_len;
+  col_item_t* col_item;
 
   line_bufp = get_line_buf(256);
   buf_offset = 0;
   *line_bufp = '\0';
   for (i = 0; i < cf->cinfo.num_cols; i++) {
+    col_item = &cf->cinfo.columns[i];
     /* Skip columns not marked as visible. */
     if (!get_column_visible(i))
       continue;
-    switch (cf->cinfo.col_fmt[i]) {
+    switch (col_item->col_fmt) {
     case COL_NUMBER:
-      column_len = col_len = strlen(cf->cinfo.col_data[i]);
+      column_len = col_len = strlen(col_item->col_data);
       if (column_len < 3)
         column_len = 3;
       line_bufp = get_line_buf(buf_offset + column_len);
-      put_spaces_string(line_bufp + buf_offset, cf->cinfo.col_data[i], col_len, column_len);
+      put_spaces_string(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
       break;
 
     case COL_CLS_TIME:
@@ -2246,11 +1798,11 @@ print_columns(capture_file *cf)
     case COL_UTC_TIME:
     case COL_UTC_YMD_TIME:  /* XXX - wider */
     case COL_UTC_YDOY_TIME: /* XXX - wider */
-      column_len = col_len = strlen(cf->cinfo.col_data[i]);
+      column_len = col_len = strlen(col_item->col_data);
       if (column_len < 10)
         column_len = 10;
       line_bufp = get_line_buf(buf_offset + column_len);
-      put_spaces_string(line_bufp + buf_offset, cf->cinfo.col_data[i], col_len, column_len);
+      put_spaces_string(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
       break;
 
     case COL_DEF_SRC:
@@ -2262,11 +1814,11 @@ print_columns(capture_file *cf)
     case COL_DEF_NET_SRC:
     case COL_RES_NET_SRC:
     case COL_UNRES_NET_SRC:
-      column_len = col_len = strlen(cf->cinfo.col_data[i]);
+      column_len = col_len = strlen(col_item->col_data);
       if (column_len < 12)
         column_len = 12;
       line_bufp = get_line_buf(buf_offset + column_len);
-      put_spaces_string(line_bufp + buf_offset, cf->cinfo.col_data[i], col_len, column_len);
+      put_spaces_string(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
       break;
 
     case COL_DEF_DST:
@@ -2278,17 +1830,17 @@ print_columns(capture_file *cf)
     case COL_DEF_NET_DST:
     case COL_RES_NET_DST:
     case COL_UNRES_NET_DST:
-      column_len = col_len = strlen(cf->cinfo.col_data[i]);
+      column_len = col_len = strlen(col_item->col_data);
       if (column_len < 12)
         column_len = 12;
       line_bufp = get_line_buf(buf_offset + column_len);
-      put_string_spaces(line_bufp + buf_offset, cf->cinfo.col_data[i], col_len, column_len);
+      put_string_spaces(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
       break;
 
     default:
-      column_len = strlen(cf->cinfo.col_data[i]);
+      column_len = strlen(col_item->col_data);
       line_bufp = get_line_buf(buf_offset + column_len);
-      put_string(line_bufp + buf_offset, cf->cinfo.col_data[i], column_len);
+      put_string(line_bufp + buf_offset, col_item->col_data, column_len);
       break;
     }
     buf_offset += column_len;
@@ -2308,12 +1860,12 @@ print_columns(capture_file *cf)
        * even if we're only adding " ".
        */
       line_bufp = get_line_buf(buf_offset + 4);
-      switch (cf->cinfo.col_fmt[i]) {
+      switch (col_item->col_fmt) {
 
       case COL_DEF_SRC:
       case COL_RES_SRC:
       case COL_UNRES_SRC:
-        switch (cf->cinfo.col_fmt[i + 1]) {
+        switch (cf->cinfo.columns[i+1].col_fmt) {
 
         case COL_DEF_DST:
         case COL_RES_DST:
@@ -2332,7 +1884,7 @@ print_columns(capture_file *cf)
       case COL_DEF_DL_SRC:
       case COL_RES_DL_SRC:
       case COL_UNRES_DL_SRC:
-        switch (cf->cinfo.col_fmt[i + 1]) {
+        switch (cf->cinfo.columns[i+1].col_fmt) {
 
         case COL_DEF_DL_DST:
         case COL_RES_DL_DST:
@@ -2351,7 +1903,7 @@ print_columns(capture_file *cf)
       case COL_DEF_NET_SRC:
       case COL_RES_NET_SRC:
       case COL_UNRES_NET_SRC:
-        switch (cf->cinfo.col_fmt[i + 1]) {
+        switch (cf->cinfo.columns[i+1].col_fmt) {
 
         case COL_DEF_NET_DST:
         case COL_RES_NET_DST:
@@ -2370,7 +1922,7 @@ print_columns(capture_file *cf)
       case COL_DEF_DST:
       case COL_RES_DST:
       case COL_UNRES_DST:
-        switch (cf->cinfo.col_fmt[i + 1]) {
+        switch (cf->cinfo.columns[i+1].col_fmt) {
 
         case COL_DEF_SRC:
         case COL_RES_SRC:
@@ -2389,7 +1941,7 @@ print_columns(capture_file *cf)
       case COL_DEF_DL_DST:
       case COL_RES_DL_DST:
       case COL_UNRES_DL_DST:
-        switch (cf->cinfo.col_fmt[i + 1]) {
+        switch (cf->cinfo.columns[i+1].col_fmt) {
 
         case COL_DEF_DL_SRC:
         case COL_RES_DL_SRC:
@@ -2408,7 +1960,7 @@ print_columns(capture_file *cf)
       case COL_DEF_NET_DST:
       case COL_RES_NET_DST:
       case COL_UNRES_NET_DST:
-        switch (cf->cinfo.col_fmt[i + 1]) {
+        switch (cf->cinfo.columns[i+1].col_fmt) {
 
         case COL_DEF_NET_SRC:
         case COL_RES_NET_SRC:
@@ -2453,7 +2005,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();
@@ -2487,11 +2039,11 @@ print_packet(capture_file *cf, epan_dissect_t *edt)
       break;
 
     case WRITE_XML:
-      proto_tree_write_pdml(edt, stdout);
+      write_pdml_proto_tree(NULL, NULL, 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);
     }
@@ -2619,9 +2171,9 @@ cf_open_error_message(int err, gchar *err_info _U_, gboolean for_writing,
   const char *errmsg;
   /* static char errmsg_errno[1024+1]; */
 
+#if 0
   if (err < 0) {
     /* Wiretap error. */
-#if 0
     switch (err) {
 
     case FTAP_ERR_NOT_REGULAR_FILE:
@@ -2730,8 +2282,8 @@ cf_open_error_message(int err, gchar *err_info _U_, gboolean for_writing,
       errmsg = errmsg_errno;
       break;
     }
-#endif
   } else
+#endif
     errmsg = file_open_error_message(err, for_writing);
   return errmsg;
 }
@@ -2790,7 +2342,7 @@ failure_message_cont(const char *msg_format, va_list ap)
 }
 
 /*
- * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
+ * Editor modelines  -  https://www.wireshark.org/tools/modelines.html
  *
  * Local variables:
  * c-basic-offset: 2