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