Let's be consistent and display lte_rrc root for all LTE RRC messages
[metze/wireshark/wip.git] / dumpcap.c
index 21e342c1ffb33067d5881ea7c431eefb2404bcf7..8bac9138e949ef342f894966a5a6b49bfa25c805 100644 (file)
--- a/dumpcap.c
+++ b/dumpcap.c
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  */
 
-#ifdef HAVE_CONFIG_H
-# include "config.h"
-#endif
+#include "config.h"
 
 #include <stdio.h>
 #include <stdlib.h> /* for exit() */
 # include <sys/types.h>
 #endif
 
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+
 #ifdef HAVE_SYS_STAT_H
 # include <sys/stat.h>
 #endif
@@ -91,7 +97,6 @@
 #endif
 
 #ifndef _WIN32
-#include <sys/socket.h>
 #include <sys/un.h>
 #endif
 
 #include "log.h"
 #include "wsutil/file_util.h"
 
+#include "ws80211_utils.h"
+
 /*
  * Get information about libpcap format from "wiretap/libpcap.h".
  * XXX - can we just use pcap_open_offline() to read the pipe?
@@ -155,6 +162,8 @@ static gboolean infoprint;      /* if TRUE, print capture info after clearing in
 
 /** Stop a low-level capture (stops the capture child). */
 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_);
 
 #if !defined (__linux__)
 #ifndef HAVE_PCAP_BREAKLOOP
@@ -227,15 +236,16 @@ typedef struct _pcap_options {
     GThread        *tid;
     int            snaplen;
     int            linktype;
+    gboolean       ts_nsec;               /* TRUE if we're using nanosecond precision. */
     /* capture pipe (unix only "input file") */
     gboolean       from_cap_pipe;         /* TRUE if we are capturing data from a capture pipe */
+    gboolean       from_cap_socket;       /* TRUE if we're capturing from socket */
     struct pcap_hdr cap_pipe_hdr;         /* Pcap header when capturing from a pipe */
     struct pcaprec_modified_hdr cap_pipe_rechdr;  /* Pcap record header when capturing from a pipe */
 #ifdef _WIN32
     HANDLE         cap_pipe_h;            /* The handle of the capture pipe */
-#else
-    int            cap_pipe_fd;           /* the file descriptor of the capture pipe */
 #endif
+    int            cap_pipe_fd;           /* the file descriptor of the capture pipe */
     gboolean       cap_pipe_modified;     /* TRUE if data in the pipe uses modified pcap headers */
     gboolean       cap_pipe_byte_swapped; /* TRUE if data in the pipe is byte swapped */
 #if defined(_WIN32)
@@ -262,7 +272,7 @@ typedef struct _loop_data {
     int            err;                   /* if non-zero, error seen while capturing */
     gint           packet_count;          /* Number of packets we have already captured */
     gint           packet_max;            /* Number of packets we're supposed to capture - 0 means infinite */
-    gint           inpkts_to_sync_pipe;   /* Packets not already send out to the sync_pipe */
+    guint          inpkts_to_sync_pipe;   /* Packets not already send out to the sync_pipe */
 #ifdef SIGINFO
     gboolean       report_packet_count;   /* Set by SIGINFO handler; print packet count */
 #endif
@@ -337,6 +347,7 @@ console_log_handler(const char *log_domain, GLogLevelFlags log_level,
 static capture_options global_capture_opts;
 static gboolean quiet = FALSE;
 static gboolean use_threads = FALSE;
+static guint64 start_time;
 
 static void capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
                                          const u_char *pd);
@@ -348,13 +359,65 @@ static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fna
 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(int packet_count);
+static void report_packet_count(unsigned int packet_count);
 static void report_packet_drops(guint32 received, guint32 drops, 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()*/
+static guint64
+create_timestamp(void) {
+    guint64 timestamp;
+#ifdef _WIN32
+    FILETIME now;
+#else
+    struct timeval now;
+#endif
+
+#ifdef _WIN32
+    /*
+     * Current time, represented as 100-nanosecond intervals since
+     * January 1, 1601, 00:00:00 UTC.
+     *
+     * I think DWORD might be signed, so cast both parts of "now"
+     * to guint32 so that the sign bit doesn't get treated specially.
+     *
+     * Windows 8 provides GetSystemTimePreciseAsFileTime which we
+     * might want to use instead.
+     */
+    GetSystemTimeAsFileTime(&now);
+    timestamp = (((guint64)(guint32)now.dwHighDateTime) << 32) +
+                (guint32)now.dwLowDateTime;
+
+    /*
+     * Convert to same thing but as 1-microsecond, i.e. 1000-nanosecond,
+     * intervals.
+     */
+    timestamp /= 10;
+
+    /*
+     * 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);
+#else
+    /*
+     * Current time, represented as seconds and microseconds since
+     * January 1, 1970, 00:00:00 UTC.
+     */
+    gettimeofday(&now, NULL);
+
+    /*
+     * Convert to delta in microseconds.
+     */
+    timestamp = (guint64)(now.tv_sec) * 1000000 +
+                (guint64)(now.tv_usec);
+#endif
+    return timestamp;
+}
+
 static void
 print_usage(gboolean print_ver)
 {
@@ -373,7 +436,10 @@ print_usage(gboolean print_ver)
     fprintf(output, "\nUsage: dumpcap [options] ...\n");
     fprintf(output, "\n");
     fprintf(output, "Capture interface:\n");
-    fprintf(output, "  -i <interface>           name or idx of interface (def: first non-loopback)\n");
+    fprintf(output, "  -i <interface>           name or idx of interface (def: first non-loopback),\n"
+                    "                           or for remote capturing, use one of these formats:\n"
+                    "                               rpcap://<host>/<interface>\n"
+                    "                               TCP@<host>:<port>\n");
     fprintf(output, "  -f <capture filter>      packet filter in libpcap filter syntax\n");
     fprintf(output, "  -s <snaplen>             packet snapshot length (def: 65535)\n");
     fprintf(output, "  -p                       don't capture in promiscuous mode\n");
@@ -389,6 +455,7 @@ print_usage(gboolean print_ver)
 #ifdef HAVE_BPF_IMAGE
     fprintf(output, "  -d                       print generated BPF code for capture filter\n");
 #endif
+    fprintf(output, "  -k                       set channel on wifi interface <freq>,[<type>]\n");
     fprintf(output, "  -S                       print statistics for each interface once per second\n");
     fprintf(output, "  -M                       for -D, -L, and -S, produce machine-readable output\n");
     fprintf(output, "\n");
@@ -425,7 +492,7 @@ print_usage(gboolean print_ver)
     fprintf(output, "  -h                       display this help and exit\n");
     fprintf(output, "\n");
     fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
-    fprintf(output, "\"Capture network packets from interface eth0 until 60s passed into 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");
 }
@@ -583,6 +650,16 @@ open_capture_device(interface_options *interface_opts,
                            (interface_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
                            (interface_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
                            CAP_READ_TIMEOUT, &auth, *open_err_str);
+        if (pcap_h == NULL) {
+            /* Error - did pcap actually supply an error message? */
+            if ((*open_err_str)[0] == '\0') {
+                /* Work around known WinPcap bug wherein no error message is
+                   filled in on a failure to open an rpcap: URL. */
+                g_strlcpy(*open_err_str,
+                          "Unknown error (pcap bug; actual error cause not reported)",
+                          sizeof *open_err_str);
+            }
+        }
         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
               "pcap_open() returned %p.", (void *)pcap_h);
     } else
@@ -604,13 +681,13 @@ open_capture_device(interface_options *interface_opts,
                   "Calling pcap_set_snaplen() with snaplen %d.", interface_opts->snaplen);
             pcap_set_snaplen(pcap_h, interface_opts->snaplen);
             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
-                  "Calling pcap_set_snaplen() with promisc_mode %d.", interface_opts->promisc_mode);
+                  "Calling pcap_set_promisc() with promisc_mode %d.", interface_opts->promisc_mode);
             pcap_set_promisc(pcap_h, interface_opts->promisc_mode);
             pcap_set_timeout(pcap_h, CAP_READ_TIMEOUT);
 
             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
                   "buffersize %d.", interface_opts->buffer_size);
