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 static bool bind_to_address(connection_t *c) {
119 for(int i = 0; i < listen_sockets; i++) {
120 if(listen_socket[i].sa.sa.sa_family != c->address.sa.sa_family)
130 sockaddr_t sa = listen_socket[s].sa;
131 if(sa.sa.sa_family == AF_INET)
133 else if(sa.sa.sa_family == AF_INET6)
134 sa.in6.sin6_port = 0;
136 if(bind(c->socket, &sa.sa, SALEN(sa.sa))) {
137 logger(DEBUG_CONNECTIONS, LOG_WARNING, "Can't bind outgoing socket: %s", strerror(errno));
144 int setup_listen_socket(const sockaddr_t *sa) {
150 nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
153 logger(DEBUG_STATUS, LOG_ERR, "Creating metasocket failed: %s", sockstrerror(sockerrno));
158 fcntl(nfd, F_SETFD, FD_CLOEXEC);
161 /* Optimize TCP settings */
164 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof option);
166 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
167 if(sa->sa.sa_family == AF_INET6)
168 setsockopt(nfd, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
172 (lookup_config(config_tree, "BindToInterface"), &iface)) {
173 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
176 memset(&ifr, 0, sizeof ifr);
177 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
179 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof ifr)) {
181 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to interface %s: %s", iface,
182 strerror(sockerrno));
186 logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform", "BindToInterface");
190 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
192 addrstr = sockaddr2hostname(sa);
193 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
200 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
207 int setup_vpn_in_socket(const sockaddr_t *sa) {
212 nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
215 logger(DEBUG_ALWAYS, LOG_ERR, "Creating UDP socket failed: %s", sockstrerror(sockerrno));
220 fcntl(nfd, F_SETFD, FD_CLOEXEC);
225 int flags = fcntl(nfd, F_GETFL);
227 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
229 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "fcntl",
236 unsigned long arg = 1;
237 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
239 logger(DEBUG_ALWAYS, LOG_ERR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
246 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof option);
247 setsockopt(nfd, SOL_SOCKET, SO_BROADCAST, (void *)&option, sizeof option);
249 if(udp_rcvbuf && setsockopt(nfd, SOL_SOCKET, SO_RCVBUF, (void *)&udp_rcvbuf, sizeof(udp_rcvbuf)))
250 logger(DEBUG_ALWAYS, LOG_WARNING, "Can't set UDP SO_RCVBUF to %i: %s", udp_rcvbuf, strerror(errno));
252 if(udp_sndbuf && setsockopt(nfd, SOL_SOCKET, SO_SNDBUF, (void *)&udp_sndbuf, sizeof(udp_sndbuf)))
253 logger(DEBUG_ALWAYS, LOG_WARNING, "Can't set UDP SO_SNDBUF to %i: %s", udp_sndbuf, strerror(errno));
255 #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
256 if(sa->sa.sa_family == AF_INET6)
257 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
260 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
261 #define IP_DONTFRAGMENT IP_DONTFRAG
264 #if defined(SOL_IP) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
265 if(myself->options & OPTION_PMTU_DISCOVERY) {
266 option = IP_PMTUDISC_DO;
267 setsockopt(nfd, SOL_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
269 #elif defined(IPPROTO_IP) && defined(IP_DONTFRAGMENT)
270 if(myself->options & OPTION_PMTU_DISCOVERY) {
272 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
275 #warning No way to disable IPv4 fragmentation
278 #if defined(SOL_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
279 if(myself->options & OPTION_PMTU_DISCOVERY) {
280 option = IPV6_PMTUDISC_DO;
281 setsockopt(nfd, SOL_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
283 #elif defined(IPPROTO_IPV6) && defined(IPV6_DONTFRAG)
284 if(myself->options & OPTION_PMTU_DISCOVERY) {
286 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
289 #warning No way to disable IPv6 fragmentation
292 if (!bind_to_interface(nfd)) {
297 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
299 addrstr = sockaddr2hostname(sa);
300 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
306 } /* int setup_vpn_in_socket */
308 static void retry_outgoing_handler(void *data) {
309 setup_outgoing_connection(data);
312 void retry_outgoing(outgoing_t *outgoing) {
313 outgoing->timeout += 5;
315 if(outgoing->timeout > maxtimeout)
316 outgoing->timeout = maxtimeout;
318 timeout_add(&outgoing->ev, retry_outgoing_handler, outgoing, &(struct timeval){outgoing->timeout, rand() % 100000});
320 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Trying to re-establish outgoing connection in %d seconds", outgoing->timeout);
323 void finish_connecting(connection_t *c) {
324 logger(DEBUG_CONNECTIONS, LOG_INFO, "Connected to %s (%s)", c->name, c->hostname);
326 c->last_ping_time = now.tv_sec;
327 c->status.connecting = false;
332 static void do_outgoing_pipe(connection_t *c, char *command) {
336 if(socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) {
337 logger(DEBUG_ALWAYS, LOG_ERR, "Could not create socketpair: %s", strerror(errno));
344 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Using proxy %s", command);
355 // Other filedescriptors should be closed automatically by CLOEXEC
360 sockaddr2str(&c->address, &host, &port);
361 setenv("REMOTEADDRESS", host, true);
362 setenv("REMOTEPORT", port, true);
363 setenv("NODE", c->name, true);
364 setenv("NAME", myself->name, true);
366 setenv("NETNAME", netname, true);
368 int result = system(command);
370 logger(DEBUG_ALWAYS, LOG_ERR, "Could not execute %s: %s", command, strerror(errno));
372 logger(DEBUG_ALWAYS, LOG_ERR, "%s exited with non-zero status %d", command, result);
375 logger(DEBUG_ALWAYS, LOG_ERR, "Proxy type exec not supported on this platform!");
380 static void handle_meta_write(connection_t *c) {
381 if(c->outbuf.len <= c->outbuf.offset)
384 ssize_t outlen = send(c->socket, c->outbuf.data + c->outbuf.offset, c->outbuf.len - c->outbuf.offset, 0);
386 if(!errno || errno == EPIPE) {
387 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection closed by %s (%s)", c->name, c->hostname);
388 } else if(sockwouldblock(sockerrno)) {
389 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Sending %d bytes to %s (%s) would block", c->outbuf.len - c->outbuf.offset, c->name, c->hostname);
392 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));
395 terminate_connection(c, c->status.active);
399 buffer_read(&c->outbuf, outlen);
401 io_set(&c->io, IO_READ);
404 static void handle_meta_io(void *data, int flags) {
405 connection_t *c = data;
407 if(c->status.connecting) {
408 c->status.connecting = false;
411 socklen_t len = sizeof result;
412 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
415 finish_connecting(c);
417 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Error while connecting to %s (%s): %s", c->name, c->hostname, sockstrerror(result));
418 terminate_connection(c, false);
424 handle_meta_write(c);
426 handle_meta_connection_data(c);
429 bool do_outgoing_connection(outgoing_t *outgoing) {
430 char *address, *port, *space;
431 struct addrinfo *proxyai = NULL;
437 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not set up a meta connection to %s", outgoing->name);
438 retry_outgoing(outgoing);
442 get_config_string(outgoing->cfg, &address);
444 space = strchr(address, ' ');
446 port = xstrdup(space + 1);
449 if(!get_config_string(lookup_config(outgoing->config_tree, "Port"), &port))
450 port = xstrdup("655");
453 outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
457 outgoing->aip = outgoing->ai;
458 outgoing->cfg = lookup_config_next(outgoing->config_tree, outgoing->cfg);
463 freeaddrinfo(outgoing->ai);
468 connection_t *c = new_connection();
469 c->outgoing = outgoing;
471 memcpy(&c->address, outgoing->aip->ai_addr, outgoing->aip->ai_addrlen);
472 outgoing->aip = outgoing->aip->ai_next;
474 c->hostname = sockaddr2hostname(&c->address);
476 logger(DEBUG_CONNECTIONS, LOG_INFO, "Trying to connect to %s (%s)", outgoing->name, c->hostname);
479 c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
481 } else if(proxytype == PROXY_EXEC) {
482 do_outgoing_pipe(c, proxyhost);
484 proxyai = str2addrinfo(proxyhost, proxyport, SOCK_STREAM);
489 logger(DEBUG_CONNECTIONS, LOG_INFO, "Using proxy at %s port %s", proxyhost, proxyport);
490 c->socket = socket(proxyai->ai_family, SOCK_STREAM, IPPROTO_TCP);
494 if(c->socket == -1) {
495 logger(DEBUG_CONNECTIONS, LOG_ERR, "Creating socket for %s failed: %s", c->hostname, sockstrerror(sockerrno));
501 fcntl(c->socket, F_SETFD, FD_CLOEXEC);
504 if(proxytype != PROXY_EXEC) {
505 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
507 if(c->address.sa.sa_family == AF_INET6)
508 setsockopt(c->socket, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
511 bind_to_interface(c->socket);
518 result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
519 } else if(proxytype == PROXY_EXEC) {
522 result = connect(c->socket, proxyai->ai_addr, proxyai->ai_addrlen);
523 freeaddrinfo(proxyai);
526 if(result == -1 && !sockinprogress(sockerrno)) {
527 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not connect to %s (%s): %s", outgoing->name, c->hostname, sockstrerror(sockerrno));
533 /* Now that there is a working socket, fill in the rest and register this connection. */
535 c->status.connecting = true;
536 c->name = xstrdup(outgoing->name);
537 c->outcipher = myself->connection->outcipher;
538 c->outdigest = myself->connection->outdigest;
539 c->outmaclength = myself->connection->outmaclength;
540 c->outcompression = myself->connection->outcompression;
541 c->last_ping_time = now.tv_sec;
545 io_add(&c->io, handle_meta_io, c, c->socket, IO_READ|IO_WRITE);
550 void setup_outgoing_connection(outgoing_t *outgoing) {
551 timeout_del(&outgoing->ev);
553 node_t *n = lookup_node(outgoing->name);
555 if(n && n->connection) {
556 logger(DEBUG_CONNECTIONS, LOG_INFO, "Already connected to %s", outgoing->name);
558 n->connection->outgoing = outgoing;
562 init_configuration(&outgoing->config_tree);
563 read_host_config(outgoing->config_tree, outgoing->name);
564 outgoing->cfg = lookup_config(outgoing->config_tree, "Address");
567 logger(DEBUG_ALWAYS, LOG_ERR, "No address specified for %s", outgoing->name);
571 do_outgoing_connection(outgoing);
575 accept a new tcp connect and create a
578 void handle_new_meta_connection(void *data, int flags) {
579 listen_socket_t *l = data;
583 socklen_t len = sizeof sa;
585 fd = accept(l->tcp.fd, &sa.sa, &len);
588 logger(DEBUG_ALWAYS, LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
594 // Check if we get many connections from the same host
596 static sockaddr_t prev_sa;
597 static time_t prev_time;
598 static int tarpit = -1;
605 if(!sockaddrcmp_noport(&sa, &prev_sa)) {
606 static int samehost_burst;
607 static int samehost_burst_time;
609 if(now.tv_sec - samehost_burst_time > samehost_burst)
612 samehost_burst -= now.tv_sec - samehost_burst_time;
614 samehost_burst_time = now.tv_sec;
617 if(samehost_burst > max_connection_burst) {
623 memcpy(&prev_sa, &sa, sizeof sa);
624 prev_time = now.tv_sec;
626 // Check if we get many connections from different hosts
628 static int connection_burst;
629 static int connection_burst_time;
631 if(now.tv_sec - connection_burst_time > connection_burst)
632 connection_burst = 0;
634 connection_burst -= now.tv_sec - connection_burst_time;
636 connection_burst_time = now.tv_sec;
639 if(connection_burst >= max_connection_burst) {
640 connection_burst = max_connection_burst;
645 // Accept the new connection
647 c = new_connection();
648 c->name = xstrdup("<unknown>");
649 c->outcipher = myself->connection->outcipher;
650 c->outdigest = myself->connection->outdigest;
651 c->outmaclength = myself->connection->outmaclength;
652 c->outcompression = myself->connection->outcompression;
655 c->hostname = sockaddr2hostname(&sa);
657 c->last_ping_time = now.tv_sec;
659 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection from %s", c->hostname);
661 io_add(&c->io, handle_meta_io, c, c->socket, IO_READ);
667 c->allow_request = ID;
673 accept a new UNIX socket connection
675 void handle_new_unix_connection(void *data, int flags) {
680 socklen_t len = sizeof sa;
682 fd = accept(io->fd, &sa.sa, &len);
685 logger(DEBUG_ALWAYS, LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
691 c = new_connection();
692 c->name = xstrdup("<control>");
694 c->hostname = xstrdup("localhost port unix");
696 c->last_ping_time = now.tv_sec;
698 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection from %s", c->hostname);
700 io_add(&c->io, handle_meta_io, c, c->socket, IO_READ);
704 c->allow_request = ID;
710 static void free_outgoing(outgoing_t *outgoing) {
711 timeout_del(&outgoing->ev);
714 freeaddrinfo(outgoing->ai);
716 if(outgoing->config_tree)
717 exit_configuration(&outgoing->config_tree);
720 free(outgoing->name);
725 void try_outgoing_connections(void) {
726 /* If there is no outgoing list yet, create one. Otherwise, mark all outgoings as deleted. */
729 outgoing_list = list_alloc((list_action_t)free_outgoing);
731 for list_each(outgoing_t, outgoing, outgoing_list)
732 outgoing->timeout = -1;
735 /* Make sure there is one outgoing_t in the list for each ConnectTo. */
737 for(config_t *cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
739 get_config_string(cfg, &name);
741 if(!check_id(name)) {
742 logger(DEBUG_ALWAYS, LOG_ERR,
743 "Invalid name for outgoing connection in %s line %d",
744 cfg->file, cfg->line);
751 for list_each(outgoing_t, outgoing, outgoing_list) {
752 if(!strcmp(outgoing->name, name)) {
754 outgoing->timeout = 0;
760 outgoing_t *outgoing = xzalloc(sizeof *outgoing);
761 outgoing->name = name;
762 list_insert_tail(outgoing_list, outgoing);
763 setup_outgoing_connection(outgoing);
767 /* Terminate any connections whose outgoing_t is to be deleted. */
769 for list_each(connection_t, c, connection_list) {
770 if(c->outgoing && c->outgoing->timeout == -1) {
772 logger(DEBUG_CONNECTIONS, LOG_INFO, "No more outgoing connection to %s", c->name);
773 terminate_connection(c, c->status.active);
777 /* Delete outgoing_ts for which there is no ConnectTo. */
779 for list_each(outgoing_t, outgoing, outgoing_list)
780 if(outgoing->timeout == -1)
781 list_delete_node(outgoing_list, node);