]> git.meshlink.io Git - meshlink/blob - src/net_socket.c
Add meta-connection attempt callback feature
[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(IP_TOS) && defined(IPTOS_LOWDELAY)
72         int lowdelay = IPTOS_LOWDELAY;
73         setsockopt(c->socket, IPPROTO_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(IPV6_V6ONLY)
134
135         if(sa->sa.sa_family == AF_INET6) {
136                 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
137         }
138
139 #else
140 #warning IPV6_V6ONLY not defined
141 #endif
142
143         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
144                 closesocket(nfd);
145                 addrstr = sockaddr2hostname(sa);
146                 logger(NULL, MESHLINK_ERROR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
147                 free(addrstr);
148                 return -1;
149         }
150
151         if(listen(nfd, 3)) {
152                 closesocket(nfd);
153                 logger(NULL, MESHLINK_ERROR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
154                 return -1;
155         }
156
157         return nfd;
158 }
159
160 int setup_vpn_in_socket(meshlink_handle_t *mesh, const sockaddr_t *sa) {
161         int nfd;
162         char *addrstr;
163         int option;
164
165         nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
166
167         if(nfd < 0) {
168                 logger(mesh, MESHLINK_ERROR, "Creating UDP socket failed: %s", sockstrerror(sockerrno));
169                 return -1;
170         }
171
172 #ifdef FD_CLOEXEC
173         fcntl(nfd, F_SETFD, FD_CLOEXEC);
174 #endif
175
176 #ifdef O_NONBLOCK
177         {
178                 int flags = fcntl(nfd, F_GETFL);
179
180                 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
181                         closesocket(nfd);
182                         logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "fcntl",
183                                strerror(errno));
184                         return -1;
185                 }
186         }
187 #elif defined(WIN32)
188         {
189                 unsigned long arg = 1;
190
191                 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
192                         closesocket(nfd);
193                         logger(mesh, MESHLINK_ERROR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
194                         return -1;
195                 }
196         }
197 #endif
198
199         option = 1;
200         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
201         setsockopt(nfd, SOL_SOCKET, SO_BROADCAST, (void *)&option, sizeof(option));
202
203 #if defined(IPV6_V6ONLY)
204
205         if(sa->sa.sa_family == AF_INET6) {
206                 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
207         }
208
209 #endif
210
211 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
212 #define IP_DONTFRAGMENT IP_DONTFRAG
213 #endif
214
215 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
216
217         if(mesh->self->options & OPTION_PMTU_DISCOVERY) {
218                 option = IP_PMTUDISC_DO;
219                 setsockopt(nfd, IPPROTO_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
220         }
221
222 #elif defined(IP_DONTFRAGMENT)
223
224         if(mesh->self->options & OPTION_PMTU_DISCOVERY) {
225                 option = 1;
226                 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
227         }
228
229 #else
230 #warning No way to disable IPv4 fragmentation
231 #endif
232
233 #if defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
234
235         if(mesh->self->options & OPTION_PMTU_DISCOVERY) {
236                 option = IPV6_PMTUDISC_DO;
237                 setsockopt(nfd, IPPROTO_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
238         }
239
240 #elif defined(IPV6_DONTFRAG)
241
242         if(mesh->self->options & OPTION_PMTU_DISCOVERY) {
243                 option = 1;
244                 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
245         }
246
247 #else
248 #warning No way to disable IPv6 fragmentation
249 #endif
250
251         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
252                 closesocket(nfd);
253                 addrstr = sockaddr2hostname(sa);
254                 logger(mesh, MESHLINK_ERROR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
255                 free(addrstr);
256                 return -1;
257         }
258
259         return nfd;
260 } /* int setup_vpn_in_socket */
261
262 static void retry_outgoing_handler(event_loop_t *loop, void *data) {
263         meshlink_handle_t *mesh = loop->data;
264         outgoing_t *outgoing = data;
265         setup_outgoing_connection(mesh, outgoing);
266 }
267
268 void retry_outgoing(meshlink_handle_t *mesh, outgoing_t *outgoing) {
269         outgoing->timeout += 5;
270
271         if(outgoing->timeout > mesh->maxtimeout) {
272                 outgoing->timeout = mesh->maxtimeout;
273         }
274
275         timeout_add(&mesh->loop, &outgoing->ev, retry_outgoing_handler, outgoing, &(struct timeval) {
276                 outgoing->timeout, rand() % 100000
277         });
278
279         logger(mesh, MESHLINK_INFO, "Trying to re-establish outgoing connection in %d seconds", outgoing->timeout);
280 }
281
282 void finish_connecting(meshlink_handle_t *mesh, connection_t *c) {
283         logger(mesh, MESHLINK_INFO, "Connected to %s", c->name);
284
285         c->last_ping_time = mesh->loop.now.tv_sec;
286         c->status.connecting = false;
287
288         send_id(mesh, c);
289 }
290
291 static void handle_meta_write(meshlink_handle_t *mesh, connection_t *c) {
292         if(c->outbuf.len <= c->outbuf.offset) {
293                 return;
294         }
295
296         ssize_t outlen = send(c->socket, c->outbuf.data + c->outbuf.offset, c->outbuf.len - c->outbuf.offset, MSG_NOSIGNAL);
297
298         if(outlen <= 0) {
299                 if(!errno || errno == EPIPE) {
300                         logger(mesh, MESHLINK_INFO, "Connection closed by %s", c->name);
301                 } else if(sockwouldblock(sockerrno)) {
302                         logger(mesh, MESHLINK_DEBUG, "Sending %lu bytes to %s would block", (unsigned long)(c->outbuf.len - c->outbuf.offset), c->name);
303                         return;
304                 } else {
305                         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));
306                 }
307
308                 terminate_connection(mesh, c, c->status.active);
309                 return;
310         }
311
312         buffer_read(&c->outbuf, outlen);
313
314         if(!c->outbuf.len) {
315                 io_set(&mesh->loop, &c->io, IO_READ);
316         }
317 }
318
319 static void handle_meta_io(event_loop_t *loop, void *data, int flags) {
320         meshlink_handle_t *mesh = loop->data;
321         connection_t *c = data;
322
323         if(c->status.connecting) {
324                 c->status.connecting = false;
325
326                 int result;
327                 socklen_t len = sizeof(result);
328                 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
329
330                 if(!result) {
331                         finish_connecting(mesh, c);
332                 } else {
333                         logger(mesh, MESHLINK_DEBUG, "Error while connecting to %s: %s", c->name, sockstrerror(result));
334                         terminate_connection(mesh, c, false);
335                         return;
336                 }
337         }
338
339         if(flags & IO_WRITE) {
340                 handle_meta_write(mesh, c);
341         } else {
342                 handle_meta_connection_data(mesh, c);
343         }
344 }
345
346 // Find edges pointing to this node, and use them to build a list of unique, known addresses.
347 static struct addrinfo *get_known_addresses(node_t *n) {
348         struct addrinfo *ai = NULL;
349
350         for splay_each(edge_t, e, n->edge_tree) {
351                 if(!e->reverse) {
352                         continue;
353                 }
354
355                 bool found = false;
356
357                 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
358                         if(!sockaddrcmp(&e->reverse->address, (sockaddr_t *)aip->ai_addr)) {
359                                 found = true;
360                                 break;
361                         }
362                 }
363
364                 if(found) {
365                         continue;
366                 }
367
368                 // Create a new struct addrinfo, and put it at the head of the list.
369                 struct addrinfo *nai = xzalloc(sizeof(*nai) + SALEN(e->reverse->address.sa));
370                 nai->ai_next = ai;
371                 ai = nai;
372
373                 ai->ai_family = e->reverse->address.sa.sa_family;
374                 ai->ai_socktype = SOCK_STREAM;
375                 ai->ai_protocol = IPPROTO_TCP;
376                 ai->ai_addrlen = SALEN(e->reverse->address.sa);
377                 ai->ai_addr = (struct sockaddr *)(nai + 1);
378                 memcpy(ai->ai_addr, &e->reverse->address, ai->ai_addrlen);
379         }
380
381         return ai;
382 }
383
384 // Free struct addrinfo list from get_known_addresses().
385 static void free_known_addresses(struct addrinfo *ai) {
386         for(struct addrinfo *aip = ai, *next; aip; aip = next) {
387                 next = aip->ai_next;
388                 free(aip);
389         }
390 }
391
392 static bool get_recent(meshlink_handle_t *mesh, outgoing_t *outgoing) {
393         node_t *n = lookup_node(mesh, outgoing->name);
394
395         if(!n) {
396                 return false;
397         }
398
399         outgoing->ai = get_known_addresses(n);
400         outgoing->aip = outgoing->ai;
401         return outgoing->aip;
402 }
403
404 static bool get_next_ai(meshlink_handle_t *mesh, outgoing_t *outgoing) {
405         if(!outgoing->ai) {
406                 char *address = NULL;
407
408                 if(get_config_string(outgoing->cfg, &address)) {
409                         char *port;
410                         char *space = strchr(address, ' ');
411
412                         if(space) {
413                                 port = xstrdup(space + 1);
414                                 *space = 0;
415                         } else {
416                                 if(!get_config_string(lookup_config(outgoing->config_tree, "Port"), &port)) {
417                                         logger(mesh, MESHLINK_ERROR, "No Port known for %s", outgoing->name);
418                                         return false;
419                                 }
420                         }
421
422                         outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
423                         free(port);
424                         free(address);
425                 }
426
427                 outgoing->aip = outgoing->ai;
428         } else {
429                 outgoing->aip = outgoing->aip->ai_next;
430         }
431
432         return outgoing->aip;
433 }
434
435 static bool get_next_cfg(meshlink_handle_t *mesh, outgoing_t *outgoing, char *variable) {
436         (void)mesh;
437
438         if(!outgoing->cfg) {
439                 outgoing->cfg = lookup_config(outgoing->config_tree, variable);
440         } else {
441                 outgoing->cfg = lookup_config_next(outgoing->config_tree, outgoing->cfg);
442         }
443
444         return outgoing->cfg;
445 }
446
447 static bool get_next_outgoing_address(meshlink_handle_t *mesh, outgoing_t *outgoing) {
448         bool start = false;
449
450         if(outgoing->state == OUTGOING_START) {
451                 start = true;
452                 outgoing->state = OUTGOING_CANONICAL;
453         }
454
455         if(outgoing->state == OUTGOING_CANONICAL) {
456                 while(outgoing->aip || get_next_cfg(mesh, outgoing, "CanonicalAddress")) {
457                         if(get_next_ai(mesh, outgoing)) {
458                                 return true;
459                         } else {
460                                 freeaddrinfo(outgoing->ai);
461                                 outgoing->ai = NULL;
462                                 outgoing->aip = NULL;
463                         }
464                 }
465
466                 outgoing->state = OUTGOING_RECENT;
467         }
468
469         if(outgoing->state == OUTGOING_RECENT) {
470                 while(outgoing->aip || get_next_cfg(mesh, outgoing, "Address")) {
471                         if(get_next_ai(mesh, outgoing)) {
472                                 return true;
473                         } else {
474                                 freeaddrinfo(outgoing->ai);
475                                 outgoing->ai = NULL;
476                                 outgoing->aip = NULL;
477                         }
478                 }
479
480                 outgoing->state = OUTGOING_KNOWN;
481         }
482
483         if(outgoing->state == OUTGOING_KNOWN) {
484                 if(!outgoing->aip) {
485                         get_recent(mesh, outgoing);
486                 } else {
487                         outgoing->aip = outgoing->aip->ai_next;
488                 }
489
490                 if(outgoing->aip) {
491                         return true;
492                 } else {
493                         free_known_addresses(outgoing->ai);
494                         outgoing->ai = NULL;
495                         outgoing->aip = NULL;
496                 }
497
498                 outgoing->state = OUTGOING_END;
499         }
500
501         if(start) {
502                 outgoing->state = OUTGOING_NO_KNOWN_ADDRESSES;
503         }
504
505         return false;
506 }
507
508 bool do_outgoing_connection(meshlink_handle_t *mesh, outgoing_t *outgoing) {
509         struct addrinfo *proxyai = NULL;
510         int result;
511
512 begin:
513
514         if(!get_next_outgoing_address(mesh, outgoing)) {
515                 if(outgoing->state == OUTGOING_NO_KNOWN_ADDRESSES) {
516                         logger(mesh, MESHLINK_ERROR, "No known addresses for %s", outgoing->name);
517                 } else {
518                         logger(mesh, MESHLINK_ERROR, "Could not set up a meta connection to %s", outgoing->name);
519                         retry_outgoing(mesh, outgoing);
520                 }
521
522                 return false;
523         }
524
525         connection_t *c = new_connection();
526         c->outgoing = outgoing;
527
528         memcpy(&c->address, outgoing->aip->ai_addr, outgoing->aip->ai_addrlen);
529
530         char *hostname = sockaddr2hostname(&c->address);
531
532         logger(mesh, MESHLINK_INFO, "Trying to connect to %s at %s", outgoing->name, hostname);
533
534         if(!mesh->proxytype) {
535                 c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
536                 configure_tcp(c);
537         } else {
538                 proxyai = str2addrinfo(mesh->proxyhost, mesh->proxyport, SOCK_STREAM);
539
540                 if(!proxyai) {
541                         free_connection(c);
542                         free(hostname);
543                         goto begin;
544                 }
545
546                 logger(mesh, MESHLINK_INFO, "Using proxy at %s port %s", mesh->proxyhost, mesh->proxyport);
547                 c->socket = socket(proxyai->ai_family, SOCK_STREAM, IPPROTO_TCP);
548                 configure_tcp(c);
549         }
550
551         if(c->socket == -1) {
552                 logger(mesh, MESHLINK_ERROR, "Creating socket for %s at %s failed: %s", c->name, hostname, sockstrerror(sockerrno));
553                 free_connection(c);
554                 free(hostname);
555                 goto begin;
556         }
557
558         free(hostname);
559
560 #ifdef FD_CLOEXEC
561         fcntl(c->socket, F_SETFD, FD_CLOEXEC);
562 #endif
563
564 #if defined(IPV6_V6ONLY)
565
566         if(c->address.sa.sa_family == AF_INET6) {
567                 static const int option = 1;
568                 setsockopt(c->socket, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
569         }
570
571 #endif
572
573         bind_to_address(mesh, c);
574
575         /* Connect */
576
577         if(!mesh->proxytype) {
578                 result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
579         } else {
580                 result = connect(c->socket, proxyai->ai_addr, proxyai->ai_addrlen);
581                 freeaddrinfo(proxyai);
582         }
583
584         if(result == -1 && !sockinprogress(sockerrno)) {
585                 logger(mesh, MESHLINK_ERROR, "Could not connect to %s: %s", outgoing->name, sockstrerror(sockerrno));
586                 free_connection(c);
587
588                 goto begin;
589         }
590
591         /* Now that there is a working socket, fill in the rest and register this connection. */
592
593         c->status.connecting = true;
594         c->name = xstrdup(outgoing->name);
595         c->outcompression = mesh->self->connection->outcompression;
596         c->last_ping_time = mesh->loop.now.tv_sec;
597
598         connection_add(mesh, c);
599
600         io_add(&mesh->loop, &c->io, handle_meta_io, c, c->socket, IO_READ | IO_WRITE);
601
602         return true;
603 }
604
605 void setup_outgoing_connection(meshlink_handle_t *mesh, outgoing_t *outgoing) {
606         bool blacklisted = false;
607         timeout_del(&mesh->loop, &outgoing->ev);
608
609         node_t *n = lookup_node(mesh, outgoing->name);
610
611         if(n && n->connection) {
612                 logger(mesh, MESHLINK_INFO, "Already connected to %s", outgoing->name);
613
614                 n->connection->outgoing = outgoing;
615                 return;
616         }
617
618
619         if(outgoing->ai) {
620                 if(outgoing->state == OUTGOING_KNOWN) {
621                         free_known_addresses(outgoing->ai);
622                 } else {
623                         freeaddrinfo(outgoing->ai);
624                 }
625         }
626
627         outgoing->cfg = NULL;
628
629         exit_configuration(&outgoing->config_tree); // discard old configuration if present
630         init_configuration(&outgoing->config_tree);
631         read_host_config(mesh, outgoing->config_tree, outgoing->name);
632         get_config_bool(lookup_config(outgoing->config_tree, "blacklisted"), &blacklisted);
633
634         outgoing->state = OUTGOING_START;
635
636         if(blacklisted) {
637                 return;
638         }
639
640         if(mesh->connection_try_cb) {
641                 node_t *n = lookup_node(mesh, outgoing->name);
642                 mesh->connection_try_cb(mesh, (struct meshlink_node *)n);
643         }
644
645         do_outgoing_connection(mesh, outgoing);
646 }
647
648 /// Delayed close of a filedescriptor.
649 static void tarpit(int fd) {
650         static int pits[10] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
651         static int next_pit = 0;
652
653         if(pits[next_pit] != -1) {
654                 closesocket(pits[next_pit]);
655         }
656
657         pits[next_pit++] = fd;
658
659         if(next_pit >= (int)(sizeof pits / sizeof pits[0])) {
660                 next_pit = 0;
661         }
662 }
663
664 /*
665   accept a new tcp connect and create a
666   new connection
667 */
668 void handle_new_meta_connection(event_loop_t *loop, void *data, int flags) {
669         (void)flags;
670         meshlink_handle_t *mesh = loop->data;
671         listen_socket_t *l = data;
672         connection_t *c;
673         sockaddr_t sa = {0};
674         int fd;
675         socklen_t len = sizeof(sa);
676
677         fd = accept(l->tcp.fd, &sa.sa, &len);
678
679         if(fd < 0) {
680                 if(errno == EINVAL) { // TODO: check if Windows agrees
681                         event_loop_stop(loop);
682                         return;
683                 }
684
685                 logger(mesh, MESHLINK_ERROR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
686                 return;
687         }
688
689         sockaddrunmap(&sa);
690
691         /* Rate limit incoming connections to max_connection_burst/second. */
692
693         static int connection_burst;
694         static int connection_burst_time;
695
696         if(mesh->loop.now.tv_sec != connection_burst_time) {
697                 connection_burst_time = mesh->loop.now.tv_sec;
698                 connection_burst = 0;
699         }
700
701         if(connection_burst >= max_connection_burst) {
702                 tarpit(fd);
703                 return;
704         }
705
706         connection_burst++;
707
708         // Accept the new connection
709
710         c = new_connection();
711         c->name = xstrdup("<unknown>");
712         c->outcompression = mesh->self->connection->outcompression;
713
714         c->address = sa;
715         c->socket = fd;
716         c->last_ping_time = mesh->loop.now.tv_sec;
717
718         char *hostname = sockaddr2hostname(&sa);
719         logger(mesh, MESHLINK_INFO, "Connection from %s", hostname);
720         free(hostname);
721
722         io_add(&mesh->loop, &c->io, handle_meta_io, c, c->socket, IO_READ);
723
724         configure_tcp(c);
725
726         connection_add(mesh, c);
727
728         c->allow_request = ID;
729         send_id(mesh, c);
730 }
731
732 static void free_outgoing(outgoing_t *outgoing) {
733         meshlink_handle_t *mesh = outgoing->mesh;
734
735         timeout_del(&mesh->loop, &outgoing->ev);
736
737         if(outgoing->ai) {
738                 if(outgoing->state == OUTGOING_KNOWN) {
739                         free_known_addresses(outgoing->ai);
740                 } else {
741                         freeaddrinfo(outgoing->ai);
742                 }
743         }
744
745         if(outgoing->config_tree) {
746                 exit_configuration(&outgoing->config_tree);
747         }
748
749         if(outgoing->name) {
750                 free(outgoing->name);
751         }
752
753         free(outgoing);
754 }
755
756 void try_outgoing_connections(meshlink_handle_t *mesh) {
757         /* If there is no outgoing list yet, create one. Otherwise, mark all outgoings as deleted. */
758
759         if(!mesh->outgoings) {
760                 mesh->outgoings = list_alloc((list_action_t)free_outgoing);
761         } else {
762                 for list_each(outgoing_t, outgoing, mesh->outgoings) {
763                         outgoing->timeout = -1;
764                 }
765         }
766
767         /* Make sure there is one outgoing_t in the list for each ConnectTo. */
768
769         // TODO: Drop support for ConnectTo since AutoConnect is now always on?
770         for(config_t *cfg = lookup_config(mesh->config, "ConnectTo"); cfg; cfg = lookup_config_next(mesh->config, cfg)) {
771                 char *name;
772                 get_config_string(cfg, &name);
773
774                 if(!check_id(name)) {
775                         logger(mesh, MESHLINK_ERROR,
776                                "Invalid name for outgoing connection in line %d",
777                                cfg->line);
778                         free(name);
779                         continue;
780                 }
781
782                 bool found = false;
783
784                 for list_each(outgoing_t, outgoing, mesh->outgoings) {
785                         if(!strcmp(outgoing->name, name)) {
786                                 found = true;
787                                 outgoing->timeout = 0;
788                                 break;
789                         }
790                 }
791
792                 if(!found) {
793                         outgoing_t *outgoing = xzalloc(sizeof(*outgoing));
794                         outgoing->mesh = mesh;
795                         outgoing->name = name;
796                         list_insert_tail(mesh->outgoings, outgoing);
797                         setup_outgoing_connection(mesh, outgoing);
798                 }
799         }
800
801         /* Terminate any connections whose outgoing_t is to be deleted. */
802
803         for list_each(connection_t, c, mesh->connections) {
804                 if(c->outgoing && c->outgoing->timeout == -1) {
805                         c->outgoing = NULL;
806                         logger(mesh, MESHLINK_INFO, "No more outgoing connection to %s", c->name);
807                         terminate_connection(mesh, c, c->status.active);
808                 }
809         }
810
811         /* Delete outgoing_ts for which there is no ConnectTo. */
812
813         for list_each(outgoing_t, outgoing, mesh->outgoings)
814                 if(outgoing->timeout == -1) {
815                         list_delete_node(mesh->outgoings, node);
816                 }
817 }