-            if (interface_opts->buffer_size > 1) {
+            if (interface_opts->buffer_size != 0) {
                 pcap_set_buffer_size(pcap_h, interface_opts->buffer_size * 1024 * 1024);
             }
             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
@@ -656,28 +733,11 @@ get_capture_device_open_failure_messages(const char *open_err_str,
                                          char *secondary_errmsg,
                                          size_t secondary_errmsg_len)
 {
+#ifndef _WIN32
     const char *libpcap_warn;
     static const char ppamsg[] = "can't find PPA for ";
+#endif
 
-    /* If we got a "can't find PPA for X" message, warn the user (who
-       is running dumcap on HP-UX) that they don't have a version of
-       libpcap that properly handles HP-UX (libpcap 0.6.x and later
-       versions, which properly handle HP-UX, say "can't find /dev/dlpi
-       PPA for X" rather than "can't find PPA for X"). */
-    if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
-        libpcap_warn =
-            "\n\n"
-            "You are running (T)Wireshark with a version of the libpcap library\n"
-            "that doesn't handle HP-UX network devices well; this means that\n"
-            "(T)Wireshark may not be able to capture packets.\n"
-            "\n"
-            "To fix this, you should install libpcap 0.6.2, or a later version\n"
-            "of libpcap, rather than libpcap 0.4 or 0.5.x.  It is available in\n"
-            "packaged binary form from the Software Porting And Archive Centre\n"
-            "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
-            "at the URL lists a number of mirror sites.";
-    else
-        libpcap_warn = "";
     g_snprintf(errmsg, (gulong) errmsg_len,
                "The capture session could not be initiated (%s).", open_err_str);
 #ifdef _WIN32
@@ -711,6 +771,26 @@ get_capture_device_open_failure_messages(const char *open_err_str,
                  iface);
     }
 #else
+    /* If we got a "can't find PPA for X" message, warn the user (who
+       is running dumpcap on HP-UX) that they don't have a version of
+       libpcap that properly handles HP-UX (libpcap 0.6.x and later
+       versions, which properly handle HP-UX, say "can't find /dev/dlpi
+       PPA for X" rather than "can't find PPA for X"). */
+    if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
+        libpcap_warn =
+            "\n\n"
+            "You are running (T)Wireshark with a version of the libpcap library\n"
+            "that doesn't handle HP-UX network devices well; this means that\n"
+            "(T)Wireshark may not be able to capture packets.\n"
+            "\n"
+            "To fix this, you should install libpcap 0.6.2, or a later version\n"
+            "of libpcap, rather than libpcap 0.4 or 0.5.x.  It is available in\n"
+            "packaged binary form from the Software Porting And Archive Centre\n"
+            "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
+            "at the URL lists a number of mirror sites.";
+    else
+        libpcap_warn = "";
+
     g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
                "Please check to make sure you have sufficient permissions, and that you have "
                "the proper interface or pipe specified.%s", libpcap_warn);
