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));
242 int flags = fcntl(nfd, F_GETFL);
244 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
246 logger(LOG_ERR, "System call `%s' failed: %s", "fcntl",
253 unsigned long arg = 1;
254 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
256 logger(LOG_ERR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
263 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof option);
265 if(udp_rcvbuf && setsockopt(nfd, SOL_SOCKET, SO_RCVBUF, (void *)&udp_rcvbuf, sizeof(udp_rcvbuf)))
266 logger(LOG_WARNING, "Can't set UDP SO_RCVBUF to %i: %s", udp_rcvbuf, strerror(errno));
268 if(udp_sndbuf && setsockopt(nfd, SOL_SOCKET, SO_SNDBUF, (void *)&udp_sndbuf, sizeof(udp_sndbuf)))
269 logger(LOG_WARNING, "Can't set UDP SO_SNDBUF to %i: %s", udp_sndbuf, strerror(errno));
271 #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
272 if(sa->sa.sa_family == AF_INET6)
273 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
276 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
277 #define IP_DONTFRAGMENT IP_DONTFRAG
280 #if defined(SOL_IP) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
281 if(myself->options & OPTION_PMTU_DISCOVERY) {
282 option = IP_PMTUDISC_DO;
283 setsockopt(nfd, SOL_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
285 #elif defined(IPPROTO_IP) && defined(IP_DONTFRAGMENT)
286 if(myself->options & OPTION_PMTU_DISCOVERY) {
288 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
291 #warning No way to disable IPv4 fragmentation
294 #if defined(SOL_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
295 if(myself->options & OPTION_PMTU_DISCOVERY) {
296 option = IPV6_PMTUDISC_DO;
297 setsockopt(nfd, SOL_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
299 #elif defined(IPPROTO_IPV6) && defined(IPV6_DONTFRAG)
300 if(myself->options & OPTION_PMTU_DISCOVERY) {
302 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
305 #warning No way to disable IPv6 fragmentation
308 if (!bind_to_interface(nfd)) {
313 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
315 addrstr = sockaddr2hostname(sa);
316 logger(LOG_ERR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
322 } /* int setup_vpn_in_socket */
324 static void retry_outgoing_handler(int fd, short events, void *data) {
325 setup_outgoing_connection(data);
328 void retry_outgoing(outgoing_t *outgoing) {
329 outgoing->timeout += 5;
331 if(outgoing->timeout > maxtimeout)
332 outgoing->timeout = maxtimeout;
334 timeout_set(&outgoing->ev, retry_outgoing_handler, outgoing);
335 event_add(&outgoing->ev, &(struct timeval){outgoing->timeout, 0});
337 ifdebug(CONNECTIONS) logger(LOG_NOTICE,
338 "Trying to re-establish outgoing connection in %d seconds",
342 void finish_connecting(connection_t *c) {
343 ifdebug(CONNECTIONS) logger(LOG_INFO, "Connected to %s (%s)", c->name, c->hostname);
347 c->last_ping_time = time(NULL);
348 c->status.connecting = false;
353 void do_outgoing_connection(connection_t *c) {
354 char *address, *port, *space;
358 logger(LOG_ERR, "do_outgoing_connection() for %s called without c->outgoing", c->name);
363 if(!c->outgoing->ai) {
364 if(!c->outgoing->cfg) {
365 ifdebug(CONNECTIONS) logger(LOG_ERR, "Could not set up a meta connection to %s",
367 retry_outgoing(c->outgoing);
373 get_config_string(c->outgoing->cfg, &address);
375 space = strchr(address, ' ');
377 port = xstrdup(space + 1);
380 if(!get_config_string(lookup_config(c->config_tree, "Port"), &port))
381 port = xstrdup("655");
384 c->outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
388 c->outgoing->aip = c->outgoing->ai;
389 c->outgoing->cfg = lookup_config_next(c->config_tree, c->outgoing->cfg);
392 if(!c->outgoing->aip) {
394 freeaddrinfo(c->outgoing->ai);
395 c->outgoing->ai = NULL;
399 memcpy(&c->address, c->outgoing->aip->ai_addr, c->outgoing->aip->ai_addrlen);
400 c->outgoing->aip = c->outgoing->aip->ai_next;
405 c->hostname = sockaddr2hostname(&c->address);
407 ifdebug(CONNECTIONS) logger(LOG_INFO, "Trying to connect to %s (%s)", c->name,
410 c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
412 if(c->socket == -1) {
413 ifdebug(CONNECTIONS) logger(LOG_ERR, "Creating socket for %s failed: %s", c->hostname, sockstrerror(sockerrno));
417 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
419 if(c->address.sa.sa_family == AF_INET6)
420 setsockopt(c->socket, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
423 bind_to_interface(c->socket);
426 /* Optimize TCP settings */
432 result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
435 if(sockinprogress(sockerrno)) {
436 c->status.connecting = true;
440 closesocket(c->socket);
442 ifdebug(CONNECTIONS) logger(LOG_ERR, "%s: %s", c->hostname, sockstrerror(sockerrno));
447 finish_connecting(c);
452 void handle_meta_read(struct bufferevent *event, void *data) {
453 logger(LOG_ERR, "handle_meta_read() called");
457 void handle_meta_write(struct bufferevent *event, void *data) {
458 ifdebug(META) logger(LOG_DEBUG, "handle_meta_write() called");
461 void handle_meta_connection_error(struct bufferevent *event, short what, void *data) {
462 connection_t *c = data;
463 logger(LOG_ERR, "handle_meta_connection_error() called: %d: %s", what, strerror(errno));
464 terminate_connection(c, c->status.active);
467 void setup_outgoing_connection(outgoing_t *outgoing) {
471 event_del(&outgoing->ev);
473 n = lookup_node(outgoing->name);
477 ifdebug(CONNECTIONS) logger(LOG_INFO, "Already connected to %s", outgoing->name);
479 n->connection->outgoing = outgoing;
483 c = new_connection();
484 c->name = xstrdup(outgoing->name);
485 c->outcipher = myself->connection->outcipher;
486 c->outdigest = myself->connection->outdigest;
487 c->outmaclength = myself->connection->outmaclength;
488 c->outcompression = myself->connection->outcompression;
490 init_configuration(&c->config_tree);
491 read_connection_config(c);
493 outgoing->cfg = lookup_config(c->config_tree, "Address");
496 logger(LOG_ERR, "No address specified for %s", c->name);
501 c->outgoing = outgoing;
502 c->last_ping_time = time(NULL);
506 do_outgoing_connection(c);
508 event_set(&c->inevent, c->socket, EV_READ | EV_PERSIST, handle_meta_connection_data, c);
509 event_add(&c->inevent, NULL);
510 c->buffer = bufferevent_new(c->socket, handle_meta_read, handle_meta_write, handle_meta_connection_error, c);
512 logger(LOG_ERR, "bufferevent_new() failed: %s", strerror(errno));
515 bufferevent_disable(c->buffer, EV_READ);
519 accept a new tcp connect and create a
522 void handle_new_meta_connection(int sock, short events, void *data) {
526 socklen_t len = sizeof sa;
528 fd = accept(sock, &sa.sa, &len);
531 logger(LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
537 c = new_connection();
538 c->name = xstrdup("<unknown>");
539 c->outcipher = myself->connection->outcipher;
540 c->outdigest = myself->connection->outdigest;
541 c->outmaclength = myself->connection->outmaclength;
542 c->outcompression = myself->connection->outcompression;
545 c->hostname = sockaddr2hostname(&sa);
547 c->last_ping_time = time(NULL);
549 ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection from %s", c->hostname);
551 event_set(&c->inevent, c->socket, EV_READ | EV_PERSIST, handle_meta_connection_data, c);
552 event_add(&c->inevent, NULL);
553 c->buffer = bufferevent_new(c->socket, NULL, handle_meta_write, handle_meta_connection_error, c);
555 logger(LOG_ERR, "bufferevent_new() failed: %s", strerror(errno));
558 bufferevent_disable(c->buffer, EV_READ);
564 c->allow_request = ID;
568 void free_outgoing(outgoing_t *outgoing) {
570 freeaddrinfo(outgoing->ai);
573 free(outgoing->name);
578 void try_outgoing_connections(void) {
579 static config_t *cfg = NULL;
581 outgoing_t *outgoing;
583 outgoing_list = list_alloc((list_action_t)free_outgoing);
585 for(cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
586 get_config_string(cfg, &name);
588 if(!check_id(name)) {
590 "Invalid name for outgoing connection in %s line %d",
591 cfg->file, cfg->line);
596 outgoing = xmalloc_and_zero(sizeof *outgoing);
597 outgoing->name = name;
598 list_insert_tail(outgoing_list, outgoing);
599 setup_outgoing_connection(outgoing);