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