@@ -1045,12 +1125,27 @@ get_if_capabilities(const char *devname, gboolean monitor_mode
      */
     caps = g_malloc(sizeof *caps);
 
+    /*
+     * WinPcap 4.1.2, and possibly earlier versions, have a bug
+     * wherein, when an open with an rpcap: URL fails, the error
+     * message for the error is not copied to errbuf and whatever
+     * on-the-stack junk is in errbuf is treated as the error
+     * message.
+     *
+     * To work around that (and any other bugs of that sort, we
+     * initialize errbuf to an empty string.  If we get an error
+     * and the string is empty, we report it as an unknown error.
+     * (If we *don't* get an error, and the string is *non*-empty,
+     * that could be a warning returned, such as "can't turn
+     * promiscuous mode on"; we currently don't do so.)
+     */
+    errbuf[0] = '\0';
 #ifdef HAVE_PCAP_OPEN
     pch = pcap_open(devname, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
     caps->can_set_rfmon = FALSE;
     if (pch == NULL) {
         if (err_str != NULL)
-            *err_str = g_strdup(errbuf);
+            *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
         g_free(caps);
         return NULL;
     }
@@ -1109,7 +1204,7 @@ get_if_capabilities(const char *devname, gboolean monitor_mode
     caps->can_set_rfmon = FALSE;
     if (pch == NULL) {
         if (err_str != NULL)
-            *err_str = g_strdup(errbuf);
+            *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
         g_free(caps);
         return NULL;
     }
@@ -1121,6 +1216,7 @@ get_if_capabilities(const char *devname, gboolean monitor_mode
         pcap_close(pch);
         if (err_str != NULL)
             *err_str = NULL; /* an empty list doesn't mean an error */
+        g_free(caps);
         return NULL;
     }
     caps->data_link_types = NULL;
@@ -1569,6 +1665,23 @@ cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcapr
     }
 }
 
+/* Wrapper: distinguish between recv/read if we're reading on Windows,
+ * or just read().
+ */
+static int
+cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
+{
+#ifdef _WIN32
+   if (from_socket) {
+      return recv(pipe_fd, buf, (int)sz, 0);
+   } else {
+      return -1;
+   }
+#else
+   return ws_read(pipe_fd, buf, sz);
+#endif
+}
+
 #if defined(_WIN32)
 /*
  * Thread function that reads from a pipe and pushes the data
@@ -1583,10 +1696,10 @@ cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcapr
  * the queues themselves (yet).
  *
  * We might want to move some of the cap_pipe_dispatch logic here so that
- * we can let cap_pipe_read run independently, queuing up multiple reads
+ * we can let cap_thread_read run independently, queuing up multiple reads
  * for the main thread (and possibly get rid of cap_pipe_read_mtx).
  */
-static void *cap_pipe_read(void *arg)
+static void *cap_thread_read(void *arg)
 {
     pcap_options *pcap_opts;
     int bytes_read;
@@ -1603,48 +1716,57 @@ static void *cap_pipe_read(void *arg)
         g_mutex_lock(pcap_opts->cap_pipe_read_mtx);
         bytes_read = 0;
         while (bytes_read < (int) pcap_opts->cap_pipe_bytes_to_read) {
+           if ((pcap_opts->from_cap_socket)
+#ifndef _WIN32
+              || 1
+#endif
+              )
+           {
+               b = cap_pipe_read(pcap_opts->cap_pipe_fd, pcap_opts->cap_pipe_buf+bytes_read,
+                        pcap_opts->cap_pipe_bytes_to_read - bytes_read, pcap_opts->from_cap_socket);
+               if (b <= 0) {
+                   if (b == 0) {
+                       pcap_opts->cap_pipe_err = PIPEOF;
+                       bytes_read = 0;
+                       break;
+                   } else {
+                       pcap_opts->cap_pipe_err = PIPERR;
+                       bytes_read = -1;
+                       break;
+                   }
+               } else {
+                   bytes_read += b;
+               }
+           }
 #ifdef _WIN32
-            /* If we try to use read() on a named pipe on Windows with partial
-             * data it appears to return EOF.
-             */
-            res = ReadFile(pcap_opts->cap_pipe_h, pcap_opts->cap_pipe_buf+bytes_read,
-                           pcap_opts->cap_pipe_bytes_to_read - bytes_read,
-                           &b, NULL);
-
-            bytes_read += b;
-            if (!res) {
-                last_err = GetLastError();
-                if (last_err == ERROR_MORE_DATA) {
-                    continue;
-                } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
-                    pcap_opts->cap_pipe_err = PIPEOF;
-                    bytes_read = 0;
-                    break;
-                }
-                pcap_opts->cap_pipe_err = PIPERR;
-                bytes_read = -1;
-                break;
-            } else if (b == 0 && pcap_opts->cap_pipe_bytes_to_read > 0) {
-                pcap_opts->cap_pipe_err = PIPEOF;
-                bytes_read = 0;
-                break;
-            }
-#else /* _WIN32 */
-            b = read(pcap_opts->cap_pipe_fd, pcap_opts->cap_pipe_buf+bytes_read,
-                     pcap_opts->cap_pipe_bytes_to_read - bytes_read);
-            if (b <= 0) {
-                if (b == 0) {
-                    pcap_opts->cap_pipe_err = PIPEOF;
-                    bytes_read = 0;
-                    break;
-                } else {
-                    pcap_opts->cap_pipe_err = PIPERR;
-                    bytes_read = -1;
-                    break;
-                }
-            } else {
-                bytes_read += b;
-            }
+           else
+           {
+               /* If we try to use read() on a named pipe on Windows with partial
+                * data it appears to return EOF.
+                */
+               res = ReadFile(pcap_opts->cap_pipe_h, pcap_opts->cap_pipe_buf+bytes_read,
+                              pcap_opts->cap_pipe_bytes_to_read - bytes_read,
+                              &b, NULL);
+
+               bytes_read += b;
+               if (!res) {
+                   last_err = GetLastError();
+                   if (last_err == ERROR_MORE_DATA) {
+                       continue;
+                   } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
+                       pcap_opts->cap_pipe_err = PIPEOF;
+                       bytes_read = 0;
+                       break;
+                   }
+                   pcap_opts->cap_pipe_err = PIPERR;
+                   bytes_read = -1;
+                   break;
+               } else if (b == 0 && pcap_opts->cap_pipe_bytes_to_read > 0) {
+                   pcap_opts->cap_pipe_err = PIPEOF;
+                   bytes_read = 0;
+                   break;
+               }
+           }
 #endif /*_WIN32 */
         }
         pcap_opts->cap_pipe_bytes_read = bytes_read;
