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