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