@@ -1657,7 +1779,6 @@ static void *cap_pipe_read(void *arg)
 }
 #endif
 
-#if !defined(_WIN32) || defined(MUST_DO_SELECT)
 /* Provide select() functionality for a single file descriptor
  * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
  *
@@ -1677,8 +1798,102 @@ cap_pipe_select(int pipe_fd)
 
     return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
 }
+
+#define DEF_TCP_PORT 19000
+
+static int
+cap_open_socket(char *pipename, pcap_options *pcap_opts, char *errmsg, int errmsgl)
+{
+  char *sockname = pipename + 4;
+  struct sockaddr_in sa;
+  char buf[16];
+  char *p;
+  unsigned long port;
+  size_t len;
+  int fd;
+
+  memset(&sa, 0, sizeof(sa));
+
+  p = strchr(sockname, ':');
+  if (p == NULL) {
+    len = strlen(sockname);
+    port = DEF_TCP_PORT;
+  }
+  else {
+    len = p - sockname;
+    port = strtoul(p + 1, &p, 10);
+    if (*p || port > 65535) {
+      goto fail_invalid;
+    }
+  }
+
+  if (len > 15) {
+    goto fail_invalid;
+  }
+
+  strncpy(buf, sockname, len);
+  buf[len] = '\0';
+  if (!inet_pton(AF_INET, buf, &sa.sin_addr)) {
+    goto fail_invalid;
+  }
+
+  sa.sin_family = AF_INET;
+  sa.sin_port = htons((u_short)port);
+
+  if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
+      (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
+#ifdef _WIN32
+      LPTSTR errorText = NULL;
+      int lastError;
+
+      lastError = WSAGetLastError();
+      FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
+                    FORMAT_MESSAGE_ALLOCATE_BUFFER |
+                    FORMAT_MESSAGE_IGNORE_INSERTS,
+                    NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+                    (LPTSTR)&errorText, 0, NULL);
+#endif
+      g_snprintf(errmsg, errmsgl,
+      "The capture session could not be initiated due to the socket error: \n"
+#ifdef _WIN32
+      "         %d: %S", lastError, errorText ? (char *)errorText : "Unknown");
+      if (errorText)
+          LocalFree(errorText);
+#else
+      "         %d: %s", errno, strerror(errno));
 #endif
+      pcap_opts->cap_pipe_err = PIPERR;
+
+      if (fd >= 0)
+          cap_pipe_close(fd, TRUE);
+      return -1;
+  }
+
+  pcap_opts->from_cap_socket = TRUE;
+  return fd;
+
+fail_invalid:
+  g_snprintf(errmsg, errmsgl,
+      "The capture session could not be initiated because\n"
+      "\"%s\" is not a valid socket specification", pipename);
+  pcap_opts->cap_pipe_err = PIPERR;
+  return -1;
+}
 
+/* Wrapper: distinguish between closesocket on Windows; use ws_close
+ * otherwise.
+ */
+static void
+cap_pipe_close(int pipe_fd, gboolean from_socket _U_)
+{
+#ifdef _WIN32
+   if (from_socket) {
+      closesocket(pipe_fd);
+   }
+#else
+   ws_close(pipe_fd);
+#endif
+}
 
 /* Mimic pcap_open_live() for pipe captures
 
@@ -1696,23 +1911,16 @@ cap_pipe_open_live(char *pipename,
 #ifndef _WIN32
     ws_statb64   pipe_stat;
     struct sockaddr_un sa;
-    int          b;
-    int          fd;
 #else /* _WIN32 */
-#if 1
     char *pncopy, *pos;
     wchar_t *err_str;
 #endif
-#endif
-#ifndef _WIN32
-    int          sel_ret;
+    int          b, fd, sel_ret;
     unsigned int bytes_read;
-#endif
     guint32       magic = 0;
 
-#ifndef _WIN32
     pcap_opts->cap_pipe_fd = -1;
