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