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