2 net_socket.c -- Handle various kinds of sockets.
3 Copyright (C) 1998-2005 Ivo Timmermans,
4 2000-2013 Guus Sliepen <guus@tinc-vpn.org>
5 2006 Scott Lamb <slamb@slamb.org>
6 2009 Florian Forster <octo@verplant.org>
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License along
19 with this program; if not, write to the Free Software Foundation, Inc.,
20 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 #include "connection.h"
27 #include "control_common.h"
38 /* Needed on Mac OS/X */
40 #define SOL_TCP IPPROTO_TCP
43 int addressfamily = AF_UNSPEC;
45 int seconds_till_retry = 5;
48 int max_connection_burst = 100;
50 listen_socket_t listen_socket[MAXSOCKETS];
55 list_t *outgoing_list = NULL;
59 static void configure_tcp(connection_t *c) {
63 int flags = fcntl(c->socket, F_GETFL);
65 if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0) {
66 logger(DEBUG_ALWAYS, LOG_ERR, "fcntl for %s: %s", c->hostname, strerror(errno));
69 unsigned long arg = 1;
71 if(ioctlsocket(c->socket, FIONBIO, &arg) != 0) {
72 logger(DEBUG_ALWAYS, LOG_ERR, "ioctlsocket for %s: %s", c->hostname, sockstrerror(sockerrno));
76 #if defined(SOL_TCP) && defined(TCP_NODELAY)
78 setsockopt(c->socket, SOL_TCP, TCP_NODELAY, (void *)&option, sizeof option);
81 #if defined(SOL_IP) && defined(IP_TOS) && defined(IPTOS_LOWDELAY)
82 option = IPTOS_LOWDELAY;
83 setsockopt(c->socket, SOL_IP, IP_TOS, (void *)&option, sizeof option);
87 static bool bind_to_interface(int sd) {
90 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
93 #endif /* defined(SOL_SOCKET) && defined(SO_BINDTODEVICE) */
95 if(!get_config_string (lookup_config (config_tree, "BindToInterface"), &iface))
98 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
99 memset(&ifr, 0, sizeof(ifr));
100 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
101 ifr.ifr_ifrn.ifrn_name[IFNAMSIZ - 1] = 0;
103 status = setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr));
105 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to interface %s: %s", iface,
109 #else /* if !defined(SOL_SOCKET) || !defined(SO_BINDTODEVICE) */
110 logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform", "BindToInterface");
116 int setup_listen_socket(const sockaddr_t *sa) {
122 nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
125 logger(DEBUG_STATUS, LOG_ERR, "Creating metasocket failed: %s", sockstrerror(sockerrno));
130 fcntl(nfd, F_SETFD, FD_CLOEXEC);
133 /* Optimize TCP settings */
136 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof option);
138 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
139 if(sa->sa.sa_family == AF_INET6)
140 setsockopt(nfd, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
144 (lookup_config(config_tree, "BindToInterface"), &iface)) {
145 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
148 memset(&ifr, 0, sizeof ifr);
149 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
151 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof ifr)) {
153 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to interface %s: %s", iface,
154 strerror(sockerrno));
158 logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform", "BindToInterface");
162 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
164 addrstr = sockaddr2hostname(sa);
165 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
172 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
179 int setup_vpn_in_socket(const sockaddr_t *sa) {
184 nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
187 logger(DEBUG_ALWAYS, LOG_ERR, "Creating UDP socket failed: %s", sockstrerror(sockerrno));
192 fcntl(nfd, F_SETFD, FD_CLOEXEC);
197 int flags = fcntl(nfd, F_GETFL);
199 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
201 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "fcntl",
208 unsigned long arg = 1;
209 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
211 logger(DEBUG_ALWAYS, LOG_ERR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
218 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof option);
219 setsockopt(nfd, SOL_SOCKET, SO_BROADCAST, (void *)&option, sizeof option);
221 if(udp_rcvbuf && setsockopt(nfd, SOL_SOCKET, SO_RCVBUF, (void *)&udp_rcvbuf, sizeof(udp_rcvbuf)))
222 logger(DEBUG_ALWAYS, LOG_WARNING, "Can't set UDP SO_RCVBUF to %i: %s", udp_rcvbuf, strerror(errno));
224 if(udp_sndbuf && setsockopt(nfd, SOL_SOCKET, SO_SNDBUF, (void *)&udp_sndbuf, sizeof(udp_sndbuf)))
225 logger(DEBUG_ALWAYS, LOG_WARNING, "Can't set UDP SO_SNDBUF to %i: %s", udp_sndbuf, strerror(errno));
227 #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
228 if(sa->sa.sa_family == AF_INET6)
229 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
232 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
233 #define IP_DONTFRAGMENT IP_DONTFRAG
236 #if defined(SOL_IP) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
237 if(myself->options & OPTION_PMTU_DISCOVERY) {
238 option = IP_PMTUDISC_DO;
239 setsockopt(nfd, SOL_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
241 #elif defined(IPPROTO_IP) && defined(IP_DONTFRAGMENT)
242 if(myself->options & OPTION_PMTU_DISCOVERY) {
244 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
247 #warning No way to disable IPv4 fragmentation
250 #if defined(SOL_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
251 if(myself->options & OPTION_PMTU_DISCOVERY) {
252 option = IPV6_PMTUDISC_DO;
253 setsockopt(nfd, SOL_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
255 #elif defined(IPPROTO_IPV6) && defined(IPV6_DONTFRAG)
256 if(myself->options & OPTION_PMTU_DISCOVERY) {
258 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
261 #warning No way to disable IPv6 fragmentation
264 if (!bind_to_interface(nfd)) {
269 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
271 addrstr = sockaddr2hostname(sa);
272 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
278 } /* int setup_vpn_in_socket */
280 static void retry_outgoing_handler(void *data) {
281 setup_outgoing_connection(data);
284 void retry_outgoing(outgoing_t *outgoing) {
285 outgoing->timeout += 5;
287 if(outgoing->timeout > maxtimeout)
288 outgoing->timeout = maxtimeout;
290 timeout_add(&outgoing->ev, retry_outgoing_handler, outgoing, &(struct timeval){outgoing->timeout, rand() % 100000});
292 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Trying to re-establish outgoing connection in %d seconds", outgoing->timeout);
295 void finish_connecting(connection_t *c) {
296 logger(DEBUG_CONNECTIONS, LOG_INFO, "Connected to %s (%s)", c->name, c->hostname);
298 c->last_ping_time = now.tv_sec;
299 c->status.connecting = false;
304 static void do_outgoing_pipe(connection_t *c, char *command) {
308 if(socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) {
309 logger(DEBUG_ALWAYS, LOG_ERR, "Could not create socketpair: %s", strerror(errno));
316 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Using proxy %s", command);
327 // Other filedescriptors should be closed automatically by CLOEXEC
332 sockaddr2str(&c->address, &host, &port);
333 setenv("REMOTEADDRESS", host, true);
334 setenv("REMOTEPORT", port, true);
335 setenv("NODE", c->name, true);
336 setenv("NAME", myself->name, true);
338 setenv("NETNAME", netname, true);
340 int result = system(command);
342 logger(DEBUG_ALWAYS, LOG_ERR, "Could not execute %s: %s", command, strerror(errno));
344 logger(DEBUG_ALWAYS, LOG_ERR, "%s exited with non-zero status %d", command, result);
347 logger(DEBUG_ALWAYS, LOG_ERR, "Proxy type exec not supported on this platform!");
352 static void handle_meta_write(connection_t *c) {
353 if(c->outbuf.len <= c->outbuf.offset)
356 ssize_t outlen = send(c->socket, c->outbuf.data + c->outbuf.offset, c->outbuf.len - c->outbuf.offset, 0);
358 if(!errno || errno == EPIPE) {
359 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection closed by %s (%s)", c->name, c->hostname);
360 } else if(sockwouldblock(sockerrno)) {
361 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Sending %d bytes to %s (%s) would block", c->outbuf.len - c->outbuf.offset, c->name, c->hostname);
364 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));
367 terminate_connection(c, c->status.active);
371 buffer_read(&c->outbuf, outlen);
373 io_set(&c->io, IO_READ);
376 static void handle_meta_io(void *data, int flags) {
377 connection_t *c = data;
379 if(c->status.connecting) {
380 c->status.connecting = false;
383 socklen_t len = sizeof result;
384 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
387 finish_connecting(c);
389 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Error while connecting to %s (%s): %s", c->name, c->hostname, sockstrerror(result));
390 terminate_connection(c, false);
396 handle_meta_write(c);
398 handle_meta_connection_data(c);
401 bool do_outgoing_connection(outgoing_t *outgoing) {
402 char *address, *port, *space;
403 struct addrinfo *proxyai = NULL;
409 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not set up a meta connection to %s", outgoing->name);
410 retry_outgoing(outgoing);
414 get_config_string(outgoing->cfg, &address);
416 space = strchr(address, ' ');
418 port = xstrdup(space + 1);
421 if(!get_config_string(lookup_config(outgoing->config_tree, "Port"), &port))
422 port = xstrdup("655");
425 outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
429 outgoing->aip = outgoing->ai;
430 outgoing->cfg = lookup_config_next(outgoing->config_tree, outgoing->cfg);
435 freeaddrinfo(outgoing->ai);
440 connection_t *c = new_connection();
441 c->outgoing = outgoing;
443 memcpy(&c->address, outgoing->aip->ai_addr, outgoing->aip->ai_addrlen);
444 outgoing->aip = outgoing->aip->ai_next;
446 c->hostname = sockaddr2hostname(&c->address);
448 logger(DEBUG_CONNECTIONS, LOG_INFO, "Trying to connect to %s (%s)", outgoing->name, c->hostname);
451 c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
453 } else if(proxytype == PROXY_EXEC) {
454 do_outgoing_pipe(c, proxyhost);
456 proxyai = str2addrinfo(proxyhost, proxyport, SOCK_STREAM);
461 logger(DEBUG_CONNECTIONS, LOG_INFO, "Using proxy at %s port %s", proxyhost, proxyport);
462 c->socket = socket(proxyai->ai_family, SOCK_STREAM, IPPROTO_TCP);
466 if(c->socket == -1) {
467 logger(DEBUG_CONNECTIONS, LOG_ERR, "Creating socket for %s failed: %s", c->hostname, sockstrerror(sockerrno));
473 fcntl(c->socket, F_SETFD, FD_CLOEXEC);
476 if(proxytype != PROXY_EXEC) {
477 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
479 if(c->address.sa.sa_family == AF_INET6)
480 setsockopt(c->socket, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
483 bind_to_interface(c->socket);
489 result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
490 } else if(proxytype == PROXY_EXEC) {
493 result = connect(c->socket, proxyai->ai_addr, proxyai->ai_addrlen);
494 freeaddrinfo(proxyai);
497 if(result == -1 && !sockinprogress(sockerrno)) {
498 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not connect to %s (%s): %s", outgoing->name, c->hostname, sockstrerror(sockerrno));
504 /* Now that there is a working socket, fill in the rest and register this connection. */
506 c->status.connecting = true;
507 c->name = xstrdup(outgoing->name);
508 c->outcipher = myself->connection->outcipher;
509 c->outdigest = myself->connection->outdigest;
510 c->outmaclength = myself->connection->outmaclength;
511 c->outcompression = myself->connection->outcompression;
512 c->last_ping_time = now.tv_sec;
516 io_add(&c->io, handle_meta_io, c, c->socket, IO_READ|IO_WRITE);
521 void setup_outgoing_connection(outgoing_t *outgoing) {
522 timeout_del(&outgoing->ev);
524 node_t *n = lookup_node(outgoing->name);
526 if(n && n->connection) {
527 logger(DEBUG_CONNECTIONS, LOG_INFO, "Already connected to %s", outgoing->name);
529 n->connection->outgoing = outgoing;
533 init_configuration(&outgoing->config_tree);
534 read_host_config(outgoing->config_tree, outgoing->name);
535 outgoing->cfg = lookup_config(outgoing->config_tree, "Address");
538 logger(DEBUG_ALWAYS, LOG_ERR, "No address specified for %s", outgoing->name);
542 do_outgoing_connection(outgoing);
546 accept a new tcp connect and create a
549 void handle_new_meta_connection(void *data, int flags) {
550 listen_socket_t *l = data;
554 socklen_t len = sizeof sa;
556 fd = accept(l->tcp.fd, &sa.sa, &len);
559 logger(DEBUG_ALWAYS, LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
565 // Check if we get many connections from the same host
567 static sockaddr_t prev_sa;
568 static time_t prev_time;
569 static int tarpit = -1;
576 if(prev_time == now.tv_sec && !sockaddrcmp_noport(&sa, &prev_sa)) {
577 // if so, keep the connection open but ignore it completely.
582 memcpy(&prev_sa, &sa, sizeof sa);
583 prev_time = now.tv_sec;
585 // Check if we get many connections from different hosts
587 static int connection_burst;
588 static int connection_burst_time;
590 if(now.tv_sec - connection_burst_time > connection_burst)
591 connection_burst = 0;
593 connection_burst -= now.tv_sec - connection_burst_time;
595 connection_burst_time = now.tv_sec;
598 if(connection_burst >= max_connection_burst) {
599 connection_burst = max_connection_burst;
604 // Accept the new connection
606 c = new_connection();
607 c->name = xstrdup("<unknown>");
608 c->outcipher = myself->connection->outcipher;
609 c->outdigest = myself->connection->outdigest;
610 c->outmaclength = myself->connection->outmaclength;
611 c->outcompression = myself->connection->outcompression;
614 c->hostname = sockaddr2hostname(&sa);
616 c->last_ping_time = now.tv_sec;
618 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection from %s", c->hostname);
620 io_add(&c->io, handle_meta_io, c, c->socket, IO_READ);
626 c->allow_request = ID;
632 accept a new UNIX socket connection
634 void handle_new_unix_connection(void *data, int flags) {
639 socklen_t len = sizeof sa;
641 fd = accept(io->fd, &sa.sa, &len);
644 logger(DEBUG_ALWAYS, LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
650 c = new_connection();
651 c->name = xstrdup("<control>");
653 c->hostname = xstrdup("localhost port unix");
655 c->last_ping_time = now.tv_sec;
657 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection from %s", c->hostname);
659 io_add(&c->io, handle_meta_io, c, c->socket, IO_READ);
663 c->allow_request = ID;
669 static void free_outgoing(outgoing_t *outgoing) {
670 timeout_del(&outgoing->ev);
673 freeaddrinfo(outgoing->ai);
675 if(outgoing->config_tree)
676 exit_configuration(&outgoing->config_tree);
679 free(outgoing->name);
684 void try_outgoing_connections(void) {
685 /* If there is no outgoing list yet, create one. Otherwise, mark all outgoings as deleted. */
688 outgoing_list = list_alloc((list_action_t)free_outgoing);
690 for list_each(outgoing_t, outgoing, outgoing_list)
691 outgoing->timeout = -1;
694 /* Make sure there is one outgoing_t in the list for each ConnectTo. */
696 for(config_t *cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
698 get_config_string(cfg, &name);
700 if(!check_id(name)) {
701 logger(DEBUG_ALWAYS, LOG_ERR,
702 "Invalid name for outgoing connection in %s line %d",
703 cfg->file, cfg->line);
710 for list_each(outgoing_t, outgoing, outgoing_list) {
711 if(!strcmp(outgoing->name, name)) {
713 outgoing->timeout = 0;
719 outgoing_t *outgoing = xzalloc(sizeof *outgoing);
720 outgoing->name = name;
721 list_insert_tail(outgoing_list, outgoing);
722 setup_outgoing_connection(outgoing);
726 /* Terminate any connections whose outgoing_t is to be deleted. */
728 for list_each(connection_t, c, connection_list) {
729 if(c->outgoing && c->outgoing->timeout == -1) {
731 logger(DEBUG_CONNECTIONS, LOG_INFO, "No more outgoing connection to %s", c->name);
732 terminate_connection(c, c->status.active);
736 /* Delete outgoing_ts for which there is no ConnectTo. */
738 for list_each(outgoing_t, outgoing, outgoing_list)
739 if(outgoing->timeout == -1)
740 list_delete_node(outgoing_list, node);