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