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
57 #if HAVE_LIBGCRYPT
58 # include <gcrypt.h>
59 GCRY_THREAD_OPTION_PTHREAD_IMPL;
60 #endif
62 #ifndef IPV6_ADD_MEMBERSHIP
63 # ifdef IPV6_JOIN_GROUP
64 # define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
65 # else
66 # error "Neither IP_ADD_MEMBERSHIP nor IPV6_JOIN_GROUP is defined"
67 # endif
68 #endif /* !IP_ADD_MEMBERSHIP */
70 /*
71 * Maximum size required for encryption / signing:
72 *
73 * 42 bytes for the encryption header
74 * + 64 bytes for the username
75 * -----------
76 * = 106 bytes
77 */
78 #define BUFF_SIG_SIZE 106
80 /*
81 * Private data types
82 */
83 #define SECURITY_LEVEL_NONE 0
84 #if HAVE_LIBGCRYPT
85 # define SECURITY_LEVEL_SIGN 1
86 # define SECURITY_LEVEL_ENCRYPT 2
87 #endif
88 struct sockent_client
89 {
90 int fd;
91 struct sockaddr_storage *addr;
92 socklen_t addrlen;
93 #if HAVE_LIBGCRYPT
94 int security_level;
95 char *username;
96 char *password;
97 gcry_cipher_hd_t cypher;
98 unsigned char password_hash[32];
99 #endif
100 };
102 struct sockent_server
103 {
104 int *fd;
105 size_t fd_num;
106 #if HAVE_LIBGCRYPT
107 int security_level;
108 char *auth_file;
109 fbhash_t *userdb;
110 gcry_cipher_hd_t cypher;
111 #endif
112 };
114 typedef struct sockent
115 {
116 #define SOCKENT_TYPE_CLIENT 1
117 #define SOCKENT_TYPE_SERVER 2
118 int type;
120 char *node;
121 char *service;
123 union
124 {
125 struct sockent_client client;
126 struct sockent_server server;
127 } data;
129 struct sockent *next;
130 } sockent_t;
132 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
133 * 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
134 * +-------+-----------------------+-------------------------------+
135 * ! Ver. ! ! Length !
136 * +-------+-----------------------+-------------------------------+
137 */
138 struct part_header_s
139 {
140 uint16_t type;
141 uint16_t length;
142 };
143 typedef struct part_header_s part_header_t;
145 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
146 * 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
147 * +-------------------------------+-------------------------------+
148 * ! Type ! Length !
149 * +-------------------------------+-------------------------------+
150 * : (Length - 4) Bytes :
151 * +---------------------------------------------------------------+
152 */
153 struct part_string_s
154 {
155 part_header_t *head;
156 char *value;
157 };
158 typedef struct part_string_s part_string_t;
160 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
161 * 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
162 * +-------------------------------+-------------------------------+
163 * ! Type ! Length !
164 * +-------------------------------+-------------------------------+
165 * : (Length - 4 == 2 || 4 || 8) Bytes :
166 * +---------------------------------------------------------------+
167 */
168 struct part_number_s
169 {
170 part_header_t *head;
171 uint64_t *value;
172 };
173 typedef struct part_number_s part_number_t;
175 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
176 * 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
177 * +-------------------------------+-------------------------------+
178 * ! Type ! Length !
179 * +-------------------------------+---------------+---------------+
180 * ! Num of values ! Type0 ! Type1 !
181 * +-------------------------------+---------------+---------------+
182 * ! Value0 !
183 * ! !
184 * +---------------------------------------------------------------+
185 * ! Value1 !
186 * ! !
187 * +---------------------------------------------------------------+
188 */
189 struct part_values_s
190 {
191 part_header_t *head;
192 uint16_t *num_values;
193 uint8_t *values_types;
194 value_t *values;
195 };
196 typedef struct part_values_s part_values_t;
198 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
199 * 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
200 * +-------------------------------+-------------------------------+
201 * ! Type ! Length !
202 * +-------------------------------+-------------------------------+
203 * ! Hash (Bits 0 - 31) !
204 * : : :
205 * ! Hash (Bits 224 - 255) !
206 * +---------------------------------------------------------------+
207 */
208 /* Minimum size */
209 #define PART_SIGNATURE_SHA256_SIZE 36
210 struct part_signature_sha256_s
211 {
212 part_header_t head;
213 unsigned char hash[32];
214 char *username;
215 };
216 typedef struct part_signature_sha256_s part_signature_sha256_t;
218 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
219 * 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
220 * +-------------------------------+-------------------------------+
221 * ! Type ! Length !
222 * +-------------------------------+-------------------------------+
223 * ! Original length ! Padding (0 - 15 bytes) !
224 * +-------------------------------+-------------------------------+
225 * ! Hash (Bits 0 - 31) !
226 * : : :
227 * ! Hash (Bits 128 - 159) !
228 * +---------------------------------------------------------------+
229 */
230 /* Minimum size */
231 #define PART_ENCRYPTION_AES256_SIZE 42
232 struct part_encryption_aes256_s
233 {
234 part_header_t head;
235 uint16_t username_length;
236 char *username;
237 unsigned char iv[16];
238 /* <encrypted> */
239 unsigned char hash[20];
240 /* <payload /> */
241 /* </encrypted> */
242 };
243 typedef struct part_encryption_aes256_s part_encryption_aes256_t;
245 struct receive_list_entry_s
246 {
247 char *data;
248 int data_len;
249 int fd;
250 struct receive_list_entry_s *next;
251 };
252 typedef struct receive_list_entry_s receive_list_entry_t;
254 /*
255 * Private variables
256 */
257 static int network_config_ttl = 0;
258 static size_t network_config_packet_size = 1024;
259 static int network_config_forward = 0;
260 static int network_config_stats = 0;
262 static sockent_t *sending_sockets = NULL;
264 static receive_list_entry_t *receive_list_head = NULL;
265 static receive_list_entry_t *receive_list_tail = NULL;
266 static pthread_mutex_t receive_list_lock = PTHREAD_MUTEX_INITIALIZER;
267 static pthread_cond_t receive_list_cond = PTHREAD_COND_INITIALIZER;
268 static uint64_t receive_list_length = 0;
270 static sockent_t *listen_sockets = NULL;
271 static struct pollfd *listen_sockets_pollfd = NULL;
272 static size_t listen_sockets_num = 0;
274 /* The receive and dispatch threads will run as long as `listen_loop' is set to
275 * zero. */
276 static int listen_loop = 0;
277 static int receive_thread_running = 0;
278 static pthread_t receive_thread_id;
279 static int dispatch_thread_running = 0;
280 static pthread_t dispatch_thread_id;
282 /* Buffer in which to-be-sent network packets are constructed. */
283 static char *send_buffer;
284 static char *send_buffer_ptr;
285 static int send_buffer_fill;
286 static value_list_t send_buffer_vl = VALUE_LIST_STATIC;
287 static pthread_mutex_t send_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
289 /* XXX: These counters are incremented from one place only. The spot in which
290 * the values are incremented is either only reachable by one thread (the
291 * dispatch thread, for example) or locked by some lock (send_buffer_lock for
292 * example). Only if neither is true, the stats_lock is acquired. The counters
293 * are always read without holding a lock in the hope that writing 8 bytes to
294 * memory is an atomic operation. */
295 static uint64_t stats_octets_rx = 0;
296 static uint64_t stats_octets_tx = 0;
297 static uint64_t stats_packets_rx = 0;
298 static uint64_t stats_packets_tx = 0;
299 static uint64_t stats_values_dispatched = 0;
300 static uint64_t stats_values_not_dispatched = 0;
301 static uint64_t stats_values_sent = 0;
302 static uint64_t stats_values_not_sent = 0;
303 static pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER;
305 /*
306 * Private functions
307 */
308 static _Bool check_receive_okay (const value_list_t *vl) /* {{{ */
309 {
310 uint64_t time_sent = 0;
311 int status;
313 status = uc_meta_data_get_unsigned_int (vl,
314 "network:time_sent", &time_sent);
316 /* This is a value we already sent. Don't allow it to be received again in
317 * order to avoid looping. */
318 if ((status == 0) && (time_sent >= ((uint64_t) vl->time)))
319 return (false);
321 return (true);
322 } /* }}} _Bool check_receive_okay */
324 static _Bool check_send_okay (const value_list_t *vl) /* {{{ */
325 {
326 _Bool received = false;
327 int status;
329 if (network_config_forward != 0)
330 return (true);
332 if (vl->meta == NULL)
333 return (true);
335 status = meta_data_get_boolean (vl->meta, "network:received", &received);
336 if (status == -ENOENT)
337 return (true);
338 else if (status != 0)
339 {
340 ERROR ("network plugin: check_send_okay: meta_data_get_boolean failed "
341 "with status %i.", status);
342 return (true);
343 }
345 /* By default, only *send* value lists that were not *received* by the
346 * network plugin. */
347 return (!received);
348 } /* }}} _Bool check_send_okay */
350 static int network_dispatch_values (value_list_t *vl) /* {{{ */
351 {
352 int status;
354 if ((vl->time <= 0)
355 || (strlen (vl->host) <= 0)
356 || (strlen (vl->plugin) <= 0)
357 || (strlen (vl->type) <= 0))
358 return (-EINVAL);
360 if (!check_receive_okay (vl))
361 {
362 #if COLLECT_DEBUG
363 char name[6*DATA_MAX_NAME_LEN];
364 FORMAT_VL (name, sizeof (name), vl);
365 name[sizeof (name) - 1] = 0;
366 DEBUG ("network plugin: network_dispatch_values: "
367 "NOT dispatching %s.", name);
368 #endif
369 stats_values_not_dispatched++;
370 return (0);
371 }
373 assert (vl->meta == NULL);
375 vl->meta = meta_data_create ();
376 if (vl->meta == NULL)
377 {
378 ERROR ("network plugin: meta_data_create failed.");
379 return (-ENOMEM);
380 }
382 status = meta_data_add_boolean (vl->meta, "network:received", true);
383 if (status != 0)
384 {
385 ERROR ("network plugin: meta_data_add_boolean failed.");
386 meta_data_destroy (vl->meta);
387 vl->meta = NULL;
388 return (status);
389 }
391 plugin_dispatch_values (vl);
392 stats_values_dispatched++;
394 meta_data_destroy (vl->meta);
395 vl->meta = NULL;
397 return (0);
398 } /* }}} int network_dispatch_values */
400 #if HAVE_LIBGCRYPT
401 static gcry_cipher_hd_t network_get_aes256_cypher (sockent_t *se, /* {{{ */
402 const void *iv, size_t iv_size, const char *username)
403 {
404 gcry_error_t err;
405 gcry_cipher_hd_t *cyper_ptr;
406 unsigned char password_hash[32];
408 if (se->type == SOCKENT_TYPE_CLIENT)
409 {
410 cyper_ptr = &se->data.client.cypher;
411 memcpy (password_hash, se->data.client.password_hash,
412 sizeof (password_hash));
413 }
414 else
415 {
416 char *secret;
418 cyper_ptr = &se->data.server.cypher;
420 if (username == NULL)
421 return (NULL);
423 secret = fbh_get (se->data.server.userdb, username);
424 if (secret == NULL)
425 return (NULL);
427 gcry_md_hash_buffer (GCRY_MD_SHA256,
428 password_hash,
429 secret, strlen (secret));
431 sfree (secret);
432 }
434 if (*cyper_ptr == NULL)
435 {
436 err = gcry_cipher_open (cyper_ptr,
437 GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB, /* flags = */ 0);
438 if (err != 0)
439 {
440 ERROR ("network plugin: gcry_cipher_open returned: %s",
441 gcry_strerror (err));
442 *cyper_ptr = NULL;
443 return (NULL);
444 }
445 }
446 else
447 {
448 gcry_cipher_reset (*cyper_ptr);
449 }
450 assert (*cyper_ptr != NULL);
452 err = gcry_cipher_setkey (*cyper_ptr,
453 password_hash, sizeof (password_hash));
454 if (err != 0)
455 {
456 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
457 gcry_strerror (err));
458 gcry_cipher_close (*cyper_ptr);
459 *cyper_ptr = NULL;
460 return (NULL);
461 }
463 err = gcry_cipher_setiv (*cyper_ptr, iv, iv_size);
464 if (err != 0)
465 {
466 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
467 gcry_strerror (err));
468 gcry_cipher_close (*cyper_ptr);
469 *cyper_ptr = NULL;
470 return (NULL);
471 }
473 return (*cyper_ptr);
474 } /* }}} int network_get_aes256_cypher */
475 #endif /* HAVE_LIBGCRYPT */
477 static int write_part_values (char **ret_buffer, int *ret_buffer_len,
478 const data_set_t *ds, const value_list_t *vl)
479 {
480 char *packet_ptr;
481 int packet_len;
482 int num_values;
484 part_header_t pkg_ph;
485 uint16_t pkg_num_values;
486 uint8_t *pkg_values_types;
487 value_t *pkg_values;
489 int offset;
490 int i;
492 num_values = vl->values_len;
493 packet_len = sizeof (part_header_t) + sizeof (uint16_t)
494 + (num_values * sizeof (uint8_t))
495 + (num_values * sizeof (value_t));
497 if (*ret_buffer_len < packet_len)
498 return (-1);
500 pkg_values_types = (uint8_t *) malloc (num_values * sizeof (uint8_t));
501 if (pkg_values_types == NULL)
502 {
503 ERROR ("network plugin: write_part_values: malloc failed.");
504 return (-1);
505 }
507 pkg_values = (value_t *) malloc (num_values * sizeof (value_t));
508 if (pkg_values == NULL)
509 {
510 free (pkg_values_types);
511 ERROR ("network plugin: write_part_values: malloc failed.");
512 return (-1);
513 }
515 pkg_ph.type = htons (TYPE_VALUES);
516 pkg_ph.length = htons (packet_len);
518 pkg_num_values = htons ((uint16_t) vl->values_len);
520 for (i = 0; i < num_values; i++)
521 {
522 pkg_values_types[i] = (uint8_t) ds->ds[i].type;
523 switch (ds->ds[i].type)
524 {
525 case DS_TYPE_COUNTER:
526 pkg_values[i].counter = htonll (vl->values[i].counter);
527 break;
529 case DS_TYPE_GAUGE:
530 pkg_values[i].gauge = htond (vl->values[i].gauge);
531 break;
533 case DS_TYPE_DERIVE:
534 pkg_values[i].derive = htonll (vl->values[i].derive);
535 break;
537 case DS_TYPE_ABSOLUTE:
538 pkg_values[i].absolute = htonll (vl->values[i].absolute);
539 break;
541 default:
542 free (pkg_values_types);
543 free (pkg_values);
544 ERROR ("network plugin: write_part_values: "
545 "Unknown data source type: %i",
546 ds->ds[i].type);
547 return (-1);
548 } /* switch (ds->ds[i].type) */
549 } /* for (num_values) */
551 /*
552 * Use `memcpy' to write everything to the buffer, because the pointer
553 * may be unaligned and some architectures, such as SPARC, can't handle
554 * that.
555 */
556 packet_ptr = *ret_buffer;
557 offset = 0;
558 memcpy (packet_ptr + offset, &pkg_ph, sizeof (pkg_ph));
559 offset += sizeof (pkg_ph);
560 memcpy (packet_ptr + offset, &pkg_num_values, sizeof (pkg_num_values));
561 offset += sizeof (pkg_num_values);
562 memcpy (packet_ptr + offset, pkg_values_types, num_values * sizeof (uint8_t));
563 offset += num_values * sizeof (uint8_t);
564 memcpy (packet_ptr + offset, pkg_values, num_values * sizeof (value_t));
565 offset += num_values * sizeof (value_t);
567 assert (offset == packet_len);
569 *ret_buffer = packet_ptr + packet_len;
570 *ret_buffer_len -= packet_len;
572 free (pkg_values_types);
573 free (pkg_values);
575 return (0);
576 } /* int write_part_values */
578 static int write_part_number (char **ret_buffer, int *ret_buffer_len,
579 int type, uint64_t value)
580 {
581 char *packet_ptr;
582 int packet_len;
584 part_header_t pkg_head;
585 uint64_t pkg_value;
587 int offset;
589 packet_len = sizeof (pkg_head) + sizeof (pkg_value);
591 if (*ret_buffer_len < packet_len)
592 return (-1);
594 pkg_head.type = htons (type);
595 pkg_head.length = htons (packet_len);
596 pkg_value = htonll (value);
598 packet_ptr = *ret_buffer;
599 offset = 0;
600 memcpy (packet_ptr + offset, &pkg_head, sizeof (pkg_head));
601 offset += sizeof (pkg_head);
602 memcpy (packet_ptr + offset, &pkg_value, sizeof (pkg_value));
603 offset += sizeof (pkg_value);
605 assert (offset == packet_len);
607 *ret_buffer = packet_ptr + packet_len;
608 *ret_buffer_len -= packet_len;
610 return (0);
611 } /* int write_part_number */
613 static int write_part_string (char **ret_buffer, int *ret_buffer_len,
614 int type, const char *str, int str_len)
615 {
616 char *buffer;
617 int buffer_len;
619 uint16_t pkg_type;
620 uint16_t pkg_length;
622 int offset;
624 buffer_len = 2 * sizeof (uint16_t) + str_len + 1;
625 if (*ret_buffer_len < buffer_len)
626 return (-1);
628 pkg_type = htons (type);
629 pkg_length = htons (buffer_len);
631 buffer = *ret_buffer;
632 offset = 0;
633 memcpy (buffer + offset, (void *) &pkg_type, sizeof (pkg_type));
634 offset += sizeof (pkg_type);
635 memcpy (buffer + offset, (void *) &pkg_length, sizeof (pkg_length));
636 offset += sizeof (pkg_length);
637 memcpy (buffer + offset, str, str_len);
638 offset += str_len;
639 memset (buffer + offset, '\0', 1);
640 offset += 1;
642 assert (offset == buffer_len);
644 *ret_buffer = buffer + buffer_len;
645 *ret_buffer_len -= buffer_len;
647 return (0);
648 } /* int write_part_string */
650 static int parse_part_values (void **ret_buffer, size_t *ret_buffer_len,
651 value_t **ret_values, int *ret_num_values)
652 {
653 char *buffer = *ret_buffer;
654 size_t buffer_len = *ret_buffer_len;
656 uint16_t tmp16;
657 size_t exp_size;
658 int i;
660 uint16_t pkg_length;
661 uint16_t pkg_type;
662 uint16_t pkg_numval;
664 uint8_t *pkg_types;
665 value_t *pkg_values;
667 if (buffer_len < 15)
668 {
669 NOTICE ("network plugin: packet is too short: "
670 "buffer_len = %zu", buffer_len);
671 return (-1);
672 }
674 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
675 buffer += sizeof (tmp16);
676 pkg_type = ntohs (tmp16);
678 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
679 buffer += sizeof (tmp16);
680 pkg_length = ntohs (tmp16);
682 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
683 buffer += sizeof (tmp16);
684 pkg_numval = ntohs (tmp16);
686 assert (pkg_type == TYPE_VALUES);
688 exp_size = 3 * sizeof (uint16_t)
689 + pkg_numval * (sizeof (uint8_t) + sizeof (value_t));
690 if ((buffer_len < 0) || (buffer_len < exp_size))
691 {
692 WARNING ("network plugin: parse_part_values: "
693 "Packet too short: "
694 "Chunk of size %zu expected, "
695 "but buffer has only %zu bytes left.",
696 exp_size, buffer_len);
697 return (-1);
698 }
700 if (pkg_length != exp_size)
701 {
702 WARNING ("network plugin: parse_part_values: "
703 "Length and number of values "
704 "in the packet don't match.");
705 return (-1);
706 }
708 pkg_types = (uint8_t *) malloc (pkg_numval * sizeof (uint8_t));
709 pkg_values = (value_t *) malloc (pkg_numval * sizeof (value_t));
710 if ((pkg_types == NULL) || (pkg_values == NULL))
711 {
712 sfree (pkg_types);
713 sfree (pkg_values);
714 ERROR ("network plugin: parse_part_values: malloc failed.");
715 return (-1);
716 }
718 memcpy ((void *) pkg_types, (void *) buffer, pkg_numval * sizeof (uint8_t));
719 buffer += pkg_numval * sizeof (uint8_t);
720 memcpy ((void *) pkg_values, (void *) buffer, pkg_numval * sizeof (value_t));
721 buffer += pkg_numval * sizeof (value_t);
723 for (i = 0; i < pkg_numval; i++)
724 {
725 switch (pkg_types[i])
726 {
727 case DS_TYPE_COUNTER:
728 pkg_values[i].counter = (counter_t) ntohll (pkg_values[i].counter);
729 break;
731 case DS_TYPE_GAUGE:
732 pkg_values[i].gauge = (gauge_t) ntohd (pkg_values[i].gauge);
733 break;
735 case DS_TYPE_DERIVE:
736 pkg_values[i].derive = (derive_t) ntohll (pkg_values[i].derive);
737 break;
739 case DS_TYPE_ABSOLUTE:
740 pkg_values[i].absolute = (absolute_t) ntohll (pkg_values[i].absolute);
741 break;
743 default:
744 NOTICE ("network plugin: parse_part_values: "
745 "Don't know how to handle data source type %"PRIu8,
746 pkg_types[i]);
747 sfree (pkg_types);
748 sfree (pkg_values);
749 return (-1);
750 } /* switch (pkg_types[i]) */
751 }
753 *ret_buffer = buffer;
754 *ret_buffer_len = buffer_len - pkg_length;
755 *ret_num_values = pkg_numval;
756 *ret_values = pkg_values;
758 sfree (pkg_types);
760 return (0);
761 } /* int parse_part_values */
763 static int parse_part_number (void **ret_buffer, size_t *ret_buffer_len,
764 uint64_t *value)
765 {
766 char *buffer = *ret_buffer;
767 size_t buffer_len = *ret_buffer_len;
769 uint16_t tmp16;
770 uint64_t tmp64;
771 size_t exp_size = 2 * sizeof (uint16_t) + sizeof (uint64_t);
773 uint16_t pkg_length;
774 uint16_t pkg_type;
776 if ((buffer_len < 0) || ((size_t) buffer_len < exp_size))
777 {
778 WARNING ("network plugin: parse_part_number: "
779 "Packet too short: "
780 "Chunk of size %zu expected, "
781 "but buffer has only %zu bytes left.",
782 exp_size, buffer_len);
783 return (-1);
784 }
786 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
787 buffer += sizeof (tmp16);
788 pkg_type = ntohs (tmp16);
790 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
791 buffer += sizeof (tmp16);
792 pkg_length = ntohs (tmp16);
794 memcpy ((void *) &tmp64, buffer, sizeof (tmp64));
795 buffer += sizeof (tmp64);
796 *value = ntohll (tmp64);
798 *ret_buffer = buffer;
799 *ret_buffer_len = buffer_len - pkg_length;
801 return (0);
802 } /* int parse_part_number */
804 static int parse_part_string (void **ret_buffer, size_t *ret_buffer_len,
805 char *output, int output_len)
806 {
807 char *buffer = *ret_buffer;
808 size_t buffer_len = *ret_buffer_len;
810 uint16_t tmp16;
811 size_t header_size = 2 * sizeof (uint16_t);
813 uint16_t pkg_length;
814 uint16_t pkg_type;
816 if ((buffer_len < 0) || (buffer_len < header_size))
817 {
818 WARNING ("network plugin: parse_part_string: "
819 "Packet too short: "
820 "Chunk of at least size %zu expected, "
821 "but buffer has only %zu bytes left.",
822 header_size, buffer_len);
823 return (-1);
824 }
826 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
827 buffer += sizeof (tmp16);
828 pkg_type = ntohs (tmp16);
830 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
831 buffer += sizeof (tmp16);
832 pkg_length = ntohs (tmp16);
834 /* Check that packet fits in the input buffer */
835 if (pkg_length > buffer_len)
836 {
837 WARNING ("network plugin: parse_part_string: "
838 "Packet too big: "
839 "Chunk of size %"PRIu16" received, "
840 "but buffer has only %zu bytes left.",
841 pkg_length, buffer_len);
842 return (-1);
843 }
845 /* Check that pkg_length is in the valid range */
846 if (pkg_length <= header_size)
847 {
848 WARNING ("network plugin: parse_part_string: "
849 "Packet too short: "
850 "Header claims this packet is only %hu "
851 "bytes long.", pkg_length);
852 return (-1);
853 }
855 /* Check that the package data fits into the output buffer.
856 * The previous if-statement ensures that:
857 * `pkg_length > header_size' */
858 if ((output_len < 0)
859 || ((size_t) output_len < ((size_t) pkg_length - header_size)))
860 {
861 WARNING ("network plugin: parse_part_string: "
862 "Output buffer too small.");
863 return (-1);
864 }
866 /* All sanity checks successfull, let's copy the data over */
867 output_len = pkg_length - header_size;
868 memcpy ((void *) output, (void *) buffer, output_len);
869 buffer += output_len;
871 /* For some very weird reason '\0' doesn't do the trick on SPARC in
872 * this statement. */
873 if (output[output_len - 1] != 0)
874 {
875 WARNING ("network plugin: parse_part_string: "
876 "Received string does not end "
877 "with a NULL-byte.");
878 return (-1);
879 }
881 *ret_buffer = buffer;
882 *ret_buffer_len = buffer_len - pkg_length;
884 return (0);
885 } /* int parse_part_string */
887 /* Forward declaration: parse_part_sign_sha256 and parse_part_encr_aes256 call
888 * parse_packet and vice versa. */
889 #define PP_SIGNED 0x01
890 #define PP_ENCRYPTED 0x02
891 static int parse_packet (sockent_t *se,
892 void *buffer, size_t buffer_size, int flags);
894 #define BUFFER_READ(p,s) do { \
895 memcpy ((p), buffer + buffer_offset, (s)); \
896 buffer_offset += (s); \
897 } while (0)
899 #if HAVE_LIBGCRYPT
900 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
901 void **ret_buffer, size_t *ret_buffer_len, int flags)
902 {
903 static c_complain_t complain_no_users = C_COMPLAIN_INIT_STATIC;
905 char *buffer;
906 size_t buffer_len;
907 size_t buffer_offset;
909 size_t username_len;
910 char *secret;
912 part_signature_sha256_t pss;
913 uint16_t pss_head_length;
914 char hash[sizeof (pss.hash)];
916 gcry_md_hd_t hd;
917 gcry_error_t err;
918 unsigned char *hash_ptr;
920 buffer = *ret_buffer;
921 buffer_len = *ret_buffer_len;
922 buffer_offset = 0;
924 if (se->data.server.userdb == NULL)
925 {
926 c_complain (LOG_NOTICE, &complain_no_users,
927 "network plugin: Received signed network packet but can't verify it "
928 "because no user DB has been configured. Will accept it.");
929 return (0);
930 }
932 /* Check if the buffer has enough data for this structure. */
933 if (buffer_len <= PART_SIGNATURE_SHA256_SIZE)
934 return (-ENOMEM);
936 /* Read type and length header */
937 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
938 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
939 pss_head_length = ntohs (pss.head.length);
941 /* Check if the `pss_head_length' is within bounds. */
942 if ((pss_head_length <= PART_SIGNATURE_SHA256_SIZE)
943 || (pss_head_length > buffer_len))
944 {
945 ERROR ("network plugin: HMAC-SHA-256 with invalid length received.");
946 return (-1);
947 }
949 /* Copy the hash. */
950 BUFFER_READ (pss.hash, sizeof (pss.hash));
952 /* Calculate username length (without null byte) and allocate memory */
953 username_len = pss_head_length - PART_SIGNATURE_SHA256_SIZE;
954 pss.username = malloc (username_len + 1);
955 if (pss.username == NULL)
956 return (-ENOMEM);
958 /* Read the username */
959 BUFFER_READ (pss.username, username_len);
960 pss.username[username_len] = 0;
962 assert (buffer_offset == pss_head_length);
964 /* Query the password */
965 secret = fbh_get (se->data.server.userdb, pss.username);
966 if (secret == NULL)
967 {
968 ERROR ("network plugin: Unknown user: %s", pss.username);
969 sfree (pss.username);
970 return (-ENOENT);
971 }
973 /* Create a hash device and check the HMAC */
974 hd = NULL;
975 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
976 if (err != 0)
977 {
978 ERROR ("network plugin: Creating HMAC-SHA-256 object failed: %s",
979 gcry_strerror (err));
980 sfree (secret);
981 sfree (pss.username);
982 return (-1);
983 }
985 err = gcry_md_setkey (hd, secret, strlen (secret));
986 if (err != 0)
987 {
988 ERROR ("network plugin: gcry_md_setkey failed: %s", gcry_strerror (err));
989 gcry_md_close (hd);
990 return (-1);
991 }
993 gcry_md_write (hd,
994 buffer + PART_SIGNATURE_SHA256_SIZE,
995 buffer_len - PART_SIGNATURE_SHA256_SIZE);
996 hash_ptr = gcry_md_read (hd, GCRY_MD_SHA256);
997 if (hash_ptr == NULL)
998 {
999 ERROR ("network plugin: gcry_md_read failed.");
1000 gcry_md_close (hd);
1001 sfree (secret);
1002 sfree (pss.username);
1003 return (-1);
1004 }
1005 memcpy (hash, hash_ptr, sizeof (hash));
1007 /* Clean up */
1008 gcry_md_close (hd);
1009 hd = NULL;
1011 sfree (secret);
1012 sfree (pss.username);
1014 if (memcmp (pss.hash, hash, sizeof (pss.hash)) != 0)
1015 {
1016 WARNING ("network plugin: Verifying HMAC-SHA-256 signature failed: "
1017 "Hash mismatch.");
1018 }
1019 else
1020 {
1021 parse_packet (se, buffer + buffer_offset, buffer_len - buffer_offset,
1022 flags | PP_SIGNED);
1023 }
1025 *ret_buffer = buffer + buffer_len;
1026 *ret_buffer_len = 0;
1028 return (0);
1029 } /* }}} int parse_part_sign_sha256 */
1030 /* #endif HAVE_LIBGCRYPT */
1032 #else /* if !HAVE_LIBGCRYPT */
1033 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
1034 void **ret_buffer, size_t *ret_buffer_size, int flags)
1035 {
1036 static int warning_has_been_printed = 0;
1038 char *buffer;
1039 size_t buffer_size;
1040 size_t buffer_offset;
1041 uint16_t part_len;
1043 part_signature_sha256_t pss;
1045 buffer = *ret_buffer;
1046 buffer_size = *ret_buffer_size;
1047 buffer_offset = 0;
1049 if (buffer_size <= PART_SIGNATURE_SHA256_SIZE)
1050 return (-ENOMEM);
1052 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
1053 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
1054 part_len = ntohs (pss.head.length);
1056 if ((part_len <= PART_SIGNATURE_SHA256_SIZE)
1057 || (part_len > buffer_size))
1058 return (-EINVAL);
1060 if (warning_has_been_printed == 0)
1061 {
1062 WARNING ("network plugin: Received signed packet, but the network "
1063 "plugin was not linked with libgcrypt, so I cannot "
1064 "verify the signature. The packet will be accepted.");
1065 warning_has_been_printed = 1;
1066 }
1068 parse_packet (se, buffer + part_len, buffer_size - part_len, flags);
1070 *ret_buffer = buffer + buffer_size;
1071 *ret_buffer_size = 0;
1073 return (0);
1074 } /* }}} int parse_part_sign_sha256 */
1075 #endif /* !HAVE_LIBGCRYPT */
1077 #if HAVE_LIBGCRYPT
1078 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1079 void **ret_buffer, size_t *ret_buffer_len,
1080 int flags)
1081 {
1082 char *buffer = *ret_buffer;
1083 size_t buffer_len = *ret_buffer_len;
1084 size_t payload_len;
1085 size_t part_size;
1086 size_t buffer_offset;
1087 uint16_t username_len;
1088 part_encryption_aes256_t pea;
1089 unsigned char hash[sizeof (pea.hash)];
1091 gcry_cipher_hd_t cypher;
1092 gcry_error_t err;
1094 /* Make sure at least the header if available. */
1095 if (buffer_len <= PART_ENCRYPTION_AES256_SIZE)
1096 {
1097 NOTICE ("network plugin: parse_part_encr_aes256: "
1098 "Discarding short packet.");
1099 return (-1);
1100 }
1102 buffer_offset = 0;
1104 /* Copy the unencrypted information into `pea'. */
1105 BUFFER_READ (&pea.head.type, sizeof (pea.head.type));
1106 BUFFER_READ (&pea.head.length, sizeof (pea.head.length));
1108 /* Check the `part size'. */
1109 part_size = ntohs (pea.head.length);
1110 if ((part_size <= PART_ENCRYPTION_AES256_SIZE)
1111 || (part_size > buffer_len))
1112 {
1113 NOTICE ("network plugin: parse_part_encr_aes256: "
1114 "Discarding part with invalid size.");
1115 return (-1);
1116 }
1118 /* Read the username */
1119 BUFFER_READ (&username_len, sizeof (username_len));
1120 username_len = ntohs (username_len);
1122 if ((username_len <= 0)
1123 || (username_len > (part_size - (PART_ENCRYPTION_AES256_SIZE + 1))))
1124 {
1125 NOTICE ("network plugin: parse_part_encr_aes256: "
1126 "Discarding part with invalid username length.");
1127 return (-1);
1128 }
1130 assert (username_len > 0);
1131 pea.username = malloc (username_len + 1);
1132 if (pea.username == NULL)
1133 return (-ENOMEM);
1134 BUFFER_READ (pea.username, username_len);
1135 pea.username[username_len] = 0;
1137 /* Last but not least, the initialization vector */
1138 BUFFER_READ (pea.iv, sizeof (pea.iv));
1140 /* Make sure we are at the right position */
1141 assert (buffer_offset == (username_len +
1142 PART_ENCRYPTION_AES256_SIZE - sizeof (pea.hash)));
1144 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
1145 pea.username);
1146 if (cypher == NULL)
1147 {
1148 sfree (pea.username);
1149 return (-1);
1150 }
1152 payload_len = part_size - (PART_ENCRYPTION_AES256_SIZE + username_len);
1153 assert (payload_len > 0);
1155 /* Decrypt the packet in-place */
1156 err = gcry_cipher_decrypt (cypher,
1157 buffer + buffer_offset,
1158 part_size - buffer_offset,
1159 /* in = */ NULL, /* in len = */ 0);
1160 if (err != 0)
1161 {
1162 sfree (pea.username);
1163 ERROR ("network plugin: gcry_cipher_decrypt returned: %s",
1164 gcry_strerror (err));
1165 return (-1);
1166 }
1168 /* Read the hash */
1169 BUFFER_READ (pea.hash, sizeof (pea.hash));
1171 /* Make sure we're at the right position - again */
1172 assert (buffer_offset == (username_len + PART_ENCRYPTION_AES256_SIZE));
1173 assert (buffer_offset == (part_size - payload_len));
1175 /* Check hash sum */
1176 memset (hash, 0, sizeof (hash));
1177 gcry_md_hash_buffer (GCRY_MD_SHA1, hash,
1178 buffer + buffer_offset, payload_len);
1179 if (memcmp (hash, pea.hash, sizeof (hash)) != 0)
1180 {
1181 sfree (pea.username);
1182 ERROR ("network plugin: Decryption failed: Checksum mismatch.");
1183 return (-1);
1184 }
1186 parse_packet (se, buffer + buffer_offset, payload_len,
1187 flags | PP_ENCRYPTED);
1189 /* Update return values */
1190 *ret_buffer = buffer + part_size;
1191 *ret_buffer_len = buffer_len - part_size;
1193 sfree (pea.username);
1195 return (0);
1196 } /* }}} int parse_part_encr_aes256 */
1197 /* #endif HAVE_LIBGCRYPT */
1199 #else /* if !HAVE_LIBGCRYPT */
1200 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1201 void **ret_buffer, size_t *ret_buffer_size, int flags)
1202 {
1203 static int warning_has_been_printed = 0;
1205 char *buffer;
1206 size_t buffer_size;
1207 size_t buffer_offset;
1209 part_header_t ph;
1210 size_t ph_length;
1212 buffer = *ret_buffer;
1213 buffer_size = *ret_buffer_size;
1214 buffer_offset = 0;
1216 /* parse_packet assures this minimum size. */
1217 assert (buffer_size >= (sizeof (ph.type) + sizeof (ph.length)));
1219 BUFFER_READ (&ph.type, sizeof (ph.type));
1220 BUFFER_READ (&ph.length, sizeof (ph.length));
1221 ph_length = ntohs (ph.length);
1223 if ((ph_length <= PART_ENCRYPTION_AES256_SIZE)
1224 || (ph_length > buffer_size))
1225 {
1226 ERROR ("network plugin: AES-256 encrypted part "
1227 "with invalid length received.");
1228 return (-1);
1229 }
1231 if (warning_has_been_printed == 0)
1232 {
1233 WARNING ("network plugin: Received encrypted packet, but the network "
1234 "plugin was not linked with libgcrypt, so I cannot "
1235 "decrypt it. The part will be discarded.");
1236 warning_has_been_printed = 1;
1237 }
1239 *ret_buffer += ph_length;
1240 *ret_buffer_size -= ph_length;
1242 return (0);
1243 } /* }}} int parse_part_encr_aes256 */
1244 #endif /* !HAVE_LIBGCRYPT */
1246 #undef BUFFER_READ
1248 static int parse_packet (sockent_t *se, /* {{{ */
1249 void *buffer, size_t buffer_size, int flags)
1250 {
1251 int status;
1253 value_list_t vl = VALUE_LIST_INIT;
1254 notification_t n;
1256 #if HAVE_LIBGCRYPT
1257 int packet_was_signed = (flags & PP_SIGNED);
1258 int packet_was_encrypted = (flags & PP_ENCRYPTED);
1259 int printed_ignore_warning = 0;
1260 #endif /* HAVE_LIBGCRYPT */
1263 memset (&vl, '\0', sizeof (vl));
1264 memset (&n, '\0', sizeof (n));
1265 status = 0;
1267 while ((status == 0) && (0 < buffer_size)
1268 && ((unsigned int) buffer_size > sizeof (part_header_t)))
1269 {
1270 uint16_t pkg_length;
1271 uint16_t pkg_type;
1273 memcpy ((void *) &pkg_type,
1274 (void *) buffer,
1275 sizeof (pkg_type));
1276 memcpy ((void *) &pkg_length,
1277 (void *) (buffer + sizeof (pkg_type)),
1278 sizeof (pkg_length));
1280 pkg_length = ntohs (pkg_length);
1281 pkg_type = ntohs (pkg_type);
1283 if (pkg_length > buffer_size)
1284 break;
1285 /* Ensure that this loop terminates eventually */
1286 if (pkg_length < (2 * sizeof (uint16_t)))
1287 break;
1289 if (pkg_type == TYPE_ENCR_AES256)
1290 {
1291 status = parse_part_encr_aes256 (se,
1292 &buffer, &buffer_size, flags);
1293 if (status != 0)
1294 {
1295 ERROR ("network plugin: Decrypting AES256 "
1296 "part failed "
1297 "with status %i.", status);
1298 break;
1299 }
1300 }
1301 #if HAVE_LIBGCRYPT
1302 else if ((se->data.server.security_level == SECURITY_LEVEL_ENCRYPT)
1303 && (packet_was_encrypted == 0))
1304 {
1305 if (printed_ignore_warning == 0)
1306 {
1307 INFO ("network plugin: Unencrypted packet or "
1308 "part has been ignored.");
1309 printed_ignore_warning = 1;
1310 }
1311 buffer = ((char *) buffer) + pkg_length;
1312 continue;
1313 }
1314 #endif /* HAVE_LIBGCRYPT */
1315 else if (pkg_type == TYPE_SIGN_SHA256)
1316 {
1317 status = parse_part_sign_sha256 (se,
1318 &buffer, &buffer_size, flags);
1319 if (status != 0)
1320 {
1321 ERROR ("network plugin: Verifying HMAC-SHA-256 "
1322 "signature failed "
1323 "with status %i.", status);
1324 break;
1325 }
1326 }
1327 #if HAVE_LIBGCRYPT
1328 else if ((se->data.server.security_level == SECURITY_LEVEL_SIGN)
1329 && (packet_was_encrypted == 0)
1330 && (packet_was_signed == 0))
1331 {
1332 if (printed_ignore_warning == 0)
1333 {
1334 INFO ("network plugin: Unsigned packet or "
1335 "part has been ignored.");
1336 printed_ignore_warning = 1;
1337 }
1338 buffer = ((char *) buffer) + pkg_length;
1339 continue;
1340 }
1341 #endif /* HAVE_LIBGCRYPT */
1342 else if (pkg_type == TYPE_VALUES)
1343 {
1344 status = parse_part_values (&buffer, &buffer_size,
1345 &vl.values, &vl.values_len);
1346 if (status != 0)
1347 break;
1349 network_dispatch_values (&vl);
1351 sfree (vl.values);
1352 }
1353 else if (pkg_type == TYPE_TIME)
1354 {
1355 uint64_t tmp = 0;
1356 status = parse_part_number (&buffer, &buffer_size,
1357 &tmp);
1358 if (status == 0)
1359 {
1360 vl.time = (time_t) tmp;
1361 n.time = (time_t) tmp;
1362 }
1363 }
1364 else if (pkg_type == TYPE_INTERVAL)
1365 {
1366 uint64_t tmp = 0;
1367 status = parse_part_number (&buffer, &buffer_size,
1368 &tmp);
1369 if (status == 0)
1370 vl.interval = (int) tmp;
1371 }
1372 else if (pkg_type == TYPE_HOST)
1373 {
1374 status = parse_part_string (&buffer, &buffer_size,
1375 vl.host, sizeof (vl.host));
1376 if (status == 0)
1377 sstrncpy (n.host, vl.host, sizeof (n.host));
1378 }
1379 else if (pkg_type == TYPE_PLUGIN)
1380 {
1381 status = parse_part_string (&buffer, &buffer_size,
1382 vl.plugin, sizeof (vl.plugin));
1383 if (status == 0)
1384 sstrncpy (n.plugin, vl.plugin,
1385 sizeof (n.plugin));
1386 }
1387 else if (pkg_type == TYPE_PLUGIN_INSTANCE)
1388 {
1389 status = parse_part_string (&buffer, &buffer_size,
1390 vl.plugin_instance,
1391 sizeof (vl.plugin_instance));
1392 if (status == 0)
1393 sstrncpy (n.plugin_instance,
1394 vl.plugin_instance,
1395 sizeof (n.plugin_instance));
1396 }
1397 else if (pkg_type == TYPE_TYPE)
1398 {
1399 status = parse_part_string (&buffer, &buffer_size,
1400 vl.type, sizeof (vl.type));
1401 if (status == 0)
1402 sstrncpy (n.type, vl.type, sizeof (n.type));
1403 }
1404 else if (pkg_type == TYPE_TYPE_INSTANCE)
1405 {
1406 status = parse_part_string (&buffer, &buffer_size,
1407 vl.type_instance,
1408 sizeof (vl.type_instance));
1409 if (status == 0)
1410 sstrncpy (n.type_instance, vl.type_instance,
1411 sizeof (n.type_instance));
1412 }
1413 else if (pkg_type == TYPE_MESSAGE)
1414 {
1415 status = parse_part_string (&buffer, &buffer_size,
1416 n.message, sizeof (n.message));
1418 if (status != 0)
1419 {
1420 /* do nothing */
1421 }
1422 else if ((n.severity != NOTIF_FAILURE)
1423 && (n.severity != NOTIF_WARNING)
1424 && (n.severity != NOTIF_OKAY))
1425 {
1426 INFO ("network plugin: "
1427 "Ignoring notification with "
1428 "unknown severity %i.",
1429 n.severity);
1430 }
1431 else if (n.time <= 0)
1432 {
1433 INFO ("network plugin: "
1434 "Ignoring notification with "
1435 "time == 0.");
1436 }
1437 else if (strlen (n.message) <= 0)
1438 {
1439 INFO ("network plugin: "
1440 "Ignoring notification with "
1441 "an empty message.");
1442 }
1443 else
1444 {
1445 plugin_dispatch_notification (&n);
1446 }
1447 }
1448 else if (pkg_type == TYPE_SEVERITY)
1449 {
1450 uint64_t tmp = 0;
1451 status = parse_part_number (&buffer, &buffer_size,
1452 &tmp);
1453 if (status == 0)
1454 n.severity = (int) tmp;
1455 }
1456 else
1457 {
1458 DEBUG ("network plugin: parse_packet: Unknown part"
1459 " type: 0x%04hx", pkg_type);
1460 buffer = ((char *) buffer) + pkg_length;
1461 }
1462 } /* while (buffer_size > sizeof (part_header_t)) */
1464 if (status == 0 && buffer_size > 0)
1465 WARNING ("network plugin: parse_packet: Received truncated "
1466 "packet, try increasing `MaxPacketSize'");
1468 return (status);
1469 } /* }}} int parse_packet */
1471 static void free_sockent_client (struct sockent_client *sec) /* {{{ */
1472 {
1473 if (sec->fd >= 0)
1474 {
1475 close (sec->fd);
1476 sec->fd = -1;
1477 }
1478 sfree (sec->addr);
1479 #if HAVE_LIBGCRYPT
1480 sfree (sec->username);
1481 sfree (sec->password);
1482 if (sec->cypher != NULL)
1483 gcry_cipher_close (sec->cypher);
1484 #endif
1485 } /* }}} void free_sockent_client */
1487 static void free_sockent_server (struct sockent_server *ses) /* {{{ */
1488 {
1489 size_t i;
1491 for (i = 0; i < ses->fd_num; i++)
1492 {
1493 if (ses->fd[i] >= 0)
1494 {
1495 close (ses->fd[i]);
1496 ses->fd[i] = -1;
1497 }
1498 }
1500 sfree (ses->fd);
1501 #if HAVE_LIBGCRYPT
1502 sfree (ses->auth_file);
1503 fbh_destroy (ses->userdb);
1504 if (ses->cypher != NULL)
1505 gcry_cipher_close (ses->cypher);
1506 #endif
1507 } /* }}} void free_sockent_server */
1509 static void sockent_destroy (sockent_t *se) /* {{{ */
1510 {
1511 sockent_t *next;
1513 DEBUG ("network plugin: sockent_destroy (se = %p);", (void *) se);
1515 while (se != NULL)
1516 {
1517 next = se->next;
1519 sfree (se->node);
1520 sfree (se->service);
1522 if (se->type == SOCKENT_TYPE_CLIENT)
1523 free_sockent_client (&se->data.client);
1524 else
1525 free_sockent_server (&se->data.server);
1527 sfree (se);
1528 se = next;
1529 }
1530 } /* }}} void sockent_destroy */
1532 /*
1533 * int network_set_ttl
1534 *
1535 * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
1536 * `IPV6_UNICAST_HOPS', depending on which option is applicable.
1537 *
1538 * The `struct addrinfo' is used to destinguish between unicast and multicast
1539 * sockets.
1540 */
1541 static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
1542 {
1543 DEBUG ("network plugin: network_set_ttl: network_config_ttl = %i;",
1544 network_config_ttl);
1546 assert (se->type == SOCKENT_TYPE_CLIENT);
1548 if ((network_config_ttl < 1) || (network_config_ttl > 255))
1549 return (-1);
1551 if (ai->ai_family == AF_INET)
1552 {
1553 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1554 int optname;
1556 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1557 optname = IP_MULTICAST_TTL;
1558 else
1559 optname = IP_TTL;
1561 if (setsockopt (se->data.client.fd, IPPROTO_IP, optname,
1562 &network_config_ttl,
1563 sizeof (network_config_ttl)) != 0)
1564 {
1565 char errbuf[1024];
1566 ERROR ("setsockopt: %s",
1567 sstrerror (errno, errbuf, sizeof (errbuf)));
1568 return (-1);
1569 }
1570 }
1571 else if (ai->ai_family == AF_INET6)
1572 {
1573 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1574 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1575 int optname;
1577 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1578 optname = IPV6_MULTICAST_HOPS;
1579 else
1580 optname = IPV6_UNICAST_HOPS;
1582 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, optname,
1583 &network_config_ttl,
1584 sizeof (network_config_ttl)) != 0)
1585 {
1586 char errbuf[1024];
1587 ERROR ("setsockopt: %s",
1588 sstrerror (errno, errbuf,
1589 sizeof (errbuf)));
1590 return (-1);
1591 }
1592 }
1594 return (0);
1595 } /* int network_set_ttl */
1597 static int network_bind_socket (int fd, const struct addrinfo *ai)
1598 {
1599 int loop = 0;
1600 int yes = 1;
1602 /* allow multiple sockets to use the same PORT number */
1603 if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
1604 &yes, sizeof(yes)) == -1) {
1605 char errbuf[1024];
1606 ERROR ("setsockopt: %s",
1607 sstrerror (errno, errbuf, sizeof (errbuf)));
1608 return (-1);
1609 }
1611 DEBUG ("fd = %i; calling `bind'", fd);
1613 if (bind (fd, ai->ai_addr, ai->ai_addrlen) == -1)
1614 {
1615 char errbuf[1024];
1616 ERROR ("bind: %s",
1617 sstrerror (errno, errbuf, sizeof (errbuf)));
1618 return (-1);
1619 }
1621 if (ai->ai_family == AF_INET)
1622 {
1623 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1624 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1625 {
1626 struct ip_mreq mreq;
1628 DEBUG ("fd = %i; IPv4 multicast address found", fd);
1630 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1631 mreq.imr_interface.s_addr = htonl (INADDR_ANY);
1633 if (setsockopt (fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1634 &loop, sizeof (loop)) == -1)
1635 {
1636 char errbuf[1024];
1637 ERROR ("setsockopt: %s",
1638 sstrerror (errno, errbuf,
1639 sizeof (errbuf)));
1640 return (-1);
1641 }
1643 if (setsockopt (fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1644 &mreq, sizeof (mreq)) == -1)
1645 {
1646 char errbuf[1024];
1647 ERROR ("setsockopt: %s",
1648 sstrerror (errno, errbuf,
1649 sizeof (errbuf)));
1650 return (-1);
1651 }
1652 }
1653 }
1654 else if (ai->ai_family == AF_INET6)
1655 {
1656 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1657 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1658 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1659 {
1660 struct ipv6_mreq mreq;
1662 DEBUG ("fd = %i; IPv6 multicast address found", fd);
1664 memcpy (&mreq.ipv6mr_multiaddr,
1665 &addr->sin6_addr,
1666 sizeof (addr->sin6_addr));
1668 /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
1669 * ipv6mr_interface may be set to zeroes to
1670 * choose the default multicast interface or to
1671 * the index of a particular multicast-capable
1672 * interface if the host is multihomed.
1673 * Membership is associ-associated with a
1674 * single interface; programs running on
1675 * multihomed hosts may need to join the same
1676 * group on more than one interface.*/
1677 mreq.ipv6mr_interface = 0;
1679 if (setsockopt (fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1680 &loop, sizeof (loop)) == -1)
1681 {
1682 char errbuf[1024];
1683 ERROR ("setsockopt: %s",
1684 sstrerror (errno, errbuf,
1685 sizeof (errbuf)));
1686 return (-1);
1687 }
1689 if (setsockopt (fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
1690 &mreq, sizeof (mreq)) == -1)
1691 {
1692 char errbuf[1024];
1693 ERROR ("setsockopt: %s",
1694 sstrerror (errno, errbuf,
1695 sizeof (errbuf)));
1696 return (-1);
1697 }
1698 }
1699 }
1701 return (0);
1702 } /* int network_bind_socket */
1704 /* Initialize a sockent structure. `type' must be either `SOCKENT_TYPE_CLIENT'
1705 * or `SOCKENT_TYPE_SERVER' */
1706 static int sockent_init (sockent_t *se, int type) /* {{{ */
1707 {
1708 if (se == NULL)
1709 return (-1);
1711 memset (se, 0, sizeof (*se));
1713 se->type = SOCKENT_TYPE_CLIENT;
1714 se->node = NULL;
1715 se->service = NULL;
1716 se->next = NULL;
1718 if (type == SOCKENT_TYPE_SERVER)
1719 {
1720 se->type = SOCKENT_TYPE_SERVER;
1721 se->data.server.fd = NULL;
1722 #if HAVE_LIBGCRYPT
1723 se->data.server.security_level = SECURITY_LEVEL_NONE;
1724 se->data.server.auth_file = NULL;
1725 se->data.server.userdb = NULL;
1726 se->data.server.cypher = NULL;
1727 #endif
1728 }
1729 else
1730 {
1731 se->data.client.fd = -1;
1732 se->data.client.addr = NULL;
1733 #if HAVE_LIBGCRYPT
1734 se->data.client.security_level = SECURITY_LEVEL_NONE;
1735 se->data.client.username = NULL;
1736 se->data.client.password = NULL;
1737 se->data.client.cypher = NULL;
1738 #endif
1739 }
1741 return (0);
1742 } /* }}} int sockent_init */
1744 /* Open the file descriptors for a initialized sockent structure. */
1745 static int sockent_open (sockent_t *se) /* {{{ */
1746 {
1747 struct addrinfo ai_hints;
1748 struct addrinfo *ai_list, *ai_ptr;
1749 int ai_return;
1751 const char *node;
1752 const char *service;
1754 if (se == NULL)
1755 return (-1);
1757 /* Set up the security structures. */
1758 #if HAVE_LIBGCRYPT /* {{{ */
1759 if (se->type == SOCKENT_TYPE_CLIENT)
1760 {
1761 if (se->data.client.security_level > SECURITY_LEVEL_NONE)
1762 {
1763 if ((se->data.client.username == NULL)
1764 || (se->data.client.password == NULL))
1765 {
1766 ERROR ("network plugin: Client socket with "
1767 "security requested, but no "
1768 "credentials are configured.");
1769 return (-1);
1770 }
1771 gcry_md_hash_buffer (GCRY_MD_SHA256,
1772 se->data.client.password_hash,
1773 se->data.client.password,
1774 strlen (se->data.client.password));
1775 }
1776 }
1777 else /* (se->type == SOCKENT_TYPE_SERVER) */
1778 {
1779 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
1780 {
1781 if (se->data.server.auth_file == NULL)
1782 {
1783 ERROR ("network plugin: Server socket with "
1784 "security requested, but no "
1785 "password file is configured.");
1786 return (-1);
1787 }
1788 }
1789 if (se->data.server.auth_file != NULL)
1790 {
1791 se->data.server.userdb = fbh_create (se->data.server.auth_file);
1792 if (se->data.server.userdb == NULL)
1793 {
1794 ERROR ("network plugin: Reading password file "
1795 "`%s' failed.",
1796 se->data.server.auth_file);
1797 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
1798 return (-1);
1799 }
1800 }
1801 }
1802 #endif /* }}} HAVE_LIBGCRYPT */
1804 node = se->node;
1805 service = se->service;
1807 if (service == NULL)
1808 service = NET_DEFAULT_PORT;
1810 DEBUG ("network plugin: sockent_open: node = %s; service = %s;",
1811 node, service);
1813 memset (&ai_hints, 0, sizeof (ai_hints));
1814 ai_hints.ai_flags = 0;
1815 #ifdef AI_PASSIVE
1816 ai_hints.ai_flags |= AI_PASSIVE;
1817 #endif
1818 #ifdef AI_ADDRCONFIG
1819 ai_hints.ai_flags |= AI_ADDRCONFIG;
1820 #endif
1821 ai_hints.ai_family = AF_UNSPEC;
1822 ai_hints.ai_socktype = SOCK_DGRAM;
1823 ai_hints.ai_protocol = IPPROTO_UDP;
1825 ai_return = getaddrinfo (node, service, &ai_hints, &ai_list);
1826 if (ai_return != 0)
1827 {
1828 ERROR ("network plugin: getaddrinfo (%s, %s) failed: %s",
1829 (se->node == NULL) ? "(null)" : se->node,
1830 (se->service == NULL) ? "(null)" : se->service,
1831 gai_strerror (ai_return));
1832 return (-1);
1833 }
1835 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1836 {
1837 int status;
1839 if (se->type == SOCKENT_TYPE_SERVER) /* {{{ */
1840 {
1841 int *tmp;
1843 tmp = realloc (se->data.server.fd,
1844 sizeof (*tmp) * (se->data.server.fd_num + 1));
1845 if (tmp == NULL)
1846 {
1847 ERROR ("network plugin: realloc failed.");
1848 continue;
1849 }
1850 se->data.server.fd = tmp;
1851 tmp = se->data.server.fd + se->data.server.fd_num;
1853 *tmp = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
1854 ai_ptr->ai_protocol);
1855 if (*tmp < 0)
1856 {
1857 char errbuf[1024];
1858 ERROR ("network plugin: socket(2) failed: %s",
1859 sstrerror (errno, errbuf,
1860 sizeof (errbuf)));
1861 continue;
1862 }
1864 status = network_bind_socket (*tmp, ai_ptr);
1865 if (status != 0)
1866 {
1867 close (*tmp);
1868 *tmp = -1;
1869 continue;
1870 }
1872 se->data.server.fd_num++;
1873 continue;
1874 } /* }}} if (se->type == SOCKENT_TYPE_SERVER) */
1875 else /* if (se->type == SOCKENT_TYPE_CLIENT) {{{ */
1876 {
1877 se->data.client.fd = socket (ai_ptr->ai_family,
1878 ai_ptr->ai_socktype,
1879 ai_ptr->ai_protocol);
1880 if (se->data.client.fd < 0)
1881 {
1882 char errbuf[1024];
1883 ERROR ("network plugin: socket(2) failed: %s",
1884 sstrerror (errno, errbuf,
1885 sizeof (errbuf)));
1886 continue;
1887 }
1889 se->data.client.addr = malloc (sizeof (*se->data.client.addr));
1890 if (se->data.client.addr == NULL)
1891 {
1892 ERROR ("network plugin: malloc failed.");
1893 close (se->data.client.fd);
1894 se->data.client.fd = -1;
1895 continue;
1896 }
1898 memset (se->data.client.addr, 0, sizeof (*se->data.client.addr));
1899 assert (sizeof (*se->data.client.addr) >= ai_ptr->ai_addrlen);
1900 memcpy (se->data.client.addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1901 se->data.client.addrlen = ai_ptr->ai_addrlen;
1903 network_set_ttl (se, ai_ptr);
1905 /* We don't open more than one write-socket per
1906 * node/service pair.. */
1907 break;
1908 } /* }}} if (se->type == SOCKENT_TYPE_CLIENT) */
1909 } /* for (ai_list) */
1911 freeaddrinfo (ai_list);
1913 /* Check if all went well. */
1914 if (se->type == SOCKENT_TYPE_SERVER)
1915 {
1916 if (se->data.server.fd_num <= 0)
1917 return (-1);
1918 }
1919 else /* if (se->type == SOCKENT_TYPE_CLIENT) */
1920 {
1921 if (se->data.client.fd < 0)
1922 return (-1);
1923 }
1925 return (0);
1926 } /* }}} int sockent_open */
1928 /* Add a sockent to the global list of sockets */
1929 static int sockent_add (sockent_t *se) /* {{{ */
1930 {
1931 sockent_t *last_ptr;
1933 if (se == NULL)
1934 return (-1);
1936 if (se->type == SOCKENT_TYPE_SERVER)
1937 {
1938 struct pollfd *tmp;
1939 size_t i;
1941 tmp = realloc (listen_sockets_pollfd,
1942 sizeof (*tmp) * (listen_sockets_num
1943 + se->data.server.fd_num));
1944 if (tmp == NULL)
1945 {
1946 ERROR ("network plugin: realloc failed.");
1947 return (-1);
1948 }
1949 listen_sockets_pollfd = tmp;
1950 tmp = listen_sockets_pollfd + listen_sockets_num;
1952 for (i = 0; i < se->data.server.fd_num; i++)
1953 {
1954 memset (tmp + i, 0, sizeof (*tmp));
1955 tmp[i].fd = se->data.server.fd[i];
1956 tmp[i].events = POLLIN | POLLPRI;
1957 tmp[i].revents = 0;
1958 }
1960 listen_sockets_num += se->data.server.fd_num;
1962 if (listen_sockets == NULL)
1963 {
1964 listen_sockets = se;
1965 return (0);
1966 }
1967 last_ptr = listen_sockets;
1968 }
1969 else /* if (se->type == SOCKENT_TYPE_CLIENT) */
1970 {
1971 if (sending_sockets == NULL)
1972 {
1973 sending_sockets = se;
1974 return (0);
1975 }
1976 last_ptr = sending_sockets;
1977 }
1979 while (last_ptr->next != NULL)
1980 last_ptr = last_ptr->next;
1981 last_ptr->next = se;
1983 return (0);
1984 } /* }}} int sockent_add */
1986 static void *dispatch_thread (void __attribute__((unused)) *arg) /* {{{ */
1987 {
1988 while (42)
1989 {
1990 receive_list_entry_t *ent;
1991 sockent_t *se;
1993 /* Lock and wait for more data to come in */
1994 pthread_mutex_lock (&receive_list_lock);
1995 while ((listen_loop == 0)
1996 && (receive_list_head == NULL))
1997 pthread_cond_wait (&receive_list_cond, &receive_list_lock);
1999 /* Remove the head entry and unlock */
2000 ent = receive_list_head;
2001 if (ent != NULL)
2002 receive_list_head = ent->next;
2003 receive_list_length--;
2004 pthread_mutex_unlock (&receive_list_lock);
2006 /* Check whether we are supposed to exit. We do NOT check `listen_loop'
2007 * because we dispatch all missing packets before shutting down. */
2008 if (ent == NULL)
2009 break;
2011 /* Look for the correct `sockent_t' */
2012 se = listen_sockets;
2013 while (se != NULL)
2014 {
2015 size_t i;
2017 for (i = 0; i < se->data.server.fd_num; i++)
2018 if (se->data.server.fd[i] == ent->fd)
2019 break;
2021 if (i < se->data.server.fd_num)
2022 break;
2024 se = se->next;
2025 }
2027 if (se == NULL)
2028 {
2029 ERROR ("network plugin: Got packet from FD %i, but can't "
2030 "find an appropriate socket entry.",
2031 ent->fd);
2032 sfree (ent->data);
2033 sfree (ent);
2034 continue;
2035 }
2037 parse_packet (se, ent->data, ent->data_len, /* flags = */ 0);
2038 sfree (ent->data);
2039 sfree (ent);
2040 } /* while (42) */
2042 return (NULL);
2043 } /* }}} void *dispatch_thread */
2045 static int network_receive (void) /* {{{ */
2046 {
2047 char buffer[network_config_packet_size];
2048 int buffer_len;
2050 int i;
2051 int status;
2053 receive_list_entry_t *private_list_head;
2054 receive_list_entry_t *private_list_tail;
2055 uint64_t private_list_length;
2057 assert (listen_sockets_num > 0);
2059 private_list_head = NULL;
2060 private_list_tail = NULL;
2061 private_list_length = 0;
2063 while (listen_loop == 0)
2064 {
2065 status = poll (listen_sockets_pollfd, listen_sockets_num, -1);
2067 if (status <= 0)
2068 {
2069 char errbuf[1024];
2070 if (errno == EINTR)
2071 continue;
2072 ERROR ("poll failed: %s",
2073 sstrerror (errno, errbuf, sizeof (errbuf)));
2074 return (-1);
2075 }
2077 for (i = 0; (i < listen_sockets_num) && (status > 0); i++)
2078 {
2079 receive_list_entry_t *ent;
2081 if ((listen_sockets_pollfd[i].revents
2082 & (POLLIN | POLLPRI)) == 0)
2083 continue;
2084 status--;
2086 buffer_len = recv (listen_sockets_pollfd[i].fd,
2087 buffer, sizeof (buffer),
2088 0 /* no flags */);
2089 if (buffer_len < 0)
2090 {
2091 char errbuf[1024];
2092 ERROR ("recv failed: %s",
2093 sstrerror (errno, errbuf,
2094 sizeof (errbuf)));
2095 return (-1);
2096 }
2098 stats_octets_rx += ((uint64_t) buffer_len);
2099 stats_packets_rx++;
2101 /* TODO: Possible performance enhancement: Do not free
2102 * these entries in the dispatch thread but put them in
2103 * another list, so we don't have to allocate more and
2104 * more of these structures. */
2105 ent = malloc (sizeof (receive_list_entry_t));
2106 if (ent == NULL)
2107 {
2108 ERROR ("network plugin: malloc failed.");
2109 return (-1);
2110 }
2111 memset (ent, 0, sizeof (receive_list_entry_t));
2112 ent->data = malloc (network_config_packet_size);
2113 if (ent->data == NULL)
2114 {
2115 sfree (ent);
2116 ERROR ("network plugin: malloc failed.");
2117 return (-1);
2118 }
2119 ent->fd = listen_sockets_pollfd[i].fd;
2120 ent->next = NULL;
2122 memcpy (ent->data, buffer, buffer_len);
2123 ent->data_len = buffer_len;
2125 if (private_list_head == NULL)
2126 private_list_head = ent;
2127 else
2128 private_list_tail->next = ent;
2129 private_list_tail = ent;
2130 private_list_length++;
2132 /* Do not block here. Blocking here has led to
2133 * insufficient performance in the past. */
2134 if (pthread_mutex_trylock (&receive_list_lock) == 0)
2135 {
2136 assert (((receive_list_head == NULL) && (receive_list_length == 0))
2137 || ((receive_list_head != NULL) && (receive_list_length != 0)));
2139 if (receive_list_head == NULL)
2140 receive_list_head = private_list_head;
2141 else
2142 receive_list_tail->next = private_list_head;
2143 receive_list_tail = private_list_tail;
2144 receive_list_length += private_list_length;
2146 pthread_cond_signal (&receive_list_cond);
2147 pthread_mutex_unlock (&receive_list_lock);
2149 private_list_head = NULL;
2150 private_list_tail = NULL;
2151 private_list_length = 0;
2152 }
2153 } /* for (listen_sockets_pollfd) */
2154 } /* while (listen_loop == 0) */
2156 /* Make sure everything is dispatched before exiting. */
2157 if (private_list_head != NULL)
2158 {
2159 pthread_mutex_lock (&receive_list_lock);
2161 if (receive_list_head == NULL)
2162 receive_list_head = private_list_head;
2163 else
2164 receive_list_tail->next = private_list_head;
2165 receive_list_tail = private_list_tail;
2166 receive_list_length += private_list_length;
2168 private_list_head = NULL;
2169 private_list_tail = NULL;
2170 private_list_length = 0;
2172 pthread_cond_signal (&receive_list_cond);
2173 pthread_mutex_unlock (&receive_list_lock);
2174 }
2176 return (0);
2177 } /* }}} int network_receive */
2179 static void *receive_thread (void __attribute__((unused)) *arg)
2180 {
2181 return (network_receive () ? (void *) 1 : (void *) 0);
2182 } /* void *receive_thread */
2184 static void network_init_buffer (void)
2185 {
2186 memset (send_buffer, 0, network_config_packet_size);
2187 send_buffer_ptr = send_buffer;
2188 send_buffer_fill = 0;
2190 memset (&send_buffer_vl, 0, sizeof (send_buffer_vl));
2191 } /* int network_init_buffer */
2193 static void networt_send_buffer_plain (const sockent_t *se, /* {{{ */
2194 const char *buffer, size_t buffer_size)
2195 {
2196 int status;
2198 while (42)
2199 {
2200 status = sendto (se->data.client.fd, buffer, buffer_size,
2201 /* flags = */ 0,
2202 (struct sockaddr *) se->data.client.addr,
2203 se->data.client.addrlen);
2204 if (status < 0)
2205 {
2206 char errbuf[1024];
2207 if (errno == EINTR)
2208 continue;
2209 ERROR ("network plugin: sendto failed: %s",
2210 sstrerror (errno, errbuf,
2211 sizeof (errbuf)));
2212 break;
2213 }
2215 break;
2216 } /* while (42) */
2217 } /* }}} void networt_send_buffer_plain */
2219 #if HAVE_LIBGCRYPT
2220 #define BUFFER_ADD(p,s) do { \
2221 memcpy (buffer + buffer_offset, (p), (s)); \
2222 buffer_offset += (s); \
2223 } while (0)
2225 static void networt_send_buffer_signed (const sockent_t *se, /* {{{ */
2226 const char *in_buffer, size_t in_buffer_size)
2227 {
2228 part_signature_sha256_t ps;
2229 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2230 size_t buffer_offset;
2231 size_t username_len;
2233 gcry_md_hd_t hd;
2234 gcry_error_t err;
2235 unsigned char *hash;
2237 hd = NULL;
2238 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
2239 if (err != 0)
2240 {
2241 ERROR ("network plugin: Creating HMAC object failed: %s",
2242 gcry_strerror (err));
2243 return;
2244 }
2246 err = gcry_md_setkey (hd, se->data.client.password,
2247 strlen (se->data.client.password));
2248 if (err != 0)
2249 {
2250 ERROR ("network plugin: gcry_md_setkey failed: %s",
2251 gcry_strerror (err));
2252 gcry_md_close (hd);
2253 return;
2254 }
2256 username_len = strlen (se->data.client.username);
2257 if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE))
2258 {
2259 ERROR ("network plugin: Username too long: %s",
2260 se->data.client.username);
2261 return;
2262 }
2264 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE,
2265 se->data.client.username, username_len);
2266 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE + username_len,
2267 in_buffer, in_buffer_size);
2269 /* Initialize the `ps' structure. */
2270 memset (&ps, 0, sizeof (ps));
2271 ps.head.type = htons (TYPE_SIGN_SHA256);
2272 ps.head.length = htons (PART_SIGNATURE_SHA256_SIZE + username_len);
2274 /* Calculate the hash value. */
2275 gcry_md_write (hd, buffer + PART_SIGNATURE_SHA256_SIZE,
2276 username_len + in_buffer_size);
2277 hash = gcry_md_read (hd, GCRY_MD_SHA256);
2278 if (hash == NULL)
2279 {
2280 ERROR ("network plugin: gcry_md_read failed.");
2281 gcry_md_close (hd);
2282 return;
2283 }
2284 memcpy (ps.hash, hash, sizeof (ps.hash));
2286 /* Add the header */
2287 buffer_offset = 0;
2289 BUFFER_ADD (&ps.head.type, sizeof (ps.head.type));
2290 BUFFER_ADD (&ps.head.length, sizeof (ps.head.length));
2291 BUFFER_ADD (ps.hash, sizeof (ps.hash));
2293 assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
2295 gcry_md_close (hd);
2296 hd = NULL;
2298 buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
2299 networt_send_buffer_plain (se, buffer, buffer_offset);
2300 } /* }}} void networt_send_buffer_signed */
2302 static void networt_send_buffer_encrypted (sockent_t *se, /* {{{ */
2303 const char *in_buffer, size_t in_buffer_size)
2304 {
2305 part_encryption_aes256_t pea;
2306 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2307 size_t buffer_size;
2308 size_t buffer_offset;
2309 size_t header_size;
2310 size_t username_len;
2311 gcry_error_t err;
2312 gcry_cipher_hd_t cypher;
2314 /* Initialize the header fields */
2315 memset (&pea, 0, sizeof (pea));
2316 pea.head.type = htons (TYPE_ENCR_AES256);
2318 pea.username = se->data.client.username;
2320 username_len = strlen (pea.username);
2321 if ((PART_ENCRYPTION_AES256_SIZE + username_len) > BUFF_SIG_SIZE)
2322 {
2323 ERROR ("network plugin: Username too long: %s", pea.username);
2324 return;
2325 }
2327 buffer_size = PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size;
2328 header_size = PART_ENCRYPTION_AES256_SIZE + username_len
2329 - sizeof (pea.hash);
2331 assert (buffer_size <= sizeof (buffer));
2332 DEBUG ("network plugin: networt_send_buffer_encrypted: "
2333 "buffer_size = %zu;", buffer_size);
2335 pea.head.length = htons ((uint16_t) (PART_ENCRYPTION_AES256_SIZE
2336 + username_len + in_buffer_size));
2337 pea.username_length = htons ((uint16_t) username_len);
2339 /* Chose a random initialization vector. */
2340 gcry_randomize ((void *) &pea.iv, sizeof (pea.iv), GCRY_STRONG_RANDOM);
2342 /* Create hash of the payload */
2343 gcry_md_hash_buffer (GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
2345 /* Initialize the buffer */
2346 buffer_offset = 0;
2347 memset (buffer, 0, sizeof (buffer));
2350 BUFFER_ADD (&pea.head.type, sizeof (pea.head.type));
2351 BUFFER_ADD (&pea.head.length, sizeof (pea.head.length));
2352 BUFFER_ADD (&pea.username_length, sizeof (pea.username_length));
2353 BUFFER_ADD (pea.username, username_len);
2354 BUFFER_ADD (pea.iv, sizeof (pea.iv));
2355 assert (buffer_offset == header_size);
2356 BUFFER_ADD (pea.hash, sizeof (pea.hash));
2357 BUFFER_ADD (in_buffer, in_buffer_size);
2359 assert (buffer_offset == buffer_size);
2361 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
2362 se->data.client.password);
2363 if (cypher == NULL)
2364 return;
2366 /* Encrypt the buffer in-place */
2367 err = gcry_cipher_encrypt (cypher,
2368 buffer + header_size,
2369 buffer_size - header_size,
2370 /* in = */ NULL, /* in len = */ 0);
2371 if (err != 0)
2372 {
2373 ERROR ("network plugin: gcry_cipher_encrypt returned: %s",
2374 gcry_strerror (err));
2375 return;
2376 }
2378 /* Send it out without further modifications */
2379 networt_send_buffer_plain (se, buffer, buffer_size);
2380 } /* }}} void networt_send_buffer_encrypted */
2381 #undef BUFFER_ADD
2382 #endif /* HAVE_LIBGCRYPT */
2384 static void network_send_buffer (char *buffer, size_t buffer_len) /* {{{ */
2385 {
2386 sockent_t *se;
2388 DEBUG ("network plugin: network_send_buffer: buffer_len = %zu", buffer_len);
2390 for (se = sending_sockets; se != NULL; se = se->next)
2391 {
2392 #if HAVE_LIBGCRYPT
2393 if (se->data.client.security_level == SECURITY_LEVEL_ENCRYPT)
2394 networt_send_buffer_encrypted (se, buffer, buffer_len);
2395 else if (se->data.client.security_level == SECURITY_LEVEL_SIGN)
2396 networt_send_buffer_signed (se, buffer, buffer_len);
2397 else /* if (se->data.client.security_level == SECURITY_LEVEL_NONE) */
2398 #endif /* HAVE_LIBGCRYPT */
2399 networt_send_buffer_plain (se, buffer, buffer_len);
2400 } /* for (sending_sockets) */
2401 } /* }}} void network_send_buffer */
2403 static int add_to_buffer (char *buffer, int buffer_size, /* {{{ */
2404 value_list_t *vl_def,
2405 const data_set_t *ds, const value_list_t *vl)
2406 {
2407 char *buffer_orig = buffer;
2409 if (strcmp (vl_def->host, vl->host) != 0)
2410 {
2411 if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
2412 vl->host, strlen (vl->host)) != 0)
2413 return (-1);
2414 sstrncpy (vl_def->host, vl->host, sizeof (vl_def->host));
2415 }
2417 if (vl_def->time != vl->time)
2418 {
2419 if (write_part_number (&buffer, &buffer_size, TYPE_TIME,
2420 (uint64_t) vl->time))
2421 return (-1);
2422 vl_def->time = vl->time;
2423 }
2425 if (vl_def->interval != vl->interval)
2426 {
2427 if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL,
2428 (uint64_t) vl->interval))
2429 return (-1);
2430 vl_def->interval = vl->interval;
2431 }
2433 if (strcmp (vl_def->plugin, vl->plugin) != 0)
2434 {
2435 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
2436 vl->plugin, strlen (vl->plugin)) != 0)
2437 return (-1);
2438 sstrncpy (vl_def->plugin, vl->plugin, sizeof (vl_def->plugin));
2439 }
2441 if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
2442 {
2443 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
2444 vl->plugin_instance,
2445 strlen (vl->plugin_instance)) != 0)
2446 return (-1);
2447 sstrncpy (vl_def->plugin_instance, vl->plugin_instance, sizeof (vl_def->plugin_instance));
2448 }
2450 if (strcmp (vl_def->type, vl->type) != 0)
2451 {
2452 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
2453 vl->type, strlen (vl->type)) != 0)
2454 return (-1);
2455 sstrncpy (vl_def->type, ds->type, sizeof (vl_def->type));
2456 }
2458 if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
2459 {
2460 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
2461 vl->type_instance,
2462 strlen (vl->type_instance)) != 0)
2463 return (-1);
2464 sstrncpy (vl_def->type_instance, vl->type_instance, sizeof (vl_def->type_instance));
2465 }
2467 if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
2468 return (-1);
2470 return (buffer - buffer_orig);
2471 } /* }}} int add_to_buffer */
2473 static void flush_buffer (void)
2474 {
2475 DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
2476 send_buffer_fill);
2478 network_send_buffer (send_buffer, (size_t) send_buffer_fill);
2480 stats_octets_tx += ((uint64_t) send_buffer_fill);
2481 stats_packets_tx++;
2483 network_init_buffer ();
2484 }
2486 static int network_write (const data_set_t *ds, const value_list_t *vl,
2487 user_data_t __attribute__((unused)) *user_data)
2488 {
2489 int status;
2491 if (!check_send_okay (vl))
2492 {
2493 #if COLLECT_DEBUG
2494 char name[6*DATA_MAX_NAME_LEN];
2495 FORMAT_VL (name, sizeof (name), vl);
2496 name[sizeof (name) - 1] = 0;
2497 DEBUG ("network plugin: network_write: "
2498 "NOT sending %s.", name);
2499 #endif
2500 /* Counter is not protected by another lock and may be reached by
2501 * multiple threads */
2502 pthread_mutex_lock (&stats_lock);
2503 stats_values_not_sent++;
2504 pthread_mutex_unlock (&stats_lock);
2505 return (0);
2506 }
2508 uc_meta_data_add_unsigned_int (vl,
2509 "network:time_sent", (uint64_t) vl->time);
2511 pthread_mutex_lock (&send_buffer_lock);
2513 status = add_to_buffer (send_buffer_ptr,
2514 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2515 &send_buffer_vl,
2516 ds, vl);
2517 if (status >= 0)
2518 {
2519 /* status == bytes added to the buffer */
2520 send_buffer_fill += status;
2521 send_buffer_ptr += status;
2523 stats_values_sent++;
2524 }
2525 else
2526 {
2527 flush_buffer ();
2529 status = add_to_buffer (send_buffer_ptr,
2530 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2531 &send_buffer_vl,
2532 ds, vl);
2534 if (status >= 0)
2535 {
2536 send_buffer_fill += status;
2537 send_buffer_ptr += status;
2539 stats_values_sent++;
2540 }
2541 }
2543 if (status < 0)
2544 {
2545 ERROR ("network plugin: Unable to append to the "
2546 "buffer for some weird reason");
2547 }
2548 else if ((network_config_packet_size - send_buffer_fill) < 15)
2549 {
2550 flush_buffer ();
2551 }
2553 pthread_mutex_unlock (&send_buffer_lock);
2555 return ((status < 0) ? -1 : 0);
2556 } /* int network_write */
2558 static int network_config_set_boolean (const oconfig_item_t *ci, /* {{{ */
2559 int *retval)
2560 {
2561 if ((ci->values_num != 1)
2562 || ((ci->values[0].type != OCONFIG_TYPE_BOOLEAN)
2563 && (ci->values[0].type != OCONFIG_TYPE_STRING)))
2564 {
2565 ERROR ("network plugin: The `%s' config option needs "
2566 "exactly one boolean argument.", ci->key);
2567 return (-1);
2568 }
2570 if (ci->values[0].type == OCONFIG_TYPE_BOOLEAN)
2571 {
2572 if (ci->values[0].value.boolean)
2573 *retval = 1;
2574 else
2575 *retval = 0;
2576 }
2577 else
2578 {
2579 char *str = ci->values[0].value.string;
2581 if (IS_TRUE (str))
2582 *retval = 1;
2583 else if (IS_FALSE (str))
2584 *retval = 0;
2585 else
2586 {
2587 ERROR ("network plugin: Cannot parse string value `%s' of the `%s' "
2588 "option as boolean value.",
2589 str, ci->key);
2590 return (-1);
2591 }
2592 }
2594 return (0);
2595 } /* }}} int network_config_set_boolean */
2597 static int network_config_set_ttl (const oconfig_item_t *ci) /* {{{ */
2598 {
2599 int tmp;
2600 if ((ci->values_num != 1)
2601 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2602 {
2603 WARNING ("network plugin: The `TimeToLive' config option needs exactly "
2604 "one numeric argument.");
2605 return (-1);
2606 }
2608 tmp = (int) ci->values[0].value.number;
2609 if ((tmp > 0) && (tmp <= 255))
2610 network_config_ttl = tmp;
2612 return (0);
2613 } /* }}} int network_config_set_ttl */
2615 static int network_config_set_buffer_size (const oconfig_item_t *ci) /* {{{ */
2616 {
2617 int tmp;
2618 if ((ci->values_num != 1)
2619 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2620 {
2621 WARNING ("network plugin: The `MaxPacketSize' config option needs exactly "
2622 "one numeric argument.");
2623 return (-1);
2624 }
2626 tmp = (int) ci->values[0].value.number;
2627 if ((tmp >= 1024) && (tmp <= 65535))
2628 network_config_packet_size = tmp;
2630 return (0);
2631 } /* }}} int network_config_set_buffer_size */
2633 #if HAVE_LIBGCRYPT
2634 static int network_config_set_string (const oconfig_item_t *ci, /* {{{ */
2635 char **ret_string)
2636 {
2637 char *tmp;
2638 if ((ci->values_num != 1)
2639 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2640 {
2641 WARNING ("network plugin: The `%s' config option needs exactly "
2642 "one string argument.", ci->key);
2643 return (-1);
2644 }
2646 tmp = strdup (ci->values[0].value.string);
2647 if (tmp == NULL)
2648 return (-1);
2650 sfree (*ret_string);
2651 *ret_string = tmp;
2653 return (0);
2654 } /* }}} int network_config_set_string */
2655 #endif /* HAVE_LIBGCRYPT */
2657 #if HAVE_LIBGCRYPT
2658 static int network_config_set_security_level (oconfig_item_t *ci, /* {{{ */
2659 int *retval)
2660 {
2661 char *str;
2662 if ((ci->values_num != 1)
2663 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2664 {
2665 WARNING ("network plugin: The `SecurityLevel' config option needs exactly "
2666 "one string argument.");
2667 return (-1);
2668 }
2670 str = ci->values[0].value.string;
2671 if (strcasecmp ("Encrypt", str) == 0)
2672 *retval = SECURITY_LEVEL_ENCRYPT;
2673 else if (strcasecmp ("Sign", str) == 0)
2674 *retval = SECURITY_LEVEL_SIGN;
2675 else if (strcasecmp ("None", str) == 0)
2676 *retval = SECURITY_LEVEL_NONE;
2677 else
2678 {
2679 WARNING ("network plugin: Unknown security level: %s.", str);
2680 return (-1);
2681 }
2683 return (0);
2684 } /* }}} int network_config_set_security_level */
2685 #endif /* HAVE_LIBGCRYPT */
2687 static int network_config_add_listen (const oconfig_item_t *ci) /* {{{ */
2688 {
2689 sockent_t *se;
2690 int status;
2691 int i;
2693 if ((ci->values_num < 1) || (ci->values_num > 2)
2694 || (ci->values[0].type != OCONFIG_TYPE_STRING)
2695 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
2696 {
2697 ERROR ("network plugin: The `%s' config option needs "
2698 "one or two string arguments.", ci->key);
2699 return (-1);
2700 }
2702 se = malloc (sizeof (*se));
2703 if (se == NULL)
2704 {
2705 ERROR ("network plugin: malloc failed.");
2706 return (-1);
2707 }
2708 sockent_init (se, SOCKENT_TYPE_SERVER);
2710 se->node = strdup (ci->values[0].value.string);
2711 if (ci->values_num >= 2)
2712 se->service = strdup (ci->values[1].value.string);
2714 for (i = 0; i < ci->children_num; i++)
2715 {
2716 oconfig_item_t *child = ci->children + i;
2718 #if HAVE_LIBGCRYPT
2719 if (strcasecmp ("AuthFile", child->key) == 0)
2720 network_config_set_string (child, &se->data.server.auth_file);
2721 else if (strcasecmp ("SecurityLevel", child->key) == 0)
2722 network_config_set_security_level (child,
2723 &se->data.server.security_level);
2724 else
2725 #endif /* HAVE_LIBGCRYPT */
2726 {
2727 WARNING ("network plugin: Option `%s' is not allowed here.",
2728 child->key);
2729 }
2730 }
2732 #if HAVE_LIBGCRYPT
2733 if ((se->data.server.security_level > SECURITY_LEVEL_NONE)
2734 && (se->data.server.auth_file == NULL))
2735 {
2736 ERROR ("network plugin: A security level higher than `none' was "
2737 "requested, but no AuthFile option was given. Cowardly refusing to "
2738 "open this socket!");
2739 sockent_destroy (se);
2740 return (-1);
2741 }
2742 #endif /* HAVE_LIBGCRYPT */
2744 status = sockent_open (se);
2745 if (status != 0)
2746 {
2747 ERROR ("network plugin: network_config_add_listen: sockent_open failed.");
2748 sockent_destroy (se);
2749 return (-1);
2750 }
2752 status = sockent_add (se);
2753 if (status != 0)
2754 {
2755 ERROR ("network plugin: network_config_add_listen: sockent_add failed.");
2756 sockent_destroy (se);
2757 return (-1);
2758 }
2760 return (0);
2761 } /* }}} int network_config_add_listen */
2763 static int network_config_add_server (const oconfig_item_t *ci) /* {{{ */
2764 {
2765 sockent_t *se;
2766 int status;
2767 int i;
2769 if ((ci->values_num < 1) || (ci->values_num > 2)
2770 || (ci->values[0].type != OCONFIG_TYPE_STRING)
2771 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
2772 {
2773 ERROR ("network plugin: The `%s' config option needs "
2774 "one or two string arguments.", ci->key);
2775 return (-1);
2776 }
2778 se = malloc (sizeof (*se));
2779 if (se == NULL)
2780 {
2781 ERROR ("network plugin: malloc failed.");
2782 return (-1);
2783 }
2784 sockent_init (se, SOCKENT_TYPE_CLIENT);
2786 se->node = strdup (ci->values[0].value.string);
2787 if (ci->values_num >= 2)
2788 se->service = strdup (ci->values[1].value.string);
2790 for (i = 0; i < ci->children_num; i++)
2791 {
2792 oconfig_item_t *child = ci->children + i;
2794 #if HAVE_LIBGCRYPT
2795 if (strcasecmp ("Username", child->key) == 0)
2796 network_config_set_string (child, &se->data.client.username);
2797 else if (strcasecmp ("Password", child->key) == 0)
2798 network_config_set_string (child, &se->data.client.password);
2799 else if (strcasecmp ("SecurityLevel", child->key) == 0)
2800 network_config_set_security_level (child,
2801 &se->data.client.security_level);
2802 else
2803 #endif /* HAVE_LIBGCRYPT */
2804 {
2805 WARNING ("network plugin: Option `%s' is not allowed here.",
2806 child->key);
2807 }
2808 }
2810 #if HAVE_LIBGCRYPT
2811 if ((se->data.client.security_level > SECURITY_LEVEL_NONE)
2812 && ((se->data.client.username == NULL)
2813 || (se->data.client.password == NULL)))
2814 {
2815 ERROR ("network plugin: A security level higher than `none' was "
2816 "requested, but no Username or Password option was given. "
2817 "Cowardly refusing to open this socket!");
2818 sockent_destroy (se);
2819 return (-1);
2820 }
2821 #endif /* HAVE_LIBGCRYPT */
2823 status = sockent_open (se);
2824 if (status != 0)
2825 {
2826 ERROR ("network plugin: network_config_add_server: sockent_open failed.");
2827 sockent_destroy (se);
2828 return (-1);
2829 }
2831 status = sockent_add (se);
2832 if (status != 0)
2833 {
2834 ERROR ("network plugin: network_config_add_server: sockent_add failed.");
2835 sockent_destroy (se);
2836 return (-1);
2837 }
2839 return (0);
2840 } /* }}} int network_config_add_server */
2842 static int network_config (oconfig_item_t *ci) /* {{{ */
2843 {
2844 int i;
2846 for (i = 0; i < ci->children_num; i++)
2847 {
2848 oconfig_item_t *child = ci->children + i;
2850 if (strcasecmp ("Listen", child->key) == 0)
2851 network_config_add_listen (child);
2852 else if (strcasecmp ("Server", child->key) == 0)
2853 network_config_add_server (child);
2854 else if (strcasecmp ("TimeToLive", child->key) == 0)
2855 network_config_set_ttl (child);
2856 else if (strcasecmp ("MaxPacketSize", child->key) == 0)
2857 network_config_set_buffer_size (child);
2858 else if (strcasecmp ("Forward", child->key) == 0)
2859 network_config_set_boolean (child, &network_config_forward);
2860 else if (strcasecmp ("ReportStats", child->key) == 0)
2861 network_config_set_boolean (child, &network_config_stats);
2862 else if (strcasecmp ("CacheFlush", child->key) == 0)
2863 /* no op for backwards compatibility only */;
2864 else
2865 {
2866 WARNING ("network plugin: Option `%s' is not allowed here.",
2867 child->key);
2868 }
2869 }
2871 return (0);
2872 } /* }}} int network_config */
2874 static int network_notification (const notification_t *n,
2875 user_data_t __attribute__((unused)) *user_data)
2876 {
2877 char buffer[network_config_packet_size];
2878 char *buffer_ptr = buffer;
2879 int buffer_free = sizeof (buffer);
2880 int status;
2882 memset (buffer, '\0', sizeof (buffer));
2885 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_TIME,
2886 (uint64_t) n->time);
2887 if (status != 0)
2888 return (-1);
2890 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_SEVERITY,
2891 (uint64_t) n->severity);
2892 if (status != 0)
2893 return (-1);
2895 if (strlen (n->host) > 0)
2896 {
2897 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_HOST,
2898 n->host, strlen (n->host));
2899 if (status != 0)
2900 return (-1);
2901 }
2903 if (strlen (n->plugin) > 0)
2904 {
2905 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_PLUGIN,
2906 n->plugin, strlen (n->plugin));
2907 if (status != 0)
2908 return (-1);
2909 }
2911 if (strlen (n->plugin_instance) > 0)
2912 {
2913 status = write_part_string (&buffer_ptr, &buffer_free,
2914 TYPE_PLUGIN_INSTANCE,
2915 n->plugin_instance, strlen (n->plugin_instance));
2916 if (status != 0)
2917 return (-1);
2918 }
2920 if (strlen (n->type) > 0)
2921 {
2922 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE,
2923 n->type, strlen (n->type));
2924 if (status != 0)
2925 return (-1);
2926 }
2928 if (strlen (n->type_instance) > 0)
2929 {
2930 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
2931 n->type_instance, strlen (n->type_instance));
2932 if (status != 0)
2933 return (-1);
2934 }
2936 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_MESSAGE,
2937 n->message, strlen (n->message));
2938 if (status != 0)
2939 return (-1);
2941 network_send_buffer (buffer, sizeof (buffer) - buffer_free);
2943 return (0);
2944 } /* int network_notification */
2946 static int network_shutdown (void)
2947 {
2948 listen_loop++;
2950 /* Kill the listening thread */
2951 if (receive_thread_running != 0)
2952 {
2953 INFO ("network plugin: Stopping receive thread.");
2954 pthread_kill (receive_thread_id, SIGTERM);
2955 pthread_join (receive_thread_id, NULL /* no return value */);
2956 memset (&receive_thread_id, 0, sizeof (receive_thread_id));
2957 receive_thread_running = 0;
2958 }
2960 /* Shutdown the dispatching thread */
2961 if (dispatch_thread_running != 0)
2962 {
2963 INFO ("network plugin: Stopping dispatch thread.");
2964 pthread_mutex_lock (&receive_list_lock);
2965 pthread_cond_broadcast (&receive_list_cond);
2966 pthread_mutex_unlock (&receive_list_lock);
2967 pthread_join (dispatch_thread_id, /* ret = */ NULL);
2968 dispatch_thread_running = 0;
2969 }
2971 sockent_destroy (listen_sockets);
2973 if (send_buffer_fill > 0)
2974 flush_buffer ();
2976 sfree (send_buffer);
2978 /* TODO: Close `sending_sockets' */
2980 plugin_unregister_config ("network");
2981 plugin_unregister_init ("network");
2982 plugin_unregister_write ("network");
2983 plugin_unregister_shutdown ("network");
2985 return (0);
2986 } /* int network_shutdown */
2988 static int network_stats_read (void) /* {{{ */
2989 {
2990 uint64_t copy_octets_rx;
2991 uint64_t copy_octets_tx;
2992 uint64_t copy_packets_rx;
2993 uint64_t copy_packets_tx;
2994 uint64_t copy_values_dispatched;
2995 uint64_t copy_values_not_dispatched;
2996 uint64_t copy_values_sent;
2997 uint64_t copy_values_not_sent;
2998 uint64_t copy_receive_list_length;
2999 value_list_t vl = VALUE_LIST_INIT;
3000 value_t values[2];
3002 copy_octets_rx = stats_octets_rx;
3003 copy_octets_tx = stats_octets_tx;
3004 copy_packets_rx = stats_packets_rx;
3005 copy_packets_tx = stats_packets_tx;
3006 copy_values_dispatched = stats_values_dispatched;
3007 copy_values_not_dispatched = stats_values_not_dispatched;
3008 copy_values_sent = stats_values_sent;
3009 copy_values_not_sent = stats_values_not_sent;
3010 copy_receive_list_length = receive_list_length;
3012 /* Initialize `vl' */
3013 vl.values = values;
3014 vl.values_len = 2;
3015 vl.time = 0;
3016 vl.interval = interval_g;
3017 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
3018 sstrncpy (vl.plugin, "network", sizeof (vl.plugin));
3020 /* Octets received / sent */
3021 vl.values[0].counter = (counter_t) copy_octets_rx;
3022 vl.values[1].counter = (counter_t) copy_octets_tx;
3023 sstrncpy (vl.type, "if_octets", sizeof (vl.type));
3024 plugin_dispatch_values (&vl);
3026 /* Packets received / send */
3027 vl.values[0].counter = (counter_t) copy_packets_rx;
3028 vl.values[1].counter = (counter_t) copy_packets_tx;
3029 sstrncpy (vl.type, "if_packets", sizeof (vl.type));
3030 plugin_dispatch_values (&vl);
3032 /* Values (not) dispatched and (not) send */
3033 sstrncpy (vl.type, "total_values", sizeof (vl.type));
3034 vl.values_len = 1;
3036 vl.values[0].derive = (derive_t) copy_values_dispatched;
3037 sstrncpy (vl.type_instance, "dispatch-accepted",
3038 sizeof (vl.type_instance));
3039 plugin_dispatch_values (&vl);
3041 vl.values[0].derive = (derive_t) copy_values_not_dispatched;
3042 sstrncpy (vl.type_instance, "dispatch-rejected",
3043 sizeof (vl.type_instance));
3044 plugin_dispatch_values (&vl);
3046 vl.values[0].derive = (derive_t) copy_values_sent;
3047 sstrncpy (vl.type_instance, "send-accepted",
3048 sizeof (vl.type_instance));
3049 plugin_dispatch_values (&vl);
3051 vl.values[0].derive = (derive_t) copy_values_not_sent;
3052 sstrncpy (vl.type_instance, "send-rejected",
3053 sizeof (vl.type_instance));
3054 plugin_dispatch_values (&vl);
3056 /* Receive queue length */
3057 vl.values[0].gauge = (gauge_t) copy_receive_list_length;
3058 sstrncpy (vl.type, "queue_length", sizeof (vl.type));
3059 vl.type_instance[0] = 0;
3060 plugin_dispatch_values (&vl);
3062 return (0);
3063 } /* }}} int network_stats_read */
3065 static int network_init (void)
3066 {
3067 static _Bool have_init = false;
3069 /* Check if we were already initialized. If so, just return - there's
3070 * nothing more to do (for now, that is). */
3071 if (have_init)
3072 return (0);
3073 have_init = true;
3075 #if HAVE_LIBGCRYPT
3076 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
3077 gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
3078 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
3079 #endif
3081 if (network_config_stats != 0)
3082 plugin_register_read ("network", network_stats_read);
3084 plugin_register_shutdown ("network", network_shutdown);
3086 send_buffer = malloc (network_config_packet_size);
3087 if (send_buffer == NULL)
3088 {
3089 ERROR ("network plugin: malloc failed.");
3090 return (-1);
3091 }
3092 network_init_buffer ();
3094 /* setup socket(s) and so on */
3095 if (sending_sockets != NULL)
3096 {
3097 plugin_register_write ("network", network_write,
3098 /* user_data = */ NULL);
3099 plugin_register_notification ("network", network_notification,
3100 /* user_data = */ NULL);
3101 }
3103 /* If no threads need to be started, return here. */
3104 if ((listen_sockets_num == 0)
3105 || ((dispatch_thread_running != 0)
3106 && (receive_thread_running != 0)))
3107 return (0);
3109 if (dispatch_thread_running == 0)
3110 {
3111 int status;
3112 status = pthread_create (&dispatch_thread_id,
3113 NULL /* no attributes */,
3114 dispatch_thread,
3115 NULL /* no argument */);
3116 if (status != 0)
3117 {
3118 char errbuf[1024];
3119 ERROR ("network: pthread_create failed: %s",
3120 sstrerror (errno, errbuf,
3121 sizeof (errbuf)));
3122 }
3123 else
3124 {
3125 dispatch_thread_running = 1;
3126 }
3127 }
3129 if (receive_thread_running == 0)
3130 {
3131 int status;
3132 status = pthread_create (&receive_thread_id,
3133 NULL /* no attributes */,
3134 receive_thread,
3135 NULL /* no argument */);
3136 if (status != 0)
3137 {
3138 char errbuf[1024];
3139 ERROR ("network: pthread_create failed: %s",
3140 sstrerror (errno, errbuf,
3141 sizeof (errbuf)));
3142 }
3143 else
3144 {
3145 receive_thread_running = 1;
3146 }
3147 }
3149 return (0);
3150 } /* int network_init */
3152 /*
3153 * The flush option of the network plugin cannot flush individual identifiers.
3154 * All the values are added to a buffer and sent when the buffer is full, the
3155 * requested value may or may not be in there, it's not worth finding out. We
3156 * just send the buffer if `flush' is called - if the requested value was in
3157 * there, good. If not, well, then there is nothing to flush.. -octo
3158 */
3159 static int network_flush (int timeout,
3160 const char __attribute__((unused)) *identifier,
3161 user_data_t __attribute__((unused)) *user_data)
3162 {
3163 pthread_mutex_lock (&send_buffer_lock);
3165 if (send_buffer_fill > 0)
3166 flush_buffer ();
3168 pthread_mutex_unlock (&send_buffer_lock);
3170 return (0);
3171 } /* int network_flush */
3173 void module_register (void)
3174 {
3175 plugin_register_complex_config ("network", network_config);
3176 plugin_register_init ("network", network_init);
3177 plugin_register_flush ("network", network_flush,
3178 /* user_data = */ NULL);
3179 } /* void module_register */
3181 /* vim: set fdm=marker : */