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