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) /* {{{ */
175 if ((peer->tls_cert_file == NULL)
176 || (peer->tls_key_file == NULL))
179 /* Initialize the structure holding our certificate information. */
180 gnutls_certificate_allocate_credentials (&peer->tls_credentials);
182 /* Set up the configured certificates. */
183 if (peer->tls_ca_file != NULL)
184 gnutls_certificate_set_x509_trust_file (peer->tls_credentials,
185 peer->tls_ca_file, GNUTLS_X509_FMT_PEM);
186 if (peer->tls_crl_file != NULL)
187 gnutls_certificate_set_x509_crl_file (peer->tls_credentials,
188 peer->tls_crl_file, GNUTLS_X509_FMT_PEM);
189 gnutls_certificate_set_x509_key_file (peer->tls_credentials,
190 peer->tls_cert_file, peer->tls_key_file, GNUTLS_X509_FMT_PEM);
192 /* Initialize Diffie-Hellman parameters. */
193 gnutls_dh_params_init (&peer->tls_dh_params);
194 gnutls_dh_params_generate2 (peer->tls_dh_params, NC_TLS_DH_BITS);
195 gnutls_certificate_set_dh_params (peer->tls_credentials,
196 peer->tls_dh_params);
198 /* Initialize a "priority cache". This will tell GNUTLS which algorithms to
199 * use and which to avoid. We use the "NORMAL" method for now. */
200 gnutls_priority_init (&peer->tls_priority,
201 /* priority = */ "NORMAL", /* errpos = */ NULL);
204 } /* }}} int nc_tls_init */
206 static gnutls_session_t nc_tls_get_session (nc_peer_t *peer) /* {{{ */
208 gnutls_session_t session;
210 if (peer->tls_credentials == NULL)
213 /* Initialize new session. */
214 gnutls_init (&session, GNUTLS_SERVER);
216 /* Set cipher priority and credentials based on the information stored with
218 gnutls_priority_set (session, peer->tls_priority);
219 gnutls_credentials_set (session,
220 GNUTLS_CRD_CERTIFICATE, peer->tls_credentials);
222 /* Request the client certificate. */
223 gnutls_certificate_server_set_request (session, GNUTLS_CERT_REQUEST);
226 } /* }}} gnutls_session_t nc_tls_get_session */
228 static int nc_open_socket (nc_peer_t *peer) /* {{{ */
230 struct addrinfo ai_hints;
231 struct addrinfo *ai_list;
232 struct addrinfo *ai_ptr;
235 const char *node = NULL;
236 const char *service = NULL;
241 service = peer->service;
245 service = NC_DEFAULT_SERVICE;
247 memset (&ai_hints, 0, sizeof (ai_hints));
249 ai_hints.ai_flags |= AI_PASSIVE;
252 ai_hints.ai_flags |= AI_ADDRCONFIG;
254 ai_hints.ai_family = AF_UNSPEC;
255 ai_hints.ai_socktype = SOCK_STREAM;
260 service = NC_DEFAULT_SERVICE;
262 status = getaddrinfo (node, service, &ai_hints, &ai_list);
265 ERROR ("netcmd plugin: getaddrinfo failed: %s",
266 gai_strerror (status));
270 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
275 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
276 ai_ptr->ai_protocol);
279 ERROR ("netcmd plugin: socket(2) failed: %s",
280 sstrerror (errno, errbuf, sizeof (errbuf)));
284 status = bind (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
288 ERROR ("netcmd plugin: bind(2) failed: %s",
289 sstrerror (errno, errbuf, sizeof (errbuf)));
293 status = listen (fd, /* backlog = */ 8);
297 ERROR ("netcmd plugin: listen(2) failed: %s",
298 sstrerror (errno, errbuf, sizeof (errbuf)));
302 status = nc_register_fd (peer, fd);
308 } /* for (ai_next) */
310 freeaddrinfo (ai_list);
312 return (nc_tls_init (peer));
313 } /* }}} int nc_open_socket */
315 static void nc_connection_close (nc_connection_t *conn) /* {{{ */
326 if (conn->fh_in != NULL)
328 fclose (conn->fh_in);
332 if (conn->fh_out != NULL)
334 fclose (conn->fh_out);
338 if (conn->have_tls_session)
340 gnutls_deinit (conn->tls_session);
341 conn->have_tls_session = 0;
345 } /* }}} void nc_connection_close */
347 static int nc_connection_init (nc_connection_t *conn) /* {{{ */
352 if (conn->have_tls_session)
354 conn->read_buffer = malloc (NC_READ_BUFFER_SIZE);
355 if (conn->read_buffer == NULL)
357 memset (conn->read_buffer, 0, NC_READ_BUFFER_SIZE);
359 gnutls_transport_set_ptr (conn->tls_session, &conn->fd);
363 /* Duplicate the file descriptor. We need two file descriptors, because we
364 * create two FILE* objects. If they pointed to the same FD and we called
365 * fclose() on each, that would call close() twice on the same FD. If
366 * another file is opened in between those two calls, it could get assigned
367 * that FD and weird stuff would happen. */
368 fd_copy = dup (conn->fd);
371 ERROR ("netcmd plugin: dup(2) failed: %s",
372 sstrerror (errno, errbuf, sizeof (errbuf)));
376 conn->fh_in = fdopen (conn->fd, "r");
377 if (conn->fh_in == NULL)
379 ERROR ("netcmd plugin: fdopen failed: %s",
380 sstrerror (errno, errbuf, sizeof (errbuf)));
383 /* Prevent other code from using the FD directly. */
386 conn->fh_out = fdopen (fd_copy, "w");
387 /* Prevent nc_connection_close from calling close(2) on this fd. */
388 if (conn->fh_out == NULL)
390 ERROR ("netcmd plugin: fdopen failed: %s",
391 sstrerror (errno, errbuf, sizeof (errbuf)));
395 /* change output buffer to line buffered mode */
396 if (setvbuf (conn->fh_out, NULL, _IOLBF, 0) != 0)
398 ERROR ("netcmd plugin: setvbuf failed: %s",
399 sstrerror (errno, errbuf, sizeof (errbuf)));
400 nc_connection_close (conn);
405 } /* }}} int nc_connection_init */
407 static char *nc_connection_gets (nc_connection_t *conn, /* {{{ */
408 char *buffer, size_t buffer_size)
411 char *orig_buffer = buffer;
419 if (!conn->have_tls_session)
420 return (fgets (buffer, (int) buffer_size, conn->fh_in));
422 if ((buffer == NULL) || (buffer_size < 2))
428 /* ensure null termination */
429 memset (buffer, 0, buffer_size);
434 size_t max_copy_bytes;
439 /* If there's no more data in the read buffer, read another chunk from the
441 if (conn->read_buffer_fill < 1)
443 status = gnutls_record_recv (conn->tls_session,
444 conn->read_buffer, NC_READ_BUFFER_SIZE);
445 if (status < 0) /* error */
447 ERROR ("netcmd plugin: Error while reading from TLS stream.");
450 else if (status == 0) /* we reached end of file */
452 if (orig_buffer == buffer) /* nothing has been written to the buffer yet */
453 return (NULL); /* end of file */
455 return (orig_buffer);
459 conn->read_buffer_fill = (size_t) status;
462 assert (conn->read_buffer_fill > 0);
464 /* Determine where the first newline character is in the buffer. We're not
465 * using strcspn(3) here, becaus the buffer is possibly not
466 * null-terminated. */
467 newline_pos = conn->read_buffer_fill;
469 for (i = 0; i < conn->read_buffer_fill; i++)
471 if (conn->read_buffer[i] == '\n')
479 /* Determine how many bytes to copy at most. This is MIN(buffer available,
480 * read buffer size, characters to newline). */
481 max_copy_bytes = buffer_size;
482 if (max_copy_bytes > conn->read_buffer_fill)
483 max_copy_bytes = conn->read_buffer_fill;
484 if (max_copy_bytes > (newline_pos + 1))
485 max_copy_bytes = newline_pos + 1;
486 assert (max_copy_bytes > 0);
488 /* Copy bytes to the output buffer. */
489 memcpy (buffer, conn->read_buffer, max_copy_bytes);
490 buffer += max_copy_bytes;
491 assert (buffer_size >= max_copy_bytes);
492 buffer_size -= max_copy_bytes;
494 /* If there is data left in the read buffer, move it to the front of the
496 if (max_copy_bytes < conn->read_buffer_fill)
498 size_t data_left_size = conn->read_buffer_fill - max_copy_bytes;
499 memmove (conn->read_buffer, conn->read_buffer + max_copy_bytes,
501 conn->read_buffer_fill -= max_copy_bytes;
505 assert (max_copy_bytes == conn->read_buffer_fill);
506 conn->read_buffer_fill = 0;
512 if (buffer_size == 0) /* no more space in the output buffer */
516 return (orig_buffer);
517 } /* }}} char *nc_connection_gets */
519 static void *nc_handle_client (void *arg) /* {{{ */
521 nc_connection_t *conn;
527 DEBUG ("netcmd plugin: nc_handle_client: Reading from fd #%i", conn->fd);
529 status = nc_connection_init (conn);
532 nc_connection_close (conn);
533 pthread_exit ((void *) 1);
539 char buffer_copy[1024];
545 if (nc_connection_gets (conn, buffer, sizeof (buffer)) == NULL)
549 WARNING ("netcmd plugin: failed to read from socket #%i: %s",
550 fileno (conn->fh_in),
551 sstrerror (errno, errbuf, sizeof (errbuf)));
556 len = strlen (buffer);
558 && ((buffer[len - 1] == '\n') || (buffer[len - 1] == '\r')))
559 buffer[--len] = '\0';
564 sstrncpy (buffer_copy, buffer, sizeof (buffer_copy));
566 fields_num = strsplit (buffer_copy, fields,
567 sizeof (fields) / sizeof (fields[0]));
571 nc_connection_close (conn);
575 if (strcasecmp (fields[0], "getval") == 0)
577 handle_getval (conn->fh_out, buffer);
579 else if (strcasecmp (fields[0], "putval") == 0)
581 handle_putval (conn->fh_out, buffer);
583 else if (strcasecmp (fields[0], "listval") == 0)
585 handle_listval (conn->fh_out, buffer);
587 else if (strcasecmp (fields[0], "putnotif") == 0)
589 handle_putnotif (conn->fh_out, buffer);
591 else if (strcasecmp (fields[0], "flush") == 0)
593 handle_flush (conn->fh_out, buffer);
597 if (fprintf (conn->fh_out, "-1 Unknown command: %s\n", fields[0]) < 0)
599 WARNING ("netcmd plugin: failed to write to socket #%i: %s",
600 fileno (conn->fh_out),
601 sstrerror (errno, errbuf, sizeof (errbuf)));
605 } /* while (fgets) */
607 DEBUG ("netcmd plugin: nc_handle_client: Exiting..");
608 nc_connection_close (conn);
610 pthread_exit ((void *) 0);
612 } /* }}} void *nc_handle_client */
614 static void *nc_server_thread (void __attribute__((unused)) *arg) /* {{{ */
618 pthread_attr_t th_attr;
622 for (i = 0; i < peers_num; i++)
623 nc_open_socket (peers + i);
626 nc_open_socket (NULL);
630 ERROR ("netcmd plugin: No sockets could be opened.");
631 pthread_exit ((void *) -1);
634 while (listen_thread_loop != 0)
636 status = poll (pollfd, (nfds_t) pollfd_num, /* timeout = */ -1);
639 if ((errno == EINTR) || (errno == EAGAIN))
642 ERROR ("netcmd plugin: poll(2) failed: %s",
643 sstrerror (errno, errbuf, sizeof (errbuf)));
644 listen_thread_loop = 0;
648 for (i = 0; i < pollfd_num; i++)
651 nc_connection_t *conn;
653 if (pollfd[i].revents == 0)
657 else if ((pollfd[i].revents & (POLLERR | POLLHUP | POLLNVAL))
660 WARNING ("netcmd plugin: File descriptor %i failed.",
662 close (pollfd[i].fd);
664 pollfd[i].events = 0;
665 pollfd[i].revents = 0;
668 pollfd[i].revents = 0;
670 peer = nc_fd_to_peer (pollfd[i].fd);
673 ERROR ("netcmd plugin: Unable to find peer structure for file "
674 "descriptor #%i.", pollfd[i].fd);
678 status = accept (pollfd[i].fd,
679 /* sockaddr = */ NULL,
680 /* sockaddr_len = */ NULL);
684 ERROR ("netcmd plugin: accept failed: %s",
685 sstrerror (errno, errbuf, sizeof (errbuf)));
689 conn = malloc (sizeof (*conn));
692 ERROR ("netcmd plugin: malloc failed.");
696 memset (conn, 0, sizeof (*conn));
702 && (peer->tls_cert_file != NULL))
704 DEBUG ("netcmd plugin: Starting TLS session on [%s]:%s",
705 (peer->node != NULL) ? peer->node : "any",
706 (peer->service != NULL) ? peer->service : NC_DEFAULT_SERVICE);
707 conn->tls_session = nc_tls_get_session (peer);
708 conn->have_tls_session = 1;
711 DEBUG ("Spawning child to handle connection on fd %i", conn->fd);
713 pthread_attr_init (&th_attr);
714 pthread_attr_setdetachstate (&th_attr, PTHREAD_CREATE_DETACHED);
716 status = pthread_create (&th, &th_attr, nc_handle_client,
720 WARNING ("netcmd plugin: pthread_create failed: %s",
721 sstrerror (errno, errbuf, sizeof (errbuf)));
722 nc_connection_close (conn);
726 } /* while (listen_thread_loop) */
728 for (i = 0; i < pollfd_num; i++)
730 if (pollfd[i].fd < 0)
733 close (pollfd[i].fd);
735 pollfd[i].events = 0;
736 pollfd[i].revents = 0;
743 } /* }}} void *nc_server_thread */
750 * TLSCertFile "/path/to/cert"
751 * TLSKeyFile "/path/to/key"
752 * TLSCAFile "/path/to/ca"
753 * TLSCRLFile "/path/to/crl"
754 * TLSVerifyPeer yes|no
758 static int nc_config_peer (const oconfig_item_t *ci) /* {{{ */
763 p = realloc (peers, sizeof (*peers) * (peers_num + 1));
766 ERROR ("netcmd plugin: realloc failed.");
770 p = peers + peers_num;
771 memset (p, 0, sizeof (*p));
774 p->tls_cert_file = NULL;
775 p->tls_key_file = NULL;
776 p->tls_ca_file = NULL;
777 p->tls_crl_file = NULL;
778 p->tls_verify_peer = 1;
780 for (i = 0; i < ci->children_num; i++)
782 oconfig_item_t *child = ci->children + i;
784 if (strcasecmp ("Address", child->key) == 0)
785 cf_util_get_string (child, &p->node);
786 else if (strcasecmp ("Port", child->key) == 0)
787 cf_util_get_string (child, &p->service);
788 else if (strcasecmp ("TLSCertFile", child->key) == 0)
789 cf_util_get_string (child, &p->tls_cert_file);
790 else if (strcasecmp ("TLSKeyFile", child->key) == 0)
791 cf_util_get_string (child, &p->tls_key_file);
792 else if (strcasecmp ("TLSCAFile", child->key) == 0)
793 cf_util_get_string (child, &p->tls_ca_file);
794 else if (strcasecmp ("TLSCRLFile", child->key) == 0)
795 cf_util_get_string (child, &p->tls_crl_file);
797 WARNING ("netcmd plugin: The option \"%s\" is not recognized within "
798 "a \"%s\" block.", child->key, ci->key);
801 DEBUG ("netcmd plugin: node = \"%s\"; service = \"%s\";", p->node, p->service);
806 } /* }}} int nc_config_peer */
808 static int nc_config (oconfig_item_t *ci)
812 for (i = 0; i < ci->children_num; i++)
814 oconfig_item_t *child = ci->children + i;
816 if (strcasecmp ("Listen", child->key) == 0)
817 nc_config_peer (child);
819 WARNING ("netcmd plugin: The option \"%s\" is not recognized.",
824 } /* int nc_config */
826 static int nc_init (void)
828 static int have_init = 0;
832 /* Initialize only once. */
837 listen_thread_loop = 1;
839 status = pthread_create (&listen_thread, NULL, nc_server_thread, NULL);
843 listen_thread_loop = 0;
844 listen_thread_running = 0;
845 ERROR ("netcmd plugin: pthread_create failed: %s",
846 sstrerror (errno, errbuf, sizeof (errbuf)));
850 listen_thread_running = 1;
854 static int nc_shutdown (void)
858 listen_thread_loop = 0;
860 if (listen_thread != (pthread_t) 0)
862 pthread_kill (listen_thread, SIGTERM);
863 pthread_join (listen_thread, &ret);
864 listen_thread = (pthread_t) 0;
867 plugin_unregister_init ("netcmd");
868 plugin_unregister_shutdown ("netcmd");
871 } /* int nc_shutdown */
873 void module_register (void)
875 plugin_register_complex_config ("netcmd", nc_config);
876 plugin_register_init ("netcmd", nc_init);
877 plugin_register_shutdown ("netcmd", nc_shutdown);
878 } /* void module_register (void) */
880 /* vim: set sw=2 sts=2 tw=78 et fdm=marker : */