1 /**
2 * collectd - src/network.c
3 * Copyright (C) 2005-2009 Florian octo Forster
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; only version 2 of the License is applicable.
8 *
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
17 *
18 * Authors:
19 * Florian octo Forster <octo at verplant.org>
20 **/
22 #include "collectd.h"
23 #include "plugin.h"
24 #include "common.h"
25 #include "configfile.h"
26 #include "utils_avltree.h"
28 #include "network.h"
30 #if HAVE_PTHREAD_H
31 # include <pthread.h>
32 #endif
33 #if HAVE_SYS_SOCKET_H
34 # include <sys/socket.h>
35 #endif
36 #if HAVE_NETDB_H
37 # include <netdb.h>
38 #endif
39 #if HAVE_NETINET_IN_H
40 # include <netinet/in.h>
41 #endif
42 #if HAVE_ARPA_INET_H
43 # include <arpa/inet.h>
44 #endif
45 #if HAVE_POLL_H
46 # include <poll.h>
47 #endif
49 #if HAVE_GCRYPT_H
50 # include <gcrypt.h>
51 #endif
53 /* 1500 - 40 - 8 = Ethernet packet - IPv6 header - UDP header */
54 /* #define BUFF_SIZE 1452 */
56 #ifndef IPV6_ADD_MEMBERSHIP
57 # ifdef IPV6_JOIN_GROUP
58 # define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
59 # else
60 # error "Neither IP_ADD_MEMBERSHIP nor IPV6_JOIN_GROUP is defined"
61 # endif
62 #endif /* !IP_ADD_MEMBERSHIP */
64 /* Buffer size to allocate. */
65 #define BUFF_SIZE 1024
67 /*
68 * Maximum size required for encryption / signing:
69 * Type/length: 4
70 * IV 16
71 * Hash/orig length: 22
72 * Padding (up to): 15
73 * --------------------
74 * 57
75 */
76 #define BUFF_SIG_SIZE 57
78 /*
79 * Private data types
80 */
81 typedef struct sockent
82 {
83 int fd;
84 struct sockaddr_storage *addr;
85 socklen_t addrlen;
87 #define SECURITY_LEVEL_NONE 0
88 #if HAVE_GCRYPT_H
89 # define SECURITY_LEVEL_SIGN 1
90 # define SECURITY_LEVEL_ENCRYPT 2
91 int security_level;
92 char *shared_secret;
93 unsigned char shared_secret_hash[32];
94 gcry_cipher_hd_t cypher;
95 #endif /* HAVE_GCRYPT_H */
97 struct sockent *next;
98 } sockent_t;
100 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
101 * 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
102 * +-------+-----------------------+-------------------------------+
103 * ! Ver. ! ! Length !
104 * +-------+-----------------------+-------------------------------+
105 */
106 struct part_header_s
107 {
108 uint16_t type;
109 uint16_t length;
110 };
111 typedef struct part_header_s part_header_t;
113 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
114 * 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
115 * +-------------------------------+-------------------------------+
116 * ! Type ! Length !
117 * +-------------------------------+-------------------------------+
118 * : (Length - 4) Bytes :
119 * +---------------------------------------------------------------+
120 */
121 struct part_string_s
122 {
123 part_header_t *head;
124 char *value;
125 };
126 typedef struct part_string_s part_string_t;
128 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
129 * 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
130 * +-------------------------------+-------------------------------+
131 * ! Type ! Length !
132 * +-------------------------------+-------------------------------+
133 * : (Length - 4 == 2 || 4 || 8) Bytes :
134 * +---------------------------------------------------------------+
135 */
136 struct part_number_s
137 {
138 part_header_t *head;
139 uint64_t *value;
140 };
141 typedef struct part_number_s part_number_t;
143 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
144 * 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
145 * +-------------------------------+-------------------------------+
146 * ! Type ! Length !
147 * +-------------------------------+---------------+---------------+
148 * ! Num of values ! Type0 ! Type1 !
149 * +-------------------------------+---------------+---------------+
150 * ! Value0 !
151 * ! !
152 * +---------------------------------------------------------------+
153 * ! Value1 !
154 * ! !
155 * +---------------------------------------------------------------+
156 */
157 struct part_values_s
158 {
159 part_header_t *head;
160 uint16_t *num_values;
161 uint8_t *values_types;
162 value_t *values;
163 };
164 typedef struct part_values_s part_values_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 * ! Hash (Bits 0 - 31) !
172 * : : :
173 * ! Hash (Bits 224 - 255) !
174 * +---------------------------------------------------------------+
175 */
176 #define PART_SIGNATURE_SHA256_SIZE 36
177 struct part_signature_sha256_s
178 {
179 part_header_t head;
180 unsigned char hash[32];
181 };
182 typedef struct part_signature_sha256_s part_signature_sha256_t;
184 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
185 * 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
186 * +-------------------------------+-------------------------------+
187 * ! Type ! Length !
188 * +-------------------------------+-------------------------------+
189 * ! Original length ! Padding (0 - 15 bytes) !
190 * +-------------------------------+-------------------------------+
191 * ! Hash (Bits 0 - 31) !
192 * : : :
193 * ! Hash (Bits 128 - 159) !
194 * +---------------------------------------------------------------+
195 */
196 /* Size without padding */
197 #define PART_ENCRYPTION_AES256_SIZE 42
198 #define PART_ENCRYPTION_AES256_UNENCR_SIZE 20
199 struct part_encryption_aes256_s
200 {
201 part_header_t head;
202 unsigned char iv[16];
203 uint16_t orig_length;
204 unsigned char hash[20];
205 unsigned char padding[15];
206 };
207 typedef struct part_encryption_aes256_s part_encryption_aes256_t;
209 struct receive_list_entry_s
210 {
211 char data[BUFF_SIZE];
212 int data_len;
213 int fd;
214 struct receive_list_entry_s *next;
215 };
216 typedef struct receive_list_entry_s receive_list_entry_t;
218 /*
219 * Private variables
220 */
221 static int network_config_ttl = 0;
222 static int network_config_forward = 0;
224 static sockent_t *sending_sockets = NULL;
226 static receive_list_entry_t *receive_list_head = NULL;
227 static receive_list_entry_t *receive_list_tail = NULL;
228 static pthread_mutex_t receive_list_lock = PTHREAD_MUTEX_INITIALIZER;
229 static pthread_cond_t receive_list_cond = PTHREAD_COND_INITIALIZER;
231 static sockent_t *listen_sockets = NULL;
232 static struct pollfd *listen_sockets_pollfd = NULL;
233 static int listen_sockets_num = 0;
235 /* The receive and dispatch threads will run as long as `listen_loop' is set to
236 * zero. */
237 static int listen_loop = 0;
238 static int receive_thread_running = 0;
239 static pthread_t receive_thread_id;
240 static int dispatch_thread_running = 0;
241 static pthread_t dispatch_thread_id;
243 /* Buffer in which to-be-sent network packets are constructed. */
244 static char send_buffer[BUFF_SIZE];
245 static char *send_buffer_ptr;
246 static int send_buffer_fill;
247 static value_list_t send_buffer_vl = VALUE_LIST_STATIC;
248 static pthread_mutex_t send_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
250 /* In this cache we store all the values we received, so we can send out only
251 * those values which were *not* received via the network plugin, too. This is
252 * used for the `Forward false' option. */
253 static c_avl_tree_t *cache_tree = NULL;
254 static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
255 static time_t cache_flush_last = 0;
256 static int cache_flush_interval = 1800;
258 /*
259 * Private functions
260 */
261 static int cache_flush (void)
262 {
263 char **keys = NULL;
264 int keys_num = 0;
266 char **tmp;
267 int i;
269 char *key;
270 time_t *value;
271 c_avl_iterator_t *iter;
273 time_t curtime = time (NULL);
275 iter = c_avl_get_iterator (cache_tree);
276 while (c_avl_iterator_next (iter, (void *) &key, (void *) &value) == 0)
277 {
278 if ((curtime - *value) <= cache_flush_interval)
279 continue;
280 tmp = (char **) realloc (keys,
281 (keys_num + 1) * sizeof (char *));
282 if (tmp == NULL)
283 {
284 sfree (keys);
285 c_avl_iterator_destroy (iter);
286 ERROR ("network plugin: cache_flush: realloc"
287 " failed.");
288 return (-1);
289 }
290 keys = tmp;
291 keys[keys_num] = key;
292 keys_num++;
293 } /* while (c_avl_iterator_next) */
294 c_avl_iterator_destroy (iter);
296 for (i = 0; i < keys_num; i++)
297 {
298 if (c_avl_remove (cache_tree, keys[i], (void *) &key,
299 (void *) &value) != 0)
300 {
301 WARNING ("network plugin: cache_flush: c_avl_remove"
302 " (%s) failed.", keys[i]);
303 continue;
304 }
306 sfree (key);
307 sfree (value);
308 }
310 sfree (keys);
312 DEBUG ("network plugin: cache_flush: Removed %i %s",
313 keys_num, (keys_num == 1) ? "entry" : "entries");
314 cache_flush_last = curtime;
315 return (0);
316 } /* int cache_flush */
318 static int cache_check (const value_list_t *vl)
319 {
320 char key[1024];
321 time_t *value = NULL;
322 int retval = -1;
324 if (cache_tree == NULL)
325 return (-1);
327 if (format_name (key, sizeof (key), vl->host, vl->plugin,
328 vl->plugin_instance, vl->type, vl->type_instance))
329 return (-1);
331 pthread_mutex_lock (&cache_lock);
333 if (c_avl_get (cache_tree, key, (void *) &value) == 0)
334 {
335 if (*value < vl->time)
336 {
337 *value = vl->time;
338 retval = 0;
339 }
340 else
341 {
342 DEBUG ("network plugin: cache_check: *value = %i >= vl->time = %i",
343 (int) *value, (int) vl->time);
344 retval = 1;
345 }
346 }
347 else
348 {
349 char *key_copy = strdup (key);
350 value = malloc (sizeof (time_t));
351 if ((key_copy != NULL) && (value != NULL))
352 {
353 *value = vl->time;
354 c_avl_insert (cache_tree, key_copy, value);
355 retval = 0;
356 }
357 else
358 {
359 sfree (key_copy);
360 sfree (value);
361 }
362 }
364 if ((time (NULL) - cache_flush_last) > cache_flush_interval)
365 cache_flush ();
367 pthread_mutex_unlock (&cache_lock);
369 return (retval);
370 } /* int cache_check */
372 #if HAVE_GCRYPT_H
373 static gcry_cipher_hd_t network_get_aes256_cypher (sockent_t *se, /* {{{ */
374 const void *iv, size_t iv_size)
375 {
376 gcry_error_t err;
378 if (se->cypher == NULL)
379 {
380 err = gcry_cipher_open (&se->cypher,
381 GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CBC, /* flags = */ 0);
382 if (err != 0)
383 {
384 ERROR ("network plugin: gcry_cipher_open returned: %s",
385 gcry_strerror (err));
386 se->cypher = NULL;
387 return (NULL);
388 }
389 }
390 else
391 {
392 gcry_cipher_reset (se->cypher);
393 }
394 assert (se->cypher != NULL);
396 err = gcry_cipher_setkey (se->cypher,
397 se->shared_secret_hash, sizeof (se->shared_secret_hash));
398 if (err != 0)
399 {
400 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
401 gcry_strerror (err));
402 gcry_cipher_close (se->cypher);
403 se->cypher = NULL;
404 return (NULL);
405 }
407 err = gcry_cipher_setiv (se->cypher, iv, iv_size);
408 if (err != 0)
409 {
410 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
411 gcry_strerror (err));
412 gcry_cipher_close (se->cypher);
413 se->cypher = NULL;
414 return (NULL);
415 }
417 return (se->cypher);
418 } /* }}} int network_get_aes256_cypher */
419 #endif /* HAVE_GCRYPT_H */
421 static int write_part_values (char **ret_buffer, int *ret_buffer_len,
422 const data_set_t *ds, const value_list_t *vl)
423 {
424 char *packet_ptr;
425 int packet_len;
426 int num_values;
428 part_header_t pkg_ph;
429 uint16_t pkg_num_values;
430 uint8_t *pkg_values_types;
431 value_t *pkg_values;
433 int offset;
434 int i;
436 num_values = vl->values_len;
437 packet_len = sizeof (part_header_t) + sizeof (uint16_t)
438 + (num_values * sizeof (uint8_t))
439 + (num_values * sizeof (value_t));
441 if (*ret_buffer_len < packet_len)
442 return (-1);
444 pkg_values_types = (uint8_t *) malloc (num_values * sizeof (uint8_t));
445 if (pkg_values_types == NULL)
446 {
447 ERROR ("network plugin: write_part_values: malloc failed.");
448 return (-1);
449 }
451 pkg_values = (value_t *) malloc (num_values * sizeof (value_t));
452 if (pkg_values == NULL)
453 {
454 free (pkg_values_types);
455 ERROR ("network plugin: write_part_values: malloc failed.");
456 return (-1);
457 }
459 pkg_ph.type = htons (TYPE_VALUES);
460 pkg_ph.length = htons (packet_len);
462 pkg_num_values = htons ((uint16_t) vl->values_len);
464 for (i = 0; i < num_values; i++)
465 {
466 if (ds->ds[i].type == DS_TYPE_COUNTER)
467 {
468 pkg_values_types[i] = DS_TYPE_COUNTER;
469 pkg_values[i].counter = htonll (vl->values[i].counter);
470 }
471 else
472 {
473 pkg_values_types[i] = DS_TYPE_GAUGE;
474 pkg_values[i].gauge = htond (vl->values[i].gauge);
475 }
476 }
478 /*
479 * Use `memcpy' to write everything to the buffer, because the pointer
480 * may be unaligned and some architectures, such as SPARC, can't handle
481 * that.
482 */
483 packet_ptr = *ret_buffer;
484 offset = 0;
485 memcpy (packet_ptr + offset, &pkg_ph, sizeof (pkg_ph));
486 offset += sizeof (pkg_ph);
487 memcpy (packet_ptr + offset, &pkg_num_values, sizeof (pkg_num_values));
488 offset += sizeof (pkg_num_values);
489 memcpy (packet_ptr + offset, pkg_values_types, num_values * sizeof (uint8_t));
490 offset += num_values * sizeof (uint8_t);
491 memcpy (packet_ptr + offset, pkg_values, num_values * sizeof (value_t));
492 offset += num_values * sizeof (value_t);
494 assert (offset == packet_len);
496 *ret_buffer = packet_ptr + packet_len;
497 *ret_buffer_len -= packet_len;
499 free (pkg_values_types);
500 free (pkg_values);
502 return (0);
503 } /* int write_part_values */
505 static int write_part_number (char **ret_buffer, int *ret_buffer_len,
506 int type, uint64_t value)
507 {
508 char *packet_ptr;
509 int packet_len;
511 part_header_t pkg_head;
512 uint64_t pkg_value;
514 int offset;
516 packet_len = sizeof (pkg_head) + sizeof (pkg_value);
518 if (*ret_buffer_len < packet_len)
519 return (-1);
521 pkg_head.type = htons (type);
522 pkg_head.length = htons (packet_len);
523 pkg_value = htonll (value);
525 packet_ptr = *ret_buffer;
526 offset = 0;
527 memcpy (packet_ptr + offset, &pkg_head, sizeof (pkg_head));
528 offset += sizeof (pkg_head);
529 memcpy (packet_ptr + offset, &pkg_value, sizeof (pkg_value));
530 offset += sizeof (pkg_value);
532 assert (offset == packet_len);
534 *ret_buffer = packet_ptr + packet_len;
535 *ret_buffer_len -= packet_len;
537 return (0);
538 } /* int write_part_number */
540 static int write_part_string (char **ret_buffer, int *ret_buffer_len,
541 int type, const char *str, int str_len)
542 {
543 char *buffer;
544 int buffer_len;
546 uint16_t pkg_type;
547 uint16_t pkg_length;
549 int offset;
551 buffer_len = 2 * sizeof (uint16_t) + str_len + 1;
552 if (*ret_buffer_len < buffer_len)
553 return (-1);
555 pkg_type = htons (type);
556 pkg_length = htons (buffer_len);
558 buffer = *ret_buffer;
559 offset = 0;
560 memcpy (buffer + offset, (void *) &pkg_type, sizeof (pkg_type));
561 offset += sizeof (pkg_type);
562 memcpy (buffer + offset, (void *) &pkg_length, sizeof (pkg_length));
563 offset += sizeof (pkg_length);
564 memcpy (buffer + offset, str, str_len);
565 offset += str_len;
566 memset (buffer + offset, '\0', 1);
567 offset += 1;
569 assert (offset == buffer_len);
571 *ret_buffer = buffer + buffer_len;
572 *ret_buffer_len -= buffer_len;
574 return (0);
575 } /* int write_part_string */
577 static int parse_part_values (void **ret_buffer, size_t *ret_buffer_len,
578 value_t **ret_values, int *ret_num_values)
579 {
580 char *buffer = *ret_buffer;
581 size_t buffer_len = *ret_buffer_len;
583 uint16_t tmp16;
584 size_t exp_size;
585 int i;
587 uint16_t pkg_length;
588 uint16_t pkg_type;
589 uint16_t pkg_numval;
591 uint8_t *pkg_types;
592 value_t *pkg_values;
594 if (buffer_len < 15)
595 {
596 NOTICE ("network plugin: packet is too short: "
597 "buffer_len = %zu", buffer_len);
598 return (-1);
599 }
601 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
602 buffer += sizeof (tmp16);
603 pkg_type = ntohs (tmp16);
605 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
606 buffer += sizeof (tmp16);
607 pkg_length = ntohs (tmp16);
609 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
610 buffer += sizeof (tmp16);
611 pkg_numval = ntohs (tmp16);
613 assert (pkg_type == TYPE_VALUES);
615 exp_size = 3 * sizeof (uint16_t)
616 + pkg_numval * (sizeof (uint8_t) + sizeof (value_t));
617 if ((buffer_len < 0) || (buffer_len < exp_size))
618 {
619 WARNING ("network plugin: parse_part_values: "
620 "Packet too short: "
621 "Chunk of size %zu expected, "
622 "but buffer has only %zu bytes left.",
623 exp_size, buffer_len);
624 return (-1);
625 }
627 if (pkg_length != exp_size)
628 {
629 WARNING ("network plugin: parse_part_values: "
630 "Length and number of values "
631 "in the packet don't match.");
632 return (-1);
633 }
635 pkg_types = (uint8_t *) malloc (pkg_numval * sizeof (uint8_t));
636 pkg_values = (value_t *) malloc (pkg_numval * sizeof (value_t));
637 if ((pkg_types == NULL) || (pkg_values == NULL))
638 {
639 sfree (pkg_types);
640 sfree (pkg_values);
641 ERROR ("network plugin: parse_part_values: malloc failed.");
642 return (-1);
643 }
645 memcpy ((void *) pkg_types, (void *) buffer, pkg_numval * sizeof (uint8_t));
646 buffer += pkg_numval * sizeof (uint8_t);
647 memcpy ((void *) pkg_values, (void *) buffer, pkg_numval * sizeof (value_t));
648 buffer += pkg_numval * sizeof (value_t);
650 for (i = 0; i < pkg_numval; i++)
651 {
652 if (pkg_types[i] == DS_TYPE_COUNTER)
653 pkg_values[i].counter = ntohll (pkg_values[i].counter);
654 else if (pkg_types[i] == DS_TYPE_GAUGE)
655 pkg_values[i].gauge = ntohd (pkg_values[i].gauge);
656 }
658 *ret_buffer = buffer;
659 *ret_buffer_len = buffer_len - pkg_length;
660 *ret_num_values = pkg_numval;
661 *ret_values = pkg_values;
663 sfree (pkg_types);
665 return (0);
666 } /* int parse_part_values */
668 static int parse_part_number (void **ret_buffer, size_t *ret_buffer_len,
669 uint64_t *value)
670 {
671 char *buffer = *ret_buffer;
672 size_t buffer_len = *ret_buffer_len;
674 uint16_t tmp16;
675 uint64_t tmp64;
676 size_t exp_size = 2 * sizeof (uint16_t) + sizeof (uint64_t);
678 uint16_t pkg_length;
679 uint16_t pkg_type;
681 if ((buffer_len < 0) || ((size_t) buffer_len < exp_size))
682 {
683 WARNING ("network plugin: parse_part_number: "
684 "Packet too short: "
685 "Chunk of size %zu expected, "
686 "but buffer has only %zu bytes left.",
687 exp_size, buffer_len);
688 return (-1);
689 }
691 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
692 buffer += sizeof (tmp16);
693 pkg_type = ntohs (tmp16);
695 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
696 buffer += sizeof (tmp16);
697 pkg_length = ntohs (tmp16);
699 memcpy ((void *) &tmp64, buffer, sizeof (tmp64));
700 buffer += sizeof (tmp64);
701 *value = ntohll (tmp64);
703 *ret_buffer = buffer;
704 *ret_buffer_len = buffer_len - pkg_length;
706 return (0);
707 } /* int parse_part_number */
709 static int parse_part_string (void **ret_buffer, size_t *ret_buffer_len,
710 char *output, int output_len)
711 {
712 char *buffer = *ret_buffer;
713 size_t buffer_len = *ret_buffer_len;
715 uint16_t tmp16;
716 size_t header_size = 2 * sizeof (uint16_t);
718 uint16_t pkg_length;
719 uint16_t pkg_type;
721 if ((buffer_len < 0) || (buffer_len < header_size))
722 {
723 WARNING ("network plugin: parse_part_string: "
724 "Packet too short: "
725 "Chunk of at least size %zu expected, "
726 "but buffer has only %zu bytes left.",
727 header_size, buffer_len);
728 return (-1);
729 }
731 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
732 buffer += sizeof (tmp16);
733 pkg_type = ntohs (tmp16);
735 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
736 buffer += sizeof (tmp16);
737 pkg_length = ntohs (tmp16);
739 /* Check that packet fits in the input buffer */
740 if (pkg_length > buffer_len)
741 {
742 WARNING ("network plugin: parse_part_string: "
743 "Packet too big: "
744 "Chunk of size %"PRIu16" received, "
745 "but buffer has only %zu bytes left.",
746 pkg_length, buffer_len);
747 return (-1);
748 }
750 /* Check that pkg_length is in the valid range */
751 if (pkg_length <= header_size)
752 {
753 WARNING ("network plugin: parse_part_string: "
754 "Packet too short: "
755 "Header claims this packet is only %hu "
756 "bytes long.", pkg_length);
757 return (-1);
758 }
760 /* Check that the package data fits into the output buffer.
761 * The previous if-statement ensures that:
762 * `pkg_length > header_size' */
763 if ((output_len < 0)
764 || ((size_t) output_len < ((size_t) pkg_length - header_size)))
765 {
766 WARNING ("network plugin: parse_part_string: "
767 "Output buffer too small.");
768 return (-1);
769 }
771 /* All sanity checks successfull, let's copy the data over */
772 output_len = pkg_length - header_size;
773 memcpy ((void *) output, (void *) buffer, output_len);
774 buffer += output_len;
776 /* For some very weird reason '\0' doesn't do the trick on SPARC in
777 * this statement. */
778 if (output[output_len - 1] != 0)
779 {
780 WARNING ("network plugin: parse_part_string: "
781 "Received string does not end "
782 "with a NULL-byte.");
783 return (-1);
784 }
786 *ret_buffer = buffer;
787 *ret_buffer_len = buffer_len - pkg_length;
789 return (0);
790 } /* int parse_part_string */
792 /* Forward declaration: parse_part_sign_sha256 and parse_part_encr_aes256 call
793 * parse_packet and vice versa. */
794 #define PP_SIGNED 0x01
795 #define PP_ENCRYPTED 0x02
796 static int parse_packet (sockent_t *se,
797 void *buffer, size_t buffer_size, int flags);
799 #define BUFFER_READ(p,s) do { \
800 memcpy ((p), buffer + buffer_offset, (s)); \
801 buffer_offset += (s); \
802 } while (0)
804 #if HAVE_GCRYPT_H
805 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
806 void **ret_buffer, size_t *ret_buffer_len, int flags)
807 {
808 char *buffer;
809 size_t buffer_len;
810 size_t buffer_offset;
812 part_signature_sha256_t pss;
813 char hash[sizeof (pss.hash)];
815 gcry_md_hd_t hd;
816 gcry_error_t err;
817 unsigned char *hash_ptr;
819 buffer = *ret_buffer;
820 buffer_len = *ret_buffer_len;
821 buffer_offset = 0;
823 if (se->shared_secret == NULL)
824 {
825 NOTICE ("network plugin: Received signed network packet but can't verify "
826 "it because no shared secret has been configured. Will accept it.");
827 return (0);
828 }
830 if (buffer_len < PART_SIGNATURE_SHA256_SIZE)
831 return (-ENOMEM);
833 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
834 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
835 BUFFER_READ (pss.hash, sizeof (pss.hash));
837 assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
839 if (ntohs (pss.head.length) != PART_SIGNATURE_SHA256_SIZE)
840 {
841 ERROR ("network plugin: HMAC-SHA-256 with invalid length received.");
842 return (-1);
843 }
845 hd = NULL;
846 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
847 if (err != 0)
848 {
849 ERROR ("network plugin: Creating HMAC-SHA-256 object failed: %s",
850 gcry_strerror (err));
851 return (-1);
852 }
854 err = gcry_md_setkey (hd, se->shared_secret,
855 strlen (se->shared_secret));
856 if (err != 0)
857 {
858 ERROR ("network plugin: gcry_md_setkey failed: %s",
859 gcry_strerror (err));
860 gcry_md_close (hd);
861 return (-1);
862 }
864 gcry_md_write (hd, buffer + buffer_offset, buffer_len - buffer_offset);
865 hash_ptr = gcry_md_read (hd, GCRY_MD_SHA256);
866 if (hash_ptr == NULL)
867 {
868 ERROR ("network plugin: gcry_md_read failed.");
869 gcry_md_close (hd);
870 return (-1);
871 }
872 memcpy (hash, hash_ptr, sizeof (hash));
874 gcry_md_close (hd);
875 hd = NULL;
877 if (memcmp (pss.hash, hash, sizeof (pss.hash)) != 0)
878 {
879 WARNING ("network plugin: Verifying HMAC-SHA-256 signature failed: "
880 "Hash mismatch.");
881 }
882 else
883 {
884 parse_packet (se, buffer + buffer_offset, buffer_len - buffer_offset,
885 flags | PP_SIGNED);
886 }
888 *ret_buffer = buffer + buffer_len;
889 *ret_buffer_len = 0;
891 return (0);
892 } /* }}} int parse_part_sign_sha256 */
893 /* #endif HAVE_GCRYPT_H */
895 #else /* if !HAVE_GCRYPT_H */
896 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
897 void **ret_buffer, size_t *ret_buffer_size, int flags)
898 {
899 static int warning_has_been_printed = 0;
901 char *buffer;
902 size_t buffer_size;
903 size_t buffer_offset;
905 part_signature_sha256_t pss;
907 buffer = *ret_buffer;
908 buffer_size = *ret_buffer_size;
909 buffer_offset = 0;
911 if (buffer_size < PART_SIGNATURE_SHA256_SIZE)
912 return (-ENOMEM);
914 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
915 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
916 BUFFER_READ (pss.hash, sizeof (pss.hash));
918 assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
920 if (ntohs (pss.head.length) != PART_SIGNATURE_SHA256_SIZE)
921 {
922 ERROR ("network plugin: HMAC-SHA-256 with invalid length received.");
923 return (-1);
924 }
926 if (warning_has_been_printed == 0)
927 {
928 WARNING ("network plugin: Received signed packet, but the network "
929 "plugin was not linked with libgcrypt, so I cannot "
930 "verify the signature. The packet will be accepted.");
931 warning_has_been_printed = 1;
932 }
934 parse_packet (se, buffer + buffer_offset, buffer_size - buffer_offset,
935 flags);
937 *ret_buffer = buffer + buffer_size;
938 *ret_buffer_size = 0;
940 return (0);
941 } /* }}} int parse_part_sign_sha256 */
942 #endif /* !HAVE_GCRYPT_H */
944 #if HAVE_GCRYPT_H
945 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
946 void **ret_buffer, size_t *ret_buffer_len,
947 int flags)
948 {
949 char *buffer = *ret_buffer;
950 size_t buffer_len = *ret_buffer_len;
951 size_t orig_buffer_len;
952 size_t part_size;
953 size_t buffer_offset;
954 size_t padding_size;
955 part_encryption_aes256_t pea;
956 unsigned char hash[sizeof (pea.hash)];
958 gcry_cipher_hd_t cypher;
959 gcry_error_t err;
961 /* Make sure at least the header if available. */
962 if (buffer_len < sizeof (pea))
963 {
964 NOTICE ("network plugin: parse_part_encr_aes256: "
965 "Discarding short packet.");
966 return (-1);
967 }
969 buffer_offset = 0;
971 /* Copy the unencrypted information into `pea'. */
972 BUFFER_READ (&pea.head.type, sizeof (pea.head.type));
973 BUFFER_READ (&pea.head.length, sizeof (pea.head.length));
974 BUFFER_READ (pea.iv, sizeof (pea.iv));
976 /* Check the `part size'. */
977 part_size = ntohs (pea.head.length);
978 if (part_size > buffer_len)
979 {
980 NOTICE ("network plugin: parse_part_encr_aes256: "
981 "Discarding large part.");
982 return (-1);
983 }
985 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv));
986 if (cypher == NULL)
987 return (-1);
989 /* Decrypt the packet in-place */
990 err = gcry_cipher_decrypt (cypher,
991 buffer + PART_ENCRYPTION_AES256_UNENCR_SIZE,
992 part_size - PART_ENCRYPTION_AES256_UNENCR_SIZE,
993 /* in = */ NULL, /* in len = */ 0);
994 if (err != 0)
995 {
996 ERROR ("network plugin: gcry_cipher_decrypt returned: %s",
997 gcry_strerror (err));
998 return (-1);
999 }
1001 /* Figure out the length of the payload and the length of the padding. */
1002 BUFFER_READ (&pea.orig_length, sizeof (pea.orig_length));
1004 orig_buffer_len = ntohs (pea.orig_length);
1005 if (orig_buffer_len > (part_size - PART_ENCRYPTION_AES256_SIZE))
1006 {
1007 ERROR ("network plugin: Decryption failed: Invalid original length.");
1008 return (-1);
1009 }
1011 /* Calculate the size of the `padding' field. */
1012 padding_size = part_size - (orig_buffer_len + PART_ENCRYPTION_AES256_SIZE);
1013 if (padding_size > sizeof (pea.padding))
1014 {
1015 ERROR ("network plugin: Part- and original length "
1016 "differ more than %zu bytes.", sizeof (pea.padding));
1017 return (-1);
1018 }
1020 BUFFER_READ (pea.hash, sizeof (pea.hash));
1022 /* Read the padding. */
1023 BUFFER_READ (pea.padding, padding_size);
1025 /* Check hash sum */
1026 memset (hash, 0, sizeof (hash));
1027 gcry_md_hash_buffer (GCRY_MD_SHA1, hash,
1028 buffer + buffer_offset, orig_buffer_len);
1030 if (memcmp (hash, pea.hash, sizeof (hash)) != 0)
1031 {
1032 ERROR ("network plugin: Decryption failed: Checksum mismatch.");
1033 return (-1);
1034 }
1036 assert ((PART_ENCRYPTION_AES256_SIZE + padding_size + orig_buffer_len)
1037 == part_size);
1039 parse_packet (se, buffer + PART_ENCRYPTION_AES256_SIZE + padding_size,
1040 orig_buffer_len, flags | PP_ENCRYPTED);
1042 /* Update return values */
1043 *ret_buffer = buffer + part_size;
1044 *ret_buffer_len = buffer_len - part_size;
1046 return (0);
1047 } /* }}} int parse_part_encr_aes256 */
1048 /* #endif HAVE_GCRYPT_H */
1050 #else /* if !HAVE_GCRYPT_H */
1051 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1052 void **ret_buffer, size_t *ret_buffer_size, int flags)
1053 {
1054 static int warning_has_been_printed = 0;
1056 char *buffer;
1057 size_t buffer_size;
1058 size_t buffer_offset;
1060 part_header_t ph;
1061 size_t ph_length;
1063 buffer = *ret_buffer;
1064 buffer_size = *ret_buffer_size;
1065 buffer_offset = 0;
1067 /* parse_packet assures this minimum size. */
1068 assert (buffer_size >= (sizeof (ph.type) + sizeof (ph.length)));
1070 BUFFER_READ (&ph.type, sizeof (ph.type));
1071 BUFFER_READ (&ph.length, sizeof (ph.length));
1072 ph_length = ntohs (ph.length);
1074 if ((ph_length < PART_ENCRYPTION_AES256_SIZE)
1075 || (ph_length > buffer_size))
1076 {
1077 ERROR ("network plugin: AES-256 encrypted part "
1078 "with invalid length received.");
1079 return (-1);
1080 }
1082 if (warning_has_been_printed == 0)
1083 {
1084 WARNING ("network plugin: Received encrypted packet, but the network "
1085 "plugin was not linked with libgcrypt, so I cannot "
1086 "decrypt it. The part will be discarded.");
1087 warning_has_been_printed = 1;
1088 }
1090 *ret_buffer += ph_length;
1091 *ret_buffer_size -= ph_length;
1093 return (0);
1094 } /* }}} int parse_part_encr_aes256 */
1095 #endif /* !HAVE_GCRYPT_H */
1097 #undef BUFFER_READ
1099 static int parse_packet (sockent_t *se, /* {{{ */
1100 void *buffer, size_t buffer_size, int flags)
1101 {
1102 int status;
1104 value_list_t vl = VALUE_LIST_INIT;
1105 notification_t n;
1107 #if HAVE_GCRYPT_H
1108 int packet_was_signed = (flags & PP_SIGNED);
1109 int packet_was_encrypted = (flags & PP_ENCRYPTED);
1110 int printed_ignore_warning = 0;
1111 #endif /* HAVE_GCRYPT_H */
1114 memset (&vl, '\0', sizeof (vl));
1115 memset (&n, '\0', sizeof (n));
1116 status = 0;
1118 while ((status == 0) && (0 < buffer_size)
1119 && ((unsigned int) buffer_size > sizeof (part_header_t)))
1120 {
1121 uint16_t pkg_length;
1122 uint16_t pkg_type;
1124 memcpy ((void *) &pkg_type,
1125 (void *) buffer,
1126 sizeof (pkg_type));
1127 memcpy ((void *) &pkg_length,
1128 (void *) (buffer + sizeof (pkg_type)),
1129 sizeof (pkg_length));
1131 pkg_length = ntohs (pkg_length);
1132 pkg_type = ntohs (pkg_type);
1134 if (pkg_length > buffer_size)
1135 break;
1136 /* Ensure that this loop terminates eventually */
1137 if (pkg_length < (2 * sizeof (uint16_t)))
1138 break;
1140 if (pkg_type == TYPE_ENCR_AES256)
1141 {
1142 status = parse_part_encr_aes256 (se,
1143 &buffer, &buffer_size, flags);
1144 if (status != 0)
1145 {
1146 ERROR ("network plugin: Decrypting AES256 "
1147 "part failed "
1148 "with status %i.", status);
1149 break;
1150 }
1151 }
1152 #if HAVE_GCRYPT_H
1153 else if ((se->security_level == SECURITY_LEVEL_ENCRYPT)
1154 && (packet_was_encrypted == 0))
1155 {
1156 if (printed_ignore_warning == 0)
1157 {
1158 INFO ("network plugin: Unencrypted packet or "
1159 "part has been ignored.");
1160 printed_ignore_warning = 1;
1161 }
1162 buffer = ((char *) buffer) + pkg_length;
1163 continue;
1164 }
1165 #endif /* HAVE_GCRYPT_H */
1166 else if (pkg_type == TYPE_SIGN_SHA256)
1167 {
1168 status = parse_part_sign_sha256 (se,
1169 &buffer, &buffer_size, flags);
1170 if (status != 0)
1171 {
1172 ERROR ("network plugin: Verifying HMAC-SHA-256 "
1173 "signature failed "
1174 "with status %i.", status);
1175 break;
1176 }
1177 }
1178 #if HAVE_GCRYPT_H
1179 else if ((se->security_level == SECURITY_LEVEL_SIGN)
1180 && (packet_was_encrypted == 0)
1181 && (packet_was_signed == 0))
1182 {
1183 if (printed_ignore_warning == 0)
1184 {
1185 INFO ("network plugin: Unsigned packet or "
1186 "part has been ignored.");
1187 printed_ignore_warning = 1;
1188 }
1189 buffer = ((char *) buffer) + pkg_length;
1190 continue;
1191 }
1192 #endif /* HAVE_GCRYPT_H */
1193 else if (pkg_type == TYPE_VALUES)
1194 {
1195 status = parse_part_values (&buffer, &buffer_size,
1196 &vl.values, &vl.values_len);
1198 if (status != 0)
1199 break;
1201 if ((vl.time > 0)
1202 && (strlen (vl.host) > 0)
1203 && (strlen (vl.plugin) > 0)
1204 && (strlen (vl.type) > 0)
1205 && (cache_check (&vl) == 0))
1206 {
1207 plugin_dispatch_values (&vl);
1208 }
1209 else
1210 {
1211 DEBUG ("network plugin: parse_packet:"
1212 " NOT dispatching values");
1213 }
1215 sfree (vl.values);
1216 }
1217 else if (pkg_type == TYPE_TIME)
1218 {
1219 uint64_t tmp = 0;
1220 status = parse_part_number (&buffer, &buffer_size,
1221 &tmp);
1222 if (status == 0)
1223 {
1224 vl.time = (time_t) tmp;
1225 n.time = (time_t) tmp;
1226 }
1227 }
1228 else if (pkg_type == TYPE_INTERVAL)
1229 {
1230 uint64_t tmp = 0;
1231 status = parse_part_number (&buffer, &buffer_size,
1232 &tmp);
1233 if (status == 0)
1234 vl.interval = (int) tmp;
1235 }
1236 else if (pkg_type == TYPE_HOST)
1237 {
1238 status = parse_part_string (&buffer, &buffer_size,
1239 vl.host, sizeof (vl.host));
1240 if (status == 0)
1241 sstrncpy (n.host, vl.host, sizeof (n.host));
1242 }
1243 else if (pkg_type == TYPE_PLUGIN)
1244 {
1245 status = parse_part_string (&buffer, &buffer_size,
1246 vl.plugin, sizeof (vl.plugin));
1247 if (status == 0)
1248 sstrncpy (n.plugin, vl.plugin,
1249 sizeof (n.plugin));
1250 }
1251 else if (pkg_type == TYPE_PLUGIN_INSTANCE)
1252 {
1253 status = parse_part_string (&buffer, &buffer_size,
1254 vl.plugin_instance,
1255 sizeof (vl.plugin_instance));
1256 if (status == 0)
1257 sstrncpy (n.plugin_instance,
1258 vl.plugin_instance,
1259 sizeof (n.plugin_instance));
1260 }
1261 else if (pkg_type == TYPE_TYPE)
1262 {
1263 status = parse_part_string (&buffer, &buffer_size,
1264 vl.type, sizeof (vl.type));
1265 if (status == 0)
1266 sstrncpy (n.type, vl.type, sizeof (n.type));
1267 }
1268 else if (pkg_type == TYPE_TYPE_INSTANCE)
1269 {
1270 status = parse_part_string (&buffer, &buffer_size,
1271 vl.type_instance,
1272 sizeof (vl.type_instance));
1273 if (status == 0)
1274 sstrncpy (n.type_instance, vl.type_instance,
1275 sizeof (n.type_instance));
1276 }
1277 else if (pkg_type == TYPE_MESSAGE)
1278 {
1279 status = parse_part_string (&buffer, &buffer_size,
1280 n.message, sizeof (n.message));
1282 if (status != 0)
1283 {
1284 /* do nothing */
1285 }
1286 else if ((n.severity != NOTIF_FAILURE)
1287 && (n.severity != NOTIF_WARNING)
1288 && (n.severity != NOTIF_OKAY))
1289 {
1290 INFO ("network plugin: "
1291 "Ignoring notification with "
1292 "unknown severity %i.",
1293 n.severity);
1294 }
1295 else if (n.time <= 0)
1296 {
1297 INFO ("network plugin: "
1298 "Ignoring notification with "
1299 "time == 0.");
1300 }
1301 else if (strlen (n.message) <= 0)
1302 {
1303 INFO ("network plugin: "
1304 "Ignoring notification with "
1305 "an empty message.");
1306 }
1307 else
1308 {
1309 plugin_dispatch_notification (&n);
1310 }
1311 }
1312 else if (pkg_type == TYPE_SEVERITY)
1313 {
1314 uint64_t tmp = 0;
1315 status = parse_part_number (&buffer, &buffer_size,
1316 &tmp);
1317 if (status == 0)
1318 n.severity = (int) tmp;
1319 }
1320 else
1321 {
1322 DEBUG ("network plugin: parse_packet: Unknown part"
1323 " type: 0x%04hx", pkg_type);
1324 buffer = ((char *) buffer) + pkg_length;
1325 }
1326 } /* while (buffer_size > sizeof (part_header_t)) */
1328 return (status);
1329 } /* }}} int parse_packet */
1331 static void free_sockent (sockent_t *se) /* {{{ */
1332 {
1333 sockent_t *next;
1334 while (se != NULL)
1335 {
1336 next = se->next;
1338 #if HAVE_GCRYPT_H
1339 if (se->cypher != NULL)
1340 {
1341 gcry_cipher_close (se->cypher);
1342 se->cypher = NULL;
1343 }
1344 free (se->shared_secret);
1345 #endif /* HAVE_GCRYPT_H */
1347 free (se->addr);
1348 free (se);
1350 se = next;
1351 }
1352 } /* }}} void free_sockent */
1354 /*
1355 * int network_set_ttl
1356 *
1357 * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
1358 * `IPV6_UNICAST_HOPS', depending on which option is applicable.
1359 *
1360 * The `struct addrinfo' is used to destinguish between unicast and multicast
1361 * sockets.
1362 */
1363 static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
1364 {
1365 DEBUG ("network plugin: network_set_ttl: network_config_ttl = %i;",
1366 network_config_ttl);
1368 if ((network_config_ttl < 1) || (network_config_ttl > 255))
1369 return (-1);
1371 if (ai->ai_family == AF_INET)
1372 {
1373 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1374 int optname;
1376 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1377 optname = IP_MULTICAST_TTL;
1378 else
1379 optname = IP_TTL;
1381 if (setsockopt (se->fd, IPPROTO_IP, optname,
1382 &network_config_ttl,
1383 sizeof (network_config_ttl)) == -1)
1384 {
1385 char errbuf[1024];
1386 ERROR ("setsockopt: %s",
1387 sstrerror (errno, errbuf, sizeof (errbuf)));
1388 return (-1);
1389 }
1390 }
1391 else if (ai->ai_family == AF_INET6)
1392 {
1393 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1394 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1395 int optname;
1397 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1398 optname = IPV6_MULTICAST_HOPS;
1399 else
1400 optname = IPV6_UNICAST_HOPS;
1402 if (setsockopt (se->fd, IPPROTO_IPV6, optname,
1403 &network_config_ttl,
1404 sizeof (network_config_ttl)) == -1)
1405 {
1406 char errbuf[1024];
1407 ERROR ("setsockopt: %s",
1408 sstrerror (errno, errbuf,
1409 sizeof (errbuf)));
1410 return (-1);
1411 }
1412 }
1414 return (0);
1415 } /* int network_set_ttl */
1417 static int network_bind_socket (const sockent_t *se, const struct addrinfo *ai)
1418 {
1419 int loop = 0;
1420 int yes = 1;
1422 /* allow multiple sockets to use the same PORT number */
1423 if (setsockopt(se->fd, SOL_SOCKET, SO_REUSEADDR,
1424 &yes, sizeof(yes)) == -1) {
1425 char errbuf[1024];
1426 ERROR ("setsockopt: %s",
1427 sstrerror (errno, errbuf, sizeof (errbuf)));
1428 return (-1);
1429 }
1431 DEBUG ("fd = %i; calling `bind'", se->fd);
1433 if (bind (se->fd, ai->ai_addr, ai->ai_addrlen) == -1)
1434 {
1435 char errbuf[1024];
1436 ERROR ("bind: %s",
1437 sstrerror (errno, errbuf, sizeof (errbuf)));
1438 return (-1);
1439 }
1441 if (ai->ai_family == AF_INET)
1442 {
1443 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1444 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1445 {
1446 struct ip_mreq mreq;
1448 DEBUG ("fd = %i; IPv4 multicast address found", se->fd);
1450 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1451 mreq.imr_interface.s_addr = htonl (INADDR_ANY);
1453 if (setsockopt (se->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1454 &loop, sizeof (loop)) == -1)
1455 {
1456 char errbuf[1024];
1457 ERROR ("setsockopt: %s",
1458 sstrerror (errno, errbuf,
1459 sizeof (errbuf)));
1460 return (-1);
1461 }
1463 if (setsockopt (se->fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1464 &mreq, sizeof (mreq)) == -1)
1465 {
1466 char errbuf[1024];
1467 ERROR ("setsockopt: %s",
1468 sstrerror (errno, errbuf,
1469 sizeof (errbuf)));
1470 return (-1);
1471 }
1472 }
1473 }
1474 else if (ai->ai_family == AF_INET6)
1475 {
1476 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1477 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1478 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1479 {
1480 struct ipv6_mreq mreq;
1482 DEBUG ("fd = %i; IPv6 multicast address found", se->fd);
1484 memcpy (&mreq.ipv6mr_multiaddr,
1485 &addr->sin6_addr,
1486 sizeof (addr->sin6_addr));
1488 /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
1489 * ipv6mr_interface may be set to zeroes to
1490 * choose the default multicast interface or to
1491 * the index of a particular multicast-capable
1492 * interface if the host is multihomed.
1493 * Membership is associ-associated with a
1494 * single interface; programs running on
1495 * multihomed hosts may need to join the same
1496 * group on more than one interface.*/
1497 mreq.ipv6mr_interface = 0;
1499 if (setsockopt (se->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1500 &loop, sizeof (loop)) == -1)
1501 {
1502 char errbuf[1024];
1503 ERROR ("setsockopt: %s",
1504 sstrerror (errno, errbuf,
1505 sizeof (errbuf)));
1506 return (-1);
1507 }
1509 if (setsockopt (se->fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
1510 &mreq, sizeof (mreq)) == -1)
1511 {
1512 char errbuf[1024];
1513 ERROR ("setsockopt: %s",
1514 sstrerror (errno, errbuf,
1515 sizeof (errbuf)));
1516 return (-1);
1517 }
1518 }
1519 }
1521 return (0);
1522 } /* int network_bind_socket */
1524 #define CREATE_SOCKET_FLAGS_LISTEN 0x0001
1525 static sockent_t *network_create_socket (const char *node, /* {{{ */
1526 const char *service,
1527 const char *shared_secret,
1528 int security_level,
1529 int flags)
1530 {
1531 struct addrinfo ai_hints;
1532 struct addrinfo *ai_list, *ai_ptr;
1533 int ai_return;
1535 sockent_t *se_head = NULL;
1536 sockent_t *se_tail = NULL;
1538 DEBUG ("node = %s, service = %s", node, service);
1540 memset (&ai_hints, '\0', sizeof (ai_hints));
1541 ai_hints.ai_flags = 0;
1542 #ifdef AI_PASSIVE
1543 ai_hints.ai_flags |= AI_PASSIVE;
1544 #endif
1545 #ifdef AI_ADDRCONFIG
1546 ai_hints.ai_flags |= AI_ADDRCONFIG;
1547 #endif
1548 ai_hints.ai_family = AF_UNSPEC;
1549 ai_hints.ai_socktype = SOCK_DGRAM;
1550 ai_hints.ai_protocol = IPPROTO_UDP;
1552 ai_return = getaddrinfo (node, service, &ai_hints, &ai_list);
1553 if (ai_return != 0)
1554 {
1555 char errbuf[1024];
1556 ERROR ("getaddrinfo (%s, %s): %s",
1557 (node == NULL) ? "(null)" : node,
1558 (service == NULL) ? "(null)" : service,
1559 (ai_return == EAI_SYSTEM)
1560 ? sstrerror (errno, errbuf, sizeof (errbuf))
1561 : gai_strerror (ai_return));
1562 return (NULL);
1563 }
1565 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1566 {
1567 sockent_t *se;
1568 int status;
1570 if ((se = (sockent_t *) malloc (sizeof (sockent_t))) == NULL)
1571 {
1572 char errbuf[1024];
1573 ERROR ("malloc: %s",
1574 sstrerror (errno, errbuf,
1575 sizeof (errbuf)));
1576 continue;
1577 }
1579 if ((se->addr = (struct sockaddr_storage *) malloc (sizeof (struct sockaddr_storage))) == NULL)
1580 {
1581 char errbuf[1024];
1582 ERROR ("malloc: %s",
1583 sstrerror (errno, errbuf,
1584 sizeof (errbuf)));
1585 free (se);
1586 continue;
1587 }
1589 assert (sizeof (struct sockaddr_storage) >= ai_ptr->ai_addrlen);
1590 memset (se->addr, '\0', sizeof (struct sockaddr_storage));
1591 memcpy (se->addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1592 se->addrlen = ai_ptr->ai_addrlen;
1594 se->fd = socket (ai_ptr->ai_family,
1595 ai_ptr->ai_socktype,
1596 ai_ptr->ai_protocol);
1597 se->next = NULL;
1599 if (se->fd == -1)
1600 {
1601 char errbuf[1024];
1602 ERROR ("socket: %s",
1603 sstrerror (errno, errbuf,
1604 sizeof (errbuf)));
1605 free (se->addr);
1606 free (se);
1607 continue;
1608 }
1610 if ((flags & CREATE_SOCKET_FLAGS_LISTEN) != 0)
1611 {
1612 status = network_bind_socket (se, ai_ptr);
1613 if (status != 0)
1614 {
1615 close (se->fd);
1616 free (se->addr);
1617 free (se);
1618 continue;
1619 }
1620 }
1621 else /* sending socket */
1622 {
1623 network_set_ttl (se, ai_ptr);
1624 }
1626 #if HAVE_GCRYPT_H
1627 se->security_level = security_level;
1628 se->shared_secret = NULL;
1629 se->cypher = NULL;
1630 if (shared_secret != NULL)
1631 {
1632 se->shared_secret = sstrdup (shared_secret);
1633 assert (se->shared_secret != NULL);
1635 memset (se->shared_secret_hash, 0,
1636 sizeof (se->shared_secret_hash));
1637 gcry_md_hash_buffer (GCRY_MD_SHA256,
1638 se->shared_secret_hash,
1639 se->shared_secret,
1640 strlen (se->shared_secret));
1641 }
1642 #else
1643 /* Make compiler happy */
1644 security_level = 0;
1645 shared_secret = NULL;
1646 #endif /* HAVE_GCRYPT_H */
1648 if (se_tail == NULL)
1649 {
1650 se_head = se;
1651 se_tail = se;
1652 }
1653 else
1654 {
1655 se_tail->next = se;
1656 se_tail = se;
1657 }
1659 /* We don't open more than one write-socket per node/service pair.. */
1660 if ((flags & CREATE_SOCKET_FLAGS_LISTEN) == 0)
1661 break;
1662 }
1664 freeaddrinfo (ai_list);
1666 return (se_head);
1667 } /* }}} sockent_t *network_create_socket */
1669 static sockent_t *network_create_default_socket (int flags) /* {{{ */
1670 {
1671 sockent_t *se_ptr = NULL;
1672 sockent_t *se_head = NULL;
1673 sockent_t *se_tail = NULL;
1675 se_ptr = network_create_socket (NET_DEFAULT_V6_ADDR, NET_DEFAULT_PORT,
1676 /* shared secret = */ NULL, SECURITY_LEVEL_NONE,
1677 flags);
1679 /* Don't send to the same machine in IPv6 and IPv4 if both are available. */
1680 if (((flags & CREATE_SOCKET_FLAGS_LISTEN) == 0) && (se_ptr != NULL))
1681 return (se_ptr);
1683 if (se_ptr != NULL)
1684 {
1685 se_head = se_ptr;
1686 se_tail = se_ptr;
1687 while (se_tail->next != NULL)
1688 se_tail = se_tail->next;
1689 }
1691 se_ptr = network_create_socket (NET_DEFAULT_V4_ADDR, NET_DEFAULT_PORT,
1692 /* shared secret = */ NULL, SECURITY_LEVEL_NONE,
1693 flags);
1695 if (se_tail == NULL)
1696 return (se_ptr);
1698 se_tail->next = se_ptr;
1699 return (se_head);
1700 } /* }}} sockent_t *network_create_default_socket */
1702 static int network_add_listen_socket (const char *node, /* {{{ */
1703 const char *service, const char *shared_secret, int security_level)
1704 {
1705 sockent_t *se;
1706 sockent_t *se_ptr;
1707 int se_num = 0;
1709 int flags;
1711 flags = CREATE_SOCKET_FLAGS_LISTEN;
1713 if (service == NULL)
1714 service = NET_DEFAULT_PORT;
1716 if (node == NULL)
1717 se = network_create_default_socket (flags);
1718 else
1719 se = network_create_socket (node, service,
1720 shared_secret, security_level, flags);
1722 if (se == NULL)
1723 return (-1);
1725 for (se_ptr = se; se_ptr != NULL; se_ptr = se_ptr->next)
1726 se_num++;
1728 listen_sockets_pollfd = realloc (listen_sockets_pollfd,
1729 (listen_sockets_num + se_num)
1730 * sizeof (struct pollfd));
1732 for (se_ptr = se; se_ptr != NULL; se_ptr = se_ptr->next)
1733 {
1734 listen_sockets_pollfd[listen_sockets_num].fd = se_ptr->fd;
1735 listen_sockets_pollfd[listen_sockets_num].events = POLLIN | POLLPRI;
1736 listen_sockets_pollfd[listen_sockets_num].revents = 0;
1737 listen_sockets_num++;
1738 } /* for (se) */
1740 se_ptr = listen_sockets;
1741 while ((se_ptr != NULL) && (se_ptr->next != NULL))
1742 se_ptr = se_ptr->next;
1744 if (se_ptr == NULL)
1745 listen_sockets = se;
1746 else
1747 se_ptr->next = se;
1749 return (0);
1750 } /* }}} int network_add_listen_socket */
1752 static int network_add_sending_socket (const char *node, /* {{{ */
1753 const char *service, const char *shared_secret, int security_level)
1754 {
1755 sockent_t *se;
1756 sockent_t *se_ptr;
1758 if (service == NULL)
1759 service = NET_DEFAULT_PORT;
1761 if (node == NULL)
1762 se = network_create_default_socket (/* flags = */ 0);
1763 else
1764 se = network_create_socket (node, service,
1765 shared_secret, security_level,
1766 /* flags = */ 0);
1768 if (se == NULL)
1769 return (-1);
1771 if (sending_sockets == NULL)
1772 {
1773 sending_sockets = se;
1774 return (0);
1775 }
1777 for (se_ptr = sending_sockets; se_ptr->next != NULL; se_ptr = se_ptr->next)
1778 /* seek end */;
1780 se_ptr->next = se;
1781 return (0);
1782 } /* }}} int network_add_sending_socket */
1784 static void *dispatch_thread (void __attribute__((unused)) *arg) /* {{{ */
1785 {
1786 while (42)
1787 {
1788 receive_list_entry_t *ent;
1789 sockent_t *se;
1791 /* Lock and wait for more data to come in */
1792 pthread_mutex_lock (&receive_list_lock);
1793 while ((listen_loop == 0)
1794 && (receive_list_head == NULL))
1795 pthread_cond_wait (&receive_list_cond, &receive_list_lock);
1797 /* Remove the head entry and unlock */
1798 ent = receive_list_head;
1799 if (ent != NULL)
1800 receive_list_head = ent->next;
1801 pthread_mutex_unlock (&receive_list_lock);
1803 /* Check whether we are supposed to exit. We do NOT check `listen_loop'
1804 * because we dispatch all missing packets before shutting down. */
1805 if (ent == NULL)
1806 break;
1808 /* Look for the correct `sockent_t' */
1809 se = listen_sockets;
1810 while ((se != NULL) && (se->fd != ent->fd))
1811 se = se->next;
1813 if (se == NULL)
1814 {
1815 ERROR ("network plugin: Got packet from FD %i, but can't "
1816 "find an appropriate socket entry.",
1817 ent->fd);
1818 sfree (ent);
1819 continue;
1820 }
1822 parse_packet (se, ent->data, ent->data_len, /* flags = */ 0);
1823 sfree (ent);
1824 } /* while (42) */
1826 return (NULL);
1827 } /* }}} void *dispatch_thread */
1829 static int network_receive (void)
1830 {
1831 char buffer[BUFF_SIZE];
1832 int buffer_len;
1834 int i;
1835 int status;
1837 receive_list_entry_t *private_list_head;
1838 receive_list_entry_t *private_list_tail;
1840 if (listen_sockets_num == 0)
1841 network_add_listen_socket (/* node = */ NULL,
1842 /* service = */ NULL,
1843 /* shared secret = */ NULL,
1844 /* encryption = */ 0);
1846 if (listen_sockets_num == 0)
1847 {
1848 ERROR ("network: Failed to open a listening socket.");
1849 return (-1);
1850 }
1852 private_list_head = NULL;
1853 private_list_tail = NULL;
1855 while (listen_loop == 0)
1856 {
1857 status = poll (listen_sockets_pollfd, listen_sockets_num, -1);
1859 if (status <= 0)
1860 {
1861 char errbuf[1024];
1862 if (errno == EINTR)
1863 continue;
1864 ERROR ("poll failed: %s",
1865 sstrerror (errno, errbuf, sizeof (errbuf)));
1866 return (-1);
1867 }
1869 for (i = 0; (i < listen_sockets_num) && (status > 0); i++)
1870 {
1871 receive_list_entry_t *ent;
1873 if ((listen_sockets_pollfd[i].revents
1874 & (POLLIN | POLLPRI)) == 0)
1875 continue;
1876 status--;
1878 buffer_len = recv (listen_sockets_pollfd[i].fd,
1879 buffer, sizeof (buffer),
1880 0 /* no flags */);
1881 if (buffer_len < 0)
1882 {
1883 char errbuf[1024];
1884 ERROR ("recv failed: %s",
1885 sstrerror (errno, errbuf,
1886 sizeof (errbuf)));
1887 return (-1);
1888 }
1890 /* TODO: Possible performance enhancement: Do not free
1891 * these entries in the dispatch thread but put them in
1892 * another list, so we don't have to allocate more and
1893 * more of these structures. */
1894 ent = malloc (sizeof (receive_list_entry_t));
1895 if (ent == NULL)
1896 {
1897 ERROR ("network plugin: malloc failed.");
1898 return (-1);
1899 }
1900 memset (ent, 0, sizeof (receive_list_entry_t));
1901 ent->fd = listen_sockets_pollfd[i].fd;
1902 ent->next = NULL;
1904 /* Hopefully this be optimized out by the compiler. It
1905 * might help prevent stupid bugs in the future though.
1906 */
1907 assert (sizeof (ent->data) == sizeof (buffer));
1909 memcpy (ent->data, buffer, buffer_len);
1910 ent->data_len = buffer_len;
1912 if (private_list_head == NULL)
1913 private_list_head = ent;
1914 else
1915 private_list_tail->next = ent;
1916 private_list_tail = ent;
1918 /* Do not block here. Blocking here has led to
1919 * insufficient performance in the past. */
1920 if (pthread_mutex_trylock (&receive_list_lock) == 0)
1921 {
1922 if (receive_list_head == NULL)
1923 receive_list_head = private_list_head;
1924 else
1925 receive_list_tail->next = private_list_head;
1926 receive_list_tail = private_list_tail;
1928 private_list_head = NULL;
1929 private_list_tail = NULL;
1931 pthread_cond_signal (&receive_list_cond);
1932 pthread_mutex_unlock (&receive_list_lock);
1933 }
1934 } /* for (listen_sockets_pollfd) */
1935 } /* while (listen_loop == 0) */
1937 /* Make sure everything is dispatched before exiting. */
1938 if (private_list_head != NULL)
1939 {
1940 pthread_mutex_lock (&receive_list_lock);
1942 if (receive_list_head == NULL)
1943 receive_list_head = private_list_head;
1944 else
1945 receive_list_tail->next = private_list_head;
1946 receive_list_tail = private_list_tail;
1948 private_list_head = NULL;
1949 private_list_tail = NULL;
1951 pthread_cond_signal (&receive_list_cond);
1952 pthread_mutex_unlock (&receive_list_lock);
1953 }
1955 return (0);
1956 } /* int network_receive */
1958 static void *receive_thread (void __attribute__((unused)) *arg)
1959 {
1960 return (network_receive () ? (void *) 1 : (void *) 0);
1961 } /* void *receive_thread */
1963 static void network_init_buffer (void)
1964 {
1965 memset (send_buffer, 0, sizeof (send_buffer));
1966 send_buffer_ptr = send_buffer;
1967 send_buffer_fill = 0;
1969 memset (&send_buffer_vl, 0, sizeof (send_buffer_vl));
1970 } /* int network_init_buffer */
1972 static void networt_send_buffer_plain (const sockent_t *se, /* {{{ */
1973 const char *buffer, size_t buffer_size)
1974 {
1975 int status;
1977 while (42)
1978 {
1979 status = sendto (se->fd, buffer, buffer_size, 0 /* no flags */,
1980 (struct sockaddr *) se->addr, se->addrlen);
1981 if (status < 0)
1982 {
1983 char errbuf[1024];
1984 if (errno == EINTR)
1985 continue;
1986 ERROR ("network plugin: sendto failed: %s",
1987 sstrerror (errno, errbuf,
1988 sizeof (errbuf)));
1989 break;
1990 }
1992 break;
1993 } /* while (42) */
1994 } /* }}} void networt_send_buffer_plain */
1996 #if HAVE_GCRYPT_H
1997 static void networt_send_buffer_signed (const sockent_t *se, /* {{{ */
1998 const char *in_buffer, size_t in_buffer_size)
1999 {
2000 part_signature_sha256_t ps;
2001 char buffer[sizeof (ps) + in_buffer_size];
2003 gcry_md_hd_t hd;
2004 gcry_error_t err;
2005 unsigned char *hash;
2007 hd = NULL;
2008 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
2009 if (err != 0)
2010 {
2011 ERROR ("network plugin: Creating HMAC object failed: %s",
2012 gcry_strerror (err));
2013 return;
2014 }
2016 err = gcry_md_setkey (hd, se->shared_secret,
2017 strlen (se->shared_secret));
2018 if (err != 0)
2019 {
2020 ERROR ("network plugin: gcry_md_setkey failed: %s",
2021 gcry_strerror (err));
2022 gcry_md_close (hd);
2023 return;
2024 }
2026 /* Initialize the `ps' structure. */
2027 memset (&ps, 0, sizeof (ps));
2028 ps.head.type = htons (TYPE_SIGN_SHA256);
2029 ps.head.length = htons ((uint16_t) sizeof (ps));
2031 /* Calculate the hash value. */
2032 gcry_md_write (hd, in_buffer, in_buffer_size);
2033 hash = gcry_md_read (hd, GCRY_MD_SHA256);
2034 if (hash == NULL)
2035 {
2036 ERROR ("network plugin: gcry_md_read failed.");
2037 gcry_md_close (hd);
2038 return;
2039 }
2041 /* Add the signature and fill the rest of the buffer. */
2042 memcpy (ps.hash, hash, sizeof (ps.hash));
2043 memcpy (buffer, &ps, sizeof (ps));
2044 memcpy (buffer + sizeof (ps), in_buffer, in_buffer_size);
2046 gcry_md_close (hd);
2047 hd = NULL;
2049 networt_send_buffer_plain (se, buffer, sizeof (buffer));
2050 } /* }}} void networt_send_buffer_signed */
2052 static void networt_send_buffer_encrypted (sockent_t *se, /* {{{ */
2053 const char *in_buffer, size_t in_buffer_size)
2054 {
2055 part_encryption_aes256_t pea;
2056 char buffer[sizeof (pea) + in_buffer_size];
2057 size_t buffer_size;
2058 size_t buffer_offset;
2059 size_t padding_size;
2060 gcry_error_t err;
2061 gcry_cipher_hd_t cypher;
2063 /* Round to the next multiple of 16, because AES has a block size of 128 bit.
2064 * the first 20 bytes of `pea' are not encrypted and must be subtracted. */
2065 buffer_size = in_buffer_size +
2066 (PART_ENCRYPTION_AES256_SIZE - PART_ENCRYPTION_AES256_UNENCR_SIZE);
2067 padding_size = buffer_size;
2068 /* Round to the next multiple of 16. */
2069 buffer_size = (buffer_size + 15) / 16;
2070 buffer_size = buffer_size * 16;
2071 /* Calculate padding_size */
2072 padding_size = buffer_size - padding_size;
2073 assert (padding_size <= sizeof (pea.padding));
2074 /* Now add the unencrypted bytes. */
2075 buffer_size += PART_ENCRYPTION_AES256_UNENCR_SIZE;
2077 DEBUG ("network plugin: networt_send_buffer_encrypted: "
2078 "buffer_size = %zu;", buffer_size);
2080 /* Initialize the header fields */
2081 memset (&pea, 0, sizeof (pea));
2082 pea.head.type = htons (TYPE_ENCR_AES256);
2083 pea.head.length = htons ((uint16_t) buffer_size);
2084 pea.orig_length = htons ((uint16_t) in_buffer_size);
2086 /* Chose a random initialization vector. */
2087 gcry_randomize ((void *) &pea.iv, sizeof (pea.iv), GCRY_STRONG_RANDOM);
2089 /* Create hash of the payload */
2090 gcry_md_hash_buffer (GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
2092 /* Fill the extra field with random values. Some entropy in the encrypted
2093 * data is usually not a bad thing, I hope. */
2094 if (padding_size > 0)
2095 gcry_randomize ((void *) &pea.padding, padding_size, GCRY_STRONG_RANDOM);
2097 /* Initialize the buffer */
2098 buffer_offset = 0;
2099 memset (buffer, 0, sizeof (buffer));
2101 #define BUFFER_ADD(p,s) do { \
2102 memcpy (buffer + buffer_offset, (p), (s)); \
2103 buffer_offset += (s); \
2104 } while (0)
2106 BUFFER_ADD (&pea.head.type, sizeof (pea.head.type));
2107 BUFFER_ADD (&pea.head.length, sizeof (pea.head.length));
2108 BUFFER_ADD (pea.iv, sizeof (pea.iv));
2109 BUFFER_ADD (&pea.orig_length, sizeof (pea.orig_length));
2110 BUFFER_ADD (pea.hash, sizeof (pea.hash));
2112 if (padding_size > 0)
2113 BUFFER_ADD (pea.padding, padding_size);
2115 BUFFER_ADD (in_buffer, in_buffer_size);
2117 assert (buffer_offset == buffer_size);
2119 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv));
2120 if (cypher == NULL)
2121 return;
2123 /* Encrypt the buffer in-place */
2124 err = gcry_cipher_encrypt (cypher,
2125 buffer + PART_ENCRYPTION_AES256_UNENCR_SIZE,
2126 buffer_size - PART_ENCRYPTION_AES256_UNENCR_SIZE,
2127 /* in = */ NULL, /* in len = */ 0);
2128 if (err != 0)
2129 {
2130 ERROR ("network plugin: gcry_cipher_encrypt returned: %s",
2131 gcry_strerror (err));
2132 return;
2133 }
2135 /* Send it out without further modifications */
2136 networt_send_buffer_plain (se, buffer, buffer_size);
2137 #undef BUFFER_ADD
2138 } /* }}} void networt_send_buffer_encrypted */
2139 #endif /* HAVE_GCRYPT_H */
2141 static void network_send_buffer (char *buffer, size_t buffer_len) /* {{{ */
2142 {
2143 sockent_t *se;
2145 DEBUG ("network plugin: network_send_buffer: buffer_len = %zu", buffer_len);
2147 for (se = sending_sockets; se != NULL; se = se->next)
2148 {
2149 #if HAVE_GCRYPT_H
2150 if (se->security_level == SECURITY_LEVEL_ENCRYPT)
2151 networt_send_buffer_encrypted (se, buffer, buffer_len);
2152 else if (se->security_level == SECURITY_LEVEL_SIGN)
2153 networt_send_buffer_signed (se, buffer, buffer_len);
2154 else /* if (se->security_level == SECURITY_LEVEL_NONE) */
2155 #endif /* HAVE_GCRYPT_H */
2156 networt_send_buffer_plain (se, buffer, buffer_len);
2157 } /* for (sending_sockets) */
2158 } /* }}} void network_send_buffer */
2160 static int add_to_buffer (char *buffer, int buffer_size, /* {{{ */
2161 value_list_t *vl_def,
2162 const data_set_t *ds, const value_list_t *vl)
2163 {
2164 char *buffer_orig = buffer;
2166 if (strcmp (vl_def->host, vl->host) != 0)
2167 {
2168 if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
2169 vl->host, strlen (vl->host)) != 0)
2170 return (-1);
2171 sstrncpy (vl_def->host, vl->host, sizeof (vl_def->host));
2172 }
2174 if (vl_def->time != vl->time)
2175 {
2176 if (write_part_number (&buffer, &buffer_size, TYPE_TIME,
2177 (uint64_t) vl->time))
2178 return (-1);
2179 vl_def->time = vl->time;
2180 }
2182 if (vl_def->interval != vl->interval)
2183 {
2184 if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL,
2185 (uint64_t) vl->interval))
2186 return (-1);
2187 vl_def->interval = vl->interval;
2188 }
2190 if (strcmp (vl_def->plugin, vl->plugin) != 0)
2191 {
2192 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
2193 vl->plugin, strlen (vl->plugin)) != 0)
2194 return (-1);
2195 sstrncpy (vl_def->plugin, vl->plugin, sizeof (vl_def->plugin));
2196 }
2198 if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
2199 {
2200 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
2201 vl->plugin_instance,
2202 strlen (vl->plugin_instance)) != 0)
2203 return (-1);
2204 sstrncpy (vl_def->plugin_instance, vl->plugin_instance, sizeof (vl_def->plugin_instance));
2205 }
2207 if (strcmp (vl_def->type, vl->type) != 0)
2208 {
2209 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
2210 vl->type, strlen (vl->type)) != 0)
2211 return (-1);
2212 sstrncpy (vl_def->type, ds->type, sizeof (vl_def->type));
2213 }
2215 if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
2216 {
2217 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
2218 vl->type_instance,
2219 strlen (vl->type_instance)) != 0)
2220 return (-1);
2221 sstrncpy (vl_def->type_instance, vl->type_instance, sizeof (vl_def->type_instance));
2222 }
2224 if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
2225 return (-1);
2227 return (buffer - buffer_orig);
2228 } /* }}} int add_to_buffer */
2230 static void flush_buffer (void)
2231 {
2232 DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
2233 send_buffer_fill);
2235 network_send_buffer (send_buffer, (size_t) send_buffer_fill);
2236 network_init_buffer ();
2237 }
2239 static int network_write (const data_set_t *ds, const value_list_t *vl,
2240 user_data_t __attribute__((unused)) *user_data)
2241 {
2242 int status;
2244 /* If the value is already in the cache, we have received it via the
2245 * network. We write it again if forwarding is activated. It's then in
2246 * the cache and should we receive it again we will ignore it. */
2247 status = cache_check (vl);
2248 if ((network_config_forward == 0)
2249 && (status != 0))
2250 return (0);
2252 pthread_mutex_lock (&send_buffer_lock);
2254 status = add_to_buffer (send_buffer_ptr,
2255 sizeof (send_buffer) - (send_buffer_fill + BUFF_SIG_SIZE),
2256 &send_buffer_vl,
2257 ds, vl);
2258 if (status >= 0)
2259 {
2260 /* status == bytes added to the buffer */
2261 send_buffer_fill += status;
2262 send_buffer_ptr += status;
2263 }
2264 else
2265 {
2266 flush_buffer ();
2268 status = add_to_buffer (send_buffer_ptr,
2269 sizeof (send_buffer) - (send_buffer_fill + BUFF_SIG_SIZE),
2270 &send_buffer_vl,
2271 ds, vl);
2273 if (status >= 0)
2274 {
2275 send_buffer_fill += status;
2276 send_buffer_ptr += status;
2277 }
2278 }
2280 if (status < 0)
2281 {
2282 ERROR ("network plugin: Unable to append to the "
2283 "buffer for some weird reason");
2284 }
2285 else if ((sizeof (send_buffer) - send_buffer_fill) < 15)
2286 {
2287 flush_buffer ();
2288 }
2290 pthread_mutex_unlock (&send_buffer_lock);
2292 return ((status < 0) ? -1 : 0);
2293 } /* int network_write */
2295 static int network_config_set_boolean (const oconfig_item_t *ci, /* {{{ */
2296 int *retval)
2297 {
2298 if ((ci->values_num != 1)
2299 || ((ci->values[0].type != OCONFIG_TYPE_BOOLEAN)
2300 && (ci->values[0].type != OCONFIG_TYPE_STRING)))
2301 {
2302 ERROR ("network plugin: The `%s' config option needs "
2303 "exactly one boolean argument.", ci->key);
2304 return (-1);
2305 }
2307 if (ci->values[0].type == OCONFIG_TYPE_BOOLEAN)
2308 {
2309 if (ci->values[0].value.boolean)
2310 *retval = 1;
2311 else
2312 *retval = 0;
2313 }
2314 else
2315 {
2316 char *str = ci->values[0].value.string;
2318 if ((strcasecmp ("true", str) == 0)
2319 || (strcasecmp ("yes", str) == 0)
2320 || (strcasecmp ("on", str) == 0))
2321 *retval = 1;
2322 else if ((strcasecmp ("false", str) == 0)
2323 || (strcasecmp ("no", str) == 0)
2324 || (strcasecmp ("off", str) == 0))
2325 *retval = 0;
2326 else
2327 {
2328 ERROR ("network plugin: Cannot parse string value `%s' of the `%s' "
2329 "option as boolean value.",
2330 str, ci->key);
2331 return (-1);
2332 }
2333 }
2335 return (0);
2336 } /* }}} int network_config_set_boolean */
2338 static int network_config_set_ttl (const oconfig_item_t *ci) /* {{{ */
2339 {
2340 int tmp;
2341 if ((ci->values_num != 1)
2342 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2343 {
2344 WARNING ("network plugin: The `TimeToLive' config option needs exactly "
2345 "one numeric argument.");
2346 return (-1);
2347 }
2349 tmp = (int) ci->values[0].value.number;
2350 if ((tmp > 0) && (tmp <= 255))
2351 network_config_ttl = tmp;
2353 return (0);
2354 } /* }}} int network_config_set_ttl */
2356 #if HAVE_GCRYPT_H
2357 static int network_config_set_security_level (oconfig_item_t *ci, /* {{{ */
2358 int *retval)
2359 {
2360 char *str;
2361 if ((ci->values_num != 1)
2362 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2363 {
2364 WARNING ("network plugin: The `SecurityLevel' config option needs exactly "
2365 "one string argument.");
2366 return (-1);
2367 }
2369 str = ci->values[0].value.string;
2370 if (strcasecmp ("Encrypt", str) == 0)
2371 *retval = SECURITY_LEVEL_ENCRYPT;
2372 else if (strcasecmp ("Sign", str) == 0)
2373 *retval = SECURITY_LEVEL_SIGN;
2374 else if (strcasecmp ("None", str) == 0)
2375 *retval = SECURITY_LEVEL_NONE;
2376 else
2377 {
2378 WARNING ("network plugin: Unknown security level: %s.", str);
2379 return (-1);
2380 }
2382 return (0);
2383 } /* }}} int network_config_set_security_level */
2384 #endif /* HAVE_GCRYPT_H */
2386 static int network_config_listen_server (const oconfig_item_t *ci) /* {{{ */
2387 {
2388 char *node;
2389 char *service;
2390 char *shared_secret = NULL;
2391 int security_level = SECURITY_LEVEL_NONE;
2392 int i;
2394 if ((ci->values_num < 1) || (ci->values_num > 2)
2395 || (ci->values[0].type != OCONFIG_TYPE_STRING)
2396 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
2397 {
2398 ERROR ("network plugin: The `%s' config option needs "
2399 "one or two string arguments.", ci->key);
2400 return (-1);
2401 }
2403 node = ci->values[0].value.string;
2404 if (ci->values_num >= 2)
2405 service = ci->values[1].value.string;
2406 else
2407 service = NULL;
2409 for (i = 0; i < ci->children_num; i++)
2410 {
2411 oconfig_item_t *child = ci->children + i;
2413 #if HAVE_GCRYPT_H
2414 if (strcasecmp ("Secret", child->key) == 0)
2415 {
2416 if ((child->values_num == 1)
2417 && (child->values[0].type == OCONFIG_TYPE_STRING))
2418 shared_secret = child->values[0].value.string;
2419 else
2420 ERROR ("network plugin: The `Secret' option needs exactly one string "
2421 "argument.");
2422 }
2423 else if (strcasecmp ("SecurityLevel", child->key) == 0)
2424 network_config_set_security_level (child, &security_level);
2425 else
2426 #endif /* HAVE_GCRYPT_H */
2427 {
2428 WARNING ("network plugin: Option `%s' is not allowed here.",
2429 child->key);
2430 }
2431 }
2433 if ((security_level > SECURITY_LEVEL_NONE) && (shared_secret == NULL))
2434 {
2435 ERROR ("network plugin: A security level higher than `none' was "
2436 "requested, but no shared key was given. Cowardly refusing to open "
2437 "this socket!");
2438 return (-1);
2439 }
2441 if (strcasecmp ("Listen", ci->key) == 0)
2442 network_add_listen_socket (node, service, shared_secret, security_level);
2443 else
2444 network_add_sending_socket (node, service, shared_secret, security_level);
2446 return (0);
2447 } /* }}} int network_config_listen_server */
2449 static int network_config_set_cache_flush (const oconfig_item_t *ci) /* {{{ */
2450 {
2451 int tmp;
2452 if ((ci->values_num != 1)
2453 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2454 {
2455 WARNING ("network plugin: The `CacheFlush' config option needs exactly "
2456 "one numeric argument.");
2457 return (-1);
2458 }
2460 tmp = (int) ci->values[0].value.number;
2461 if (tmp > 0)
2462 network_config_ttl = tmp;
2464 return (0);
2465 } /* }}} int network_config_set_cache_flush */
2467 static int network_config (oconfig_item_t *ci) /* {{{ */
2468 {
2469 int i;
2471 for (i = 0; i < ci->children_num; i++)
2472 {
2473 oconfig_item_t *child = ci->children + i;
2475 if ((strcasecmp ("Listen", child->key) == 0)
2476 || (strcasecmp ("Server", child->key) == 0))
2477 network_config_listen_server (child);
2478 else if (strcasecmp ("TimeToLive", child->key) == 0)
2479 network_config_set_ttl (child);
2480 else if (strcasecmp ("Forward", child->key) == 0)
2481 network_config_set_boolean (child, &network_config_forward);
2482 else if (strcasecmp ("CacheFlush", child->key) == 0)
2483 network_config_set_cache_flush (child);
2484 else
2485 {
2486 WARNING ("network plugin: Option `%s' is not allowed here.",
2487 child->key);
2488 }
2489 }
2491 return (0);
2492 } /* }}} int network_config */
2494 static int network_notification (const notification_t *n,
2495 user_data_t __attribute__((unused)) *user_data)
2496 {
2497 char buffer[BUFF_SIZE];
2498 char *buffer_ptr = buffer;
2499 int buffer_free = sizeof (buffer);
2500 int status;
2502 memset (buffer, '\0', sizeof (buffer));
2505 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_TIME,
2506 (uint64_t) n->time);
2507 if (status != 0)
2508 return (-1);
2510 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_SEVERITY,
2511 (uint64_t) n->severity);
2512 if (status != 0)
2513 return (-1);
2515 if (strlen (n->host) > 0)
2516 {
2517 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_HOST,
2518 n->host, strlen (n->host));
2519 if (status != 0)
2520 return (-1);
2521 }
2523 if (strlen (n->plugin) > 0)
2524 {
2525 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_PLUGIN,
2526 n->plugin, strlen (n->plugin));
2527 if (status != 0)
2528 return (-1);
2529 }
2531 if (strlen (n->plugin_instance) > 0)
2532 {
2533 status = write_part_string (&buffer_ptr, &buffer_free,
2534 TYPE_PLUGIN_INSTANCE,
2535 n->plugin_instance, strlen (n->plugin_instance));
2536 if (status != 0)
2537 return (-1);
2538 }
2540 if (strlen (n->type) > 0)
2541 {
2542 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE,
2543 n->type, strlen (n->type));
2544 if (status != 0)
2545 return (-1);
2546 }
2548 if (strlen (n->type_instance) > 0)
2549 {
2550 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
2551 n->type_instance, strlen (n->type_instance));
2552 if (status != 0)
2553 return (-1);
2554 }
2556 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_MESSAGE,
2557 n->message, strlen (n->message));
2558 if (status != 0)
2559 return (-1);
2561 network_send_buffer (buffer, sizeof (buffer) - buffer_free);
2563 return (0);
2564 } /* int network_notification */
2566 static int network_shutdown (void)
2567 {
2568 listen_loop++;
2570 /* Kill the listening thread */
2571 if (receive_thread_running != 0)
2572 {
2573 INFO ("network plugin: Stopping receive thread.");
2574 pthread_kill (receive_thread_id, SIGTERM);
2575 pthread_join (receive_thread_id, NULL /* no return value */);
2576 memset (&receive_thread_id, 0, sizeof (receive_thread_id));
2577 receive_thread_running = 0;
2578 }
2580 /* Shutdown the dispatching thread */
2581 if (dispatch_thread_running != 0)
2582 {
2583 INFO ("network plugin: Stopping dispatch thread.");
2584 pthread_mutex_lock (&receive_list_lock);
2585 pthread_cond_broadcast (&receive_list_cond);
2586 pthread_mutex_unlock (&receive_list_lock);
2587 pthread_join (dispatch_thread_id, /* ret = */ NULL);
2588 dispatch_thread_running = 0;
2589 }
2591 free_sockent (listen_sockets);
2593 if (send_buffer_fill > 0)
2594 flush_buffer ();
2596 if (cache_tree != NULL)
2597 {
2598 void *key;
2599 void *value;
2601 while (c_avl_pick (cache_tree, &key, &value) == 0)
2602 {
2603 sfree (key);
2604 sfree (value);
2605 }
2606 c_avl_destroy (cache_tree);
2607 cache_tree = NULL;
2608 }
2610 /* TODO: Close `sending_sockets' */
2612 plugin_unregister_config ("network");
2613 plugin_unregister_init ("network");
2614 plugin_unregister_write ("network");
2615 plugin_unregister_shutdown ("network");
2617 /* Let the init function do it's move again ;) */
2618 cache_flush_last = 0;
2620 return (0);
2621 } /* int network_shutdown */
2623 static int network_init (void)
2624 {
2625 /* Check if we were already initialized. If so, just return - there's
2626 * nothing more to do (for now, that is). */
2627 if (cache_flush_last != 0)
2628 return (0);
2630 plugin_register_shutdown ("network", network_shutdown);
2632 network_init_buffer ();
2634 cache_tree = c_avl_create ((int (*) (const void *, const void *)) strcmp);
2635 cache_flush_last = time (NULL);
2637 /* setup socket(s) and so on */
2638 if (sending_sockets != NULL)
2639 {
2640 plugin_register_write ("network", network_write,
2641 /* user_data = */ NULL);
2642 plugin_register_notification ("network", network_notification,
2643 /* user_data = */ NULL);
2644 }
2646 /* If no threads need to be started, return here. */
2647 if ((listen_sockets_num == 0)
2648 || ((dispatch_thread_running != 0)
2649 && (receive_thread_running != 0)))
2650 return (0);
2652 if (dispatch_thread_running == 0)
2653 {
2654 int status;
2655 status = pthread_create (&dispatch_thread_id,
2656 NULL /* no attributes */,
2657 dispatch_thread,
2658 NULL /* no argument */);
2659 if (status != 0)
2660 {
2661 char errbuf[1024];
2662 ERROR ("network: pthread_create failed: %s",
2663 sstrerror (errno, errbuf,
2664 sizeof (errbuf)));
2665 }
2666 else
2667 {
2668 dispatch_thread_running = 1;
2669 }
2670 }
2672 if (receive_thread_running == 0)
2673 {
2674 int status;
2675 status = pthread_create (&receive_thread_id,
2676 NULL /* no attributes */,
2677 receive_thread,
2678 NULL /* no argument */);
2679 if (status != 0)
2680 {
2681 char errbuf[1024];
2682 ERROR ("network: pthread_create failed: %s",
2683 sstrerror (errno, errbuf,
2684 sizeof (errbuf)));
2685 }
2686 else
2687 {
2688 receive_thread_running = 1;
2689 }
2690 }
2692 return (0);
2693 } /* int network_init */
2695 /*
2696 * The flush option of the network plugin cannot flush individual identifiers.
2697 * All the values are added to a buffer and sent when the buffer is full, the
2698 * requested value may or may not be in there, it's not worth finding out. We
2699 * just send the buffer if `flush' is called - if the requested value was in
2700 * there, good. If not, well, then there is nothing to flush.. -octo
2701 */
2702 static int network_flush (int timeout,
2703 const char __attribute__((unused)) *identifier,
2704 user_data_t __attribute__((unused)) *user_data)
2705 {
2706 pthread_mutex_lock (&send_buffer_lock);
2708 if (((time (NULL) - cache_flush_last) >= timeout)
2709 && (send_buffer_fill > 0))
2710 {
2711 flush_buffer ();
2712 }
2714 pthread_mutex_unlock (&send_buffer_lock);
2716 return (0);
2717 } /* int network_flush */
2719 void module_register (void)
2720 {
2721 plugin_register_complex_config ("network", network_config);
2722 plugin_register_init ("network", network_init);
2723 plugin_register_flush ("network", network_flush,
2724 /* user_data = */ NULL);
2725 } /* void module_register */
2727 /* vim: set fdm=marker : */