40671db0183e061dc01b309b1b36832fd94e5a4e
[tinc] / src / net_socket.c
1 /*
2     net_socket.c -- Handle various kinds of sockets.
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2018 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 "address_cache.h"
26 #include "conf.h"
27 #include "connection.h"
28 #include "list.h"
29 #include "logger.h"
30 #include "names.h"
31 #include "net.h"
32 #include "netutl.h"
33 #include "protocol.h"
34 #include "utils.h"
35 #include "xalloc.h"
36
37 int addressfamily = AF_UNSPEC;
38 int maxtimeout = 900;
39 int seconds_till_retry = 5;
40 int udp_rcvbuf = 1024 * 1024;
41 int udp_sndbuf = 1024 * 1024;
42 bool udp_rcvbuf_warnings;
43 bool udp_sndbuf_warnings;
44 int max_connection_burst = 10;
45 int fwmark;
46
47 listen_socket_t listen_socket[MAXSOCKETS];
48 int listen_sockets;
49 #ifndef HAVE_MINGW
50 io_t unix_socket;
51 #endif
52 list_t *outgoing_list = NULL;
53
54 /* Setup sockets */
55
56 static void configure_tcp(connection_t *c) {
57         int option;
58
59 #ifdef O_NONBLOCK
60         int flags = fcntl(c->socket, F_GETFL);
61
62         if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0) {
63                 logger(DEBUG_ALWAYS, LOG_ERR, "fcntl for %s fd %d: %s", c->hostname, c->socket, strerror(errno));
64         }
65
66 #elif defined(WIN32)
67         unsigned long arg = 1;
68
69         if(ioctlsocket(c->socket, FIONBIO, &arg) != 0) {
70                 logger(DEBUG_ALWAYS, LOG_ERR, "ioctlsocket for %s fd %d: %s", c->hostname, c->socket, sockstrerror(sockerrno));
71         }
72
73 #endif
74
75 #if defined(TCP_NODELAY)
76         option = 1;
77         setsockopt(c->socket, IPPROTO_TCP, TCP_NODELAY, (void *)&option, sizeof(option));
78 #endif
79
80 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
81         option = IPTOS_LOWDELAY;
82         setsockopt(c->socket, IPPROTO_IP, IP_TOS, (void *)&option, sizeof(option));
83 #endif
84
85 #if defined(IPV6_TCLASS) && defined(IPTOS_LOWDELAY)
86         option = IPTOS_LOWDELAY;
87         setsockopt(c->socket, IPPROTO_IPV6, IPV6_TCLASS, (void *)&option, sizeof(option));
88 #endif
89
90 #if defined(SO_MARK)
91
92         if(fwmark) {
93                 setsockopt(c->socket, SOL_SOCKET, SO_MARK, (void *)&fwmark, sizeof(fwmark));
94         }
95
96 #endif
97 }
98
99 static bool bind_to_interface(int sd) {
100         char *iface;
101
102 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
103         struct ifreq ifr;
104         int status;
105 #endif /* defined(SOL_SOCKET) && defined(SO_BINDTODEVICE) */
106
107         if(!get_config_string(lookup_config(config_tree, "BindToInterface"), &iface)) {
108                 return true;
109         }
110
111 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
112         memset(&ifr, 0, sizeof(ifr));
113         strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
114         ifr.ifr_ifrn.ifrn_name[IFNAMSIZ - 1] = 0;
115
116         status = setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr));
117
118         if(status) {
119                 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to interface %s: %s", iface,
120                        sockstrerror(sockerrno));
121                 return false;
122         }
123
124 #else /* if !defined(SOL_SOCKET) || !defined(SO_BINDTODEVICE) */
125         (void)sd;
126         logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform", "BindToInterface");
127 #endif
128
129         return true;
130 }
131
132 static bool bind_to_address(connection_t *c) {
133         int s = -1;
134
135         for(int i = 0; i < listen_sockets && listen_socket[i].bindto; i++) {
136                 if(listen_socket[i].sa.sa.sa_family != c->address.sa.sa_family) {
137                         continue;
138                 }
139
140                 if(s >= 0) {
141                         return false;
142                 }
143
144                 s = i;
145         }
146
147         if(s < 0) {
148                 return false;
149         }
150
151         sockaddr_t sa = listen_socket[s].sa;
152
153         if(sa.sa.sa_family == AF_INET) {
154                 sa.in.sin_port = 0;
155         } else if(sa.sa.sa_family == AF_INET6) {
156                 sa.in6.sin6_port = 0;
157         }
158
159         if(bind(c->socket, &sa.sa, SALEN(sa.sa))) {
160                 logger(DEBUG_CONNECTIONS, LOG_WARNING, "Can't bind outgoing socket: %s", sockstrerror(sockerrno));
161                 return false;
162         }
163
164         return true;
165 }
166
167 int setup_listen_socket(const sockaddr_t *sa) {
168         int nfd;
169         char *addrstr;
170         int option;
171         char *iface;
172
173         nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
174
175         if(nfd < 0) {
176                 logger(DEBUG_STATUS, LOG_ERR, "Creating metasocket failed: %s", sockstrerror(sockerrno));
177                 return -1;
178         }
179
180 #ifdef FD_CLOEXEC
181         fcntl(nfd, F_SETFD, FD_CLOEXEC);
182 #endif
183
184         /* Optimize TCP settings */
185
186         option = 1;
187         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
188
189 #if defined(IPV6_V6ONLY)
190
191         if(sa->sa.sa_family == AF_INET6) {
192                 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
193         }
194
195 #else
196 #warning IPV6_V6ONLY not defined
197 #endif
198
199 #if defined(SO_MARK)
200
201         if(fwmark) {
202                 setsockopt(nfd, SOL_SOCKET, SO_MARK, (void *)&fwmark, sizeof(fwmark));
203         }
204
205 #endif
206
207         if(get_config_string
208                         (lookup_config(config_tree, "BindToInterface"), &iface)) {
209 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
210                 struct ifreq ifr;
211
212                 memset(&ifr, 0, sizeof(ifr));
213                 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
214                 ifr.ifr_ifrn.ifrn_name[IFNAMSIZ - 1] = 0;
215
216                 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr))) {
217                         closesocket(nfd);
218                         logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to interface %s: %s", iface,
219                                sockstrerror(sockerrno));
220                         return -1;
221                 }
222
223 #else
224                 logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform", "BindToInterface");
225 #endif
226         }
227
228         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
229                 closesocket(nfd);
230                 addrstr = sockaddr2hostname(sa);
231                 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
232                 free(addrstr);
233                 return -1;
234         }
235
236         if(listen(nfd, 3)) {
237                 closesocket(nfd);
238                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
239                 return -1;
240         }
241
242         return nfd;
243 }
244
245 static void set_udp_buffer(int nfd, int type, const char *name, int size, bool warnings) {
246         if(!size) {
247                 return;
248         }
249
250         if(setsockopt(nfd, SOL_SOCKET, type, (void *)&size, sizeof(size))) {
251                 logger(DEBUG_ALWAYS, LOG_WARNING, "Can't set UDP %s to %i: %s", name, size, sockstrerror(sockerrno));
252                 return;
253         }
254
255         if(!warnings) {
256                 return;
257         }
258
259         // The system may cap the requested buffer size.
260         // Read back the value and check if it is now as requested.
261         int actual = -1;
262         socklen_t optlen = sizeof(actual);
263
264         if(getsockopt(nfd, SOL_SOCKET, type, (void *)&actual, &optlen)) {
265                 logger(DEBUG_ALWAYS, LOG_WARNING, "Can't read back UDP %s: %s", name, sockstrerror(sockerrno));
266         } else if(optlen != sizeof(actual)) {
267                 logger(DEBUG_ALWAYS, LOG_WARNING, "Can't read back UDP %s: unexpected returned optlen %d", name, (int)optlen);
268         } else if(actual < size) {
269                 logger(DEBUG_ALWAYS, LOG_WARNING, "Can't set UDP %s to %i, the system set it to %i instead", name, size, actual);
270         }
271 }
272
273
274 int setup_vpn_in_socket(const sockaddr_t *sa) {
275         int nfd;
276         char *addrstr;
277         int option;
278
279         nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
280
281         if(nfd < 0) {
282                 logger(DEBUG_ALWAYS, LOG_ERR, "Creating UDP socket failed: %s", sockstrerror(sockerrno));
283                 return -1;
284         }
285
286 #ifdef FD_CLOEXEC
287         fcntl(nfd, F_SETFD, FD_CLOEXEC);
288 #endif
289
290 #ifdef O_NONBLOCK
291         {
292                 int flags = fcntl(nfd, F_GETFL);
293
294                 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
295                         closesocket(nfd);
296                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "fcntl",
297                                strerror(errno));
298                         return -1;
299                 }
300         }
301 #elif defined(WIN32)
302         {
303                 unsigned long arg = 1;
304
305                 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
306                         closesocket(nfd);
307                         logger(DEBUG_ALWAYS, LOG_ERR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
308                         return -1;
309                 }
310         }
311 #endif
312
313         option = 1;
314         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
315         setsockopt(nfd, SOL_SOCKET, SO_BROADCAST, (void *)&option, sizeof(option));
316
317         set_udp_buffer(nfd, SO_RCVBUF, "SO_RCVBUF", udp_rcvbuf, udp_rcvbuf_warnings);
318         set_udp_buffer(nfd, SO_SNDBUF, "SO_SNDBUF", udp_sndbuf, udp_sndbuf_warnings);
319
320 #if defined(IPV6_V6ONLY)
321
322         if(sa->sa.sa_family == AF_INET6) {
323                 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
324         }
325
326 #endif
327
328 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
329 #define IP_DONTFRAGMENT IP_DONTFRAG
330 #endif
331
332 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
333
334         if(myself->options & OPTION_PMTU_DISCOVERY) {
335                 option = IP_PMTUDISC_DO;
336                 setsockopt(nfd, IPPROTO_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
337         }
338
339 #elif defined(IP_DONTFRAGMENT)
340
341         if(myself->options & OPTION_PMTU_DISCOVERY) {
342                 option = 1;
343                 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
344         }
345
346 #endif
347
348 #if defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
349
350         if(myself->options & OPTION_PMTU_DISCOVERY) {
351                 option = IPV6_PMTUDISC_DO;
352                 setsockopt(nfd, IPPROTO_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
353         }
354
355 #elif defined(IPV6_DONTFRAG)
356
357         if(myself->options & OPTION_PMTU_DISCOVERY) {
358                 option = 1;
359                 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
360         }
361
362 #endif
363
364 #if defined(SO_MARK)
365
366         if(fwmark) {
367                 setsockopt(nfd, SOL_SOCKET, SO_MARK, (void *)&fwmark, sizeof(fwmark));
368         }
369
370 #endif
371
372         if(!bind_to_interface(nfd)) {
373                 closesocket(nfd);
374                 return -1;
375         }
376
377         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
378                 closesocket(nfd);
379                 addrstr = sockaddr2hostname(sa);
380                 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
381                 free(addrstr);
382                 return -1;
383         }
384
385         return nfd;
386 } /* int setup_vpn_in_socket */
387
388 static void retry_outgoing_handler(void *data) {
389         setup_outgoing_connection(data, true);
390 }
391
392 void retry_outgoing(outgoing_t *outgoing) {
393         outgoing->timeout += 5;
394
395         if(outgoing->timeout > maxtimeout) {
396                 outgoing->timeout = maxtimeout;
397         }
398
399         timeout_add(&outgoing->ev, retry_outgoing_handler, outgoing, &(struct timeval) {
400                 outgoing->timeout, rand() % 100000
401         });
402
403         logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Trying to re-establish outgoing connection in %d seconds", outgoing->timeout);
404 }
405
406 void finish_connecting(connection_t *c) {
407         logger(DEBUG_CONNECTIONS, LOG_INFO, "Connected to %s (%s)", c->name, c->hostname);
408
409         c->last_ping_time = now.tv_sec;
410         c->status.connecting = false;
411
412         send_id(c);
413 }
414
415 static void do_outgoing_pipe(connection_t *c, const char *command) {
416 #ifndef HAVE_MINGW
417         int fd[2];
418
419         if(socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) {
420                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not create socketpair: %s", sockstrerror(sockerrno));
421                 return;
422         }
423
424         if(fork()) {
425                 c->socket = fd[0];
426                 close(fd[1]);
427                 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Using proxy %s", command);
428                 return;
429         }
430
431         close(0);
432         close(1);
433         close(fd[0]);
434         dup2(fd[1], 0);
435         dup2(fd[1], 1);
436         close(fd[1]);
437
438         // Other filedescriptors should be closed automatically by CLOEXEC
439
440         char *host = NULL;
441         char *port = NULL;
442
443         sockaddr2str(&c->address, &host, &port);
444         setenv("REMOTEADDRESS", host, true);
445         setenv("REMOTEPORT", port, true);
446         setenv("NODE", c->name, true);
447         setenv("NAME", myself->name, true);
448
449         if(netname) {
450                 setenv("NETNAME", netname, true);
451         }
452
453         int result = system(command);
454
455         if(result < 0) {
456                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not execute %s: %s", command, strerror(errno));
457         } else if(result) {
458                 logger(DEBUG_ALWAYS, LOG_ERR, "%s exited with non-zero status %d", command, result);
459         }
460
461         exit(result);
462 #else
463         (void)c;
464         (void)command;
465         logger(DEBUG_ALWAYS, LOG_ERR, "Proxy type exec not supported on this platform!");
466         return;
467 #endif
468 }
469
470 static void handle_meta_write(connection_t *c) {
471         if(c->outbuf.len <= c->outbuf.offset) {
472                 return;
473         }
474
475         ssize_t outlen = send(c->socket, c->outbuf.data + c->outbuf.offset, c->outbuf.len - c->outbuf.offset, 0);
476
477         if(outlen <= 0) {
478                 if(!sockerrno || sockerrno == EPIPE) {
479                         logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection closed by %s (%s)", c->name, c->hostname);
480                 } else if(sockwouldblock(sockerrno)) {
481                         logger(DEBUG_META, LOG_DEBUG, "Sending %d bytes to %s (%s) would block", c->outbuf.len - c->outbuf.offset, c->name, c->hostname);
482                         return;
483                 } else {
484                         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, sockstrerror(sockerrno));
485                 }
486
487                 terminate_connection(c, c->edge);
488                 return;
489         }
490
491         buffer_read(&c->outbuf, outlen);
492
493         if(!c->outbuf.len) {
494                 io_set(&c->io, IO_READ);
495         }
496 }
497
498 static void handle_meta_io(void *data, int flags) {
499         connection_t *c = data;
500
501         if(c->status.connecting) {
502                 /*
503                    The event loop does not protect against spurious events. Verify that we are actually connected
504                    by issuing an empty send() call.
505
506                    Note that the behavior of send() on potentially unconnected sockets differ between platforms:
507                    +------------+-----------+-------------+-----------+
508                    |   Event    |   POSIX   |    Linux    |  Windows  |
509                    +------------+-----------+-------------+-----------+
510                    | Spurious   | ENOTCONN  | EWOULDBLOCK | ENOTCONN  |
511                    | Failed     | ENOTCONN  | (cause)     | ENOTCONN  |
512                    | Successful | (success) | (success)   | (success) |
513                    +------------+-----------+-------------+-----------+
514                 */
515                 if(send(c->socket, NULL, 0, 0) != 0) {
516                         if(sockwouldblock(sockerrno)) {
517                                 return;
518                         }
519
520                         int socket_error;
521
522                         if(!socknotconn(sockerrno)) {
523                                 socket_error = sockerrno;
524                         } else {
525                                 socklen_t len = sizeof(socket_error);
526                                 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&socket_error, &len);
527                         }
528
529                         if(socket_error) {
530                                 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Error while connecting to %s (%s): %s", c->name, c->hostname, sockstrerror(socket_error));
531                                 terminate_connection(c, false);
532                         }
533
534                         return;
535                 }
536
537                 c->status.connecting = false;
538                 finish_connecting(c);
539         }
540
541         if(flags & IO_WRITE) {
542                 handle_meta_write(c);
543         } else {
544                 handle_meta_connection_data(c);
545         }
546 }
547
548 bool do_outgoing_connection(outgoing_t *outgoing) {
549         const sockaddr_t *sa;
550         struct addrinfo *proxyai = NULL;
551         int result;
552
553 begin:
554         sa = get_recent_address(outgoing->node->address_cache);
555
556         if(!sa) {
557                 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not set up a meta connection to %s", outgoing->node->name);
558                 retry_outgoing(outgoing);
559                 return false;
560         }
561
562         connection_t *c = new_connection();
563         c->outgoing = outgoing;
564         memcpy(&c->address, sa, SALEN(sa->sa));
565         c->hostname = sockaddr2hostname(&c->address);
566
567         logger(DEBUG_CONNECTIONS, LOG_INFO, "Trying to connect to %s (%s)", outgoing->node->name, c->hostname);
568
569         if(!proxytype) {
570                 c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
571                 configure_tcp(c);
572         } else if(proxytype == PROXY_EXEC) {
573                 do_outgoing_pipe(c, proxyhost);
574         } else {
575                 proxyai = str2addrinfo(proxyhost, proxyport, SOCK_STREAM);
576
577                 if(!proxyai) {
578                         free_connection(c);
579                         goto begin;
580                 }
581
582                 logger(DEBUG_CONNECTIONS, LOG_INFO, "Using proxy at %s port %s", proxyhost, proxyport);
583                 c->socket = socket(proxyai->ai_family, SOCK_STREAM, IPPROTO_TCP);
584                 configure_tcp(c);
585         }
586
587         if(c->socket == -1) {
588                 logger(DEBUG_CONNECTIONS, LOG_ERR, "Creating socket for %s failed: %s", c->hostname, sockstrerror(sockerrno));
589                 free_connection(c);
590                 goto begin;
591         }
592
593 #ifdef FD_CLOEXEC
594         fcntl(c->socket, F_SETFD, FD_CLOEXEC);
595 #endif
596
597         if(proxytype != PROXY_EXEC) {
598 #if defined(IPV6_V6ONLY)
599                 int option = 1;
600
601                 if(c->address.sa.sa_family == AF_INET6) {
602                         setsockopt(c->socket, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
603                 }
604
605 #endif
606
607                 bind_to_interface(c->socket);
608                 bind_to_address(c);
609         }
610
611         /* Connect */
612
613         if(!proxytype) {
614                 result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
615         } else if(proxytype == PROXY_EXEC) {
616                 result = 0;
617         } else {
618                 if(!proxyai) {
619                         abort();
620                 }
621
622                 result = connect(c->socket, proxyai->ai_addr, proxyai->ai_addrlen);
623                 freeaddrinfo(proxyai);
624         }
625
626         if(result == -1 && !sockinprogress(sockerrno)) {
627                 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not connect to %s (%s): %s", outgoing->node->name, c->hostname, sockstrerror(sockerrno));
628                 free_connection(c);
629
630                 goto begin;
631         }
632
633         /* Now that there is a working socket, fill in the rest and register this connection. */
634
635         c->last_ping_time = time(NULL);
636         c->status.connecting = true;
637         c->name = xstrdup(outgoing->node->name);
638 #ifndef DISABLE_LEGACY
639         c->outcipher = myself->connection->outcipher;
640         c->outdigest = myself->connection->outdigest;
641 #endif
642         c->outmaclength = myself->connection->outmaclength;
643         c->outcompression = myself->connection->outcompression;
644         c->last_ping_time = now.tv_sec;
645
646         connection_add(c);
647
648         io_add(&c->io, handle_meta_io, c, c->socket, IO_READ | IO_WRITE);
649
650         return true;
651 }
652
653 void setup_outgoing_connection(outgoing_t *outgoing, bool verbose) {
654         (void)verbose;
655         timeout_del(&outgoing->ev);
656
657         node_t *n = outgoing->node;
658
659         if(!n->address_cache) {
660                 n->address_cache = open_address_cache(n);
661         }
662
663         if(n->connection) {
664                 logger(DEBUG_CONNECTIONS, LOG_INFO, "Already connected to %s", n->name);
665
666                 if(!n->connection->outgoing) {
667                         n->connection->outgoing = outgoing;
668                         return;
669                 } else {
670                         goto remove;
671                 }
672         }
673
674         do_outgoing_connection(outgoing);
675         return;
676
677 remove:
678         list_delete(outgoing_list, outgoing);
679 }
680
681 /*
682   accept a new tcp connect and create a
683   new connection
684 */
685 void handle_new_meta_connection(void *data, int flags) {
686         (void)flags;
687         listen_socket_t *l = data;
688         connection_t *c;
689         sockaddr_t sa;
690         int fd;
691         socklen_t len = sizeof(sa);
692
693         fd = accept(l->tcp.fd, &sa.sa, &len);
694
695         if(fd < 0) {
696                 logger(DEBUG_ALWAYS, LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
697                 return;
698         }
699
700         sockaddrunmap(&sa);
701
702         // Check if we get many connections from the same host
703
704         static sockaddr_t prev_sa;
705
706         if(!sockaddrcmp_noport(&sa, &prev_sa)) {
707                 static time_t samehost_burst;
708                 static time_t samehost_burst_time;
709
710                 if(now.tv_sec - samehost_burst_time > samehost_burst) {
711                         samehost_burst = 0;
712                 } else {
713                         samehost_burst -= now.tv_sec - samehost_burst_time;
714                 }
715
716                 samehost_burst_time = now.tv_sec;
717                 samehost_burst++;
718
719                 if(samehost_burst > max_connection_burst) {
720                         tarpit(fd);
721                         return;
722                 }
723         }
724
725         memcpy(&prev_sa, &sa, sizeof(sa));
726
727         // Check if we get many connections from different hosts
728
729         static time_t connection_burst;
730         static time_t connection_burst_time;
731
732         if(now.tv_sec - connection_burst_time > connection_burst) {
733                 connection_burst = 0;
734         } else {
735                 connection_burst -= now.tv_sec - connection_burst_time;
736         }
737
738         connection_burst_time = now.tv_sec;
739         connection_burst++;
740
741         if(connection_burst >= max_connection_burst) {
742                 connection_burst = max_connection_burst;
743                 tarpit(fd);
744                 return;
745         }
746
747         // Accept the new connection
748
749         c = new_connection();
750         c->name = xstrdup("<unknown>");
751 #ifndef DISABLE_LEGACY
752         c->outcipher = myself->connection->outcipher;
753         c->outdigest = myself->connection->outdigest;
754 #endif
755         c->outmaclength = myself->connection->outmaclength;
756         c->outcompression = myself->connection->outcompression;
757
758         c->address = sa;
759         c->hostname = sockaddr2hostname(&sa);
760         c->socket = fd;
761         c->last_ping_time = now.tv_sec;
762
763         logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection from %s", c->hostname);
764
765         io_add(&c->io, handle_meta_io, c, c->socket, IO_READ);
766
767         configure_tcp(c);
768
769         connection_add(c);
770
771         c->allow_request = ID;
772 }
773
774 #ifndef HAVE_MINGW
775 /*
776   accept a new UNIX socket connection
777 */
778 void handle_new_unix_connection(void *data, int flags) {
779         (void)flags;
780         io_t *io = data;
781         connection_t *c;
782         sockaddr_t sa;
783         int fd;
784         socklen_t len = sizeof(sa);
785
786         fd = accept(io->fd, &sa.sa, &len);
787
788         if(fd < 0) {
789                 logger(DEBUG_ALWAYS, LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
790                 return;
791         }
792
793         sockaddrunmap(&sa);
794
795         c = new_connection();
796         c->name = xstrdup("<control>");
797         c->address = sa;
798         c->hostname = xstrdup("localhost port unix");
799         c->socket = fd;
800         c->last_ping_time = now.tv_sec;
801
802         logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection from %s", c->hostname);
803
804         io_add(&c->io, handle_meta_io, c, c->socket, IO_READ);
805
806         connection_add(c);
807
808         c->allow_request = ID;
809 }
810 #endif
811
812 static void free_outgoing(outgoing_t *outgoing) {
813         timeout_del(&outgoing->ev);
814         free(outgoing);
815 }
816
817 void try_outgoing_connections(void) {
818         /* If there is no outgoing list yet, create one. Otherwise, mark all outgoings as deleted. */
819
820         if(!outgoing_list) {
821                 outgoing_list = list_alloc((list_action_t)free_outgoing);
822         } else {
823                 for list_each(outgoing_t, outgoing, outgoing_list) {
824                         outgoing->timeout = -1;
825                 }
826         }
827
828         /* Make sure there is one outgoing_t in the list for each ConnectTo. */
829
830         for(config_t *cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
831                 char *name;
832                 get_config_string(cfg, &name);
833
834                 if(!check_id(name)) {
835                         logger(DEBUG_ALWAYS, LOG_ERR,
836                                "Invalid name for outgoing connection in %s line %d",
837                                cfg->file, cfg->line);
838                         free(name);
839                         continue;
840                 }
841
842                 if(!strcmp(name, myself->name)) {
843                         free(name);
844                         continue;
845                 }
846
847                 bool found = false;
848
849                 for list_each(outgoing_t, outgoing, outgoing_list) {
850                         if(!strcmp(outgoing->node->name, name)) {
851                                 found = true;
852                                 outgoing->timeout = 0;
853                                 break;
854                         }
855                 }
856
857                 if(!found) {
858                         outgoing_t *outgoing = xzalloc(sizeof(*outgoing));
859                         node_t *n = lookup_node(name);
860
861                         if(!n) {
862                                 n = new_node();
863                                 n->name = xstrdup(name);
864                                 node_add(n);
865                         }
866
867                         free(name);
868
869                         outgoing->node = n;
870                         list_insert_tail(outgoing_list, outgoing);
871                         setup_outgoing_connection(outgoing, true);
872                 }
873         }
874
875         /* Terminate any connections whose outgoing_t is to be deleted. */
876
877         for list_each(connection_t, c, connection_list) {
878                 if(c->outgoing && c->outgoing->timeout == -1) {
879                         c->outgoing = NULL;
880                         logger(DEBUG_CONNECTIONS, LOG_INFO, "No more outgoing connection to %s", c->name);
881                         terminate_connection(c, c->edge);
882                 }
883         }
884
885         /* Delete outgoing_ts for which there is no ConnectTo. */
886
887         for list_each(outgoing_t, outgoing, outgoing_list)
888                 if(outgoing->timeout == -1) {
889                         list_delete_node(outgoing_list, node);
890                 }
891 }