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