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 = 10;
47 listen_socket_t listen_socket[MAXSOCKETS];
52 list_t *outgoing_list = NULL;
56 static void configure_tcp(connection_t *c) {
60 int flags = fcntl(c->socket, F_GETFL);
62 if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0) {
63 logger(DEBUG_ALWAYS, LOG_ERR, "fcntl for %s fd %d: %s", c->hostname, c->socket, strerror(errno));
67 unsigned long arg = 1;
69 if(ioctlsocket(c->socket, FIONBIO, &arg) != 0) {
70 logger(DEBUG_ALWAYS, LOG_ERR, "ioctlsocket for %s fd %d: %s", c->hostname, c->socket, sockstrerror(sockerrno));
75 #if defined(TCP_NODELAY)
77 setsockopt(c->socket, IPPROTO_TCP, TCP_NODELAY, (void *)&option, sizeof(option));
80 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
81 option = IPTOS_LOWDELAY;
82 setsockopt(c->socket, IPPROTO_IP, IP_TOS, (void *)&option, sizeof(option));
85 #if defined(IPV6_TCLASS) && defined(IPTOS_LOWDELAY)
86 option = IPTOS_LOWDELAY;
87 setsockopt(c->socket, IPPROTO_IPV6, IPV6_TCLASS, (void *)&option, sizeof(option));
93 setsockopt(c->socket, SOL_SOCKET, SO_MARK, (void *)&fwmark, sizeof(fwmark));
99 static bool bind_to_interface(int sd) {
102 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
105 #endif /* defined(SOL_SOCKET) && defined(SO_BINDTODEVICE) */
107 if(!get_config_string(lookup_config(config_tree, "BindToInterface"), &iface)) {
111 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
112 memset(&ifr, 0, sizeof(ifr));
113 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
114 ifr.ifr_ifrn.ifrn_name[IFNAMSIZ - 1] = 0;
116 status = setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr));
119 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to interface %s: %s", iface,
120 sockstrerror(sockerrno));
124 #else /* if !defined(SOL_SOCKET) || !defined(SO_BINDTODEVICE) */
125 logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform", "BindToInterface");
131 static bool bind_to_address(connection_t *c) {
134 for(int i = 0; i < listen_sockets && listen_socket[i].bindto; i++) {
135 if(listen_socket[i].sa.sa.sa_family != c->address.sa.sa_family) {
150 sockaddr_t sa = listen_socket[s].sa;
152 if(sa.sa.sa_family == AF_INET) {
154 } else if(sa.sa.sa_family == AF_INET6) {
155 sa.in6.sin6_port = 0;
158 if(bind(c->socket, &sa.sa, SALEN(sa.sa))) {
159 logger(DEBUG_CONNECTIONS, LOG_WARNING, "Can't bind outgoing socket: %s", sockstrerror(sockerrno));
166 int setup_listen_socket(const sockaddr_t *sa) {
172 nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
175 logger(DEBUG_STATUS, LOG_ERR, "Creating metasocket failed: %s", sockstrerror(sockerrno));
180 fcntl(nfd, F_SETFD, FD_CLOEXEC);
183 /* Optimize TCP settings */
186 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
188 #if defined(IPV6_V6ONLY)
190 if(sa->sa.sa_family == AF_INET6) {
191 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
195 #warning IPV6_V6ONLY not defined
201 setsockopt(nfd, SOL_SOCKET, SO_MARK, (void *)&fwmark, sizeof(fwmark));
207 (lookup_config(config_tree, "BindToInterface"), &iface)) {
208 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
211 memset(&ifr, 0, sizeof(ifr));
212 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
213 ifr.ifr_ifrn.ifrn_name[IFNAMSIZ - 1] = 0;
215 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr))) {
217 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to interface %s: %s", iface,
218 sockstrerror(sockerrno));
223 logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform", "BindToInterface");
227 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
229 addrstr = sockaddr2hostname(sa);
230 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
237 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
244 int setup_vpn_in_socket(const sockaddr_t *sa) {
249 nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
252 logger(DEBUG_ALWAYS, LOG_ERR, "Creating UDP socket failed: %s", sockstrerror(sockerrno));
257 fcntl(nfd, F_SETFD, FD_CLOEXEC);
262 int flags = fcntl(nfd, F_GETFL);
264 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
266 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "fcntl",
273 unsigned long arg = 1;
275 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
277 logger(DEBUG_ALWAYS, LOG_ERR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
284 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
285 setsockopt(nfd, SOL_SOCKET, SO_BROADCAST, (void *)&option, sizeof(option));
287 if(udp_rcvbuf && setsockopt(nfd, SOL_SOCKET, SO_RCVBUF, (void *)&udp_rcvbuf, sizeof(udp_rcvbuf))) {
288 logger(DEBUG_ALWAYS, LOG_WARNING, "Can't set UDP SO_RCVBUF to %i: %s", udp_rcvbuf, sockstrerror(sockerrno));
291 if(udp_sndbuf && setsockopt(nfd, SOL_SOCKET, SO_SNDBUF, (void *)&udp_sndbuf, sizeof(udp_sndbuf))) {
292 logger(DEBUG_ALWAYS, LOG_WARNING, "Can't set UDP SO_SNDBUF to %i: %s", udp_sndbuf, sockstrerror(sockerrno));
295 #if defined(IPV6_V6ONLY)
297 if(sa->sa.sa_family == AF_INET6) {
298 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
303 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
304 #define IP_DONTFRAGMENT IP_DONTFRAG
307 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
309 if(myself->options & OPTION_PMTU_DISCOVERY) {
310 option = IP_PMTUDISC_DO;
311 setsockopt(nfd, IPPROTO_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
314 #elif defined(IP_DONTFRAGMENT)
316 if(myself->options & OPTION_PMTU_DISCOVERY) {
318 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
323 #if defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
325 if(myself->options & OPTION_PMTU_DISCOVERY) {
326 option = IPV6_PMTUDISC_DO;
327 setsockopt(nfd, IPPROTO_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
330 #elif defined(IPV6_DONTFRAG)
332 if(myself->options & OPTION_PMTU_DISCOVERY) {
334 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
342 setsockopt(nfd, SOL_SOCKET, SO_MARK, (void *)&fwmark, sizeof(fwmark));
347 if(!bind_to_interface(nfd)) {
352 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
354 addrstr = sockaddr2hostname(sa);
355 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
361 } /* int setup_vpn_in_socket */
363 static void retry_outgoing_handler(void *data) {
364 setup_outgoing_connection(data, true);
367 void retry_outgoing(outgoing_t *outgoing) {
368 outgoing->timeout += 5;
370 if(outgoing->timeout > maxtimeout) {
371 outgoing->timeout = maxtimeout;
374 timeout_add(&outgoing->ev, retry_outgoing_handler, outgoing, &(struct timeval) {
375 outgoing->timeout, rand() % 100000
378 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Trying to re-establish outgoing connection in %d seconds", outgoing->timeout);
381 void finish_connecting(connection_t *c) {
382 logger(DEBUG_CONNECTIONS, LOG_INFO, "Connected to %s (%s)", c->name, c->hostname);
384 c->last_ping_time = now.tv_sec;
385 c->status.connecting = false;
390 static void do_outgoing_pipe(connection_t *c, char *command) {
394 if(socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) {
395 logger(DEBUG_ALWAYS, LOG_ERR, "Could not create socketpair: %s", sockstrerror(sockerrno));
402 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Using proxy %s", command);
413 // Other filedescriptors should be closed automatically by CLOEXEC
418 sockaddr2str(&c->address, &host, &port);
419 setenv("REMOTEADDRESS", host, true);
420 setenv("REMOTEPORT", port, true);
421 setenv("NODE", c->name, true);
422 setenv("NAME", myself->name, true);
425 setenv("NETNAME", netname, true);
428 int result = system(command);
431 logger(DEBUG_ALWAYS, LOG_ERR, "Could not execute %s: %s", command, strerror(errno));
433 logger(DEBUG_ALWAYS, LOG_ERR, "%s exited with non-zero status %d", command, result);
438 logger(DEBUG_ALWAYS, LOG_ERR, "Proxy type exec not supported on this platform!");
443 static void handle_meta_write(connection_t *c) {
444 if(c->outbuf.len <= c->outbuf.offset) {
448 ssize_t outlen = send(c->socket, c->outbuf.data + c->outbuf.offset, c->outbuf.len - c->outbuf.offset, 0);
451 if(!sockerrno || sockerrno == EPIPE) {
452 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection closed by %s (%s)", c->name, c->hostname);
453 } else if(sockwouldblock(sockerrno)) {
454 logger(DEBUG_META, LOG_DEBUG, "Sending %d bytes to %s (%s) would block", c->outbuf.len - c->outbuf.offset, c->name, c->hostname);
457 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));
460 terminate_connection(c, c->edge);
464 buffer_read(&c->outbuf, outlen);
467 io_set(&c->io, IO_READ);
471 static void handle_meta_io(void *data, int flags) {
472 connection_t *c = data;
474 if(c->status.connecting) {
476 The event loop does not protect against spurious events. Verify that we are actually connected
477 by issuing an empty send() call.
479 Note that the behavior of send() on potentially unconnected sockets differ between platforms:
480 +------------+-----------+-------------+-----------+
481 | Event | POSIX | Linux | Windows |
482 +------------+-----------+-------------+-----------+
483 | Spurious | ENOTCONN | EWOULDBLOCK | ENOTCONN |
484 | Failed | ENOTCONN | (cause) | ENOTCONN |
485 | Successful | (success) | (success) | (success) |
486 +------------+-----------+-------------+-----------+
488 if(send(c->socket, NULL, 0, 0) != 0) {
489 if(sockwouldblock(sockerrno)) {
495 if(!socknotconn(sockerrno)) {
496 socket_error = sockerrno;
498 socklen_t len = sizeof(socket_error);
499 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&socket_error, &len);
503 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Error while connecting to %s (%s): %s", c->name, c->hostname, sockstrerror(socket_error));
504 terminate_connection(c, false);
510 c->status.connecting = false;
511 finish_connecting(c);
514 if(flags & IO_WRITE) {
515 handle_meta_write(c);
517 handle_meta_connection_data(c);
521 bool do_outgoing_connection(outgoing_t *outgoing) {
522 const sockaddr_t *sa;
523 struct addrinfo *proxyai = NULL;
527 sa = get_recent_address(outgoing->address_cache);
530 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not set up a meta connection to %s", outgoing->node->name);
531 retry_outgoing(outgoing);
535 connection_t *c = new_connection();
536 c->outgoing = outgoing;
537 memcpy(&c->address, sa, SALEN(sa->sa));
538 c->hostname = sockaddr2hostname(&c->address);
540 logger(DEBUG_CONNECTIONS, LOG_INFO, "Trying to connect to %s (%s)", outgoing->node->name, c->hostname);
543 c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
545 } else if(proxytype == PROXY_EXEC) {
546 do_outgoing_pipe(c, proxyhost);
548 proxyai = str2addrinfo(proxyhost, proxyport, SOCK_STREAM);
555 logger(DEBUG_CONNECTIONS, LOG_INFO, "Using proxy at %s port %s", proxyhost, proxyport);
556 c->socket = socket(proxyai->ai_family, SOCK_STREAM, IPPROTO_TCP);
560 if(c->socket == -1) {
561 logger(DEBUG_CONNECTIONS, LOG_ERR, "Creating socket for %s failed: %s", c->hostname, sockstrerror(sockerrno));
567 fcntl(c->socket, F_SETFD, FD_CLOEXEC);
570 if(proxytype != PROXY_EXEC) {
571 #if defined(IPV6_V6ONLY)
574 if(c->address.sa.sa_family == AF_INET6) {
575 setsockopt(c->socket, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
580 bind_to_interface(c->socket);
587 result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
588 } else if(proxytype == PROXY_EXEC) {
595 result = connect(c->socket, proxyai->ai_addr, proxyai->ai_addrlen);
596 freeaddrinfo(proxyai);
599 if(result == -1 && !sockinprogress(sockerrno)) {
600 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not connect to %s (%s): %s", outgoing->node->name, c->hostname, sockstrerror(sockerrno));
606 /* Now that there is a working socket, fill in the rest and register this connection. */
608 c->last_ping_time = time(NULL);
609 c->status.connecting = true;
610 c->name = xstrdup(outgoing->node->name);
611 #ifndef DISABLE_LEGACY
612 c->outcipher = myself->connection->outcipher;
613 c->outdigest = myself->connection->outdigest;
615 c->outmaclength = myself->connection->outmaclength;
616 c->outcompression = myself->connection->outcompression;
617 c->last_ping_time = now.tv_sec;
621 io_add(&c->io, handle_meta_io, c, c->socket, IO_READ | IO_WRITE);
626 void setup_outgoing_connection(outgoing_t *outgoing, bool verbose) {
628 timeout_del(&outgoing->ev);
630 node_t *n = outgoing->node;
633 logger(DEBUG_CONNECTIONS, LOG_INFO, "Already connected to %s", n->name);
635 if(!n->connection->outgoing) {
636 n->connection->outgoing = outgoing;
643 if(!outgoing->address_cache) {
644 outgoing->address_cache = open_address_cache(n);
647 do_outgoing_connection(outgoing);
651 list_delete(outgoing_list, outgoing);
655 accept a new tcp connect and create a
658 void handle_new_meta_connection(void *data, int flags) {
660 listen_socket_t *l = data;
664 socklen_t len = sizeof(sa);
666 fd = accept(l->tcp.fd, &sa.sa, &len);
669 logger(DEBUG_ALWAYS, LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
675 // Check if we get many connections from the same host
677 static sockaddr_t prev_sa;
679 if(!sockaddrcmp_noport(&sa, &prev_sa)) {
680 static int samehost_burst;
681 static int samehost_burst_time;
683 if(now.tv_sec - samehost_burst_time > samehost_burst) {
686 samehost_burst -= now.tv_sec - samehost_burst_time;
689 samehost_burst_time = now.tv_sec;
692 if(samehost_burst > max_connection_burst) {
698 memcpy(&prev_sa, &sa, sizeof(sa));
700 // Check if we get many connections from different hosts
702 static int connection_burst;
703 static int connection_burst_time;
705 if(now.tv_sec - connection_burst_time > connection_burst) {
706 connection_burst = 0;
708 connection_burst -= now.tv_sec - connection_burst_time;
711 connection_burst_time = now.tv_sec;
714 if(connection_burst >= max_connection_burst) {
715 connection_burst = max_connection_burst;
720 // Accept the new connection
722 c = new_connection();
723 c->name = xstrdup("<unknown>");
724 #ifndef DISABLE_LEGACY
725 c->outcipher = myself->connection->outcipher;
726 c->outdigest = myself->connection->outdigest;
728 c->outmaclength = myself->connection->outmaclength;
729 c->outcompression = myself->connection->outcompression;
732 c->hostname = sockaddr2hostname(&sa);
734 c->last_ping_time = now.tv_sec;
736 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection from %s", c->hostname);
738 io_add(&c->io, handle_meta_io, c, c->socket, IO_READ);
744 c->allow_request = ID;
749 accept a new UNIX socket connection
751 void handle_new_unix_connection(void *data, int flags) {
757 socklen_t len = sizeof(sa);
759 fd = accept(io->fd, &sa.sa, &len);
762 logger(DEBUG_ALWAYS, LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
768 c = new_connection();
769 c->name = xstrdup("<control>");
771 c->hostname = xstrdup("localhost port unix");
773 c->last_ping_time = now.tv_sec;
775 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection from %s", c->hostname);
777 io_add(&c->io, handle_meta_io, c, c->socket, IO_READ);
781 c->allow_request = ID;
785 static void free_outgoing(outgoing_t *outgoing) {
786 timeout_del(&outgoing->ev);
788 if(outgoing->address_cache) {
789 close_address_cache(outgoing->address_cache);
795 void try_outgoing_connections(void) {
796 /* If there is no outgoing list yet, create one. Otherwise, mark all outgoings as deleted. */
799 outgoing_list = list_alloc((list_action_t)free_outgoing);
801 for list_each(outgoing_t, outgoing, outgoing_list) {
802 outgoing->timeout = -1;
806 /* Make sure there is one outgoing_t in the list for each ConnectTo. */
808 for(config_t *cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
810 get_config_string(cfg, &name);
812 if(!check_id(name)) {
813 logger(DEBUG_ALWAYS, LOG_ERR,
814 "Invalid name for outgoing connection in %s line %d",
815 cfg->file, cfg->line);
820 if(!strcmp(name, myself->name)) {
827 for list_each(outgoing_t, outgoing, outgoing_list) {
828 if(!strcmp(outgoing->node->name, name)) {
830 outgoing->timeout = 0;
836 outgoing_t *outgoing = xzalloc(sizeof(*outgoing));
837 node_t *n = lookup_node(name);
841 n->name = xstrdup(name);
846 list_insert_tail(outgoing_list, outgoing);
847 setup_outgoing_connection(outgoing, true);
851 /* Terminate any connections whose outgoing_t is to be deleted. */
853 for list_each(connection_t, c, connection_list) {
854 if(c->outgoing && c->outgoing->timeout == -1) {
856 logger(DEBUG_CONNECTIONS, LOG_INFO, "No more outgoing connection to %s", c->name);
857 terminate_connection(c, c->edge);
861 /* Delete outgoing_ts for which there is no ConnectTo. */
863 for list_each(outgoing_t, outgoing, outgoing_list)
864 if(outgoing->timeout == -1) {
865 list_delete_node(outgoing_list, node);