2 net_socket.c -- Handle various kinds of sockets.
3 Copyright (C) 1998-2005 Ivo Timmermans,
4 2000-2017 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.
25 #include "address_cache.h"
27 #include "connection.h"
28 #include "control_common.h"
39 int addressfamily = AF_UNSPEC;
41 int seconds_till_retry = 5;
42 int udp_rcvbuf = 1024 * 1024;
43 int udp_sndbuf = 1024 * 1024;
44 int max_connection_burst = 100;
46 listen_socket_t listen_socket[MAXSOCKETS];
51 list_t *outgoing_list = NULL;
55 static void configure_tcp(connection_t *c) {
59 int flags = fcntl(c->socket, F_GETFL);
61 if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0) {
62 logger(DEBUG_ALWAYS, LOG_ERR, "fcntl for %s: %s", c->hostname, strerror(errno));
66 unsigned long arg = 1;
68 if(ioctlsocket(c->socket, FIONBIO, &arg) != 0) {
69 logger(DEBUG_ALWAYS, LOG_ERR, "ioctlsocket for %s: %s", c->hostname, sockstrerror(sockerrno));
74 #if defined(TCP_NODELAY)
76 setsockopt(c->socket, IPPROTO_TCP, TCP_NODELAY, (void *)&option, sizeof(option));
79 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
80 option = IPTOS_LOWDELAY;
81 setsockopt(c->socket, IPPROTO_IP, IP_TOS, (void *)&option, sizeof(option));
84 #if defined(IPV6_TCLASS) && defined(IPTOS_LOWDELAY)
85 option = IPTOS_LOWDELAY;
86 setsockopt(c->socket, IPPROTO_IPV6, IPV6_TCLASS, (void *)&option, sizeof(option));
90 static bool bind_to_interface(int sd) {
93 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
96 #endif /* defined(SOL_SOCKET) && defined(SO_BINDTODEVICE) */
98 if(!get_config_string(lookup_config(config_tree, "BindToInterface"), &iface)) {
102 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
103 memset(&ifr, 0, sizeof(ifr));
104 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
105 ifr.ifr_ifrn.ifrn_name[IFNAMSIZ - 1] = 0;
107 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));
115 #else /* if !defined(SOL_SOCKET) || !defined(SO_BINDTODEVICE) */
116 logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform", "BindToInterface");
122 static bool bind_to_address(connection_t *c) {
125 for(int i = 0; i < listen_sockets && listen_socket[i].bindto; i++) {
126 if(listen_socket[i].sa.sa.sa_family != c->address.sa.sa_family) {
141 sockaddr_t sa = listen_socket[s].sa;
143 if(sa.sa.sa_family == AF_INET) {
145 } else if(sa.sa.sa_family == AF_INET6) {
146 sa.in6.sin6_port = 0;
149 if(bind(c->socket, &sa.sa, SALEN(sa.sa))) {
150 logger(DEBUG_CONNECTIONS, LOG_WARNING, "Can't bind outgoing socket: %s", sockstrerror(sockerrno));
157 int setup_listen_socket(const sockaddr_t *sa) {
163 nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
166 logger(DEBUG_STATUS, LOG_ERR, "Creating metasocket failed: %s", sockstrerror(sockerrno));
171 fcntl(nfd, F_SETFD, FD_CLOEXEC);
174 /* Optimize TCP settings */
177 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
179 #if defined(IPV6_V6ONLY)
181 if(sa->sa.sa_family == AF_INET6) {
182 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
186 #warning IPV6_V6ONLY not defined
190 (lookup_config(config_tree, "BindToInterface"), &iface)) {
191 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
194 memset(&ifr, 0, sizeof(ifr));
195 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
197 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr))) {
199 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to interface %s: %s", iface,
200 sockstrerror(sockerrno));
205 logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform", "BindToInterface");
209 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
211 addrstr = sockaddr2hostname(sa);
212 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
219 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
226 int setup_vpn_in_socket(const sockaddr_t *sa) {
231 nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
234 logger(DEBUG_ALWAYS, LOG_ERR, "Creating UDP socket failed: %s", sockstrerror(sockerrno));
239 fcntl(nfd, F_SETFD, FD_CLOEXEC);
244 int flags = fcntl(nfd, F_GETFL);
246 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
248 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "fcntl",
255 unsigned long arg = 1;
257 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
259 logger(DEBUG_ALWAYS, LOG_ERR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
266 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
267 setsockopt(nfd, SOL_SOCKET, SO_BROADCAST, (void *)&option, sizeof(option));
269 if(udp_rcvbuf && setsockopt(nfd, SOL_SOCKET, SO_RCVBUF, (void *)&udp_rcvbuf, sizeof(udp_rcvbuf))) {
270 logger(DEBUG_ALWAYS, LOG_WARNING, "Can't set UDP SO_RCVBUF to %i: %s", udp_rcvbuf, sockstrerror(sockerrno));
273 if(udp_sndbuf && setsockopt(nfd, SOL_SOCKET, SO_SNDBUF, (void *)&udp_sndbuf, sizeof(udp_sndbuf))) {
274 logger(DEBUG_ALWAYS, LOG_WARNING, "Can't set UDP SO_SNDBUF to %i: %s", udp_sndbuf, sockstrerror(sockerrno));
277 #if defined(IPV6_V6ONLY)
279 if(sa->sa.sa_family == AF_INET6) {
280 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
285 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
286 #define IP_DONTFRAGMENT IP_DONTFRAG
289 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
291 if(myself->options & OPTION_PMTU_DISCOVERY) {
292 option = IP_PMTUDISC_DO;
293 setsockopt(nfd, IPPROTO_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
296 #elif defined(IP_DONTFRAGMENT)
298 if(myself->options & OPTION_PMTU_DISCOVERY) {
300 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
305 #if defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
307 if(myself->options & OPTION_PMTU_DISCOVERY) {
308 option = IPV6_PMTUDISC_DO;
309 setsockopt(nfd, IPPROTO_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
312 #elif defined(IPV6_DONTFRAG)
314 if(myself->options & OPTION_PMTU_DISCOVERY) {
316 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
321 if(!bind_to_interface(nfd)) {
326 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
328 addrstr = sockaddr2hostname(sa);
329 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
335 } /* int setup_vpn_in_socket */
337 static void retry_outgoing_handler(void *data) {
338 setup_outgoing_connection(data, true);
341 void retry_outgoing(outgoing_t *outgoing) {
342 outgoing->timeout += 5;
344 if(outgoing->timeout > maxtimeout) {
345 outgoing->timeout = maxtimeout;
348 timeout_add(&outgoing->ev, retry_outgoing_handler, outgoing, &(struct timeval) {
349 outgoing->timeout, rand() % 100000
352 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Trying to re-establish outgoing connection in %d seconds", outgoing->timeout);
355 void finish_connecting(connection_t *c) {
356 logger(DEBUG_CONNECTIONS, LOG_INFO, "Connected to %s (%s)", c->name, c->hostname);
358 c->last_ping_time = now.tv_sec;
359 c->status.connecting = false;
364 static void do_outgoing_pipe(connection_t *c, char *command) {
368 if(socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) {
369 logger(DEBUG_ALWAYS, LOG_ERR, "Could not create socketpair: %s", sockstrerror(sockerrno));
376 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Using proxy %s", command);
387 // Other filedescriptors should be closed automatically by CLOEXEC
392 sockaddr2str(&c->address, &host, &port);
393 setenv("REMOTEADDRESS", host, true);
394 setenv("REMOTEPORT", port, true);
395 setenv("NODE", c->name, true);
396 setenv("NAME", myself->name, true);
399 setenv("NETNAME", netname, true);
402 int result = system(command);
405 logger(DEBUG_ALWAYS, LOG_ERR, "Could not execute %s: %s", command, strerror(errno));
407 logger(DEBUG_ALWAYS, LOG_ERR, "%s exited with non-zero status %d", command, result);
412 logger(DEBUG_ALWAYS, LOG_ERR, "Proxy type exec not supported on this platform!");
417 static void handle_meta_write(connection_t *c) {
418 if(c->outbuf.len <= c->outbuf.offset) {
422 ssize_t outlen = send(c->socket, c->outbuf.data + c->outbuf.offset, c->outbuf.len - c->outbuf.offset, 0);
425 if(!sockerrno || sockerrno == EPIPE) {
426 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection closed by %s (%s)", c->name, c->hostname);
427 } else if(sockwouldblock(sockerrno)) {
428 logger(DEBUG_META, LOG_DEBUG, "Sending %d bytes to %s (%s) would block", c->outbuf.len - c->outbuf.offset, c->name, c->hostname);
431 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));
434 terminate_connection(c, c->edge);
438 buffer_read(&c->outbuf, outlen);
441 io_set(&c->io, IO_READ);
445 static void handle_meta_io(void *data, int flags) {
446 connection_t *c = data;
448 if(c->status.connecting) {
450 The event loop does not protect against spurious events. Verify that we are actually connected
451 by issuing an empty send() call.
453 Note that the behavior of send() on potentially unconnected sockets differ between platforms:
454 +------------+-----------+-------------+-----------+
455 | Event | POSIX | Linux | Windows |
456 +------------+-----------+-------------+-----------+
457 | Spurious | ENOTCONN | EWOULDBLOCK | ENOTCONN |
458 | Failed | ENOTCONN | (cause) | ENOTCONN |
459 | Successful | (success) | (success) | (success) |
460 +------------+-----------+-------------+-----------+
462 if(send(c->socket, NULL, 0, 0) != 0) {
463 if(sockwouldblock(sockerrno)) {
469 if(!socknotconn(sockerrno)) {
470 socket_error = sockerrno;
472 socklen_t len = sizeof(socket_error);
473 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&socket_error, &len);
477 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Error while connecting to %s (%s): %s", c->name, c->hostname, sockstrerror(socket_error));
478 terminate_connection(c, false);
484 c->status.connecting = false;
485 finish_connecting(c);
488 if(flags & IO_WRITE) {
489 handle_meta_write(c);
491 handle_meta_connection_data(c);
495 bool do_outgoing_connection(outgoing_t *outgoing) {
496 const sockaddr_t *sa;
497 struct addrinfo *proxyai = NULL;
501 sa = get_recent_address(outgoing->address_cache);
504 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not set up a meta connection to %s", outgoing->node->name);
505 retry_outgoing(outgoing);
509 connection_t *c = new_connection();
510 c->outgoing = outgoing;
512 c->hostname = sockaddr2hostname(&c->address);
514 logger(DEBUG_CONNECTIONS, LOG_INFO, "Trying to connect to %s (%s)", outgoing->node->name, c->hostname);
517 c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
519 } else if(proxytype == PROXY_EXEC) {
520 do_outgoing_pipe(c, proxyhost);
522 proxyai = str2addrinfo(proxyhost, proxyport, SOCK_STREAM);
529 logger(DEBUG_CONNECTIONS, LOG_INFO, "Using proxy at %s port %s", proxyhost, proxyport);
530 c->socket = socket(proxyai->ai_family, SOCK_STREAM, IPPROTO_TCP);
534 if(c->socket == -1) {
535 logger(DEBUG_CONNECTIONS, LOG_ERR, "Creating socket for %s failed: %s", c->hostname, sockstrerror(sockerrno));
541 fcntl(c->socket, F_SETFD, FD_CLOEXEC);
544 if(proxytype != PROXY_EXEC) {
545 #if defined(IPV6_V6ONLY)
548 if(c->address.sa.sa_family == AF_INET6) {
549 setsockopt(c->socket, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
554 bind_to_interface(c->socket);
561 result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
562 } else if(proxytype == PROXY_EXEC) {
569 result = connect(c->socket, proxyai->ai_addr, proxyai->ai_addrlen);
570 freeaddrinfo(proxyai);
573 if(result == -1 && !sockinprogress(sockerrno)) {
574 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not connect to %s (%s): %s", outgoing->node->name, c->hostname, sockstrerror(sockerrno));
580 /* Now that there is a working socket, fill in the rest and register this connection. */
582 c->last_ping_time = time(NULL);
583 c->status.connecting = true;
584 c->name = xstrdup(outgoing->node->name);
585 #ifndef DISABLE_LEGACY
586 c->outcipher = myself->connection->outcipher;
587 c->outdigest = myself->connection->outdigest;
589 c->outmaclength = myself->connection->outmaclength;
590 c->outcompression = myself->connection->outcompression;
591 c->last_ping_time = now.tv_sec;
595 io_add(&c->io, handle_meta_io, c, c->socket, IO_READ | IO_WRITE);
600 void setup_outgoing_connection(outgoing_t *outgoing, bool verbose) {
601 timeout_del(&outgoing->ev);
603 node_t *n = outgoing->node;
606 logger(DEBUG_CONNECTIONS, LOG_INFO, "Already connected to %s", n->name);
608 if(!n->connection->outgoing) {
609 n->connection->outgoing = outgoing;
616 if(!outgoing->address_cache) {
617 outgoing->address_cache = open_address_cache(n);
620 do_outgoing_connection(outgoing);
624 list_delete(outgoing_list, outgoing);
628 accept a new tcp connect and create a
631 void handle_new_meta_connection(void *data, int flags) {
632 listen_socket_t *l = data;
636 socklen_t len = sizeof(sa);
638 fd = accept(l->tcp.fd, &sa.sa, &len);
641 logger(DEBUG_ALWAYS, LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
647 // Check if we get many connections from the same host
649 static sockaddr_t prev_sa;
650 static int tarpit = -1;
657 if(!sockaddrcmp_noport(&sa, &prev_sa)) {
658 static int samehost_burst;
659 static int samehost_burst_time;
661 if(now.tv_sec - samehost_burst_time > samehost_burst) {
664 samehost_burst -= now.tv_sec - samehost_burst_time;
667 samehost_burst_time = now.tv_sec;
670 if(samehost_burst > max_connection_burst) {
676 memcpy(&prev_sa, &sa, sizeof(sa));
678 // Check if we get many connections from different hosts
680 static int connection_burst;
681 static int connection_burst_time;
683 if(now.tv_sec - connection_burst_time > connection_burst) {
684 connection_burst = 0;
686 connection_burst -= now.tv_sec - connection_burst_time;
689 connection_burst_time = now.tv_sec;
692 if(connection_burst >= max_connection_burst) {
693 connection_burst = max_connection_burst;
698 // Accept the new connection
700 c = new_connection();
701 c->name = xstrdup("<unknown>");
702 #ifndef DISABLE_LEGACY
703 c->outcipher = myself->connection->outcipher;
704 c->outdigest = myself->connection->outdigest;
706 c->outmaclength = myself->connection->outmaclength;
707 c->outcompression = myself->connection->outcompression;
710 c->hostname = sockaddr2hostname(&sa);
712 c->last_ping_time = now.tv_sec;
714 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection from %s", c->hostname);
716 io_add(&c->io, handle_meta_io, c, c->socket, IO_READ);
722 c->allow_request = ID;
728 accept a new UNIX socket connection
730 void handle_new_unix_connection(void *data, int flags) {
735 socklen_t len = sizeof(sa);
737 fd = accept(io->fd, &sa.sa, &len);
740 logger(DEBUG_ALWAYS, LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
746 c = new_connection();
747 c->name = xstrdup("<control>");
749 c->hostname = xstrdup("localhost port unix");
751 c->last_ping_time = now.tv_sec;
753 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection from %s", c->hostname);
755 io_add(&c->io, handle_meta_io, c, c->socket, IO_READ);
759 c->allow_request = ID;
765 static void free_outgoing(outgoing_t *outgoing) {
766 timeout_del(&outgoing->ev);
768 if(outgoing->address_cache) {
769 close_address_cache(outgoing->address_cache);
775 void try_outgoing_connections(void) {
776 /* If there is no outgoing list yet, create one. Otherwise, mark all outgoings as deleted. */
779 outgoing_list = list_alloc((list_action_t)free_outgoing);
781 for list_each(outgoing_t, outgoing, outgoing_list) {
782 outgoing->timeout = -1;
786 /* Make sure there is one outgoing_t in the list for each ConnectTo. */
788 for(config_t *cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
790 get_config_string(cfg, &name);
792 if(!check_id(name)) {
793 logger(DEBUG_ALWAYS, LOG_ERR,
794 "Invalid name for outgoing connection in %s line %d",
795 cfg->file, cfg->line);
800 if(!strcmp(name, myself->name)) {
807 for list_each(outgoing_t, outgoing, outgoing_list) {
808 if(!strcmp(outgoing->node->name, name)) {
810 outgoing->timeout = 0;
816 outgoing_t *outgoing = xzalloc(sizeof(*outgoing));
817 node_t *n = lookup_node(name);
820 n->name = xstrdup(name);
824 list_insert_tail(outgoing_list, outgoing);
825 setup_outgoing_connection(outgoing, true);
829 /* Terminate any connections whose outgoing_t is to be deleted. */
831 for list_each(connection_t, c, connection_list) {
832 if(c->outgoing && c->outgoing->timeout == -1) {
834 logger(DEBUG_CONNECTIONS, LOG_INFO, "No more outgoing connection to %s", c->name);
835 terminate_connection(c, c->edge);
839 /* Delete outgoing_ts for which there is no ConnectTo. */
841 for list_each(outgoing_t, outgoing, outgoing_list)
842 if(outgoing->timeout == -1) {
843 list_delete_node(outgoing_list, node);