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