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