2 net_socket.c -- Handle various kinds of sockets.
3 Copyright (C) 1998-2005 Ivo Timmermans,
4 2000-2016 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;
46 int udp_rcvbuf = 1024 * 1024;
47 int udp_sndbuf = 1024 * 1024;
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);
86 #if defined(IPPROTO_IPV6) && defined(IPV6_TCLASS) && defined(IPTOS_LOWDELAY)
87 option = IPTOS_LOWDELAY;
88 setsockopt(c->socket, IPPROTO_IPV6, IPV6_TCLASS, (void *)&option, sizeof option);
92 static bool bind_to_interface(int sd) {
95 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
98 #endif /* defined(SOL_SOCKET) && defined(SO_BINDTODEVICE) */
100 if(!get_config_string (lookup_config (config_tree, "BindToInterface"), &iface))
103 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
104 memset(&ifr, 0, sizeof(ifr));
105 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
106 ifr.ifr_ifrn.ifrn_name[IFNAMSIZ - 1] = 0;
108 status = setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr));
110 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to interface %s: %s", iface,
111 sockstrerror(sockerrno));
114 #else /* if !defined(SOL_SOCKET) || !defined(SO_BINDTODEVICE) */
115 logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform", "BindToInterface");
121 static bool bind_to_address(connection_t *c) {
124 for(int i = 0; i < listen_sockets && listen_socket[i].bindto; i++) {
125 if(listen_socket[i].sa.sa.sa_family != c->address.sa.sa_family)
135 sockaddr_t sa = listen_socket[s].sa;
136 if(sa.sa.sa_family == AF_INET)
138 else if(sa.sa.sa_family == AF_INET6)
139 sa.in6.sin6_port = 0;
141 if(bind(c->socket, &sa.sa, SALEN(sa.sa))) {
142 logger(DEBUG_CONNECTIONS, LOG_WARNING, "Can't bind outgoing socket: %s", sockstrerror(sockerrno));
149 int setup_listen_socket(const sockaddr_t *sa) {
155 nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
158 logger(DEBUG_STATUS, LOG_ERR, "Creating metasocket failed: %s", sockstrerror(sockerrno));
163 fcntl(nfd, F_SETFD, FD_CLOEXEC);
166 /* Optimize TCP settings */
169 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof option);
171 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
172 if(sa->sa.sa_family == AF_INET6)
173 setsockopt(nfd, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
177 (lookup_config(config_tree, "BindToInterface"), &iface)) {
178 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
181 memset(&ifr, 0, sizeof ifr);
182 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
184 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof ifr)) {
186 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to interface %s: %s", iface,
187 sockstrerror(sockerrno));
191 logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform", "BindToInterface");
195 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
197 addrstr = sockaddr2hostname(sa);
198 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
205 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
212 int setup_vpn_in_socket(const sockaddr_t *sa) {
217 nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
220 logger(DEBUG_ALWAYS, LOG_ERR, "Creating UDP socket failed: %s", sockstrerror(sockerrno));
225 fcntl(nfd, F_SETFD, FD_CLOEXEC);
230 int flags = fcntl(nfd, F_GETFL);
232 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
234 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "fcntl",
241 unsigned long arg = 1;
242 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
244 logger(DEBUG_ALWAYS, LOG_ERR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
251 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof option);
252 setsockopt(nfd, SOL_SOCKET, SO_BROADCAST, (void *)&option, sizeof option);
254 if(udp_rcvbuf && setsockopt(nfd, SOL_SOCKET, SO_RCVBUF, (void *)&udp_rcvbuf, sizeof(udp_rcvbuf)))
255 logger(DEBUG_ALWAYS, LOG_WARNING, "Can't set UDP SO_RCVBUF to %i: %s", udp_rcvbuf, sockstrerror(sockerrno));
257 if(udp_sndbuf && setsockopt(nfd, SOL_SOCKET, SO_SNDBUF, (void *)&udp_sndbuf, sizeof(udp_sndbuf)))
258 logger(DEBUG_ALWAYS, LOG_WARNING, "Can't set UDP SO_SNDBUF to %i: %s", udp_sndbuf, sockstrerror(sockerrno));
260 #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
261 if(sa->sa.sa_family == AF_INET6)
262 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
265 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
266 #define IP_DONTFRAGMENT IP_DONTFRAG
269 #if defined(SOL_IP) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
270 if(myself->options & OPTION_PMTU_DISCOVERY) {
271 option = IP_PMTUDISC_DO;
272 setsockopt(nfd, SOL_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
274 #elif defined(IPPROTO_IP) && defined(IP_DONTFRAGMENT)
275 if(myself->options & OPTION_PMTU_DISCOVERY) {
277 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
281 #if defined(SOL_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
282 if(myself->options & OPTION_PMTU_DISCOVERY) {
283 option = IPV6_PMTUDISC_DO;
284 setsockopt(nfd, SOL_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
286 #elif defined(IPPROTO_IPV6) && defined(IPV6_DONTFRAG)
287 if(myself->options & OPTION_PMTU_DISCOVERY) {
289 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
293 if (!bind_to_interface(nfd)) {
298 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
300 addrstr = sockaddr2hostname(sa);
301 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
307 } /* int setup_vpn_in_socket */
309 static void retry_outgoing_handler(void *data) {
310 setup_outgoing_connection(data);
313 void retry_outgoing(outgoing_t *outgoing) {
314 outgoing->timeout += 5;
316 if(outgoing->timeout > maxtimeout)
317 outgoing->timeout = maxtimeout;
319 timeout_add(&outgoing->ev, retry_outgoing_handler, outgoing, &(struct timeval){outgoing->timeout, rand() % 100000});
321 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Trying to re-establish outgoing connection in %d seconds", outgoing->timeout);
324 void finish_connecting(connection_t *c) {
325 logger(DEBUG_CONNECTIONS, LOG_INFO, "Connected to %s (%s)", c->name, c->hostname);
327 c->last_ping_time = now.tv_sec;
328 c->status.connecting = false;
333 static void do_outgoing_pipe(connection_t *c, char *command) {
337 if(socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) {
338 logger(DEBUG_ALWAYS, LOG_ERR, "Could not create socketpair: %s", sockstrerror(sockerrno));
345 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Using proxy %s", command);
356 // Other filedescriptors should be closed automatically by CLOEXEC
361 sockaddr2str(&c->address, &host, &port);
362 setenv("REMOTEADDRESS", host, true);
363 setenv("REMOTEPORT", port, true);
364 setenv("NODE", c->name, true);
365 setenv("NAME", myself->name, true);
367 setenv("NETNAME", netname, true);
369 int result = system(command);
371 logger(DEBUG_ALWAYS, LOG_ERR, "Could not execute %s: %s", command, strerror(errno));
373 logger(DEBUG_ALWAYS, LOG_ERR, "%s exited with non-zero status %d", command, result);
376 logger(DEBUG_ALWAYS, LOG_ERR, "Proxy type exec not supported on this platform!");
381 static void handle_meta_write(connection_t *c) {
382 if(c->outbuf.len <= c->outbuf.offset)
385 ssize_t outlen = send(c->socket, c->outbuf.data + c->outbuf.offset, c->outbuf.len - c->outbuf.offset, 0);
387 if(!sockerrno || sockerrno == EPIPE) {
388 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection closed by %s (%s)", c->name, c->hostname);
389 } else if(sockwouldblock(sockerrno)) {
390 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Sending %d bytes to %s (%s) would block", c->outbuf.len - c->outbuf.offset, c->name, c->hostname);
393 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, sockstrerror(sockerrno));
396 terminate_connection(c, c->edge);
400 buffer_read(&c->outbuf, outlen);
402 io_set(&c->io, IO_READ);
405 static void handle_meta_io(void *data, int flags) {
406 connection_t *c = data;
408 if(c->status.connecting) {
410 The event loop does not protect against spurious events. Verify that we are actually connected
411 by issuing an empty send() call.
413 Note that the behavior of send() on potentially unconnected sockets differ between platforms:
414 +------------+-----------+-------------+-----------+
415 | Event | POSIX | Linux | Windows |
416 +------------+-----------+-------------+-----------+
417 | Spurious | ENOTCONN | EWOULDBLOCK | ENOTCONN |
418 | Failed | ENOTCONN | (cause) | ENOTCONN |
419 | Successful | (success) | (success) | (success) |
420 +------------+-----------+-------------+-----------+
422 if (send(c->socket, NULL, 0, 0) != 0) {
423 if (sockwouldblock(sockerrno))
426 if (!socknotconn(sockerrno))
427 socket_error = sockerrno;
429 socklen_t len = sizeof socket_error;
430 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&socket_error, &len);
433 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Error while connecting to %s (%s): %s", c->name, c->hostname, sockstrerror(socket_error));
434 terminate_connection(c, false);
439 c->status.connecting = false;
440 finish_connecting(c);
444 handle_meta_write(c);
446 handle_meta_connection_data(c);
449 bool do_outgoing_connection(outgoing_t *outgoing) {
450 char *address, *port, *space;
451 struct addrinfo *proxyai = NULL;
457 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not set up a meta connection to %s", outgoing->name);
458 retry_outgoing(outgoing);
462 get_config_string(outgoing->cfg, &address);
464 space = strchr(address, ' ');
466 port = xstrdup(space + 1);
469 if(!get_config_string(lookup_config(outgoing->config_tree, "Port"), &port))
470 port = xstrdup("655");
473 outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
477 outgoing->aip = outgoing->ai;
478 outgoing->cfg = lookup_config_next(outgoing->config_tree, outgoing->cfg);
483 freeaddrinfo(outgoing->ai);
488 connection_t *c = new_connection();
489 c->outgoing = outgoing;
491 memcpy(&c->address, outgoing->aip->ai_addr, outgoing->aip->ai_addrlen);
492 outgoing->aip = outgoing->aip->ai_next;
494 c->hostname = sockaddr2hostname(&c->address);
496 logger(DEBUG_CONNECTIONS, LOG_INFO, "Trying to connect to %s (%s)", outgoing->name, c->hostname);
499 c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
501 } else if(proxytype == PROXY_EXEC) {
502 do_outgoing_pipe(c, proxyhost);
504 proxyai = str2addrinfo(proxyhost, proxyport, SOCK_STREAM);
509 logger(DEBUG_CONNECTIONS, LOG_INFO, "Using proxy at %s port %s", proxyhost, proxyport);
510 c->socket = socket(proxyai->ai_family, SOCK_STREAM, IPPROTO_TCP);
514 if(c->socket == -1) {
515 logger(DEBUG_CONNECTIONS, LOG_ERR, "Creating socket for %s failed: %s", c->hostname, sockstrerror(sockerrno));
521 fcntl(c->socket, F_SETFD, FD_CLOEXEC);
524 if(proxytype != PROXY_EXEC) {
525 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
527 if(c->address.sa.sa_family == AF_INET6)
528 setsockopt(c->socket, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
531 bind_to_interface(c->socket);
538 result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
539 } else if(proxytype == PROXY_EXEC) {
542 result = connect(c->socket, proxyai->ai_addr, proxyai->ai_addrlen);
543 freeaddrinfo(proxyai);
546 if(result == -1 && !sockinprogress(sockerrno)) {
547 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not connect to %s (%s): %s", outgoing->name, c->hostname, sockstrerror(sockerrno));
553 /* Now that there is a working socket, fill in the rest and register this connection. */
555 c->last_ping_time = time(NULL);
556 c->status.connecting = true;
557 c->name = xstrdup(outgoing->name);
558 #ifndef DISABLE_LEGACY
559 c->outcipher = myself->connection->outcipher;
560 c->outdigest = myself->connection->outdigest;
562 c->outmaclength = myself->connection->outmaclength;
563 c->outcompression = myself->connection->outcompression;
564 c->last_ping_time = now.tv_sec;
568 io_add(&c->io, handle_meta_io, c, c->socket, IO_READ|IO_WRITE);
573 // Find edges pointing to this node, and use them to build a list of unique, known addresses.
574 static struct addrinfo *get_known_addresses(node_t *n) {
575 struct addrinfo *ai = NULL;
577 for splay_each(edge_t, e, n->edge_tree) {
582 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
583 if(!sockaddrcmp(&e->reverse->address, (sockaddr_t *)aip->ai_addr)) {
591 struct addrinfo *nai = xzalloc(sizeof *nai);
595 ai->ai_family = e->reverse->address.sa.sa_family;
596 ai->ai_socktype = SOCK_STREAM;
597 ai->ai_protocol = IPPROTO_TCP;
598 ai->ai_addrlen = SALEN(e->reverse->address.sa);
599 ai->ai_addr = xmalloc(ai->ai_addrlen);
600 memcpy(ai->ai_addr, &e->reverse->address, ai->ai_addrlen);
606 void setup_outgoing_connection(outgoing_t *outgoing) {
607 timeout_del(&outgoing->ev);
609 node_t *n = lookup_node(outgoing->name);
611 if(n && n->connection) {
612 logger(DEBUG_CONNECTIONS, LOG_INFO, "Already connected to %s", outgoing->name);
613 if(!n->connection->outgoing) {
614 n->connection->outgoing = outgoing;
621 init_configuration(&outgoing->config_tree);
622 read_host_config(outgoing->config_tree, outgoing->name);
623 outgoing->cfg = lookup_config(outgoing->config_tree, "Address");
627 outgoing->aip = outgoing->ai = get_known_addresses(n);
629 logger(DEBUG_ALWAYS, LOG_DEBUG, "No address known for %s", outgoing->name);
634 do_outgoing_connection(outgoing);
638 list_delete(outgoing_list, outgoing);
642 accept a new tcp connect and create a
645 void handle_new_meta_connection(void *data, int flags) {
646 listen_socket_t *l = data;
650 socklen_t len = sizeof sa;
652 fd = accept(l->tcp.fd, &sa.sa, &len);
655 logger(DEBUG_ALWAYS, LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
661 // Check if we get many connections from the same host
663 static sockaddr_t prev_sa;
664 static int tarpit = -1;
671 if(!sockaddrcmp_noport(&sa, &prev_sa)) {
672 static int samehost_burst;
673 static int samehost_burst_time;
675 if(now.tv_sec - samehost_burst_time > samehost_burst)
678 samehost_burst -= now.tv_sec - samehost_burst_time;
680 samehost_burst_time = now.tv_sec;
683 if(samehost_burst > max_connection_burst) {
689 memcpy(&prev_sa, &sa, sizeof sa);
691 // Check if we get many connections from different hosts
693 static int connection_burst;
694 static int connection_burst_time;
696 if(now.tv_sec - connection_burst_time > connection_burst)
697 connection_burst = 0;
699 connection_burst -= now.tv_sec - connection_burst_time;
701 connection_burst_time = now.tv_sec;
704 if(connection_burst >= max_connection_burst) {
705 connection_burst = max_connection_burst;
710 // Accept the new connection
712 c = new_connection();
713 c->name = xstrdup("<unknown>");
714 #ifndef DISABLE_LEGACY
715 c->outcipher = myself->connection->outcipher;
716 c->outdigest = myself->connection->outdigest;
718 c->outmaclength = myself->connection->outmaclength;
719 c->outcompression = myself->connection->outcompression;
722 c->hostname = sockaddr2hostname(&sa);
724 c->last_ping_time = now.tv_sec;
726 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection from %s", c->hostname);
728 io_add(&c->io, handle_meta_io, c, c->socket, IO_READ);
734 c->allow_request = ID;
740 accept a new UNIX socket connection
742 void handle_new_unix_connection(void *data, int flags) {
747 socklen_t len = sizeof sa;
749 fd = accept(io->fd, &sa.sa, &len);
752 logger(DEBUG_ALWAYS, LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
758 c = new_connection();
759 c->name = xstrdup("<control>");
761 c->hostname = xstrdup("localhost port unix");
763 c->last_ping_time = now.tv_sec;
765 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection from %s", c->hostname);
767 io_add(&c->io, handle_meta_io, c, c->socket, IO_READ);
771 c->allow_request = ID;
777 static void free_outgoing(outgoing_t *outgoing) {
778 timeout_del(&outgoing->ev);
781 freeaddrinfo(outgoing->ai);
783 if(outgoing->config_tree)
784 exit_configuration(&outgoing->config_tree);
787 free(outgoing->name);
792 void try_outgoing_connections(void) {
793 /* If there is no outgoing list yet, create one. Otherwise, mark all outgoings as deleted. */
796 outgoing_list = list_alloc((list_action_t)free_outgoing);
798 for list_each(outgoing_t, outgoing, outgoing_list)
799 outgoing->timeout = -1;
802 /* Make sure there is one outgoing_t in the list for each ConnectTo. */
804 for(config_t *cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
806 get_config_string(cfg, &name);
808 if(!check_id(name)) {
809 logger(DEBUG_ALWAYS, LOG_ERR,
810 "Invalid name for outgoing connection in %s line %d",
811 cfg->file, cfg->line);
816 if(!strcmp(name, myself->name)) {
823 for list_each(outgoing_t, outgoing, outgoing_list) {
824 if(!strcmp(outgoing->name, name)) {
826 outgoing->timeout = 0;
832 outgoing_t *outgoing = xzalloc(sizeof *outgoing);
833 outgoing->name = name;
834 list_insert_tail(outgoing_list, outgoing);
835 setup_outgoing_connection(outgoing);
839 /* Terminate any connections whose outgoing_t is to be deleted. */
841 for list_each(connection_t, c, connection_list) {
842 if(c->outgoing && c->outgoing->timeout == -1) {
844 logger(DEBUG_CONNECTIONS, LOG_INFO, "No more outgoing connection to %s", c->name);
845 terminate_connection(c, c->edge);
849 /* Delete outgoing_ts for which there is no ConnectTo. */
851 for list_each(outgoing_t, outgoing, outgoing_list)
852 if(outgoing->timeout == -1)
853 list_delete_node(outgoing_list, node);