2 net_socket.c -- Handle various kinds of sockets.
3 Copyright (C) 1998-2005 Ivo Timmermans,
4 2000-2015 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));
66 unsigned long arg = 1;
68 if(ioctlsocket(c->socket, FIONBIO, &arg) != 0) {
69 logger(LOG_ERR, "ioctlsocket for %s: %s", c->hostname, sockstrerror(sockerrno));
73 #if defined(SOL_TCP) && defined(TCP_NODELAY)
75 setsockopt(c->socket, SOL_TCP, TCP_NODELAY, (void *)&option, sizeof(option));
78 #if defined(SOL_IP) && defined(IP_TOS) && defined(IPTOS_LOWDELAY)
79 option = IPTOS_LOWDELAY;
80 setsockopt(c->socket, SOL_IP, IP_TOS, (void *)&option, sizeof(option));
83 #if defined(IPPROTO_IPV6) && defined(IPV6_TCLASS) && defined(IPTOS_LOWDELAY)
84 option = IPTOS_LOWDELAY;
85 setsockopt(c->socket, IPPROTO_IPV6, IPV6_TCLASS, (void *)&option, sizeof(option));
89 static bool bind_to_interface(int sd) {
92 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
95 #endif /* defined(SOL_SOCKET) && defined(SO_BINDTODEVICE) */
97 if(!get_config_string(lookup_config (config_tree, "BindToInterface"), &iface))
100 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
101 memset(&ifr, 0, sizeof(ifr));
102 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
103 ifr.ifr_ifrn.ifrn_name[IFNAMSIZ - 1] = 0;
106 status = setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr));
108 logger(LOG_ERR, "Can't bind to interface %s: %s", ifr.ifr_ifrn.ifrn_name, strerror(errno));
112 #else /* if !defined(SOL_SOCKET) || !defined(SO_BINDTODEVICE) */
113 logger(LOG_WARNING, "%s not supported on this platform", "BindToInterface");
119 int setup_listen_socket(const sockaddr_t *sa) {
125 nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
128 ifdebug(STATUS) logger(LOG_ERR, "Creating metasocket failed: %s", sockstrerror(sockerrno));
133 fcntl(nfd, F_SETFD, FD_CLOEXEC);
136 /* Optimize TCP settings */
139 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
141 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
142 if(sa->sa.sa_family == AF_INET6)
143 setsockopt(nfd, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
146 if(get_config_string(lookup_config(config_tree, "BindToInterface"), &iface)) {
147 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
150 memset(&ifr, 0, sizeof(ifr));
151 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
152 ifr.ifr_ifrn.ifrn_name[IFNAMSIZ - 1] = 0;
155 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr))) {
157 logger(LOG_ERR, "Can't bind to interface %s: %s", ifr.ifr_ifrn.ifrn_name, strerror(sockerrno));
162 logger(LOG_WARNING, "%s not supported on this platform", "BindToInterface");
166 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
168 addrstr = sockaddr2hostname(sa);
169 logger(LOG_ERR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
176 logger(LOG_ERR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
183 int setup_vpn_in_socket(const sockaddr_t *sa) {
188 nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
191 logger(LOG_ERR, "Creating UDP socket failed: %s", sockstrerror(sockerrno));
196 fcntl(nfd, F_SETFD, FD_CLOEXEC);
201 int flags = fcntl(nfd, F_GETFL);
203 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
205 logger(LOG_ERR, "System call `%s' failed: %s", "fcntl",
212 unsigned long arg = 1;
213 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
215 logger(LOG_ERR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
222 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
223 setsockopt(nfd, SOL_SOCKET, SO_BROADCAST, (void *)&option, sizeof(option));
225 if(udp_rcvbuf && setsockopt(nfd, SOL_SOCKET, SO_RCVBUF, (void *)&udp_rcvbuf, sizeof(udp_rcvbuf)))
226 logger(LOG_WARNING, "Can't set UDP SO_RCVBUF to %i: %s", udp_rcvbuf, strerror(errno));
228 if(udp_sndbuf && setsockopt(nfd, SOL_SOCKET, SO_SNDBUF, (void *)&udp_sndbuf, sizeof(udp_sndbuf)))
229 logger(LOG_WARNING, "Can't set UDP SO_SNDBUF to %i: %s", udp_sndbuf, strerror(errno));
231 #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
232 if(sa->sa.sa_family == AF_INET6)
233 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
236 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
237 #define IP_DONTFRAGMENT IP_DONTFRAG
240 #if defined(SOL_IP) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
241 if(myself->options & OPTION_PMTU_DISCOVERY) {
242 option = IP_PMTUDISC_DO;
243 setsockopt(nfd, SOL_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
245 #elif defined(IPPROTO_IP) && defined(IP_DONTFRAGMENT)
246 if(myself->options & OPTION_PMTU_DISCOVERY) {
248 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
252 #if defined(SOL_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
253 if(myself->options & OPTION_PMTU_DISCOVERY) {
254 option = IPV6_PMTUDISC_DO;
255 setsockopt(nfd, SOL_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
257 #elif defined(IPPROTO_IPV6) && defined(IPV6_DONTFRAG)
258 if(myself->options & OPTION_PMTU_DISCOVERY) {
260 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
264 if (!bind_to_interface(nfd)) {
269 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
271 addrstr = sockaddr2hostname(sa);
272 logger(LOG_ERR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
278 } /* int setup_vpn_in_socket */
280 void retry_outgoing(outgoing_t *outgoing) {
281 outgoing->timeout += 5;
283 if(outgoing->timeout < mintimeout)
284 outgoing->timeout = mintimeout;
286 if(outgoing->timeout > maxtimeout)
287 outgoing->timeout = maxtimeout;
290 event_del(outgoing->event);
291 outgoing->event = new_event();
292 outgoing->event->handler = (event_handler_t) setup_outgoing_connection;
293 outgoing->event->time = now + outgoing->timeout;
294 outgoing->event->data = outgoing;
295 event_add(outgoing->event);
297 ifdebug(CONNECTIONS) logger(LOG_NOTICE,
298 "Trying to re-establish outgoing connection in %d seconds",
302 void finish_connecting(connection_t *c) {
303 ifdebug(CONNECTIONS) logger(LOG_INFO, "Connected to %s (%s)", c->name, c->hostname);
305 c->last_ping_time = now;
310 static void do_outgoing_pipe(connection_t *c, char *command) {
314 if(socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) {
315 logger(LOG_ERR, "Could not create socketpair: %s\n", strerror(errno));
322 ifdebug(CONNECTIONS) logger(LOG_DEBUG, "Using proxy %s", command);
333 // Other filedescriptors should be closed automatically by CLOEXEC
338 sockaddr2str(&c->address, &host, &port);
339 setenv("REMOTEADDRESS", host, true);
340 setenv("REMOTEPORT", port, true);
341 setenv("NODE", c->name, true);
342 setenv("NAME", myself->name, true);
344 setenv("NETNAME", netname, true);
346 int result = system(command);
348 logger(LOG_ERR, "Could not execute %s: %s\n", command, strerror(errno));
350 logger(LOG_ERR, "%s exited with non-zero status %d", command, result);
353 logger(LOG_ERR, "Proxy type exec not supported on this platform!");
358 static bool is_valid_host_port(const char *host, const char *port) {
359 for(const char *p = host; *p; p++)
360 if(!isalnum(*p) && *p != '-' && *p != '.')
363 for(const char *p = port; *p; p++)
370 void do_outgoing_connection(connection_t *c) {
371 struct addrinfo *proxyai = NULL;
375 logger(LOG_ERR, "do_outgoing_connection() for %s called without c->outgoing", c->name);
380 if(!c->outgoing->ai) {
381 if(!c->outgoing->cfg) {
382 ifdebug(CONNECTIONS) logger(LOG_ERR, "Could not set up a meta connection to %s",
384 c->status.remove = true;
385 retry_outgoing(c->outgoing);
390 char *address, *port, *space;
392 get_config_string(c->outgoing->cfg, &address);
394 space = strchr(address, ' ');
396 port = xstrdup(space + 1);
399 if(!get_config_string(lookup_config(c->config_tree, "Port"), &port))
400 port = xstrdup("655");
403 c->outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
405 // If we cannot resolve the address, maybe we are using a proxy that can?
406 if(!c->outgoing->ai && proxytype != PROXY_NONE && is_valid_host_port(address, port)) {
407 memset(&c->address, 0, sizeof c->address);
408 c->address.sa.sa_family = AF_UNKNOWN;
409 c->address.unknown.address = address;
410 c->address.unknown.port = port;
416 c->outgoing->aip = c->outgoing->ai;
417 c->outgoing->cfg = lookup_config_next(c->config_tree, c->outgoing->cfg);
419 if(!c->outgoing->ai && proxytype != PROXY_NONE)
423 if(!c->outgoing->aip) {
425 freeaddrinfo(c->outgoing->ai);
426 c->outgoing->ai = NULL;
430 memcpy(&c->address, c->outgoing->aip->ai_addr, c->outgoing->aip->ai_addrlen);
431 c->outgoing->aip = c->outgoing->aip->ai_next;
437 c->hostname = sockaddr2hostname(&c->address);
439 ifdebug(CONNECTIONS) logger(LOG_INFO, "Trying to connect to %s (%s)", c->name,
443 c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
444 } else if(proxytype == PROXY_EXEC) {
445 do_outgoing_pipe(c, proxyhost);
447 proxyai = str2addrinfo(proxyhost, proxyport, SOCK_STREAM);
450 ifdebug(CONNECTIONS) logger(LOG_INFO, "Using proxy at %s port %s", proxyhost, proxyport);
451 c->socket = socket(proxyai->ai_family, SOCK_STREAM, IPPROTO_TCP);
454 if(c->socket == -1) {
455 ifdebug(CONNECTIONS) logger(LOG_ERR, "Creating socket for %s failed: %s", c->hostname, sockstrerror(sockerrno));
459 if(proxytype != PROXY_EXEC)
463 fcntl(c->socket, F_SETFD, FD_CLOEXEC);
466 if(proxytype != PROXY_EXEC) {
467 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
469 if(c->address.sa.sa_family == AF_INET6)
470 setsockopt(c->socket, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
473 bind_to_interface(c->socket);
479 result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
480 } else if(proxytype == PROXY_EXEC) {
483 result = connect(c->socket, proxyai->ai_addr, proxyai->ai_addrlen);
484 freeaddrinfo(proxyai);
490 if(sockinprogress(sockerrno)) {
491 c->last_ping_time = now;
492 c->status.connecting = true;
496 closesocket(c->socket);
498 ifdebug(CONNECTIONS) logger(LOG_ERR, "%s: %s", c->hostname, sockstrerror(sockerrno));
503 finish_connecting(c);
508 void setup_outgoing_connection(outgoing_t *outgoing) {
512 outgoing->event = NULL;
514 n = lookup_node(outgoing->name);
518 ifdebug(CONNECTIONS) logger(LOG_INFO, "Already connected to %s", outgoing->name);
520 n->connection->outgoing = outgoing;
524 c = new_connection();
525 c->name = xstrdup(outgoing->name);
526 c->outcipher = myself->connection->outcipher;
527 c->outdigest = myself->connection->outdigest;
528 c->outmaclength = myself->connection->outmaclength;
529 c->outcompression = myself->connection->outcompression;
531 init_configuration(&c->config_tree);
532 read_connection_config(c);
534 outgoing->cfg = lookup_config(c->config_tree, "Address");
537 logger(LOG_ERR, "No address specified for %s", c->name);
542 c->outgoing = outgoing;
543 c->last_ping_time = now;
547 do_outgoing_connection(c);
551 accept a new tcp connect and create a
554 bool handle_new_meta_connection(int sock) {
558 socklen_t len = sizeof(sa);
560 fd = accept(sock, &sa.sa, &len);
563 logger(LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
569 c = new_connection();
570 c->name = xstrdup("<unknown>");
571 c->outcipher = myself->connection->outcipher;
572 c->outdigest = myself->connection->outdigest;
573 c->outmaclength = myself->connection->outmaclength;
574 c->outcompression = myself->connection->outcompression;
577 c->hostname = sockaddr2hostname(&sa);
579 c->last_ping_time = now;
581 ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection from %s", c->hostname);
587 c->allow_request = ID;
593 static void free_outgoing(outgoing_t *outgoing) {
595 freeaddrinfo(outgoing->ai);
598 free(outgoing->name);
603 void try_outgoing_connections(void) {
604 static config_t *cfg = NULL;
606 outgoing_t *outgoing;
608 outgoing_list = list_alloc((list_action_t)free_outgoing);
610 for(cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
611 get_config_string(cfg, &name);
613 if(!check_id(name)) {
615 "Invalid name for outgoing connection in %s line %d",
616 cfg->file, cfg->line);
621 outgoing = xmalloc_and_zero(sizeof(*outgoing));
622 outgoing->name = name;
623 list_insert_tail(outgoing_list, outgoing);
624 setup_outgoing_connection(outgoing);