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