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