-#else
+#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);
@@ -1727,6 +1935,10 @@ cap_pipe_open_live(char *pipename,
 #else /* _WIN32 */
         pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
 #endif  /* _WIN32 */
+    } else if (!strncmp(pipename, "TCP@", 4)) {
+       if ((fd = cap_open_socket(pipename, pcap_opts, errmsg, errmsgl)) < 0) {
+          return;
+       }
     } else {
 #ifndef _WIN32
         if (ws_stat64(pipename, &pipe_stat) < 0) {
@@ -1788,6 +2000,7 @@ cap_pipe_open_live(char *pipename,
                            "The capture session coud not be initiated "
                            "due to error on socket connect: Path name too long");
                 pcap_opts->cap_pipe_err = PIPERR;
+                ws_close(fd);
                 return;
             }
             b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
@@ -1796,6 +2009,7 @@ cap_pipe_open_live(char *pipename,
                            "The capture session coud not be initiated "
                            "due to error on socket connect: %s", g_strerror(errno));
                 pcap_opts->cap_pipe_err = PIPERR;
+                ws_close(fd);
                 return;
             }
         } else {
@@ -1845,7 +2059,7 @@ cap_pipe_open_live(char *pipename,
                 break;
 
             if (GetLastError() != ERROR_PIPE_BUSY) {
-                FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
+                FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
                               NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
                 g_snprintf(errmsg, errmsgl,
                            "The capture session on \"%s\" could not be started "
@@ -1857,7 +2071,7 @@ cap_pipe_open_live(char *pipename,
             }
 
             if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
-                FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
+                FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
                               NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
                 g_snprintf(errmsg, errmsgl,
                            "The capture session on \"%s\" timed out during "
@@ -1873,54 +2087,63 @@ cap_pipe_open_live(char *pipename,
 
     pcap_opts->from_cap_pipe = TRUE;
 
+    if ((pcap_opts->from_cap_socket)
 #ifndef _WIN32
-    /* read the pcap header */
-    bytes_read = 0;
-    while (bytes_read < sizeof magic) {
-        sel_ret = cap_pipe_select(fd);
-        if (sel_ret < 0) {
-            g_snprintf(errmsg, errmsgl,
-                       "Unexpected error from select: %s", g_strerror(errno));
-            goto error;
-        } else if (sel_ret > 0) {
-            b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
-            if (b <= 0) {
-                if (b == 0)
-                    g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
-                else
-                    g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
-                               g_strerror(errno));
-                goto error;
-            }
-            bytes_read += b;
-        }
+         || 1
+#endif
+         )
+    {
+       /* read the pcap header */
+       bytes_read = 0;
+       while (bytes_read < sizeof magic) {
+           sel_ret = cap_pipe_select(fd);
+           if (sel_ret < 0) {
+               g_snprintf(errmsg, errmsgl,
+                          "Unexpected error from select: %s", g_strerror(errno));
+               goto error;
+           } else if (sel_ret > 0) {
+               b = cap_pipe_read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read, pcap_opts->from_cap_socket);
+               if (b <= 0) {
+                   if (b == 0)
+                       g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
+                   else
+                       g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
+                                  g_strerror(errno));
+                   goto error;
+               }
+               bytes_read += b;
+           }
+       }
     }
-#else
-    g_thread_create(&cap_pipe_read, pcap_opts, FALSE, NULL);
-
-    pcap_opts->cap_pipe_buf = (char *) &magic;
-    pcap_opts->cap_pipe_bytes_read = 0;
-    pcap_opts->cap_pipe_bytes_to_read = sizeof(magic);
-    /* We don't have to worry about cap_pipe_read_mtx here */
-    g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
-    g_async_queue_pop(pcap_opts->cap_pipe_done_q);
-    if (pcap_opts->cap_pipe_bytes_read <= 0) {
-        if (pcap_opts->cap_pipe_bytes_read == 0)
-            g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
-        else
-            g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
-                       g_strerror(errno));
-        goto error;
+#ifdef _WIN32
+    else {
+       g_thread_create(&cap_thread_read, pcap_opts, FALSE, NULL);
+
+       pcap_opts->cap_pipe_buf = (char *) &magic;
+       pcap_opts->cap_pipe_bytes_read = 0;
+       pcap_opts->cap_pipe_bytes_to_read = sizeof(magic);
+       /* We don't have to worry about cap_pipe_read_mtx here */
+       g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
+       g_async_queue_pop(pcap_opts->cap_pipe_done_q);
+       if (pcap_opts->cap_pipe_bytes_read <= 0) {
+           if (pcap_opts->cap_pipe_bytes_read == 0)
+               g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
+           else
+               g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
+                          g_strerror(errno));
+           goto error;
+       }
     }
-
 #endif
 
     switch (magic) {
     case PCAP_MAGIC:
+    case PCAP_NSEC_MAGIC:
         /* Host that wrote it has our byte order, and was running
            a program using either standard or ss990417 libpcap. */
         pcap_opts->cap_pipe_byte_swapped = FALSE;
         pcap_opts->cap_pipe_modified = FALSE;
+        pcap_opts->ts_nsec = magic == PCAP_NSEC_MAGIC;
         break;
     case PCAP_MODIFIED_MAGIC:
         /* Host that wrote it has our byte order, but was running
@@ -1929,11 +2152,13 @@ cap_pipe_open_live(char *pipename,
         pcap_opts->cap_pipe_modified = TRUE;
         break;
     case PCAP_SWAPPED_MAGIC:
+    case PCAP_SWAPPED_NSEC_MAGIC:
         /* Host that wrote it has a byte order opposite to ours,
            and was running a program using either standard or
            ss990417 libpcap. */
         pcap_opts->cap_pipe_byte_swapped = TRUE;
         pcap_opts->cap_pipe_modified = FALSE;
+        pcap_opts->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
         break;
     case PCAP_SWAPPED_MODIFIED_MAGIC:
         /* Host that wrote it out has a byte order opposite to
@@ -1948,42 +2173,50 @@ cap_pipe_open_live(char *pipename,
         goto error;
     }
 
+    if ((pcap_opts->from_cap_socket)
 #ifndef _WIN32
-    /* Read the rest of the header */
-    bytes_read = 0;
-    while (bytes_read < sizeof(struct pcap_hdr)) {
-        sel_ret = cap_pipe_select(fd);
-        if (sel_ret < 0) {
-            g_snprintf(errmsg, errmsgl,
-                       "Unexpected error from select: %s", g_strerror(errno));
-            goto error;
-        } else if (sel_ret > 0) {
-            b = read(fd, ((char *)hdr)+bytes_read,
-                     sizeof(struct pcap_hdr) - bytes_read);
-            if (b <= 0) {
-                if (b == 0)
-                    g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
-                else
-                    g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
-                               g_strerror(errno));
-                goto error;
-            }
-            bytes_read += b;
-        }
+         || 1
+#endif
+         )
+    {
+       /* Read the rest of the header */
+       bytes_read = 0;
+       while (bytes_read < sizeof(struct pcap_hdr)) {
+           sel_ret = cap_pipe_select(fd);
+           if (sel_ret < 0) {
+               g_snprintf(errmsg, errmsgl,
+                          "Unexpected error from select: %s", g_strerror(errno));
+               goto error;
+           } else if (sel_ret > 0) {
+               b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
+                        sizeof(struct pcap_hdr) - bytes_read, pcap_opts->from_cap_socket);
+               if (b <= 0) {
+                   if (b == 0)
+                       g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
+                   else
+                       g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
+                                  g_strerror(errno));
+                   goto error;
+               }
+               bytes_read += b;
+           }
+       }
     }
-#else
-    pcap_opts->cap_pipe_buf = (char *) hdr;
-    pcap_opts->cap_pipe_bytes_read = 0;
-    pcap_opts->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
-    g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
-    g_async_queue_pop(pcap_opts->cap_pipe_done_q);
-    if (pcap_opts->cap_pipe_bytes_read <= 0) {
-        if (pcap_opts->cap_pipe_bytes_read == 0)
-            g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
-        else
-            g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
-                       g_strerror(errno));
-        goto error;
+#ifdef _WIN32
+    else {
+       pcap_opts->cap_pipe_buf = (char *) hdr;
+       pcap_opts->cap_pipe_bytes_read = 0;
+       pcap_opts->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
+       g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
+       g_async_queue_pop(pcap_opts->cap_pipe_done_q);
+       if (pcap_opts->cap_pipe_bytes_read <= 0) {
+           if (pcap_opts->cap_pipe_bytes_read == 0)
+               g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
+           else
+               g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
+                          g_strerror(errno));
+           goto error;
+       }
     }
 #endif
 
