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