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