2 * collectd - src/netcmd.c
3 * Copyright (C) 2007-2011 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>
51 #define NC_DEFAULT_SERVICE "25826"
52 #define NC_TLS_DH_BITS 1024
55 * Private data structures
68 _Bool tls_verify_peer;
70 gnutls_certificate_credentials_t tls_credentials;
71 gnutls_dh_params_t tls_dh_params;
72 gnutls_priority_t tls_priority;
75 typedef struct nc_peer_s nc_peer_t;
78 # define NC_READ_BUFFER_SIZE PAGESIZE
79 #elif defined(PAGE_SIZE)
80 # define NC_READ_BUFFER_SIZE PAGE_SIZE
82 # define NC_READ_BUFFER_SIZE 4096
85 struct nc_connection_s
90 size_t read_buffer_fill;
96 gnutls_session_t tls_session;
97 _Bool have_tls_session;
99 typedef struct nc_connection_s nc_connection_t;
105 /* socket configuration */
106 static nc_peer_t *peers = NULL;
107 static size_t peers_num;
109 static struct pollfd *pollfd = NULL;
110 static size_t pollfd_num;
112 static int listen_thread_loop = 0;
113 static int listen_thread_running = 0;
114 static pthread_t listen_thread;
119 static nc_peer_t *nc_fd_to_peer (int fd) /* {{{ */
123 for (i = 0; i < peers_num; i++)
127 for (j = 0; j < peers[i].fds_num; j++)
128 if (peers[i].fds[j] == fd)
133 } /* }}} nc_peer_t *nc_fd_to_peer */
135 static int nc_register_fd (nc_peer_t *peer, int fd) /* {{{ */
137 struct pollfd *poll_ptr;
140 poll_ptr = realloc (pollfd, (pollfd_num + 1) * sizeof (*pollfd));
141 if (poll_ptr == NULL)
143 ERROR ("netcmd plugin: realloc failed.");
148 memset (&pollfd[pollfd_num], 0, sizeof (pollfd[pollfd_num]));
149 pollfd[pollfd_num].fd = fd;
150 pollfd[pollfd_num].events = POLLIN | POLLPRI;
151 pollfd[pollfd_num].revents = 0;
157 fd_ptr = realloc (peer->fds, (peer->fds_num + 1) * sizeof (*peer->fds));
160 ERROR ("netcmd plugin: realloc failed.");
164 peer->fds[peer->fds_num] = fd;
168 } /* }}} int nc_register_fd */
170 static int nc_tls_init (nc_peer_t *peer) /* {{{ */
177 if ((peer->tls_cert_file == NULL)
178 || (peer->tls_key_file == NULL))
180 DEBUG ("netcmd plugin: Not setting up TLS environment for peer.");
184 DEBUG ("netcmd plugin: Setting up TLS environment for peer.");
186 /* Initialize the structure holding our certificate information. */
187 status = gnutls_certificate_allocate_credentials (&peer->tls_credentials);
188 if (status != GNUTLS_E_SUCCESS)
190 ERROR ("netcmd plugin: gnutls_certificate_allocate_credentials failed: %s",
191 gnutls_strerror (status));
195 /* Set up the configured certificates. */
196 if (peer->tls_ca_file != NULL)
198 status = gnutls_certificate_set_x509_trust_file (peer->tls_credentials,
199 peer->tls_ca_file, GNUTLS_X509_FMT_PEM);
202 ERROR ("netcmd plugin: gnutls_certificate_set_x509_trust_file (%s) "
204 peer->tls_ca_file, gnutls_strerror (status));
209 DEBUG ("netcmd plugin: Successfully loaded %i CA(s).", status);
213 if (peer->tls_crl_file != NULL)
215 status = gnutls_certificate_set_x509_crl_file (peer->tls_credentials,
216 peer->tls_crl_file, GNUTLS_X509_FMT_PEM);
219 ERROR ("netcmd plugin: gnutls_certificate_set_x509_crl_file (%s) "
221 peer->tls_crl_file, gnutls_strerror (status));
226 DEBUG ("netcmd plugin: Successfully loaded %i CRL(s).", status);
230 status = gnutls_certificate_set_x509_key_file (peer->tls_credentials,
231 peer->tls_cert_file, peer->tls_key_file, GNUTLS_X509_FMT_PEM);
232 if (status != GNUTLS_E_SUCCESS)
234 ERROR ("netcmd plugin: gnutls_certificate_set_x509_key_file failed: %s",
235 gnutls_strerror (status));
239 /* Initialize Diffie-Hellman parameters. */
240 gnutls_dh_params_init (&peer->tls_dh_params);
241 gnutls_dh_params_generate2 (peer->tls_dh_params, NC_TLS_DH_BITS);
242 gnutls_certificate_set_dh_params (peer->tls_credentials,
243 peer->tls_dh_params);
245 /* Initialize a "priority cache". This will tell GNUTLS which algorithms to
246 * use and which to avoid. We use the "NORMAL" method for now. */
247 gnutls_priority_init (&peer->tls_priority,
248 /* priority = */ "NORMAL", /* errpos = */ NULL);
251 } /* }}} int nc_tls_init */
253 static gnutls_session_t nc_tls_get_session (nc_peer_t *peer) /* {{{ */
255 gnutls_session_t session;
258 if (peer->tls_credentials == NULL)
261 DEBUG ("netcmd plugin: nc_tls_get_session (%s)", peer->node);
263 /* Initialize new session. */
264 gnutls_init (&session, GNUTLS_SERVER);
266 /* Set cipher priority and credentials based on the information stored with
268 status = gnutls_priority_set (session, peer->tls_priority);
269 if (status != GNUTLS_E_SUCCESS)
271 ERROR ("netcmd plugin: gnutls_priority_set failed: %s",
272 gnutls_strerror (status));
273 gnutls_deinit (session);
277 status = gnutls_credentials_set (session,
278 GNUTLS_CRD_CERTIFICATE, peer->tls_credentials);
279 if (status != GNUTLS_E_SUCCESS)
281 ERROR ("netcmd plugin: gnutls_credentials_set failed: %s",
282 gnutls_strerror (status));
283 gnutls_deinit (session);
287 /* Request the client certificate. If TLSVerifyPeer is set to true,
288 * *require* a client certificate. */
289 gnutls_certificate_server_set_request (session,
290 peer->tls_verify_peer ? GNUTLS_CERT_REQUIRE : GNUTLS_CERT_REQUEST);
293 } /* }}} gnutls_session_t nc_tls_get_session */
295 static int nc_open_socket (nc_peer_t *peer) /* {{{ */
297 struct addrinfo ai_hints;
298 struct addrinfo *ai_list;
299 struct addrinfo *ai_ptr;
302 const char *node = NULL;
303 const char *service = NULL;
308 service = peer->service;
312 service = NC_DEFAULT_SERVICE;
314 memset (&ai_hints, 0, sizeof (ai_hints));
316 ai_hints.ai_flags |= AI_PASSIVE;
319 ai_hints.ai_flags |= AI_ADDRCONFIG;
321 ai_hints.ai_family = AF_UNSPEC;
322 ai_hints.ai_socktype = SOCK_STREAM;
327 service = NC_DEFAULT_SERVICE;
329 status = getaddrinfo (node, service, &ai_hints, &ai_list);
332 ERROR ("netcmd plugin: getaddrinfo failed: %s",
333 gai_strerror (status));
337 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
342 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
343 ai_ptr->ai_protocol);
346 ERROR ("netcmd plugin: socket(2) failed: %s",
347 sstrerror (errno, errbuf, sizeof (errbuf)));
351 status = bind (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
355 ERROR ("netcmd plugin: bind(2) failed: %s",
356 sstrerror (errno, errbuf, sizeof (errbuf)));
360 status = listen (fd, /* backlog = */ 8);
364 ERROR ("netcmd plugin: listen(2) failed: %s",
365 sstrerror (errno, errbuf, sizeof (errbuf)));
369 status = nc_register_fd (peer, fd);
375 } /* for (ai_next) */
377 freeaddrinfo (ai_list);
379 return (nc_tls_init (peer));
380 } /* }}} int nc_open_socket */
382 static void nc_connection_close (nc_connection_t *conn) /* {{{ */
393 if (conn->fh_in != NULL)
395 fclose (conn->fh_in);
399 if (conn->fh_out != NULL)
401 fclose (conn->fh_out);
405 if (conn->have_tls_session)
407 gnutls_deinit (conn->tls_session);
408 conn->have_tls_session = 0;
412 } /* }}} void nc_connection_close */
414 static int nc_connection_init (nc_connection_t *conn) /* {{{ */
419 DEBUG ("netcmd plugin: nc_connection_init();");
421 if (conn->have_tls_session)
425 conn->read_buffer = malloc (NC_READ_BUFFER_SIZE);
426 if (conn->read_buffer == NULL)
428 memset (conn->read_buffer, 0, NC_READ_BUFFER_SIZE);
430 gnutls_transport_set_ptr (conn->tls_session,
431 (gnutls_transport_ptr_t) conn->fd);
435 status = gnutls_handshake (conn->tls_session);
436 if (status == GNUTLS_E_SUCCESS)
438 else if ((status == GNUTLS_E_AGAIN) || (status == GNUTLS_E_INTERRUPTED))
442 ERROR ("netcmd plugin: gnutls_handshake failed: %s",
443 gnutls_strerror (status));
451 /* Duplicate the file descriptor. We need two file descriptors, because we
452 * create two FILE* objects. If they pointed to the same FD and we called
453 * fclose() on each, that would call close() twice on the same FD. If
454 * another file is opened in between those two calls, it could get assigned
455 * that FD and weird stuff would happen. */
456 fd_copy = dup (conn->fd);
459 ERROR ("netcmd plugin: dup(2) failed: %s",
460 sstrerror (errno, errbuf, sizeof (errbuf)));
464 conn->fh_in = fdopen (conn->fd, "r");
465 if (conn->fh_in == NULL)
467 ERROR ("netcmd plugin: fdopen failed: %s",
468 sstrerror (errno, errbuf, sizeof (errbuf)));
471 /* Prevent other code from using the FD directly. */
474 conn->fh_out = fdopen (fd_copy, "w");
475 /* Prevent nc_connection_close from calling close(2) on this fd. */
476 if (conn->fh_out == NULL)
478 ERROR ("netcmd plugin: fdopen failed: %s",
479 sstrerror (errno, errbuf, sizeof (errbuf)));
483 /* change output buffer to line buffered mode */
484 if (setvbuf (conn->fh_out, NULL, _IOLBF, 0) != 0)
486 ERROR ("netcmd plugin: setvbuf failed: %s",
487 sstrerror (errno, errbuf, sizeof (errbuf)));
488 nc_connection_close (conn);
493 } /* }}} int nc_connection_init */
495 static char *nc_connection_gets (nc_connection_t *conn, /* {{{ */
496 char *buffer, size_t buffer_size)
499 char *orig_buffer = buffer;
507 if (!conn->have_tls_session)
508 return (fgets (buffer, (int) buffer_size, conn->fh_in));
510 if ((buffer == NULL) || (buffer_size < 2))
516 /* ensure null termination */
517 memset (buffer, 0, buffer_size);
522 size_t max_copy_bytes;
527 /* If there's no more data in the read buffer, read another chunk from the
529 if (conn->read_buffer_fill < 1)
531 status = gnutls_record_recv (conn->tls_session,
532 conn->read_buffer, NC_READ_BUFFER_SIZE);
533 if (status < 0) /* error */
535 ERROR ("netcmd plugin: Error while reading from TLS stream.");
538 else if (status == 0) /* we reached end of file */
540 if (orig_buffer == buffer) /* nothing has been written to the buffer yet */
541 return (NULL); /* end of file */
543 return (orig_buffer);
547 conn->read_buffer_fill = (size_t) status;
550 assert (conn->read_buffer_fill > 0);
552 /* Determine where the first newline character is in the buffer. We're not
553 * using strcspn(3) here, becaus the buffer is possibly not
554 * null-terminated. */
555 newline_pos = conn->read_buffer_fill;
557 for (i = 0; i < conn->read_buffer_fill; i++)
559 if (conn->read_buffer[i] == '\n')
567 /* Determine how many bytes to copy at most. This is MIN(buffer available,
568 * read buffer size, characters to newline). */
569 max_copy_bytes = buffer_size;
570 if (max_copy_bytes > conn->read_buffer_fill)
571 max_copy_bytes = conn->read_buffer_fill;
572 if (max_copy_bytes > (newline_pos + 1))
573 max_copy_bytes = newline_pos + 1;
574 assert (max_copy_bytes > 0);
576 /* Copy bytes to the output buffer. */
577 memcpy (buffer, conn->read_buffer, max_copy_bytes);
578 buffer += max_copy_bytes;
579 assert (buffer_size >= max_copy_bytes);
580 buffer_size -= max_copy_bytes;
582 /* If there is data left in the read buffer, move it to the front of the
584 if (max_copy_bytes < conn->read_buffer_fill)
586 size_t data_left_size = conn->read_buffer_fill - max_copy_bytes;
587 memmove (conn->read_buffer, conn->read_buffer + max_copy_bytes,
589 conn->read_buffer_fill -= max_copy_bytes;
593 assert (max_copy_bytes == conn->read_buffer_fill);
594 conn->read_buffer_fill = 0;
600 if (buffer_size == 0) /* no more space in the output buffer */
604 return (orig_buffer);
605 } /* }}} char *nc_connection_gets */
607 static void *nc_handle_client (void *arg) /* {{{ */
609 nc_connection_t *conn;
615 DEBUG ("netcmd plugin: nc_handle_client: Reading from fd #%i", conn->fd);
617 status = nc_connection_init (conn);
620 nc_connection_close (conn);
621 pthread_exit ((void *) 1);
627 char buffer_copy[1024];
633 if (nc_connection_gets (conn, buffer, sizeof (buffer)) == NULL)
637 WARNING ("netcmd plugin: failed to read from socket #%i: %s",
638 fileno (conn->fh_in),
639 sstrerror (errno, errbuf, sizeof (errbuf)));
644 len = strlen (buffer);
646 && ((buffer[len - 1] == '\n') || (buffer[len - 1] == '\r')))
647 buffer[--len] = '\0';
652 sstrncpy (buffer_copy, buffer, sizeof (buffer_copy));
654 fields_num = strsplit (buffer_copy, fields,
655 sizeof (fields) / sizeof (fields[0]));
659 nc_connection_close (conn);
663 if (strcasecmp (fields[0], "getval") == 0)
665 handle_getval (conn->fh_out, buffer);
667 else if (strcasecmp (fields[0], "putval") == 0)
669 handle_putval (conn->fh_out, buffer);
671 else if (strcasecmp (fields[0], "listval") == 0)
673 handle_listval (conn->fh_out, buffer);
675 else if (strcasecmp (fields[0], "putnotif") == 0)
677 handle_putnotif (conn->fh_out, buffer);
679 else if (strcasecmp (fields[0], "flush") == 0)
681 handle_flush (conn->fh_out, buffer);
685 if (fprintf (conn->fh_out, "-1 Unknown command: %s\n", fields[0]) < 0)
687 WARNING ("netcmd plugin: failed to write to socket #%i: %s",
688 fileno (conn->fh_out),
689 sstrerror (errno, errbuf, sizeof (errbuf)));
693 } /* while (fgets) */
695 DEBUG ("netcmd plugin: nc_handle_client: Exiting..");
696 nc_connection_close (conn);
698 pthread_exit ((void *) 0);
700 } /* }}} void *nc_handle_client */
702 static void *nc_server_thread (void __attribute__((unused)) *arg) /* {{{ */
706 pthread_attr_t th_attr;
710 for (i = 0; i < peers_num; i++)
711 nc_open_socket (peers + i);
714 nc_open_socket (NULL);
718 ERROR ("netcmd plugin: No sockets could be opened.");
719 pthread_exit ((void *) -1);
722 while (listen_thread_loop != 0)
724 status = poll (pollfd, (nfds_t) pollfd_num, /* timeout = */ -1);
727 if ((errno == EINTR) || (errno == EAGAIN))
730 ERROR ("netcmd plugin: poll(2) failed: %s",
731 sstrerror (errno, errbuf, sizeof (errbuf)));
732 listen_thread_loop = 0;
736 for (i = 0; i < pollfd_num; i++)
739 nc_connection_t *conn;
741 if (pollfd[i].revents == 0)
745 else if ((pollfd[i].revents & (POLLERR | POLLHUP | POLLNVAL))
748 WARNING ("netcmd plugin: File descriptor %i failed.",
750 close (pollfd[i].fd);
752 pollfd[i].events = 0;
753 pollfd[i].revents = 0;
756 pollfd[i].revents = 0;
758 peer = nc_fd_to_peer (pollfd[i].fd);
761 ERROR ("netcmd plugin: Unable to find peer structure for file "
762 "descriptor #%i.", pollfd[i].fd);
766 status = accept (pollfd[i].fd,
767 /* sockaddr = */ NULL,
768 /* sockaddr_len = */ NULL);
772 ERROR ("netcmd plugin: accept failed: %s",
773 sstrerror (errno, errbuf, sizeof (errbuf)));
777 conn = malloc (sizeof (*conn));
780 ERROR ("netcmd plugin: malloc failed.");
784 memset (conn, 0, sizeof (*conn));
790 && (peer->tls_cert_file != NULL))
792 DEBUG ("netcmd plugin: Starting TLS session on [%s]:%s",
793 (peer->node != NULL) ? peer->node : "any",
794 (peer->service != NULL) ? peer->service : NC_DEFAULT_SERVICE);
795 conn->tls_session = nc_tls_get_session (peer);
796 conn->have_tls_session = 1;
799 DEBUG ("Spawning child to handle connection on fd %i", conn->fd);
801 pthread_attr_init (&th_attr);
802 pthread_attr_setdetachstate (&th_attr, PTHREAD_CREATE_DETACHED);
804 status = pthread_create (&th, &th_attr, nc_handle_client,
808 WARNING ("netcmd plugin: pthread_create failed: %s",
809 sstrerror (errno, errbuf, sizeof (errbuf)));
810 nc_connection_close (conn);
814 } /* while (listen_thread_loop) */
816 for (i = 0; i < pollfd_num; i++)
818 if (pollfd[i].fd < 0)
821 close (pollfd[i].fd);
823 pollfd[i].events = 0;
824 pollfd[i].revents = 0;
831 } /* }}} void *nc_server_thread */
838 * TLSCertFile "/path/to/cert"
839 * TLSKeyFile "/path/to/key"
840 * TLSCAFile "/path/to/ca"
841 * TLSCRLFile "/path/to/crl"
842 * TLSVerifyPeer yes|no
846 static int nc_config_peer (const oconfig_item_t *ci) /* {{{ */
851 p = realloc (peers, sizeof (*peers) * (peers_num + 1));
854 ERROR ("netcmd plugin: realloc failed.");
858 p = peers + peers_num;
859 memset (p, 0, sizeof (*p));
862 p->tls_cert_file = NULL;
863 p->tls_key_file = NULL;
864 p->tls_ca_file = NULL;
865 p->tls_crl_file = NULL;
866 p->tls_verify_peer = 1;
868 for (i = 0; i < ci->children_num; i++)
870 oconfig_item_t *child = ci->children + i;
872 if (strcasecmp ("Address", child->key) == 0)
873 cf_util_get_string (child, &p->node);
874 else if (strcasecmp ("Port", child->key) == 0)
875 cf_util_get_string (child, &p->service);
876 else if (strcasecmp ("TLSCertFile", child->key) == 0)
877 cf_util_get_string (child, &p->tls_cert_file);
878 else if (strcasecmp ("TLSKeyFile", child->key) == 0)
879 cf_util_get_string (child, &p->tls_key_file);
880 else if (strcasecmp ("TLSCAFile", child->key) == 0)
881 cf_util_get_string (child, &p->tls_ca_file);
882 else if (strcasecmp ("TLSCRLFile", child->key) == 0)
883 cf_util_get_string (child, &p->tls_crl_file);
884 else if (strcasecmp ("TLSVerifyPeer", child->key) == 0)
885 cf_util_get_boolean (child, &p->tls_verify_peer);
887 WARNING ("netcmd plugin: The option \"%s\" is not recognized within "
888 "a \"%s\" block.", child->key, ci->key);
891 DEBUG ("netcmd plugin: node = \"%s\"; service = \"%s\";", p->node, p->service);
896 } /* }}} int nc_config_peer */
898 static int nc_config (oconfig_item_t *ci)
902 for (i = 0; i < ci->children_num; i++)
904 oconfig_item_t *child = ci->children + i;
906 if (strcasecmp ("Listen", child->key) == 0)
907 nc_config_peer (child);
909 WARNING ("netcmd plugin: The option \"%s\" is not recognized.",
914 } /* int nc_config */
916 static int nc_init (void)
918 static int have_init = 0;
922 /* Initialize only once. */
927 gnutls_global_init ();
929 listen_thread_loop = 1;
931 status = pthread_create (&listen_thread, NULL, nc_server_thread, NULL);
935 listen_thread_loop = 0;
936 listen_thread_running = 0;
937 ERROR ("netcmd plugin: pthread_create failed: %s",
938 sstrerror (errno, errbuf, sizeof (errbuf)));
942 listen_thread_running = 1;
946 static int nc_shutdown (void)
950 listen_thread_loop = 0;
952 if (listen_thread != (pthread_t) 0)
954 pthread_kill (listen_thread, SIGTERM);
955 pthread_join (listen_thread, &ret);
956 listen_thread = (pthread_t) 0;
959 plugin_unregister_init ("netcmd");
960 plugin_unregister_shutdown ("netcmd");
963 } /* int nc_shutdown */
965 void module_register (void)
967 plugin_register_complex_config ("netcmd", nc_config);
968 plugin_register_init ("netcmd", nc_init);
969 plugin_register_shutdown ("netcmd", nc_shutdown);
970 } /* void module_register (void) */
972 /* vim: set sw=2 sts=2 tw=78 et fdm=marker : */