2 * collectd - src/netcmd.c
3 * Copyright (C) 2007-2015 Florian octo Forster
5 * Permission is hereby granted, free of charge, to any person obtaining a
6 * copy of this software and associated documentation files (the "Software"),
7 * to deal in the Software without restriction, including without limitation
8 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 * and/or sell copies of the Software, and to permit persons to whom the
10 * Software is furnished to do so, subject to the following conditions:
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21 * DEALINGS IN THE SOFTWARE.
24 * Florian octo Forster <octo at collectd.org>
30 #include "configfile.h"
32 #include "utils_cmd_flush.h"
33 #include "utils_cmd_getval.h"
34 #include "utils_cmd_listval.h"
35 #include "utils_cmd_putval.h"
36 #include "utils_cmd_putnotif.h"
38 /* Folks without pthread will need to disable this plugin. */
41 #include <sys/socket.h>
49 #include <gnutls/gnutls.h>
50 #include <gnutls/x509.h>
52 #define NC_DEFAULT_SERVICE "25826"
54 #ifndef NC_DEFAULT_DH_BITS
55 # define NC_DEFAULT_DH_BITS 2048
59 * Private data structures
61 struct nc_peer_s /* {{{ */
72 _Bool tls_verify_peer;
73 unsigned int tls_dh_bits;
75 gnutls_certificate_credentials_t tls_credentials;
76 gnutls_dh_params_t tls_dh_params;
77 gnutls_priority_t tls_priority;
79 typedef struct nc_peer_s nc_peer_t;
82 # define NC_READ_BUFFER_SIZE PAGESIZE
83 #elif defined(PAGE_SIZE)
84 # define NC_READ_BUFFER_SIZE PAGE_SIZE
86 # define NC_READ_BUFFER_SIZE 4096
89 struct nc_connection_s /* {{{ */
94 size_t read_buffer_fill;
100 gnutls_session_t tls_session;
101 _Bool have_tls_session;
102 _Bool tls_verify_peer;
104 typedef struct nc_connection_s nc_connection_t;
111 gnutls_session_t tls_session;
113 typedef struct nc_proxy_s nc_proxy_t;
119 /* socket configuration */
120 static nc_peer_t *peers = NULL;
121 static size_t peers_num;
123 static struct pollfd *pollfd = NULL;
124 static size_t pollfd_num;
126 static _Bool listen_thread_loop = 0;
127 static _Bool listen_thread_running = 0;
128 static pthread_t listen_thread;
133 static const char *nc_verify_status_to_string (gnutls_certificate_status_t status) /* {{{ */
137 else if (status & GNUTLS_CERT_INVALID)
139 else if (status & GNUTLS_CERT_REVOKED)
141 else if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
142 return ("Signer not found");
143 else if (status & GNUTLS_CERT_SIGNER_NOT_CA)
144 return ("Signer not a CA");
145 else if (status & GNUTLS_CERT_INSECURE_ALGORITHM)
146 return ("Insecure algorithm");
147 #if GNUTLS_VERSION_NUMBER >= 0x020708
148 else if (status & GNUTLS_CERT_NOT_ACTIVATED)
149 return ("Not activated");
150 else if (status & GNUTLS_CERT_EXPIRED)
155 } /* }}} const char *nc_verify_status_to_string */
157 static void *nc_proxy_thread (void *args) /* {{{ */
159 nc_proxy_t *data = args;
160 struct pollfd fds[2];
164 gtls_fd = (int) gnutls_transport_get_ptr (data->tls_session);
165 DEBUG ("netcmd plugin: nc_proxy_thread: pipe_rx = %i; pipe_tx = %i; gtls_fd = %i;",
166 data->pipe_rx, data->pipe_tx, gtls_fd);
168 memset (fds, 0, sizeof (fds));
169 fds[0].fd = data->pipe_rx;
170 fds[0].events = POLLIN | POLLPRI;
172 fds[1].events = POLLIN | POLLPRI;
174 pagesize = sysconf (_SC_PAGESIZE);
179 char buffer[pagesize];
182 status = poll (fds, STATIC_ARRAY_SIZE(fds), /* timeout = */ -1);
185 if ((errno == EINTR) || (errno == EAGAIN))
187 ERROR ("netcmd plugin: poll(2) failed: %s",
188 sstrerror (errno, errbuf, sizeof (errbuf)));
193 if (fds[0].revents != 0) /* {{{ */
199 DEBUG ("netcmd plugin: nc_proxy_thread: Something's up on the pipe.");
201 /* Check for hangup, error, ... */
202 if ((fds[0].revents & (POLLIN | POLLPRI)) == 0)
205 iostatus = read (fds[0].fd, buffer, sizeof (buffer));
206 DEBUG ("netcmd plugin: nc_proxy_thread: Received %zi bytes from pipe.",
210 if ((errno == EINTR) || (errno == EAGAIN))
212 ERROR ("netcmd plugin: read(2) failed: %s",
213 sstrerror (errno, errbuf, sizeof (errbuf)));
216 else if (iostatus == 0)
222 buffer_size = (size_t) iostatus;
223 while (buffer_size > 0)
225 iostatus = gnutls_record_send (data->tls_session,
226 buffer, buffer_size);
227 DEBUG ("netcmd plugin: nc_proxy_thread: Wrote %zi bytes to GNU-TLS.",
231 ERROR ("netcmd plugin: gnutls_record_send failed: %s",
232 gnutls_strerror ((int) iostatus));
236 assert (iostatus <= buffer_size);
237 buffer_ptr += iostatus;
238 buffer_size -= iostatus;
239 } /* while (buffer_size > 0) */
241 if (buffer_size != 0)
245 } /* }}} if (fds[0].revents != 0) */
248 if (fds[1].revents != 0) /* {{{ */
253 DEBUG ("netcmd plugin: nc_proxy_thread: Something's up on the TLS socket.");
255 /* Check for hangup, error, ... */
256 if ((fds[1].revents & (POLLIN | POLLPRI)) == 0)
259 iostatus = gnutls_record_recv (data->tls_session, buffer, sizeof (buffer));
260 DEBUG ("netcmd plugin: nc_proxy_thread: Received %zi bytes from GNU-TLS.",
264 if ((iostatus == GNUTLS_E_INTERRUPTED)
265 || (iostatus == GNUTLS_E_AGAIN))
267 ERROR ("netcmd plugin: gnutls_record_recv failed: %s",
268 gnutls_strerror ((int) iostatus));
271 else if (iostatus == 0)
276 buffer_size = (size_t) iostatus;
277 iostatus = swrite (data->pipe_tx, buffer, buffer_size);
278 DEBUG ("netcmd plugin: nc_proxy_thread: Wrote %zi bytes to pipe.",
282 } /* }}} if (fds[1].revents != 0) */
285 DEBUG ("netcmd plugin: nc_proxy_thread: Shutting down.");
287 } /* }}} void *nc_proxy_thread */
289 /* Creates two pipes and a separate thread to pass data between two FILE* and
290 * the GNUTLS back and forth. This is required because the handle_<cmd>
291 * functions expect to be able to write to a FILE*. */
292 static int nc_start_tls_file_handles (nc_connection_t *conn) /* {{{ */
294 #define BAIL_OUT(status) do { \
295 DEBUG ("netcmd plugin: nc_start_tls_file_handles: Bailing out with status %i.", (status)); \
296 if (proxy_config->pipe_rx >= 0) { close (proxy_config->pipe_rx); } \
297 if (proxy_config->pipe_tx >= 0) { close (proxy_config->pipe_tx); } \
298 if (conn->fh_in != NULL) { fclose (conn->fh_in); conn->fh_in = NULL; } \
299 if (conn->fh_out != NULL) { fclose (conn->fh_out); conn->fh_out = NULL; } \
300 free (proxy_config); \
304 nc_proxy_t *proxy_config;
311 if ((conn->fh_in != NULL) || (conn->fh_out != NULL))
313 ERROR ("netcmd plugin: nc_start_tls_file_handles: Connection already connected.");
317 proxy_config = malloc (sizeof (*proxy_config));
318 if (proxy_config == NULL)
320 ERROR ("netcmd plugin: malloc failed.");
323 memset (proxy_config, 0, sizeof (*proxy_config));
324 proxy_config->pipe_rx = -1;
325 proxy_config->pipe_tx = -1;
326 proxy_config->tls_session = conn->tls_session;
328 pipe_fd[0] = pipe_fd[1] = -1;
329 status = pipe (pipe_fd);
333 ERROR ("netcmd plugin: pipe(2) failed: %s",
334 sstrerror (errno, errmsg, sizeof (errmsg)));
337 proxy_config->pipe_rx = pipe_fd[0];
338 conn->fh_out = fdopen (pipe_fd[1], "w");
339 if (conn->fh_out == NULL)
342 ERROR ("netcmd plugin: fdopen(2) failed: %s",
343 sstrerror (errno, errmsg, sizeof (errmsg)));
348 pipe_fd[0] = pipe_fd[1] = -1;
349 status = pipe (pipe_fd);
353 ERROR ("netcmd plugin: pipe(2) failed: %s",
354 sstrerror (errno, errmsg, sizeof (errmsg)));
357 proxy_config->pipe_tx = pipe_fd[1];
358 conn->fh_in = fdopen (pipe_fd[0], "r");
359 if (conn->fh_in == NULL)
362 ERROR ("netcmd plugin: fdopen(2) failed: %s",
363 sstrerror (errno, errmsg, sizeof (errmsg)));
368 pthread_attr_init (&attr);
369 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
371 status = pthread_create (&thread, &attr, nc_proxy_thread, proxy_config);
372 pthread_attr_destroy (&attr);
376 ERROR ("netcmd plugin: pthread_create(2) failed: %s",
377 sstrerror (errno, errmsg, sizeof (errmsg)));
381 DEBUG ("netcmd plugin: nc_start_tls_file_handles: Successfully started proxy thread.");
383 } /* }}} int nc_start_tls_file_handles */
385 static nc_peer_t *nc_fd_to_peer (int fd) /* {{{ */
389 for (i = 0; i < peers_num; i++)
393 for (j = 0; j < peers[i].fds_num; j++)
394 if (peers[i].fds[j] == fd)
399 } /* }}} nc_peer_t *nc_fd_to_peer */
401 static void nc_free_peer (nc_peer_t *p) /* {{{ */
410 for (i = 0; i < p->fds_num; i++)
419 sfree (p->tls_cert_file);
420 sfree (p->tls_key_file);
421 sfree (p->tls_ca_file);
422 sfree (p->tls_crl_file);
424 gnutls_certificate_free_credentials (p->tls_credentials);
425 gnutls_dh_params_deinit (p->tls_dh_params);
426 gnutls_priority_deinit (p->tls_priority);
427 } /* }}} void nc_free_peer */
429 static int nc_register_fd (nc_peer_t *peer, int fd) /* {{{ */
431 struct pollfd *poll_ptr;
434 poll_ptr = realloc (pollfd, (pollfd_num + 1) * sizeof (*pollfd));
435 if (poll_ptr == NULL)
437 ERROR ("netcmd plugin: realloc failed.");
442 memset (&pollfd[pollfd_num], 0, sizeof (pollfd[pollfd_num]));
443 pollfd[pollfd_num].fd = fd;
444 pollfd[pollfd_num].events = POLLIN | POLLPRI;
445 pollfd[pollfd_num].revents = 0;
451 fd_ptr = realloc (peer->fds, (peer->fds_num + 1) * sizeof (*peer->fds));
454 ERROR ("netcmd plugin: realloc failed.");
458 peer->fds[peer->fds_num] = fd;
462 } /* }}} int nc_register_fd */
464 static gnutls_datum_t nc_read_file (char const *file) /* {{{ */
468 gnutls_datum_t blob = { 0 };
470 if (read_file (file, &data, &sz) != 0)
474 blob.size = (unsigned int) sz;
476 } /* }}} gnutls_datum_t nc_read_file */
478 static int nc_x509_crt_import_file (gnutls_x509_crt_t *cert, char const *file) /* {{{ */
480 gnutls_datum_t blob = nc_read_file (file);
484 ERROR ("netcmd plugin: reading \"%s\" failed: %s", file,
485 sstrerror (errno, errbuf, sizeof (errbuf)));
489 int status = gnutls_x509_crt_init (cert);
490 if (status != GNUTLS_E_SUCCESS)
492 ERROR ("netcmd plugin: gnutls_x509_crt_init failed: %s",
493 gnutls_strerror (status));
498 status = gnutls_x509_crt_import (*cert, &blob, GNUTLS_X509_FMT_PEM);
499 if (status != GNUTLS_E_SUCCESS)
501 ERROR ("netcmd plugin: gnutls_x509_crt_import failed: %s",
502 gnutls_strerror (status));
507 } /* }}} int nc_x509_crt_import_file */
509 static int nc_x509_privkey_import_file (gnutls_x509_privkey_t *key, char const *file) /* {{{ */
511 gnutls_datum_t blob = nc_read_file (file);
515 ERROR ("netcmd plugin: reading \"%s\" failed: %s", file,
516 sstrerror (errno, errbuf, sizeof (errbuf)));
520 int status = gnutls_x509_privkey_init (key);
521 if (status != GNUTLS_E_SUCCESS)
523 ERROR ("netcmd plugin: gnutls_x509_privkey_init failed: %s",
524 gnutls_strerror (status));
529 status = gnutls_x509_privkey_import (*key, &blob, GNUTLS_X509_FMT_PEM);
530 if (status != GNUTLS_E_SUCCESS)
532 ERROR ("netcmd plugin: gnutls_x509_privkey_import failed: %s",
533 gnutls_strerror (status));
538 } /* }}} int nc_x509_privkey_import_file */
540 static int nc_tls_init (nc_peer_t *peer) /* {{{ */
547 if (peer->tls_key_file == NULL)
549 DEBUG ("netcmd plugin: Not setting up TLS environment for peer.");
553 DEBUG ("netcmd plugin: Setting up TLS environment for peer.");
555 /* Initialize the structure holding our certificate information. */
556 status = gnutls_certificate_allocate_credentials (&peer->tls_credentials);
557 if (status != GNUTLS_E_SUCCESS)
559 ERROR ("netcmd plugin: gnutls_certificate_allocate_credentials failed: %s",
560 gnutls_strerror (status));
564 /* Set up the configured certificates. */
565 if (peer->tls_ca_file != NULL)
567 status = gnutls_certificate_set_x509_trust_file (peer->tls_credentials,
568 peer->tls_ca_file, GNUTLS_X509_FMT_PEM);
571 ERROR ("netcmd plugin: gnutls_certificate_set_x509_trust_file (%s) "
573 peer->tls_ca_file, gnutls_strerror (status));
578 DEBUG ("netcmd plugin: Successfully loaded %i CA(s).", status);
582 if (peer->tls_crl_file != NULL)
584 status = gnutls_certificate_set_x509_crl_file (peer->tls_credentials,
585 peer->tls_crl_file, GNUTLS_X509_FMT_PEM);
588 ERROR ("netcmd plugin: gnutls_certificate_set_x509_crl_file (%s) "
590 peer->tls_crl_file, gnutls_strerror (status));
595 DEBUG ("netcmd plugin: Successfully loaded %i CRL(s).", status);
599 gnutls_x509_crt_t cert;
600 status = nc_x509_crt_import_file (&cert, peer->tls_cert_file);
601 if (status != GNUTLS_E_SUCCESS)
603 ERROR ("netcmd plugin: failed to load certificate from \"%s\"",
604 peer->tls_cert_file);
608 gnutls_x509_privkey_t key;
609 status = nc_x509_privkey_import_file (&key, peer->tls_key_file);
610 if (status != GNUTLS_E_SUCCESS)
612 ERROR ("netcmd plugin: failed to load private key from \"%s\"",
617 status = gnutls_certificate_set_x509_key (peer->tls_credentials,
618 /* cert_list = */ &cert, /* cert_list_size = */ 1, key);
619 if (status != GNUTLS_E_SUCCESS)
621 ERROR ("netcmd plugin: gnutls_certificate_set_x509_key failed: %s",
622 gnutls_strerror (status));
626 if (peer->tls_dh_bits == 0)
628 status = gnutls_x509_crt_get_pk_algorithm (cert, &peer->tls_dh_bits);
629 if (status != GNUTLS_E_SUCCESS)
631 ERROR ("netcmd plugin: Failed to determine size of the public key: %s. "
632 "Falling back to using DH with %d bits.",
633 gnutls_strerror (status), NC_DEFAULT_DH_BITS);
634 peer->tls_dh_bits = NC_DEFAULT_DH_BITS;
638 DEBUG ("netcmd plugin: Public key has %u bits", peer->tls_dh_bits);
642 /* Initialize Diffie-Hellman parameters. */
643 gnutls_dh_params_init (&peer->tls_dh_params);
644 gnutls_dh_params_generate2 (peer->tls_dh_params, peer->tls_dh_bits);
645 gnutls_certificate_set_dh_params (peer->tls_credentials, peer->tls_dh_params);
647 /* Initialize a "priority cache". This will tell GNUTLS which algorithms to
648 * use and which to avoid. We use the "NORMAL" method for now. */
649 /* TODO(octo): Add CipherList option. */
650 gnutls_priority_init (&peer->tls_priority,
651 /* priority = */ "NORMAL", /* errpos = */ NULL);
654 } /* }}} int nc_tls_init */
656 static gnutls_session_t nc_tls_get_session (nc_peer_t *peer) /* {{{ */
658 gnutls_session_t session;
661 if (peer->tls_credentials == NULL)
664 DEBUG ("netcmd plugin: nc_tls_get_session (%s)", peer->node);
666 /* Initialize new session. */
667 gnutls_init (&session, GNUTLS_SERVER);
669 /* Set cipher priority and credentials based on the information stored with
671 status = gnutls_priority_set (session, peer->tls_priority);
672 if (status != GNUTLS_E_SUCCESS)
674 ERROR ("netcmd plugin: gnutls_priority_set failed: %s",
675 gnutls_strerror (status));
676 gnutls_deinit (session);
680 status = gnutls_credentials_set (session,
681 GNUTLS_CRD_CERTIFICATE, peer->tls_credentials);
682 if (status != GNUTLS_E_SUCCESS)
684 ERROR ("netcmd plugin: gnutls_credentials_set failed: %s",
685 gnutls_strerror (status));
686 gnutls_deinit (session);
690 /* Request the client certificate. If TLSVerifyPeer is set to true,
691 * *require* a client certificate. */
692 gnutls_certificate_server_set_request (session,
693 peer->tls_verify_peer ? GNUTLS_CERT_REQUIRE : GNUTLS_CERT_REQUEST);
696 } /* }}} gnutls_session_t nc_tls_get_session */
698 static int nc_open_socket (nc_peer_t *peer) /* {{{ */
700 struct addrinfo ai_hints;
701 struct addrinfo *ai_list;
702 struct addrinfo *ai_ptr;
705 const char *node = NULL;
706 const char *service = NULL;
711 service = peer->service;
715 service = NC_DEFAULT_SERVICE;
717 memset (&ai_hints, 0, sizeof (ai_hints));
719 ai_hints.ai_flags |= AI_PASSIVE;
722 ai_hints.ai_flags |= AI_ADDRCONFIG;
724 ai_hints.ai_family = AF_UNSPEC;
725 ai_hints.ai_socktype = SOCK_STREAM;
730 service = NC_DEFAULT_SERVICE;
732 status = getaddrinfo (node, service, &ai_hints, &ai_list);
735 ERROR ("netcmd plugin: getaddrinfo failed: %s",
736 gai_strerror (status));
740 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
745 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
746 ai_ptr->ai_protocol);
749 ERROR ("netcmd plugin: socket(2) failed: %s",
750 sstrerror (errno, errbuf, sizeof (errbuf)));
754 status = bind (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
758 ERROR ("netcmd plugin: bind(2) failed: %s",
759 sstrerror (errno, errbuf, sizeof (errbuf)));
763 status = listen (fd, /* backlog = */ 8);
767 ERROR ("netcmd plugin: listen(2) failed: %s",
768 sstrerror (errno, errbuf, sizeof (errbuf)));
772 status = nc_register_fd (peer, fd);
778 } /* for (ai_next) */
780 freeaddrinfo (ai_list);
782 return (nc_tls_init (peer));
783 } /* }}} int nc_open_socket */
785 static void nc_connection_close (nc_connection_t *conn) /* {{{ */
796 if (conn->fh_in != NULL)
798 fclose (conn->fh_in);
802 if (conn->fh_out != NULL)
804 fclose (conn->fh_out);
808 if (conn->have_tls_session)
810 gnutls_deinit (conn->tls_session);
811 conn->have_tls_session = 0;
815 } /* }}} void nc_connection_close */
817 static int nc_connection_init_tls (nc_connection_t *conn) /* {{{ */
822 conn->read_buffer = malloc (NC_READ_BUFFER_SIZE);
823 if (conn->read_buffer == NULL)
825 memset (conn->read_buffer, 0, NC_READ_BUFFER_SIZE);
827 /* Make (relatively) sure that 'fd' and 'void*' have the same size to make
829 fd = (intptr_t) conn->fd;
830 gnutls_transport_set_ptr (conn->tls_session,
831 (gnutls_transport_ptr_t) fd);
835 status = gnutls_handshake (conn->tls_session);
836 if (status == GNUTLS_E_SUCCESS)
838 else if ((status == GNUTLS_E_AGAIN) || (status == GNUTLS_E_INTERRUPTED))
842 ERROR ("netcmd plugin: gnutls_handshake failed: %s",
843 gnutls_strerror (status));
848 if (conn->tls_verify_peer)
850 unsigned int verify_status = 0;
852 status = gnutls_certificate_verify_peers2 (conn->tls_session,
854 if (status != GNUTLS_E_SUCCESS)
856 ERROR ("netcmd plugin: gnutls_certificate_verify_peers2 failed: %s",
857 gnutls_strerror (status));
861 if (verify_status != 0)
865 reason = nc_verify_status_to_string (verify_status);
867 ERROR ("netcmd plugin: Verification of peer failed with "
868 "status %i (%#x)", verify_status, verify_status);
870 ERROR ("netcmd plugin: Verification of peer failed with "
871 "status %i (%s)", verify_status, reason);
875 } /* if (conn->tls_verify_peer) */
877 status = nc_start_tls_file_handles (conn);
880 nc_connection_close (conn);
885 } /* }}} int nc_connection_init_tls */
887 static int nc_connection_init (nc_connection_t *conn) /* {{{ */
892 if (conn->have_tls_session)
893 return (nc_connection_init_tls (conn));
895 /* Duplicate the file descriptor. We need two file descriptors, because we
896 * create two FILE* objects. If they pointed to the same FD and we called
897 * fclose() on each, that would call close() twice on the same FD. If
898 * another file is opened in between those two calls, it could get assigned
899 * that FD and weird stuff would happen. */
900 fd_copy = dup (conn->fd);
903 ERROR ("netcmd plugin: dup(2) failed: %s",
904 sstrerror (errno, errbuf, sizeof (errbuf)));
908 conn->fh_in = fdopen (conn->fd, "r");
909 if (conn->fh_in == NULL)
911 ERROR ("netcmd plugin: fdopen failed: %s",
912 sstrerror (errno, errbuf, sizeof (errbuf)));
915 /* Prevent other code from using the FD directly. */
918 conn->fh_out = fdopen (fd_copy, "w");
919 /* Prevent nc_connection_close from calling close(2) on this fd. */
920 if (conn->fh_out == NULL)
922 ERROR ("netcmd plugin: fdopen failed: %s",
923 sstrerror (errno, errbuf, sizeof (errbuf)));
927 /* change output buffer to line buffered mode */
928 if (setvbuf (conn->fh_out, NULL, _IOLBF, 0) != 0)
930 ERROR ("netcmd plugin: setvbuf failed: %s",
931 sstrerror (errno, errbuf, sizeof (errbuf)));
932 nc_connection_close (conn);
937 } /* }}} int nc_connection_init */
939 /* nc_connection_gets reads one more block from the connection, looks for a
940 * newline and copies everything up until and including the first newline into
941 * buffer end returns buffer itself. */
942 static char *nc_connection_gets (nc_connection_t *conn, /* {{{ */
943 char *buffer, size_t buffer_size)
946 char *orig_buffer = buffer;
954 if (!conn->have_tls_session)
955 return (fgets (buffer, (int) buffer_size, conn->fh_in));
957 if ((buffer == NULL) || (buffer_size < 2))
963 /* ensure null termination */
964 memset (buffer, 0, buffer_size);
969 size_t max_copy_bytes;
974 /* If there's no more data in the read buffer, read another chunk from the
976 if (conn->read_buffer_fill < 1)
978 status = gnutls_record_recv (conn->tls_session,
979 conn->read_buffer, NC_READ_BUFFER_SIZE);
980 if (status < 0) /* error */
982 ERROR ("netcmd plugin: Error while reading from TLS stream.");
985 else if (status == 0) /* we reached end of file */
987 if (orig_buffer == buffer) /* nothing has been written to the buffer yet */
988 return (NULL); /* end of file */
990 return (orig_buffer);
994 conn->read_buffer_fill = (size_t) status;
997 assert (conn->read_buffer_fill > 0);
999 /* Determine where the first newline character is in the buffer. We're not
1000 * using strcspn(3) here, becaus the buffer is possibly not
1001 * null-terminated. */
1002 newline_pos = conn->read_buffer_fill;
1004 for (i = 0; i < conn->read_buffer_fill; i++)
1006 if (conn->read_buffer[i] == '\n')
1014 /* Determine how many bytes to copy at most. This is MIN(buffer available,
1015 * read buffer size, characters to newline). */
1016 max_copy_bytes = buffer_size;
1017 if (max_copy_bytes > conn->read_buffer_fill)
1018 max_copy_bytes = conn->read_buffer_fill;
1019 if (max_copy_bytes > (newline_pos + 1))
1020 max_copy_bytes = newline_pos + 1;
1021 assert (max_copy_bytes > 0);
1023 /* Copy bytes to the output buffer. */
1024 memcpy (buffer, conn->read_buffer, max_copy_bytes);
1025 buffer += max_copy_bytes;
1026 assert (buffer_size >= max_copy_bytes);
1027 buffer_size -= max_copy_bytes;
1029 /* If there is data left in the read buffer, move it to the front of the
1031 if (max_copy_bytes < conn->read_buffer_fill)
1033 size_t data_left_size = conn->read_buffer_fill - max_copy_bytes;
1034 memmove (conn->read_buffer, conn->read_buffer + max_copy_bytes,
1036 conn->read_buffer_fill -= max_copy_bytes;
1040 assert (max_copy_bytes == conn->read_buffer_fill);
1041 conn->read_buffer_fill = 0;
1047 if (buffer_size == 0) /* no more space in the output buffer */
1051 return (orig_buffer);
1052 } /* }}} char *nc_connection_gets */
1054 static void *nc_handle_client (void *arg) /* {{{ */
1056 nc_connection_t *conn;
1062 DEBUG ("netcmd plugin: nc_handle_client: Reading from fd #%i", conn->fd);
1064 status = nc_connection_init (conn);
1067 nc_connection_close (conn);
1068 pthread_exit ((void *) 1);
1074 char buffer_copy[1024];
1080 if (nc_connection_gets (conn, buffer, sizeof (buffer)) == NULL)
1084 WARNING ("netcmd plugin: failed to read from socket #%i: %s",
1085 fileno (conn->fh_in),
1086 sstrerror (errno, errbuf, sizeof (errbuf)));
1091 len = strlen (buffer);
1093 && ((buffer[len - 1] == '\n') || (buffer[len - 1] == '\r')))
1094 buffer[--len] = '\0';
1099 sstrncpy (buffer_copy, buffer, sizeof (buffer_copy));
1101 fields_num = strsplit (buffer_copy, fields,
1102 sizeof (fields) / sizeof (fields[0]));
1106 nc_connection_close (conn);
1110 if (strcasecmp (fields[0], "getval") == 0)
1112 handle_getval (conn->fh_out, buffer);
1114 else if (strcasecmp (fields[0], "putval") == 0)
1116 handle_putval (conn->fh_out, buffer);
1118 else if (strcasecmp (fields[0], "listval") == 0)
1120 handle_listval (conn->fh_out, buffer);
1122 else if (strcasecmp (fields[0], "putnotif") == 0)
1124 handle_putnotif (conn->fh_out, buffer);
1126 else if (strcasecmp (fields[0], "flush") == 0)
1128 handle_flush (conn->fh_out, buffer);
1132 if (fprintf (conn->fh_out, "-1 Unknown command: %s\n", fields[0]) < 0)
1134 WARNING ("netcmd plugin: failed to write to socket #%i: %s",
1135 fileno (conn->fh_out),
1136 sstrerror (errno, errbuf, sizeof (errbuf)));
1140 } /* while (fgets) */
1142 DEBUG ("netcmd plugin: nc_handle_client: Exiting..");
1143 nc_connection_close (conn);
1145 pthread_exit ((void *) 0);
1146 return ((void *) 0);
1147 } /* }}} void *nc_handle_client */
1149 static void *nc_server_thread (void __attribute__((unused)) *arg) /* {{{ */
1153 pthread_attr_t th_attr;
1157 for (i = 0; i < peers_num; i++)
1158 nc_open_socket (peers + i);
1161 nc_open_socket (NULL);
1163 if (pollfd_num == 0)
1165 ERROR ("netcmd plugin: No sockets could be opened.");
1166 pthread_exit ((void *) -1);
1169 while (listen_thread_loop)
1171 status = poll (pollfd, (nfds_t) pollfd_num, /* timeout = */ -1);
1174 if ((errno == EINTR) || (errno == EAGAIN))
1177 ERROR ("netcmd plugin: poll(2) failed: %s",
1178 sstrerror (errno, errbuf, sizeof (errbuf)));
1179 listen_thread_loop = 0;
1183 for (i = 0; i < pollfd_num; i++)
1186 nc_connection_t *conn;
1188 if (pollfd[i].revents == 0)
1192 else if ((pollfd[i].revents & (POLLERR | POLLHUP | POLLNVAL))
1195 WARNING ("netcmd plugin: File descriptor %i failed.",
1197 close (pollfd[i].fd);
1199 pollfd[i].events = 0;
1200 pollfd[i].revents = 0;
1203 pollfd[i].revents = 0;
1205 peer = nc_fd_to_peer (pollfd[i].fd);
1208 ERROR ("netcmd plugin: Unable to find peer structure for file "
1209 "descriptor #%i.", pollfd[i].fd);
1213 status = accept (pollfd[i].fd,
1214 /* sockaddr = */ NULL,
1215 /* sockaddr_len = */ NULL);
1219 ERROR ("netcmd plugin: accept failed: %s",
1220 sstrerror (errno, errbuf, sizeof (errbuf)));
1224 conn = malloc (sizeof (*conn));
1227 ERROR ("netcmd plugin: malloc failed.");
1231 memset (conn, 0, sizeof (*conn));
1233 conn->fh_out = NULL;
1237 /* Start up the TLS session if the required configuration options have
1240 && (peer->tls_key_file != NULL))
1242 DEBUG ("netcmd plugin: Starting TLS session on a connection "
1244 (peer->node != NULL) ? peer->node : "any",
1245 (peer->service != NULL) ? peer->service : NC_DEFAULT_SERVICE);
1246 conn->tls_session = nc_tls_get_session (peer);
1247 if (conn->tls_session == NULL)
1249 ERROR ("netcmd plugin: Creating TLS session on a connection via "
1250 "[%s]:%s failed. For security reasons this connection will be "
1252 (peer->node != NULL) ? peer->node : "any",
1253 (peer->service != NULL) ? peer->service : NC_DEFAULT_SERVICE);
1254 nc_connection_close (conn);
1257 conn->have_tls_session = 1;
1258 conn->tls_verify_peer = peer->tls_verify_peer;
1261 DEBUG ("netcmd plugin: Spawning child to handle connection on fd #%i",
1264 pthread_attr_init (&th_attr);
1265 pthread_attr_setdetachstate (&th_attr, PTHREAD_CREATE_DETACHED);
1267 status = pthread_create (&th, &th_attr, nc_handle_client, conn);
1268 pthread_attr_destroy (&th_attr);
1271 WARNING ("netcmd plugin: pthread_create failed: %s",
1272 sstrerror (errno, errbuf, sizeof (errbuf)));
1273 nc_connection_close (conn);
1277 } /* while (listen_thread_loop) */
1279 for (i = 0; i < pollfd_num; i++)
1281 if (pollfd[i].fd < 0)
1284 close (pollfd[i].fd);
1286 pollfd[i].events = 0;
1287 pollfd[i].revents = 0;
1293 return ((void *) 0);
1294 } /* }}} void *nc_server_thread */
1301 * TLSCertFile "/path/to/cert"
1302 * TLSKeyFile "/path/to/key"
1303 * TLSCAFile "/path/to/ca"
1304 * TLSCRLFile "/path/to/crl"
1305 * TLSVerifyPeer yes|no
1309 static int nc_config_peer (const oconfig_item_t *ci) /* {{{ */
1315 p = realloc (peers, sizeof (*peers) * (peers_num + 1));
1318 ERROR ("netcmd plugin: realloc failed.");
1322 p = peers + peers_num;
1323 memset (p, 0, sizeof (*p));
1326 p->tls_cert_file = NULL;
1327 p->tls_key_file = NULL;
1328 p->tls_ca_file = NULL;
1329 p->tls_crl_file = NULL;
1330 p->tls_verify_peer = 0;
1332 for (i = 0; i < ci->children_num; i++)
1334 oconfig_item_t *child = ci->children + i;
1336 if (strcasecmp ("Address", child->key) == 0)
1337 cf_util_get_string (child, &p->node);
1338 else if (strcasecmp ("Port", child->key) == 0)
1339 cf_util_get_service (child, &p->service);
1340 else if (strcasecmp ("TLSCertFile", child->key) == 0)
1341 cf_util_get_string (child, &p->tls_cert_file);
1342 else if (strcasecmp ("TLSKeyFile", child->key) == 0)
1343 cf_util_get_string (child, &p->tls_key_file);
1344 else if (strcasecmp ("TLSCAFile", child->key) == 0)
1345 cf_util_get_string (child, &p->tls_ca_file);
1346 else if (strcasecmp ("TLSCRLFile", child->key) == 0)
1347 cf_util_get_string (child, &p->tls_crl_file);
1348 else if (strcasecmp ("TLSVerifyPeer", child->key) == 0)
1349 cf_util_get_boolean (child, &p->tls_verify_peer);
1350 else if (strcasecmp ("TLSDHBits", child->key) == 0)
1353 if (cf_util_get_int (child, &tmp) == 0)
1356 p->tls_dh_bits = (unsigned int) tmp;
1358 ERROR ("netcmd plugin: The \"TLSDHBits\" option was set to %d, but expects a positive integer.", tmp);
1362 WARNING ("netcmd plugin: The option \"%s\" is not recognized within "
1363 "a \"%s\" block.", child->key, ci->key);
1366 /* TLS is confusing for many people. Be verbose on mis-configurations to
1367 * help people set up encryption correctly. */
1369 if (p->tls_key_file == NULL)
1371 if (p->tls_cert_file != NULL)
1373 WARNING ("netcmd plugin: The \"TLSCertFile\" option is only valid in "
1374 "combination with the \"TLSKeyFile\" option.");
1377 if (p->tls_ca_file != NULL)
1379 WARNING ("netcmd plugin: The \"TLSCAFile\" option is only valid when "
1380 "the \"TLSKeyFile\" option has been specified.");
1383 if (p->tls_crl_file != NULL)
1385 WARNING ("netcmd plugin: The \"TLSCRLFile\" option is only valid when "
1386 "the \"TLSKeyFile\" option has been specified.");
1390 else if (p->tls_cert_file == NULL)
1392 WARNING ("netcmd plugin: The \"TLSKeyFile\" option is only valid in "
1393 "combination with the \"TLSCertFile\" option.");
1399 ERROR ("netcmd plugin: Problems in the security settings have been "
1400 "detected in the <Listen /> block for [%s]:%s. The entire block "
1401 "will be ignored to prevent unauthorized access.",
1402 (p->node == NULL) ? "::0" : p->node,
1403 (p->service == NULL) ? NC_DEFAULT_SERVICE : p->service);
1408 DEBUG ("netcmd plugin: node = \"%s\"; service = \"%s\";", p->node, p->service);
1413 } /* }}} int nc_config_peer */
1415 static int nc_config (oconfig_item_t *ci) /* {{{ */
1419 for (i = 0; i < ci->children_num; i++)
1421 oconfig_item_t *child = ci->children + i;
1423 if (strcasecmp ("Listen", child->key) == 0)
1424 nc_config_peer (child);
1426 WARNING ("netcmd plugin: The option \"%s\" is not recognized.",
1431 } /* }}} int nc_config */
1433 static int nc_init (void) /* {{{ */
1435 static int have_init = 0;
1439 /* Initialize only once. */
1444 gnutls_global_init ();
1446 listen_thread_loop = 1;
1448 status = pthread_create (&listen_thread, NULL, nc_server_thread, NULL);
1452 listen_thread_loop = 0;
1453 listen_thread_running = 0;
1454 ERROR ("netcmd plugin: pthread_create failed: %s",
1455 sstrerror (errno, errbuf, sizeof (errbuf)));
1459 listen_thread_running = 1;
1461 } /* }}} int nc_init */
1463 static int nc_shutdown (void) /* {{{ */
1467 listen_thread_loop = 0;
1469 if (listen_thread != (pthread_t) 0)
1473 pthread_kill (listen_thread, SIGTERM);
1474 pthread_join (listen_thread, &ret);
1475 listen_thread = (pthread_t) 0;
1478 plugin_unregister_init ("netcmd");
1479 plugin_unregister_shutdown ("netcmd");
1481 for (i = 0; i < peers_num; i++)
1482 nc_free_peer (peers + i);
1487 } /* }}} int nc_shutdown */
1489 void module_register (void) /* {{{ */
1491 plugin_register_complex_config ("netcmd", nc_config);
1492 plugin_register_init ("netcmd", nc_init);
1493 plugin_register_shutdown ("netcmd", nc_shutdown);
1494 } /* }}} void module_register (void) */
1496 /* vim: set sw=2 sts=2 tw=78 et fdm=marker : */