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)
426 conn->read_buffer = malloc (NC_READ_BUFFER_SIZE);
427 if (conn->read_buffer == NULL)
429 memset (conn->read_buffer, 0, NC_READ_BUFFER_SIZE);
431 /* Make (relatively) sure that 'fd' and 'void*' have the same size to make
433 fd = (intptr_t) conn->fd;
434 gnutls_transport_set_ptr (conn->tls_session,
435 (gnutls_transport_ptr_t) fd);
439 status = gnutls_handshake (conn->tls_session);
440 if (status == GNUTLS_E_SUCCESS)
442 else if ((status == GNUTLS_E_AGAIN) || (status == GNUTLS_E_INTERRUPTED))
446 ERROR ("netcmd plugin: gnutls_handshake failed: %s",
447 gnutls_strerror (status));
455 /* Duplicate the file descriptor. We need two file descriptors, because we
456 * create two FILE* objects. If they pointed to the same FD and we called
457 * fclose() on each, that would call close() twice on the same FD. If
458 * another file is opened in between those two calls, it could get assigned
459 * that FD and weird stuff would happen. */
460 fd_copy = dup (conn->fd);
463 ERROR ("netcmd plugin: dup(2) failed: %s",
464 sstrerror (errno, errbuf, sizeof (errbuf)));
468 conn->fh_in = fdopen (conn->fd, "r");
469 if (conn->fh_in == NULL)
471 ERROR ("netcmd plugin: fdopen failed: %s",
472 sstrerror (errno, errbuf, sizeof (errbuf)));
475 /* Prevent other code from using the FD directly. */
478 conn->fh_out = fdopen (fd_copy, "w");
479 /* Prevent nc_connection_close from calling close(2) on this fd. */
480 if (conn->fh_out == NULL)
482 ERROR ("netcmd plugin: fdopen failed: %s",
483 sstrerror (errno, errbuf, sizeof (errbuf)));
487 /* change output buffer to line buffered mode */
488 if (setvbuf (conn->fh_out, NULL, _IOLBF, 0) != 0)
490 ERROR ("netcmd plugin: setvbuf failed: %s",
491 sstrerror (errno, errbuf, sizeof (errbuf)));
492 nc_connection_close (conn);
497 } /* }}} int nc_connection_init */
499 static char *nc_connection_gets (nc_connection_t *conn, /* {{{ */
500 char *buffer, size_t buffer_size)
503 char *orig_buffer = buffer;
511 if (!conn->have_tls_session)
512 return (fgets (buffer, (int) buffer_size, conn->fh_in));
514 if ((buffer == NULL) || (buffer_size < 2))
520 /* ensure null termination */
521 memset (buffer, 0, buffer_size);
526 size_t max_copy_bytes;
531 /* If there's no more data in the read buffer, read another chunk from the
533 if (conn->read_buffer_fill < 1)
535 status = gnutls_record_recv (conn->tls_session,
536 conn->read_buffer, NC_READ_BUFFER_SIZE);
537 if (status < 0) /* error */
539 ERROR ("netcmd plugin: Error while reading from TLS stream.");
542 else if (status == 0) /* we reached end of file */
544 if (orig_buffer == buffer) /* nothing has been written to the buffer yet */
545 return (NULL); /* end of file */
547 return (orig_buffer);
551 conn->read_buffer_fill = (size_t) status;
554 assert (conn->read_buffer_fill > 0);
556 /* Determine where the first newline character is in the buffer. We're not
557 * using strcspn(3) here, becaus the buffer is possibly not
558 * null-terminated. */
559 newline_pos = conn->read_buffer_fill;
561 for (i = 0; i < conn->read_buffer_fill; i++)
563 if (conn->read_buffer[i] == '\n')
571 /* Determine how many bytes to copy at most. This is MIN(buffer available,
572 * read buffer size, characters to newline). */
573 max_copy_bytes = buffer_size;
574 if (max_copy_bytes > conn->read_buffer_fill)
575 max_copy_bytes = conn->read_buffer_fill;
576 if (max_copy_bytes > (newline_pos + 1))
577 max_copy_bytes = newline_pos + 1;
578 assert (max_copy_bytes > 0);
580 /* Copy bytes to the output buffer. */
581 memcpy (buffer, conn->read_buffer, max_copy_bytes);
582 buffer += max_copy_bytes;
583 assert (buffer_size >= max_copy_bytes);
584 buffer_size -= max_copy_bytes;
586 /* If there is data left in the read buffer, move it to the front of the
588 if (max_copy_bytes < conn->read_buffer_fill)
590 size_t data_left_size = conn->read_buffer_fill - max_copy_bytes;
591 memmove (conn->read_buffer, conn->read_buffer + max_copy_bytes,
593 conn->read_buffer_fill -= max_copy_bytes;
597 assert (max_copy_bytes == conn->read_buffer_fill);
598 conn->read_buffer_fill = 0;
604 if (buffer_size == 0) /* no more space in the output buffer */
608 return (orig_buffer);
609 } /* }}} char *nc_connection_gets */
611 static void *nc_handle_client (void *arg) /* {{{ */
613 nc_connection_t *conn;
619 DEBUG ("netcmd plugin: nc_handle_client: Reading from fd #%i", conn->fd);
621 status = nc_connection_init (conn);
624 nc_connection_close (conn);
625 pthread_exit ((void *) 1);
631 char buffer_copy[1024];
637 if (nc_connection_gets (conn, buffer, sizeof (buffer)) == NULL)
641 WARNING ("netcmd plugin: failed to read from socket #%i: %s",
642 fileno (conn->fh_in),
643 sstrerror (errno, errbuf, sizeof (errbuf)));
648 len = strlen (buffer);
650 && ((buffer[len - 1] == '\n') || (buffer[len - 1] == '\r')))
651 buffer[--len] = '\0';
656 sstrncpy (buffer_copy, buffer, sizeof (buffer_copy));
658 fields_num = strsplit (buffer_copy, fields,
659 sizeof (fields) / sizeof (fields[0]));
663 nc_connection_close (conn);
667 if (strcasecmp (fields[0], "getval") == 0)
669 handle_getval (conn->fh_out, buffer);
671 else if (strcasecmp (fields[0], "putval") == 0)
673 handle_putval (conn->fh_out, buffer);
675 else if (strcasecmp (fields[0], "listval") == 0)
677 handle_listval (conn->fh_out, buffer);
679 else if (strcasecmp (fields[0], "putnotif") == 0)
681 handle_putnotif (conn->fh_out, buffer);
683 else if (strcasecmp (fields[0], "flush") == 0)
685 handle_flush (conn->fh_out, buffer);
689 if (fprintf (conn->fh_out, "-1 Unknown command: %s\n", fields[0]) < 0)
691 WARNING ("netcmd plugin: failed to write to socket #%i: %s",
692 fileno (conn->fh_out),
693 sstrerror (errno, errbuf, sizeof (errbuf)));
697 } /* while (fgets) */
699 DEBUG ("netcmd plugin: nc_handle_client: Exiting..");
700 nc_connection_close (conn);
702 pthread_exit ((void *) 0);
704 } /* }}} void *nc_handle_client */
706 static void *nc_server_thread (void __attribute__((unused)) *arg) /* {{{ */
710 pthread_attr_t th_attr;
714 for (i = 0; i < peers_num; i++)
715 nc_open_socket (peers + i);
718 nc_open_socket (NULL);
722 ERROR ("netcmd plugin: No sockets could be opened.");
723 pthread_exit ((void *) -1);
726 while (listen_thread_loop != 0)
728 status = poll (pollfd, (nfds_t) pollfd_num, /* timeout = */ -1);
731 if ((errno == EINTR) || (errno == EAGAIN))
734 ERROR ("netcmd plugin: poll(2) failed: %s",
735 sstrerror (errno, errbuf, sizeof (errbuf)));
736 listen_thread_loop = 0;
740 for (i = 0; i < pollfd_num; i++)
743 nc_connection_t *conn;
745 if (pollfd[i].revents == 0)
749 else if ((pollfd[i].revents & (POLLERR | POLLHUP | POLLNVAL))
752 WARNING ("netcmd plugin: File descriptor %i failed.",
754 close (pollfd[i].fd);
756 pollfd[i].events = 0;
757 pollfd[i].revents = 0;
760 pollfd[i].revents = 0;
762 peer = nc_fd_to_peer (pollfd[i].fd);
765 ERROR ("netcmd plugin: Unable to find peer structure for file "
766 "descriptor #%i.", pollfd[i].fd);
770 status = accept (pollfd[i].fd,
771 /* sockaddr = */ NULL,
772 /* sockaddr_len = */ NULL);
776 ERROR ("netcmd plugin: accept failed: %s",
777 sstrerror (errno, errbuf, sizeof (errbuf)));
781 conn = malloc (sizeof (*conn));
784 ERROR ("netcmd plugin: malloc failed.");
788 memset (conn, 0, sizeof (*conn));
794 && (peer->tls_cert_file != NULL))
796 DEBUG ("netcmd plugin: Starting TLS session on [%s]:%s",
797 (peer->node != NULL) ? peer->node : "any",
798 (peer->service != NULL) ? peer->service : NC_DEFAULT_SERVICE);
799 conn->tls_session = nc_tls_get_session (peer);
800 conn->have_tls_session = 1;
803 DEBUG ("Spawning child to handle connection on fd %i", conn->fd);
805 pthread_attr_init (&th_attr);
806 pthread_attr_setdetachstate (&th_attr, PTHREAD_CREATE_DETACHED);
808 status = pthread_create (&th, &th_attr, nc_handle_client,
812 WARNING ("netcmd plugin: pthread_create failed: %s",
813 sstrerror (errno, errbuf, sizeof (errbuf)));
814 nc_connection_close (conn);
818 } /* while (listen_thread_loop) */
820 for (i = 0; i < pollfd_num; i++)
822 if (pollfd[i].fd < 0)
825 close (pollfd[i].fd);
827 pollfd[i].events = 0;
828 pollfd[i].revents = 0;
835 } /* }}} void *nc_server_thread */
842 * TLSCertFile "/path/to/cert"
843 * TLSKeyFile "/path/to/key"
844 * TLSCAFile "/path/to/ca"
845 * TLSCRLFile "/path/to/crl"
846 * TLSVerifyPeer yes|no
850 static int nc_config_peer (const oconfig_item_t *ci) /* {{{ */
855 p = realloc (peers, sizeof (*peers) * (peers_num + 1));
858 ERROR ("netcmd plugin: realloc failed.");
862 p = peers + peers_num;
863 memset (p, 0, sizeof (*p));
866 p->tls_cert_file = NULL;
867 p->tls_key_file = NULL;
868 p->tls_ca_file = NULL;
869 p->tls_crl_file = NULL;
870 p->tls_verify_peer = 1;
872 for (i = 0; i < ci->children_num; i++)
874 oconfig_item_t *child = ci->children + i;
876 if (strcasecmp ("Address", child->key) == 0)
877 cf_util_get_string (child, &p->node);
878 else if (strcasecmp ("Port", child->key) == 0)
879 cf_util_get_string (child, &p->service);
880 else if (strcasecmp ("TLSCertFile", child->key) == 0)
881 cf_util_get_string (child, &p->tls_cert_file);
882 else if (strcasecmp ("TLSKeyFile", child->key) == 0)
883 cf_util_get_string (child, &p->tls_key_file);
884 else if (strcasecmp ("TLSCAFile", child->key) == 0)
885 cf_util_get_string (child, &p->tls_ca_file);
886 else if (strcasecmp ("TLSCRLFile", child->key) == 0)
887 cf_util_get_string (child, &p->tls_crl_file);
888 else if (strcasecmp ("TLSVerifyPeer", child->key) == 0)
889 cf_util_get_boolean (child, &p->tls_verify_peer);
891 WARNING ("netcmd plugin: The option \"%s\" is not recognized within "
892 "a \"%s\" block.", child->key, ci->key);
895 DEBUG ("netcmd plugin: node = \"%s\"; service = \"%s\";", p->node, p->service);
900 } /* }}} int nc_config_peer */
902 static int nc_config (oconfig_item_t *ci)
906 for (i = 0; i < ci->children_num; i++)
908 oconfig_item_t *child = ci->children + i;
910 if (strcasecmp ("Listen", child->key) == 0)
911 nc_config_peer (child);
913 WARNING ("netcmd plugin: The option \"%s\" is not recognized.",
918 } /* int nc_config */
920 static int nc_init (void)
922 static int have_init = 0;
926 /* Initialize only once. */
931 gnutls_global_init ();
933 listen_thread_loop = 1;
935 status = pthread_create (&listen_thread, NULL, nc_server_thread, NULL);
939 listen_thread_loop = 0;
940 listen_thread_running = 0;
941 ERROR ("netcmd plugin: pthread_create failed: %s",
942 sstrerror (errno, errbuf, sizeof (errbuf)));
946 listen_thread_running = 1;
950 static int nc_shutdown (void)
954 listen_thread_loop = 0;
956 if (listen_thread != (pthread_t) 0)
958 pthread_kill (listen_thread, SIGTERM);
959 pthread_join (listen_thread, &ret);
960 listen_thread = (pthread_t) 0;
963 plugin_unregister_init ("netcmd");
964 plugin_unregister_shutdown ("netcmd");
967 } /* int nc_shutdown */
969 void module_register (void)
971 plugin_register_complex_config ("netcmd", nc_config);
972 plugin_register_init ("netcmd", nc_init);
973 plugin_register_shutdown ("netcmd", nc_shutdown);
974 } /* void module_register (void) */
976 /* vim: set sw=2 sts=2 tw=78 et fdm=marker : */