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