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