@@ -2003,18 +2236,14 @@ cap_pipe_open_live(char *pipename,
 
     pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
     pcap_opts->cap_pipe_err = PIPOK;
-#ifndef _WIN32
     pcap_opts->cap_pipe_fd = fd;
-#endif
     return;
 
 error:
     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
     pcap_opts->cap_pipe_err = PIPERR;
-#ifndef _WIN32
-    ws_close(fd);
+    cap_pipe_close(fd, pcap_opts->from_cap_socket);
     pcap_opts->cap_pipe_fd = -1;
-#endif
     return;
 
 }
@@ -2029,14 +2258,13 @@ cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *er
     enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
            PD_ERR } result;
 #ifdef _WIN32
+#if !GLIB_CHECK_VERSION(2,31,18)
     GTimeVal wait_time;
-    gpointer q_status;
-#else
-    int b;
 #endif
-#ifdef _WIN32
+    gpointer q_status;
     wchar_t *err_str;
 #endif
+    int b;
 
 #ifdef LOG_CAPTURE_VERBOSE
     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
@@ -2063,9 +2291,14 @@ 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
-        b = 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);
+         || 1
+#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) {
             if (b == 0)
                 result = PD_PIPE_EOF;
@@ -2074,10 +2307,17 @@ cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *er
             break;
         }
         pcap_opts->cap_pipe_bytes_read += b;
+      }
+#ifdef _WIN32
+      else
+      {
+#if GLIB_CHECK_VERSION(2,31,18)
+        q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
 #else
         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
         if (pcap_opts->cap_pipe_err == PIPEOF) {
             result = PD_PIPE_EOF;
             break;
@@ -2088,6 +2328,7 @@ cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *er
         if (!q_status) {
             return 0;
         }
+      }
 #endif
         if ((pcap_opts->cap_pipe_bytes_read) < pcap_opts->cap_pipe_bytes_to_read)
             return 0;
@@ -2112,9 +2353,14 @@ 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
-        b = 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);
+         || 1
+#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, pcap_opts->from_cap_socket);
         if (b <= 0) {
             if (b == 0)
                 result = PD_PIPE_EOF;
@@ -2123,10 +2369,18 @@ cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *er
             break;
         }
         pcap_opts->cap_pipe_bytes_read += b;
+      }
+#ifdef _WIN32
+      else
+      {
+
+#if GLIB_CHECK_VERSION(2,31,18)
+        q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
 #else
         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
         if (pcap_opts->cap_pipe_err == PIPEOF) {
             result = PD_PIPE_EOF;
             break;
@@ -2137,6 +2391,7 @@ cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *er
         if (!q_status) {
             return 0;
         }
+      }
 #endif
         if ((pcap_opts->cap_pipe_bytes_read) < pcap_opts->cap_pipe_bytes_to_read)
             return 0;
@@ -2147,7 +2402,7 @@ cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *er
         g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
         result = PD_ERR;
 
-    } /* switch (ld->cap_pipe_state) */
+    } /* switch (pcap_opts->cap_pipe_state) */
 
     /*
      * We've now read as much data as we were expecting, so process it.
@@ -2191,7 +2446,7 @@ cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *er
 
     case PD_PIPE_ERR:
 #ifdef _WIN32
-        FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
+        FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
                       NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
         g_snprintf(errmsg, errmsgl,
                    "Error reading from pipe: %s (error %d)",
@@ -2281,7 +2536,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 mulitple interfaces!");
+                   "Using threads is required for capturing on multiple interfaces!");
         return FALSE;
     }
 
@@ -2304,14 +2559,15 @@ capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
         pcap_opts->tid = NULL;
         pcap_opts->snaplen = 0;
         pcap_opts->linktype = -1;
+        pcap_opts->ts_nsec = FALSE;
         pcap_opts->from_cap_pipe = FALSE;
+        pcap_opts->from_cap_socket = FALSE;
         memset(&pcap_opts->cap_pipe_hdr, 0, sizeof(struct pcap_hdr));
         memset(&pcap_opts->cap_pipe_rechdr, 0, sizeof(struct pcaprec_modified_hdr));
 #ifdef _WIN32
         pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
-#else
-        pcap_opts->cap_pipe_fd = -1;
 #endif
+        pcap_opts->cap_pipe_fd = -1;
         pcap_opts->cap_pipe_modified = FALSE;
         pcap_opts->cap_pipe_byte_swapped = FALSE;
 #ifdef _WIN32
@@ -2469,13 +2725,12 @@ static void capture_loop_close_input(loop_data *ld)
     for (i = 0; i < ld->pcaps->len; i++) {
         pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
         /* if open, close the capture pipe "input file" */
