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