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