afe349d9e22611dab6736cf74f1a66c9ad704a88
[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 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 int setup_vpn_in_socket(const sockaddr_t *sa) {
246         int nfd;
247         char *addrstr;
248         int option;
249
250         nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
251
252         if(nfd < 0) {
253                 logger(DEBUG_ALWAYS, LOG_ERR, "Creating UDP socket failed: %s", sockstrerror(sockerrno));
254                 return -1;
255         }
256
257 #ifdef FD_CLOEXEC
258         fcntl(nfd, F_SETFD, FD_CLOEXEC);
259 #endif
260
261 #ifdef O_NONBLOCK
262         {
263                 int flags = fcntl(nfd, F_GETFL);
264
265                 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
266                         closesocket(nfd);
267                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "fcntl",
268                                strerror(errno));
269                         return -1;
270                 }
271         }
272 #elif defined(WIN32)
273         {
274                 unsigned long arg = 1;
275
276                 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
277                         closesocket(nfd);
278                         logger(DEBUG_ALWAYS, LOG_ERR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
279                         return -1;
280                 }
281         }
282 #endif
283
284         option = 1;
285         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
286         setsockopt(nfd, SOL_SOCKET, SO_BROADCAST, (void *)&option, sizeof(option));
287
288         if(udp_rcvbuf && setsockopt(nfd, SOL_SOCKET, SO_RCVBUF, (void *)&udp_rcvbuf, sizeof(udp_rcvbuf))) {
289                 logger(DEBUG_ALWAYS, LOG_WARNING, "Can't set UDP SO_RCVBUF to %i: %s", udp_rcvbuf, sockstrerror(sockerrno));
290         }
291
292         {
293                 // The system may cap the requested buffer size.
294                 // Read back the value and check if it is now as requested.
295                 int udp_rcvbuf_actual = -1;
296                 socklen_t optlen = sizeof(udp_rcvbuf_actual);
297
298                 if(getsockopt(nfd, SOL_SOCKET, SO_RCVBUF, (void *)&udp_rcvbuf_actual, &optlen)) {
299                         logger(DEBUG_ALWAYS, LOG_WARNING, "Can't read back UDP SO_RCVBUF: %s", sockstrerror(sockerrno));
300                 } else if(optlen != sizeof(udp_rcvbuf_actual)) {
301                         logger(DEBUG_ALWAYS, LOG_WARNING, "Can't read back UDP SO_RCVBUF: Unexpected returned optlen %jd", (intmax_t) optlen);
302                 } else {
303                         if(udp_rcvbuf_actual != udp_rcvbuf) {
304                                 logger(DEBUG_ALWAYS, LOG_WARNING, "Can't set UDP SO_RCVBUF to %i, the system set it to %i instead", udp_rcvbuf, udp_rcvbuf_actual);
305                         }
306                 }
307         }
308
309         if(udp_sndbuf && setsockopt(nfd, SOL_SOCKET, SO_SNDBUF, (void *)&udp_sndbuf, sizeof(udp_sndbuf))) {
310                 logger(DEBUG_ALWAYS, LOG_WARNING, "Can't set UDP SO_SNDBUF to %i: %s", udp_sndbuf, sockstrerror(sockerrno));
311         }
312
313         {
314                 // The system may cap the requested buffer size.
315                 // Read back the value and check if it is now as requested.
316                 int udp_sndbuf_actual = -1;
317                 socklen_t optlen = sizeof(udp_sndbuf_actual);
318
319                 if(getsockopt(nfd, SOL_SOCKET, SO_SNDBUF, (void *)&udp_sndbuf_actual, &optlen)) {
320                         logger(DEBUG_ALWAYS, LOG_WARNING, "Can't read back UDP SO_SNDBUF: %s", sockstrerror(sockerrno));
321                 } else if(optlen != sizeof(udp_sndbuf_actual)) {
322                         logger(DEBUG_ALWAYS, LOG_WARNING, "Can't read back UDP SO_SNDBUF: Unexpected returned optlen %jd", (intmax_t) optlen);
323                 } else {
324                         if(udp_sndbuf_actual != udp_sndbuf) {
325                                 logger(DEBUG_ALWAYS, LOG_WARNING, "Can't set UDP SO_SNDBUF to %i, the system set it to %i instead", udp_sndbuf, udp_sndbuf_actual);
326                         }
327                 }
328         }
329
330 #if defined(IPV6_V6ONLY)
331
332         if(sa->sa.sa_family == AF_INET6) {
333                 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
334         }
335
336 #endif
337
338 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
339 #define IP_DONTFRAGMENT IP_DONTFRAG
340 #endif
341
342 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
343
344         if(myself->options & OPTION_PMTU_DISCOVERY) {
345                 option = IP_PMTUDISC_DO;
346                 setsockopt(nfd, IPPROTO_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
347         }
348
349 #elif defined(IP_DONTFRAGMENT)
350
351         if(myself->options & OPTION_PMTU_DISCOVERY) {
352                 option = 1;
353                 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
354         }
355
356 #endif
357
358 #if defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
359
360         if(myself->options & OPTION_PMTU_DISCOVERY) {
361                 option = IPV6_PMTUDISC_DO;
362                 setsockopt(nfd, IPPROTO_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
363         }
364
365 #elif defined(IPV6_DONTFRAG)
366
367         if(myself->options & OPTION_PMTU_DISCOVERY) {
368                 option = 1;
369                 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
370         }
371
372 #endif
373
374 #if defined(SO_MARK)
375
376         if(fwmark) {
377                 setsockopt(nfd, SOL_SOCKET, SO_MARK, (void *)&fwmark, sizeof(fwmark));
378         }
379
380 #endif
381
382         if(!bind_to_interface(nfd)) {
383                 closesocket(nfd);
384                 return -1;
385         }
386
387         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
388                 closesocket(nfd);
389                 addrstr = sockaddr2hostname(sa);
390                 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
391                 free(addrstr);
392                 return -1;
393         }
394
395         return nfd;
396 } /* int setup_vpn_in_socket */
397
398 static void retry_outgoing_handler(void *data) {
399         setup_outgoing_connection(data, true);
400 }
401
402 void retry_outgoing(outgoing_t *outgoing) {
403         outgoing->timeout += 5;
404
405         if(outgoing->timeout > maxtimeout) {
406                 outgoing->timeout = maxtimeout;
407         }
408
409         timeout_add(&outgoing->ev, retry_outgoing_handler, outgoing, &(struct timeval) {
410                 outgoing->timeout, rand() % 100000
411         });
412
413         logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Trying to re-establish outgoing connection in %d seconds", outgoing->timeout);
414 }
415
416 void finish_connecting(connection_t *c) {
417         logger(DEBUG_CONNECTIONS, LOG_INFO, "Connected to %s (%s)", c->name, c->hostname);
418
419         c->last_ping_time = now.tv_sec;
420         c->status.connecting = false;
421
422         send_id(c);
423 }
424
425 static void do_outgoing_pipe(connection_t *c, const char *command) {
426 #ifndef HAVE_MINGW
427         int fd[2];
428
429         if(socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) {
430                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not create socketpair: %s", sockstrerror(sockerrno));
431                 return;
432         }
433
434         if(fork()) {
435                 c->socket = fd[0];
436                 close(fd[1]);
437                 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Using proxy %s", command);
438                 return;
439         }
440
441         close(0);
442         close(1);
443         close(fd[0]);
444         dup2(fd[1], 0);
445         dup2(fd[1], 1);
446         close(fd[1]);
447
448         // Other filedescriptors should be closed automatically by CLOEXEC
449
450         char *host = NULL;
451         char *port = NULL;
452
453         sockaddr2str(&c->address, &host, &port);
454         setenv("REMOTEADDRESS", host, true);
455         setenv("REMOTEPORT", port, true);
456         setenv("NODE", c->name, true);
457         setenv("NAME", myself->name, true);
458
459         if(netname) {
460                 setenv("NETNAME", netname, true);
461         }
462
463         int result = system(command);
464
465         if(result < 0) {
466                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not execute %s: %s", command, strerror(errno));
467         } else if(result) {
468                 logger(DEBUG_ALWAYS, LOG_ERR, "%s exited with non-zero status %d", command, result);
469         }
470
471         exit(result);
472 #else
473         (void)c;
474         (void)command;
475         logger(DEBUG_ALWAYS, LOG_ERR, "Proxy type exec not supported on this platform!");
476         return;
477 #endif
478 }
479
480 static void handle_meta_write(connection_t *c) {
481         if(c->outbuf.len <= c->outbuf.offset) {
482                 return;
483         }
484
485         ssize_t outlen = send(c->socket, c->outbuf.data + c->outbuf.offset, c->outbuf.len - c->outbuf.offset, 0);
486
487         if(outlen <= 0) {
488                 if(!sockerrno || sockerrno == EPIPE) {
489                         logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection closed by %s (%s)", c->name, c->hostname);
490                 } else if(sockwouldblock(sockerrno)) {
491                         logger(DEBUG_META, LOG_DEBUG, "Sending %d bytes to %s (%s) would block", c->outbuf.len - c->outbuf.offset, c->name, c->hostname);
492                         return;
493                 } else {
494                         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));
495                 }
496
497                 terminate_connection(c, c->edge);
498                 return;
499         }
500
501         buffer_read(&c->outbuf, outlen);
502
503         if(!c->outbuf.len) {
504                 io_set(&c->io, IO_READ);
505         }
506 }
507
508 static void handle_meta_io(void *data, int flags) {
509         connection_t *c = data;
510
511         if(c->status.connecting) {
512                 /*
513                    The event loop does not protect against spurious events. Verify that we are actually connected
514                    by issuing an empty send() call.
515
516                    Note that the behavior of send() on potentially unconnected sockets differ between platforms:
517                    +------------+-----------+-------------+-----------+
518                    |   Event    |   POSIX   |    Linux    |  Windows  |
519                    +------------+-----------+-------------+-----------+
520                    | Spurious   | ENOTCONN  | EWOULDBLOCK | ENOTCONN  |
521                    | Failed     | ENOTCONN  | (cause)     | ENOTCONN  |
522                    | Successful | (success) | (success)   | (success) |
523                    +------------+-----------+-------------+-----------+
524                 */
525                 if(send(c->socket, NULL, 0, 0) != 0) {
526                         if(sockwouldblock(sockerrno)) {
527                                 return;
528                         }
529
530                         int socket_error;
531
532                         if(!socknotconn(sockerrno)) {
533                                 socket_error = sockerrno;
534                         } else {
535                                 socklen_t len = sizeof(socket_error);
536                                 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&socket_error, &len);
537                         }
538
539                         if(socket_error) {
540                                 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Error while connecting to %s (%s): %s", c->name, c->hostname, sockstrerror(socket_error));
541                                 terminate_connection(c, false);
542                         }
543
544                         return;
545                 }
546
547                 c->status.connecting = false;
548                 finish_connecting(c);
549         }
550
551         if(flags & IO_WRITE) {
552                 handle_meta_write(c);
553         } else {
554                 handle_meta_connection_data(c);
555         }
556 }
557
558 bool do_outgoing_connection(outgoing_t *outgoing) {
559         const sockaddr_t *sa;
560         struct addrinfo *proxyai = NULL;
561         int result;
562
563 begin:
564         sa = get_recent_address(outgoing->node->address_cache);
565
566         if(!sa) {
567                 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not set up a meta connection to %s", outgoing->node->name);
568                 retry_outgoing(outgoing);
569                 return false;
570         }
571
572         connection_t *c = new_connection();
573         c->outgoing = outgoing;
574         memcpy(&c->address, sa, SALEN(sa->sa));
575         c->hostname = sockaddr2hostname(&c->address);
576
577         logger(DEBUG_CONNECTIONS, LOG_INFO, "Trying to connect to %s (%s)", outgoing->node->name, c->hostname);
578
579         if(!proxytype) {
580                 c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
581                 configure_tcp(c);
582         } else if(proxytype == PROXY_EXEC) {
583                 do_outgoing_pipe(c, proxyhost);
584         } else {
585                 proxyai = str2addrinfo(proxyhost, proxyport, SOCK_STREAM);
586
587                 if(!proxyai) {
588                         free_connection(c);
589                         goto begin;
590                 }
591
592                 logger(DEBUG_CONNECTIONS, LOG_INFO, "Using proxy at %s port %s", proxyhost, proxyport);
593                 c->socket = socket(proxyai->ai_family, SOCK_STREAM, IPPROTO_TCP);
594                 configure_tcp(c);
595         }
596
597         if(c->socket == -1) {
598                 logger(DEBUG_CONNECTIONS, LOG_ERR, "Creating socket for %s failed: %s", c->hostname, sockstrerror(sockerrno));
599                 free_connection(c);
600                 goto begin;
601         }
602
603 #ifdef FD_CLOEXEC
604         fcntl(c->socket, F_SETFD, FD_CLOEXEC);
605 #endif
606
607         if(proxytype != PROXY_EXEC) {
608 #if defined(IPV6_V6ONLY)
609                 int option = 1;
610
611                 if(c->address.sa.sa_family == AF_INET6) {
612                         setsockopt(c->socket, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
613                 }
614
615 #endif
616
617                 bind_to_interface(c->socket);
618                 bind_to_address(c);
619         }
620
621         /* Connect */
622
623         if(!proxytype) {
624                 result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
625         } else if(proxytype == PROXY_EXEC) {
626                 result = 0;
627         } else {
628                 if(!proxyai) {
629                         abort();
630                 }
631
632                 result = connect(c->socket, proxyai->ai_addr, proxyai->ai_addrlen);
633                 freeaddrinfo(proxyai);
634         }
635
636         if(result == -1 && !sockinprogress(sockerrno)) {
637                 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not connect to %s (%s): %s", outgoing->node->name, c->hostname, sockstrerror(sockerrno));
638                 free_connection(c);
639
640                 goto begin;
641         }
642
643         /* Now that there is a working socket, fill in the rest and register this connection. */
644
645         c->last_ping_time = time(NULL);
646         c->status.connecting = true;
647         c->name = xstrdup(outgoing->node->name);
648 #ifndef DISABLE_LEGACY
649         c->outcipher = myself->connection->outcipher;
650         c->outdigest = myself->connection->outdigest;
651 #endif
652         c->outmaclength = myself->connection->outmaclength;
653         c->outcompression = myself->connection->outcompression;
654         c->last_ping_time = now.tv_sec;
655
656         connection_add(c);
657
658         io_add(&c->io, handle_meta_io, c, c->socket, IO_READ | IO_WRITE);
659
660         return true;
661 }
662
663 void setup_outgoing_connection(outgoing_t *outgoing, bool verbose) {
664         (void)verbose;
665         timeout_del(&outgoing->ev);
666
667         node_t *n = outgoing->node;
668
669         if(!n->address_cache) {
670                 n->address_cache = open_address_cache(n);
671         }
672
673         if(n->connection) {
674                 logger(DEBUG_CONNECTIONS, LOG_INFO, "Already connected to %s", n->name);
675
676                 if(!n->connection->outgoing) {
677                         n->connection->outgoing = outgoing;
678                         return;
679                 } else {
680                         goto remove;
681                 }
682         }
683
684         do_outgoing_connection(outgoing);
685         return;
686
687 remove:
688         list_delete(outgoing_list, outgoing);
689 }
690
691 /*
692   accept a new tcp connect and create a
693   new connection
694 */
695 void handle_new_meta_connection(void *data, int flags) {
696         (void)flags;
697         listen_socket_t *l = data;
698         connection_t *c;
699         sockaddr_t sa;
700         int fd;
701         socklen_t len = sizeof(sa);
702
703         fd = accept(l->tcp.fd, &sa.sa, &len);
704
705         if(fd < 0) {
706                 logger(DEBUG_ALWAYS, LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
707                 return;
708         }
709
710         sockaddrunmap(&sa);
711
712         // Check if we get many connections from the same host
713
714         static sockaddr_t prev_sa;
715
716         if(!sockaddrcmp_noport(&sa, &prev_sa)) {
717                 static int samehost_burst;
718                 static int samehost_burst_time;
719
720                 if(now.tv_sec - samehost_burst_time > samehost_burst) {
721                         samehost_burst = 0;
722                 } else {
723                         samehost_burst -= now.tv_sec - samehost_burst_time;
724                 }
725
726                 samehost_burst_time = now.tv_sec;
727                 samehost_burst++;
728
729                 if(samehost_burst > max_connection_burst) {
730                         tarpit(fd);
731                         return;
732                 }
733         }
734
735         memcpy(&prev_sa, &sa, sizeof(sa));
736
737         // Check if we get many connections from different hosts
738
739         static int connection_burst;
740         static int connection_burst_time;
741
742         if(now.tv_sec - connection_burst_time > connection_burst) {
743                 connection_burst = 0;
744         } else {
745                 connection_burst -= now.tv_sec - connection_burst_time;
746         }
747
748         connection_burst_time = now.tv_sec;
749         connection_burst++;
750
751         if(connection_burst >= max_connection_burst) {
752                 connection_burst = max_connection_burst;
753                 tarpit(fd);
754                 return;
755         }
756
757         // Accept the new connection
758
759         c = new_connection();
760         c->name = xstrdup("<unknown>");
761 #ifndef DISABLE_LEGACY
762         c->outcipher = myself->connection->outcipher;
763         c->outdigest = myself->connection->outdigest;
764 #endif
765         c->outmaclength = myself->connection->outmaclength;
766         c->outcompression = myself->connection->outcompression;
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_MINGW
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 static void free_outgoing(outgoing_t *outgoing) {
823         timeout_del(&outgoing->ev);
824         free(outgoing);
825 }
826
827 void try_outgoing_connections(void) {
828         /* If there is no outgoing list yet, create one. Otherwise, mark all outgoings as deleted. */
829
830         if(!outgoing_list) {
831                 outgoing_list = list_alloc((list_action_t)free_outgoing);
832         } else {
833                 for list_each(outgoing_t, outgoing, outgoing_list) {
834                         outgoing->timeout = -1;
835                 }
836         }
837
838         /* Make sure there is one outgoing_t in the list for each ConnectTo. */
839
840         for(config_t *cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
841                 char *name;
842                 get_config_string(cfg, &name);
843
844                 if(!check_id(name)) {
845                         logger(DEBUG_ALWAYS, LOG_ERR,
846                                "Invalid name for outgoing connection in %s line %d",
847                                cfg->file, cfg->line);
848                         free(name);
849                         continue;
850                 }
851
852                 if(!strcmp(name, myself->name)) {
853                         free(name);
854                         continue;
855                 }
856
857                 bool found = false;
858
859                 for list_each(outgoing_t, outgoing, outgoing_list) {
860                         if(!strcmp(outgoing->node->name, name)) {
861                                 found = true;
862                                 outgoing->timeout = 0;
863                                 break;
864                         }
865                 }
866
867                 if(!found) {
868                         outgoing_t *outgoing = xzalloc(sizeof(*outgoing));
869                         node_t *n = lookup_node(name);
870
871                         if(!n) {
872                                 n = new_node();
873                                 n->name = xstrdup(name);
874                                 node_add(n);
875                         }
876
877                         outgoing->node = n;
878                         list_insert_tail(outgoing_list, outgoing);
879                         setup_outgoing_connection(outgoing, true);
880                 }
881         }
882
883         /* Terminate any connections whose outgoing_t is to be deleted. */
884
885         for list_each(connection_t, c, connection_list) {
886                 if(c->outgoing && c->outgoing->timeout == -1) {
887                         c->outgoing = NULL;
888                         logger(DEBUG_CONNECTIONS, LOG_INFO, "No more outgoing connection to %s", c->name);
889                         terminate_connection(c, c->edge);
890                 }
891         }
892
893         /* Delete outgoing_ts for which there is no ConnectTo. */
894
895         for list_each(outgoing_t, outgoing, outgoing_list)
896                 if(outgoing->timeout == -1) {
897                         list_delete_node(outgoing_list, node);
898                 }
899 }