Bug#404018: Close the file descriptor when binding to a socket fails.
[collectd.git] / src / network.c
1 /**
2  * collectd - src/network.c
3  * Copyright (C) 2005,2006  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; either version 2 of the License, or (at your
8  * option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
18  *
19  * Authors:
20  *   Florian octo Forster <octo at verplant.org>
21  **/
22
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <string.h>
26 #include <sys/types.h>
27 #include <sys/socket.h>
28 #include <netdb.h>
29 #include <netinet/in.h>
30 #include <arpa/inet.h>
31 #include <syslog.h>
32 #include <errno.h>
33
34 #include "network.h"
35 #include "common.h"
36 #include "configfile.h"
37 #include "utils_debug.h"
38
39 /* 1500 - 40 - 8  =  Ethernet packet - IPv6 header - UDP header */
40 /* #define BUFF_SIZE 1452 */
41
42 #ifndef IPV6_ADD_MEMBERSHIP
43 # ifdef IPV6_JOIN_GROUP
44 #  define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
45 # else
46 #  error "Neither IP_ADD_MEMBERSHIP nor IPV6_JOIN_GROUP is defined"
47 # endif
48 #endif /* !IP_ADD_MEMBERSHIP */
49
50 #define BUFF_SIZE 4096
51
52 extern int operating_mode;
53
54 typedef struct sockent
55 {
56         int                      fd;
57         int                      mode;
58         struct sockaddr_storage *addr;
59         socklen_t                addrlen;
60         struct sockent          *next;
61 } sockent_t;
62
63 static sockent_t *socklist_head = NULL;
64
65 static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
66 {
67         char *ttl_str;
68         int   ttl_int;
69
70         ttl_str = cf_get_option ("TimeToLive", NULL);
71         if (ttl_str == NULL)
72                 return (-1);
73
74         ttl_int = atoi (ttl_str);
75         if ((ttl_int < 1) || (ttl_int > 255))
76         {
77                 syslog (LOG_WARNING, "A TTL value of %i is invalid.", ttl_int);
78                 return (-1);
79         }
80
81         DBG ("ttl = %i", ttl_int);
82
83         if (ai->ai_family == AF_INET)
84         {
85                 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
86                 int optname;
87
88                 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
89                         optname = IP_MULTICAST_TTL;
90                 else
91                         optname = IP_TTL;
92
93                 if (setsockopt (se->fd, IPPROTO_IP, optname,
94                                         &ttl_int, sizeof (ttl_int)) == -1)
95                 {
96                         syslog (LOG_ERR, "setsockopt: %s", strerror (errno));
97                         return (-1);
98                 }
99         }
100         else if (ai->ai_family == AF_INET6)
101         {
102                 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
103                 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
104                 int optname;
105
106                 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
107                         optname = IPV6_MULTICAST_HOPS;
108                 else
109                         optname = IPV6_UNICAST_HOPS;
110
111                 if (setsockopt (se->fd, IPPROTO_IPV6, optname,
112                                         &ttl_int, sizeof (ttl_int)) == -1)
113                 {
114                         syslog (LOG_ERR, "setsockopt: %s", strerror (errno));
115                         return (-1);
116                 }
117         }
118
119         return (0);
120 }
121
122 static int network_bind_socket (const sockent_t *se, const struct addrinfo *ai)
123 {
124         int loop = 1;
125
126         DBG ("fd = %i; calling `bind'", se->fd);
127
128         if (bind (se->fd, ai->ai_addr, ai->ai_addrlen) == -1)
129         {
130                 syslog (LOG_ERR, "bind: %s", strerror (errno));
131                 return (-1);
132         }
133
134         if (ai->ai_family == AF_INET)
135         {
136                 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
137                 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
138                 {
139                         struct ip_mreq mreq;
140
141                         DBG ("fd = %i; IPv4 multicast address found", se->fd);
142
143                         mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
144                         mreq.imr_interface.s_addr = htonl (INADDR_ANY);
145
146                         if (setsockopt (se->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
147                                                 &loop, sizeof (loop)) == -1)
148                         {
149                                 syslog (LOG_ERR, "setsockopt: %s", strerror (errno));
150                                 return (-1);
151                         }
152
153                         if (setsockopt (se->fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
154                                                 &mreq, sizeof (mreq)) == -1)
155                         {
156                                 syslog (LOG_ERR, "setsockopt: %s", strerror (errno));
157                                 return (-1);
158                         }
159                 }
160         }
161         else if (ai->ai_family == AF_INET6)
162         {
163                 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
164                 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
165                 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
166                 {
167                         struct ipv6_mreq mreq;
168
169                         DBG ("fd = %i; IPv6 multicast address found", se->fd);
170
171                         memcpy (&mreq.ipv6mr_multiaddr,
172                                         &addr->sin6_addr,
173                                         sizeof (addr->sin6_addr));
174
175                         /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
176                          * ipv6mr_interface may be set to zeroes to
177                          * choose the default multicast interface or to
178                          * the index of a particular multicast-capable
179                          * interface if the host is multihomed.
180                          * Membership is associ-associated with a
181                          * single interface; programs running on
182                          * multihomed hosts may need to join the same
183                          * group on more than one interface.*/
184                         mreq.ipv6mr_interface = 0;
185
186                         if (setsockopt (se->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
187                                                 &loop, sizeof (loop)) == -1)
188                         {
189                                 syslog (LOG_ERR, "setsockopt: %s", strerror (errno));
190                                 return (-1);
191                         }
192
193                         if (setsockopt (se->fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
194                                                 &mreq, sizeof (mreq)) == -1)
195                         {
196                                 syslog (LOG_ERR, "setsockopt: %s", strerror (errno));
197                                 return (-1);
198                         }
199                 }
200         }
201
202         return (0);
203 }
204
205 int network_create_socket (const char *node, const char *service)
206 {
207         sockent_t *socklist_tail;
208
209         struct addrinfo  ai_hints;
210         struct addrinfo *ai_list, *ai_ptr;
211         int              ai_return;
212
213         int num_added = 0;
214
215         DBG ("node = %s, service = %s", node, service);
216
217         if (operating_mode == MODE_LOCAL || operating_mode == MODE_LOG)
218         {
219                 syslog (LOG_WARNING, "network_create_socket: There is no point opening a socket when you are in mode `%s'.",
220                                 operating_mode == MODE_LOCAL ? "Local" : "Log");
221                 return (-1);
222         }
223
224         socklist_tail = socklist_head;
225         while ((socklist_tail != NULL) && (socklist_tail->next != NULL))
226                 socklist_tail = socklist_tail->next;
227
228         memset (&ai_hints, '\0', sizeof (ai_hints));
229         ai_hints.ai_flags    = 0;
230 #ifdef AI_PASSIVE
231         ai_hints.ai_flags |= AI_PASSIVE;
232 #endif
233 #ifdef AI_ADDRCONFIG
234         ai_hints.ai_flags |= AI_ADDRCONFIG;
235 #endif
236         ai_hints.ai_family   = PF_UNSPEC;
237         ai_hints.ai_socktype = SOCK_DGRAM;
238         ai_hints.ai_protocol = IPPROTO_UDP;
239
240         if ((ai_return = getaddrinfo (node, service, &ai_hints, &ai_list)) != 0)
241         {
242                 syslog (LOG_ERR, "getaddrinfo (%s, %s): %s",
243                                 node == NULL ? "(null)" : node,
244                                 service == NULL ? "(null)" : service,
245                                 ai_return == EAI_SYSTEM ? strerror (errno) : gai_strerror (ai_return));
246                 return (-1);
247         }
248
249         for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
250         {
251                 sockent_t *se;
252
253                 if ((se = (sockent_t *) malloc (sizeof (sockent_t))) == NULL)
254                 {
255                         syslog (LOG_EMERG, "malloc: %s", strerror (errno));
256                         continue;
257                 }
258
259                 if ((se->addr = (struct sockaddr_storage *) malloc (sizeof (struct sockaddr_storage))) == NULL)
260                 {
261                         syslog (LOG_EMERG, "malloc: %s", strerror (errno));
262                         free (se);
263                         continue;
264                 }
265
266                 assert (sizeof (struct sockaddr_storage) >= ai_ptr->ai_addrlen);
267                 memset (se->addr, '\0', sizeof (struct sockaddr_storage));
268                 memcpy (se->addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
269                 se->addrlen = ai_ptr->ai_addrlen;
270
271                 se->mode = operating_mode;
272                 se->fd   = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
273                 se->next = NULL;
274
275                 if (se->fd == -1)
276                 {
277                         syslog (LOG_ERR, "socket: %s", strerror (errno));
278                         free (se->addr);
279                         free (se);
280                         continue;
281                 }
282
283                 if (operating_mode == MODE_SERVER)
284                 {
285                         if (network_bind_socket (se, ai_ptr) != 0)
286                         {
287                                 close (se->fd);
288                                 free (se->addr);
289                                 free (se);
290                                 continue;
291                         }
292                 }
293                 else if (operating_mode == MODE_CLIENT)
294                 {
295                         network_set_ttl (se, ai_ptr);
296                 }
297
298                 if (socklist_tail == NULL)
299                 {
300                         socklist_head = se;
301                         socklist_tail = se;
302                 }
303                 else
304                 {
305                         socklist_tail->next = se;
306                         socklist_tail = se;
307                 }
308
309                 num_added++;
310
311                 /* We don't open more than one write-socket per node/service pair.. */
312                 if (operating_mode == MODE_CLIENT)
313                         break;
314         }
315
316         freeaddrinfo (ai_list);
317
318         return (num_added);
319 }
320
321 static int network_connect_default (void)
322 {
323         int ret;
324
325         if (socklist_head != NULL)
326                 return (0);
327
328         DBG ("socklist_head is NULL");
329
330         ret = 0;
331
332         if (network_create_socket (NET_DEFAULT_V6_ADDR, NET_DEFAULT_PORT) > 0)
333                 ret++;
334
335         /* Don't use IPv4 and IPv6 in parallel by default.. */
336         if ((operating_mode == MODE_CLIENT) && (ret != 0))
337                 return (ret);
338
339         if (network_create_socket (NET_DEFAULT_V4_ADDR, NET_DEFAULT_PORT) > 0)
340                 ret++;
341
342         if (ret == 0)
343                 ret = -1;
344
345         return (ret);
346 }
347
348 static int network_get_listen_socket (void)
349 {
350         int fd;
351         int max_fd;
352         int status;
353
354         fd_set readfds;
355         sockent_t *se;
356
357         if (socklist_head == NULL)
358                 network_connect_default ();
359
360         FD_ZERO (&readfds);
361         max_fd = -1;
362         for (se = socklist_head; se != NULL; se = se->next)
363         {
364                 if (se->mode != operating_mode)
365                         continue;
366
367                 FD_SET (se->fd, &readfds);
368                 if (se->fd >= max_fd)
369                         max_fd = se->fd + 1;
370         }
371
372         if (max_fd == -1)
373         {
374                 syslog (LOG_WARNING, "No listen sockets found!");
375                 return (-1);
376         }
377
378         status = select (max_fd, &readfds, NULL, NULL, NULL);
379
380         if (status == -1)
381         {
382                 if (errno != EINTR)
383                         syslog (LOG_ERR, "select: %s", strerror (errno));
384                 return (-1);
385         }
386
387         fd = -1;
388         for (se = socklist_head; se != NULL; se = se->next)
389         {
390                 if (se->mode != operating_mode)
391                         continue;
392
393                 if (FD_ISSET (se->fd, &readfds))
394                 {
395                         fd = se->fd;
396                         break;
397                 }
398         }
399
400         if (fd == -1)
401                 syslog (LOG_WARNING, "No socket ready..?");
402
403         DBG ("fd = %i", fd);
404         return (fd);
405 }
406
407 int network_receive (char **host, char **type, char **inst, char **value)
408 {
409         int fd;
410         char buffer[BUFF_SIZE];
411
412         struct sockaddr_storage addr;
413         socklen_t               addrlen;
414         int status;
415
416         char *fields[4];
417
418         assert (operating_mode == MODE_SERVER);
419
420         *host  = NULL;
421         *type  = NULL;
422         *inst  = NULL;
423         *value = NULL;
424
425         if ((fd = network_get_listen_socket ()) < 0)
426                 return (-1);
427
428         addrlen = sizeof (addr);
429         if (recvfrom (fd, buffer, BUFF_SIZE, 0, (struct sockaddr *) &addr, &addrlen) == -1)
430         {
431                 syslog (LOG_ERR, "recvfrom: %s", strerror (errno));
432                 return (-1);
433         }
434
435         if ((*host = (char *) malloc (BUFF_SIZE)) == NULL)
436         {
437                 syslog (LOG_EMERG, "malloc: %s", strerror (errno));
438                 return (-1);
439         }
440
441         status = getnameinfo ((struct sockaddr *) &addr, addrlen,
442                         *host, BUFF_SIZE, NULL, 0, 0);
443         if (status != 0)
444         {
445                 free (*host); *host = NULL;
446                 syslog (LOG_ERR, "getnameinfo: %s",
447                                 status == EAI_SYSTEM ? strerror (errno) : gai_strerror (status));
448                 return (-1);
449         }
450
451         if (strsplit (buffer, fields, 4) != 3)
452         {
453                 syslog (LOG_WARNING, "Invalid message from `%s'", *host);
454                 free (*host); *host = NULL;
455                 return (1);
456         }
457
458         if ((*type = strdup (fields[0])) == NULL)
459         {
460                 syslog (LOG_EMERG, "strdup: %s", strerror (errno));
461                 free (*host); *host = NULL;
462                 return (-1);
463         }
464
465         if ((*inst = strdup (fields[1])) == NULL)
466         {
467                 syslog (LOG_EMERG, "strdup: %s", strerror (errno));
468                 free (*host); *host = NULL;
469                 free (*type); *type = NULL;
470                 return (-1);
471         }
472
473         if ((*value = strdup (fields[2])) == NULL)
474         {
475                 syslog (LOG_EMERG, "strdup: %s", strerror (errno));
476                 free (*host); *host = NULL;
477                 free (*type); *type = NULL;
478                 free (*inst); *inst = NULL;
479                 return (-1);
480         }
481
482         DBG ("host = %s, type = %s, inst = %s, value = %s",
483                         *host, *type, *inst, *value);
484
485         return (0);
486 }
487
488 int network_send (char *type, char *inst, char *value)
489 {
490         char buf[BUFF_SIZE];
491         int buflen;
492
493         sockent_t *se;
494
495         int ret;
496         int status;
497
498         DBG ("type = %s, inst = %s, value = %s", type, inst, value);
499
500         assert (operating_mode == MODE_CLIENT);
501
502         buflen = snprintf (buf, BUFF_SIZE, "%s %s %s", type, inst, value);
503         if ((buflen >= BUFF_SIZE) || (buflen < 1))
504         {
505                 syslog (LOG_WARNING, "network_send: snprintf failed..");
506                 return (-1);
507         }
508         buf[buflen] = '\0';
509         buflen++;
510
511         if (socklist_head == NULL)
512                 network_connect_default ();
513
514         ret = 0;
515         for (se = socklist_head; se != NULL; se = se->next)
516         {
517                 if (se->mode != operating_mode)
518                         continue;
519
520                 while (1)
521                 {
522                         status = sendto (se->fd, buf, buflen, 0,
523                                         (struct sockaddr *) se->addr, se->addrlen);
524
525                         if (status == -1)
526                         {
527                                 if (errno == EINTR)
528                                 {
529                                         DBG ("sendto was interrupted");
530                                         continue;
531                                 }
532                                 else
533                                 {
534                                         syslog (LOG_ERR, "sendto: %s", strerror (errno));
535                                         ret = -1;
536                                         break;
537                                 }
538                         }
539                         else if (ret >= 0)
540                                 ret++;
541                         break;
542                 }
543         }
544
545         if (ret == 0)
546                 syslog (LOG_WARNING, "Message wasn't sent to anybody..");
547
548         return (ret);
549 }