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