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