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