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