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