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