Show the Experimental-Result-Code if we don't know have a subdissector for that
[metze/wireshark/wip.git] / dumpcap.c
index 025337c2c92417d29acda55ac74f3100e8406c76..06b76c41ca00f80932a0e6a4e4f4be002f167e67 100644 (file)
--- a/dumpcap.c
+++ b/dumpcap.c
@@ -1,6 +1,4 @@
 /* dumpcap.c
- *
- * $Id$
  *
  * Wireshark - Network traffic analyzer
  * By Gerald Combs <gerald@wireshark.org>
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  */
 
-#include "config.h"
+#include <config.h>
 
 #include <stdio.h>
 #include <stdlib.h> /* for exit() */
 #include <glib.h>
 
 #include <string.h>
-#include <ctype.h>
 
 #ifdef HAVE_SYS_TYPES_H
 # include <sys/types.h>
 #include <unistd.h>
 #endif
 
+#ifdef HAVE_GETOPT_H
+#include <getopt.h>
+#endif
+
 #ifdef HAVE_ARPA_INET_H
 #include <arpa/inet.h>
 #endif
 #include <sys/utsname.h>
 #endif
 
+/*
+ * Linux bonding devices mishandle unknown ioctls; they fail
+ * with ENODEV rather than ENOTSUP, EOPNOTSUPP, or ENOTTY,
+ * so pcap_can_set_rfmon() returns a "no such device" indication
+ * if we try to do SIOCGIWMODE on them.
+ *
+ * So, on Linux, we check for bonding devices, if we can, before
+ * trying pcap_can_set_rfmon(), as pcap_can_set_rfmon() will
+ * end up trying SIOCGIWMODE on the device if that ioctl exists.
+ */
+#if defined(HAVE_PCAP_CREATE) && defined(__linux__)
+
+#include <sys/ioctl.h>
+
+/*
+ * If we're building for a Linux version that supports bonding,
+ * HAVE_BONDING will be defined.
+ */
+
+#ifdef HAVE_LINUX_SOCKIOS_H
+#include <linux/sockios.h>
+#endif
+
+#ifdef HAVE_LINUX_IF_BONDING_H
+#include <linux/if_bonding.h>
+#endif
+
+#if defined(BOND_INFO_QUERY_OLD) || defined(SIOCBONDINFOQUERY)
+#define HAVE_BONDING
+#endif
+
+#endif /* defined(HAVE_PCAP_CREATE) && defined(__linux__) */
+
 #include <signal.h>
 #include <errno.h>
 
+#ifdef HAVE_LIBZ
+#include <zlib.h>      /* to get the libz version number */
+#endif
+
+#include <wsutil/cmdarg_err.h>
 #include <wsutil/crash_info.h>
+#include <wsutil/ws_diag_control.h>
+#include <wsutil/ws_version_info.h>
 
-#ifndef HAVE_GETOPT
+#ifndef HAVE_GETOPT_LONG
 #include "wsutil/wsgetopt.h"
 #endif
 
 #endif
 
 #include "ringbuffer.h"
-#include "clopts_common.h"
-#include "console_io.h"
-#include "cmdarg_err.h"
-#include "version_info.h"
 
-#include "capture-pcap-util.h"
+#include "caputils/capture_ifinfo.h"
+#include "caputils/capture-pcap-util.h"
+#include "caputils/capture-pcap-util-int.h"
 #ifdef _WIN32
-#include "capture-wpcap.h"
+#include "caputils/capture-wpcap.h"
 #endif /* _WIN32 */
 
 #include "pcapio.h"
 
 #ifdef _WIN32
-#include "capture-wpcap.h"
 #include <wsutil/unicode-utils.h>
 #endif
 
 # include "wsutil/inet_v6defs.h"
 #endif
 
+#include <wsutil/clopts_common.h>
 #include <wsutil/privileges.h>
 
 #include "sync_pipe.h"
 
 #include "capture_opts.h"
-#include "capture_ifinfo.h"
-#include "capture_sync.h"
+#include <capchild/capture_session.h>
+#include <capchild/capture_sync.h>
 
 #include "conditions.h"
 #include "capture_stop_conditions.h"
 
-#include "tempfile.h"
+#include "wsutil/tempfile.h"
 #include "log.h"
 #include "wsutil/file_util.h"
+#include "wsutil/os_version_info.h"
 
-#include "ws80211_utils.h"
+#include "caputils/ws80211_utils.h"
+
+#ifdef HAVE_EXTCAP
+#include "extcap.h"
+#endif
 
 /*
  * Get information about libpcap format from "wiretap/libpcap.h".
@@ -147,8 +191,8 @@ FILE *debug_log;   /* for logging debug messages to  */
 static GAsyncQueue *pcap_queue;
 static gint64 pcap_queue_bytes;
 static gint64 pcap_queue_packets;
-static gint64 pcap_queue_byte_limit = 1024 * 1024;
-static gint64 pcap_queue_packet_limit = 1000;
+static gint64 pcap_queue_byte_limit = 0;
+static gint64 pcap_queue_packet_limit = 0;
 
 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
 #ifdef _WIN32
@@ -167,6 +211,32 @@ static void capture_loop_stop(void);
 /** Close a pipe, or socket if \a from_socket is TRUE */
 static void cap_pipe_close(int pipe_fd, gboolean from_socket _U_);
 
+#ifdef __linux__
+/*
+ * Enable kernel BPF JIT compiler if available.
+ * If any calls fail, just drive on - the JIT compiler might not be
+ * enabled, but filtering will still work, and it's not clear what
+ * we could do if the calls fail; should we just report the error
+ * and not continue to capture, should we report it as a warning, or
+ * what?
+ */
+static void
+enable_kernel_bpf_jit_compiler(void)
+{
+    int fd;
+    ssize_t written _U_;
+    static const char file[] = "/proc/sys/net/core/bpf_jit_enable";
+
+    fd = ws_open(file, O_WRONLY);
+    if (fd < 0)
+        return;
+
+    written = write(fd, "1", strlen("1"));
+
+    close(fd);
+}
+#endif
+
 #if !defined (__linux__)
 #ifndef HAVE_PCAP_BREAKLOOP
 /*
@@ -215,6 +285,10 @@ static void cap_pipe_close(int pipe_fd, gboolean from_socket _U_);
 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
  * in pcap_dispatch(); on the other hand, select() works just fine there.
  * Hence we use a select for that come what may.
+ *
+ * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
+ * internally, and, with TPACKET_V3, once that's supported, it'll
+ * support timeouts, at least as I understand the way the code works.
  */
 #define MUST_DO_SELECT
 #endif
@@ -226,9 +300,24 @@ typedef enum {
     INITFILTER_OTHER_ERROR
 } initfilter_status_t;
 
