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(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));
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(IPV6_V6ONLY)
147 if(sa->sa.sa_family == AF_INET6) {
148 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
152 #warning IPV6_V6ONLY not defined
155 if(get_config_string(lookup_config(config_tree, "BindToInterface"), &iface)) {
156 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
159 memset(&ifr, 0, sizeof(ifr));
160 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
161 ifr.ifr_ifrn.ifrn_name[IFNAMSIZ - 1] = 0;
164 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr))) {
166 logger(LOG_ERR, "Can't bind to interface %s: %s", ifr.ifr_ifrn.ifrn_name, strerror(sockerrno));
171 logger(LOG_WARNING, "%s not supported on this platform", "BindToInterface");
175 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
177 addrstr = sockaddr2hostname(sa);
178 logger(LOG_ERR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
185 logger(LOG_ERR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
192 int setup_vpn_in_socket(const sockaddr_t *sa) {
197 nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
200 logger(LOG_ERR, "Creating UDP socket failed: %s", sockstrerror(sockerrno));
205 fcntl(nfd, F_SETFD, FD_CLOEXEC);
210 int flags = fcntl(nfd, F_GETFL);
212 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
214 logger(LOG_ERR, "System call `%s' failed: %s", "fcntl",
221 unsigned long arg = 1;
223 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
225 logger(LOG_ERR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
232 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
233 setsockopt(nfd, SOL_SOCKET, SO_BROADCAST, (void *)&option, sizeof(option));
235 if(udp_rcvbuf && setsockopt(nfd, SOL_SOCKET, SO_RCVBUF, (void *)&udp_rcvbuf, sizeof(udp_rcvbuf))) {
236 logger(LOG_WARNING, "Can't set UDP SO_RCVBUF to %i: %s", udp_rcvbuf, strerror(errno));
239 if(udp_sndbuf && setsockopt(nfd, SOL_SOCKET, SO_SNDBUF, (void *)&udp_sndbuf, sizeof(udp_sndbuf))) {
240 logger(LOG_WARNING, "Can't set UDP SO_SNDBUF to %i: %s", udp_sndbuf, strerror(errno));
243 #if defined(IPV6_V6ONLY)
245 if(sa->sa.sa_family == AF_INET6) {
246 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
251 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
252 #define IP_DONTFRAGMENT IP_DONTFRAG
255 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
257 if(myself->options & OPTION_PMTU_DISCOVERY) {
258 option = IP_PMTUDISC_DO;
259 setsockopt(nfd, IPPROTO_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
262 #elif defined(IP_DONTFRAGMENT)
264 if(myself->options & OPTION_PMTU_DISCOVERY) {
266 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
271 #if defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
273 if(myself->options & OPTION_PMTU_DISCOVERY) {
274 option = IPV6_PMTUDISC_DO;
275 setsockopt(nfd, IPPROTO_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
278 #elif defined(IPV6_DONTFRAG)
280 if(myself->options & OPTION_PMTU_DISCOVERY) {
282 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
287 if(!bind_to_interface(nfd)) {
292 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
294 addrstr = sockaddr2hostname(sa);
295 logger(LOG_ERR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
301 } /* int setup_vpn_in_socket */
303 void retry_outgoing(outgoing_t *outgoing) {
304 outgoing->timeout += 5;
306 if(outgoing->timeout < mintimeout) {
307 outgoing->timeout = mintimeout;
310 if(outgoing->timeout > maxtimeout) {
311 outgoing->timeout = maxtimeout;
314 if(outgoing->event) {
315 event_del(outgoing->event);
318 outgoing->event = new_event();
319 outgoing->event->handler = (event_handler_t) setup_outgoing_connection;
320 outgoing->event->time = now + outgoing->timeout;
321 outgoing->event->data = outgoing;
322 event_add(outgoing->event);
324 ifdebug(CONNECTIONS) logger(LOG_NOTICE,
325 "Trying to re-establish outgoing connection in %d seconds",
329 void finish_connecting(connection_t *c) {
330 ifdebug(CONNECTIONS) logger(LOG_INFO, "Connected to %s (%s)", c->name, c->hostname);
332 c->last_ping_time = now;
337 static void do_outgoing_pipe(connection_t *c, char *command) {
341 if(socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) {
342 logger(LOG_ERR, "Could not create socketpair: %s\n", strerror(errno));
349 ifdebug(CONNECTIONS) logger(LOG_DEBUG, "Using proxy %s", command);
360 // Other filedescriptors should be closed automatically by CLOEXEC
365 sockaddr2str(&c->address, &host, &port);
366 setenv("REMOTEADDRESS", host, true);
367 setenv("REMOTEPORT", port, true);
368 setenv("NODE", c->name, true);
369 setenv("NAME", myself->name, true);
372 setenv("NETNAME", netname, true);
375 int result = system(command);
378 logger(LOG_ERR, "Could not execute %s: %s\n", command, strerror(errno));
380 logger(LOG_ERR, "%s exited with non-zero status %d", command, result);
385 logger(LOG_ERR, "Proxy type exec not supported on this platform!");
390 static bool is_valid_host_port(const char *host, const char *port) {
391 for(const char *p = host; *p; p++)
392 if(!isalnum(*p) && *p != '-' && *p != '.') {
396 for(const char *p = port; *p; p++)
404 void do_outgoing_connection(connection_t *c) {
405 struct addrinfo *proxyai = NULL;
409 logger(LOG_ERR, "do_outgoing_connection() for %s called without c->outgoing", c->name);
415 if(!c->outgoing->ai) {
416 if(!c->outgoing->cfg) {
417 ifdebug(CONNECTIONS) logger(LOG_ERR, "Could not set up a meta connection to %s",
419 c->status.remove = true;
420 retry_outgoing(c->outgoing);
425 char *address, *port, *space;
427 get_config_string(c->outgoing->cfg, &address);
429 space = strchr(address, ' ');
432 port = xstrdup(space + 1);
435 if(!get_config_string(lookup_config(c->config_tree, "Port"), &port)) {
436 port = xstrdup("655");
440 c->outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
442 // If we cannot resolve the address, maybe we are using a proxy that can?
443 if(!c->outgoing->ai && proxytype != PROXY_NONE && is_valid_host_port(address, port)) {
444 memset(&c->address, 0, sizeof(c->address));
445 c->address.sa.sa_family = AF_UNKNOWN;
446 c->address.unknown.address = address;
447 c->address.unknown.port = port;
453 c->outgoing->aip = c->outgoing->ai;
454 c->outgoing->cfg = lookup_config_next(c->config_tree, c->outgoing->cfg);
456 if(!c->outgoing->ai && proxytype != PROXY_NONE) {
461 if(!c->outgoing->aip) {
462 if(c->outgoing->ai) {
463 freeaddrinfo(c->outgoing->ai);
466 c->outgoing->ai = NULL;
470 memcpy(&c->address, c->outgoing->aip->ai_addr, c->outgoing->aip->ai_addrlen);
471 c->outgoing->aip = c->outgoing->aip->ai_next;
479 c->hostname = sockaddr2hostname(&c->address);
481 ifdebug(CONNECTIONS) logger(LOG_INFO, "Trying to connect to %s (%s)", c->name,
485 c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
486 } else if(proxytype == PROXY_EXEC) {
487 c->status.proxy_passed = true;
488 do_outgoing_pipe(c, proxyhost);
490 proxyai = str2addrinfo(proxyhost, proxyport, SOCK_STREAM);
496 ifdebug(CONNECTIONS) logger(LOG_INFO, "Using proxy at %s port %s", proxyhost, proxyport);
497 c->socket = socket(proxyai->ai_family, SOCK_STREAM, IPPROTO_TCP);
500 if(c->socket == -1) {
501 ifdebug(CONNECTIONS) logger(LOG_ERR, "Creating socket for %s failed: %s", c->hostname, sockstrerror(sockerrno));
505 if(proxytype != PROXY_EXEC) {
510 fcntl(c->socket, F_SETFD, FD_CLOEXEC);
513 if(proxytype != PROXY_EXEC) {
514 #if defined(IPV6_V6ONLY)
517 if(c->address.sa.sa_family == AF_INET6) {
518 setsockopt(c->socket, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
523 bind_to_interface(c->socket);
527 for(int i = 0; i < listen_sockets; i++) {
528 if(listen_socket[i].sa.sa.sa_family == c->address.sa.sa_family) {
539 sockaddr_t sa = listen_socket[b].sa;
541 if(sa.sa.sa_family == AF_INET) {
543 } else if(sa.sa.sa_family == AF_INET6) {
544 sa.in6.sin6_port = 0;
547 if(bind(c->socket, &sa.sa, SALEN(sa.sa))) {
548 char *addrstr = sockaddr2hostname(&sa);
549 logger(LOG_ERR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
558 result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
559 } else if(proxytype == PROXY_EXEC) {
562 result = connect(c->socket, proxyai->ai_addr, proxyai->ai_addrlen);
563 freeaddrinfo(proxyai);
569 if(sockinprogress(sockerrno)) {
570 c->last_ping_time = now;
571 c->status.connecting = true;
575 closesocket(c->socket);
577 ifdebug(CONNECTIONS) logger(LOG_ERR, "%s: %s", c->hostname, sockstrerror(sockerrno));
582 finish_connecting(c);
587 void setup_outgoing_connection(outgoing_t *outgoing) {
591 outgoing->event = NULL;
593 n = lookup_node(outgoing->name);
597 ifdebug(CONNECTIONS) logger(LOG_INFO, "Already connected to %s", outgoing->name);
599 n->connection->outgoing = outgoing;
603 c = new_connection();
604 c->name = xstrdup(outgoing->name);
605 c->outcipher = myself->connection->outcipher;
606 c->outdigest = myself->connection->outdigest;
607 c->outmaclength = myself->connection->outmaclength;
608 c->outcompression = myself->connection->outcompression;
610 init_configuration(&c->config_tree);
612 if(!read_connection_config(c)) {
614 outgoing->timeout = maxtimeout;
615 retry_outgoing(outgoing);
619 outgoing->cfg = lookup_config(c->config_tree, "Address");
622 logger(LOG_ERR, "No address specified for %s", c->name);
624 outgoing->timeout = maxtimeout;
625 retry_outgoing(outgoing);
629 c->outgoing = outgoing;
630 c->last_ping_time = now;
634 do_outgoing_connection(c);
638 accept a new tcp connect and create a
641 bool handle_new_meta_connection(int sock) {
645 socklen_t len = sizeof(sa);
647 fd = accept(sock, &sa.sa, &len);
650 logger(LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
656 c = new_connection();
657 c->name = xstrdup("<unknown>");
658 c->outcipher = myself->connection->outcipher;
659 c->outdigest = myself->connection->outdigest;
660 c->outmaclength = myself->connection->outmaclength;
661 c->outcompression = myself->connection->outcompression;
664 c->hostname = sockaddr2hostname(&sa);
666 c->last_ping_time = now;
668 ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection from %s", c->hostname);
674 c->allow_request = ID;
680 static void free_outgoing(outgoing_t *outgoing) {
682 freeaddrinfo(outgoing->ai);
686 free(outgoing->name);
692 void try_outgoing_connections(void) {
693 static config_t *cfg = NULL;
695 outgoing_t *outgoing;
697 outgoing_list = list_alloc((list_action_t)free_outgoing);
699 for(cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
700 get_config_string(cfg, &name);
702 if(!check_id(name)) {
704 "Invalid name for outgoing connection in %s line %d",
705 cfg->file, cfg->line);
710 outgoing = xmalloc_and_zero(sizeof(*outgoing));
711 outgoing->name = name;
712 list_insert_tail(outgoing_list, outgoing);
713 setup_outgoing_connection(outgoing);