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