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;
40 int seconds_till_retry = 5;
41 int max_connection_burst = 100;
45 static void configure_tcp(connection_t *c) {
47 int flags = fcntl(c->socket, F_GETFL);
49 if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0) {
50 logger(DEBUG_ALWAYS, LOG_ERR, "fcntl for %s: %s", c->hostname, strerror(errno));
53 unsigned long arg = 1;
55 if(ioctlsocket(c->socket, FIONBIO, &arg) != 0) {
56 logger(DEBUG_ALWAYS, LOG_ERR, "ioctlsocket for %s: %s", c->hostname, sockstrerror(sockerrno));
60 #if defined(SOL_TCP) && defined(TCP_NODELAY)
62 setsockopt(c->socket, SOL_TCP, TCP_NODELAY, (void *)&option, sizeof option);
65 #if defined(SOL_IP) && defined(IP_TOS) && defined(IPTOS_LOWDELAY)
66 option = IPTOS_LOWDELAY;
67 setsockopt(c->socket, SOL_IP, IP_TOS, (void *)&option, sizeof option);
71 static bool bind_to_address(meshlink_handle_t *mesh, connection_t *c) {
74 for(int i = 0; i < mesh->listen_sockets && mesh->listen_socket[i].bindto; i++) {
75 if(mesh->listen_socket[i].sa.sa.sa_family != c->address.sa.sa_family)
85 sockaddr_t sa = mesh->listen_socket[s].sa;
86 if(sa.sa.sa_family == AF_INET)
88 else if(sa.sa.sa_family == AF_INET6)
91 if(bind(c->socket, &sa.sa, SALEN(sa.sa))) {
92 logger(DEBUG_CONNECTIONS, LOG_WARNING, "Can't bind outgoing socket: %s", strerror(errno));
99 int setup_listen_socket(const sockaddr_t *sa) {
104 nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
107 logger(DEBUG_STATUS, LOG_ERR, "Creating metasocket failed: %s", sockstrerror(sockerrno));
112 fcntl(nfd, F_SETFD, FD_CLOEXEC);
115 /* Optimize TCP settings */
118 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof option);
120 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
121 if(sa->sa.sa_family == AF_INET6)
122 setsockopt(nfd, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
125 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
127 addrstr = sockaddr2hostname(sa);
128 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
135 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
142 int setup_vpn_in_socket(meshlink_handle_t *mesh, const sockaddr_t *sa) {
147 nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
150 logger(DEBUG_ALWAYS, LOG_ERR, "Creating UDP socket failed: %s", sockstrerror(sockerrno));
155 fcntl(nfd, F_SETFD, FD_CLOEXEC);
160 int flags = fcntl(nfd, F_GETFL);
162 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
164 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "fcntl",
171 unsigned long arg = 1;
172 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
174 logger(DEBUG_ALWAYS, LOG_ERR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
181 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof option);
182 setsockopt(nfd, SOL_SOCKET, SO_BROADCAST, (void *)&option, sizeof option);
184 #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
185 if(sa->sa.sa_family == AF_INET6)
186 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
189 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
190 #define IP_DONTFRAGMENT IP_DONTFRAG
193 #if defined(SOL_IP) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
194 if(mesh->self->options & OPTION_PMTU_DISCOVERY) {
195 option = IP_PMTUDISC_DO;
196 setsockopt(nfd, SOL_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
198 #elif defined(IPPROTO_IP) && defined(IP_DONTFRAGMENT)
199 if(mesh->self->options & OPTION_PMTU_DISCOVERY) {
201 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
204 #warning No way to disable IPv4 fragmentation
207 #if defined(SOL_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
208 if(mesh->self->options & OPTION_PMTU_DISCOVERY) {
209 option = IPV6_PMTUDISC_DO;
210 setsockopt(nfd, SOL_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
212 #elif defined(IPPROTO_IPV6) && defined(IPV6_DONTFRAG)
213 if(mesh->self->options & OPTION_PMTU_DISCOVERY) {
215 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
218 #warning No way to disable IPv6 fragmentation
221 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
223 addrstr = sockaddr2hostname(sa);
224 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
230 } /* int setup_vpn_in_socket */
232 static void retry_outgoing_handler(event_loop_t *loop, void *data) {
233 meshlink_handle_t *mesh = loop->data;
234 outgoing_t *outgoing = data;
235 setup_outgoing_connection(mesh, outgoing);
238 void retry_outgoing(meshlink_handle_t *mesh, outgoing_t *outgoing) {
239 outgoing->timeout += 5;
241 if(outgoing->timeout > mesh->maxtimeout)
242 outgoing->timeout = mesh->maxtimeout;
244 timeout_add(&mesh->loop, &outgoing->ev, retry_outgoing_handler, outgoing, &(struct timeval){outgoing->timeout, rand() % 100000});
246 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Trying to re-establish outgoing connection in %d seconds", outgoing->timeout);
249 void finish_connecting(meshlink_handle_t *mesh, connection_t *c) {
250 logger(DEBUG_CONNECTIONS, LOG_INFO, "Connected to %s (%s)", c->name, c->hostname);
252 c->last_ping_time = mesh->loop.now.tv_sec;
253 c->status.connecting = false;
258 static void do_outgoing_pipe(meshlink_handle_t *mesh, connection_t *c, char *command) {
262 if(socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) {
263 logger(DEBUG_ALWAYS, LOG_ERR, "Could not create socketpair: %s", strerror(errno));
270 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Using proxy %s", command);
281 // Other filedescriptors should be closed automatically by CLOEXEC
286 sockaddr2str(&c->address, &host, &port);
287 setenv("REMOTEADDRESS", host, true);
288 setenv("REMOTEPORT", port, true);
289 setenv("NODE", c->name, true);
290 setenv("NAME", mesh->self->name, true);
292 int result = system(command);
294 logger(DEBUG_ALWAYS, LOG_ERR, "Could not execute %s: %s", command, strerror(errno));
296 logger(DEBUG_ALWAYS, LOG_ERR, "%s exited with non-zero status %d", command, result);
299 logger(DEBUG_ALWAYS, LOG_ERR, "Proxy type exec not supported on this platform!");
304 static void handle_meta_write(meshlink_handle_t *mesh, connection_t *c) {
305 if(c->outbuf.len <= c->outbuf.offset)
308 ssize_t outlen = send(c->socket, c->outbuf.data + c->outbuf.offset, c->outbuf.len - c->outbuf.offset, 0);
310 if(!errno || errno == EPIPE) {
311 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection closed by %s (%s)", c->name, c->hostname);
312 } else if(sockwouldblock(sockerrno)) {
313 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Sending %d bytes to %s (%s) would block", c->outbuf.len - c->outbuf.offset, c->name, c->hostname);
316 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));
319 terminate_connection(mesh, c, c->status.active);
323 buffer_read(&c->outbuf, outlen);
325 io_set(&mesh->loop, &c->io, IO_READ);
328 static void handle_meta_io(event_loop_t *loop, void *data, int flags) {
329 meshlink_handle_t *mesh = loop->data;
330 connection_t *c = data;
332 if(c->status.connecting) {
333 c->status.connecting = false;
336 socklen_t len = sizeof result;
337 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
340 finish_connecting(mesh, c);
342 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Error while connecting to %s (%s): %s", c->name, c->hostname, sockstrerror(result));
343 terminate_connection(mesh, c, false);
349 handle_meta_write(mesh, c);
351 handle_meta_connection_data(mesh, c);
354 bool do_outgoing_connection(meshlink_handle_t *mesh, outgoing_t *outgoing) {
355 char *address, *port, *space;
356 struct addrinfo *proxyai = NULL;
362 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not set up a meta connection to %s", outgoing->name);
363 retry_outgoing(mesh, outgoing);
367 get_config_string(outgoing->cfg, &address);
369 space = strchr(address, ' ');
371 port = xstrdup(space + 1);
374 // TODO: Only allow Address statements?
375 if(!get_config_string(lookup_config(outgoing->config_tree, "Port"), &port))
376 port = xstrdup("655");
379 outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
383 outgoing->aip = outgoing->ai;
384 outgoing->cfg = lookup_config_next(outgoing->config_tree, outgoing->cfg);
389 freeaddrinfo(outgoing->ai);
394 connection_t *c = new_connection();
395 c->outgoing = outgoing;
397 memcpy(&c->address, outgoing->aip->ai_addr, outgoing->aip->ai_addrlen);
398 outgoing->aip = outgoing->aip->ai_next;
400 c->hostname = sockaddr2hostname(&c->address);
402 logger(DEBUG_CONNECTIONS, LOG_INFO, "Trying to connect to %s (%s)", outgoing->name, c->hostname);
404 if(!mesh->proxytype) {
405 c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
407 } else if(mesh->proxytype == PROXY_EXEC) {
408 do_outgoing_pipe(mesh, c, mesh->proxyhost);
410 proxyai = str2addrinfo(mesh->proxyhost, mesh->proxyport, SOCK_STREAM);
415 logger(DEBUG_CONNECTIONS, LOG_INFO, "Using proxy at %s port %s", mesh->proxyhost, mesh->proxyport);
416 c->socket = socket(proxyai->ai_family, SOCK_STREAM, IPPROTO_TCP);
420 if(c->socket == -1) {
421 logger(DEBUG_CONNECTIONS, LOG_ERR, "Creating socket for %s failed: %s", c->hostname, sockstrerror(sockerrno));
427 fcntl(c->socket, F_SETFD, FD_CLOEXEC);
430 if(mesh->proxytype != PROXY_EXEC) {
431 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
433 if(c->address.sa.sa_family == AF_INET6)
434 setsockopt(c->socket, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
437 bind_to_address(mesh, c);
442 if(!mesh->proxytype) {
443 result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
444 } else if(mesh->proxytype == PROXY_EXEC) {
447 result = connect(c->socket, proxyai->ai_addr, proxyai->ai_addrlen);
448 freeaddrinfo(proxyai);
451 if(result == -1 && !sockinprogress(sockerrno)) {
452 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not connect to %s (%s): %s", outgoing->name, c->hostname, sockstrerror(sockerrno));
458 /* Now that there is a working socket, fill in the rest and register this connection. */
460 c->status.connecting = true;
461 c->name = xstrdup(outgoing->name);
462 c->outcompression = mesh->self->connection->outcompression;
463 c->last_ping_time = mesh->loop.now.tv_sec;
465 connection_add(mesh, c);
467 io_add(&mesh->loop, &c->io, handle_meta_io, c, c->socket, IO_READ|IO_WRITE);
472 // Find edges pointing to this node, and use them to build a list of unique, known addresses.
473 static struct addrinfo *get_known_addresses(node_t *n) {
474 struct addrinfo *ai = NULL;
476 for splay_each(edge_t, e, n->edge_tree) {
481 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
482 if(!sockaddrcmp(&e->reverse->address, (sockaddr_t *)aip->ai_addr)) {
490 struct addrinfo *nai = xzalloc(sizeof *nai);
494 ai->ai_family = e->reverse->address.sa.sa_family;
495 ai->ai_socktype = SOCK_STREAM;
496 ai->ai_protocol = IPPROTO_TCP;
497 ai->ai_addrlen = SALEN(e->reverse->address.sa);
498 ai->ai_addr = xmalloc(ai->ai_addrlen);
499 memcpy(ai->ai_addr, &e->reverse->address, ai->ai_addrlen);
505 void setup_outgoing_connection(meshlink_handle_t *mesh, outgoing_t *outgoing) {
506 bool blacklisted = false;
507 timeout_del(&mesh->loop, &outgoing->ev);
509 node_t *n = lookup_node(mesh, outgoing->name);
511 if(n && n->connection) {
512 logger(DEBUG_CONNECTIONS, LOG_INFO, "Already connected to %s", outgoing->name);
514 n->connection->outgoing = outgoing;
518 init_configuration(&outgoing->config_tree);
519 read_host_config(mesh, outgoing->config_tree, outgoing->name);
520 outgoing->cfg = lookup_config(outgoing->config_tree, "Address");
522 get_config_bool(lookup_config(outgoing->config_tree, "blacklisted"), &blacklisted);
523 if (blacklisted) return;
527 outgoing->aip = outgoing->ai = get_known_addresses(n);
529 logger(DEBUG_ALWAYS, LOG_ERR, "No address known for %s", outgoing->name);
534 do_outgoing_connection(mesh, outgoing);
538 accept a new tcp connect and create a
541 void handle_new_meta_connection(event_loop_t *loop, void *data, int flags) {
542 meshlink_handle_t *mesh = loop->data;
543 listen_socket_t *l = data;
547 socklen_t len = sizeof sa;
549 fd = accept(l->tcp.fd, &sa.sa, &len);
552 if(errno == EINVAL) { // TODO: check if Windows agrees
553 event_loop_stop(loop);
557 logger(DEBUG_ALWAYS, LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
563 // Check if we get many connections from the same host
565 static sockaddr_t prev_sa;
566 static int tarpit = -1;
573 if(!sockaddrcmp_noport(&sa, &prev_sa)) {
574 static int samehost_burst;
575 static int samehost_burst_time;
577 if(mesh->loop.now.tv_sec - samehost_burst_time > samehost_burst)
580 samehost_burst -= mesh->loop.now.tv_sec - samehost_burst_time;
582 samehost_burst_time = mesh->loop.now.tv_sec;
585 if(samehost_burst > max_connection_burst) {
591 memcpy(&prev_sa, &sa, sizeof sa);
593 // Check if we get many connections from different hosts
595 static int connection_burst;
596 static int connection_burst_time;
598 if(mesh->loop.now.tv_sec - connection_burst_time > connection_burst)
599 connection_burst = 0;
601 connection_burst -= mesh->loop.now.tv_sec - connection_burst_time;
603 connection_burst_time = mesh->loop.now.tv_sec;
606 if(connection_burst >= max_connection_burst) {
607 connection_burst = max_connection_burst;
612 // Accept the new connection
614 c = new_connection();
615 c->name = xstrdup("<unknown>");
616 c->outcompression = mesh->self->connection->outcompression;
619 c->hostname = sockaddr2hostname(&sa);
621 c->last_ping_time = mesh->loop.now.tv_sec;
623 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection from %s", c->hostname);
625 io_add(&mesh->loop, &c->io, handle_meta_io, c, c->socket, IO_READ);
629 connection_add(mesh, c);
631 c->allow_request = ID;
635 static void free_outgoing(meshlink_handle_t *mesh, outgoing_t *outgoing) {
636 timeout_del(&mesh->loop, &outgoing->ev);
639 freeaddrinfo(outgoing->ai);
641 if(outgoing->config_tree)
642 exit_configuration(&outgoing->config_tree);
645 free(outgoing->name);
650 void try_outgoing_connections(meshlink_handle_t *mesh) {
651 /* If there is no outgoing list yet, create one. Otherwise, mark all outgoings as deleted. */
653 if(!mesh->outgoings) {
654 mesh->outgoings = list_alloc((list_action_t)free_outgoing);
656 for list_each(outgoing_t, outgoing, mesh->outgoings)
657 outgoing->timeout = -1;
660 /* Make sure there is one outgoing_t in the list for each ConnectTo. */
662 // TODO: Drop support for ConnectTo since AutoConnect is now always on?
663 for(config_t *cfg = lookup_config(mesh->config, "ConnectTo"); cfg; cfg = lookup_config_next(mesh->config, cfg)) {
665 get_config_string(cfg, &name);
667 if(!check_id(name)) {
668 logger(DEBUG_ALWAYS, LOG_ERR,
669 "Invalid name for outgoing connection in %s line %d",
670 cfg->file, cfg->line);
677 for list_each(outgoing_t, outgoing, mesh->outgoings) {
678 if(!strcmp(outgoing->name, name)) {
680 outgoing->timeout = 0;
686 outgoing_t *outgoing = xzalloc(sizeof *outgoing);
687 outgoing->name = name;
688 list_insert_tail(mesh->outgoings, outgoing);
689 setup_outgoing_connection(mesh, outgoing);
693 /* Terminate any connections whose outgoing_t is to be deleted. */
695 for list_each(connection_t, c, mesh->connections) {
696 if(c->outgoing && c->outgoing->timeout == -1) {
698 logger(DEBUG_CONNECTIONS, LOG_INFO, "No more outgoing connection to %s", c->name);
699 terminate_connection(mesh, c, c->status.active);
703 /* Delete outgoing_ts for which there is no ConnectTo. */
705 for list_each(outgoing_t, outgoing, mesh->outgoings)
706 if(outgoing->timeout == -1)
707 list_delete_node(mesh->outgoings, node);