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.
27 #include "connection.h"
38 /* Needed on Mac OS/X */
40 #define SOL_TCP IPPROTO_TCP
43 int addressfamily = AF_UNSPEC;
46 int seconds_till_retry = 5;
50 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(LOG_ERR, "fcntl for %s: %s", c->hostname, strerror(errno));
67 unsigned long arg = 1;
69 if(ioctlsocket(c->socket, FIONBIO, &arg) != 0) {
70 logger(LOG_ERR, "ioctlsocket for %s: %s", c->hostname, sockstrerror(sockerrno));
75 #if defined(SOL_TCP) && defined(TCP_NODELAY)
77 setsockopt(c->socket, SOL_TCP, TCP_NODELAY, (void *)&option, sizeof(option));
80 #if defined(SOL_IP) && defined(IP_TOS) && defined(IPTOS_LOWDELAY)
81 option = IPTOS_LOWDELAY;
82 setsockopt(c->socket, SOL_IP, IP_TOS, (void *)&option, sizeof(option));
85 #if defined(IPPROTO_IPV6) && defined(IPV6_TCLASS) && defined(IPTOS_LOWDELAY)
86 option = IPTOS_LOWDELAY;
87 setsockopt(c->socket, IPPROTO_IPV6, IPV6_TCLASS, (void *)&option, sizeof(option));
91 static bool bind_to_interface(int sd) {
94 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
97 #endif /* defined(SOL_SOCKET) && defined(SO_BINDTODEVICE) */
99 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;
109 status = setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr));
112 logger(LOG_ERR, "Can't bind to interface %s: %s", ifr.ifr_ifrn.ifrn_name, strerror(errno));
116 #else /* if !defined(SOL_SOCKET) || !defined(SO_BINDTODEVICE) */
117 logger(LOG_WARNING, "%s not supported on this platform", "BindToInterface");
123 int setup_listen_socket(const sockaddr_t *sa) {
129 nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
132 ifdebug(STATUS) logger(LOG_ERR, "Creating metasocket failed: %s", sockstrerror(sockerrno));
137 fcntl(nfd, F_SETFD, FD_CLOEXEC);
140 /* Optimize TCP settings */
143 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
145 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
147 if(sa->sa.sa_family == AF_INET6) {
148 setsockopt(nfd, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
153 if(get_config_string(lookup_config(config_tree, "BindToInterface"), &iface)) {
154 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
157 memset(&ifr, 0, sizeof(ifr));
158 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
159 ifr.ifr_ifrn.ifrn_name[IFNAMSIZ - 1] = 0;
162 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr))) {
164 logger(LOG_ERR, "Can't bind to interface %s: %s", ifr.ifr_ifrn.ifrn_name, strerror(sockerrno));
169 logger(LOG_WARNING, "%s not supported on this platform", "BindToInterface");
173 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
175 addrstr = sockaddr2hostname(sa);
176 logger(LOG_ERR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
183 logger(LOG_ERR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
190 int setup_vpn_in_socket(const sockaddr_t *sa) {
195 nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
198 logger(LOG_ERR, "Creating UDP socket failed: %s", sockstrerror(sockerrno));
203 fcntl(nfd, F_SETFD, FD_CLOEXEC);
208 int flags = fcntl(nfd, F_GETFL);
210 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
212 logger(LOG_ERR, "System call `%s' failed: %s", "fcntl",
219 unsigned long arg = 1;
221 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
223 logger(LOG_ERR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
230 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
231 setsockopt(nfd, SOL_SOCKET, SO_BROADCAST, (void *)&option, sizeof(option));
233 if(udp_rcvbuf && setsockopt(nfd, SOL_SOCKET, SO_RCVBUF, (void *)&udp_rcvbuf, sizeof(udp_rcvbuf))) {
234 logger(LOG_WARNING, "Can't set UDP SO_RCVBUF to %i: %s", udp_rcvbuf, strerror(errno));
237 if(udp_sndbuf && setsockopt(nfd, SOL_SOCKET, SO_SNDBUF, (void *)&udp_sndbuf, sizeof(udp_sndbuf))) {
238 logger(LOG_WARNING, "Can't set UDP SO_SNDBUF to %i: %s", udp_sndbuf, strerror(errno));
241 #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
243 if(sa->sa.sa_family == AF_INET6) {
244 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
249 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
250 #define IP_DONTFRAGMENT IP_DONTFRAG
253 #if defined(SOL_IP) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
255 if(myself->options & OPTION_PMTU_DISCOVERY) {
256 option = IP_PMTUDISC_DO;
257 setsockopt(nfd, SOL_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
260 #elif defined(IPPROTO_IP) && defined(IP_DONTFRAGMENT)
262 if(myself->options & OPTION_PMTU_DISCOVERY) {
264 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
269 #if defined(SOL_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
271 if(myself->options & OPTION_PMTU_DISCOVERY) {
272 option = IPV6_PMTUDISC_DO;
273 setsockopt(nfd, SOL_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
276 #elif defined(IPPROTO_IPV6) && defined(IPV6_DONTFRAG)
278 if(myself->options & OPTION_PMTU_DISCOVERY) {
280 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
285 if(!bind_to_interface(nfd)) {
290 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
292 addrstr = sockaddr2hostname(sa);
293 logger(LOG_ERR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
299 } /* int setup_vpn_in_socket */
301 void retry_outgoing(outgoing_t *outgoing) {
302 outgoing->timeout += 5;
304 if(outgoing->timeout < mintimeout) {
305 outgoing->timeout = mintimeout;
308 if(outgoing->timeout > maxtimeout) {
309 outgoing->timeout = maxtimeout;
312 if(outgoing->event) {
313 event_del(outgoing->event);
316 outgoing->event = new_event();
317 outgoing->event->handler = (event_handler_t) setup_outgoing_connection;
318 outgoing->event->time = now + outgoing->timeout;
319 outgoing->event->data = outgoing;
320 event_add(outgoing->event);
322 ifdebug(CONNECTIONS) logger(LOG_NOTICE,
323 "Trying to re-establish outgoing connection in %d seconds",
327 void finish_connecting(connection_t *c) {
328 ifdebug(CONNECTIONS) logger(LOG_INFO, "Connected to %s (%s)", c->name, c->hostname);
330 c->last_ping_time = now;
335 static void do_outgoing_pipe(connection_t *c, char *command) {
339 if(socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) {
340 logger(LOG_ERR, "Could not create socketpair: %s\n", strerror(errno));
347 ifdebug(CONNECTIONS) logger(LOG_DEBUG, "Using proxy %s", command);
358 // Other filedescriptors should be closed automatically by CLOEXEC
363 sockaddr2str(&c->address, &host, &port);
364 setenv("REMOTEADDRESS", host, true);
365 setenv("REMOTEPORT", port, true);
366 setenv("NODE", c->name, true);
367 setenv("NAME", myself->name, true);
370 setenv("NETNAME", netname, true);
373 int result = system(command);
376 logger(LOG_ERR, "Could not execute %s: %s\n", command, strerror(errno));
378 logger(LOG_ERR, "%s exited with non-zero status %d", command, result);
383 logger(LOG_ERR, "Proxy type exec not supported on this platform!");
388 static bool is_valid_host_port(const char *host, const char *port) {
389 for(const char *p = host; *p; p++)
390 if(!isalnum(*p) && *p != '-' && *p != '.') {
394 for(const char *p = port; *p; p++)
402 void do_outgoing_connection(connection_t *c) {
403 struct addrinfo *proxyai = NULL;
407 logger(LOG_ERR, "do_outgoing_connection() for %s called without c->outgoing", c->name);
413 if(!c->outgoing->ai) {
414 if(!c->outgoing->cfg) {
415 ifdebug(CONNECTIONS) logger(LOG_ERR, "Could not set up a meta connection to %s",
417 c->status.remove = true;
418 retry_outgoing(c->outgoing);
423 char *address, *port, *space;
425 get_config_string(c->outgoing->cfg, &address);
427 space = strchr(address, ' ');
430 port = xstrdup(space + 1);
433 if(!get_config_string(lookup_config(c->config_tree, "Port"), &port)) {
434 port = xstrdup("655");
438 c->outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
440 // If we cannot resolve the address, maybe we are using a proxy that can?
441 if(!c->outgoing->ai && proxytype != PROXY_NONE && is_valid_host_port(address, port)) {
442 memset(&c->address, 0, sizeof(c->address));
443 c->address.sa.sa_family = AF_UNKNOWN;
444 c->address.unknown.address = address;
445 c->address.unknown.port = port;
451 c->outgoing->aip = c->outgoing->ai;
452 c->outgoing->cfg = lookup_config_next(c->config_tree, c->outgoing->cfg);
454 if(!c->outgoing->ai && proxytype != PROXY_NONE) {
459 if(!c->outgoing->aip) {
460 if(c->outgoing->ai) {
461 freeaddrinfo(c->outgoing->ai);
464 c->outgoing->ai = NULL;
468 memcpy(&c->address, c->outgoing->aip->ai_addr, c->outgoing->aip->ai_addrlen);
469 c->outgoing->aip = c->outgoing->aip->ai_next;
477 c->hostname = sockaddr2hostname(&c->address);
479 ifdebug(CONNECTIONS) logger(LOG_INFO, "Trying to connect to %s (%s)", c->name,
483 c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
484 } else if(proxytype == PROXY_EXEC) {
485 c->status.proxy_passed = true;
486 do_outgoing_pipe(c, proxyhost);
488 proxyai = str2addrinfo(proxyhost, proxyport, SOCK_STREAM);
494 ifdebug(CONNECTIONS) logger(LOG_INFO, "Using proxy at %s port %s", proxyhost, proxyport);
495 c->socket = socket(proxyai->ai_family, SOCK_STREAM, IPPROTO_TCP);
498 if(c->socket == -1) {
499 ifdebug(CONNECTIONS) logger(LOG_ERR, "Creating socket for %s failed: %s", c->hostname, sockstrerror(sockerrno));
503 if(proxytype != PROXY_EXEC) {
508 fcntl(c->socket, F_SETFD, FD_CLOEXEC);
511 if(proxytype != PROXY_EXEC) {
512 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
515 if(c->address.sa.sa_family == AF_INET6) {
516 setsockopt(c->socket, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
521 bind_to_interface(c->socket);
525 for(int i = 0; i < listen_sockets; i++) {
526 if(listen_socket[i].sa.sa.sa_family == c->address.sa.sa_family) {
537 sockaddr_t sa = listen_socket[b].sa;
539 if(sa.sa.sa_family == AF_INET) {
541 } else if(sa.sa.sa_family == AF_INET6) {
542 sa.in6.sin6_port = 0;
545 if(bind(c->socket, &sa.sa, SALEN(sa.sa))) {
546 char *addrstr = sockaddr2hostname(&sa);
547 logger(LOG_ERR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
556 result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
557 } else if(proxytype == PROXY_EXEC) {
560 result = connect(c->socket, proxyai->ai_addr, proxyai->ai_addrlen);
561 freeaddrinfo(proxyai);
567 if(sockinprogress(sockerrno)) {
568 c->last_ping_time = now;
569 c->status.connecting = true;
573 closesocket(c->socket);
575 ifdebug(CONNECTIONS) logger(LOG_ERR, "%s: %s", c->hostname, sockstrerror(sockerrno));
580 finish_connecting(c);
585 void setup_outgoing_connection(outgoing_t *outgoing) {
589 outgoing->event = NULL;
591 n = lookup_node(outgoing->name);
595 ifdebug(CONNECTIONS) logger(LOG_INFO, "Already connected to %s", outgoing->name);
597 n->connection->outgoing = outgoing;
601 c = new_connection();
602 c->name = xstrdup(outgoing->name);
603 c->outcipher = myself->connection->outcipher;
604 c->outdigest = myself->connection->outdigest;
605 c->outmaclength = myself->connection->outmaclength;
606 c->outcompression = myself->connection->outcompression;
608 init_configuration(&c->config_tree);
610 if(!read_connection_config(c)) {
612 outgoing->timeout = maxtimeout;
613 retry_outgoing(outgoing);
617 outgoing->cfg = lookup_config(c->config_tree, "Address");
620 logger(LOG_ERR, "No address specified for %s", c->name);
622 outgoing->timeout = maxtimeout;
623 retry_outgoing(outgoing);
627 c->outgoing = outgoing;
628 c->last_ping_time = now;
632 do_outgoing_connection(c);
636 accept a new tcp connect and create a
639 bool handle_new_meta_connection(int sock) {
643 socklen_t len = sizeof(sa);
645 fd = accept(sock, &sa.sa, &len);
648 logger(LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
654 c = new_connection();
655 c->name = xstrdup("<unknown>");
656 c->outcipher = myself->connection->outcipher;
657 c->outdigest = myself->connection->outdigest;
658 c->outmaclength = myself->connection->outmaclength;
659 c->outcompression = myself->connection->outcompression;
662 c->hostname = sockaddr2hostname(&sa);
664 c->last_ping_time = now;
666 ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection from %s", c->hostname);
672 c->allow_request = ID;
678 static void free_outgoing(outgoing_t *outgoing) {
680 freeaddrinfo(outgoing->ai);
684 free(outgoing->name);
690 void try_outgoing_connections(void) {
691 static config_t *cfg = NULL;
693 outgoing_t *outgoing;
695 outgoing_list = list_alloc((list_action_t)free_outgoing);
697 for(cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
698 get_config_string(cfg, &name);
700 if(!check_id(name)) {
702 "Invalid name for outgoing connection in %s line %d",
703 cfg->file, cfg->line);
708 outgoing = xmalloc_and_zero(sizeof(*outgoing));
709 outgoing->name = name;
710 list_insert_tail(outgoing_list, outgoing);
711 setup_outgoing_connection(outgoing);