2 net_socket.c -- Handle various kinds of sockets.
3 Copyright (C) 2014 Guus Sliepen <guus@meshlink.io>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #include "connection.h"
26 #include "meshlink_internal.h"
34 /* Needed on Mac OS/X */
36 #define SOL_TCP IPPROTO_TCP
39 int addressfamily = AF_UNSPEC;
41 int seconds_till_retry = 5;
42 int max_connection_burst = 100;
44 listen_socket_t listen_socket[MAXSOCKETS];
46 list_t *outgoing_list = NULL;
50 static void configure_tcp(connection_t *c) {
54 int flags = fcntl(c->socket, F_GETFL);
56 if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0) {
57 logger(DEBUG_ALWAYS, LOG_ERR, "fcntl for %s: %s", c->hostname, strerror(errno));
60 unsigned long arg = 1;
62 if(ioctlsocket(c->socket, FIONBIO, &arg) != 0) {
63 logger(DEBUG_ALWAYS, LOG_ERR, "ioctlsocket for %s: %s", c->hostname, sockstrerror(sockerrno));
67 #if defined(SOL_TCP) && defined(TCP_NODELAY)
69 setsockopt(c->socket, SOL_TCP, TCP_NODELAY, (void *)&option, sizeof option);
72 #if defined(SOL_IP) && defined(IP_TOS) && defined(IPTOS_LOWDELAY)
73 option = IPTOS_LOWDELAY;
74 setsockopt(c->socket, SOL_IP, IP_TOS, (void *)&option, sizeof option);
78 static bool bind_to_address(connection_t *c) {
81 for(int i = 0; i < listen_sockets && listen_socket[i].bindto; i++) {
82 if(listen_socket[i].sa.sa.sa_family != c->address.sa.sa_family)
92 sockaddr_t sa = listen_socket[s].sa;
93 if(sa.sa.sa_family == AF_INET)
95 else if(sa.sa.sa_family == AF_INET6)
98 if(bind(c->socket, &sa.sa, SALEN(sa.sa))) {
99 logger(DEBUG_CONNECTIONS, LOG_WARNING, "Can't bind outgoing socket: %s", strerror(errno));
106 int setup_listen_socket(const sockaddr_t *sa) {
112 nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
115 logger(DEBUG_STATUS, LOG_ERR, "Creating metasocket failed: %s", sockstrerror(sockerrno));
120 fcntl(nfd, F_SETFD, FD_CLOEXEC);
123 /* Optimize TCP settings */
126 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof option);
128 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
129 if(sa->sa.sa_family == AF_INET6)
130 setsockopt(nfd, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
133 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
135 addrstr = sockaddr2hostname(sa);
136 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
143 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
150 int setup_vpn_in_socket(const sockaddr_t *sa) {
155 nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
158 logger(DEBUG_ALWAYS, LOG_ERR, "Creating UDP socket failed: %s", sockstrerror(sockerrno));
163 fcntl(nfd, F_SETFD, FD_CLOEXEC);
168 int flags = fcntl(nfd, F_GETFL);
170 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
172 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "fcntl",
179 unsigned long arg = 1;
180 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
182 logger(DEBUG_ALWAYS, LOG_ERR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
189 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof option);
190 setsockopt(nfd, SOL_SOCKET, SO_BROADCAST, (void *)&option, sizeof option);
192 #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
193 if(sa->sa.sa_family == AF_INET6)
194 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
197 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
198 #define IP_DONTFRAGMENT IP_DONTFRAG
201 #if defined(SOL_IP) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
202 if(mesh->self->options & OPTION_PMTU_DISCOVERY) {
203 option = IP_PMTUDISC_DO;
204 setsockopt(nfd, SOL_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
206 #elif defined(IPPROTO_IP) && defined(IP_DONTFRAGMENT)
207 if(mesh->self->options & OPTION_PMTU_DISCOVERY) {
209 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
212 #warning No way to disable IPv4 fragmentation
215 #if defined(SOL_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
216 if(mesh->self->options & OPTION_PMTU_DISCOVERY) {
217 option = IPV6_PMTUDISC_DO;
218 setsockopt(nfd, SOL_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
220 #elif defined(IPPROTO_IPV6) && defined(IPV6_DONTFRAG)
221 if(mesh->self->options & OPTION_PMTU_DISCOVERY) {
223 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
226 #warning No way to disable IPv6 fragmentation
229 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
231 addrstr = sockaddr2hostname(sa);
232 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
238 } /* int setup_vpn_in_socket */
240 static void retry_outgoing_handler(void *data) {
241 setup_outgoing_connection(data);
244 void retry_outgoing(outgoing_t *outgoing) {
245 outgoing->timeout += 5;
247 if(outgoing->timeout > maxtimeout)
248 outgoing->timeout = maxtimeout;
250 timeout_add(&outgoing->ev, retry_outgoing_handler, outgoing, &(struct timeval){outgoing->timeout, rand() % 100000});
252 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Trying to re-establish outgoing connection in %d seconds", outgoing->timeout);
255 void finish_connecting(connection_t *c) {
256 logger(DEBUG_CONNECTIONS, LOG_INFO, "Connected to %s (%s)", c->name, c->hostname);
258 c->last_ping_time = now.tv_sec;
259 c->status.connecting = false;
264 static void do_outgoing_pipe(connection_t *c, char *command) {
268 if(socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) {
269 logger(DEBUG_ALWAYS, LOG_ERR, "Could not create socketpair: %s", strerror(errno));
276 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Using proxy %s", command);
287 // Other filedescriptors should be closed automatically by CLOEXEC
292 sockaddr2str(&c->address, &host, &port);
293 setenv("REMOTEADDRESS", host, true);
294 setenv("REMOTEPORT", port, true);
295 setenv("NODE", c->name, true);
296 setenv("NAME", mesh->self->name, true);
298 int result = system(command);
300 logger(DEBUG_ALWAYS, LOG_ERR, "Could not execute %s: %s", command, strerror(errno));
302 logger(DEBUG_ALWAYS, LOG_ERR, "%s exited with non-zero status %d", command, result);
305 logger(DEBUG_ALWAYS, LOG_ERR, "Proxy type exec not supported on this platform!");
310 static void handle_meta_write(connection_t *c) {
311 if(c->outbuf.len <= c->outbuf.offset)
314 ssize_t outlen = send(c->socket, c->outbuf.data + c->outbuf.offset, c->outbuf.len - c->outbuf.offset, 0);
316 if(!errno || errno == EPIPE) {
317 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection closed by %s (%s)", c->name, c->hostname);
318 } else if(sockwouldblock(sockerrno)) {
319 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Sending %d bytes to %s (%s) would block", c->outbuf.len - c->outbuf.offset, c->name, c->hostname);
322 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not send %d bytes of data to %s (%s): %s", c->outbuf.len - c->outbuf.offset, c->name, c->hostname, strerror(errno));
325 terminate_connection(c, c->status.active);
329 buffer_read(&c->outbuf, outlen);
331 io_set(&c->io, IO_READ);
334 static void handle_meta_io(void *data, int flags) {
335 connection_t *c = data;
337 if(c->status.connecting) {
338 c->status.connecting = false;
341 socklen_t len = sizeof result;
342 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
345 finish_connecting(c);
347 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Error while connecting to %s (%s): %s", c->name, c->hostname, sockstrerror(result));
348 terminate_connection(c, false);
354 handle_meta_write(c);
356 handle_meta_connection_data(c);
359 bool do_outgoing_connection(outgoing_t *outgoing) {
360 char *address, *port, *space;
361 struct addrinfo *proxyai = NULL;
367 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not set up a meta connection to %s", outgoing->name);
368 retry_outgoing(outgoing);
372 get_config_string(outgoing->cfg, &address);
374 space = strchr(address, ' ');
376 port = xstrdup(space + 1);
379 // TODO: Only allow Address statements?
380 if(!get_config_string(lookup_config(outgoing->config_tree, "Port"), &port))
381 port = xstrdup("655");
384 outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
388 outgoing->aip = outgoing->ai;
389 outgoing->cfg = lookup_config_next(outgoing->config_tree, outgoing->cfg);
394 freeaddrinfo(outgoing->ai);
399 connection_t *c = new_connection();
400 c->outgoing = outgoing;
402 memcpy(&c->address, outgoing->aip->ai_addr, outgoing->aip->ai_addrlen);
403 outgoing->aip = outgoing->aip->ai_next;
405 c->hostname = sockaddr2hostname(&c->address);
407 logger(DEBUG_CONNECTIONS, LOG_INFO, "Trying to connect to %s (%s)", outgoing->name, c->hostname);
410 c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
412 } else if(proxytype == PROXY_EXEC) {
413 do_outgoing_pipe(c, proxyhost);
415 proxyai = str2addrinfo(proxyhost, proxyport, SOCK_STREAM);
420 logger(DEBUG_CONNECTIONS, LOG_INFO, "Using proxy at %s port %s", proxyhost, proxyport);
421 c->socket = socket(proxyai->ai_family, SOCK_STREAM, IPPROTO_TCP);
425 if(c->socket == -1) {
426 logger(DEBUG_CONNECTIONS, LOG_ERR, "Creating socket for %s failed: %s", c->hostname, sockstrerror(sockerrno));
432 fcntl(c->socket, F_SETFD, FD_CLOEXEC);
435 if(proxytype != PROXY_EXEC) {
436 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
438 if(c->address.sa.sa_family == AF_INET6)
439 setsockopt(c->socket, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
448 result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
449 } else if(proxytype == PROXY_EXEC) {
452 result = connect(c->socket, proxyai->ai_addr, proxyai->ai_addrlen);
453 freeaddrinfo(proxyai);
456 if(result == -1 && !sockinprogress(sockerrno)) {
457 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not connect to %s (%s): %s", outgoing->name, c->hostname, sockstrerror(sockerrno));
463 /* Now that there is a working socket, fill in the rest and register this connection. */
465 c->status.connecting = true;
466 c->name = xstrdup(outgoing->name);
467 c->outcompression = mesh->self->connection->outcompression;
468 c->last_ping_time = now.tv_sec;
472 io_add(&c->io, handle_meta_io, c, c->socket, IO_READ|IO_WRITE);
477 // Find edges pointing to this node, and use them to build a list of unique, known addresses.
478 static struct addrinfo *get_known_addresses(node_t *n) {
479 struct addrinfo *ai = NULL;
481 for splay_each(edge_t, e, n->edge_tree) {
486 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
487 if(!sockaddrcmp(&e->reverse->address, (sockaddr_t *)aip->ai_addr)) {
495 struct addrinfo *nai = xzalloc(sizeof *nai);
499 ai->ai_family = e->reverse->address.sa.sa_family;
500 ai->ai_socktype = SOCK_STREAM;
501 ai->ai_protocol = IPPROTO_TCP;
502 ai->ai_addrlen = SALEN(e->reverse->address.sa);
503 ai->ai_addr = xmalloc(ai->ai_addrlen);
504 memcpy(ai->ai_addr, &e->reverse->address, ai->ai_addrlen);
510 void setup_outgoing_connection(outgoing_t *outgoing) {
511 timeout_del(&outgoing->ev);
513 node_t *n = lookup_node(outgoing->name);
515 if(n && n->connection) {
516 logger(DEBUG_CONNECTIONS, LOG_INFO, "Already connected to %s", outgoing->name);
518 n->connection->outgoing = outgoing;
522 init_configuration(&outgoing->config_tree);
523 read_host_config(outgoing->config_tree, outgoing->name);
524 outgoing->cfg = lookup_config(outgoing->config_tree, "Address");
528 outgoing->aip = outgoing->ai = get_known_addresses(n);
530 logger(DEBUG_ALWAYS, LOG_ERR, "No address known for %s", outgoing->name);
535 do_outgoing_connection(outgoing);
539 accept a new tcp connect and create a
542 void handle_new_meta_connection(void *data, int flags) {
543 listen_socket_t *l = data;
547 socklen_t len = sizeof sa;
549 fd = accept(l->tcp.fd, &sa.sa, &len);
552 logger(DEBUG_ALWAYS, LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
558 // Check if we get many connections from the same host
560 static sockaddr_t prev_sa;
561 static int tarpit = -1;
568 if(!sockaddrcmp_noport(&sa, &prev_sa)) {
569 static int samehost_burst;
570 static int samehost_burst_time;
572 if(now.tv_sec - samehost_burst_time > samehost_burst)
575 samehost_burst -= now.tv_sec - samehost_burst_time;
577 samehost_burst_time = now.tv_sec;
580 if(samehost_burst > max_connection_burst) {
586 memcpy(&prev_sa, &sa, sizeof sa);
588 // Check if we get many connections from different hosts
590 static int connection_burst;
591 static int connection_burst_time;
593 if(now.tv_sec - connection_burst_time > connection_burst)
594 connection_burst = 0;
596 connection_burst -= now.tv_sec - connection_burst_time;
598 connection_burst_time = now.tv_sec;
601 if(connection_burst >= max_connection_burst) {
602 connection_burst = max_connection_burst;
607 // Accept the new connection
609 c = new_connection();
610 c->name = xstrdup("<unknown>");
611 c->outcompression = mesh->self->connection->outcompression;
614 c->hostname = sockaddr2hostname(&sa);
616 c->last_ping_time = now.tv_sec;
618 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection from %s", c->hostname);
620 io_add(&c->io, handle_meta_io, c, c->socket, IO_READ);
626 c->allow_request = ID;
630 static void free_outgoing(outgoing_t *outgoing) {
631 timeout_del(&outgoing->ev);
634 freeaddrinfo(outgoing->ai);
636 if(outgoing->config_tree)
637 exit_configuration(&outgoing->config_tree);
640 free(outgoing->name);
645 void try_outgoing_connections(void) {
646 /* If there is no outgoing list yet, create one. Otherwise, mark all outgoings as deleted. */
649 outgoing_list = list_alloc((list_action_t)free_outgoing);
651 for list_each(outgoing_t, outgoing, outgoing_list)
652 outgoing->timeout = -1;
655 /* Make sure there is one outgoing_t in the list for each ConnectTo. */
657 // TODO: Drop support for ConnectTo since AutoConnect is now always on?
658 for(config_t *cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
660 get_config_string(cfg, &name);
662 if(!check_id(name)) {
663 logger(DEBUG_ALWAYS, LOG_ERR,
664 "Invalid name for outgoing connection in %s line %d",
665 cfg->file, cfg->line);
672 for list_each(outgoing_t, outgoing, outgoing_list) {
673 if(!strcmp(outgoing->name, name)) {
675 outgoing->timeout = 0;
681 outgoing_t *outgoing = xzalloc(sizeof *outgoing);
682 outgoing->name = name;
683 list_insert_tail(outgoing_list, outgoing);
684 setup_outgoing_connection(outgoing);
688 /* Terminate any connections whose outgoing_t is to be deleted. */
690 for list_each(connection_t, c, mesh->connections) {
691 if(c->outgoing && c->outgoing->timeout == -1) {
693 logger(DEBUG_CONNECTIONS, LOG_INFO, "No more outgoing connection to %s", c->name);
694 terminate_connection(c, c->status.active);
698 /* Delete outgoing_ts for which there is no ConnectTo. */
700 for list_each(outgoing_t, outgoing, outgoing_list)
701 if(outgoing->timeout == -1)
702 list_delete_node(outgoing_list, node);