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