-#ifndef _WIN32
         if (pcap_opts->cap_pipe_fd >= 0) {
             g_assert(pcap_opts->from_cap_pipe);
-            ws_close(pcap_opts->cap_pipe_fd);
+            cap_pipe_close(pcap_opts->cap_pipe_fd, pcap_opts->from_cap_socket);
             pcap_opts->cap_pipe_fd = -1;
         }
-#else
+#ifdef _WIN32
         if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE) {
             CloseHandle(pcap_opts->cap_pipe_h);
             pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
@@ -2546,7 +2801,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 mulitple interfaces! Use the -n option.");
+                   "Using PCAPNG is required for capturing on multiple interfaces! Use the -n option.");
         return FALSE;
     }
 
@@ -2559,9 +2814,21 @@ 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;
+
+            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(ld->pdh, appname, &ld->bytes_written, &err);
+            successful = libpcap_write_session_header_block(ld->pdh,
+                                NULL,                        /* Comment*/
+                                NULL,                        /* HW*/
+                                os_info_str->str,            /* OS*/
+                                appname,
+                                -1,                          /* section_length */
+                                &ld->bytes_written,
+                                &err);
+
             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(ld->pcaps, pcap_options *, i);
@@ -2570,14 +2837,22 @@ 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(ld->pdh,
-                                                                       interface_opts.name,
-                                                                       interface_opts.cfilter?interface_opts.cfilter:"",
+                successful = libpcap_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,
-                                                                       &ld->bytes_written,
-                                                                       &err);
+                                                                       &(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(ld->pcaps, pcap_options *, 0);
             if (pcap_opts->from_cap_pipe) {
@@ -2586,7 +2861,7 @@ capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *err
                 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
             }
             successful = libpcap_write_file_header(ld->pdh, pcap_opts->linktype, pcap_opts->snaplen,
-                                                   &ld->bytes_written, &err);
+                                                   pcap_opts->ts_nsec, &ld->bytes_written, &err);
         }
         if (!successful) {
             fclose(ld->pdh);
@@ -2626,6 +2901,7 @@ capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err
 
     unsigned int i;
     pcap_options *pcap_opts;
+    guint64 end_time = create_timestamp();
 
     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
 
@@ -2636,7 +2912,25 @@ capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err
             for (i = 0; i < global_ld.pcaps->len; i++) {
                 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
                 if (!pcap_opts->from_cap_pipe) {
-                    libpcap_write_interface_statistics_block(ld->pdh, i, pcap_opts->pcap_h, &ld->bytes_written, err_close);
+                    guint64 isb_ifrecv, isb_ifdrop;
+                    struct pcap_stat stats;
+
+                    if (pcap_stats(pcap_opts->pcap_h, &stats) >= 0) {
+                        isb_ifrecv = pcap_opts->received;
+                        isb_ifdrop = stats.ps_drop + pcap_opts->dropped;
+                   } else {
+                        isb_ifrecv = G_MAXUINT64;
+                        isb_ifdrop = G_MAXUINT64;
+                    }
+                    libpcap_write_interface_statistics_block(ld->pdh,
+                                                             i,
+                                                             &ld->bytes_written,
+                                                             "Counters provided by dumpcap",
+                                                             start_time,
+                                                             end_time,
+                                                             isb_ifrecv,
+                                                             isb_ifdrop,
+                                                             err_close);
                 }
             }
         }
