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