Move .h files from noinst_HEADERS to tincd_SOURCES.
[tinc] / src / net_socket.c
1 /*
2     net_socket.c -- Handle various kinds of sockets.
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2013 Guus Sliepen <guus@tinc-vpn.org>
5                   2006      Scott Lamb <slamb@slamb.org>
6                   2009      Florian Forster <octo@verplant.org>
7
8     This program is free software; you can redistribute it and/or modify
9     it under the terms of the GNU General Public License as published by
10     the Free Software Foundation; either version 2 of the License, or
11     (at your option) any later version.
12
13     This program is distributed in the hope that it will be useful,
14     but WITHOUT ANY WARRANTY; without even the implied warranty of
15     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16     GNU General Public License for more details.
17
18     You should have received a copy of the GNU General Public License along
19     with this program; if not, write to the Free Software Foundation, Inc.,
20     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 */
22
23 #include "system.h"
24
25 #include "conf.h"
26 #include "connection.h"
27 #include "control_common.h"
28 #include "list.h"
29 #include "logger.h"
30 #include "meta.h"
31 #include "names.h"
32 #include "net.h"
33 #include "netutl.h"
34 #include "protocol.h"
35 #include "utils.h"
36 #include "xalloc.h"
37
38 /* Needed on Mac OS/X */
39 #ifndef SOL_TCP
40 #define SOL_TCP IPPROTO_TCP
41 #endif
42
43 int addressfamily = AF_UNSPEC;
44 int maxtimeout = 900;
45 int seconds_till_retry = 5;
46 int udp_rcvbuf = 0;
47 int udp_sndbuf = 0;
48 int max_connection_burst = 100;
49
50 listen_socket_t listen_socket[MAXSOCKETS];
51 int listen_sockets;
52 #ifndef HAVE_MINGW
53 io_t unix_socket;
54 #endif
55 list_t *outgoing_list = NULL;
56
57 /* Setup sockets */
58
59 static void configure_tcp(connection_t *c) {
60         int option;
61
62 #ifdef O_NONBLOCK
63         int flags = fcntl(c->socket, F_GETFL);
64
65         if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0) {
66                 logger(DEBUG_ALWAYS, LOG_ERR, "fcntl for %s: %s", c->hostname, strerror(errno));
67         }
68 #elif defined(WIN32)
69         unsigned long arg = 1;
70
71         if(ioctlsocket(c->socket, FIONBIO, &arg) != 0) {
72                 logger(DEBUG_ALWAYS, LOG_ERR, "ioctlsocket for %s: %s", c->hostname, sockstrerror(sockerrno));
73         }
74 #endif
75
76 #if defined(SOL_TCP) && defined(TCP_NODELAY)
77         option = 1;
78         setsockopt(c->socket, SOL_TCP, TCP_NODELAY, (void *)&option, sizeof option);
79 #endif
80
81 #if defined(SOL_IP) && defined(IP_TOS) && defined(IPTOS_LOWDELAY)
82         option = IPTOS_LOWDELAY;
83         setsockopt(c->socket, SOL_IP, IP_TOS, (void *)&option, sizeof option);
84 #endif
85 }
86
87 static bool bind_to_interface(int sd) {
88         char *iface;
89
90 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
91         struct ifreq ifr;
92         int status;
93 #endif /* defined(SOL_SOCKET) && defined(SO_BINDTODEVICE) */
94
95         if(!get_config_string (lookup_config (config_tree, "BindToInterface"), &iface))
96                 return true;
97
98 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
99         memset(&ifr, 0, sizeof(ifr));
100         strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
101         ifr.ifr_ifrn.ifrn_name[IFNAMSIZ - 1] = 0;
102
103         status = setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr));
104         if(status) {
105                 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to interface %s: %s", iface,
106                                 strerror(errno));
107                 return false;
108         }
109 #else /* if !defined(SOL_SOCKET) || !defined(SO_BINDTODEVICE) */
110         logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform", "BindToInterface");
111 #endif
112
113         return true;
114 }
115
116 int setup_listen_socket(const sockaddr_t *sa) {
117         int nfd;
118         char *addrstr;
119         int option;
120         char *iface;
121
122         nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
123
124         if(nfd < 0) {
125                 logger(DEBUG_STATUS, LOG_ERR, "Creating metasocket failed: %s", sockstrerror(sockerrno));
126                 return -1;
127         }
128
129 #ifdef FD_CLOEXEC
130         fcntl(nfd, F_SETFD, FD_CLOEXEC);
131 #endif
132
133         /* Optimize TCP settings */
134
135         option = 1;
136         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof option);
137
138 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
139         if(sa->sa.sa_family == AF_INET6)
140                 setsockopt(nfd, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
141 #endif
142
143         if(get_config_string
144            (lookup_config(config_tree, "BindToInterface"), &iface)) {
145 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
146                 struct ifreq ifr;
147
148                 memset(&ifr, 0, sizeof ifr);
149                 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
150
151                 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof ifr)) {
152                         closesocket(nfd);
153                         logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to interface %s: %s", iface,
154                                    strerror(sockerrno));
155                         return -1;
156                 }
157 #else
158                 logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform", "BindToInterface");
159 #endif
160         }
161
162         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
163                 closesocket(nfd);
164                 addrstr = sockaddr2hostname(sa);
165                 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
166                 free(addrstr);
167                 return -1;
168         }
169
170         if(listen(nfd, 3)) {
171                 closesocket(nfd);
172                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
173                 return -1;
174         }
175
176         return nfd;
177 }
178
179 int setup_vpn_in_socket(const sockaddr_t *sa) {
180         int nfd;
181         char *addrstr;
182         int option;
183
184         nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
185
186         if(nfd < 0) {
187                 logger(DEBUG_ALWAYS, LOG_ERR, "Creating UDP socket failed: %s", sockstrerror(sockerrno));
188                 return -1;
189         }
190
191 #ifdef FD_CLOEXEC
192         fcntl(nfd, F_SETFD, FD_CLOEXEC);
193 #endif
194
195 #ifdef O_NONBLOCK
196         {
197                 int flags = fcntl(nfd, F_GETFL);
198
199                 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
200                         closesocket(nfd);
201                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "fcntl",
202                                    strerror(errno));
203                         return -1;
204                 }
205         }
206 #elif defined(WIN32)
207         {
208                 unsigned long arg = 1;
209                 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
210                         closesocket(nfd);
211                         logger(DEBUG_ALWAYS, LOG_ERR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
212                         return -1;
213                 }
214         }
215 #endif
216
217         option = 1;
218         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof option);
219         setsockopt(nfd, SOL_SOCKET, SO_BROADCAST, (void *)&option, sizeof option);
220
221         if(udp_rcvbuf && setsockopt(nfd, SOL_SOCKET, SO_RCVBUF, (void *)&udp_rcvbuf, sizeof(udp_rcvbuf)))
222                 logger(DEBUG_ALWAYS, LOG_WARNING, "Can't set UDP SO_RCVBUF to %i: %s", udp_rcvbuf, strerror(errno));
223
224         if(udp_sndbuf && setsockopt(nfd, SOL_SOCKET, SO_SNDBUF, (void *)&udp_sndbuf, sizeof(udp_sndbuf)))
225                 logger(DEBUG_ALWAYS, LOG_WARNING, "Can't set UDP SO_SNDBUF to %i: %s", udp_sndbuf, strerror(errno));
226
227 #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
228         if(sa->sa.sa_family == AF_INET6)
229                 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
230 #endif
231
232 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
233 #define IP_DONTFRAGMENT IP_DONTFRAG
234 #endif
235
236 #if defined(SOL_IP) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
237         if(myself->options & OPTION_PMTU_DISCOVERY) {
238                 option = IP_PMTUDISC_DO;
239                 setsockopt(nfd, SOL_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
240         }
241 #elif defined(IPPROTO_IP) && defined(IP_DONTFRAGMENT)
242         if(myself->options & OPTION_PMTU_DISCOVERY) {
243                 option = 1;
244                 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
245         }
246 #else
247 #warning No way to disable IPv4 fragmentation
248 #endif
249
250 #if defined(SOL_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
251         if(myself->options & OPTION_PMTU_DISCOVERY) {
252                 option = IPV6_PMTUDISC_DO;
253                 setsockopt(nfd, SOL_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
254         }
255 #elif defined(IPPROTO_IPV6) && defined(IPV6_DONTFRAG)
256         if(myself->options & OPTION_PMTU_DISCOVERY) {
257                 option = 1;
258                 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
259         }
260 #else
261 #warning No way to disable IPv6 fragmentation
262 #endif
263
264         if (!bind_to_interface(nfd)) {
265                 closesocket(nfd);
266                 return -1;
267         }
268
269         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
270                 closesocket(nfd);
271                 addrstr = sockaddr2hostname(sa);
272                 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
273                 free(addrstr);
274                 return -1;
275         }
276
277         return nfd;
278 } /* int setup_vpn_in_socket */
279
280 static void retry_outgoing_handler(void *data) {
281         setup_outgoing_connection(data);
282 }
283
284 void retry_outgoing(outgoing_t *outgoing) {
285         outgoing->timeout += 5;
286
287         if(outgoing->timeout > maxtimeout)
288                 outgoing->timeout = maxtimeout;
289
290         timeout_add(&outgoing->ev, retry_outgoing_handler, outgoing, &(struct timeval){outgoing->timeout, rand() % 100000});
291
292         logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Trying to re-establish outgoing connection in %d seconds", outgoing->timeout);
293 }
294
295 void finish_connecting(connection_t *c) {
296         logger(DEBUG_CONNECTIONS, LOG_INFO, "Connected to %s (%s)", c->name, c->hostname);
297
298         c->last_ping_time = now.tv_sec;
299         c->status.connecting = false;
300
301         send_id(c);
302 }
303
304 static void do_outgoing_pipe(connection_t *c, char *command) {
305 #ifndef HAVE_MINGW
306         int fd[2];
307
308         if(socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) {
309                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not create socketpair: %s", strerror(errno));
310                 return;
311         }
312
313         if(fork()) {
314                 c->socket = fd[0];
315                 close(fd[1]);
316                 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Using proxy %s", command);
317                 return;
318         }
319
320         close(0);
321         close(1);
322         close(fd[0]);
323         dup2(fd[1], 0);
324         dup2(fd[1], 1);
325         close(fd[1]);
326
327         // Other filedescriptors should be closed automatically by CLOEXEC
328
329         char *host = NULL;
330         char *port = NULL;
331
332         sockaddr2str(&c->address, &host, &port);
333         setenv("REMOTEADDRESS", host, true);
334         setenv("REMOTEPORT", port, true);
335         setenv("NODE", c->name, true);
336         setenv("NAME", myself->name, true);
337         if(netname)
338                 setenv("NETNAME", netname, true);
339
340         int result = system(command);
341         if(result < 0)
342                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not execute %s: %s", command, strerror(errno));
343         else if(result)
344                 logger(DEBUG_ALWAYS, LOG_ERR, "%s exited with non-zero status %d", command, result);
345         exit(result);
346 #else
347         logger(DEBUG_ALWAYS, LOG_ERR, "Proxy type exec not supported on this platform!");
348         return;
349 #endif
350 }
351
352 static void handle_meta_write(connection_t *c) {
353         if(c->outbuf.len <= c->outbuf.offset)
354                 return;
355
356         ssize_t outlen = send(c->socket, c->outbuf.data + c->outbuf.offset, c->outbuf.len - c->outbuf.offset, 0);
357         if(outlen <= 0) {
358                 if(!errno || errno == EPIPE) {
359                         logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection closed by %s (%s)", c->name, c->hostname);
360                 } else if(sockwouldblock(sockerrno)) {
361                         logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Sending %d bytes to %s (%s) would block", c->outbuf.len - c->outbuf.offset, c->name, c->hostname);
362                         return;
363                 } else {
364                         logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not send %d bytes of data to %s (%s): %s", c->outbuf.len - c->outbuf.offset, c->name, c->hostname, strerror(errno));
365                 }
366
367                 terminate_connection(c, c->status.active);
368                 return;
369         }
370
371         buffer_read(&c->outbuf, outlen);
372         if(!c->outbuf.len)
373                 io_set(&c->io, IO_READ);
374 }
375
376 static void handle_meta_io(void *data, int flags) {
377         connection_t *c = data;
378
379         if(c->status.connecting) {
380                 c->status.connecting = false;
381
382                 int result;
383                 socklen_t len = sizeof result;
384                 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
385
386                 if(!result)
387                         finish_connecting(c);
388                 else {
389                         logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Error while connecting to %s (%s): %s", c->name, c->hostname, sockstrerror(result));
390                         terminate_connection(c, false);
391                         return;
392                 }
393         }
394
395         if(flags & IO_WRITE)
396                 handle_meta_write(c);
397         else
398                 handle_meta_connection_data(c);
399 }
400
401 bool do_outgoing_connection(outgoing_t *outgoing) {
402         char *address, *port, *space;
403         struct addrinfo *proxyai = NULL;
404         int result;
405
406 begin:
407         if(!outgoing->ai) {
408                 if(!outgoing->cfg) {
409                         logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not set up a meta connection to %s", outgoing->name);
410                         retry_outgoing(outgoing);
411                         return false;
412                 }
413
414                 get_config_string(outgoing->cfg, &address);
415
416                 space = strchr(address, ' ');
417                 if(space) {
418                         port = xstrdup(space + 1);
419                         *space = 0;
420                 } else {
421                         if(!get_config_string(lookup_config(outgoing->config_tree, "Port"), &port))
422                                 port = xstrdup("655");
423                 }
424
425                 outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
426                 free(address);
427                 free(port);
428
429                 outgoing->aip = outgoing->ai;
430                 outgoing->cfg = lookup_config_next(outgoing->config_tree, outgoing->cfg);
431         }
432
433         if(!outgoing->aip) {
434                 if(outgoing->ai)
435                         freeaddrinfo(outgoing->ai);
436                 outgoing->ai = NULL;
437                 goto begin;
438         }
439
440         connection_t *c = new_connection();
441         c->outgoing = outgoing;
442
443         memcpy(&c->address, outgoing->aip->ai_addr, outgoing->aip->ai_addrlen);
444         outgoing->aip = outgoing->aip->ai_next;
445
446         c->hostname = sockaddr2hostname(&c->address);
447
448         logger(DEBUG_CONNECTIONS, LOG_INFO, "Trying to connect to %s (%s)", outgoing->name, c->hostname);
449
450         if(!proxytype) {
451                 c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
452                 configure_tcp(c);
453         } else if(proxytype == PROXY_EXEC) {
454                 do_outgoing_pipe(c, proxyhost);
455         } else {
456                 proxyai = str2addrinfo(proxyhost, proxyport, SOCK_STREAM);
457                 if(!proxyai) {
458                         free_connection(c);
459                         goto begin;
460                 }
461                 logger(DEBUG_CONNECTIONS, LOG_INFO, "Using proxy at %s port %s", proxyhost, proxyport);
462                 c->socket = socket(proxyai->ai_family, SOCK_STREAM, IPPROTO_TCP);
463                 configure_tcp(c);
464         }
465
466         if(c->socket == -1) {
467                 logger(DEBUG_CONNECTIONS, LOG_ERR, "Creating socket for %s failed: %s", c->hostname, sockstrerror(sockerrno));
468                 free_connection(c);
469                 goto begin;
470         }
471
472 #ifdef FD_CLOEXEC
473         fcntl(c->socket, F_SETFD, FD_CLOEXEC);
474 #endif
475
476         if(proxytype != PROXY_EXEC) {
477 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
478                 int option = 1;
479                 if(c->address.sa.sa_family == AF_INET6)
480                         setsockopt(c->socket, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
481 #endif
482
483                 bind_to_interface(c->socket);
484         }
485
486         /* Connect */
487
488         if(!proxytype) {
489                 result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
490         } else if(proxytype == PROXY_EXEC) {
491                 result = 0;
492         } else {
493                 result = connect(c->socket, proxyai->ai_addr, proxyai->ai_addrlen);
494                 freeaddrinfo(proxyai);
495         }
496
497         if(result == -1 && !sockinprogress(sockerrno)) {
498                 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not connect to %s (%s): %s", outgoing->name, c->hostname, sockstrerror(sockerrno));
499                 free_connection(c);
500
501                 goto begin;
502         }
503
504         /* Now that there is a working socket, fill in the rest and register this connection. */
505
506         c->status.connecting = true;
507         c->name = xstrdup(outgoing->name);
508         c->outcipher = myself->connection->outcipher;
509         c->outdigest = myself->connection->outdigest;
510         c->outmaclength = myself->connection->outmaclength;
511         c->outcompression = myself->connection->outcompression;
512         c->last_ping_time = now.tv_sec;
513
514         connection_add(c);
515
516         io_add(&c->io, handle_meta_io, c, c->socket, IO_READ|IO_WRITE);
517
518         return true;
519 }
520
521 void setup_outgoing_connection(outgoing_t *outgoing) {
522         timeout_del(&outgoing->ev);
523
524         node_t *n = lookup_node(outgoing->name);
525
526         if(n && n->connection) {
527                 logger(DEBUG_CONNECTIONS, LOG_INFO, "Already connected to %s", outgoing->name);
528
529                 n->connection->outgoing = outgoing;
530                 return;
531         }
532
533         init_configuration(&outgoing->config_tree);
534         read_host_config(outgoing->config_tree, outgoing->name);
535         outgoing->cfg = lookup_config(outgoing->config_tree, "Address");
536
537         if(!outgoing->cfg) {
538                 logger(DEBUG_ALWAYS, LOG_ERR, "No address specified for %s", outgoing->name);
539                 return;
540         }
541
542         do_outgoing_connection(outgoing);
543 }
544
545 /*
546   accept a new tcp connect and create a
547   new connection
548 */
549 void handle_new_meta_connection(void *data, int flags) {
550         listen_socket_t *l = data;
551         connection_t *c;
552         sockaddr_t sa;
553         int fd;
554         socklen_t len = sizeof sa;
555
556         fd = accept(l->tcp.fd, &sa.sa, &len);
557
558         if(fd < 0) {
559                 logger(DEBUG_ALWAYS, LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
560                 return;
561         }
562
563         sockaddrunmap(&sa);
564
565         // Check if we get many connections from the same host
566
567         static sockaddr_t prev_sa;
568         static time_t prev_time;
569         static int tarpit = -1;
570
571         if(tarpit >= 0) {
572                 closesocket(tarpit);
573                 tarpit = -1;
574         }
575
576         if(prev_time == now.tv_sec && !sockaddrcmp_noport(&sa, &prev_sa)) {
577                 // if so, keep the connection open but ignore it completely.
578                 tarpit = fd;
579                 return;
580         }
581
582         memcpy(&prev_sa, &sa, sizeof sa);
583         prev_time = now.tv_sec;
584
585         // Check if we get many connections from different hosts
586
587         static int connection_burst;
588         static int connection_burst_time;
589
590         if(now.tv_sec - connection_burst_time > connection_burst)
591                 connection_burst = 0;
592         else
593                 connection_burst -= now.tv_sec - connection_burst_time;
594
595         connection_burst_time = now.tv_sec;
596         connection_burst++;
597
598         if(connection_burst >= max_connection_burst) {
599                 connection_burst = max_connection_burst;
600                 tarpit = fd;
601                 return;
602         }
603
604         // Accept the new connection
605
606         c = new_connection();
607         c->name = xstrdup("<unknown>");
608         c->outcipher = myself->connection->outcipher;
609         c->outdigest = myself->connection->outdigest;
610         c->outmaclength = myself->connection->outmaclength;
611         c->outcompression = myself->connection->outcompression;
612
613         c->address = sa;
614         c->hostname = sockaddr2hostname(&sa);
615         c->socket = fd;
616         c->last_ping_time = now.tv_sec;
617
618         logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection from %s", c->hostname);
619
620         io_add(&c->io, handle_meta_io, c, c->socket, IO_READ);
621
622         configure_tcp(c);
623
624         connection_add(c);
625
626         c->allow_request = ID;
627         send_id(c);
628 }
629
630 #ifndef HAVE_MINGW
631 /*
632   accept a new UNIX socket connection
633 */
634 void handle_new_unix_connection(void *data, int flags) {
635         io_t *io = data;
636         connection_t *c;
637         sockaddr_t sa;
638         int fd;
639         socklen_t len = sizeof sa;
640
641         fd = accept(io->fd, &sa.sa, &len);
642
643         if(fd < 0) {
644                 logger(DEBUG_ALWAYS, LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
645                 return;
646         }
647
648         sockaddrunmap(&sa);
649
650         c = new_connection();
651         c->name = xstrdup("<control>");
652         c->address = sa;
653         c->hostname = xstrdup("localhost port unix");
654         c->socket = fd;
655         c->last_ping_time = now.tv_sec;
656
657         logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection from %s", c->hostname);
658
659         io_add(&c->io, handle_meta_io, c, c->socket, IO_READ);
660
661         connection_add(c);
662
663         c->allow_request = ID;
664
665         send_id(c);
666 }
667 #endif
668
669 static void free_outgoing(outgoing_t *outgoing) {
670         timeout_del(&outgoing->ev);
671
672         if(outgoing->ai)
673                 freeaddrinfo(outgoing->ai);
674
675         if(outgoing->config_tree)
676                 exit_configuration(&outgoing->config_tree);
677
678         if(outgoing->name)
679                 free(outgoing->name);
680
681         free(outgoing);
682 }
683
684 void try_outgoing_connections(void) {
685         /* If there is no outgoing list yet, create one. Otherwise, mark all outgoings as deleted. */
686
687         if(!outgoing_list) {
688                 outgoing_list = list_alloc((list_action_t)free_outgoing);
689         } else {
690                 for list_each(outgoing_t, outgoing, outgoing_list)
691                         outgoing->timeout = -1;
692         }
693
694         /* Make sure there is one outgoing_t in the list for each ConnectTo. */
695
696         for(config_t *cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
697                 char *name;
698                 get_config_string(cfg, &name);
699
700                 if(!check_id(name)) {
701                         logger(DEBUG_ALWAYS, LOG_ERR,
702                                    "Invalid name for outgoing connection in %s line %d",
703                                    cfg->file, cfg->line);
704                         free(name);
705                         continue;
706                 }
707
708                 bool found = false;
709
710                 for list_each(outgoing_t, outgoing, outgoing_list) {
711                         if(!strcmp(outgoing->name, name)) {
712                                 found = true;
713                                 outgoing->timeout = 0;
714                                 break;
715                         }
716                 }
717
718                 if(!found) {
719                         outgoing_t *outgoing = xzalloc(sizeof *outgoing);
720                         outgoing->name = name;
721                         list_insert_tail(outgoing_list, outgoing);
722                         setup_outgoing_connection(outgoing);
723                 }
724         }
725
726         /* Terminate any connections whose outgoing_t is to be deleted. */
727
728         for list_each(connection_t, c, connection_list) {
729                 if(c->outgoing && c->outgoing->timeout == -1) {
730                         c->outgoing = NULL;
731                         logger(DEBUG_CONNECTIONS, LOG_INFO, "No more outgoing connection to %s", c->name);
732                         terminate_connection(c, c->status.active);
733                 }
734         }
735
736         /* Delete outgoing_ts for which there is no ConnectTo. */
737
738         for list_each(outgoing_t, outgoing, outgoing_list)
739                 if(outgoing->timeout == -1)
740                         list_delete_node(outgoing_list, node);
741 }