+typedef enum {
+    STATE_EXPECT_REC_HDR,
+    STATE_READ_REC_HDR,
+    STATE_EXPECT_DATA,
+    STATE_READ_DATA
+} cap_pipe_state_t;
+
+typedef enum {
+    PIPOK,
+    PIPEOF,
+    PIPERR,
+    PIPNEXIST
+} cap_pipe_err_t;
+
 typedef struct _pcap_options {
     guint32                      received;
     guint32                      dropped;
+    guint32                      flushed;
     pcap_t                      *pcap_h;
 #ifdef MUST_DO_SELECT
     int                          pcap_fd;                /**< pcap file descriptor */
@@ -258,13 +347,9 @@ typedef struct _pcap_options {
     size_t                       cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
     size_t                       cap_pipe_bytes_read;    /**< Used by cap_pipe_dispatch */
 #endif
-    enum {
-        STATE_EXPECT_REC_HDR,
-        STATE_READ_REC_HDR,
-        STATE_EXPECT_DATA,
-        STATE_READ_DATA
-    } cap_pipe_state;
-    enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } cap_pipe_err;
+    cap_pipe_state_t cap_pipe_state;
+    cap_pipe_err_t cap_pipe_err;
+
 #if defined(_WIN32)
     GMutex                      *cap_pipe_read_mtx;
     GAsyncQueue                 *cap_pipe_pending_q, *cap_pipe_done_q;
@@ -300,6 +385,7 @@ typedef struct _pcap_queue_element {
  */
 static const char please_report[] =
     "Please report this to the Wireshark developers.\n"
+    "https://bugs.wireshark.org/\n"
     "(This is not a crash; please do not report it as such.)";
 
 /*
@@ -365,13 +451,13 @@ static void WS_MSVC_NORETURN exit_main(int err) G_GNUC_NORETURN;
 
 static void report_new_capture_file(const char *filename);
 static void report_packet_count(unsigned int packet_count);
-static void report_packet_drops(guint32 received, guint32 drops, gchar *name);
+static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name);
 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
 
 #define MSG_MAX_LENGTH 4096
 
-/* Copied from pcapio.c libpcap_write_interface_statistics_block()*/
+/* Copied from pcapio.c pcapng_write_interface_statistics_block()*/
 static guint64
 create_timestamp(void) {
     guint64  timestamp;
@@ -406,7 +492,7 @@ create_timestamp(void) {
      * Subtract difference, in microseconds, between January 1, 1601
      * 00:00:00 UTC and January 1, 1970, 00:00:00 UTC.
      */
-    timestamp -= G_GINT64_CONSTANT(11644473600000000U);
+    timestamp -= G_GUINT64_CONSTANT(11644473600000000);
 #else
     /*
      * Current time, represented as seconds and microseconds since
@@ -424,20 +510,8 @@ create_timestamp(void) {
 }
 
 static void
-print_usage(gboolean print_ver)
+print_usage(FILE *output)
 {
-    FILE *output;
-
-    if (print_ver) {
-        output = stdout;
-        fprintf(output,
-                "Dumpcap " VERSION "%s\n"
-                "Capture network packets and dump them into a pcapng file.\n"
-                "See http://www.wireshark.org for more information.\n",
-                wireshark_svnversion);
-    } else {
-        output = stderr;
-    }
     fprintf(output, "\nUsage: dumpcap [options] ...\n");
     fprintf(output, "\n");
     fprintf(output, "Capture interface:\n");
@@ -451,8 +525,8 @@ print_usage(gboolean print_ver)
 #ifdef HAVE_PCAP_CREATE
     fprintf(output, "  -I                       capture in monitor mode, if available\n");
 #endif
-#if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
-    fprintf(output, "  -B <buffer size>         size of kernel buffer in MB (def: 2MB)\n");
+#ifdef CAN_SET_CAPTURE_BUFFER_SIZE
+    fprintf(output, "  -B <buffer size>         size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
 #endif
     fprintf(output, "  -y <link type>           link layer type (def: first appropriate)\n");
     fprintf(output, "  -D                       print list of interfaces and exit\n");
@@ -489,97 +563,68 @@ print_usage(gboolean print_ver)
     fprintf(output, "                              files:NUM - ringbuffer: replace after NUM files\n");
     fprintf(output, "  -n                       use pcapng format instead of pcap (default)\n");
     fprintf(output, "  -P                       use libpcap format instead of pcapng\n");
+    fprintf(output, "  --capture-comment <comment>\n");
+    fprintf(output, "                           add a capture comment to the output file\n");
+    fprintf(output, "                           (only for pcapng)\n");
     fprintf(output, "\n");
     fprintf(output, "Miscellaneous:\n");
+    fprintf(output, "  -N <packet_limit>        maximum number of packets buffered within dumpcap\n");
+    fprintf(output, "  -C <byte_limit>          maximum number of bytes used for buffering packets\n");
+    fprintf(output, "                           within dumpcap\n");
     fprintf(output, "  -t                       use a separate thread per interface\n");
     fprintf(output, "  -q                       don't report packet capture counts\n");
     fprintf(output, "  -v                       print version information and exit\n");
     fprintf(output, "  -h                       display this help and exit\n");
     fprintf(output, "\n");
+#ifdef __linux__
+    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
     fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
     fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
     fprintf(output, "\n");
     fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
 }
 
-static void
-show_version(GString *comp_info_str, GString *runtime_info_str)
-{
-    printf(
-        "Dumpcap " VERSION "%s\n"
-        "\n"
-        "%s\n"
-        "%s\n"
-        "%s\n"
-        "See http://www.wireshark.org for more information.\n",
-        wireshark_svnversion, get_copyright_info(), comp_info_str->str, runtime_info_str->str);
-}
-
-/*
- * Print to the standard error.  This is a command-line tool, so there's
- * no need to pop up a console.
- */
-void
-vfprintf_stderr(const char *fmt, va_list ap)
-{
-    vfprintf(stderr, fmt, ap);
-}
-
-void
-fprintf_stderr(const char *fmt, ...)
-{
-    va_list ap;
-
-    va_start(ap, fmt);
-    vfprintf_stderr(fmt, ap);
-    va_end(ap);
-}
-
 /*
  * Report an error in command-line arguments.
+ * If we're a capture child, send a message back to the parent, otherwise
+ * just print it.
  */
-void
-cmdarg_err(const char *fmt, ...)
+static void
+dumpcap_cmdarg_err(const char *fmt, va_list ap)
 {
-    va_list ap;
-
     if (capture_child) {
         gchar *msg;
         /* Generate a 'special format' message back to parent */
-        va_start(ap, fmt);
         msg = g_strdup_vprintf(fmt, ap);
         sync_pipe_errmsg_to_parent(2, msg, "");
         g_free(msg);
-        va_end(ap);
     } else {
-        va_start(ap, fmt);
         fprintf(stderr, "dumpcap: ");
         vfprintf(stderr, fmt, ap);
         fprintf(stderr, "\n");
-        va_end(ap);
     }
 }
 
 /*
  * Report additional information for an error in command-line arguments.
+ * If we're a capture child, send a message back to the parent, otherwise
+ * just print it.
  */
-void
-cmdarg_err_cont(const char *fmt, ...)
+static void
+dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
 {
-    va_list ap;
-
     if (capture_child) {
         gchar *msg;
-        va_start(ap, fmt);
         msg = g_strdup_vprintf(fmt, ap);
         sync_pipe_errmsg_to_parent(2, msg, "");
         g_free(msg);
-        va_end(ap);
     } else {
-        va_start(ap, fmt);
         vfprintf(stderr, fmt, ap);
         fprintf(stderr, "\n");
-        va_end(ap);
     }
 }
 
@@ -617,7 +662,12 @@ relinquish_all_capabilities(void)
 #endif
 
 static pcap_t *
-open_capture_device(interface_options *interface_opts,
+open_capture_device(capture_options *capture_opts
+#ifndef HAVE_PCAP_SET_TSTAMP_PRECISION
+                    _U_
+#endif
+                    ,
+                    interface_options *interface_opts,
                     char (*open_err_str)[PCAP_ERRBUF_SIZE])
 {
     pcap_t *pcap_h;
@@ -690,6 +740,22 @@ open_capture_device(interface_options *interface_opts,
             pcap_set_promisc(pcap_h, interface_opts->promisc_mode);
             pcap_set_timeout(pcap_h, CAP_READ_TIMEOUT);
 
+#ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
+            /*
+             * If we're writing pcap-ng files, try to enable
+             * nanosecond-resolution capture; any code that
+             * can read pcap-ng files must be able to handle
+             * nanosecond-resolution time stamps.
+             *
+             * If we're writing pcap files, don't try to enable
+             * nanosecond-resolution capture, as not all code
+             * that reads pcap files recognizes the nanosecond-
+             * resolution pcap file magic number.
+             */
+            if (capture_opts->use_pcapng)
+                request_high_resolution_timestamp(pcap_h);
+#endif /* HAVE_PCAP_SET_TSTAMP_PRECISION */
+
             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
                   "buffersize %d.", interface_opts->buffer_size);
             if (interface_opts->buffer_size != 0) {
@@ -721,6 +787,23 @@ open_capture_device(interface_options *interface_opts,
                                 *open_err_str);
         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
               "pcap_open_live() returned %p.", (void *)pcap_h);
+
+/* Windows doesn't have pcap_create() yet */
+#ifdef _WIN32
+        /* try to set the capture buffer size -- but not for remote devices */
+        if (pcap_h && interface_opts->buffer_size > 1 &&
+            pcap_setbuff(pcap_h, interface_opts->buffer_size * 1024 * 1024) != 0) {
+            gchar      *sync_secondary_msg_str;
+
+            sync_secondary_msg_str = g_strdup_printf(
+                "Unable to set a capture buffer size of %d MiB.\n"
+                "Capturing using the default size of %d MiB instead.",
+                interface_opts->buffer_size, DEFAULT_CAPTURE_BUFFER_SIZE);
+            report_capture_error("Couldn't set the capture buffer size.",
+                                 sync_secondary_msg_str);
+            g_free(sync_secondary_msg_str);
+        }
+#endif
 #endif
     }
     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "open_capture_device %s : %s", pcap_h ? "SUCCESS" : "FAILURE", interface_opts->name);
@@ -729,11 +812,7 @@ open_capture_device(interface_options *interface_opts,
 
 static void
 get_capture_device_open_failure_messages(const char *open_err_str,
-                                         const char *iface
-#ifndef _WIN32
-                                                           _U_
-#endif
-                                         ,
+                                         const char *iface,
                                          char *errmsg, size_t errmsg_len,
                                          char *secondary_errmsg,
                                          size_t secondary_errmsg_len)
@@ -744,22 +823,15 @@ get_capture_device_open_failure_messages(const char *open_err_str,
 #endif
 
     g_snprintf(errmsg, (gulong) errmsg_len,
-               "The capture session could not be initiated (%s).", open_err_str);
+               "The capture session could not be initiated on interface '%s' (%s).",
+               iface, open_err_str);
 #ifdef _WIN32
     if (!has_wpcap) {
       g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
                  "\n"
                  "In order to capture packets, WinPcap must be installed; see\n"
                  "\n"
-                 "        http://www.winpcap.org/\n"
-                 "\n"
-                 "or the mirror at\n"
-                 "\n"
-                 "        http://www.mirrors.wiretapped.net/security/packet-capture/winpcap/\n"
-                 "\n"
-                 "or the mirror at\n"
-                 "\n"
-                 "        http://winpcap.cs.pu.edu.tw/\n"
+                 "        https://www.winpcap.org/\n"
                  "\n"
                  "for a downloadable version of WinPcap and for instructions on how to install\n"
                  "WinPcap.");
@@ -771,8 +843,8 @@ get_capture_device_open_failure_messages(const char *open_err_str,
                  "\n"
                  "Help can be found at:\n"
                  "\n"
-                 "       http://wiki.wireshark.org/WinPcap\n"
-                 "       http://wiki.wireshark.org/CaptureSetup\n",
+                 "       https://wiki.wireshark.org/WinPcap\n"
+                 "       https://wiki.wireshark.org/CaptureSetup\n",
                  iface);
     }
 #else
@@ -804,12 +876,7 @@ get_capture_device_open_failure_messages(const char *open_err_str,
 
 /* Set the data link type on a pcap. */
 static gboolean
-set_pcap_linktype(pcap_t *pcap_h, int linktype,
-#ifdef HAVE_PCAP_SET_DATALINK
-                  char *name _U_,
-#else
-                  char *name,
-#endif
+set_pcap_linktype(pcap_t *pcap_h, int linktype, char *name,
                   char *errmsg, size_t errmsg_len,
                   char *secondary_errmsg, size_t secondary_errmsg_len)
 {
@@ -828,8 +895,8 @@ set_pcap_linktype(pcap_t *pcap_h, int linktype,
     set_linktype_err_str =
         "That DLT isn't one of the DLTs supported by this device";
 #endif
-    g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type (%s).",
-               set_linktype_err_str);
+    g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type on interface '%s' (%s).",
+               name, set_linktype_err_str);
     /*
      * If the error isn't "XXX is not one of the DLTs supported by this device",
      * tell the user to tell the Wireshark developers about it.
@@ -868,8 +935,10 @@ compile_capture_filter(const char *iface, pcap_t *pcap_h,
      * third argument to pcap_compile() as a const pointer.  Cast
      * away the warning.
      */
+DIAG_OFF(cast-qual)
     if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
         return FALSE;
+DIAG_ON(cast-qual)
     return TRUE;
 }
 
@@ -889,7 +958,7 @@ show_filter_code(capture_options *capture_opts)
 
     for (j = 0; j < capture_opts->ifaces->len; j++) {
         interface_opts = g_array_index(capture_opts->ifaces, interface_options, j);
-        pcap_h = open_capture_device(&interface_opts, &open_err_str);
+        pcap_h = open_capture_device(capture_opts, &interface_opts, &open_err_str);
         if (pcap_h == NULL) {
             /* Open failed; get messages */
             get_capture_device_open_failure_messages(open_err_str,
@@ -958,7 +1027,7 @@ show_filter_code(capture_options *capture_opts)
  * just call get_interface_list().
  */
 GList *
-capture_interface_list(int *err, char **err_str)
+capture_interface_list(int *err, char **err_str, void(*update_cb)(void) _U_)
 {
     return get_interface_list(err, err_str);
 }
@@ -1102,15 +1171,50 @@ create_data_link_info(int dlt)
     return data_link_info;
 }
 
+#if defined(HAVE_BONDING) && defined(HAVE_PCAP_CREATE)
+static gboolean
+is_linux_bonding_device(const char *ifname)
+{
+    int fd;
+    struct ifreq ifr;
+    ifbond ifb;
+
+    fd = socket(PF_INET, SOCK_DGRAM, 0);
+    if (fd == -1)
+        return FALSE;
+
+    memset(&ifr, 0, sizeof ifr);
+    g_strlcpy(ifr.ifr_name, ifname, sizeof ifr.ifr_name);
+    memset(&ifb, 0, sizeof ifb);
+    ifr.ifr_data = (caddr_t)&ifb;
+#if defined(SIOCBONDINFOQUERY)
+    if (ioctl(fd, SIOCBONDINFOQUERY, &ifr) == 0) {
+        close(fd);
+        return TRUE;
+    }
+#else
+    if (ioctl(fd, BOND_INFO_QUERY_OLD, &ifr) == 0) {
+        close(fd);
+        return TRUE;
+    }
+#endif
+
+    close(fd);
+    return FALSE;
+}
+#elif defined(HAVE_PCAP_CREATE)
+static gboolean
+is_linux_bonding_device(const char *ifname _U_)
+{
+    return FALSE;
+}
+#endif
+
 /*
  * Get the capabilities of a network device.
  */
 static if_capabilities_t *
-get_if_capabilities(const char *devicename, gboolean monitor_mode
-#ifndef HAVE_PCAP_CREATE
-        _U_
-#endif
-, char **err_str)
+get_if_capabilities(interface_options *interface_opts, char **err_str)
 {
     if_capabilities_t *caps;
     char errbuf[PCAP_ERRBUF_SIZE];
@@ -1128,7 +1232,7 @@ get_if_capabilities(const char *devicename, gboolean monitor_mode
     /*
      * Allocate the interface capabilities structure.
      */
-    caps = g_malloc(sizeof *caps);
+    caps = (if_capabilities_t *)g_malloc(sizeof *caps);
 
     /*
      * WinPcap 4.1.2, and possibly earlier versions, have a bug
@@ -1146,7 +1250,19 @@ get_if_capabilities(const char *devicename, gboolean monitor_mode
      */
     errbuf[0] = '\0';
 #ifdef HAVE_PCAP_OPEN
-    pch = pcap_open(devicename, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
+#ifdef HAVE_PCAP_REMOTE
+    if (strncmp (interface_opts->name, "rpcap://", 8) == 0) {
+        struct pcap_rmtauth auth;
+
+        auth.type = interface_opts->auth_type == CAPTURE_AUTH_PWD ?
+            RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
+        auth.username = interface_opts->auth_username;
+        auth.password = interface_opts->auth_password;
+
+        pch = pcap_open(interface_opts->name, MIN_PACKET_SIZE, 0, 0, &auth, errbuf);
+    } else
+#endif
+        pch = pcap_open(interface_opts->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
     caps->can_set_rfmon = FALSE;
     if (pch == NULL) {
         if (err_str != NULL)
@@ -1155,14 +1271,26 @@ get_if_capabilities(const char *devicename, gboolean monitor_mode
         return NULL;
     }
 #elif defined(HAVE_PCAP_CREATE)
-    pch = pcap_create(devicename, errbuf);
+    pch = pcap_create(interface_opts->name, errbuf);
     if (pch == NULL) {
         if (err_str != NULL)
             *err_str = g_strdup(errbuf);
         g_free(caps);
         return NULL;
     }
-    status = pcap_can_set_rfmon(pch);
+    if (is_linux_bonding_device(interface_opts->name)) {
+        /*
+         * Linux bonding device; not Wi-Fi, so no monitor mode, and
+         * calling pcap_can_set_rfmon() might get a "no such device"
+         * error.
+         */
+        status = 0;
+    } else {
+        /*
+         * Not a Linux bonding device, so go ahead.
+         */
+        status = pcap_can_set_rfmon(pch);
+    }
     if (status < 0) {
         /* Error. */
         if (status == PCAP_ERROR)
@@ -1178,7 +1306,7 @@ get_if_capabilities(const char *devicename, gboolean monitor_mode
         caps->can_set_rfmon = FALSE;
     else if (status == 1) {
         caps->can_set_rfmon = TRUE;
-        if (monitor_mode)
+        if (interface_opts->monitor_mode)
             pcap_set_rfmon(pch, 1);
     } else {
         if (err_str != NULL) {
@@ -1205,7 +1333,7 @@ get_if_capabilities(const char *devicename, gboolean monitor_mode
         return NULL;
     }
 #else
-    pch = pcap_open_live(devicename, MIN_PACKET_SIZE, 0, 0, errbuf);
+    pch = pcap_open_live(interface_opts->name, MIN_PACKET_SIZE, 0, 0, errbuf);
     caps->can_set_rfmon = FALSE;
     if (pch == NULL) {
         if (err_str != NULL)
@@ -1214,7 +1342,7 @@ get_if_capabilities(const char *devicename, gboolean monitor_mode
         return NULL;
     }
 #endif
-    deflt = get_pcap_linktype(pch, devicename);
+    deflt = get_pcap_linktype(pch, interface_opts->name);
 #ifdef HAVE_PCAP_LIST_DATALINKS
     nlt = pcap_list_datalinks(pch, &linktypes);
     if (nlt == 0 || linktypes == NULL) {
@@ -1254,11 +1382,11 @@ get_if_capabilities(const char *devicename, gboolean monitor_mode
      *
      * See the mail threads starting at
      *
-     *    http://www.winpcap.org/pipermail/winpcap-users/2006-September/001421.html
+     *    https://www.winpcap.org/pipermail/winpcap-users/2006-September/001421.html
      *
      * and
      *
-     *    http://www.winpcap.org/pipermail/winpcap-users/2008-May/002498.html
+     *    https://www.winpcap.org/pipermail/winpcap-users/2008-May/002498.html
      */
 #ifndef _WIN32
 #define xx_free free  /* hack so checkAPIs doesn't complain */
@@ -1304,7 +1432,7 @@ print_machine_readable_interfaces(GList *if_list)
     for (if_entry = g_list_first(if_list); if_entry != NULL;
          if_entry = g_list_next(if_entry)) {
         if_info = (if_info_t *)if_entry->data;
-        printf("%d. %s", i++, if_info->name);
+        printf("%d. %s\t", i++, if_info->name);
 
         /*
          * Print the contents of the if_entry struct in a parseable format.
@@ -1313,9 +1441,9 @@ print_machine_readable_interfaces(GList *if_list)
          */
         /* XXX - Make sure our description doesn't contain a tab */
         if (if_info->vendor_description != NULL)
-            printf("\t%s\t", if_info->vendor_description);
+            printf("%s\t", if_info->vendor_description);
         else
-            printf("\t\t");
+            printf("\t");
 
         /* XXX - Make sure our friendly name doesn't contain a tab */
         if (if_info->friendly_name != NULL)
@@ -1323,6 +1451,8 @@ print_machine_readable_interfaces(GList *if_list)
         else
             printf("\t");
 
+        printf("%i\t", if_info->type);
+
         for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
                     addr = g_slist_next(addr)) {
             if (addr != g_slist_nth(if_info->addrs, 0))
@@ -1347,7 +1477,7 @@ print_machine_readable_interfaces(GList *if_list)
                 }
                 break;
             default:
-                printf("<type unknown %u>", if_addr->ifat_type);
+                printf("<type unknown %i>", if_addr->ifat_type);
             }
         }
 
@@ -1355,7 +1485,9 @@ print_machine_readable_interfaces(GList *if_list)
             printf("\tloopback");
         else
             printf("\tnetwork");
-
+#ifdef HAVE_EXTCAP
+        printf("\t%s", if_info->extcap);
+#endif
         printf("\n");
     }
 }
@@ -1412,22 +1544,29 @@ print_statistics_loop(gboolean machine_readable)
 
     if_list = get_interface_list(&err, &err_str);
     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 err;
     }
 
     for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
         if_info = (if_info_t *)if_entry->data;
+
+#ifdef __linux__
+        /* On Linux nf* interfaces don't collect stats properly and don't allows multiple
+         * connections. We avoid collecting stats on them.
+         */
+        if (!strncmp(if_info->name, "nf", 2)) {
+            g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Skipping interface %s for stats",
+                if_info->name);
+            continue;
+        }
+#endif
+
 #ifdef HAVE_PCAP_OPEN
         pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
 #else
@@ -1473,6 +1612,10 @@ print_statistics_loop(gboolean machine_readable)
             }
         }
 #ifdef _WIN32
+        /* If we have a dummy signal pipe check it */
+        if (!signal_pipe_check_running()) {
+            global_ld.go = FALSE;
+        }
         Sleep(1 * 1000);
 #else
         sleep(1);
@@ -1548,7 +1691,7 @@ report_capture_count(gboolean reportit)
 {
     /* Don't print this if we're a capture child. */
     if (!capture_child && reportit) {
-        fprintf(stderr, "\rPackets captured: %u\n", global_ld.packet_count);
+        fprintf(stderr, "\rPackets captured: %d\n", global_ld.packet_count);
         /* stderr could be line buffered */
         fflush(stderr);
     }
@@ -1657,10 +1800,10 @@ cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcapr
 {
     if (byte_swapped) {
         /* Byte-swap the record header fields. */
-        rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
-        rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
-        rechdr->incl_len = BSWAP32(rechdr->incl_len);
-        rechdr->orig_len = BSWAP32(rechdr->orig_len);
+        rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
+        rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
+        rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
+        rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
     }
 
     /* In file format version 2.3, the "incl_len" and "orig_len" fields were
@@ -1847,14 +1990,14 @@ cap_open_socket(char *pipename, pcap_options *pcap_opts, char *errmsg, int errms
     goto fail_invalid;
   }
 
-  strncpy(buf, sockname, len);
+  g_snprintf ( buf,(gulong)len + 1, "%s", sockname );
   buf[len] = '\0';
-  if (!inet_pton(AF_INET, buf, &sa.sin_addr)) {
+  if (inet_pton(AF_INET, buf, &sa.sin_addr) <= 0) {
     goto fail_invalid;
   }
 
   sa.sin_family = AF_INET;
-  sa.sin_port = htons((u_short)port);
+  sa.sin_port = g_htons((u_short)port);
 
   if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
       (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
@@ -1876,7 +2019,7 @@ cap_open_socket(char *pipename, pcap_options *pcap_opts, char *errmsg, int errms
       if (errorText)
           LocalFree(errorText);
 #else
-      "         %d: %s", errno, strerror(errno));
+      "         %d: %s", errno, g_strerror(errno));
 #endif
       pcap_opts->cap_pipe_err = PIPERR;
 
@@ -1930,16 +2073,21 @@ cap_pipe_open_live(char *pipename,
 #else /* _WIN32 */
     char    *pncopy, *pos;
     wchar_t *err_str;
+    interface_options interface_opts;
+#ifdef HAVE_EXTCAP
+    char* extcap_pipe_name;
+    gboolean extcap_pipe;
+#endif
 #endif
     ssize_t  b;
-    int      fd, sel_ret;
+    int      fd = -1, sel_ret;
     size_t   bytes_read;
     guint32  magic = 0;
-
     pcap_opts->cap_pipe_fd = -1;
 #ifdef _WIN32
     pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
 #endif
+
     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
 
     /*
@@ -2066,10 +2214,23 @@ cap_pipe_open_live(char *pipename,
             return;
         }
 
+        interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
+#ifdef HAVE_EXTCAP
+        extcap_pipe_name = g_strconcat("\\\\.\\pipe\\", EXTCAP_PIPE_PREFIX, NULL);
+        extcap_pipe = strstr(interface_opts.name, extcap_pipe_name) ? TRUE : FALSE;
+        g_free(extcap_pipe_name);
+#endif
+
         /* Wait for the pipe to appear */
         while (1) {
-            pcap_opts->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
-                                               OPEN_EXISTING, 0, NULL);
+
+#ifdef HAVE_EXTCAP
+            if(extcap_pipe)
+                pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
+            else
+#endif
+                pcap_opts->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
+                                                   OPEN_EXISTING, 0, NULL);
 
             if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE)
                 break;
@@ -2088,7 +2249,7 @@ cap_pipe_open_live(char *pipename,
 
             if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
                 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
-                              NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
+                             NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
                 g_snprintf(errmsg, errmsgl,
                            "The capture session on \"%s\" timed out during "
                            "pipe open: %s (error %d)",
@@ -2103,14 +2264,18 @@ cap_pipe_open_live(char *pipename,
 
     pcap_opts->from_cap_pipe = TRUE;
 
-    if ((pcap_opts->from_cap_socket)
-#ifndef _WIN32
-         || 1
+#ifdef _WIN32
+    if (pcap_opts->from_cap_socket)
 #endif
-         ) {
+    {
         /* read the pcap header */
         bytes_read = 0;
         while (bytes_read < sizeof magic) {
+            if (fd == -1) {
+                g_snprintf(errmsg, errmsgl, "Invalid file descriptor");
+                goto error;
+            }
+
             sel_ret = cap_pipe_select(fd);
             if (sel_ret < 0) {
                 g_snprintf(errmsg, errmsgl,
@@ -2194,11 +2359,10 @@ cap_pipe_open_live(char *pipename,
         goto error;
     }
 
-    if ((pcap_opts->from_cap_socket)
-#ifndef _WIN32
-         || 1
+#ifdef _WIN32
+    if (pcap_opts->from_cap_socket)
 #endif
-         ) {
+    {
         /* Read the rest of the header */
         bytes_read = 0;
         while (bytes_read < sizeof(struct pcap_hdr)) {
@@ -2243,10 +2407,10 @@ cap_pipe_open_live(char *pipename,
 
     if (pcap_opts->cap_pipe_byte_swapped) {
         /* Byte-swap the header fields about which we care. */
-        hdr->version_major = BSWAP16(hdr->version_major);
-        hdr->version_minor = BSWAP16(hdr->version_minor);
-        hdr->snaplen = BSWAP32(hdr->snaplen);
-        hdr->network = BSWAP32(hdr->network);
+        hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
+        hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
+        hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
+        hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
     }
     pcap_opts->linktype = hdr->network;
 
@@ -2310,11 +2474,10 @@ cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *er
         /* Fall through */
 
     case STATE_READ_REC_HDR:
-        if ((pcap_opts->from_cap_socket)
-#ifndef _WIN32
-           || 1
+#ifdef _WIN32
+        if (pcap_opts->from_cap_socket)
 #endif
-           ) {
+        {
             b = cap_pipe_read(pcap_opts->cap_pipe_fd, ((char *)&pcap_opts->cap_pipe_rechdr)+pcap_opts->cap_pipe_bytes_read,
                  pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read, pcap_opts->from_cap_socket);
             if (b <= 0) {
@@ -2370,11 +2533,10 @@ cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *er
         /* Fall through */
 
     case STATE_READ_DATA:
-        if ((pcap_opts->from_cap_socket)
-#ifndef _WIN32
-           || 1
+#ifdef _WIN32
+        if (pcap_opts->from_cap_socket)
 #endif
-           ) {
+        {
             b = cap_pipe_read(pcap_opts->cap_pipe_fd,
                               data+pcap_opts->cap_pipe_bytes_read,
                               pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read,
@@ -2397,7 +2559,7 @@ cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *er
             g_get_current_time(&wait_time);
             g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
             q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
-#endif
+#endif /* GLIB_CHECK_VERSION(2,31,18) */
             if (pcap_opts->cap_pipe_err == PIPEOF) {
                 result = PD_PIPE_EOF;
                 break;
@@ -2409,7 +2571,7 @@ cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *er
                 return 0;
             }
         }
-#endif
+#endif /* _WIN32 */
         if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
             return 0;
         result = PD_DATA_READ;
@@ -2498,14 +2660,13 @@ capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
     guint             i;
 #ifdef _WIN32
     int         err;
-    gchar      *sync_secondary_msg_str;
     WORD        wVersionRequested;
     WSADATA     wsaData;
 #endif
 
 /* XXX - opening Winsock on tshark? */
 
-    /* Initialize Windows Socket if we are in a WIN32 OS
+    /* Initialize Windows Socket if we are in a Win32 OS
        This needs to be done before querying the interface for network/netmask */
 #ifdef _WIN32
     /* XXX - do we really require 1.1 or earlier?
@@ -2553,7 +2714,7 @@ capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
     if ((use_threads == FALSE) &&
         (capture_opts->ifaces->len > 1)) {
         g_snprintf(errmsg, (gulong) errmsg_len,
-                   "Using threads is required for capturing on multiple interfaces!");
+                   "Using threads is required for capturing on multiple interfaces.");
         return FALSE;
     }
 
@@ -2567,6 +2728,7 @@ capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
         }
         pcap_opts->received = 0;
         pcap_opts->dropped = 0;
+        pcap_opts->flushed = 0;
         pcap_opts->pcap_h = NULL;
 #ifdef MUST_DO_SELECT
         pcap_opts->pcap_fd = -1;
@@ -2592,7 +2754,7 @@ capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
 #endif
         pcap_opts->cap_pipe_bytes_to_read = 0;
         pcap_opts->cap_pipe_bytes_read = 0;
-        pcap_opts->cap_pipe_state = 0;
+        pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
         pcap_opts->cap_pipe_err = PIPOK;
 #ifdef _WIN32
 #if GLIB_CHECK_VERSION(2,31,0)
@@ -2607,24 +2769,14 @@ capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
         g_array_append_val(ld->pcaps, pcap_opts);
 
         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts.name);
-        pcap_opts->pcap_h = open_capture_device(&interface_opts, &open_err_str);
+        pcap_opts->pcap_h = open_capture_device(capture_opts, &interface_opts, &open_err_str);
 
         if (pcap_opts->pcap_h != NULL) {
             /* we've opened "iface" as a network device */
-#ifdef _WIN32
-            /* try to set the capture buffer size */
-            if (interface_opts.buffer_size > 1 &&
-                pcap_setbuff(pcap_opts->pcap_h, interface_opts.buffer_size * 1024 * 1024) != 0) {
-                sync_secondary_msg_str = g_strdup_printf(
-                    "The capture buffer size of %dMB seems to be too high for your machine,\n"
-                    "the default of 1MB will be used.\n"
-                    "\n"
-                    "Nonetheless, the capture is started.\n",
-                    interface_opts.buffer_size);
-                report_capture_error("Couldn't set the capture buffer size!",
-                                     sync_secondary_msg_str);
-                g_free(sync_secondary_msg_str);
-            }
+
+#ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
+            /* Find out if we're getting nanosecond-precision time stamps */
+            pcap_opts->ts_nsec = have_high_resolution_timestamp(pcap_opts->pcap_h);
 #endif
 
 #if defined(HAVE_PCAP_SETSAMPLING)
@@ -2818,7 +2970,7 @@ capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *err
     if ((capture_opts->use_pcapng == FALSE) &&
         (capture_opts->ifaces->len > 1)) {
         g_snprintf(errmsg, errmsg_len,
-                   "Using PCAPNG is required for capturing on multiple interfaces! Use the -n option.");
+                   "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
         return FALSE;
     }
 
@@ -2833,21 +2985,22 @@ capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *err
     }
     if (ld->pdh) {
         if (capture_opts->use_pcapng) {
-            char appname[100];
-            GString             *os_info_str;
+            char    *appname;
+            GString *os_info_str;
 
             os_info_str = g_string_new("");
             get_os_version_info(os_info_str);
 
-            g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
-            successful = libpcap_write_session_header_block(libpcap_write_to_file, ld->pdh,
-                                NULL,                        /* Comment*/
+            appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
+            successful = pcapng_write_session_header_block(ld->pdh,
+                                (const char *)capture_opts->capture_comment,   /* Comment*/
                                 NULL,                        /* HW*/
                                 os_info_str->str,            /* OS*/
                                 appname,
                                 -1,                          /* section_length */
                                 &ld->bytes_written,
                                 &err);
+            g_free(appname);
 
             for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
                 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
@@ -2857,18 +3010,18 @@ capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *err
                 } else {
                     pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
                 }
-                successful = libpcap_write_interface_description_block(libpcap_write_to_file, global_ld.pdh,
-                                                                       NULL,                       /* OPT_COMMENT       1 */
-                                                                       interface_opts.name,        /* IDB_NAME          2 */
-                                                                       interface_opts.descr,       /* IDB_DESCRIPTION   3 */
-                                                                       interface_opts.cfilter,     /* IDB_FILTER       11 */
-                                                                       os_info_str->str,           /* IDB_OS           12 */
-                                                                       pcap_opts->linktype,
-                                                                       pcap_opts->snaplen,
-                                                                       &(global_ld.bytes_written),
-                                                                       0,                          /* IDB_IF_SPEED      8 */
-                                                                       pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL       9 */
-                                                                       &global_ld.err);
+                successful = pcapng_write_interface_description_block(global_ld.pdh,
+                                                                      NULL,                       /* OPT_COMMENT       1 */
+                                                                      interface_opts.name,        /* IDB_NAME          2 */
+                                                                      interface_opts.descr,       /* IDB_DESCRIPTION   3 */
+                                                                      interface_opts.cfilter,     /* IDB_FILTER       11 */
+                                                                      os_info_str->str,           /* IDB_OS           12 */
+                                                                      pcap_opts->linktype,
+                                                                      pcap_opts->snaplen,
+                                                                      &(global_ld.bytes_written),
+                                                                      0,                          /* IDB_IF_SPEED      8 */
+                                                                      pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL       9 */
+                                                                      &global_ld.err);
             }
 
             g_string_free(os_info_str, TRUE);
@@ -2880,7 +3033,7 @@ capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *err
             } else {
                 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
             }
-            successful = libpcap_write_file_header(libpcap_write_to_file, ld->pdh, pcap_opts->linktype, pcap_opts->snaplen,
+            successful = libpcap_write_file_header(ld->pdh, pcap_opts->linktype, pcap_opts->snaplen,
                                                    pcap_opts->ts_nsec, &ld->bytes_written, &err);
         }
         if (!successful) {
@@ -2937,20 +3090,20 @@ capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err
 
                     if (pcap_stats(pcap_opts->pcap_h, &stats) >= 0) {
                         isb_ifrecv = pcap_opts->received;
-                        isb_ifdrop = stats.ps_drop + pcap_opts->dropped;
+                        isb_ifdrop = stats.ps_drop + pcap_opts->dropped + pcap_opts->flushed;
                    } else {
                         isb_ifrecv = G_MAXUINT64;
                         isb_ifdrop = G_MAXUINT64;
                     }
-                    libpcap_write_interface_statistics_block(libpcap_write_to_file, ld->pdh,
-                                                             i,
-                                                             &ld->bytes_written,
-                                                             "Counters provided by dumpcap",
-                                                             start_time,
-                                                             end_time,
-                                                             isb_ifrecv,
-                                                             isb_ifdrop,
-                                                             err_close);
+                    pcapng_write_interface_statistics_block(ld->pdh,
+                                                            i,
+                                                            &ld->bytes_written,
+                                                            "Counters provided by dumpcap",
+                                                            start_time,
+                                                            end_time,
+                                                            isb_ifrecv,
+                                                            isb_ifdrop,
+                                                            err_close);
                 }
             }
         }
@@ -3110,7 +3263,7 @@ capture_loop_dispatch(loop_data *ld,
 
             /*
              * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
-             * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
+             * see https://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
              * This should be fixed in the WinPcap 4.0 alpha release.
              *
              * For reference, an example remote interface:
@@ -3313,7 +3466,7 @@ do_file_switch_or_stop(capture_options *capture_opts,
 
     if (capture_opts->multi_files_on) {
         if (cnd_autostop_files != NULL &&
-            cnd_eval(cnd_autostop_files, ++global_ld.autostop_files)) {
+            cnd_eval(cnd_autostop_files, (guint64)++global_ld.autostop_files)) {
             /* no files left: stop here */
             global_ld.go = FALSE;
             return FALSE;
@@ -3326,14 +3479,14 @@ do_file_switch_or_stop(capture_options *capture_opts,
             /* File switch succeeded: reset the conditions */
             global_ld.bytes_written = 0;
             if (capture_opts->use_pcapng) {
-                char appname[100];
-                GString             *os_info_str;
+                char    *appname;
+                GString *os_info_str;
 
                 os_info_str = g_string_new("");
                 get_os_version_info(os_info_str);
 
-                g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
-                successful = libpcap_write_session_header_block(libpcap_write_to_file, global_ld.pdh,
+                appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
+                successful = pcapng_write_session_header_block(global_ld.pdh,
                                 NULL,                        /* Comment */
                                 NULL,                        /* HW */
                                 os_info_str->str,            /* OS */
@@ -3341,29 +3494,30 @@ do_file_switch_or_stop(capture_options *capture_opts,
                                                                 -1,                          /* section_length */
                                 &(global_ld.bytes_written),
                                 &global_ld.err);
+                g_free(appname);
 
                 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
                     interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
                     pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
-                    successful = libpcap_write_interface_description_block(libpcap_write_to_file, global_ld.pdh,
-                                                                           NULL,                       /* OPT_COMMENT       1 */
-                                                                           interface_opts.name,        /* IDB_NAME          2 */
-                                                                           interface_opts.descr,       /* IDB_DESCRIPTION   3 */
-                                                                           interface_opts.cfilter,     /* IDB_FILTER       11 */
-                                                                           os_info_str->str,           /* IDB_OS           12 */
-                                                                           pcap_opts->linktype,
-                                                                           pcap_opts->snaplen,
-                                                                           &(global_ld.bytes_written),
-                                                                           0,                          /* IDB_IF_SPEED      8 */
-                                                                           pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL       9 */
-                                                                           &global_ld.err);
+                    successful = pcapng_write_interface_description_block(global_ld.pdh,
+                                                                          NULL,                       /* OPT_COMMENT       1 */
+                                                                          interface_opts.name,        /* IDB_NAME          2 */
+                                                                          interface_opts.descr,       /* IDB_DESCRIPTION   3 */
+                                                                          interface_opts.cfilter,     /* IDB_FILTER       11 */
+                                                                          os_info_str->str,           /* IDB_OS           12 */
+                                                                          pcap_opts->linktype,
+                                                                          pcap_opts->snaplen,
+                                                                          &(global_ld.bytes_written),
+                                                                          0,                          /* IDB_IF_SPEED      8 */
+                                                                          pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL       9 */
+                                                                          &global_ld.err);
                 }
 
                 g_string_free(os_info_str, TRUE);
 
             } else {
                 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
-                successful = libpcap_write_file_header(libpcap_write_to_file, global_ld.pdh, pcap_opts->linktype, pcap_opts->snaplen,
+                successful = libpcap_write_file_header(global_ld.pdh, pcap_opts->linktype, pcap_opts->snaplen,
                                                        pcap_opts->ts_nsec, &global_ld.bytes_written, &global_ld.err);
             }
             if (!successful) {
@@ -3420,7 +3574,7 @@ pcap_read_handler(void* arg)
 static gboolean
 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
 {
-#ifdef WIN32
+#ifdef _WIN32
     DWORD              upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
 #else
     struct timeval     upd_time, cur_time;
@@ -3534,9 +3688,13 @@ capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct
     /* initialize capture stop (and alike) conditions */
     init_capture_stop_conditions();
     /* create stop conditions */
-    if (capture_opts->has_autostop_filesize)
+    if (capture_opts->has_autostop_filesize) {
+        if (capture_opts->autostop_filesize > (((guint32)INT_MAX + 1) / 1000)) {
+            capture_opts->autostop_filesize = ((guint32)INT_MAX + 1) / 1000;
+        }
         cnd_autostop_size =
-            cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
+            cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_filesize * 1000);
+    }
     if (capture_opts->has_autostop_duration)
         cnd_autostop_duration =
             cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
@@ -3548,17 +3706,17 @@ capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct
 
         if (capture_opts->has_autostop_files)
             cnd_autostop_files =
-                cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
+                cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_files);
     }
 
     /* init the time values */
-#ifdef WIN32
+#ifdef _WIN32
     upd_time = GetTickCount();
 #else
     gettimeofday(&upd_time, NULL);
 #endif
     start_time = create_timestamp();
-    g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
+    g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running.");
 
     /* WOW, everything is prepared! */
     /* please fasten your seat belts, we will enter now the actual capture loop */
@@ -3583,14 +3741,14 @@ capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct
 #if GLIB_CHECK_VERSION(2,31,18)
 
             g_async_queue_lock(pcap_queue);
-            queue_element = g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
+            queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
 #else
             GTimeVal write_thread_time;
 
             g_get_current_time(&write_thread_time);
             g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
             g_async_queue_lock(pcap_queue);
-            queue_element = g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
+            queue_element = (pcap_queue_element *)g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
 #endif
             if (queue_element) {
                 pcap_queue_bytes -= queue_element->phdr.caplen;
@@ -3637,7 +3795,7 @@ capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct
 
             /* check capture size condition */
             if (cnd_autostop_size != NULL &&
-                cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)) {
+                cnd_eval(cnd_autostop_size, global_ld.bytes_written)) {
                 /* Capture size limit reached, do we have another file? */
                 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
                                             cnd_autostop_size, cnd_file_duration))
@@ -3654,13 +3812,13 @@ capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct
          */
 #define DUMPCAP_UPD_TIME 500
 
-#ifdef WIN32
+#ifdef _WIN32
         cur_time = GetTickCount();  /* Note: wraps to 0 if sys runs for 49.7 days */
         if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
 #else
         gettimeofday(&cur_time, NULL);
-        if ((cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
-            (upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
+        if (((guint64)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
+            ((guint64)upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
 #endif
 
             upd_time = cur_time;
@@ -3714,7 +3872,7 @@ capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct
         }
         while (1) {
             g_async_queue_lock(pcap_queue);
-            queue_element = g_async_queue_try_pop_unlocked(pcap_queue);
+            queue_element = (pcap_queue_element *)g_async_queue_try_pop_unlocked(pcap_queue);
             if (queue_element) {
                 pcap_queue_bytes -= queue_element->phdr.caplen;
                 pcap_queue_packets -= 1;
@@ -3834,19 +3992,23 @@ capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct
     /* get packet drop statistics from pcap */
     for (i = 0; i < capture_opts->ifaces->len; i++) {
         guint32 received;
-        guint32 dropped;
+        guint32 pcap_dropped = 0;
 
         pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
         interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
         received = pcap_opts->received;
-        dropped = pcap_opts->dropped;
         if (pcap_opts->pcap_h != NULL) {
             g_assert(!pcap_opts->from_cap_pipe);
             /* Get the capture statistics, so we know how many packets were dropped. */
+            /*
+             * Older versions of libpcap didn't set ps_ifdrop on some
+             * platforms; initialize it to 0 to handle that.
+             */
+            stats->ps_ifdrop = 0;
             if (pcap_stats(pcap_opts->pcap_h, stats) >= 0) {
                 *stats_known = TRUE;
                 /* Let the parent process know. */
-                dropped += stats->ps_drop;
+                pcap_dropped += stats->ps_drop;
             } else {
                 g_snprintf(errmsg, sizeof(errmsg),
                            "Can't get packet-drop statistics: %s",
@@ -3854,13 +4016,13 @@ capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct
                 report_capture_error(errmsg, please_report);
             }
         }
-        report_packet_drops(received, dropped, interface_opts.console_display_name);
+        report_packet_drops(received, pcap_dropped, pcap_opts->dropped, pcap_opts->flushed, stats->ps_ifdrop, interface_opts.console_display_name);
     }
 
     /* close the input file (pcap or capture pipe) */
     capture_loop_close_input(&global_ld);
 
-    g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
+    g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped.");
 
     /* ok, if the write and the close were successful. */
     return write_ok && close_ok;
@@ -3973,7 +4135,7 @@ capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr
        the "stop capturing" flag, ignore this packet, as we're not
        supposed to be saving any more packets. */
     if (!global_ld.go) {
-        pcap_opts->dropped++;
+        pcap_opts->flushed++;
         return;
     }
 
@@ -3984,17 +4146,17 @@ capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr
            If this fails, set "ld->go" to FALSE, to stop the capture, and set
            "ld->err" to the error. */
         if (global_capture_opts.use_pcapng) {
-            successful = libpcap_write_enhanced_packet_block(libpcap_write_to_file, global_ld.pdh,
-                                                             NULL,
-                                                             phdr->ts.tv_sec, phdr->ts.tv_usec,
-                                                             phdr->caplen, phdr->len,
-                                                             pcap_opts->interface_id,
-                                                             ts_mul,
-                                                             pd, 0,
-                                                             &global_ld.bytes_written, &err);
+            successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
+                                                            NULL,
+                                                            phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
+                                                            phdr->caplen, phdr->len,
+                                                            pcap_opts->interface_id,
+                                                            ts_mul,
+                                                            pd, 0,
+                                                            &global_ld.bytes_written, &err);
         } else {
-            successful = libpcap_write_packet(libpcap_write_to_file, global_ld.pdh,
-                                              phdr->ts.tv_sec, phdr->ts.tv_usec,
+            successful = libpcap_write_packet(global_ld.pdh,
+                                              phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
                                               phdr->caplen, phdr->len,
                                               pd,
                                               &global_ld.bytes_written, &err);
@@ -4004,9 +4166,11 @@ capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr
             global_ld.err = err;
             pcap_opts->dropped++;
         } else {
+#if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
                   "Wrote a packet of length %d captured on interface %u.",
                    phdr->caplen, pcap_opts->interface_id);
+#endif
             global_ld.packet_count++;
             pcap_opts->received++;
             /* if the user told us to stop after x packets, do we already have enough? */
@@ -4030,7 +4194,7 @@ capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr
        the "stop capturing" flag, ignore this packet, as we're not
        supposed to be saving any more packets. */
     if (!global_ld.go) {
-        pcap_opts->dropped++;
+        pcap_opts->flushed++;
         return;
     }
 
@@ -4049,8 +4213,8 @@ capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr
     }
     memcpy(queue_element->pd, pd, phdr->caplen);
     g_async_queue_lock(pcap_queue);
-    if (((pcap_queue_byte_limit > 0) && (pcap_queue_bytes < pcap_queue_byte_limit)) &&
-        ((pcap_queue_packet_limit > 0) && (pcap_queue_packets < pcap_queue_packet_limit))) {
+    if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
+        ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
         limit_reached = FALSE;
         g_async_queue_push_unlocked(pcap_queue, queue_element);
         pcap_queue_bytes += phdr->caplen;
@@ -4123,6 +4287,40 @@ out:
     return ret;
 }
 
+static void
+get_dumpcap_compiled_info(GString *str)
+{
+    /* Capture libraries */
+    g_string_append(str, ", ");
+    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_dumpcap_runtime_info(GString *str)
+{
+    /* Capture libraries */
+    g_string_append(str, ", ");
+    get_runtime_caplibs_version(str);
+
+    /* zlib */
+#if defined(HAVE_LIBZ) && !defined(_WIN32)
+    g_string_append_printf(str, ", with libz %s", zlibVersion());
+#endif
+}
+
 /* And now our feature presentation... [ fade to music ] */
 int
 main(int argc, char *argv[])
@@ -4130,6 +4328,15 @@ main(int argc, char *argv[])
     GString          *comp_info_str;
     GString          *runtime_info_str;
     int               opt;
+DIAG_OFF(cast-qual)
+    static const struct option long_options[] = {
+        {(char *)"help", no_argument, NULL, 'h'},
+        {(char *)"version", no_argument, NULL, 'v'},
+        LONGOPT_CAPTURE_COMMON
+        {0, 0, 0, 0 }
+    };
+DIAG_ON(cast-qual)
+
     gboolean          arg_error             = FALSE;
 
 #ifdef _WIN32
@@ -4159,21 +4366,21 @@ main(int argc, char *argv[])
 #endif
     GString          *str;
 
-    /* Assemble the compile-time version information string */
-    comp_info_str = g_string_new("Compiled ");
-    get_compiled_version_info(comp_info_str, NULL, NULL);
+    cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
 
-    /* Assemble the run-time version information string */
-    runtime_info_str = g_string_new("Running ");
-    get_runtime_version_info(runtime_info_str, NULL);
+    /* Get the compile-time version information string */
+    comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
+
+    /* Get the run-time version information string */
+    runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
 
     /* Add it to the information to be reported on a crash. */
-    ws_add_crash_info("Dumpcap " VERSION "%s\n"
+    ws_add_crash_info("Dumpcap (Wireshark) %s\n"
            "\n"
            "%s"
            "\n"
            "%s",
-        wireshark_svnversion, comp_info_str->str, runtime_info_str->str);
+        get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
 
 #ifdef _WIN32
     arg_list_utf_16to8(argc, argv);
@@ -4186,12 +4393,16 @@ main(int argc, char *argv[])
     ws_init_dll_search_path();
 #endif
 
+#ifdef HAVE_BPF_IMAGE
+#define OPTSTRING_d "d"
+#else
+#define OPTSTRING_d ""
+#endif
+
 #ifdef HAVE_PCAP_REMOTE
-#define OPTSTRING_A "A:"
 #define OPTSTRING_r "r"
 #define OPTSTRING_u "u"
 #else
-#define OPTSTRING_A ""
 #define OPTSTRING_r ""
 #define OPTSTRING_u ""
 #endif
@@ -4202,29 +4413,11 @@ main(int argc, char *argv[])
 #define OPTSTRING_m ""
 #endif
 
-#if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
-#define OPTSTRING_B "B:"
-#else
-#define OPTSTRING_B ""
-#endif  /* _WIN32 or HAVE_PCAP_CREATE */
-
-#ifdef HAVE_PCAP_CREATE
-#define OPTSTRING_I "I"
-#else
-#define OPTSTRING_I ""
-#endif
-
-#ifdef HAVE_BPF_IMAGE
-#define OPTSTRING_d "d"
-#else
-#define OPTSTRING_d ""
-#endif
-
-#define OPTSTRING "a:" OPTSTRING_A "b:" OPTSTRING_B "c:" OPTSTRING_d "Df:ghi:" OPTSTRING_I "k:L" OPTSTRING_m "MnpPq" OPTSTRING_r "Ss:t" OPTSTRING_u "vw:y:Z:"
+#define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:" OPTSTRING_d "gh" "k:" OPTSTRING_m "MN:nPq" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
 
 #ifdef DEBUG_CHILD_DUMPCAP
     if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
-        fprintf (stderr, "Unable to open debug log file !\n");
+        fprintf (stderr, "Unable to open debug log file .\n");
         exit (1);
     }
 #endif
@@ -4296,13 +4489,15 @@ main(int argc, char *argv[])
     /* with the correct format.                                          */
 
     log_flags =
+        (GLogLevelFlags)(
         G_LOG_LEVEL_ERROR|
         G_LOG_LEVEL_CRITICAL|
         G_LOG_LEVEL_WARNING|
         G_LOG_LEVEL_MESSAGE|
         G_LOG_LEVEL_INFO|
         G_LOG_LEVEL_DEBUG|
-        G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
+        G_LOG_FLAG_FATAL|
+        G_LOG_FLAG_RECURSION);
 
     g_log_set_handler(NULL,
                       log_flags,
@@ -4377,6 +4572,10 @@ main(int argc, char *argv[])
 #endif /* SIGINFO */
 #endif  /* _WIN32 */
 
+#ifdef __linux__
+    enable_kernel_bpf_jit_compiler();
+#endif
+
     /* ----------------------------------------------------------------- */
     /* Privilege and capability handling                                 */
     /* Cases:                                                            */
@@ -4428,7 +4627,7 @@ main(int argc, char *argv[])
     /*        This behaviour will apparently be changed in the kernel    */
     /*        to allow the kill (signal) in this case.                   */
     /*        See the following for details:                             */
-    /*           http://www.mail-archive.com/  [wrapped]                 */
+    /*           https://www.mail-archive.com/  [wrapped]                */
     /*             linux-security-module@vger.kernel.org/msg02913.html   */
     /*                                                                   */
     /*        It is therefore conceivable that if dumpcap somehow hangs  */
@@ -4461,23 +4660,29 @@ main(int argc, char *argv[])
 
     /* Set the initial values in the capture options. This might be overwritten
        by the command line parameters. */
-    capture_opts_init(&global_capture_opts, NULL);
-
+    capture_opts_init(&global_capture_opts);
     /* We always save to a file - if no file was specified, we save to a
        temporary file. */
     global_capture_opts.saving_to_file      = TRUE;
     global_capture_opts.has_ring_num_files  = TRUE;
 
+    /* Pass on capture_child mode for capture_opts */
+    global_capture_opts.capture_child = capture_child;
+
     /* Now get our args */
-    while ((opt = getopt(argc, argv, OPTSTRING)) != -1) {
+    while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
         switch (opt) {
         case 'h':        /* Print help and exit */
-            print_usage(TRUE);
+            printf("Dumpcap (Wireshark) %s\n"
+                   "Capture network packets and dump them into a pcapng or pcap file.\n"
+                   "See https://www.wireshark.org for more information.\n",
+                   get_ws_vcs_version_info());
+            print_usage(stdout);
             exit_main(0);
             break;
         case 'v':        /* Show version and exit */
         {
-            show_version(comp_info_str, runtime_info_str);
+            show_version("Dumpcap (Wireshark)", comp_info_str, runtime_info_str);
             g_string_free(comp_info_str, TRUE);
             g_string_free(runtime_info_str, TRUE);
             exit_main(0);
@@ -4496,6 +4701,7 @@ main(int argc, char *argv[])
         case 's':        /* Set the snapshot (capture) length */
         case 'w':        /* Write to capture file x */
         case 'y':        /* Set the pcap data link type */
+        case  LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
 #ifdef HAVE_PCAP_REMOTE
         case 'u':        /* Use UDP for data transfer */
         case 'r':        /* Capture own RPCAP traffic too */
@@ -4504,9 +4710,9 @@ main(int argc, char *argv[])
 #ifdef HAVE_PCAP_SETSAMPLING
         case 'm':        /* Sampling */
 #endif
-#if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
+#ifdef CAN_SET_CAPTURE_BUFFER_SIZE
         case 'B':        /* Buffer size */
-#endif /* _WIN32 or HAVE_PCAP_CREATE */
+#endif
 #ifdef HAVE_PCAP_CREATE
         case 'I':        /* Monitor mode */
 #endif
@@ -4548,31 +4754,50 @@ main(int argc, char *argv[])
             break;
             /*** all non capture option specific ***/
         case 'D':        /* Print a list of capture devices and exit */
-            list_interfaces = TRUE;
-            run_once_args++;
+            if (!list_interfaces) {
+                list_interfaces = TRUE;
+                run_once_args++;
+            }
             break;
         case 'L':        /* Print list of link-layer types and exit */
-            list_link_layer_types = TRUE;
-            run_once_args++;
+            if (!list_link_layer_types) {
+                list_link_layer_types = TRUE;
+                run_once_args++;
+            }
             break;
 #ifdef HAVE_BPF_IMAGE
         case 'd':        /* Print BPF code for capture filter and exit */
-            print_bpf_code = TRUE;
-            run_once_args++;
+            if (!print_bpf_code) {
+                print_bpf_code = TRUE;
+                run_once_args++;
+            }
             break;
 #endif
         case 'S':        /* Print interface statistics once a second */
-            print_statistics = TRUE;
-            run_once_args++;
+            if (!print_statistics) {
+                print_statistics = TRUE;
+                run_once_args++;
+            }
             break;
         case 'k':        /* Set wireless channel */
-            set_chan = TRUE;
-            set_chan_arg = optarg;
-            run_once_args++;
-           break;
+            if (!set_chan) {
+                set_chan = TRUE;
+                set_chan_arg = optarg;
+                run_once_args++;
+            } else {
+                cmdarg_err("Only one -k flag may be specified");
+                arg_error = TRUE;
+            }
+            break;
         case 'M':        /* For -D, -L, and -S, print machine-readable output */
             machine_readable = TRUE;
             break;
+        case 'C':
+            pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
+            break;
+        case 'N':
+            pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
+            break;
         default:
             cmdarg_err("Invalid Option: %s", argv[optind-1]);
             /* FALLTHROUGH */
@@ -4600,13 +4825,26 @@ main(int argc, char *argv[])
         }
     }
 
+    if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
+        use_threads = TRUE;
+    }
+    if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
+        /* Use some default if the user hasn't specified some */
+        /* XXX: Are these defaults good enough? */
+        pcap_queue_byte_limit = 1000 * 1000;
+        pcap_queue_packet_limit = 1000;
+    }
     if (arg_error) {
-        print_usage(FALSE);
+        print_usage(stderr);
         exit_main(1);
     }
 
     if (run_once_args > 1) {
-        cmdarg_err("Only one of -D, -L, or -S may be supplied.");
+#ifdef HAVE_BPF_IMAGE
+        cmdarg_err("Only one of -D, -L, -d, -k, or -S may be supplied.");
+#else
+        cmdarg_err("Only one of -D, -L, -k, or -S may be supplied.");
+#endif
         exit_main(1);
     } else if (run_once_args == 1) {
         /* We're supposed to print some information, rather than
@@ -4617,11 +4855,20 @@ main(int argc, char *argv[])
         }
     } else {
         /* We're supposed to capture traffic; */
+
         /* Are we capturing on multiple interface? If so, use threads and pcapng. */
         if (global_capture_opts.ifaces->len > 1) {
             use_threads = TRUE;
             global_capture_opts.use_pcapng = TRUE;
         }
+
+        if (global_capture_opts.capture_comment &&
+            (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
+            /* XXX - for ringbuffer, should we apply the comment to each file? */
+            cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
+            exit_main(1);
+        }
+
         /* Was the ring buffer option specified and, if so, does it make sense? */
         if (global_capture_opts.multi_files_on) {
             /* Ring buffer works only under certain conditions:
@@ -4652,17 +4899,9 @@ main(int argc, char *argv[])
         int    err;
         gchar *err_str;
 
-        if_list = capture_interface_list(&err, &err_str);
+        if_list = capture_interface_list(&err, &err_str,NULL);
         if (if_list == NULL) {
-            switch (err) {
-            case CANT_GET_INTERFACE_LIST:
-            case DONT_HAVE_PCAP:
-                cmdarg_err("%s", err_str);
-                g_free(err_str);
-                exit_main(2);
-                break;
-
-            case NO_INTERFACES_FOUND:
+            if (err == 0) {
                 /*
                  * If we're being run by another program, just give them
                  * an empty list of interfaces, don't report this as
@@ -4673,7 +4912,10 @@ main(int argc, char *argv[])
                     cmdarg_err("There are no interfaces on which a capture can be done");
                     exit_main(2);
                 }
-                break;
+            } else {
+                cmdarg_err("%s", err_str);
+                g_free(err_str);
+                exit_main(2);
             }
         }
 
@@ -4711,12 +4953,49 @@ main(int argc, char *argv[])
      * "-L", "-d", and capturing act on a particular interface, so we have to
      * have an interface; if none was specified, pick a default.
      */
-    status = capture_opts_trim_iface(&global_capture_opts, NULL);
+    status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
     if (status != 0) {
         /* cmdarg_err() already called .... */
         exit_main(status);
     }
 
+    if (list_link_layer_types) {
+        /* Get the list of link-layer types for the capture device. */
+        if_capabilities_t *caps;
+        gchar *err_str;
+        guint  ii;
+
+        for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
+            interface_options interface_opts;
+
+            interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, ii);
+
+            caps = get_if_capabilities(&interface_opts, &err_str);
+            if (caps == NULL) {
+                cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
+                           "Please check to make sure you have sufficient permissions, and that\n"
+                           "you have the proper interface or pipe specified.", interface_opts.name, err_str);
+                g_free(err_str);
+                exit_main(2);
+            }
+            if (caps->data_link_types == NULL) {
+                cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
+                exit_main(2);
+            }
+            if (machine_readable)      /* tab-separated values to stdout */
+                /* XXX: We need to change the format and adopt consumers */
+                print_machine_readable_if_capabilities(caps);
+            else
+                /* XXX: We might want to print also the interface name */
+                capture_opts_print_if_capabilities(caps, interface_opts.name,
+                                                   interface_opts.monitor_mode);
+            free_if_capabilities(caps);
+        }
+        exit_main(0);
+    }
+
+    /* We're supposed to do a capture, or print the BPF code for a filter. */
+
     /* Let the user know what interfaces were chosen. */
     if (capture_child) {
         for (j = 0; j < global_capture_opts.ifaces->len; j++) {
@@ -4756,43 +5035,7 @@ main(int argc, char *argv[])
         g_string_free(str, TRUE);
     }
 
-    if (list_link_layer_types) {
-        /* Get the list of link-layer types for the capture device. */
-        if_capabilities_t *caps;
-        gchar *err_str;
-        guint  ii;
-
-        for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
-            interface_options interface_opts;
-
-            interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, ii);
-            caps = get_if_capabilities(interface_opts.name,
-                                       interface_opts.monitor_mode, &err_str);
-            if (caps == NULL) {
-                cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
-                           "Please check to make sure you have sufficient permissions, and that\n"
-                           "you have the proper interface or pipe specified.", interface_opts.name, err_str);
-                g_free(err_str);
-                exit_main(2);
-            }
-            if (caps->data_link_types == NULL) {
-                cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
-                exit_main(2);
-            }
-            if (machine_readable)      /* tab-separated values to stdout */
-                /* XXX: We need to change the format and adopt consumers */
-                print_machine_readable_if_capabilities(caps);
-            else
-                /* XXX: We might want to print also the interface name */
-                capture_opts_print_if_capabilities(caps, interface_opts.name,
-                                                   interface_opts.monitor_mode);
-            free_if_capabilities(caps);
-        }
-        exit_main(0);
-    }
-
-    /* We're supposed to do a capture, or print the BPF code for a filter.
-       Process the snapshot length, as that affects the generated BPF code. */
+    /* Process the snapshot length, as that affects the generated BPF code. */
     capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
 
 #ifdef HAVE_BPF_IMAGE
@@ -4809,7 +5052,6 @@ main(int argc, char *argv[])
     fflush(stderr);
 
     /* Now start the capture. */
-
     if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
         /* capture ok */
         exit_main(0);
@@ -4861,7 +5103,7 @@ console_log_handler(const char *log_domain, GLogLevelFlags log_level,
         level = "Dbg ";
         break;
     default:
-        fprintf(stderr, "unknown log_level %u\n", log_level);
+        fprintf(stderr, "unknown log_level %d\n", log_level);
         level = NULL;
         g_assert_not_reached();
     }
@@ -4980,7 +5222,7 @@ report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
              */
             interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
             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.",
@@ -5006,23 +5248,24 @@ report_capture_error(const char *error_msg, const char *secondary_error_msg)
 }
 
 static void
-report_packet_drops(guint32 received, guint32 drops, gchar *name)
+report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
 {
     char tmp[SP_DECISIZE+1+1];
+    guint32 total_drops = pcap_drops + drops + flushed;
 
-    g_snprintf(tmp, sizeof(tmp), "%u", drops);
+    g_snprintf(tmp, sizeof(tmp), "%u", total_drops);
 
     if (capture_child) {
         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
-            "Packets received/dropped on interface %s: %u/%u",
-            name, received, drops);
+            "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
+            name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
         /* XXX: Need to provide interface id, changes to consumers required. */
         pipe_write_block(2, SP_DROPS, tmp);
     } else {
         fprintf(stderr,
-            "Packets received/dropped on interface '%s': %u/%u (%.1f%%)\n",
-            name, received, drops,
-            received ? 100.0 * received / (received + drops) : 0.0);
+            "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
+            name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
+            received ? 100.0 * received / (received + total_drops) : 0.0);
         /* stderr could be line buffered */
         fflush(stderr);
     }
@@ -5077,8 +5320,12 @@ signal_pipe_check_running(void)
 }
 #endif
 
+
+
+
+
 /*
- * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
+ * Editor modelines  -  https://www.wireshark.org/tools/modelines.html
  *
  * Local variables:
  * c-basic-offset: 4