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