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