2 net_socket.c -- Handle various kinds of sockets.
3 Copyright (C) 1998-2005 Ivo Timmermans,
4 2000-2014 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"
36 /* Needed on Mac OS/X */
38 #define SOL_TCP IPPROTO_TCP
41 int addressfamily = AF_UNSPEC;
43 int seconds_till_retry = 5;
46 int max_connection_burst = 100;
48 listen_socket_t listen_socket[MAXSOCKETS];
50 list_t *outgoing_list = NULL;
54 static void configure_tcp(connection_t *c) {
58 int flags = fcntl(c->socket, F_GETFL);
60 if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0) {
61 logger(DEBUG_ALWAYS, LOG_ERR, "fcntl for %s: %s", c->hostname, strerror(errno));
64 unsigned long arg = 1;
66 if(ioctlsocket(c->socket, FIONBIO, &arg) != 0) {
67 logger(DEBUG_ALWAYS, LOG_ERR, "ioctlsocket for %s: %s", c->hostname, sockstrerror(sockerrno));
71 #if defined(SOL_TCP) && defined(TCP_NODELAY)
73 setsockopt(c->socket, SOL_TCP, TCP_NODELAY, (void *)&option, sizeof option);
76 #if defined(SOL_IP) && defined(IP_TOS) && defined(IPTOS_LOWDELAY)
77 option = IPTOS_LOWDELAY;
78 setsockopt(c->socket, SOL_IP, IP_TOS, (void *)&option, sizeof option);
82 static bool bind_to_interface(int sd) {
85 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
88 #endif /* defined(SOL_SOCKET) && defined(SO_BINDTODEVICE) */
90 if(!get_config_string (lookup_config (config_tree, "BindToInterface"), &iface))
93 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
94 memset(&ifr, 0, sizeof(ifr));
95 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
96 ifr.ifr_ifrn.ifrn_name[IFNAMSIZ - 1] = 0;
98 status = setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr));
100 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to interface %s: %s", iface,
104 #else /* if !defined(SOL_SOCKET) || !defined(SO_BINDTODEVICE) */
105 logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform", "BindToInterface");
111 static bool bind_to_address(connection_t *c) {
114 for(int i = 0; i < listen_sockets && listen_socket[i].bindto; i++) {
115 if(listen_socket[i].sa.sa.sa_family != c->address.sa.sa_family)
125 sockaddr_t sa = listen_socket[s].sa;
126 if(sa.sa.sa_family == AF_INET)
128 else if(sa.sa.sa_family == AF_INET6)
129 sa.in6.sin6_port = 0;
131 if(bind(c->socket, &sa.sa, SALEN(sa.sa))) {
132 logger(DEBUG_CONNECTIONS, LOG_WARNING, "Can't bind outgoing socket: %s", strerror(errno));
139 int setup_listen_socket(const sockaddr_t *sa) {
145 nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
148 logger(DEBUG_STATUS, LOG_ERR, "Creating metasocket failed: %s", sockstrerror(sockerrno));
153 fcntl(nfd, F_SETFD, FD_CLOEXEC);
156 /* Optimize TCP settings */
159 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof option);
161 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
162 if(sa->sa.sa_family == AF_INET6)
163 setsockopt(nfd, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
167 (lookup_config(config_tree, "BindToInterface"), &iface)) {
168 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
171 memset(&ifr, 0, sizeof ifr);
172 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
174 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof ifr)) {
176 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to interface %s: %s", iface,
177 strerror(sockerrno));
181 logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform", "BindToInterface");
185 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
187 addrstr = sockaddr2hostname(sa);
188 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
195 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
202 int setup_vpn_in_socket(const sockaddr_t *sa) {
207 nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
210 logger(DEBUG_ALWAYS, LOG_ERR, "Creating UDP socket failed: %s", sockstrerror(sockerrno));
215 fcntl(nfd, F_SETFD, FD_CLOEXEC);
220 int flags = fcntl(nfd, F_GETFL);
222 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
224 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "fcntl",
231 unsigned long arg = 1;
232 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
234 logger(DEBUG_ALWAYS, LOG_ERR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
241 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof option);
242 setsockopt(nfd, SOL_SOCKET, SO_BROADCAST, (void *)&option, sizeof option);
244 if(udp_rcvbuf && setsockopt(nfd, SOL_SOCKET, SO_RCVBUF, (void *)&udp_rcvbuf, sizeof(udp_rcvbuf)))
245 logger(DEBUG_ALWAYS, LOG_WARNING, "Can't set UDP SO_RCVBUF to %i: %s", udp_rcvbuf, strerror(errno));
247 if(udp_sndbuf && setsockopt(nfd, SOL_SOCKET, SO_SNDBUF, (void *)&udp_sndbuf, sizeof(udp_sndbuf)))
248 logger(DEBUG_ALWAYS, LOG_WARNING, "Can't set UDP SO_SNDBUF to %i: %s", udp_sndbuf, strerror(errno));
250 #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
251 if(sa->sa.sa_family == AF_INET6)
252 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
255 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
256 #define IP_DONTFRAGMENT IP_DONTFRAG
259 #if defined(SOL_IP) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
260 if(myself->options & OPTION_PMTU_DISCOVERY) {
261 option = IP_PMTUDISC_DO;
262 setsockopt(nfd, SOL_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
264 #elif defined(IPPROTO_IP) && defined(IP_DONTFRAGMENT)
265 if(myself->options & OPTION_PMTU_DISCOVERY) {
267 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
270 #warning No way to disable IPv4 fragmentation
273 #if defined(SOL_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
274 if(myself->options & OPTION_PMTU_DISCOVERY) {
275 option = IPV6_PMTUDISC_DO;
276 setsockopt(nfd, SOL_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
278 #elif defined(IPPROTO_IPV6) && defined(IPV6_DONTFRAG)
279 if(myself->options & OPTION_PMTU_DISCOVERY) {
281 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
284 #warning No way to disable IPv6 fragmentation
287 if (!bind_to_interface(nfd)) {
292 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
294 addrstr = sockaddr2hostname(sa);
295 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
301 } /* int setup_vpn_in_socket */
303 static void retry_outgoing_handler(void *data) {
304 setup_outgoing_connection(data);
307 void retry_outgoing(outgoing_t *outgoing) {
308 outgoing->timeout += 5;
310 if(outgoing->timeout > maxtimeout)
311 outgoing->timeout = maxtimeout;
313 timeout_add(&outgoing->ev, retry_outgoing_handler, outgoing, &(struct timeval){outgoing->timeout, rand() % 100000});
315 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Trying to re-establish outgoing connection in %d seconds", outgoing->timeout);
318 void finish_connecting(connection_t *c) {
319 logger(DEBUG_CONNECTIONS, LOG_INFO, "Connected to %s (%s)", c->name, c->hostname);
321 c->last_ping_time = now.tv_sec;
322 c->status.connecting = false;
327 static void do_outgoing_pipe(connection_t *c, char *command) {
331 if(socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) {
332 logger(DEBUG_ALWAYS, LOG_ERR, "Could not create socketpair: %s", strerror(errno));
339 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Using proxy %s", command);
350 // Other filedescriptors should be closed automatically by CLOEXEC
355 sockaddr2str(&c->address, &host, &port);
356 setenv("REMOTEADDRESS", host, true);
357 setenv("REMOTEPORT", port, true);
358 setenv("NODE", c->name, true);
359 setenv("NAME", myself->name, true);
361 int result = system(command);
363 logger(DEBUG_ALWAYS, LOG_ERR, "Could not execute %s: %s", command, strerror(errno));
365 logger(DEBUG_ALWAYS, LOG_ERR, "%s exited with non-zero status %d", command, result);
368 logger(DEBUG_ALWAYS, LOG_ERR, "Proxy type exec not supported on this platform!");
373 static void handle_meta_write(connection_t *c) {
374 if(c->outbuf.len <= c->outbuf.offset)
377 ssize_t outlen = send(c->socket, c->outbuf.data + c->outbuf.offset, c->outbuf.len - c->outbuf.offset, 0);
379 if(!errno || errno == EPIPE) {
380 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection closed by %s (%s)", c->name, c->hostname);
381 } else if(sockwouldblock(sockerrno)) {
382 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Sending %d bytes to %s (%s) would block", c->outbuf.len - c->outbuf.offset, c->name, c->hostname);
385 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));
388 terminate_connection(c, c->status.active);
392 buffer_read(&c->outbuf, outlen);
394 io_set(&c->io, IO_READ);
397 static void handle_meta_io(void *data, int flags) {
398 connection_t *c = data;
400 if(c->status.connecting) {
401 c->status.connecting = false;
404 socklen_t len = sizeof result;
405 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
408 finish_connecting(c);
410 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Error while connecting to %s (%s): %s", c->name, c->hostname, sockstrerror(result));
411 terminate_connection(c, false);
417 handle_meta_write(c);
419 handle_meta_connection_data(c);
422 bool do_outgoing_connection(outgoing_t *outgoing) {
423 char *address, *port, *space;
424 struct addrinfo *proxyai = NULL;
430 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not set up a meta connection to %s", outgoing->name);
431 retry_outgoing(outgoing);
435 get_config_string(outgoing->cfg, &address);
437 space = strchr(address, ' ');
439 port = xstrdup(space + 1);
442 if(!get_config_string(lookup_config(outgoing->config_tree, "Port"), &port))
443 port = xstrdup("655");
446 outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
450 outgoing->aip = outgoing->ai;
451 outgoing->cfg = lookup_config_next(outgoing->config_tree, outgoing->cfg);
456 freeaddrinfo(outgoing->ai);
461 connection_t *c = new_connection();
462 c->outgoing = outgoing;
464 memcpy(&c->address, outgoing->aip->ai_addr, outgoing->aip->ai_addrlen);
465 outgoing->aip = outgoing->aip->ai_next;
467 c->hostname = sockaddr2hostname(&c->address);
469 logger(DEBUG_CONNECTIONS, LOG_INFO, "Trying to connect to %s (%s)", outgoing->name, c->hostname);
472 c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
474 } else if(proxytype == PROXY_EXEC) {
475 do_outgoing_pipe(c, proxyhost);
477 proxyai = str2addrinfo(proxyhost, proxyport, SOCK_STREAM);
482 logger(DEBUG_CONNECTIONS, LOG_INFO, "Using proxy at %s port %s", proxyhost, proxyport);
483 c->socket = socket(proxyai->ai_family, SOCK_STREAM, IPPROTO_TCP);
487 if(c->socket == -1) {
488 logger(DEBUG_CONNECTIONS, LOG_ERR, "Creating socket for %s failed: %s", c->hostname, sockstrerror(sockerrno));
494 fcntl(c->socket, F_SETFD, FD_CLOEXEC);
497 if(proxytype != PROXY_EXEC) {
498 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
500 if(c->address.sa.sa_family == AF_INET6)
501 setsockopt(c->socket, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
504 bind_to_interface(c->socket);
511 result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
512 } else if(proxytype == PROXY_EXEC) {
515 result = connect(c->socket, proxyai->ai_addr, proxyai->ai_addrlen);
516 freeaddrinfo(proxyai);
519 if(result == -1 && !sockinprogress(sockerrno)) {
520 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not connect to %s (%s): %s", outgoing->name, c->hostname, sockstrerror(sockerrno));
526 /* Now that there is a working socket, fill in the rest and register this connection. */
528 c->status.connecting = true;
529 c->name = xstrdup(outgoing->name);
530 c->outcipher = myself->connection->outcipher;
531 c->outdigest = myself->connection->outdigest;
532 c->outmaclength = myself->connection->outmaclength;
533 c->outcompression = myself->connection->outcompression;
534 c->last_ping_time = now.tv_sec;
538 io_add(&c->io, handle_meta_io, c, c->socket, IO_READ|IO_WRITE);
543 // Find edges pointing to this node, and use them to build a list of unique, known addresses.
544 static struct addrinfo *get_known_addresses(node_t *n) {
545 struct addrinfo *ai = NULL;
547 for splay_each(edge_t, e, n->edge_tree) {
552 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
553 if(!sockaddrcmp(&e->reverse->address, (sockaddr_t *)aip->ai_addr)) {
561 struct addrinfo *nai = xzalloc(sizeof *nai);
565 ai->ai_family = e->reverse->address.sa.sa_family;
566 ai->ai_socktype = SOCK_STREAM;
567 ai->ai_protocol = IPPROTO_TCP;
568 ai->ai_addrlen = SALEN(e->reverse->address.sa);
569 ai->ai_addr = xmalloc(ai->ai_addrlen);
570 memcpy(ai->ai_addr, &e->reverse->address, ai->ai_addrlen);
576 void setup_outgoing_connection(outgoing_t *outgoing) {
577 timeout_del(&outgoing->ev);
579 node_t *n = lookup_node(outgoing->name);
581 if(n && n->connection) {
582 logger(DEBUG_CONNECTIONS, LOG_INFO, "Already connected to %s", outgoing->name);
584 n->connection->outgoing = outgoing;
588 init_configuration(&outgoing->config_tree);
589 read_host_config(outgoing->config_tree, outgoing->name);
590 outgoing->cfg = lookup_config(outgoing->config_tree, "Address");
594 outgoing->aip = outgoing->ai = get_known_addresses(n);
596 logger(DEBUG_ALWAYS, LOG_ERR, "No address known for %s", outgoing->name);
601 do_outgoing_connection(outgoing);
605 accept a new tcp connect and create a
608 void handle_new_meta_connection(void *data, int flags) {
609 listen_socket_t *l = data;
613 socklen_t len = sizeof sa;
615 fd = accept(l->tcp.fd, &sa.sa, &len);
618 logger(DEBUG_ALWAYS, LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
624 // Check if we get many connections from the same host
626 static sockaddr_t prev_sa;
627 static int tarpit = -1;
634 if(!sockaddrcmp_noport(&sa, &prev_sa)) {
635 static int samehost_burst;
636 static int samehost_burst_time;
638 if(now.tv_sec - samehost_burst_time > samehost_burst)
641 samehost_burst -= now.tv_sec - samehost_burst_time;
643 samehost_burst_time = now.tv_sec;
646 if(samehost_burst > max_connection_burst) {
652 memcpy(&prev_sa, &sa, sizeof sa);
654 // Check if we get many connections from different hosts
656 static int connection_burst;
657 static int connection_burst_time;
659 if(now.tv_sec - connection_burst_time > connection_burst)
660 connection_burst = 0;
662 connection_burst -= now.tv_sec - connection_burst_time;
664 connection_burst_time = now.tv_sec;
667 if(connection_burst >= max_connection_burst) {
668 connection_burst = max_connection_burst;
673 // Accept the new connection
675 c = new_connection();
676 c->name = xstrdup("<unknown>");
677 c->outcipher = myself->connection->outcipher;
678 c->outdigest = myself->connection->outdigest;
679 c->outmaclength = myself->connection->outmaclength;
680 c->outcompression = myself->connection->outcompression;
683 c->hostname = sockaddr2hostname(&sa);
685 c->last_ping_time = now.tv_sec;
687 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection from %s", c->hostname);
689 io_add(&c->io, handle_meta_io, c, c->socket, IO_READ);
695 c->allow_request = ID;
699 static void free_outgoing(outgoing_t *outgoing) {
700 timeout_del(&outgoing->ev);
703 freeaddrinfo(outgoing->ai);
705 if(outgoing->config_tree)
706 exit_configuration(&outgoing->config_tree);
709 free(outgoing->name);
714 void try_outgoing_connections(void) {
715 /* If there is no outgoing list yet, create one. Otherwise, mark all outgoings as deleted. */
718 outgoing_list = list_alloc((list_action_t)free_outgoing);
720 for list_each(outgoing_t, outgoing, outgoing_list)
721 outgoing->timeout = -1;
724 /* Make sure there is one outgoing_t in the list for each ConnectTo. */
726 for(config_t *cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
728 get_config_string(cfg, &name);
730 if(!check_id(name)) {
731 logger(DEBUG_ALWAYS, LOG_ERR,
732 "Invalid name for outgoing connection in %s line %d",
733 cfg->file, cfg->line);
740 for list_each(outgoing_t, outgoing, outgoing_list) {
741 if(!strcmp(outgoing->name, name)) {
743 outgoing->timeout = 0;
749 outgoing_t *outgoing = xzalloc(sizeof *outgoing);
750 outgoing->name = name;
751 list_insert_tail(outgoing_list, outgoing);
752 setup_outgoing_connection(outgoing);
756 /* Terminate any connections whose outgoing_t is to be deleted. */
758 for list_each(connection_t, c, connection_list) {
759 if(c->outgoing && c->outgoing->timeout == -1) {
761 logger(DEBUG_CONNECTIONS, LOG_INFO, "No more outgoing connection to %s", c->name);
762 terminate_connection(c, c->status.active);
766 /* Delete outgoing_ts for which there is no ConnectTo. */
768 for list_each(outgoing_t, outgoing, outgoing_list)
769 if(outgoing->timeout == -1)
770 list_delete_node(outgoing_list, node);