1 /**
2 * collectd - src/network.c
3 * Copyright (C) 2005-2009 Florian octo Forster
4 * Copyright (C) 2009 Aman Gupta
5 *
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as published by
8 * the Free Software Foundation; only version 2.1 of the License is
9 * applicable.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 *
20 * Authors:
21 * Florian octo Forster <octo at verplant.org>
22 * Aman Gupta <aman at tmm1.net>
23 **/
25 #define _BSD_SOURCE /* For struct ip_mreq */
27 #include "collectd.h"
28 #include "plugin.h"
29 #include "common.h"
30 #include "configfile.h"
31 #include "utils_fbhash.h"
32 #include "utils_avltree.h"
33 #include "utils_cache.h"
34 #include "utils_complain.h"
36 #include "network.h"
38 #if HAVE_PTHREAD_H
39 # include <pthread.h>
40 #endif
41 #if HAVE_SYS_SOCKET_H
42 # include <sys/socket.h>
43 #endif
44 #if HAVE_NETDB_H
45 # include <netdb.h>
46 #endif
47 #if HAVE_NETINET_IN_H
48 # include <netinet/in.h>
49 #endif
50 #if HAVE_ARPA_INET_H
51 # include <arpa/inet.h>
52 #endif
53 #if HAVE_POLL_H
54 # include <poll.h>
55 #endif
56 #if HAVE_NET_IF_H
57 # include <net/if.h>
58 #endif
60 #if HAVE_LIBGCRYPT
61 # include <pthread.h>
62 # if defined __APPLE__
63 /* default xcode compiler throws warnings even when deprecated functionality
64 * is not used. -Werror breaks the build because of erroneous warnings.
65 * http://stackoverflow.com/questions/10556299/compiler-warnings-with-libgcrypt-v1-5-0/12830209#12830209
66 */
67 # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
68 # endif
69 /* FreeBSD's copy of libgcrypt extends the existing GCRYPT_NO_DEPRECATED
70 * to properly hide all deprecated functionality.
71 * http://svnweb.freebsd.org/ports/head/security/libgcrypt/files/patch-src__gcrypt.h.in
72 */
73 # define GCRYPT_NO_DEPRECATED
74 # include <gcrypt.h>
75 # if defined __APPLE__
76 /* Re enable deprecation warnings */
77 # pragma GCC diagnostic warning "-Wdeprecated-declarations"
78 # endif
79 GCRY_THREAD_OPTION_PTHREAD_IMPL;
80 #endif
82 #ifndef IPV6_ADD_MEMBERSHIP
83 # ifdef IPV6_JOIN_GROUP
84 # define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
85 # else
86 # error "Neither IP_ADD_MEMBERSHIP nor IPV6_JOIN_GROUP is defined"
87 # endif
88 #endif /* !IP_ADD_MEMBERSHIP */
90 /*
91 * Maximum size required for encryption / signing:
92 *
93 * 42 bytes for the encryption header
94 * + 64 bytes for the username
95 * -----------
96 * = 106 bytes
97 */
98 #define BUFF_SIG_SIZE 106
100 /*
101 * Private data types
102 */
103 #define SECURITY_LEVEL_NONE 0
104 #if HAVE_LIBGCRYPT
105 # define SECURITY_LEVEL_SIGN 1
106 # define SECURITY_LEVEL_ENCRYPT 2
107 #endif
108 struct sockent_client
109 {
110 int fd;
111 struct sockaddr_storage *addr;
112 socklen_t addrlen;
113 #if HAVE_LIBGCRYPT
114 int security_level;
115 char *username;
116 char *password;
117 gcry_cipher_hd_t cypher;
118 unsigned char password_hash[32];
119 #endif
120 };
122 struct sockent_server
123 {
124 int *fd;
125 size_t fd_num;
126 #if HAVE_LIBGCRYPT
127 int security_level;
128 char *auth_file;
129 fbhash_t *userdb;
130 gcry_cipher_hd_t cypher;
131 #endif
132 };
134 typedef struct sockent
135 {
136 #define SOCKENT_TYPE_CLIENT 1
137 #define SOCKENT_TYPE_SERVER 2
138 int type;
140 char *node;
141 char *service;
142 int interface;
144 union
145 {
146 struct sockent_client client;
147 struct sockent_server server;
148 } data;
150 struct sockent *next;
151 } sockent_t;
153 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
154 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
155 * +-------+-----------------------+-------------------------------+
156 * ! Ver. ! ! Length !
157 * +-------+-----------------------+-------------------------------+
158 */
159 struct part_header_s
160 {
161 uint16_t type;
162 uint16_t length;
163 };
164 typedef struct part_header_s part_header_t;
166 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
167 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
168 * +-------------------------------+-------------------------------+
169 * ! Type ! Length !
170 * +-------------------------------+-------------------------------+
171 * : (Length - 4) Bytes :
172 * +---------------------------------------------------------------+
173 */
174 struct part_string_s
175 {
176 part_header_t *head;
177 char *value;
178 };
179 typedef struct part_string_s part_string_t;
181 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
182 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
183 * +-------------------------------+-------------------------------+
184 * ! Type ! Length !
185 * +-------------------------------+-------------------------------+
186 * : (Length - 4 == 2 || 4 || 8) Bytes :
187 * +---------------------------------------------------------------+
188 */
189 struct part_number_s
190 {
191 part_header_t *head;
192 uint64_t *value;
193 };
194 typedef struct part_number_s part_number_t;
196 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
197 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
198 * +-------------------------------+-------------------------------+
199 * ! Type ! Length !
200 * +-------------------------------+---------------+---------------+
201 * ! Num of values ! Type0 ! Type1 !
202 * +-------------------------------+---------------+---------------+
203 * ! Value0 !
204 * ! !
205 * +---------------------------------------------------------------+
206 * ! Value1 !
207 * ! !
208 * +---------------------------------------------------------------+
209 */
210 struct part_values_s
211 {
212 part_header_t *head;
213 uint16_t *num_values;
214 uint8_t *values_types;
215 value_t *values;
216 };
217 typedef struct part_values_s part_values_t;
219 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
220 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
221 * +-------------------------------+-------------------------------+
222 * ! Type ! Length !
223 * +-------------------------------+-------------------------------+
224 * ! Hash (Bits 0 - 31) !
225 * : : :
226 * ! Hash (Bits 224 - 255) !
227 * +---------------------------------------------------------------+
228 */
229 /* Minimum size */
230 #define PART_SIGNATURE_SHA256_SIZE 36
231 struct part_signature_sha256_s
232 {
233 part_header_t head;
234 unsigned char hash[32];
235 char *username;
236 };
237 typedef struct part_signature_sha256_s part_signature_sha256_t;
239 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
240 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
241 * +-------------------------------+-------------------------------+
242 * ! Type ! Length !
243 * +-------------------------------+-------------------------------+
244 * ! Original length ! Padding (0 - 15 bytes) !
245 * +-------------------------------+-------------------------------+
246 * ! Hash (Bits 0 - 31) !
247 * : : :
248 * ! Hash (Bits 128 - 159) !
249 * +---------------------------------------------------------------+
250 */
251 /* Minimum size */
252 #define PART_ENCRYPTION_AES256_SIZE 42
253 struct part_encryption_aes256_s
254 {
255 part_header_t head;
256 uint16_t username_length;
257 char *username;
258 unsigned char iv[16];
259 /* <encrypted> */
260 unsigned char hash[20];
261 /* <payload /> */
262 /* </encrypted> */
263 };
264 typedef struct part_encryption_aes256_s part_encryption_aes256_t;
266 struct receive_list_entry_s
267 {
268 char *data;
269 int data_len;
270 int fd;
271 struct receive_list_entry_s *next;
272 };
273 typedef struct receive_list_entry_s receive_list_entry_t;
275 /*
276 * Private variables
277 */
278 static int network_config_ttl = 0;
279 static size_t network_config_packet_size = 1024;
280 static int network_config_forward = 0;
281 static int network_config_stats = 0;
283 static sockent_t *sending_sockets = NULL;
285 static receive_list_entry_t *receive_list_head = NULL;
286 static receive_list_entry_t *receive_list_tail = NULL;
287 static pthread_mutex_t receive_list_lock = PTHREAD_MUTEX_INITIALIZER;
288 static pthread_cond_t receive_list_cond = PTHREAD_COND_INITIALIZER;
289 static uint64_t receive_list_length = 0;
291 static sockent_t *listen_sockets = NULL;
292 static struct pollfd *listen_sockets_pollfd = NULL;
293 static size_t listen_sockets_num = 0;
295 /* The receive and dispatch threads will run as long as `listen_loop' is set to
296 * zero. */
297 static int listen_loop = 0;
298 static int receive_thread_running = 0;
299 static pthread_t receive_thread_id;
300 static int dispatch_thread_running = 0;
301 static pthread_t dispatch_thread_id;
303 /* Buffer in which to-be-sent network packets are constructed. */
304 static char *send_buffer;
305 static char *send_buffer_ptr;
306 static int send_buffer_fill;
307 static value_list_t send_buffer_vl = VALUE_LIST_STATIC;
308 static pthread_mutex_t send_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
310 /* XXX: These counters are incremented from one place only. The spot in which
311 * the values are incremented is either only reachable by one thread (the
312 * dispatch thread, for example) or locked by some lock (send_buffer_lock for
313 * example). Only if neither is true, the stats_lock is acquired. The counters
314 * are always read without holding a lock in the hope that writing 8 bytes to
315 * memory is an atomic operation. */
316 static uint64_t stats_octets_rx = 0;
317 static uint64_t stats_octets_tx = 0;
318 static uint64_t stats_packets_rx = 0;
319 static uint64_t stats_packets_tx = 0;
320 static uint64_t stats_values_dispatched = 0;
321 static uint64_t stats_values_not_dispatched = 0;
322 static uint64_t stats_values_sent = 0;
323 static uint64_t stats_values_not_sent = 0;
324 static pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER;
326 /*
327 * Private functions
328 */
329 static _Bool check_receive_okay (const value_list_t *vl) /* {{{ */
330 {
331 uint64_t time_sent = 0;
332 int status;
334 status = uc_meta_data_get_unsigned_int (vl,
335 "network:time_sent", &time_sent);
337 /* This is a value we already sent. Don't allow it to be received again in
338 * order to avoid looping. */
339 if ((status == 0) && (time_sent >= ((uint64_t) vl->time)))
340 return (false);
342 return (true);
343 } /* }}} _Bool check_receive_okay */
345 static _Bool check_send_okay (const value_list_t *vl) /* {{{ */
346 {
347 _Bool received = false;
348 int status;
350 if (network_config_forward != 0)
351 return (true);
353 if (vl->meta == NULL)
354 return (true);
356 status = meta_data_get_boolean (vl->meta, "network:received", &received);
357 if (status == -ENOENT)
358 return (true);
359 else if (status != 0)
360 {
361 ERROR ("network plugin: check_send_okay: meta_data_get_boolean failed "
362 "with status %i.", status);
363 return (true);
364 }
366 /* By default, only *send* value lists that were not *received* by the
367 * network plugin. */
368 return (!received);
369 } /* }}} _Bool check_send_okay */
371 static _Bool check_notify_received (const notification_t *n) /* {{{ */
372 {
373 notification_meta_t *ptr;
375 for (ptr = n->meta; ptr != NULL; ptr = ptr->next)
376 if ((strcmp ("network:received", ptr->name) == 0)
377 && (ptr->type == NM_TYPE_BOOLEAN))
378 return ((_Bool) ptr->nm_value.nm_boolean);
380 return (0);
381 } /* }}} _Bool check_notify_received */
383 static _Bool check_send_notify_okay (const notification_t *n) /* {{{ */
384 {
385 static c_complain_t complain_forwarding = C_COMPLAIN_INIT_STATIC;
386 _Bool received = 0;
388 if (n->meta == NULL)
389 return (1);
391 received = check_notify_received (n);
393 if (network_config_forward && received)
394 {
395 c_complain_once (LOG_ERR, &complain_forwarding,
396 "network plugin: A notification has been received via the network "
397 "forwarding if enabled. Forwarding of notifications is currently "
398 "not supported, because there is not loop-deteciton available. "
399 "Please contact the collectd mailing list if you need this "
400 "feature.");
401 }
403 /* By default, only *send* value lists that were not *received* by the
404 * network plugin. */
405 return (!received);
406 } /* }}} _Bool check_send_notify_okay */
408 static int network_dispatch_values (value_list_t *vl, /* {{{ */
409 const char *username)
410 {
411 int status;
413 if ((vl->time <= 0)
414 || (strlen (vl->host) <= 0)
415 || (strlen (vl->plugin) <= 0)
416 || (strlen (vl->type) <= 0))
417 return (-EINVAL);
419 if (!check_receive_okay (vl))
420 {
421 #if COLLECT_DEBUG
422 char name[6*DATA_MAX_NAME_LEN];
423 FORMAT_VL (name, sizeof (name), vl);
424 name[sizeof (name) - 1] = 0;
425 DEBUG ("network plugin: network_dispatch_values: "
426 "NOT dispatching %s.", name);
427 #endif
428 stats_values_not_dispatched++;
429 return (0);
430 }
432 assert (vl->meta == NULL);
434 vl->meta = meta_data_create ();
435 if (vl->meta == NULL)
436 {
437 ERROR ("network plugin: meta_data_create failed.");
438 return (-ENOMEM);
439 }
441 status = meta_data_add_boolean (vl->meta, "network:received", true);
442 if (status != 0)
443 {
444 ERROR ("network plugin: meta_data_add_boolean failed.");
445 meta_data_destroy (vl->meta);
446 vl->meta = NULL;
447 return (status);
448 }
450 if (username != NULL)
451 {
452 status = meta_data_add_string (vl->meta, "network:username", username);
453 if (status != 0)
454 {
455 ERROR ("network plugin: meta_data_add_string failed.");
456 meta_data_destroy (vl->meta);
457 vl->meta = NULL;
458 return (status);
459 }
460 }
462 plugin_dispatch_values_secure (vl);
463 stats_values_dispatched++;
465 meta_data_destroy (vl->meta);
466 vl->meta = NULL;
468 return (0);
469 } /* }}} int network_dispatch_values */
471 static int network_dispatch_notification (notification_t *n) /* {{{ */
472 {
473 int status;
475 assert (n->meta == NULL);
477 status = plugin_notification_meta_add_boolean (n, "network:received", 1);
478 if (status != 0)
479 {
480 ERROR ("network plugin: plugin_notification_meta_add_boolean failed.");
481 plugin_notification_meta_free (n->meta);
482 n->meta = NULL;
483 return (status);
484 }
486 status = plugin_dispatch_notification (n);
488 plugin_notification_meta_free (n->meta);
489 n->meta = NULL;
491 return (status);
492 } /* }}} int network_dispatch_notification */
494 #if HAVE_LIBGCRYPT
495 static gcry_cipher_hd_t network_get_aes256_cypher (sockent_t *se, /* {{{ */
496 const void *iv, size_t iv_size, const char *username)
497 {
498 gcry_error_t err;
499 gcry_cipher_hd_t *cyper_ptr;
500 unsigned char password_hash[32];
502 if (se->type == SOCKENT_TYPE_CLIENT)
503 {
504 cyper_ptr = &se->data.client.cypher;
505 memcpy (password_hash, se->data.client.password_hash,
506 sizeof (password_hash));
507 }
508 else
509 {
510 char *secret;
512 cyper_ptr = &se->data.server.cypher;
514 if (username == NULL)
515 return (NULL);
517 secret = fbh_get (se->data.server.userdb, username);
518 if (secret == NULL)
519 return (NULL);
521 gcry_md_hash_buffer (GCRY_MD_SHA256,
522 password_hash,
523 secret, strlen (secret));
525 sfree (secret);
526 }
528 if (*cyper_ptr == NULL)
529 {
530 err = gcry_cipher_open (cyper_ptr,
531 GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB, /* flags = */ 0);
532 if (err != 0)
533 {
534 ERROR ("network plugin: gcry_cipher_open returned: %s",
535 gcry_strerror (err));
536 *cyper_ptr = NULL;
537 return (NULL);
538 }
539 }
540 else
541 {
542 gcry_cipher_reset (*cyper_ptr);
543 }
544 assert (*cyper_ptr != NULL);
546 err = gcry_cipher_setkey (*cyper_ptr,
547 password_hash, sizeof (password_hash));
548 if (err != 0)
549 {
550 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
551 gcry_strerror (err));
552 gcry_cipher_close (*cyper_ptr);
553 *cyper_ptr = NULL;
554 return (NULL);
555 }
557 err = gcry_cipher_setiv (*cyper_ptr, iv, iv_size);
558 if (err != 0)
559 {
560 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
561 gcry_strerror (err));
562 gcry_cipher_close (*cyper_ptr);
563 *cyper_ptr = NULL;
564 return (NULL);
565 }
567 return (*cyper_ptr);
568 } /* }}} int network_get_aes256_cypher */
569 #endif /* HAVE_LIBGCRYPT */
571 static int write_part_values (char **ret_buffer, int *ret_buffer_len,
572 const data_set_t *ds, const value_list_t *vl)
573 {
574 char *packet_ptr;
575 int packet_len;
576 int num_values;
578 part_header_t pkg_ph;
579 uint16_t pkg_num_values;
580 uint8_t *pkg_values_types;
581 value_t *pkg_values;
583 int offset;
584 int i;
586 num_values = vl->values_len;
587 packet_len = sizeof (part_header_t) + sizeof (uint16_t)
588 + (num_values * sizeof (uint8_t))
589 + (num_values * sizeof (value_t));
591 if (*ret_buffer_len < packet_len)
592 return (-1);
594 pkg_values_types = (uint8_t *) malloc (num_values * sizeof (uint8_t));
595 if (pkg_values_types == NULL)
596 {
597 ERROR ("network plugin: write_part_values: malloc failed.");
598 return (-1);
599 }
601 pkg_values = (value_t *) malloc (num_values * sizeof (value_t));
602 if (pkg_values == NULL)
603 {
604 free (pkg_values_types);
605 ERROR ("network plugin: write_part_values: malloc failed.");
606 return (-1);
607 }
609 pkg_ph.type = htons (TYPE_VALUES);
610 pkg_ph.length = htons (packet_len);
612 pkg_num_values = htons ((uint16_t) vl->values_len);
614 for (i = 0; i < num_values; i++)
615 {
616 pkg_values_types[i] = (uint8_t) ds->ds[i].type;
617 switch (ds->ds[i].type)
618 {
619 case DS_TYPE_COUNTER:
620 pkg_values[i].counter = htonll (vl->values[i].counter);
621 break;
623 case DS_TYPE_GAUGE:
624 pkg_values[i].gauge = htond (vl->values[i].gauge);
625 break;
627 case DS_TYPE_DERIVE:
628 pkg_values[i].derive = htonll (vl->values[i].derive);
629 break;
631 case DS_TYPE_ABSOLUTE:
632 pkg_values[i].absolute = htonll (vl->values[i].absolute);
633 break;
635 default:
636 free (pkg_values_types);
637 free (pkg_values);
638 ERROR ("network plugin: write_part_values: "
639 "Unknown data source type: %i",
640 ds->ds[i].type);
641 return (-1);
642 } /* switch (ds->ds[i].type) */
643 } /* for (num_values) */
645 /*
646 * Use `memcpy' to write everything to the buffer, because the pointer
647 * may be unaligned and some architectures, such as SPARC, can't handle
648 * that.
649 */
650 packet_ptr = *ret_buffer;
651 offset = 0;
652 memcpy (packet_ptr + offset, &pkg_ph, sizeof (pkg_ph));
653 offset += sizeof (pkg_ph);
654 memcpy (packet_ptr + offset, &pkg_num_values, sizeof (pkg_num_values));
655 offset += sizeof (pkg_num_values);
656 memcpy (packet_ptr + offset, pkg_values_types, num_values * sizeof (uint8_t));
657 offset += num_values * sizeof (uint8_t);
658 memcpy (packet_ptr + offset, pkg_values, num_values * sizeof (value_t));
659 offset += num_values * sizeof (value_t);
661 assert (offset == packet_len);
663 *ret_buffer = packet_ptr + packet_len;
664 *ret_buffer_len -= packet_len;
666 free (pkg_values_types);
667 free (pkg_values);
669 return (0);
670 } /* int write_part_values */
672 static int write_part_number (char **ret_buffer, int *ret_buffer_len,
673 int type, uint64_t value)
674 {
675 char *packet_ptr;
676 int packet_len;
678 part_header_t pkg_head;
679 uint64_t pkg_value;
681 int offset;
683 packet_len = sizeof (pkg_head) + sizeof (pkg_value);
685 if (*ret_buffer_len < packet_len)
686 return (-1);
688 pkg_head.type = htons (type);
689 pkg_head.length = htons (packet_len);
690 pkg_value = htonll (value);
692 packet_ptr = *ret_buffer;
693 offset = 0;
694 memcpy (packet_ptr + offset, &pkg_head, sizeof (pkg_head));
695 offset += sizeof (pkg_head);
696 memcpy (packet_ptr + offset, &pkg_value, sizeof (pkg_value));
697 offset += sizeof (pkg_value);
699 assert (offset == packet_len);
701 *ret_buffer = packet_ptr + packet_len;
702 *ret_buffer_len -= packet_len;
704 return (0);
705 } /* int write_part_number */
707 static int write_part_string (char **ret_buffer, int *ret_buffer_len,
708 int type, const char *str, int str_len)
709 {
710 char *buffer;
711 int buffer_len;
713 uint16_t pkg_type;
714 uint16_t pkg_length;
716 int offset;
718 buffer_len = 2 * sizeof (uint16_t) + str_len + 1;
719 if (*ret_buffer_len < buffer_len)
720 return (-1);
722 pkg_type = htons (type);
723 pkg_length = htons (buffer_len);
725 buffer = *ret_buffer;
726 offset = 0;
727 memcpy (buffer + offset, (void *) &pkg_type, sizeof (pkg_type));
728 offset += sizeof (pkg_type);
729 memcpy (buffer + offset, (void *) &pkg_length, sizeof (pkg_length));
730 offset += sizeof (pkg_length);
731 memcpy (buffer + offset, str, str_len);
732 offset += str_len;
733 memset (buffer + offset, '\0', 1);
734 offset += 1;
736 assert (offset == buffer_len);
738 *ret_buffer = buffer + buffer_len;
739 *ret_buffer_len -= buffer_len;
741 return (0);
742 } /* int write_part_string */
744 static int parse_part_values (void **ret_buffer, size_t *ret_buffer_len,
745 value_t **ret_values, int *ret_num_values)
746 {
747 char *buffer = *ret_buffer;
748 size_t buffer_len = *ret_buffer_len;
750 uint16_t tmp16;
751 size_t exp_size;
752 int i;
754 uint16_t pkg_length;
755 uint16_t pkg_type;
756 uint16_t pkg_numval;
758 uint8_t *pkg_types;
759 value_t *pkg_values;
761 if (buffer_len < 15)
762 {
763 NOTICE ("network plugin: packet is too short: "
764 "buffer_len = %zu", buffer_len);
765 return (-1);
766 }
768 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
769 buffer += sizeof (tmp16);
770 pkg_type = ntohs (tmp16);
772 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
773 buffer += sizeof (tmp16);
774 pkg_length = ntohs (tmp16);
776 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
777 buffer += sizeof (tmp16);
778 pkg_numval = ntohs (tmp16);
780 assert (pkg_type == TYPE_VALUES);
782 exp_size = 3 * sizeof (uint16_t)
783 + pkg_numval * (sizeof (uint8_t) + sizeof (value_t));
784 if (buffer_len < exp_size)
785 {
786 WARNING ("network plugin: parse_part_values: "
787 "Packet too short: "
788 "Chunk of size %zu expected, "
789 "but buffer has only %zu bytes left.",
790 exp_size, buffer_len);
791 return (-1);
792 }
794 if (pkg_length != exp_size)
795 {
796 WARNING ("network plugin: parse_part_values: "
797 "Length and number of values "
798 "in the packet don't match.");
799 return (-1);
800 }
802 pkg_types = (uint8_t *) malloc (pkg_numval * sizeof (uint8_t));
803 pkg_values = (value_t *) malloc (pkg_numval * sizeof (value_t));
804 if ((pkg_types == NULL) || (pkg_values == NULL))
805 {
806 sfree (pkg_types);
807 sfree (pkg_values);
808 ERROR ("network plugin: parse_part_values: malloc failed.");
809 return (-1);
810 }
812 memcpy ((void *) pkg_types, (void *) buffer, pkg_numval * sizeof (uint8_t));
813 buffer += pkg_numval * sizeof (uint8_t);
814 memcpy ((void *) pkg_values, (void *) buffer, pkg_numval * sizeof (value_t));
815 buffer += pkg_numval * sizeof (value_t);
817 for (i = 0; i < pkg_numval; i++)
818 {
819 switch (pkg_types[i])
820 {
821 case DS_TYPE_COUNTER:
822 pkg_values[i].counter = (counter_t) ntohll (pkg_values[i].counter);
823 break;
825 case DS_TYPE_GAUGE:
826 pkg_values[i].gauge = (gauge_t) ntohd (pkg_values[i].gauge);
827 break;
829 case DS_TYPE_DERIVE:
830 pkg_values[i].derive = (derive_t) ntohll (pkg_values[i].derive);
831 break;
833 case DS_TYPE_ABSOLUTE:
834 pkg_values[i].absolute = (absolute_t) ntohll (pkg_values[i].absolute);
835 break;
837 default:
838 NOTICE ("network plugin: parse_part_values: "
839 "Don't know how to handle data source type %"PRIu8,
840 pkg_types[i]);
841 sfree (pkg_types);
842 sfree (pkg_values);
843 return (-1);
844 } /* switch (pkg_types[i]) */
845 }
847 *ret_buffer = buffer;
848 *ret_buffer_len = buffer_len - pkg_length;
849 *ret_num_values = pkg_numval;
850 *ret_values = pkg_values;
852 sfree (pkg_types);
854 return (0);
855 } /* int parse_part_values */
857 static int parse_part_number (void **ret_buffer, size_t *ret_buffer_len,
858 uint64_t *value)
859 {
860 char *buffer = *ret_buffer;
861 size_t buffer_len = *ret_buffer_len;
863 uint16_t tmp16;
864 uint64_t tmp64;
865 size_t exp_size = 2 * sizeof (uint16_t) + sizeof (uint64_t);
867 uint16_t pkg_length;
869 if (buffer_len < exp_size)
870 {
871 WARNING ("network plugin: parse_part_number: "
872 "Packet too short: "
873 "Chunk of size %zu expected, "
874 "but buffer has only %zu bytes left.",
875 exp_size, buffer_len);
876 return (-1);
877 }
879 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
880 buffer += sizeof (tmp16);
881 /* pkg_type = ntohs (tmp16); */
883 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
884 buffer += sizeof (tmp16);
885 pkg_length = ntohs (tmp16);
887 memcpy ((void *) &tmp64, buffer, sizeof (tmp64));
888 buffer += sizeof (tmp64);
889 *value = ntohll (tmp64);
891 *ret_buffer = buffer;
892 *ret_buffer_len = buffer_len - pkg_length;
894 return (0);
895 } /* int parse_part_number */
897 static int parse_part_string (void **ret_buffer, size_t *ret_buffer_len,
898 char *output, int output_len)
899 {
900 char *buffer = *ret_buffer;
901 size_t buffer_len = *ret_buffer_len;
903 uint16_t tmp16;
904 size_t header_size = 2 * sizeof (uint16_t);
906 uint16_t pkg_length;
908 if (buffer_len < header_size)
909 {
910 WARNING ("network plugin: parse_part_string: "
911 "Packet too short: "
912 "Chunk of at least size %zu expected, "
913 "but buffer has only %zu bytes left.",
914 header_size, buffer_len);
915 return (-1);
916 }
918 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
919 buffer += sizeof (tmp16);
920 /* pkg_type = ntohs (tmp16); */
922 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
923 buffer += sizeof (tmp16);
924 pkg_length = ntohs (tmp16);
926 /* Check that packet fits in the input buffer */
927 if (pkg_length > buffer_len)
928 {
929 WARNING ("network plugin: parse_part_string: "
930 "Packet too big: "
931 "Chunk of size %"PRIu16" received, "
932 "but buffer has only %zu bytes left.",
933 pkg_length, buffer_len);
934 return (-1);
935 }
937 /* Check that pkg_length is in the valid range */
938 if (pkg_length <= header_size)
939 {
940 WARNING ("network plugin: parse_part_string: "
941 "Packet too short: "
942 "Header claims this packet is only %hu "
943 "bytes long.", pkg_length);
944 return (-1);
945 }
947 /* Check that the package data fits into the output buffer.
948 * The previous if-statement ensures that:
949 * `pkg_length > header_size' */
950 if ((output_len < 0)
951 || ((size_t) output_len < ((size_t) pkg_length - header_size)))
952 {
953 WARNING ("network plugin: parse_part_string: "
954 "Output buffer too small.");
955 return (-1);
956 }
958 /* All sanity checks successfull, let's copy the data over */
959 output_len = pkg_length - header_size;
960 memcpy ((void *) output, (void *) buffer, output_len);
961 buffer += output_len;
963 /* For some very weird reason '\0' doesn't do the trick on SPARC in
964 * this statement. */
965 if (output[output_len - 1] != 0)
966 {
967 WARNING ("network plugin: parse_part_string: "
968 "Received string does not end "
969 "with a NULL-byte.");
970 return (-1);
971 }
973 *ret_buffer = buffer;
974 *ret_buffer_len = buffer_len - pkg_length;
976 return (0);
977 } /* int parse_part_string */
979 /* Forward declaration: parse_part_sign_sha256 and parse_part_encr_aes256 call
980 * parse_packet and vice versa. */
981 #define PP_SIGNED 0x01
982 #define PP_ENCRYPTED 0x02
983 static int parse_packet (sockent_t *se,
984 void *buffer, size_t buffer_size, int flags,
985 const char *username);
987 #define BUFFER_READ(p,s) do { \
988 memcpy ((p), buffer + buffer_offset, (s)); \
989 buffer_offset += (s); \
990 } while (0)
992 #if HAVE_LIBGCRYPT
993 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
994 void **ret_buffer, size_t *ret_buffer_len, int flags)
995 {
996 static c_complain_t complain_no_users = C_COMPLAIN_INIT_STATIC;
998 char *buffer;
999 size_t buffer_len;
1000 size_t buffer_offset;
1002 size_t username_len;
1003 char *secret;
1005 part_signature_sha256_t pss;
1006 uint16_t pss_head_length;
1007 char hash[sizeof (pss.hash)];
1009 gcry_md_hd_t hd;
1010 gcry_error_t err;
1011 unsigned char *hash_ptr;
1013 buffer = *ret_buffer;
1014 buffer_len = *ret_buffer_len;
1015 buffer_offset = 0;
1017 if (se->data.server.userdb == NULL)
1018 {
1019 c_complain (LOG_NOTICE, &complain_no_users,
1020 "network plugin: Received signed network packet but can't verify it "
1021 "because no user DB has been configured. Will accept it.");
1022 return (0);
1023 }
1025 /* Check if the buffer has enough data for this structure. */
1026 if (buffer_len <= PART_SIGNATURE_SHA256_SIZE)
1027 return (-ENOMEM);
1029 /* Read type and length header */
1030 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
1031 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
1032 pss_head_length = ntohs (pss.head.length);
1034 /* Check if the `pss_head_length' is within bounds. */
1035 if ((pss_head_length <= PART_SIGNATURE_SHA256_SIZE)
1036 || (pss_head_length > buffer_len))
1037 {
1038 ERROR ("network plugin: HMAC-SHA-256 with invalid length received.");
1039 return (-1);
1040 }
1042 /* Copy the hash. */
1043 BUFFER_READ (pss.hash, sizeof (pss.hash));
1045 /* Calculate username length (without null byte) and allocate memory */
1046 username_len = pss_head_length - PART_SIGNATURE_SHA256_SIZE;
1047 pss.username = malloc (username_len + 1);
1048 if (pss.username == NULL)
1049 return (-ENOMEM);
1051 /* Read the username */
1052 BUFFER_READ (pss.username, username_len);
1053 pss.username[username_len] = 0;
1055 assert (buffer_offset == pss_head_length);
1057 /* Query the password */
1058 secret = fbh_get (se->data.server.userdb, pss.username);
1059 if (secret == NULL)
1060 {
1061 ERROR ("network plugin: Unknown user: %s", pss.username);
1062 sfree (pss.username);
1063 return (-ENOENT);
1064 }
1066 /* Create a hash device and check the HMAC */
1067 hd = NULL;
1068 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
1069 if (err != 0)
1070 {
1071 ERROR ("network plugin: Creating HMAC-SHA-256 object failed: %s",
1072 gcry_strerror (err));
1073 sfree (secret);
1074 sfree (pss.username);
1075 return (-1);
1076 }
1078 err = gcry_md_setkey (hd, secret, strlen (secret));
1079 if (err != 0)
1080 {
1081 ERROR ("network plugin: gcry_md_setkey failed: %s", gcry_strerror (err));
1082 gcry_md_close (hd);
1083 sfree (secret);
1084 sfree (pss.username);
1085 return (-1);
1086 }
1088 gcry_md_write (hd,
1089 buffer + PART_SIGNATURE_SHA256_SIZE,
1090 buffer_len - PART_SIGNATURE_SHA256_SIZE);
1091 hash_ptr = gcry_md_read (hd, GCRY_MD_SHA256);
1092 if (hash_ptr == NULL)
1093 {
1094 ERROR ("network plugin: gcry_md_read failed.");
1095 gcry_md_close (hd);
1096 sfree (secret);
1097 sfree (pss.username);
1098 return (-1);
1099 }
1100 memcpy (hash, hash_ptr, sizeof (hash));
1102 /* Clean up */
1103 gcry_md_close (hd);
1104 hd = NULL;
1106 if (memcmp (pss.hash, hash, sizeof (pss.hash)) != 0)
1107 {
1108 WARNING ("network plugin: Verifying HMAC-SHA-256 signature failed: "
1109 "Hash mismatch.");
1110 }
1111 else
1112 {
1113 parse_packet (se, buffer + buffer_offset, buffer_len - buffer_offset,
1114 flags | PP_SIGNED, pss.username);
1115 }
1117 sfree (secret);
1118 sfree (pss.username);
1120 *ret_buffer = buffer + buffer_len;
1121 *ret_buffer_len = 0;
1123 return (0);
1124 } /* }}} int parse_part_sign_sha256 */
1125 /* #endif HAVE_LIBGCRYPT */
1127 #else /* if !HAVE_LIBGCRYPT */
1128 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
1129 void **ret_buffer, size_t *ret_buffer_size, int flags)
1130 {
1131 static int warning_has_been_printed = 0;
1133 char *buffer;
1134 size_t buffer_size;
1135 size_t buffer_offset;
1136 uint16_t part_len;
1138 part_signature_sha256_t pss;
1140 buffer = *ret_buffer;
1141 buffer_size = *ret_buffer_size;
1142 buffer_offset = 0;
1144 if (buffer_size <= PART_SIGNATURE_SHA256_SIZE)
1145 return (-ENOMEM);
1147 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
1148 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
1149 part_len = ntohs (pss.head.length);
1151 if ((part_len <= PART_SIGNATURE_SHA256_SIZE)
1152 || (part_len > buffer_size))
1153 return (-EINVAL);
1155 if (warning_has_been_printed == 0)
1156 {
1157 WARNING ("network plugin: Received signed packet, but the network "
1158 "plugin was not linked with libgcrypt, so I cannot "
1159 "verify the signature. The packet will be accepted.");
1160 warning_has_been_printed = 1;
1161 }
1163 parse_packet (se, buffer + part_len, buffer_size - part_len, flags,
1164 /* username = */ NULL);
1166 *ret_buffer = buffer + buffer_size;
1167 *ret_buffer_size = 0;
1169 return (0);
1170 } /* }}} int parse_part_sign_sha256 */
1171 #endif /* !HAVE_LIBGCRYPT */
1173 #if HAVE_LIBGCRYPT
1174 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1175 void **ret_buffer, size_t *ret_buffer_len,
1176 int flags)
1177 {
1178 char *buffer = *ret_buffer;
1179 size_t buffer_len = *ret_buffer_len;
1180 size_t payload_len;
1181 size_t part_size;
1182 size_t buffer_offset;
1183 uint16_t username_len;
1184 part_encryption_aes256_t pea;
1185 unsigned char hash[sizeof (pea.hash)];
1187 gcry_cipher_hd_t cypher;
1188 gcry_error_t err;
1190 /* Make sure at least the header if available. */
1191 if (buffer_len <= PART_ENCRYPTION_AES256_SIZE)
1192 {
1193 NOTICE ("network plugin: parse_part_encr_aes256: "
1194 "Discarding short packet.");
1195 return (-1);
1196 }
1198 buffer_offset = 0;
1200 /* Copy the unencrypted information into `pea'. */
1201 BUFFER_READ (&pea.head.type, sizeof (pea.head.type));
1202 BUFFER_READ (&pea.head.length, sizeof (pea.head.length));
1204 /* Check the `part size'. */
1205 part_size = ntohs (pea.head.length);
1206 if ((part_size <= PART_ENCRYPTION_AES256_SIZE)
1207 || (part_size > buffer_len))
1208 {
1209 NOTICE ("network plugin: parse_part_encr_aes256: "
1210 "Discarding part with invalid size.");
1211 return (-1);
1212 }
1214 /* Read the username */
1215 BUFFER_READ (&username_len, sizeof (username_len));
1216 username_len = ntohs (username_len);
1218 if ((username_len <= 0)
1219 || (username_len > (part_size - (PART_ENCRYPTION_AES256_SIZE + 1))))
1220 {
1221 NOTICE ("network plugin: parse_part_encr_aes256: "
1222 "Discarding part with invalid username length.");
1223 return (-1);
1224 }
1226 assert (username_len > 0);
1227 pea.username = malloc (username_len + 1);
1228 if (pea.username == NULL)
1229 return (-ENOMEM);
1230 BUFFER_READ (pea.username, username_len);
1231 pea.username[username_len] = 0;
1233 /* Last but not least, the initialization vector */
1234 BUFFER_READ (pea.iv, sizeof (pea.iv));
1236 /* Make sure we are at the right position */
1237 assert (buffer_offset == (username_len +
1238 PART_ENCRYPTION_AES256_SIZE - sizeof (pea.hash)));
1240 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
1241 pea.username);
1242 if (cypher == NULL)
1243 {
1244 sfree (pea.username);
1245 return (-1);
1246 }
1248 payload_len = part_size - (PART_ENCRYPTION_AES256_SIZE + username_len);
1249 assert (payload_len > 0);
1251 /* Decrypt the packet in-place */
1252 err = gcry_cipher_decrypt (cypher,
1253 buffer + buffer_offset,
1254 part_size - buffer_offset,
1255 /* in = */ NULL, /* in len = */ 0);
1256 if (err != 0)
1257 {
1258 sfree (pea.username);
1259 ERROR ("network plugin: gcry_cipher_decrypt returned: %s",
1260 gcry_strerror (err));
1261 return (-1);
1262 }
1264 /* Read the hash */
1265 BUFFER_READ (pea.hash, sizeof (pea.hash));
1267 /* Make sure we're at the right position - again */
1268 assert (buffer_offset == (username_len + PART_ENCRYPTION_AES256_SIZE));
1269 assert (buffer_offset == (part_size - payload_len));
1271 /* Check hash sum */
1272 memset (hash, 0, sizeof (hash));
1273 gcry_md_hash_buffer (GCRY_MD_SHA1, hash,
1274 buffer + buffer_offset, payload_len);
1275 if (memcmp (hash, pea.hash, sizeof (hash)) != 0)
1276 {
1277 sfree (pea.username);
1278 ERROR ("network plugin: Decryption failed: Checksum mismatch.");
1279 return (-1);
1280 }
1282 parse_packet (se, buffer + buffer_offset, payload_len,
1283 flags | PP_ENCRYPTED, pea.username);
1285 /* XXX: Free pea.username?!? */
1287 /* Update return values */
1288 *ret_buffer = buffer + part_size;
1289 *ret_buffer_len = buffer_len - part_size;
1291 sfree (pea.username);
1293 return (0);
1294 } /* }}} int parse_part_encr_aes256 */
1295 /* #endif HAVE_LIBGCRYPT */
1297 #else /* if !HAVE_LIBGCRYPT */
1298 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1299 void **ret_buffer, size_t *ret_buffer_size, int flags)
1300 {
1301 static int warning_has_been_printed = 0;
1303 char *buffer;
1304 size_t buffer_size;
1305 size_t buffer_offset;
1307 part_header_t ph;
1308 size_t ph_length;
1310 buffer = *ret_buffer;
1311 buffer_size = *ret_buffer_size;
1312 buffer_offset = 0;
1314 /* parse_packet assures this minimum size. */
1315 assert (buffer_size >= (sizeof (ph.type) + sizeof (ph.length)));
1317 BUFFER_READ (&ph.type, sizeof (ph.type));
1318 BUFFER_READ (&ph.length, sizeof (ph.length));
1319 ph_length = ntohs (ph.length);
1321 if ((ph_length <= PART_ENCRYPTION_AES256_SIZE)
1322 || (ph_length > buffer_size))
1323 {
1324 ERROR ("network plugin: AES-256 encrypted part "
1325 "with invalid length received.");
1326 return (-1);
1327 }
1329 if (warning_has_been_printed == 0)
1330 {
1331 WARNING ("network plugin: Received encrypted packet, but the network "
1332 "plugin was not linked with libgcrypt, so I cannot "
1333 "decrypt it. The part will be discarded.");
1334 warning_has_been_printed = 1;
1335 }
1337 *ret_buffer += ph_length;
1338 *ret_buffer_size -= ph_length;
1340 return (0);
1341 } /* }}} int parse_part_encr_aes256 */
1342 #endif /* !HAVE_LIBGCRYPT */
1344 #undef BUFFER_READ
1346 static int parse_packet (sockent_t *se, /* {{{ */
1347 void *buffer, size_t buffer_size, int flags,
1348 const char *username)
1349 {
1350 int status;
1352 value_list_t vl = VALUE_LIST_INIT;
1353 notification_t n;
1355 #if HAVE_LIBGCRYPT
1356 int packet_was_signed = (flags & PP_SIGNED);
1357 int packet_was_encrypted = (flags & PP_ENCRYPTED);
1358 int printed_ignore_warning = 0;
1359 #endif /* HAVE_LIBGCRYPT */
1362 memset (&vl, '\0', sizeof (vl));
1363 memset (&n, '\0', sizeof (n));
1364 status = 0;
1366 while ((status == 0) && (0 < buffer_size)
1367 && ((unsigned int) buffer_size > sizeof (part_header_t)))
1368 {
1369 uint16_t pkg_length;
1370 uint16_t pkg_type;
1372 memcpy ((void *) &pkg_type,
1373 (void *) buffer,
1374 sizeof (pkg_type));
1375 memcpy ((void *) &pkg_length,
1376 (void *) (buffer + sizeof (pkg_type)),
1377 sizeof (pkg_length));
1379 pkg_length = ntohs (pkg_length);
1380 pkg_type = ntohs (pkg_type);
1382 if (pkg_length > buffer_size)
1383 break;
1384 /* Ensure that this loop terminates eventually */
1385 if (pkg_length < (2 * sizeof (uint16_t)))
1386 break;
1388 if (pkg_type == TYPE_ENCR_AES256)
1389 {
1390 status = parse_part_encr_aes256 (se,
1391 &buffer, &buffer_size, flags);
1392 if (status != 0)
1393 {
1394 ERROR ("network plugin: Decrypting AES256 "
1395 "part failed "
1396 "with status %i.", status);
1397 break;
1398 }
1399 }
1400 #if HAVE_LIBGCRYPT
1401 else if ((se->data.server.security_level == SECURITY_LEVEL_ENCRYPT)
1402 && (packet_was_encrypted == 0))
1403 {
1404 if (printed_ignore_warning == 0)
1405 {
1406 INFO ("network plugin: Unencrypted packet or "
1407 "part has been ignored.");
1408 printed_ignore_warning = 1;
1409 }
1410 buffer = ((char *) buffer) + pkg_length;
1411 continue;
1412 }
1413 #endif /* HAVE_LIBGCRYPT */
1414 else if (pkg_type == TYPE_SIGN_SHA256)
1415 {
1416 status = parse_part_sign_sha256 (se,
1417 &buffer, &buffer_size, flags);
1418 if (status != 0)
1419 {
1420 ERROR ("network plugin: Verifying HMAC-SHA-256 "
1421 "signature failed "
1422 "with status %i.", status);
1423 break;
1424 }
1425 }
1426 #if HAVE_LIBGCRYPT
1427 else if ((se->data.server.security_level == SECURITY_LEVEL_SIGN)
1428 && (packet_was_encrypted == 0)
1429 && (packet_was_signed == 0))
1430 {
1431 if (printed_ignore_warning == 0)
1432 {
1433 INFO ("network plugin: Unsigned packet or "
1434 "part has been ignored.");
1435 printed_ignore_warning = 1;
1436 }
1437 buffer = ((char *) buffer) + pkg_length;
1438 continue;
1439 }
1440 #endif /* HAVE_LIBGCRYPT */
1441 else if (pkg_type == TYPE_VALUES)
1442 {
1443 status = parse_part_values (&buffer, &buffer_size,
1444 &vl.values, &vl.values_len);
1445 if (status != 0)
1446 break;
1448 network_dispatch_values (&vl, username);
1450 sfree (vl.values);
1451 }
1452 else if (pkg_type == TYPE_TIME)
1453 {
1454 uint64_t tmp = 0;
1455 status = parse_part_number (&buffer, &buffer_size,
1456 &tmp);
1457 if (status == 0)
1458 {
1459 vl.time = (time_t) tmp;
1460 n.time = (time_t) tmp;
1461 }
1462 }
1463 else if (pkg_type == TYPE_INTERVAL)
1464 {
1465 uint64_t tmp = 0;
1466 status = parse_part_number (&buffer, &buffer_size,
1467 &tmp);
1468 if (status == 0)
1469 vl.interval = (int) tmp;
1470 }
1471 else if (pkg_type == TYPE_HOST)
1472 {
1473 status = parse_part_string (&buffer, &buffer_size,
1474 vl.host, sizeof (vl.host));
1475 if (status == 0)
1476 sstrncpy (n.host, vl.host, sizeof (n.host));
1477 }
1478 else if (pkg_type == TYPE_PLUGIN)
1479 {
1480 status = parse_part_string (&buffer, &buffer_size,
1481 vl.plugin, sizeof (vl.plugin));
1482 if (status == 0)
1483 sstrncpy (n.plugin, vl.plugin,
1484 sizeof (n.plugin));
1485 }
1486 else if (pkg_type == TYPE_PLUGIN_INSTANCE)
1487 {
1488 status = parse_part_string (&buffer, &buffer_size,
1489 vl.plugin_instance,
1490 sizeof (vl.plugin_instance));
1491 if (status == 0)
1492 sstrncpy (n.plugin_instance,
1493 vl.plugin_instance,
1494 sizeof (n.plugin_instance));
1495 }
1496 else if (pkg_type == TYPE_TYPE)
1497 {
1498 status = parse_part_string (&buffer, &buffer_size,
1499 vl.type, sizeof (vl.type));
1500 if (status == 0)
1501 sstrncpy (n.type, vl.type, sizeof (n.type));
1502 }
1503 else if (pkg_type == TYPE_TYPE_INSTANCE)
1504 {
1505 status = parse_part_string (&buffer, &buffer_size,
1506 vl.type_instance,
1507 sizeof (vl.type_instance));
1508 if (status == 0)
1509 sstrncpy (n.type_instance, vl.type_instance,
1510 sizeof (n.type_instance));
1511 }
1512 else if (pkg_type == TYPE_MESSAGE)
1513 {
1514 status = parse_part_string (&buffer, &buffer_size,
1515 n.message, sizeof (n.message));
1517 if (status != 0)
1518 {
1519 /* do nothing */
1520 }
1521 else if ((n.severity != NOTIF_FAILURE)
1522 && (n.severity != NOTIF_WARNING)
1523 && (n.severity != NOTIF_OKAY))
1524 {
1525 INFO ("network plugin: "
1526 "Ignoring notification with "
1527 "unknown severity %i.",
1528 n.severity);
1529 }
1530 else if (n.time <= 0)
1531 {
1532 INFO ("network plugin: "
1533 "Ignoring notification with "
1534 "time == 0.");
1535 }
1536 else if (strlen (n.message) <= 0)
1537 {
1538 INFO ("network plugin: "
1539 "Ignoring notification with "
1540 "an empty message.");
1541 }
1542 else
1543 {
1544 network_dispatch_notification (&n);
1545 }
1546 }
1547 else if (pkg_type == TYPE_SEVERITY)
1548 {
1549 uint64_t tmp = 0;
1550 status = parse_part_number (&buffer, &buffer_size,
1551 &tmp);
1552 if (status == 0)
1553 n.severity = (int) tmp;
1554 }
1555 else
1556 {
1557 DEBUG ("network plugin: parse_packet: Unknown part"
1558 " type: 0x%04hx", pkg_type);
1559 buffer = ((char *) buffer) + pkg_length;
1560 }
1561 } /* while (buffer_size > sizeof (part_header_t)) */
1563 if (status == 0 && buffer_size > 0)
1564 WARNING ("network plugin: parse_packet: Received truncated "
1565 "packet, try increasing `MaxPacketSize'");
1567 return (status);
1568 } /* }}} int parse_packet */
1570 static void free_sockent_client (struct sockent_client *sec) /* {{{ */
1571 {
1572 if (sec->fd >= 0)
1573 {
1574 close (sec->fd);
1575 sec->fd = -1;
1576 }
1577 sfree (sec->addr);
1578 #if HAVE_LIBGCRYPT
1579 sfree (sec->username);
1580 sfree (sec->password);
1581 if (sec->cypher != NULL)
1582 gcry_cipher_close (sec->cypher);
1583 #endif
1584 } /* }}} void free_sockent_client */
1586 static void free_sockent_server (struct sockent_server *ses) /* {{{ */
1587 {
1588 size_t i;
1590 for (i = 0; i < ses->fd_num; i++)
1591 {
1592 if (ses->fd[i] >= 0)
1593 {
1594 close (ses->fd[i]);
1595 ses->fd[i] = -1;
1596 }
1597 }
1599 sfree (ses->fd);
1600 #if HAVE_LIBGCRYPT
1601 sfree (ses->auth_file);
1602 fbh_destroy (ses->userdb);
1603 if (ses->cypher != NULL)
1604 gcry_cipher_close (ses->cypher);
1605 #endif
1606 } /* }}} void free_sockent_server */
1608 static void sockent_destroy (sockent_t *se) /* {{{ */
1609 {
1610 sockent_t *next;
1612 DEBUG ("network plugin: sockent_destroy (se = %p);", (void *) se);
1614 while (se != NULL)
1615 {
1616 next = se->next;
1618 sfree (se->node);
1619 sfree (se->service);
1621 if (se->type == SOCKENT_TYPE_CLIENT)
1622 free_sockent_client (&se->data.client);
1623 else
1624 free_sockent_server (&se->data.server);
1626 sfree (se);
1627 se = next;
1628 }
1629 } /* }}} void sockent_destroy */
1631 /*
1632 * int network_set_ttl
1633 *
1634 * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
1635 * `IPV6_UNICAST_HOPS', depending on which option is applicable.
1636 *
1637 * The `struct addrinfo' is used to destinguish between unicast and multicast
1638 * sockets.
1639 */
1640 static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
1641 {
1642 DEBUG ("network plugin: network_set_ttl: network_config_ttl = %i;",
1643 network_config_ttl);
1645 assert (se->type == SOCKENT_TYPE_CLIENT);
1647 if ((network_config_ttl < 1) || (network_config_ttl > 255))
1648 return (-1);
1650 if (ai->ai_family == AF_INET)
1651 {
1652 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1653 int optname;
1655 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1656 optname = IP_MULTICAST_TTL;
1657 else
1658 optname = IP_TTL;
1660 if (setsockopt (se->data.client.fd, IPPROTO_IP, optname,
1661 &network_config_ttl,
1662 sizeof (network_config_ttl)) != 0)
1663 {
1664 char errbuf[1024];
1665 ERROR ("network plugin: setsockopt (ipv4-ttl): %s",
1666 sstrerror (errno, errbuf, sizeof (errbuf)));
1667 return (-1);
1668 }
1669 }
1670 else if (ai->ai_family == AF_INET6)
1671 {
1672 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1673 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1674 int optname;
1676 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1677 optname = IPV6_MULTICAST_HOPS;
1678 else
1679 optname = IPV6_UNICAST_HOPS;
1681 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, optname,
1682 &network_config_ttl,
1683 sizeof (network_config_ttl)) != 0)
1684 {
1685 char errbuf[1024];
1686 ERROR ("network plugin: setsockopt(ipv6-ttl): %s",
1687 sstrerror (errno, errbuf,
1688 sizeof (errbuf)));
1689 return (-1);
1690 }
1691 }
1693 return (0);
1694 } /* int network_set_ttl */
1696 static int network_set_interface (const sockent_t *se, const struct addrinfo *ai) /* {{{ */
1697 {
1698 DEBUG ("network plugin: network_set_interface: interface index = %i;",
1699 se->interface);
1701 assert (se->type == SOCKENT_TYPE_CLIENT);
1703 if (ai->ai_family == AF_INET)
1704 {
1705 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1707 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1708 {
1709 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1710 /* If possible, use the "ip_mreqn" structure which has
1711 * an "interface index" member. Using the interface
1712 * index is preferred here, because of its similarity
1713 * to the way IPv6 handles this. Unfortunately, it
1714 * appears not to be portable. */
1715 struct ip_mreqn mreq;
1717 memset (&mreq, 0, sizeof (mreq));
1718 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1719 mreq.imr_address.s_addr = ntohl (INADDR_ANY);
1720 mreq.imr_ifindex = se->interface;
1721 #else
1722 struct ip_mreq mreq;
1724 memset (&mreq, 0, sizeof (mreq));
1725 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1726 mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
1727 #endif
1729 if (setsockopt (se->data.client.fd, IPPROTO_IP, IP_MULTICAST_IF,
1730 &mreq, sizeof (mreq)) != 0)
1731 {
1732 char errbuf[1024];
1733 ERROR ("network plugin: setsockopt (ipv4-multicast-if): %s",
1734 sstrerror (errno, errbuf, sizeof (errbuf)));
1735 return (-1);
1736 }
1738 return (0);
1739 }
1740 }
1741 else if (ai->ai_family == AF_INET6)
1742 {
1743 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1745 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1746 {
1747 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
1748 &se->interface,
1749 sizeof (se->interface)) != 0)
1750 {
1751 char errbuf[1024];
1752 ERROR ("network plugin: setsockopt (ipv6-multicast-if): %s",
1753 sstrerror (errno, errbuf,
1754 sizeof (errbuf)));
1755 return (-1);
1756 }
1758 return (0);
1759 }
1760 }
1762 /* else: Not a multicast interface. */
1763 if (se->interface != 0)
1764 {
1765 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
1766 char interface_name[IFNAMSIZ];
1768 if (if_indextoname (se->interface, interface_name) == NULL)
1769 return (-1);
1771 DEBUG ("network plugin: Binding socket to interface %s", interface_name);
1773 if (setsockopt (se->data.client.fd, SOL_SOCKET, SO_BINDTODEVICE,
1774 interface_name,
1775 sizeof(interface_name)) == -1 )
1776 {
1777 char errbuf[1024];
1778 ERROR ("network plugin: setsockopt (bind-if): %s",
1779 sstrerror (errno, errbuf, sizeof (errbuf)));
1780 return (-1);
1781 }
1782 /* #endif HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1784 #else
1785 WARNING ("network plugin: Cannot set the interface on a unicast "
1786 "socket because "
1787 # if !defined(SO_BINDTODEVICE)
1788 "the \"SO_BINDTODEVICE\" socket option "
1789 # else
1790 "the \"if_indextoname\" function "
1791 # endif
1792 "is not available on your system.");
1793 #endif
1795 }
1797 return (0);
1798 } /* }}} network_set_interface */
1800 static int network_bind_socket (int fd, const struct addrinfo *ai, const int interface_idx)
1801 {
1802 #if KERNEL_SOLARIS
1803 char loop = 0;
1804 #else
1805 int loop = 0;
1806 #endif
1807 int yes = 1;
1809 /* allow multiple sockets to use the same PORT number */
1810 if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
1811 &yes, sizeof(yes)) == -1) {
1812 char errbuf[1024];
1813 ERROR ("network plugin: setsockopt (reuseaddr): %s",
1814 sstrerror (errno, errbuf, sizeof (errbuf)));
1815 return (-1);
1816 }
1818 DEBUG ("fd = %i; calling `bind'", fd);
1820 if (bind (fd, ai->ai_addr, ai->ai_addrlen) == -1)
1821 {
1822 char errbuf[1024];
1823 ERROR ("bind: %s",
1824 sstrerror (errno, errbuf, sizeof (errbuf)));
1825 return (-1);
1826 }
1828 if (ai->ai_family == AF_INET)
1829 {
1830 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1831 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1832 {
1833 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1834 struct ip_mreqn mreq;
1835 #else
1836 struct ip_mreq mreq;
1837 #endif
1839 DEBUG ("fd = %i; IPv4 multicast address found", fd);
1841 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1842 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1843 /* Set the interface using the interface index if
1844 * possible (available). Unfortunately, the struct
1845 * ip_mreqn is not portable. */
1846 mreq.imr_address.s_addr = ntohl (INADDR_ANY);
1847 mreq.imr_ifindex = interface_idx;
1848 #else
1849 mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
1850 #endif
1852 if (setsockopt (fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1853 &loop, sizeof (loop)) == -1)
1854 {
1855 char errbuf[1024];
1856 ERROR ("network plugin: setsockopt (multicast-loop): %s",
1857 sstrerror (errno, errbuf,
1858 sizeof (errbuf)));
1859 return (-1);
1860 }
1862 if (setsockopt (fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1863 &mreq, sizeof (mreq)) == -1)
1864 {
1865 char errbuf[1024];
1866 ERROR ("network plugin: setsockopt (add-membership): %s",
1867 sstrerror (errno, errbuf,
1868 sizeof (errbuf)));
1869 return (-1);
1870 }
1872 return (0);
1873 }
1874 }
1875 else if (ai->ai_family == AF_INET6)
1876 {
1877 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1878 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1879 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1880 {
1881 struct ipv6_mreq mreq;
1883 DEBUG ("fd = %i; IPv6 multicast address found", fd);
1885 memcpy (&mreq.ipv6mr_multiaddr,
1886 &addr->sin6_addr,
1887 sizeof (addr->sin6_addr));
1889 /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
1890 * ipv6mr_interface may be set to zeroes to
1891 * choose the default multicast interface or to
1892 * the index of a particular multicast-capable
1893 * interface if the host is multihomed.
1894 * Membership is associ-associated with a
1895 * single interface; programs running on
1896 * multihomed hosts may need to join the same
1897 * group on more than one interface.*/
1898 mreq.ipv6mr_interface = interface_idx;
1900 if (setsockopt (fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1901 &loop, sizeof (loop)) == -1)
1902 {
1903 char errbuf[1024];
1904 ERROR ("network plugin: setsockopt (ipv6-multicast-loop): %s",
1905 sstrerror (errno, errbuf,
1906 sizeof (errbuf)));
1907 return (-1);
1908 }
1910 if (setsockopt (fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
1911 &mreq, sizeof (mreq)) == -1)
1912 {
1913 char errbuf[1024];
1914 ERROR ("network plugin: setsockopt (ipv6-add-membership): %s",
1915 sstrerror (errno, errbuf,
1916 sizeof (errbuf)));
1917 return (-1);
1918 }
1920 return (0);
1921 }
1922 }
1924 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
1925 /* if a specific interface was set, bind the socket to it. But to avoid
1926 * possible problems with multicast routing, only do that for non-multicast
1927 * addresses */
1928 if (interface_idx != 0)
1929 {
1930 char interface_name[IFNAMSIZ];
1932 if (if_indextoname (interface_idx, interface_name) == NULL)
1933 return (-1);
1935 DEBUG ("fd = %i; Binding socket to interface %s", fd, interface_name);
1937 if (setsockopt (fd, SOL_SOCKET, SO_BINDTODEVICE,
1938 interface_name,
1939 sizeof(interface_name)) == -1 )
1940 {
1941 char errbuf[1024];
1942 ERROR ("network plugin: setsockopt (bind-if): %s",
1943 sstrerror (errno, errbuf, sizeof (errbuf)));
1944 return (-1);
1945 }
1946 }
1947 #endif /* HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1949 return (0);
1950 } /* int network_bind_socket */
1952 /* Initialize a sockent structure. `type' must be either `SOCKENT_TYPE_CLIENT'
1953 * or `SOCKENT_TYPE_SERVER' */
1954 static int sockent_init (sockent_t *se, int type) /* {{{ */
1955 {
1956 if (se == NULL)
1957 return (-1);
1959 memset (se, 0, sizeof (*se));
1961 se->type = SOCKENT_TYPE_CLIENT;
1962 se->node = NULL;
1963 se->service = NULL;
1964 se->interface = 0;
1965 se->next = NULL;
1967 if (type == SOCKENT_TYPE_SERVER)
1968 {
1969 se->type = SOCKENT_TYPE_SERVER;
1970 se->data.server.fd = NULL;
1971 #if HAVE_LIBGCRYPT
1972 se->data.server.security_level = SECURITY_LEVEL_NONE;
1973 se->data.server.auth_file = NULL;
1974 se->data.server.userdb = NULL;
1975 se->data.server.cypher = NULL;
1976 #endif
1977 }
1978 else
1979 {
1980 se->data.client.fd = -1;
1981 se->data.client.addr = NULL;
1982 #if HAVE_LIBGCRYPT
1983 se->data.client.security_level = SECURITY_LEVEL_NONE;
1984 se->data.client.username = NULL;
1985 se->data.client.password = NULL;
1986 se->data.client.cypher = NULL;
1987 #endif
1988 }
1990 return (0);
1991 } /* }}} int sockent_init */
1993 /* Open the file descriptors for a initialized sockent structure. */
1994 static int sockent_open (sockent_t *se) /* {{{ */
1995 {
1996 struct addrinfo ai_hints;
1997 struct addrinfo *ai_list, *ai_ptr;
1998 int ai_return;
2000 const char *node;
2001 const char *service;
2003 if (se == NULL)
2004 return (-1);
2006 /* Set up the security structures. */
2007 #if HAVE_LIBGCRYPT /* {{{ */
2008 if (se->type == SOCKENT_TYPE_CLIENT)
2009 {
2010 if (se->data.client.security_level > SECURITY_LEVEL_NONE)
2011 {
2012 if ((se->data.client.username == NULL)
2013 || (se->data.client.password == NULL))
2014 {
2015 ERROR ("network plugin: Client socket with "
2016 "security requested, but no "
2017 "credentials are configured.");
2018 return (-1);
2019 }
2020 gcry_md_hash_buffer (GCRY_MD_SHA256,
2021 se->data.client.password_hash,
2022 se->data.client.password,
2023 strlen (se->data.client.password));
2024 }
2025 }
2026 else /* (se->type == SOCKENT_TYPE_SERVER) */
2027 {
2028 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
2029 {
2030 if (se->data.server.auth_file == NULL)
2031 {
2032 ERROR ("network plugin: Server socket with "
2033 "security requested, but no "
2034 "password file is configured.");
2035 return (-1);
2036 }
2037 }
2038 if (se->data.server.auth_file != NULL)
2039 {
2040 se->data.server.userdb = fbh_create (se->data.server.auth_file);
2041 if (se->data.server.userdb == NULL)
2042 {
2043 ERROR ("network plugin: Reading password file "
2044 "`%s' failed.",
2045 se->data.server.auth_file);
2046 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
2047 return (-1);
2048 }
2049 }
2050 }
2051 #endif /* }}} HAVE_LIBGCRYPT */
2053 node = se->node;
2054 service = se->service;
2056 if (service == NULL)
2057 service = NET_DEFAULT_PORT;
2059 DEBUG ("network plugin: sockent_open: node = %s; service = %s;",
2060 node, service);
2062 memset (&ai_hints, 0, sizeof (ai_hints));
2063 ai_hints.ai_flags = 0;
2064 #ifdef AI_PASSIVE
2065 ai_hints.ai_flags |= AI_PASSIVE;
2066 #endif
2067 #ifdef AI_ADDRCONFIG
2068 ai_hints.ai_flags |= AI_ADDRCONFIG;
2069 #endif
2070 ai_hints.ai_family = AF_UNSPEC;
2071 ai_hints.ai_socktype = SOCK_DGRAM;
2072 ai_hints.ai_protocol = IPPROTO_UDP;
2074 ai_return = getaddrinfo (node, service, &ai_hints, &ai_list);
2075 if (ai_return != 0)
2076 {
2077 ERROR ("network plugin: getaddrinfo (%s, %s) failed: %s",
2078 (se->node == NULL) ? "(null)" : se->node,
2079 (se->service == NULL) ? "(null)" : se->service,
2080 gai_strerror (ai_return));
2081 return (-1);
2082 }
2084 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
2085 {
2086 int status;
2088 if (se->type == SOCKENT_TYPE_SERVER) /* {{{ */
2089 {
2090 int *tmp;
2092 tmp = realloc (se->data.server.fd,
2093 sizeof (*tmp) * (se->data.server.fd_num + 1));
2094 if (tmp == NULL)
2095 {
2096 ERROR ("network plugin: realloc failed.");
2097 continue;
2098 }
2099 se->data.server.fd = tmp;
2100 tmp = se->data.server.fd + se->data.server.fd_num;
2102 *tmp = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
2103 ai_ptr->ai_protocol);
2104 if (*tmp < 0)
2105 {
2106 char errbuf[1024];
2107 ERROR ("network plugin: socket(2) failed: %s",
2108 sstrerror (errno, errbuf,
2109 sizeof (errbuf)));
2110 continue;
2111 }
2113 status = network_bind_socket (*tmp, ai_ptr, se->interface);
2114 if (status != 0)
2115 {
2116 close (*tmp);
2117 *tmp = -1;
2118 continue;
2119 }
2121 se->data.server.fd_num++;
2122 continue;
2123 } /* }}} if (se->type == SOCKENT_TYPE_SERVER) */
2124 else /* if (se->type == SOCKENT_TYPE_CLIENT) {{{ */
2125 {
2126 se->data.client.fd = socket (ai_ptr->ai_family,
2127 ai_ptr->ai_socktype,
2128 ai_ptr->ai_protocol);
2129 if (se->data.client.fd < 0)
2130 {
2131 char errbuf[1024];
2132 ERROR ("network plugin: socket(2) failed: %s",
2133 sstrerror (errno, errbuf,
2134 sizeof (errbuf)));
2135 continue;
2136 }
2138 se->data.client.addr = malloc (sizeof (*se->data.client.addr));
2139 if (se->data.client.addr == NULL)
2140 {
2141 ERROR ("network plugin: malloc failed.");
2142 close (se->data.client.fd);
2143 se->data.client.fd = -1;
2144 continue;
2145 }
2147 memset (se->data.client.addr, 0, sizeof (*se->data.client.addr));
2148 assert (sizeof (*se->data.client.addr) >= ai_ptr->ai_addrlen);
2149 memcpy (se->data.client.addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
2150 se->data.client.addrlen = ai_ptr->ai_addrlen;
2152 network_set_ttl (se, ai_ptr);
2153 network_set_interface (se, ai_ptr);
2155 /* We don't open more than one write-socket per
2156 * node/service pair.. */
2157 break;
2158 } /* }}} if (se->type == SOCKENT_TYPE_CLIENT) */
2159 } /* for (ai_list) */
2161 freeaddrinfo (ai_list);
2163 /* Check if all went well. */
2164 if (se->type == SOCKENT_TYPE_SERVER)
2165 {
2166 if (se->data.server.fd_num <= 0)
2167 return (-1);
2168 }
2169 else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2170 {
2171 if (se->data.client.fd < 0)
2172 return (-1);
2173 }
2175 return (0);
2176 } /* }}} int sockent_open */
2178 /* Add a sockent to the global list of sockets */
2179 static int sockent_add (sockent_t *se) /* {{{ */
2180 {
2181 sockent_t *last_ptr;
2183 if (se == NULL)
2184 return (-1);
2186 if (se->type == SOCKENT_TYPE_SERVER)
2187 {
2188 struct pollfd *tmp;
2189 size_t i;
2191 tmp = realloc (listen_sockets_pollfd,
2192 sizeof (*tmp) * (listen_sockets_num
2193 + se->data.server.fd_num));
2194 if (tmp == NULL)
2195 {
2196 ERROR ("network plugin: realloc failed.");
2197 return (-1);
2198 }
2199 listen_sockets_pollfd = tmp;
2200 tmp = listen_sockets_pollfd + listen_sockets_num;
2202 for (i = 0; i < se->data.server.fd_num; i++)
2203 {
2204 memset (tmp + i, 0, sizeof (*tmp));
2205 tmp[i].fd = se->data.server.fd[i];
2206 tmp[i].events = POLLIN | POLLPRI;
2207 tmp[i].revents = 0;
2208 }
2210 listen_sockets_num += se->data.server.fd_num;
2212 if (listen_sockets == NULL)
2213 {
2214 listen_sockets = se;
2215 return (0);
2216 }
2217 last_ptr = listen_sockets;
2218 }
2219 else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2220 {
2221 if (sending_sockets == NULL)
2222 {
2223 sending_sockets = se;
2224 return (0);
2225 }
2226 last_ptr = sending_sockets;
2227 }
2229 while (last_ptr->next != NULL)
2230 last_ptr = last_ptr->next;
2231 last_ptr->next = se;
2233 return (0);
2234 } /* }}} int sockent_add */
2236 static void *dispatch_thread (void __attribute__((unused)) *arg) /* {{{ */
2237 {
2238 while (42)
2239 {
2240 receive_list_entry_t *ent;
2241 sockent_t *se;
2243 /* Lock and wait for more data to come in */
2244 pthread_mutex_lock (&receive_list_lock);
2245 while ((listen_loop == 0)
2246 && (receive_list_head == NULL))
2247 pthread_cond_wait (&receive_list_cond, &receive_list_lock);
2249 /* Remove the head entry and unlock */
2250 ent = receive_list_head;
2251 if (ent != NULL)
2252 receive_list_head = ent->next;
2253 receive_list_length--;
2254 pthread_mutex_unlock (&receive_list_lock);
2256 /* Check whether we are supposed to exit. We do NOT check `listen_loop'
2257 * because we dispatch all missing packets before shutting down. */
2258 if (ent == NULL)
2259 break;
2261 /* Look for the correct `sockent_t' */
2262 se = listen_sockets;
2263 while (se != NULL)
2264 {
2265 size_t i;
2267 for (i = 0; i < se->data.server.fd_num; i++)
2268 if (se->data.server.fd[i] == ent->fd)
2269 break;
2271 if (i < se->data.server.fd_num)
2272 break;
2274 se = se->next;
2275 }
2277 if (se == NULL)
2278 {
2279 ERROR ("network plugin: Got packet from FD %i, but can't "
2280 "find an appropriate socket entry.",
2281 ent->fd);
2282 sfree (ent->data);
2283 sfree (ent);
2284 continue;
2285 }
2287 parse_packet (se, ent->data, ent->data_len, /* flags = */ 0,
2288 /* username = */ NULL);
2289 sfree (ent->data);
2290 sfree (ent);
2291 } /* while (42) */
2293 return (NULL);
2294 } /* }}} void *dispatch_thread */
2296 static int network_receive (void) /* {{{ */
2297 {
2298 char buffer[network_config_packet_size];
2299 int buffer_len;
2301 int i;
2302 int status;
2304 receive_list_entry_t *private_list_head;
2305 receive_list_entry_t *private_list_tail;
2306 uint64_t private_list_length;
2308 assert (listen_sockets_num > 0);
2310 private_list_head = NULL;
2311 private_list_tail = NULL;
2312 private_list_length = 0;
2314 while (listen_loop == 0)
2315 {
2316 status = poll (listen_sockets_pollfd, listen_sockets_num, -1);
2318 if (status <= 0)
2319 {
2320 char errbuf[1024];
2321 if (errno == EINTR)
2322 continue;
2323 ERROR ("poll failed: %s",
2324 sstrerror (errno, errbuf, sizeof (errbuf)));
2325 return (-1);
2326 }
2328 for (i = 0; (i < listen_sockets_num) && (status > 0); i++)
2329 {
2330 receive_list_entry_t *ent;
2332 if ((listen_sockets_pollfd[i].revents
2333 & (POLLIN | POLLPRI)) == 0)
2334 continue;
2335 status--;
2337 buffer_len = recv (listen_sockets_pollfd[i].fd,
2338 buffer, sizeof (buffer),
2339 0 /* no flags */);
2340 if (buffer_len < 0)
2341 {
2342 char errbuf[1024];
2343 ERROR ("recv failed: %s",
2344 sstrerror (errno, errbuf,
2345 sizeof (errbuf)));
2346 return (-1);
2347 }
2349 stats_octets_rx += ((uint64_t) buffer_len);
2350 stats_packets_rx++;
2352 /* TODO: Possible performance enhancement: Do not free
2353 * these entries in the dispatch thread but put them in
2354 * another list, so we don't have to allocate more and
2355 * more of these structures. */
2356 ent = malloc (sizeof (receive_list_entry_t));
2357 if (ent == NULL)
2358 {
2359 ERROR ("network plugin: malloc failed.");
2360 return (-1);
2361 }
2362 memset (ent, 0, sizeof (receive_list_entry_t));
2363 ent->data = malloc (network_config_packet_size);
2364 if (ent->data == NULL)
2365 {
2366 sfree (ent);
2367 ERROR ("network plugin: malloc failed.");
2368 return (-1);
2369 }
2370 ent->fd = listen_sockets_pollfd[i].fd;
2371 ent->next = NULL;
2373 memcpy (ent->data, buffer, buffer_len);
2374 ent->data_len = buffer_len;
2376 if (private_list_head == NULL)
2377 private_list_head = ent;
2378 else
2379 private_list_tail->next = ent;
2380 private_list_tail = ent;
2381 private_list_length++;
2383 /* Do not block here. Blocking here has led to
2384 * insufficient performance in the past. */
2385 if (pthread_mutex_trylock (&receive_list_lock) == 0)
2386 {
2387 assert (((receive_list_head == NULL) && (receive_list_length == 0))
2388 || ((receive_list_head != NULL) && (receive_list_length != 0)));
2390 if (receive_list_head == NULL)
2391 receive_list_head = private_list_head;
2392 else
2393 receive_list_tail->next = private_list_head;
2394 receive_list_tail = private_list_tail;
2395 receive_list_length += private_list_length;
2397 pthread_cond_signal (&receive_list_cond);
2398 pthread_mutex_unlock (&receive_list_lock);
2400 private_list_head = NULL;
2401 private_list_tail = NULL;
2402 private_list_length = 0;
2403 }
2404 } /* for (listen_sockets_pollfd) */
2405 } /* while (listen_loop == 0) */
2407 /* Make sure everything is dispatched before exiting. */
2408 if (private_list_head != NULL)
2409 {
2410 pthread_mutex_lock (&receive_list_lock);
2412 if (receive_list_head == NULL)
2413 receive_list_head = private_list_head;
2414 else
2415 receive_list_tail->next = private_list_head;
2416 receive_list_tail = private_list_tail;
2417 receive_list_length += private_list_length;
2419 private_list_head = NULL;
2420 private_list_tail = NULL;
2421 private_list_length = 0;
2423 pthread_cond_signal (&receive_list_cond);
2424 pthread_mutex_unlock (&receive_list_lock);
2425 }
2427 return (0);
2428 } /* }}} int network_receive */
2430 static void *receive_thread (void __attribute__((unused)) *arg)
2431 {
2432 return (network_receive () ? (void *) 1 : (void *) 0);
2433 } /* void *receive_thread */
2435 static void network_init_buffer (void)
2436 {
2437 memset (send_buffer, 0, network_config_packet_size);
2438 send_buffer_ptr = send_buffer;
2439 send_buffer_fill = 0;
2441 memset (&send_buffer_vl, 0, sizeof (send_buffer_vl));
2442 } /* int network_init_buffer */
2444 static void networt_send_buffer_plain (const sockent_t *se, /* {{{ */
2445 const char *buffer, size_t buffer_size)
2446 {
2447 int status;
2449 while (42)
2450 {
2451 status = sendto (se->data.client.fd, buffer, buffer_size,
2452 /* flags = */ 0,
2453 (struct sockaddr *) se->data.client.addr,
2454 se->data.client.addrlen);
2455 if (status < 0)
2456 {
2457 char errbuf[1024];
2458 if (errno == EINTR)
2459 continue;
2460 ERROR ("network plugin: sendto failed: %s",
2461 sstrerror (errno, errbuf,
2462 sizeof (errbuf)));
2463 break;
2464 }
2466 break;
2467 } /* while (42) */
2468 } /* }}} void networt_send_buffer_plain */
2470 #if HAVE_LIBGCRYPT
2471 #define BUFFER_ADD(p,s) do { \
2472 memcpy (buffer + buffer_offset, (p), (s)); \
2473 buffer_offset += (s); \
2474 } while (0)
2476 static void networt_send_buffer_signed (const sockent_t *se, /* {{{ */
2477 const char *in_buffer, size_t in_buffer_size)
2478 {
2479 part_signature_sha256_t ps;
2480 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2481 size_t buffer_offset;
2482 size_t username_len;
2484 gcry_md_hd_t hd;
2485 gcry_error_t err;
2486 unsigned char *hash;
2488 hd = NULL;
2489 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
2490 if (err != 0)
2491 {
2492 ERROR ("network plugin: Creating HMAC object failed: %s",
2493 gcry_strerror (err));
2494 return;
2495 }
2497 err = gcry_md_setkey (hd, se->data.client.password,
2498 strlen (se->data.client.password));
2499 if (err != 0)
2500 {
2501 ERROR ("network plugin: gcry_md_setkey failed: %s",
2502 gcry_strerror (err));
2503 gcry_md_close (hd);
2504 return;
2505 }
2507 username_len = strlen (se->data.client.username);
2508 if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE))
2509 {
2510 ERROR ("network plugin: Username too long: %s",
2511 se->data.client.username);
2512 return;
2513 }
2515 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE,
2516 se->data.client.username, username_len);
2517 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE + username_len,
2518 in_buffer, in_buffer_size);
2520 /* Initialize the `ps' structure. */
2521 memset (&ps, 0, sizeof (ps));
2522 ps.head.type = htons (TYPE_SIGN_SHA256);
2523 ps.head.length = htons (PART_SIGNATURE_SHA256_SIZE + username_len);
2525 /* Calculate the hash value. */
2526 gcry_md_write (hd, buffer + PART_SIGNATURE_SHA256_SIZE,
2527 username_len + in_buffer_size);
2528 hash = gcry_md_read (hd, GCRY_MD_SHA256);
2529 if (hash == NULL)
2530 {
2531 ERROR ("network plugin: gcry_md_read failed.");
2532 gcry_md_close (hd);
2533 return;
2534 }
2535 memcpy (ps.hash, hash, sizeof (ps.hash));
2537 /* Add the header */
2538 buffer_offset = 0;
2540 BUFFER_ADD (&ps.head.type, sizeof (ps.head.type));
2541 BUFFER_ADD (&ps.head.length, sizeof (ps.head.length));
2542 BUFFER_ADD (ps.hash, sizeof (ps.hash));
2544 assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
2546 gcry_md_close (hd);
2547 hd = NULL;
2549 buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
2550 networt_send_buffer_plain (se, buffer, buffer_offset);
2551 } /* }}} void networt_send_buffer_signed */
2553 static void networt_send_buffer_encrypted (sockent_t *se, /* {{{ */
2554 const char *in_buffer, size_t in_buffer_size)
2555 {
2556 part_encryption_aes256_t pea;
2557 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2558 size_t buffer_size;
2559 size_t buffer_offset;
2560 size_t header_size;
2561 size_t username_len;
2562 gcry_error_t err;
2563 gcry_cipher_hd_t cypher;
2565 /* Initialize the header fields */
2566 memset (&pea, 0, sizeof (pea));
2567 pea.head.type = htons (TYPE_ENCR_AES256);
2569 pea.username = se->data.client.username;
2571 username_len = strlen (pea.username);
2572 if ((PART_ENCRYPTION_AES256_SIZE + username_len) > BUFF_SIG_SIZE)
2573 {
2574 ERROR ("network plugin: Username too long: %s", pea.username);
2575 return;
2576 }
2578 buffer_size = PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size;
2579 header_size = PART_ENCRYPTION_AES256_SIZE + username_len
2580 - sizeof (pea.hash);
2582 assert (buffer_size <= sizeof (buffer));
2583 DEBUG ("network plugin: networt_send_buffer_encrypted: "
2584 "buffer_size = %zu;", buffer_size);
2586 pea.head.length = htons ((uint16_t) (PART_ENCRYPTION_AES256_SIZE
2587 + username_len + in_buffer_size));
2588 pea.username_length = htons ((uint16_t) username_len);
2590 /* Chose a random initialization vector. */
2591 gcry_randomize ((void *) &pea.iv, sizeof (pea.iv), GCRY_STRONG_RANDOM);
2593 /* Create hash of the payload */
2594 gcry_md_hash_buffer (GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
2596 /* Initialize the buffer */
2597 buffer_offset = 0;
2598 memset (buffer, 0, sizeof (buffer));
2601 BUFFER_ADD (&pea.head.type, sizeof (pea.head.type));
2602 BUFFER_ADD (&pea.head.length, sizeof (pea.head.length));
2603 BUFFER_ADD (&pea.username_length, sizeof (pea.username_length));
2604 BUFFER_ADD (pea.username, username_len);
2605 BUFFER_ADD (pea.iv, sizeof (pea.iv));
2606 assert (buffer_offset == header_size);
2607 BUFFER_ADD (pea.hash, sizeof (pea.hash));
2608 BUFFER_ADD (in_buffer, in_buffer_size);
2610 assert (buffer_offset == buffer_size);
2612 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
2613 se->data.client.password);
2614 if (cypher == NULL)
2615 return;
2617 /* Encrypt the buffer in-place */
2618 err = gcry_cipher_encrypt (cypher,
2619 buffer + header_size,
2620 buffer_size - header_size,
2621 /* in = */ NULL, /* in len = */ 0);
2622 if (err != 0)
2623 {
2624 ERROR ("network plugin: gcry_cipher_encrypt returned: %s",
2625 gcry_strerror (err));
2626 return;
2627 }
2629 /* Send it out without further modifications */
2630 networt_send_buffer_plain (se, buffer, buffer_size);
2631 } /* }}} void networt_send_buffer_encrypted */
2632 #undef BUFFER_ADD
2633 #endif /* HAVE_LIBGCRYPT */
2635 static void network_send_buffer (char *buffer, size_t buffer_len) /* {{{ */
2636 {
2637 sockent_t *se;
2639 DEBUG ("network plugin: network_send_buffer: buffer_len = %zu", buffer_len);
2641 for (se = sending_sockets; se != NULL; se = se->next)
2642 {
2643 #if HAVE_LIBGCRYPT
2644 if (se->data.client.security_level == SECURITY_LEVEL_ENCRYPT)
2645 networt_send_buffer_encrypted (se, buffer, buffer_len);
2646 else if (se->data.client.security_level == SECURITY_LEVEL_SIGN)
2647 networt_send_buffer_signed (se, buffer, buffer_len);
2648 else /* if (se->data.client.security_level == SECURITY_LEVEL_NONE) */
2649 #endif /* HAVE_LIBGCRYPT */
2650 networt_send_buffer_plain (se, buffer, buffer_len);
2651 } /* for (sending_sockets) */
2652 } /* }}} void network_send_buffer */
2654 static int add_to_buffer (char *buffer, int buffer_size, /* {{{ */
2655 value_list_t *vl_def,
2656 const data_set_t *ds, const value_list_t *vl)
2657 {
2658 char *buffer_orig = buffer;
2660 if (strcmp (vl_def->host, vl->host) != 0)
2661 {
2662 if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
2663 vl->host, strlen (vl->host)) != 0)
2664 return (-1);
2665 sstrncpy (vl_def->host, vl->host, sizeof (vl_def->host));
2666 }
2668 if (vl_def->time != vl->time)
2669 {
2670 if (write_part_number (&buffer, &buffer_size, TYPE_TIME,
2671 (uint64_t) vl->time))
2672 return (-1);
2673 vl_def->time = vl->time;
2674 }
2676 if (vl_def->interval != vl->interval)
2677 {
2678 if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL,
2679 (uint64_t) vl->interval))
2680 return (-1);
2681 vl_def->interval = vl->interval;
2682 }
2684 if (strcmp (vl_def->plugin, vl->plugin) != 0)
2685 {
2686 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
2687 vl->plugin, strlen (vl->plugin)) != 0)
2688 return (-1);
2689 sstrncpy (vl_def->plugin, vl->plugin, sizeof (vl_def->plugin));
2690 }
2692 if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
2693 {
2694 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
2695 vl->plugin_instance,
2696 strlen (vl->plugin_instance)) != 0)
2697 return (-1);
2698 sstrncpy (vl_def->plugin_instance, vl->plugin_instance, sizeof (vl_def->plugin_instance));
2699 }
2701 if (strcmp (vl_def->type, vl->type) != 0)
2702 {
2703 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
2704 vl->type, strlen (vl->type)) != 0)
2705 return (-1);
2706 sstrncpy (vl_def->type, ds->type, sizeof (vl_def->type));
2707 }
2709 if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
2710 {
2711 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
2712 vl->type_instance,
2713 strlen (vl->type_instance)) != 0)
2714 return (-1);
2715 sstrncpy (vl_def->type_instance, vl->type_instance, sizeof (vl_def->type_instance));
2716 }
2718 if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
2719 return (-1);
2721 return (buffer - buffer_orig);
2722 } /* }}} int add_to_buffer */
2724 static void flush_buffer (void)
2725 {
2726 DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
2727 send_buffer_fill);
2729 network_send_buffer (send_buffer, (size_t) send_buffer_fill);
2731 stats_octets_tx += ((uint64_t) send_buffer_fill);
2732 stats_packets_tx++;
2734 network_init_buffer ();
2735 }
2737 static int network_write (const data_set_t *ds, const value_list_t *vl,
2738 user_data_t __attribute__((unused)) *user_data)
2739 {
2740 int status;
2742 if (!check_send_okay (vl))
2743 {
2744 #if COLLECT_DEBUG
2745 char name[6*DATA_MAX_NAME_LEN];
2746 FORMAT_VL (name, sizeof (name), vl);
2747 name[sizeof (name) - 1] = 0;
2748 DEBUG ("network plugin: network_write: "
2749 "NOT sending %s.", name);
2750 #endif
2751 /* Counter is not protected by another lock and may be reached by
2752 * multiple threads */
2753 pthread_mutex_lock (&stats_lock);
2754 stats_values_not_sent++;
2755 pthread_mutex_unlock (&stats_lock);
2756 return (0);
2757 }
2759 uc_meta_data_add_unsigned_int (vl,
2760 "network:time_sent", (uint64_t) vl->time);
2762 pthread_mutex_lock (&send_buffer_lock);
2764 status = add_to_buffer (send_buffer_ptr,
2765 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2766 &send_buffer_vl,
2767 ds, vl);
2768 if (status >= 0)
2769 {
2770 /* status == bytes added to the buffer */
2771 send_buffer_fill += status;
2772 send_buffer_ptr += status;
2774 stats_values_sent++;
2775 }
2776 else
2777 {
2778 flush_buffer ();
2780 status = add_to_buffer (send_buffer_ptr,
2781 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2782 &send_buffer_vl,
2783 ds, vl);
2785 if (status >= 0)
2786 {
2787 send_buffer_fill += status;
2788 send_buffer_ptr += status;
2790 stats_values_sent++;
2791 }
2792 }
2794 if (status < 0)
2795 {
2796 ERROR ("network plugin: Unable to append to the "
2797 "buffer for some weird reason");
2798 }
2799 else if ((network_config_packet_size - send_buffer_fill) < 15)
2800 {
2801 flush_buffer ();
2802 }
2804 pthread_mutex_unlock (&send_buffer_lock);
2806 return ((status < 0) ? -1 : 0);
2807 } /* int network_write */
2809 static int network_config_set_boolean (const oconfig_item_t *ci, /* {{{ */
2810 int *retval)
2811 {
2812 if ((ci->values_num != 1)
2813 || ((ci->values[0].type != OCONFIG_TYPE_BOOLEAN)
2814 && (ci->values[0].type != OCONFIG_TYPE_STRING)))
2815 {
2816 ERROR ("network plugin: The `%s' config option needs "
2817 "exactly one boolean argument.", ci->key);
2818 return (-1);
2819 }
2821 if (ci->values[0].type == OCONFIG_TYPE_BOOLEAN)
2822 {
2823 if (ci->values[0].value.boolean)
2824 *retval = 1;
2825 else
2826 *retval = 0;
2827 }
2828 else
2829 {
2830 char *str = ci->values[0].value.string;
2832 if (IS_TRUE (str))
2833 *retval = 1;
2834 else if (IS_FALSE (str))
2835 *retval = 0;
2836 else
2837 {
2838 ERROR ("network plugin: Cannot parse string value `%s' of the `%s' "
2839 "option as boolean value.",
2840 str, ci->key);
2841 return (-1);
2842 }
2843 }
2845 return (0);
2846 } /* }}} int network_config_set_boolean */
2848 static int network_config_set_ttl (const oconfig_item_t *ci) /* {{{ */
2849 {
2850 int tmp;
2851 if ((ci->values_num != 1)
2852 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2853 {
2854 WARNING ("network plugin: The `TimeToLive' config option needs exactly "
2855 "one numeric argument.");
2856 return (-1);
2857 }
2859 tmp = (int) ci->values[0].value.number;
2860 if ((tmp > 0) && (tmp <= 255))
2861 network_config_ttl = tmp;
2863 return (0);
2864 } /* }}} int network_config_set_ttl */
2866 static int network_config_set_interface (const oconfig_item_t *ci, /* {{{ */
2867 int *interface)
2868 {
2869 if ((ci->values_num != 1)
2870 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2871 {
2872 WARNING ("network plugin: The `Interface' config option needs exactly "
2873 "one string argument.");
2874 return (-1);
2875 }
2877 if (interface == NULL)
2878 return (-1);
2880 *interface = if_nametoindex (ci->values[0].value.string);
2882 return (0);
2883 } /* }}} int network_config_set_interface */
2885 static int network_config_set_buffer_size (const oconfig_item_t *ci) /* {{{ */
2886 {
2887 int tmp;
2888 if ((ci->values_num != 1)
2889 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2890 {
2891 WARNING ("network plugin: The `MaxPacketSize' config option needs exactly "
2892 "one numeric argument.");
2893 return (-1);
2894 }
2896 tmp = (int) ci->values[0].value.number;
2897 if ((tmp >= 1024) && (tmp <= 65535))
2898 network_config_packet_size = tmp;
2900 return (0);
2901 } /* }}} int network_config_set_buffer_size */
2903 #if HAVE_LIBGCRYPT
2904 static int network_config_set_string (const oconfig_item_t *ci, /* {{{ */
2905 char **ret_string)
2906 {
2907 char *tmp;
2908 if ((ci->values_num != 1)
2909 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2910 {
2911 WARNING ("network plugin: The `%s' config option needs exactly "
2912 "one string argument.", ci->key);
2913 return (-1);
2914 }
2916 tmp = strdup (ci->values[0].value.string);
2917 if (tmp == NULL)
2918 return (-1);
2920 sfree (*ret_string);
2921 *ret_string = tmp;
2923 return (0);
2924 } /* }}} int network_config_set_string */
2925 #endif /* HAVE_LIBGCRYPT */
2927 #if HAVE_LIBGCRYPT
2928 static int network_config_set_security_level (oconfig_item_t *ci, /* {{{ */
2929 int *retval)
2930 {
2931 char *str;
2932 if ((ci->values_num != 1)
2933 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2934 {
2935 WARNING ("network plugin: The `SecurityLevel' config option needs exactly "
2936 "one string argument.");
2937 return (-1);
2938 }
2940 str = ci->values[0].value.string;
2941 if (strcasecmp ("Encrypt", str) == 0)
2942 *retval = SECURITY_LEVEL_ENCRYPT;
2943 else if (strcasecmp ("Sign", str) == 0)
2944 *retval = SECURITY_LEVEL_SIGN;
2945 else if (strcasecmp ("None", str) == 0)
2946 *retval = SECURITY_LEVEL_NONE;
2947 else
2948 {
2949 WARNING ("network plugin: Unknown security level: %s.", str);
2950 return (-1);
2951 }
2953 return (0);
2954 } /* }}} int network_config_set_security_level */
2955 #endif /* HAVE_LIBGCRYPT */
2957 static int network_config_add_listen (const oconfig_item_t *ci) /* {{{ */
2958 {
2959 sockent_t *se;
2960 int status;
2961 int i;
2963 if ((ci->values_num < 1) || (ci->values_num > 2)
2964 || (ci->values[0].type != OCONFIG_TYPE_STRING)
2965 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
2966 {
2967 ERROR ("network plugin: The `%s' config option needs "
2968 "one or two string arguments.", ci->key);
2969 return (-1);
2970 }
2972 se = malloc (sizeof (*se));
2973 if (se == NULL)
2974 {
2975 ERROR ("network plugin: malloc failed.");
2976 return (-1);
2977 }
2978 sockent_init (se, SOCKENT_TYPE_SERVER);
2980 se->node = strdup (ci->values[0].value.string);
2981 if (ci->values_num >= 2)
2982 se->service = strdup (ci->values[1].value.string);
2984 for (i = 0; i < ci->children_num; i++)
2985 {
2986 oconfig_item_t *child = ci->children + i;
2988 #if HAVE_LIBGCRYPT
2989 if (strcasecmp ("AuthFile", child->key) == 0)
2990 network_config_set_string (child, &se->data.server.auth_file);
2991 else if (strcasecmp ("SecurityLevel", child->key) == 0)
2992 network_config_set_security_level (child,
2993 &se->data.server.security_level);
2994 else
2995 #endif /* HAVE_LIBGCRYPT */
2996 if (strcasecmp ("Interface", child->key) == 0)
2997 network_config_set_interface (child,
2998 &se->interface);
2999 else
3000 {
3001 WARNING ("network plugin: Option `%s' is not allowed here.",
3002 child->key);
3003 }
3004 }
3006 #if HAVE_LIBGCRYPT
3007 if ((se->data.server.security_level > SECURITY_LEVEL_NONE)
3008 && (se->data.server.auth_file == NULL))
3009 {
3010 ERROR ("network plugin: A security level higher than `none' was "
3011 "requested, but no AuthFile option was given. Cowardly refusing to "
3012 "open this socket!");
3013 sockent_destroy (se);
3014 return (-1);
3015 }
3016 #endif /* HAVE_LIBGCRYPT */
3018 status = sockent_open (se);
3019 if (status != 0)
3020 {
3021 ERROR ("network plugin: network_config_add_listen: sockent_open failed.");
3022 sockent_destroy (se);
3023 return (-1);
3024 }
3026 status = sockent_add (se);
3027 if (status != 0)
3028 {
3029 ERROR ("network plugin: network_config_add_listen: sockent_add failed.");
3030 sockent_destroy (se);
3031 return (-1);
3032 }
3034 return (0);
3035 } /* }}} int network_config_add_listen */
3037 static int network_config_add_server (const oconfig_item_t *ci) /* {{{ */
3038 {
3039 sockent_t *se;
3040 int status;
3041 int i;
3043 if ((ci->values_num < 1) || (ci->values_num > 2)
3044 || (ci->values[0].type != OCONFIG_TYPE_STRING)
3045 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
3046 {
3047 ERROR ("network plugin: The `%s' config option needs "
3048 "one or two string arguments.", ci->key);
3049 return (-1);
3050 }
3052 se = malloc (sizeof (*se));
3053 if (se == NULL)
3054 {
3055 ERROR ("network plugin: malloc failed.");
3056 return (-1);
3057 }
3058 sockent_init (se, SOCKENT_TYPE_CLIENT);
3060 se->node = strdup (ci->values[0].value.string);
3061 if (ci->values_num >= 2)
3062 se->service = strdup (ci->values[1].value.string);
3064 for (i = 0; i < ci->children_num; i++)
3065 {
3066 oconfig_item_t *child = ci->children + i;
3068 #if HAVE_LIBGCRYPT
3069 if (strcasecmp ("Username", child->key) == 0)
3070 network_config_set_string (child, &se->data.client.username);
3071 else if (strcasecmp ("Password", child->key) == 0)
3072 network_config_set_string (child, &se->data.client.password);
3073 else if (strcasecmp ("SecurityLevel", child->key) == 0)
3074 network_config_set_security_level (child,
3075 &se->data.client.security_level);
3076 else
3077 #endif /* HAVE_LIBGCRYPT */
3078 if (strcasecmp ("Interface", child->key) == 0)
3079 network_config_set_interface (child,
3080 &se->interface);
3081 else
3082 {
3083 WARNING ("network plugin: Option `%s' is not allowed here.",
3084 child->key);
3085 }
3086 }
3088 #if HAVE_LIBGCRYPT
3089 if ((se->data.client.security_level > SECURITY_LEVEL_NONE)
3090 && ((se->data.client.username == NULL)
3091 || (se->data.client.password == NULL)))
3092 {
3093 ERROR ("network plugin: A security level higher than `none' was "
3094 "requested, but no Username or Password option was given. "
3095 "Cowardly refusing to open this socket!");
3096 sockent_destroy (se);
3097 return (-1);
3098 }
3099 #endif /* HAVE_LIBGCRYPT */
3101 status = sockent_open (se);
3102 if (status != 0)
3103 {
3104 ERROR ("network plugin: network_config_add_server: sockent_open failed.");
3105 sockent_destroy (se);
3106 return (-1);
3107 }
3109 status = sockent_add (se);
3110 if (status != 0)
3111 {
3112 ERROR ("network plugin: network_config_add_server: sockent_add failed.");
3113 sockent_destroy (se);
3114 return (-1);
3115 }
3117 return (0);
3118 } /* }}} int network_config_add_server */
3120 static int network_config (oconfig_item_t *ci) /* {{{ */
3121 {
3122 int i;
3124 for (i = 0; i < ci->children_num; i++)
3125 {
3126 oconfig_item_t *child = ci->children + i;
3128 if (strcasecmp ("Listen", child->key) == 0)
3129 network_config_add_listen (child);
3130 else if (strcasecmp ("Server", child->key) == 0)
3131 network_config_add_server (child);
3132 else if (strcasecmp ("TimeToLive", child->key) == 0)
3133 network_config_set_ttl (child);
3134 else if (strcasecmp ("MaxPacketSize", child->key) == 0)
3135 network_config_set_buffer_size (child);
3136 else if (strcasecmp ("Forward", child->key) == 0)
3137 network_config_set_boolean (child, &network_config_forward);
3138 else if (strcasecmp ("ReportStats", child->key) == 0)
3139 network_config_set_boolean (child, &network_config_stats);
3140 else if (strcasecmp ("CacheFlush", child->key) == 0)
3141 /* no op for backwards compatibility only */;
3142 else
3143 {
3144 WARNING ("network plugin: Option `%s' is not allowed here.",
3145 child->key);
3146 }
3147 }
3149 return (0);
3150 } /* }}} int network_config */
3152 static int network_notification (const notification_t *n,
3153 user_data_t __attribute__((unused)) *user_data)
3154 {
3155 char buffer[network_config_packet_size];
3156 char *buffer_ptr = buffer;
3157 int buffer_free = sizeof (buffer);
3158 int status;
3160 if (!check_send_notify_okay (n))
3161 return (0);
3163 memset (buffer, 0, sizeof (buffer));
3165 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_TIME,
3166 (uint64_t) n->time);
3167 if (status != 0)
3168 return (-1);
3170 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_SEVERITY,
3171 (uint64_t) n->severity);
3172 if (status != 0)
3173 return (-1);
3175 if (strlen (n->host) > 0)
3176 {
3177 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_HOST,
3178 n->host, strlen (n->host));
3179 if (status != 0)
3180 return (-1);
3181 }
3183 if (strlen (n->plugin) > 0)
3184 {
3185 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_PLUGIN,
3186 n->plugin, strlen (n->plugin));
3187 if (status != 0)
3188 return (-1);
3189 }
3191 if (strlen (n->plugin_instance) > 0)
3192 {
3193 status = write_part_string (&buffer_ptr, &buffer_free,
3194 TYPE_PLUGIN_INSTANCE,
3195 n->plugin_instance, strlen (n->plugin_instance));
3196 if (status != 0)
3197 return (-1);
3198 }
3200 if (strlen (n->type) > 0)
3201 {
3202 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE,
3203 n->type, strlen (n->type));
3204 if (status != 0)
3205 return (-1);
3206 }
3208 if (strlen (n->type_instance) > 0)
3209 {
3210 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
3211 n->type_instance, strlen (n->type_instance));
3212 if (status != 0)
3213 return (-1);
3214 }
3216 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_MESSAGE,
3217 n->message, strlen (n->message));
3218 if (status != 0)
3219 return (-1);
3221 network_send_buffer (buffer, sizeof (buffer) - buffer_free);
3223 return (0);
3224 } /* int network_notification */
3226 static int network_shutdown (void)
3227 {
3228 listen_loop++;
3230 /* Kill the listening thread */
3231 if (receive_thread_running != 0)
3232 {
3233 INFO ("network plugin: Stopping receive thread.");
3234 pthread_kill (receive_thread_id, SIGTERM);
3235 pthread_join (receive_thread_id, NULL /* no return value */);
3236 memset (&receive_thread_id, 0, sizeof (receive_thread_id));
3237 receive_thread_running = 0;
3238 }
3240 /* Shutdown the dispatching thread */
3241 if (dispatch_thread_running != 0)
3242 {
3243 INFO ("network plugin: Stopping dispatch thread.");
3244 pthread_mutex_lock (&receive_list_lock);
3245 pthread_cond_broadcast (&receive_list_cond);
3246 pthread_mutex_unlock (&receive_list_lock);
3247 pthread_join (dispatch_thread_id, /* ret = */ NULL);
3248 dispatch_thread_running = 0;
3249 }
3251 sockent_destroy (listen_sockets);
3253 if (send_buffer_fill > 0)
3254 flush_buffer ();
3256 sfree (send_buffer);
3258 /* TODO: Close `sending_sockets' */
3260 plugin_unregister_config ("network");
3261 plugin_unregister_init ("network");
3262 plugin_unregister_write ("network");
3263 plugin_unregister_shutdown ("network");
3265 return (0);
3266 } /* int network_shutdown */
3268 static int network_stats_read (void) /* {{{ */
3269 {
3270 uint64_t copy_octets_rx;
3271 uint64_t copy_octets_tx;
3272 uint64_t copy_packets_rx;
3273 uint64_t copy_packets_tx;
3274 uint64_t copy_values_dispatched;
3275 uint64_t copy_values_not_dispatched;
3276 uint64_t copy_values_sent;
3277 uint64_t copy_values_not_sent;
3278 uint64_t copy_receive_list_length;
3279 value_list_t vl = VALUE_LIST_INIT;
3280 value_t values[2];
3282 copy_octets_rx = stats_octets_rx;
3283 copy_octets_tx = stats_octets_tx;
3284 copy_packets_rx = stats_packets_rx;
3285 copy_packets_tx = stats_packets_tx;
3286 copy_values_dispatched = stats_values_dispatched;
3287 copy_values_not_dispatched = stats_values_not_dispatched;
3288 copy_values_sent = stats_values_sent;
3289 copy_values_not_sent = stats_values_not_sent;
3290 copy_receive_list_length = receive_list_length;
3292 /* Initialize `vl' */
3293 vl.values = values;
3294 vl.values_len = 2;
3295 vl.time = 0;
3296 vl.interval = interval_g;
3297 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
3298 sstrncpy (vl.plugin, "network", sizeof (vl.plugin));
3300 /* Octets received / sent */
3301 vl.values[0].counter = (counter_t) copy_octets_rx;
3302 vl.values[1].counter = (counter_t) copy_octets_tx;
3303 sstrncpy (vl.type, "if_octets", sizeof (vl.type));
3304 plugin_dispatch_values_secure (&vl);
3306 /* Packets received / send */
3307 vl.values[0].counter = (counter_t) copy_packets_rx;
3308 vl.values[1].counter = (counter_t) copy_packets_tx;
3309 sstrncpy (vl.type, "if_packets", sizeof (vl.type));
3310 plugin_dispatch_values_secure (&vl);
3312 /* Values (not) dispatched and (not) send */
3313 sstrncpy (vl.type, "total_values", sizeof (vl.type));
3314 vl.values_len = 1;
3316 vl.values[0].derive = (derive_t) copy_values_dispatched;
3317 sstrncpy (vl.type_instance, "dispatch-accepted",
3318 sizeof (vl.type_instance));
3319 plugin_dispatch_values_secure (&vl);
3321 vl.values[0].derive = (derive_t) copy_values_not_dispatched;
3322 sstrncpy (vl.type_instance, "dispatch-rejected",
3323 sizeof (vl.type_instance));
3324 plugin_dispatch_values_secure (&vl);
3326 vl.values[0].derive = (derive_t) copy_values_sent;
3327 sstrncpy (vl.type_instance, "send-accepted",
3328 sizeof (vl.type_instance));
3329 plugin_dispatch_values_secure (&vl);
3331 vl.values[0].derive = (derive_t) copy_values_not_sent;
3332 sstrncpy (vl.type_instance, "send-rejected",
3333 sizeof (vl.type_instance));
3334 plugin_dispatch_values_secure (&vl);
3336 /* Receive queue length */
3337 vl.values[0].gauge = (gauge_t) copy_receive_list_length;
3338 sstrncpy (vl.type, "queue_length", sizeof (vl.type));
3339 vl.type_instance[0] = 0;
3340 plugin_dispatch_values_secure (&vl);
3342 return (0);
3343 } /* }}} int network_stats_read */
3345 static int network_init (void)
3346 {
3347 static _Bool have_init = false;
3349 /* Check if we were already initialized. If so, just return - there's
3350 * nothing more to do (for now, that is). */
3351 if (have_init)
3352 return (0);
3353 have_init = true;
3355 #if HAVE_LIBGCRYPT
3356 /* http://lists.gnupg.org/pipermail/gcrypt-devel/2003-August/000458.html
3357 * Because you can't know in a library whether another library has
3358 * already initialized the library
3359 */
3360 if (!gcry_control (GCRYCTL_ANY_INITIALIZATION_P))
3361 {
3362 gcry_check_version(NULL); /* before calling any other functions */
3363 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
3364 gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
3365 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
3366 }
3367 #endif
3369 if (network_config_stats != 0)
3370 plugin_register_read ("network", network_stats_read);
3372 plugin_register_shutdown ("network", network_shutdown);
3374 send_buffer = malloc (network_config_packet_size);
3375 if (send_buffer == NULL)
3376 {
3377 ERROR ("network plugin: malloc failed.");
3378 return (-1);
3379 }
3380 network_init_buffer ();
3382 /* setup socket(s) and so on */
3383 if (sending_sockets != NULL)
3384 {
3385 plugin_register_write ("network", network_write,
3386 /* user_data = */ NULL);
3387 plugin_register_notification ("network", network_notification,
3388 /* user_data = */ NULL);
3389 }
3391 /* If no threads need to be started, return here. */
3392 if ((listen_sockets_num == 0)
3393 || ((dispatch_thread_running != 0)
3394 && (receive_thread_running != 0)))
3395 return (0);
3397 if (dispatch_thread_running == 0)
3398 {
3399 int status;
3400 status = pthread_create (&dispatch_thread_id,
3401 NULL /* no attributes */,
3402 dispatch_thread,
3403 NULL /* no argument */);
3404 if (status != 0)
3405 {
3406 char errbuf[1024];
3407 ERROR ("network: pthread_create failed: %s",
3408 sstrerror (errno, errbuf,
3409 sizeof (errbuf)));
3410 }
3411 else
3412 {
3413 dispatch_thread_running = 1;
3414 }
3415 }
3417 if (receive_thread_running == 0)
3418 {
3419 int status;
3420 status = pthread_create (&receive_thread_id,
3421 NULL /* no attributes */,
3422 receive_thread,
3423 NULL /* no argument */);
3424 if (status != 0)
3425 {
3426 char errbuf[1024];
3427 ERROR ("network: pthread_create failed: %s",
3428 sstrerror (errno, errbuf,
3429 sizeof (errbuf)));
3430 }
3431 else
3432 {
3433 receive_thread_running = 1;
3434 }
3435 }
3437 return (0);
3438 } /* int network_init */
3440 /*
3441 * The flush option of the network plugin cannot flush individual identifiers.
3442 * All the values are added to a buffer and sent when the buffer is full, the
3443 * requested value may or may not be in there, it's not worth finding out. We
3444 * just send the buffer if `flush' is called - if the requested value was in
3445 * there, good. If not, well, then there is nothing to flush.. -octo
3446 */
3447 static int network_flush (int timeout,
3448 const char __attribute__((unused)) *identifier,
3449 user_data_t __attribute__((unused)) *user_data)
3450 {
3451 pthread_mutex_lock (&send_buffer_lock);
3453 if (send_buffer_fill > 0)
3454 flush_buffer ();
3456 pthread_mutex_unlock (&send_buffer_lock);
3458 return (0);
3459 } /* int network_flush */
3461 void module_register (void)
3462 {
3463 plugin_register_complex_config ("network", network_config);
3464 plugin_register_init ("network", network_init);
3465 plugin_register_flush ("network", network_flush,
3466 /* user_data = */ NULL);
3467 } /* void module_register */
3469 /* vim: set fdm=marker : */