@@ -2994,24 +3288,44 @@ do_file_switch_or_stop(capture_options *capture_opts,
             global_ld.bytes_written = 0;
             if (capture_opts->use_pcapng) {
                 char appname[100];
+                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(global_ld.pdh, appname, &(global_ld.bytes_written), &global_ld.err);
+                successful = libpcap_write_session_header_block(global_ld.pdh,
+                                NULL,                        /* Comment */
+                                NULL,                        /* HW */
+                                os_info_str->str,            /* OS */
+                                appname,
+                                                                -1,                          /* section_length */
+                                &(global_ld.bytes_written),
+                                &global_ld.err);
+
                 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(global_ld.pdh,
-                                                                           interface_opts.name,
-                                                                           interface_opts.cfilter?interface_opts.cfilter:"",
+                                                                           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(global_ld.pdh, pcap_opts->linktype, pcap_opts->snaplen,
-                                                       &global_ld.bytes_written, &global_ld.err);
+                                                       pcap_opts->ts_nsec, &global_ld.bytes_written, &global_ld.err);
             }
             if (!successful) {
                 fclose(global_ld.pdh);
@@ -3123,7 +3437,7 @@ capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct
         /* init the input filter from the network interface (capture pipe will do nothing) */
         /*
          * When remote capturing WinPCap crashes when the capture filter
-         * is NULL. This might be a bug in WPCap. Therefore we provide an emtpy
+         * is NULL. This might be a bug in WPCap. Therefore we provide an empty
          * string.
          */
         switch (capture_loop_init_filter(pcap_opts->pcap_h, pcap_opts->from_cap_pipe,
@@ -3204,7 +3518,7 @@ capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct
 #else
     gettimeofday(&upd_time, NULL);
 #endif
-
+    start_time = create_timestamp();
     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
 
     /* WOW, everything is prepared! */
@@ -3226,13 +3540,19 @@ capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct
     while (global_ld.go) {
         /* dispatch incoming packets */
         if (use_threads) {
-            GTimeVal write_thread_time;
             pcap_queue_element *queue_element;
+#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);
+#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);
+#endif
             if (queue_element) {
                 pcap_queue_bytes -= queue_element->phdr.caplen;
                 pcap_queue_packets -= 1;
@@ -3607,12 +3927,15 @@ capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr
 {
     pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
     int err;
+    guint ts_mul = pcap_opts->ts_nsec ? 1000000000 : 1000000;
 
     /* We may be called multiple times from pcap_dispatch(); if we've set
        the "stop capturing" flag, ignore this packet, as we're not
        supposed to be saving any more packets. */
-    if (!global_ld.go)
+    if (!global_ld.go) {
+        pcap_opts->dropped++;
         return;
+    }
 
     if (global_ld.pdh) {
         gboolean successful;
@@ -3621,13 +3944,14 @@ 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(global_ld.pdh, phdr, pcap_opts->interface_id, pd, &global_ld.bytes_written, &err);
+            successful = libpcap_write_enhanced_packet_block(global_ld.pdh, phdr, pcap_opts->interface_id, ts_mul, pd, &global_ld.bytes_written, &err);
         } else {
             successful = libpcap_write_packet(global_ld.pdh, phdr, pd, &global_ld.bytes_written, &err);
         }
         if (!successful) {
             global_ld.go = FALSE;
             global_ld.err = err;
+            pcap_opts->dropped++;
         } else {
             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
                   "Wrote a packet of length %d captured on interface %u.",
@@ -3654,8 +3978,10 @@ capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr
     /* We may be called multiple times from pcap_dispatch(); if we've set
        the "stop capturing" flag, ignore this packet, as we're not
        supposed to be saving any more packets. */
-    if (!global_ld.go)
+    if (!global_ld.go) {
+        pcap_opts->dropped++;
         return;
+    }
 
     queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
     if (queue_element == NULL) {
@@ -3702,6 +4028,49 @@ capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr
           pcap_queue_bytes, pcap_queue_packets);
 }
 
+static int
+set_80211_channel(const char *iface, const char *opt)
+{
+    int freq = 0, type, ret;
+    gchar **options = NULL;
+    options = g_strsplit_set(opt, ",", 2);
+
+    if (options[0])
+        freq = atoi(options[0]);
+
+    if (options[1]) {
+        type = ws80211_str_to_chan_type(options[1]);
+        if (type == -1) {
+            ret = EINVAL;
+            goto out;
+        }
+    }
+    else
+        type = -1;
+
+    ret = ws80211_init();
+    if (ret) {
+        cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
+        ret = 2;
+        goto out;
+    }
+    ret = ws80211_set_freq(iface, freq, type);
+
+    if (ret) {
+        cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
+        ret = 2;
+        goto out;
+    }
+
+    if (capture_child)
+        pipe_write_block(2, SP_SUCCESS, NULL);
+    ret = 0;
+
+out:
+    g_strfreev(options);
+    return ret;
+}
+
 /* And now our feature presentation... [ fade to music ] */
 int
 main(int argc, char *argv[])
@@ -3724,6 +4093,8 @@ main(int argc, char *argv[])
 #ifdef HAVE_BPF_IMAGE
     gboolean             print_bpf_code = FALSE;
 #endif
+    gboolean             set_chan = FALSE;
+    gchar                *set_chan_arg = NULL;
     gboolean             machine_readable = FALSE;
     gboolean             print_statistics = FALSE;
     int                  status, run_once_args = 0;
@@ -3780,7 +4151,7 @@ main(int argc, char *argv[])
 #define OPTSTRING_d ""
 #endif
 
-#define OPTSTRING "a:" OPTSTRING_A "b:" OPTSTRING_B "c:" OPTSTRING_d "Df:ghi:" OPTSTRING_I "L" OPTSTRING_m "MnpPq" OPTSTRING_r "Ss:t" OPTSTRING_u "vw:y:Z:"
+#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:"
 
 #ifdef DEBUG_CHILD_DUMPCAP
     if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
@@ -3900,7 +4271,18 @@ main(int argc, char *argv[])
     SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
 #else
     /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
-       and exit. */
+       and exit.  Do the same with SIGPIPE, in case, for example,
+       we're writing to our standard output and it's a pipe.
+       Do the same with SIGHUP if it's not being ignored (if we're
+       being run under nohup, it might be ignored, in which case we
+       should leave it ignored).
+
+       XXX - apparently, Coverity complained that part of action
+       wasn't initialized.  Perhaps it's running on Linux, where
+       struct sigaction has an ignored "sa_restorer" element and
+       where "sa_handler" and "sa_sigaction" might not be two
+       members of a union. */
+    memset(&action, 0, sizeof(action));
     action.sa_handler = capture_cleanup_handler;
     /*
      * Arrange that system calls not get restarted, because when
@@ -4123,6 +4505,11 @@ main(int argc, char *argv[])
             print_statistics = TRUE;
             run_once_args++;
             break;
+        case 'k':        /* Set wireless channel */
+            set_chan = TRUE;
+            set_chan_arg = optarg;
+            run_once_args++;
+           break;
         case 'M':        /* For -D, -L, and -S, print machine-readable output */
             machine_readable = TRUE;
             break;
@@ -4247,6 +4634,19 @@ main(int argc, char *argv[])
         exit_main(status);
     }
 
+    if (set_chan) {
+        interface_options interface_opts;
+
+        if (global_capture_opts.ifaces->len != 1) {
+            cmdarg_err("Need one interface");
+            exit_main(2);
+        }
+
+        interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
+        status = set_80211_channel(interface_opts.name, set_chan_arg);
+        exit_main(status);
+    }
+
     /*
      * "-L", "-d", and capturing act on a particular interface, so we have to
      * have an interface; if none was specified, pick a default.
@@ -4447,13 +4847,13 @@ console_log_handler(const char *log_domain, GLogLevelFlags log_level,
 
 
 static void
-report_packet_count(int packet_count)
+report_packet_count(unsigned int packet_count)
 {
     char tmp[SP_DECISIZE+1+1];
-    static int count = 0;
+    static unsigned int count = 0;
 
     if(capture_child) {
-        g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
+        g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
         pipe_write_block(2, SP_PACKET_COUNT, tmp);
     } else {