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