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