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