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