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;
47 listen_socket_t listen_socket[MAXSOCKETS];
49 list_t *outgoing_list = NULL;
53 static void configure_tcp(connection_t *c) {
57 int flags = fcntl(c->socket, F_GETFL);
59 if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0) {
60 logger(LOG_ERR, "fcntl for %s: %s", c->hostname, strerror(errno));
63 unsigned long arg = 1;
65 if(ioctlsocket(c->socket, FIONBIO, &arg) != 0) {
66 logger(LOG_ERR, "ioctlsocket for %s: %d", c->hostname, sockstrerror(sockerrno));
70 #if defined(SOL_TCP) && defined(TCP_NODELAY)
72 setsockopt(c->socket, SOL_TCP, TCP_NODELAY, &option, sizeof option);
75 #if defined(SOL_IP) && defined(IP_TOS) && defined(IPTOS_LOWDELAY)
76 option = IPTOS_LOWDELAY;
77 setsockopt(c->socket, SOL_IP, IP_TOS, &option, sizeof option);
81 static bool bind_to_interface(int sd) {
84 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
87 #endif /* defined(SOL_SOCKET) && defined(SO_BINDTODEVICE) */
89 if(!get_config_string (lookup_config (config_tree, "BindToInterface"), &iface))
92 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
93 memset(&ifr, 0, sizeof(ifr));
94 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
95 ifr.ifr_ifrn.ifrn_name[IFNAMSIZ - 1] = 0;
97 status = setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr));
99 logger(LOG_ERR, "Can't bind to interface %s: %s", iface,
103 #else /* if !defined(SOL_SOCKET) || !defined(SO_BINDTODEVICE) */
104 logger(LOG_WARNING, "%s not supported on this platform", "BindToInterface");
110 static bool bind_to_address(connection_t *c) {
112 struct addrinfo *ai_list;
113 struct addrinfo *ai_ptr;
114 struct addrinfo ai_hints;
118 assert(c->socket >= 0);
121 if(!get_config_string(lookup_config(config_tree, "BindToAddress"),
125 assert(node != NULL);
127 memset(&ai_hints, 0, sizeof(ai_hints));
128 ai_hints.ai_family = c->address.sa.sa_family;
129 /* We're called from `do_outgoing_connection' only. */
130 ai_hints.ai_socktype = SOCK_STREAM;
131 ai_hints.ai_protocol = IPPROTO_TCP;
135 status = getaddrinfo(node, /* service = */ NULL,
136 &ai_hints, &ai_list);
139 logger(LOG_WARNING, "Error looking up %s port %s: %s",
140 node, "any", gai_strerror(status));
143 assert(ai_list != NULL);
146 for(ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) {
147 status = bind(c->socket,
148 ai_list->ai_addr, ai_list->ai_addrlen);
155 logger(LOG_ERR, "Can't bind to %s/tcp: %s", node, sockstrerror(sockerrno));
156 } else ifdebug(CONNECTIONS) {
157 logger(LOG_DEBUG, "Successfully bound outgoing "
158 "TCP socket to %s", node);
162 freeaddrinfo(ai_list);
164 return status ? false : true;
167 int setup_listen_socket(const sockaddr_t *sa) {
173 nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
176 ifdebug(STATUS) logger(LOG_ERR, "Creating metasocket failed: %s", sockstrerror(sockerrno));
180 /* Optimize TCP settings */
183 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof option);
185 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
186 if(sa->sa.sa_family == AF_INET6)
187 setsockopt(nfd, SOL_IPV6, IPV6_V6ONLY, &option, sizeof option);
191 (lookup_config(config_tree, "BindToInterface"), &iface)) {
192 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
195 memset(&ifr, 0, sizeof ifr);
196 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
198 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof ifr)) {
200 logger(LOG_ERR, "Can't bind to interface %s: %s", iface,
201 strerror(sockerrno));
205 logger(LOG_WARNING, "%s not supported on this platform", "BindToInterface");
209 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
211 addrstr = sockaddr2hostname(sa);
212 logger(LOG_ERR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
219 logger(LOG_ERR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
226 int setup_vpn_in_socket(const sockaddr_t *sa) {
231 nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
234 logger(LOG_ERR, "Creating UDP socket failed: %s", sockstrerror(sockerrno));
240 int flags = fcntl(nfd, F_GETFL);
242 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
244 logger(LOG_ERR, "System call `%s' failed: %s", "fcntl",
251 unsigned long arg = 1;
252 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
254 logger(LOG_ERR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
261 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof option);
263 #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
264 if(sa->sa.sa_family == AF_INET6)
265 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, &option, sizeof option);
268 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
269 #define IP_DONTFRAGMENT IP_DONTFRAG
272 #if defined(SOL_IP) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
273 if(myself->options & OPTION_PMTU_DISCOVERY) {
274 option = IP_PMTUDISC_DO;
275 setsockopt(nfd, SOL_IP, IP_MTU_DISCOVER, &option, sizeof(option));
277 #elif defined(IPPROTO_IP) && defined(IP_DONTFRAGMENT)
278 if(myself->options & OPTION_PMTU_DISCOVERY) {
280 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, &option, sizeof(option));
283 #warning No way to disable IPv4 fragmentation
286 #if defined(SOL_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
287 if(myself->options & OPTION_PMTU_DISCOVERY) {
288 option = IPV6_PMTUDISC_DO;
289 setsockopt(nfd, SOL_IPV6, IPV6_MTU_DISCOVER, &option, sizeof(option));
291 #elif defined(IPPROTO_IPV6) && defined(IPV6_DONTFRAG)
292 if(myself->options & OPTION_PMTU_DISCOVERY) {
294 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, &option, sizeof(option));
297 #warning No way to disable IPv6 fragmentation
300 if (!bind_to_interface(nfd)) {
305 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
307 addrstr = sockaddr2hostname(sa);
308 logger(LOG_ERR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
314 } /* int setup_vpn_in_socket */
316 static void retry_outgoing_handler(int fd, short events, void *data) {
317 setup_outgoing_connection(data);
320 void retry_outgoing(outgoing_t *outgoing) {
321 outgoing->timeout += 5;
323 if(outgoing->timeout > maxtimeout)
324 outgoing->timeout = maxtimeout;
326 timeout_set(&outgoing->ev, retry_outgoing_handler, outgoing);
327 event_add(&outgoing->ev, &(struct timeval){outgoing->timeout, 0});
329 ifdebug(CONNECTIONS) logger(LOG_NOTICE,
330 "Trying to re-establish outgoing connection in %d seconds",
334 void finish_connecting(connection_t *c) {
335 ifdebug(CONNECTIONS) logger(LOG_INFO, "Connected to %s (%s)", c->name, c->hostname);
339 c->last_ping_time = time(NULL);
340 c->status.connecting = false;
345 void do_outgoing_connection(connection_t *c) {
346 char *address, *port, *space;
350 logger(LOG_ERR, "do_outgoing_connection() for %s called without c->outgoing", c->name);
355 if(!c->outgoing->ai) {
356 if(!c->outgoing->cfg) {
357 ifdebug(CONNECTIONS) logger(LOG_ERR, "Could not set up a meta connection to %s",
359 retry_outgoing(c->outgoing);
365 get_config_string(c->outgoing->cfg, &address);
367 space = strchr(address, ' ');
369 port = xstrdup(space + 1);
372 if(!get_config_string(lookup_config(c->config_tree, "Port"), &port))
373 port = xstrdup("655");
376 c->outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
380 c->outgoing->aip = c->outgoing->ai;
381 c->outgoing->cfg = lookup_config_next(c->config_tree, c->outgoing->cfg);
384 if(!c->outgoing->aip) {
386 freeaddrinfo(c->outgoing->ai);
387 c->outgoing->ai = NULL;
391 memcpy(&c->address, c->outgoing->aip->ai_addr, c->outgoing->aip->ai_addrlen);
392 c->outgoing->aip = c->outgoing->aip->ai_next;
397 c->hostname = sockaddr2hostname(&c->address);
399 ifdebug(CONNECTIONS) logger(LOG_INFO, "Trying to connect to %s (%s)", c->name,
402 c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
404 if(c->socket == -1) {
405 ifdebug(CONNECTIONS) logger(LOG_ERR, "Creating socket for %s failed: %s", c->hostname, sockstrerror(sockerrno));
409 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
411 if(c->address.sa.sa_family == AF_INET6)
412 setsockopt(c->socket, SOL_IPV6, IPV6_V6ONLY, &option, sizeof option);
415 bind_to_interface(c->socket);
418 /* Optimize TCP settings */
424 result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
427 if(sockinprogress(sockerrno)) {
428 c->status.connecting = true;
432 closesocket(c->socket);
434 ifdebug(CONNECTIONS) logger(LOG_ERR, "%s: %s", c->hostname, sockstrerror(sockerrno));
439 finish_connecting(c);
444 void handle_meta_read(struct bufferevent *event, void *data) {
445 logger(LOG_ERR, "handle_meta_read() called");
449 void handle_meta_write(struct bufferevent *event, void *data) {
450 ifdebug(META) logger(LOG_DEBUG, "handle_meta_write() called");
453 void handle_meta_connection_error(struct bufferevent *event, short what, void *data) {
454 connection_t *c = data;
455 logger(LOG_ERR, "handle_meta_connection_error() called: %d: %s", what, strerror(errno));
456 terminate_connection(c, c->status.active);
459 void setup_outgoing_connection(outgoing_t *outgoing) {
463 event_del(&outgoing->ev);
465 n = lookup_node(outgoing->name);
469 ifdebug(CONNECTIONS) logger(LOG_INFO, "Already connected to %s", outgoing->name);
471 n->connection->outgoing = outgoing;
475 c = new_connection();
476 c->name = xstrdup(outgoing->name);
477 c->outcipher = myself->connection->outcipher;
478 c->outdigest = myself->connection->outdigest;
479 c->outmaclength = myself->connection->outmaclength;
480 c->outcompression = myself->connection->outcompression;
482 init_configuration(&c->config_tree);
483 read_connection_config(c);
485 outgoing->cfg = lookup_config(c->config_tree, "Address");
488 logger(LOG_ERR, "No address specified for %s", c->name);
493 c->outgoing = outgoing;
494 c->last_ping_time = time(NULL);
498 do_outgoing_connection(c);
500 event_set(&c->inevent, c->socket, EV_READ | EV_PERSIST, handle_meta_connection_data, c);
501 event_add(&c->inevent, NULL);
502 c->buffer = bufferevent_new(c->socket, handle_meta_read, handle_meta_write, handle_meta_connection_error, c);
504 logger(LOG_ERR, "bufferevent_new() failed: %s", strerror(errno));
507 bufferevent_disable(c->buffer, EV_READ);
511 accept a new tcp connect and create a
514 void handle_new_meta_connection(int sock, short events, void *data) {
518 socklen_t len = sizeof sa;
520 fd = accept(sock, &sa.sa, &len);
523 logger(LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
529 c = new_connection();
530 c->name = xstrdup("<unknown>");
531 c->outcipher = myself->connection->outcipher;
532 c->outdigest = myself->connection->outdigest;
533 c->outmaclength = myself->connection->outmaclength;
534 c->outcompression = myself->connection->outcompression;
537 c->hostname = sockaddr2hostname(&sa);
539 c->last_ping_time = time(NULL);
541 ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection from %s", c->hostname);
543 event_set(&c->inevent, c->socket, EV_READ | EV_PERSIST, handle_meta_connection_data, c);
544 event_add(&c->inevent, NULL);
545 c->buffer = bufferevent_new(c->socket, NULL, handle_meta_write, handle_meta_connection_error, c);
547 logger(LOG_ERR, "bufferevent_new() failed: %s", strerror(errno));
550 bufferevent_disable(c->buffer, EV_READ);
556 c->allow_request = ID;
560 void free_outgoing(outgoing_t *outgoing) {
562 freeaddrinfo(outgoing->ai);
565 free(outgoing->name);
570 void try_outgoing_connections(void) {
571 static config_t *cfg = NULL;
573 outgoing_t *outgoing;
575 outgoing_list = list_alloc((list_action_t)free_outgoing);
577 for(cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
578 get_config_string(cfg, &name);
580 if(!check_id(name)) {
582 "Invalid name for outgoing connection in %s line %d",
583 cfg->file, cfg->line);
588 outgoing = xmalloc_and_zero(sizeof *outgoing);
589 outgoing->name = name;
590 list_insert_tail(outgoing_list, outgoing);
591 setup_outgoing_connection(outgoing);