netcmd plugin: Add work-around for GCC warning.
[collectd.git] / src / netcmd.c
index cf89d13..a4c443c 100644 (file)
@@ -74,9 +74,24 @@ struct nc_peer_s
 };
 typedef struct nc_peer_s nc_peer_t;
 
+#if defined(PAGESIZE)
+# define NC_READ_BUFFER_SIZE PAGESIZE
+#elif defined(PAGE_SIZE)
+# define NC_READ_BUFFER_SIZE PAGE_SIZE
+#else
+# define NC_READ_BUFFER_SIZE 4096
+#endif
+
 struct nc_connection_s
 {
+  /* TLS fields */
   int fd;
+  char *read_buffer;
+  size_t read_buffer_fill;
+
+  /* non-TLS fields */
+  FILE *fh_in;
+  FILE *fh_out;
 
   gnutls_session_t tls_session;
   _Bool have_tls_session;
@@ -154,25 +169,72 @@ static int nc_register_fd (nc_peer_t *peer, int fd) /* {{{ */
 
 static int nc_tls_init (nc_peer_t *peer) /* {{{ */
 {
+  int status;
+
   if (peer == NULL)
     return (EINVAL);
 
   if ((peer->tls_cert_file == NULL)
       || (peer->tls_key_file == NULL))
+  {
+    DEBUG ("netcmd plugin: Not setting up TLS environment for peer.");
     return (0);
+  }
+
+  DEBUG ("netcmd plugin: Setting up TLS environment for peer.");
 
   /* Initialize the structure holding our certificate information. */
-  gnutls_certificate_allocate_credentials (&peer->tls_credentials);
+  status = gnutls_certificate_allocate_credentials (&peer->tls_credentials);
+  if (status != GNUTLS_E_SUCCESS)
+  {
+    ERROR ("netcmd plugin: gnutls_certificate_allocate_credentials failed: %s",
+        gnutls_strerror (status));
+    return (status);
+  }
 
   /* Set up the configured certificates. */
   if (peer->tls_ca_file != NULL)
-    gnutls_certificate_set_x509_trust_file (peer->tls_credentials,
+  {
+    status = gnutls_certificate_set_x509_trust_file (peer->tls_credentials,
         peer->tls_ca_file, GNUTLS_X509_FMT_PEM);
+    if (status < 0)
+    {
+      ERROR ("netcmd plugin: gnutls_certificate_set_x509_trust_file (%s) "
+          "failed: %s",
+          peer->tls_ca_file, gnutls_strerror (status));
+      return (status);
+    }
+    else
+    {
+      DEBUG ("netcmd plugin: Successfully loaded %i CA(s).", status);
+    }
+  }
+
   if (peer->tls_crl_file != NULL)
-      gnutls_certificate_set_x509_crl_file (peer->tls_credentials,
-          peer->tls_crl_file, GNUTLS_X509_FMT_PEM);
-  gnutls_certificate_set_x509_key_file (peer->tls_credentials,
+  {
+    status = gnutls_certificate_set_x509_crl_file (peer->tls_credentials,
+        peer->tls_crl_file, GNUTLS_X509_FMT_PEM);
+    if (status < 0)
+    {
+      ERROR ("netcmd plugin: gnutls_certificate_set_x509_crl_file (%s) "
+          "failed: %s",
+          peer->tls_crl_file, gnutls_strerror (status));
+      return (status);
+    }
+    else
+    {
+      DEBUG ("netcmd plugin: Successfully loaded %i CRL(s).", status);
+    }
+  }
+
+  status = gnutls_certificate_set_x509_key_file (peer->tls_credentials,
       peer->tls_cert_file, peer->tls_key_file, GNUTLS_X509_FMT_PEM);
+  if (status != GNUTLS_E_SUCCESS)
+  {
+    ERROR ("netcmd plugin: gnutls_certificate_set_x509_key_file failed: %s",
+        gnutls_strerror (status));
+    return (status);
+  }
 
   /* Initialize Diffie-Hellman parameters. */
   gnutls_dh_params_init (&peer->tls_dh_params);
@@ -191,21 +253,41 @@ static int nc_tls_init (nc_peer_t *peer) /* {{{ */
 static gnutls_session_t nc_tls_get_session (nc_peer_t *peer) /* {{{ */
 {
   gnutls_session_t session;
+  int status;
 
   if (peer->tls_credentials == NULL)
     return (NULL);
 
+  DEBUG ("netcmd plugin: nc_tls_get_session (%s)", peer->node);
+
   /* Initialize new session. */
   gnutls_init (&session, GNUTLS_SERVER);
 
   /* Set cipher priority and credentials based on the information stored with
    * the peer. */
-  gnutls_priority_set (session, peer->tls_priority);
-  gnutls_credentials_set (session,
+  status = gnutls_priority_set (session, peer->tls_priority);
+  if (status != GNUTLS_E_SUCCESS)
+  {
+    ERROR ("netcmd plugin: gnutls_priority_set failed: %s",
+        gnutls_strerror (status));
+    gnutls_deinit (session);
+    return (NULL);
+  }
+
+  status = gnutls_credentials_set (session,
       GNUTLS_CRD_CERTIFICATE, peer->tls_credentials);
+  if (status != GNUTLS_E_SUCCESS)
+  {
+    ERROR ("netcmd plugin: gnutls_credentials_set failed: %s",
+        gnutls_strerror (status));
+    gnutls_deinit (session);
+    return (NULL);
+  }
 
-  /* Request the client certificate. */
-  gnutls_certificate_server_set_request (session, GNUTLS_CERT_REQUEST);
+  /* Request the client certificate. If TLSVerifyPeer is set to true,
+   * *require* a client certificate. */
+  gnutls_certificate_server_set_request (session,
+      peer->tls_verify_peer ? GNUTLS_CERT_REQUIRE : GNUTLS_CERT_REQUEST);
 
   return (session);
 } /* }}} gnutls_session_t nc_tls_get_session */
@@ -308,6 +390,18 @@ static void nc_connection_close (nc_connection_t *conn) /* {{{ */
     conn->fd = -1;
   }
 
+  if (conn->fh_in != NULL)
+  {
+    fclose (conn->fh_in);
+    conn->fh_in = NULL;
+  }
+
+  if (conn->fh_out != NULL)
+  {
+    fclose (conn->fh_out);
+    conn->fh_out = NULL;
+  }
+
   if (conn->have_tls_session)
   {
     gnutls_deinit (conn->tls_session);
@@ -317,44 +411,217 @@ static void nc_connection_close (nc_connection_t *conn) /* {{{ */
   sfree (conn);
 } /* }}} void nc_connection_close */
 
-static void *nc_handle_client (void *arg) /* {{{ */
+static int nc_connection_init (nc_connection_t *conn) /* {{{ */
 {
-  nc_connection_t *conn;
-  FILE *fhin, *fhout;
+  int fd_copy;
   char errbuf[1024];
 
-  conn = arg;
+  DEBUG ("netcmd plugin: nc_connection_init();");
 
-  DEBUG ("netcmd plugin: nc_handle_client: Reading from fd #%i", conn->fd);
+  if (conn->have_tls_session)
+  {
+    int status;
+    intptr_t fd;
+
+    conn->read_buffer = malloc (NC_READ_BUFFER_SIZE);
+    if (conn->read_buffer == NULL)
+      return (ENOMEM);
+    memset (conn->read_buffer, 0, NC_READ_BUFFER_SIZE);
+
+    /* Make (relatively) sure that 'fd' and 'void*' have the same size to make
+     * GCC happy. */
+    fd = (intptr_t) conn->fd;
+    gnutls_transport_set_ptr (conn->tls_session,
+        (gnutls_transport_ptr_t) fd);
+
+    while (42)
+    {
+      status = gnutls_handshake (conn->tls_session);
+      if (status == GNUTLS_E_SUCCESS)
+        break;
+      else if ((status == GNUTLS_E_AGAIN) || (status == GNUTLS_E_INTERRUPTED))
+        continue;
+      else
+      {
+        ERROR ("netcmd plugin: gnutls_handshake failed: %s",
+            gnutls_strerror (status));
+        return (-1);
+      }
+    }
+
+    return (0);
+  }
+
+  /* Duplicate the file descriptor. We need two file descriptors, because we
+   * create two FILE* objects. If they pointed to the same FD and we called
+   * fclose() on each, that would call close() twice on the same FD. If
+   * another file is opened in between those two calls, it could get assigned
+   * that FD and weird stuff would happen. */
+  fd_copy = dup (conn->fd);
+  if (fd_copy < 0)
+  {
+    ERROR ("netcmd plugin: dup(2) failed: %s",
+        sstrerror (errno, errbuf, sizeof (errbuf)));
+    return (-1);
+  }
 
-  fhin  = fdopen (conn->fd, "r");
-  if (fhin == NULL)
+  conn->fh_in  = fdopen (conn->fd, "r");
+  if (conn->fh_in == NULL)
   {
     ERROR ("netcmd plugin: fdopen failed: %s",
         sstrerror (errno, errbuf, sizeof (errbuf)));
-    nc_connection_close (conn);
-    pthread_exit ((void *) 1);
+    return (-1);
   }
+  /* Prevent other code from using the FD directly. */
+  conn->fd = -1;
 
-  /* FIXME: dup conn->fd before calling fdopen! */
-  fhout = fdopen (conn->fd, "w");
+  conn->fh_out = fdopen (fd_copy, "w");
   /* Prevent nc_connection_close from calling close(2) on this fd. */
-  conn->fd = -1;
-  if (fhout == NULL)
+  if (conn->fh_out == NULL)
   {
     ERROR ("netcmd plugin: fdopen failed: %s",
         sstrerror (errno, errbuf, sizeof (errbuf)));
-    fclose (fhin); /* this closes fd as well */
-    nc_connection_close (conn);
-    pthread_exit ((void *) 1);
+    return (-1);
   }
 
   /* change output buffer to line buffered mode */
-  if (setvbuf (fhout, NULL, _IOLBF, 0) != 0)
+  if (setvbuf (conn->fh_out, NULL, _IOLBF, 0) != 0)
   {
     ERROR ("netcmd plugin: setvbuf failed: %s",
         sstrerror (errno, errbuf, sizeof (errbuf)));
     nc_connection_close (conn);
+    return (-1);
+  }
+
+  return (0);
+} /* }}} int nc_connection_init */
+
+static char *nc_connection_gets (nc_connection_t *conn, /* {{{ */
+    char *buffer, size_t buffer_size)
+{
+  ssize_t status;
+  char *orig_buffer = buffer;
+
+  if (conn == NULL)
+  {
+    errno = EINVAL;
+    return (NULL);
+  }
+
+  if (!conn->have_tls_session)
+    return (fgets (buffer, (int) buffer_size, conn->fh_in));
+
+  if ((buffer == NULL) || (buffer_size < 2))
+  {
+    errno = EINVAL;
+    return (NULL);
+  }
+
+  /* ensure null termination */
+  memset (buffer, 0, buffer_size);
+  buffer_size--;
+
+  while (42)
+  {
+    size_t max_copy_bytes;
+    size_t newline_pos;
+    _Bool found_newline;
+    size_t i;
+
+    /* If there's no more data in the read buffer, read another chunk from the
+     * socket. */
+    if (conn->read_buffer_fill < 1)
+    {
+      status = gnutls_record_recv (conn->tls_session,
+          conn->read_buffer, NC_READ_BUFFER_SIZE);
+      if (status < 0) /* error */
+      {
+        ERROR ("netcmd plugin: Error while reading from TLS stream.");
+        return (NULL);
+      }
+      else if (status == 0) /* we reached end of file */
+      {
+        if (orig_buffer == buffer) /* nothing has been written to the buffer yet */
+          return (NULL); /* end of file */
+        else
+          return (orig_buffer);
+      }
+      else
+      {
+        conn->read_buffer_fill = (size_t) status;
+      }
+    }
+    assert (conn->read_buffer_fill > 0);
+
+    /* Determine where the first newline character is in the buffer. We're not
+     * using strcspn(3) here, becaus the buffer is possibly not
+     * null-terminated. */
+    newline_pos = conn->read_buffer_fill;
+    found_newline = 0;
+    for (i = 0; i < conn->read_buffer_fill; i++)
+    {
+      if (conn->read_buffer[i] == '\n')
+      {
+        newline_pos = i;
+        found_newline = 1;
+        break;
+      }
+    }
+
+    /* Determine how many bytes to copy at most. This is MIN(buffer available,
+     * read buffer size, characters to newline). */
+    max_copy_bytes = buffer_size;
+    if (max_copy_bytes > conn->read_buffer_fill)
+      max_copy_bytes = conn->read_buffer_fill;
+    if (max_copy_bytes > (newline_pos + 1))
+      max_copy_bytes = newline_pos + 1;
+    assert (max_copy_bytes > 0);
+
+    /* Copy bytes to the output buffer. */
+    memcpy (buffer, conn->read_buffer, max_copy_bytes);
+    buffer += max_copy_bytes;
+    assert (buffer_size >= max_copy_bytes);
+    buffer_size -= max_copy_bytes;
+
+    /* If there is data left in the read buffer, move it to the front of the
+     * buffer. */
+    if (max_copy_bytes < conn->read_buffer_fill)
+    {
+      size_t data_left_size = conn->read_buffer_fill - max_copy_bytes;
+      memmove (conn->read_buffer, conn->read_buffer + max_copy_bytes,
+          data_left_size);
+      conn->read_buffer_fill -= max_copy_bytes;
+    }
+    else
+    {
+      assert (max_copy_bytes == conn->read_buffer_fill);
+      conn->read_buffer_fill = 0;
+    }
+
+    if (found_newline)
+      break;
+
+    if (buffer_size == 0) /* no more space in the output buffer */
+      break;
+  }
+
+  return (orig_buffer);
+} /* }}} char *nc_connection_gets */
+
+static void *nc_handle_client (void *arg) /* {{{ */
+{
+  nc_connection_t *conn;
+  char errbuf[1024];
+  int status;
+
+  conn = arg;
+
+  DEBUG ("netcmd plugin: nc_handle_client: Reading from fd #%i", conn->fd);
+
+  status = nc_connection_init (conn);
+  if (status != 0)
+  {
+    nc_connection_close (conn);
     pthread_exit ((void *) 1);
   }
 
@@ -367,12 +634,12 @@ static void *nc_handle_client (void *arg) /* {{{ */
     int   len;
 
     errno = 0;
-    if (fgets (buffer, sizeof (buffer), fhin) == NULL)
+    if (nc_connection_gets (conn, buffer, sizeof (buffer)) == NULL)
     {
       if (errno != 0)
       {
         WARNING ("netcmd plugin: failed to read from socket #%i: %s",
-            fileno (fhin),
+            fileno (conn->fh_in),
             sstrerror (errno, errbuf, sizeof (errbuf)));
       }
       break;
@@ -399,30 +666,30 @@ static void *nc_handle_client (void *arg) /* {{{ */
 
     if (strcasecmp (fields[0], "getval") == 0)
     {
-      handle_getval (fhout, buffer);
+      handle_getval (conn->fh_out, buffer);
     }
     else if (strcasecmp (fields[0], "putval") == 0)
     {
-      handle_putval (fhout, buffer);
+      handle_putval (conn->fh_out, buffer);
     }
     else if (strcasecmp (fields[0], "listval") == 0)
     {
-      handle_listval (fhout, buffer);
+      handle_listval (conn->fh_out, buffer);
     }
     else if (strcasecmp (fields[0], "putnotif") == 0)
     {
-      handle_putnotif (fhout, buffer);
+      handle_putnotif (conn->fh_out, buffer);
     }
     else if (strcasecmp (fields[0], "flush") == 0)
     {
-      handle_flush (fhout, buffer);
+      handle_flush (conn->fh_out, buffer);
     }
     else
     {
-      if (fprintf (fhout, "-1 Unknown command: %s\n", fields[0]) < 0)
+      if (fprintf (conn->fh_out, "-1 Unknown command: %s\n", fields[0]) < 0)
       {
         WARNING ("netcmd plugin: failed to write to socket #%i: %s",
-            fileno (fhout),
+            fileno (conn->fh_out),
             sstrerror (errno, errbuf, sizeof (errbuf)));
         break;
       }
@@ -430,9 +697,6 @@ static void *nc_handle_client (void *arg) /* {{{ */
   } /* while (fgets) */
 
   DEBUG ("netcmd plugin: nc_handle_client: Exiting..");
-  /* XXX: Is this calling close on the same FD twice? */
-  fclose (fhin);
-  fclose (fhout);
   nc_connection_close (conn);
 
   pthread_exit ((void *) 0);
@@ -522,6 +786,8 @@ static void *nc_server_thread (void __attribute__((unused)) *arg) /* {{{ */
         continue;
       }
       memset (conn, 0, sizeof (*conn));
+      conn->fh_in = NULL;
+      conn->fh_out = NULL;
 
       conn->fd = status;
       if ((peer != NULL)
@@ -619,6 +885,8 @@ static int nc_config_peer (const oconfig_item_t *ci) /* {{{ */
       cf_util_get_string (child, &p->tls_ca_file);
     else if (strcasecmp ("TLSCRLFile", child->key) == 0)
       cf_util_get_string (child, &p->tls_crl_file);
+    else if (strcasecmp ("TLSVerifyPeer", child->key) == 0)
+      cf_util_get_boolean (child, &p->tls_verify_peer);
     else
       WARNING ("netcmd plugin: The option \"%s\" is not recognized within "
           "a \"%s\" block.", child->key, ci->key);
@@ -660,6 +928,8 @@ static int nc_init (void)
     return (0);
   have_init = 1;
 
+  gnutls_global_init ();
+
   listen_thread_loop = 1;
 
   status = pthread_create (&listen_thread, NULL, nc_server_thread, NULL);