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