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