2 net_socket.c -- Handle various kinds of sockets.
3 Copyright (C) 1998-2005 Ivo Timmermans,
4 2000-2010 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 "splay_tree.h"
27 #include "connection.h"
38 /* Needed on Mac OS/X */
40 #define SOL_TCP IPPROTO_TCP
43 int addressfamily = AF_UNSPEC;
45 int seconds_till_retry = 5;
49 listen_socket_t listen_socket[MAXSOCKETS];
51 list_t *outgoing_list = NULL;
55 static void configure_tcp(connection_t *c) {
59 int flags = fcntl(c->socket, F_GETFL);
61 if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0) {
62 logger(LOG_ERR, "fcntl for %s: %s", c->hostname, strerror(errno));
65 unsigned long arg = 1;
67 if(ioctlsocket(c->socket, FIONBIO, &arg) != 0) {
68 logger(LOG_ERR, "ioctlsocket for %s: %d", c->hostname, sockstrerror(sockerrno));
72 #if defined(SOL_TCP) && defined(TCP_NODELAY)
74 setsockopt(c->socket, SOL_TCP, TCP_NODELAY, (void *)&option, sizeof option);
77 #if defined(SOL_IP) && defined(IP_TOS) && defined(IPTOS_LOWDELAY)
78 option = IPTOS_LOWDELAY;
79 setsockopt(c->socket, SOL_IP, IP_TOS, (void *)&option, sizeof option);
83 static bool bind_to_interface(int sd) {
86 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
89 #endif /* defined(SOL_SOCKET) && defined(SO_BINDTODEVICE) */
91 if(!get_config_string (lookup_config (config_tree, "BindToInterface"), &iface))
94 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
95 memset(&ifr, 0, sizeof(ifr));
96 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
97 ifr.ifr_ifrn.ifrn_name[IFNAMSIZ - 1] = 0;
99 status = setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr));
101 logger(LOG_ERR, "Can't bind to interface %s: %s", iface,
105 #else /* if !defined(SOL_SOCKET) || !defined(SO_BINDTODEVICE) */
106 logger(LOG_WARNING, "%s not supported on this platform", "BindToInterface");
112 static bool bind_to_address(connection_t *c) {
114 struct addrinfo *ai_list;
115 struct addrinfo *ai_ptr;
116 struct addrinfo ai_hints;
120 assert(c->socket >= 0);
123 if(!get_config_string(lookup_config(config_tree, "BindToAddress"),
127 assert(node != NULL);
129 memset(&ai_hints, 0, sizeof(ai_hints));
130 ai_hints.ai_family = c->address.sa.sa_family;
131 /* We're called from `do_outgoing_connection' only. */
132 ai_hints.ai_socktype = SOCK_STREAM;
133 ai_hints.ai_protocol = IPPROTO_TCP;
137 status = getaddrinfo(node, /* service = */ NULL,
138 &ai_hints, &ai_list);
141 logger(LOG_WARNING, "Error looking up %s port %s: %s",
142 node, "any", gai_strerror(status));
145 assert(ai_list != NULL);
148 for(ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) {
149 status = bind(c->socket,
150 ai_list->ai_addr, ai_list->ai_addrlen);
157 logger(LOG_ERR, "Can't bind to %s/tcp: %s", node, sockstrerror(sockerrno));
158 } else ifdebug(CONNECTIONS) {
159 logger(LOG_DEBUG, "Successfully bound outgoing "
160 "TCP socket to %s", node);
164 freeaddrinfo(ai_list);
166 return status ? false : true;
169 int setup_listen_socket(const sockaddr_t *sa) {
175 nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
178 ifdebug(STATUS) logger(LOG_ERR, "Creating metasocket failed: %s", sockstrerror(sockerrno));
182 /* Optimize TCP settings */
185 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof option);
187 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
188 if(sa->sa.sa_family == AF_INET6)
189 setsockopt(nfd, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
193 (lookup_config(config_tree, "BindToInterface"), &iface)) {
194 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
197 memset(&ifr, 0, sizeof ifr);
198 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
200 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof ifr)) {
202 logger(LOG_ERR, "Can't bind to interface %s: %s", iface,
203 strerror(sockerrno));
207 logger(LOG_WARNING, "%s not supported on this platform", "BindToInterface");
211 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
213 addrstr = sockaddr2hostname(sa);
214 logger(LOG_ERR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
221 logger(LOG_ERR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
228 int setup_vpn_in_socket(const sockaddr_t *sa) {
233 nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
236 logger(LOG_ERR, "Creating UDP socket failed: %s", sockstrerror(sockerrno));
241 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof option);
243 if(udp_rcvbuf && setsockopt(nfd, SOL_SOCKET, SO_RCVBUF, (void *)&udp_rcvbuf, sizeof(udp_rcvbuf)))
244 logger(LOG_WARNING, "Can't set UDP SO_RCVBUF to %i: %s", udp_rcvbuf, strerror(errno));
246 if(udp_sndbuf && setsockopt(nfd, SOL_SOCKET, SO_SNDBUF, (void *)&udp_sndbuf, sizeof(udp_sndbuf)))
247 logger(LOG_WARNING, "Can't set UDP SO_SNDBUF to %i: %s", udp_sndbuf, strerror(errno));
249 #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
250 if(sa->sa.sa_family == AF_INET6)
251 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
254 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
255 #define IP_DONTFRAGMENT IP_DONTFRAG
258 #if defined(SOL_IP) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
259 if(myself->options & OPTION_PMTU_DISCOVERY) {
260 option = IP_PMTUDISC_DO;
261 setsockopt(nfd, SOL_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
263 #elif defined(IPPROTO_IP) && defined(IP_DONTFRAGMENT)
264 if(myself->options & OPTION_PMTU_DISCOVERY) {
266 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
269 #warning No way to disable IPv4 fragmentation
272 #if defined(SOL_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
273 if(myself->options & OPTION_PMTU_DISCOVERY) {
274 option = IPV6_PMTUDISC_DO;
275 setsockopt(nfd, SOL_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
277 #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));
283 #warning No way to disable IPv6 fragmentation
286 if (!bind_to_interface(nfd)) {
291 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
293 addrstr = sockaddr2hostname(sa);
294 logger(LOG_ERR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
300 } /* int setup_vpn_in_socket */
302 static void retry_outgoing_handler(int fd, short events, void *data) {
303 setup_outgoing_connection(data);
306 void retry_outgoing(outgoing_t *outgoing) {
307 outgoing->timeout += 5;
309 if(outgoing->timeout > maxtimeout)
310 outgoing->timeout = maxtimeout;
312 timeout_set(&outgoing->ev, retry_outgoing_handler, outgoing);
313 event_add(&outgoing->ev, &(struct timeval){outgoing->timeout, 0});
315 ifdebug(CONNECTIONS) logger(LOG_NOTICE,
316 "Trying to re-establish outgoing connection in %d seconds",
320 void finish_connecting(connection_t *c) {
321 ifdebug(CONNECTIONS) logger(LOG_INFO, "Connected to %s (%s)", c->name, c->hostname);
325 c->last_ping_time = time(NULL);
326 c->status.connecting = false;
331 void do_outgoing_connection(connection_t *c) {
332 char *address, *port, *space;
336 logger(LOG_ERR, "do_outgoing_connection() for %s called without c->outgoing", c->name);
341 if(!c->outgoing->ai) {
342 if(!c->outgoing->cfg) {
343 ifdebug(CONNECTIONS) logger(LOG_ERR, "Could not set up a meta connection to %s",
345 retry_outgoing(c->outgoing);
351 get_config_string(c->outgoing->cfg, &address);
353 space = strchr(address, ' ');
355 port = xstrdup(space + 1);
358 if(!get_config_string(lookup_config(c->config_tree, "Port"), &port))
359 port = xstrdup("655");
362 c->outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
366 c->outgoing->aip = c->outgoing->ai;
367 c->outgoing->cfg = lookup_config_next(c->config_tree, c->outgoing->cfg);
370 if(!c->outgoing->aip) {
372 freeaddrinfo(c->outgoing->ai);
373 c->outgoing->ai = NULL;
377 memcpy(&c->address, c->outgoing->aip->ai_addr, c->outgoing->aip->ai_addrlen);
378 c->outgoing->aip = c->outgoing->aip->ai_next;
383 c->hostname = sockaddr2hostname(&c->address);
385 ifdebug(CONNECTIONS) logger(LOG_INFO, "Trying to connect to %s (%s)", c->name,
388 c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
390 if(c->socket == -1) {
391 ifdebug(CONNECTIONS) logger(LOG_ERR, "Creating socket for %s failed: %s", c->hostname, sockstrerror(sockerrno));
395 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
397 if(c->address.sa.sa_family == AF_INET6)
398 setsockopt(c->socket, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
401 bind_to_interface(c->socket);
404 /* Optimize TCP settings */
410 result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
413 if(sockinprogress(sockerrno)) {
414 c->status.connecting = true;
418 closesocket(c->socket);
420 ifdebug(CONNECTIONS) logger(LOG_ERR, "%s: %s", c->hostname, sockstrerror(sockerrno));
425 finish_connecting(c);
430 void handle_meta_read(struct bufferevent *event, void *data) {
431 logger(LOG_ERR, "handle_meta_read() called");
435 void handle_meta_write(struct bufferevent *event, void *data) {
436 ifdebug(META) logger(LOG_DEBUG, "handle_meta_write() called");
439 void handle_meta_connection_error(struct bufferevent *event, short what, void *data) {
440 connection_t *c = data;
441 logger(LOG_ERR, "handle_meta_connection_error() called: %d: %s", what, strerror(errno));
442 terminate_connection(c, c->status.active);
445 void setup_outgoing_connection(outgoing_t *outgoing) {
449 event_del(&outgoing->ev);
451 n = lookup_node(outgoing->name);
455 ifdebug(CONNECTIONS) logger(LOG_INFO, "Already connected to %s", outgoing->name);
457 n->connection->outgoing = outgoing;
461 c = new_connection();
462 c->name = xstrdup(outgoing->name);
463 c->outcipher = myself->connection->outcipher;
464 c->outdigest = myself->connection->outdigest;
465 c->outmaclength = myself->connection->outmaclength;
466 c->outcompression = myself->connection->outcompression;
468 init_configuration(&c->config_tree);
469 read_connection_config(c);
471 outgoing->cfg = lookup_config(c->config_tree, "Address");
474 logger(LOG_ERR, "No address specified for %s", c->name);
479 c->outgoing = outgoing;
480 c->last_ping_time = time(NULL);
484 do_outgoing_connection(c);
486 event_set(&c->inevent, c->socket, EV_READ | EV_PERSIST, handle_meta_connection_data, c);
487 event_add(&c->inevent, NULL);
488 c->buffer = bufferevent_new(c->socket, handle_meta_read, handle_meta_write, handle_meta_connection_error, c);
490 logger(LOG_ERR, "bufferevent_new() failed: %s", strerror(errno));
493 bufferevent_disable(c->buffer, EV_READ);
497 accept a new tcp connect and create a
500 void handle_new_meta_connection(int sock, short events, void *data) {
504 socklen_t len = sizeof sa;
506 fd = accept(sock, &sa.sa, &len);
509 logger(LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
515 c = new_connection();
516 c->name = xstrdup("<unknown>");
517 c->outcipher = myself->connection->outcipher;
518 c->outdigest = myself->connection->outdigest;
519 c->outmaclength = myself->connection->outmaclength;
520 c->outcompression = myself->connection->outcompression;
523 c->hostname = sockaddr2hostname(&sa);
525 c->last_ping_time = time(NULL);
527 ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection from %s", c->hostname);
529 event_set(&c->inevent, c->socket, EV_READ | EV_PERSIST, handle_meta_connection_data, c);
530 event_add(&c->inevent, NULL);
531 c->buffer = bufferevent_new(c->socket, NULL, handle_meta_write, handle_meta_connection_error, c);
533 logger(LOG_ERR, "bufferevent_new() failed: %s", strerror(errno));
536 bufferevent_disable(c->buffer, EV_READ);
542 c->allow_request = ID;
546 void free_outgoing(outgoing_t *outgoing) {
548 freeaddrinfo(outgoing->ai);
551 free(outgoing->name);
556 void try_outgoing_connections(void) {
557 static config_t *cfg = NULL;
559 outgoing_t *outgoing;
561 outgoing_list = list_alloc((list_action_t)free_outgoing);
563 for(cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
564 get_config_string(cfg, &name);
566 if(!check_id(name)) {
568 "Invalid name for outgoing connection in %s line %d",
569 cfg->file, cfg->line);
574 outgoing = xmalloc_and_zero(sizeof *outgoing);
575 outgoing->name = name;
576 list_insert_tail(outgoing_list, outgoing);
577 setup_outgoing_connection(outgoing);