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;
46 static void configure_tcp(connection_t *c) {
50 int flags = fcntl(c->socket, F_GETFL);
52 if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0) {
53 logger(DEBUG_ALWAYS, LOG_ERR, "fcntl for %s: %s", c->hostname, strerror(errno));
56 unsigned long arg = 1;
58 if(ioctlsocket(c->socket, FIONBIO, &arg) != 0) {
59 logger(DEBUG_ALWAYS, LOG_ERR, "ioctlsocket for %s: %s", c->hostname, sockstrerror(sockerrno));
63 #if defined(SOL_TCP) && defined(TCP_NODELAY)
65 setsockopt(c->socket, SOL_TCP, TCP_NODELAY, (void *)&option, sizeof option);
68 #if defined(SOL_IP) && defined(IP_TOS) && defined(IPTOS_LOWDELAY)
69 option = IPTOS_LOWDELAY;
70 setsockopt(c->socket, SOL_IP, IP_TOS, (void *)&option, sizeof option);
74 static bool bind_to_address(connection_t *c) {
77 for(int i = 0; i < mesh->listen_sockets && mesh->listen_socket[i].bindto; i++) {
78 if(mesh->listen_socket[i].sa.sa.sa_family != c->address.sa.sa_family)
88 sockaddr_t sa = mesh->listen_socket[s].sa;
89 if(sa.sa.sa_family == AF_INET)
91 else if(sa.sa.sa_family == AF_INET6)
94 if(bind(c->socket, &sa.sa, SALEN(sa.sa))) {
95 logger(DEBUG_CONNECTIONS, LOG_WARNING, "Can't bind outgoing socket: %s", strerror(errno));
102 int setup_listen_socket(const sockaddr_t *sa) {
108 nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
111 logger(DEBUG_STATUS, LOG_ERR, "Creating metasocket failed: %s", sockstrerror(sockerrno));
116 fcntl(nfd, F_SETFD, FD_CLOEXEC);
119 /* Optimize TCP settings */
122 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof option);
124 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
125 if(sa->sa.sa_family == AF_INET6)
126 setsockopt(nfd, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
129 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
131 addrstr = sockaddr2hostname(sa);
132 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
139 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
146 int setup_vpn_in_socket(const sockaddr_t *sa) {
151 nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
154 logger(DEBUG_ALWAYS, LOG_ERR, "Creating UDP socket failed: %s", sockstrerror(sockerrno));
159 fcntl(nfd, F_SETFD, FD_CLOEXEC);
164 int flags = fcntl(nfd, F_GETFL);
166 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
168 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "fcntl",
175 unsigned long arg = 1;
176 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
178 logger(DEBUG_ALWAYS, LOG_ERR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
185 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof option);
186 setsockopt(nfd, SOL_SOCKET, SO_BROADCAST, (void *)&option, sizeof option);
188 #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
189 if(sa->sa.sa_family == AF_INET6)
190 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
193 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
194 #define IP_DONTFRAGMENT IP_DONTFRAG
197 #if defined(SOL_IP) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
198 if(mesh->self->options & OPTION_PMTU_DISCOVERY) {
199 option = IP_PMTUDISC_DO;
200 setsockopt(nfd, SOL_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
202 #elif defined(IPPROTO_IP) && defined(IP_DONTFRAGMENT)
203 if(mesh->self->options & OPTION_PMTU_DISCOVERY) {
205 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
208 #warning No way to disable IPv4 fragmentation
211 #if defined(SOL_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
212 if(mesh->self->options & OPTION_PMTU_DISCOVERY) {
213 option = IPV6_PMTUDISC_DO;
214 setsockopt(nfd, SOL_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
216 #elif defined(IPPROTO_IPV6) && defined(IPV6_DONTFRAG)
217 if(mesh->self->options & OPTION_PMTU_DISCOVERY) {
219 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
222 #warning No way to disable IPv6 fragmentation
225 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
227 addrstr = sockaddr2hostname(sa);
228 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
234 } /* int setup_vpn_in_socket */
236 static void retry_outgoing_handler(void *data) {
237 setup_outgoing_connection(data);
240 void retry_outgoing(outgoing_t *outgoing) {
241 outgoing->timeout += 5;
243 if(outgoing->timeout > maxtimeout)
244 outgoing->timeout = maxtimeout;
246 timeout_add(&outgoing->ev, retry_outgoing_handler, outgoing, &(struct timeval){outgoing->timeout, rand() % 100000});
248 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Trying to re-establish outgoing connection in %d seconds", outgoing->timeout);
251 void finish_connecting(connection_t *c) {
252 logger(DEBUG_CONNECTIONS, LOG_INFO, "Connected to %s (%s)", c->name, c->hostname);
254 c->last_ping_time = now.tv_sec;
255 c->status.connecting = false;
260 static void do_outgoing_pipe(connection_t *c, char *command) {
264 if(socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) {
265 logger(DEBUG_ALWAYS, LOG_ERR, "Could not create socketpair: %s", strerror(errno));
272 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Using proxy %s", command);
283 // Other filedescriptors should be closed automatically by CLOEXEC
288 sockaddr2str(&c->address, &host, &port);
289 setenv("REMOTEADDRESS", host, true);
290 setenv("REMOTEPORT", port, true);
291 setenv("NODE", c->name, true);
292 setenv("NAME", mesh->self->name, true);
294 int result = system(command);
296 logger(DEBUG_ALWAYS, LOG_ERR, "Could not execute %s: %s", command, strerror(errno));
298 logger(DEBUG_ALWAYS, LOG_ERR, "%s exited with non-zero status %d", command, result);
301 logger(DEBUG_ALWAYS, LOG_ERR, "Proxy type exec not supported on this platform!");
306 static void handle_meta_write(connection_t *c) {
307 if(c->outbuf.len <= c->outbuf.offset)
310 ssize_t outlen = send(c->socket, c->outbuf.data + c->outbuf.offset, c->outbuf.len - c->outbuf.offset, 0);
312 if(!errno || errno == EPIPE) {
313 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection closed by %s (%s)", c->name, c->hostname);
314 } else if(sockwouldblock(sockerrno)) {
315 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Sending %d bytes to %s (%s) would block", c->outbuf.len - c->outbuf.offset, c->name, c->hostname);
318 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));
321 terminate_connection(c, c->status.active);
325 buffer_read(&c->outbuf, outlen);
327 io_set(&c->io, IO_READ);
330 static void handle_meta_io(void *data, int flags) {
331 connection_t *c = data;
333 if(c->status.connecting) {
334 c->status.connecting = false;
337 socklen_t len = sizeof result;
338 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
341 finish_connecting(c);
343 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Error while connecting to %s (%s): %s", c->name, c->hostname, sockstrerror(result));
344 terminate_connection(c, false);
350 handle_meta_write(c);
352 handle_meta_connection_data(c);
355 bool do_outgoing_connection(outgoing_t *outgoing) {
356 char *address, *port, *space;
357 struct addrinfo *proxyai = NULL;
363 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not set up a meta connection to %s", outgoing->name);
364 retry_outgoing(outgoing);
368 get_config_string(outgoing->cfg, &address);
370 space = strchr(address, ' ');
372 port = xstrdup(space + 1);
375 // TODO: Only allow Address statements?
376 if(!get_config_string(lookup_config(outgoing->config_tree, "Port"), &port))
377 port = xstrdup("655");
380 outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
384 outgoing->aip = outgoing->ai;
385 outgoing->cfg = lookup_config_next(outgoing->config_tree, outgoing->cfg);
390 freeaddrinfo(outgoing->ai);
395 connection_t *c = new_connection();
396 c->outgoing = outgoing;
398 memcpy(&c->address, outgoing->aip->ai_addr, outgoing->aip->ai_addrlen);
399 outgoing->aip = outgoing->aip->ai_next;
401 c->hostname = sockaddr2hostname(&c->address);
403 logger(DEBUG_CONNECTIONS, LOG_INFO, "Trying to connect to %s (%s)", outgoing->name, c->hostname);
405 if(!mesh->proxytype) {
406 c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
408 } else if(mesh->proxytype == PROXY_EXEC) {
409 do_outgoing_pipe(c, mesh->proxyhost);
411 proxyai = str2addrinfo(mesh->proxyhost, mesh->proxyport, SOCK_STREAM);
416 logger(DEBUG_CONNECTIONS, LOG_INFO, "Using proxy at %s port %s", mesh->proxyhost, mesh->proxyport);
417 c->socket = socket(proxyai->ai_family, SOCK_STREAM, IPPROTO_TCP);
421 if(c->socket == -1) {
422 logger(DEBUG_CONNECTIONS, LOG_ERR, "Creating socket for %s failed: %s", c->hostname, sockstrerror(sockerrno));
428 fcntl(c->socket, F_SETFD, FD_CLOEXEC);
431 if(mesh->proxytype != PROXY_EXEC) {
432 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
434 if(c->address.sa.sa_family == AF_INET6)
435 setsockopt(c->socket, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
443 if(!mesh->proxytype) {
444 result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
445 } else if(mesh->proxytype == PROXY_EXEC) {
448 result = connect(c->socket, proxyai->ai_addr, proxyai->ai_addrlen);
449 freeaddrinfo(proxyai);
452 if(result == -1 && !sockinprogress(sockerrno)) {
453 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not connect to %s (%s): %s", outgoing->name, c->hostname, sockstrerror(sockerrno));
459 /* Now that there is a working socket, fill in the rest and register this connection. */
461 c->status.connecting = true;
462 c->name = xstrdup(outgoing->name);
463 c->outcompression = mesh->self->connection->outcompression;
464 c->last_ping_time = now.tv_sec;
468 io_add(&c->io, handle_meta_io, c, c->socket, IO_READ|IO_WRITE);
473 // Find edges pointing to this node, and use them to build a list of unique, known addresses.
474 static struct addrinfo *get_known_addresses(node_t *n) {
475 struct addrinfo *ai = NULL;
477 for splay_each(edge_t, e, n->edge_tree) {
482 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
483 if(!sockaddrcmp(&e->reverse->address, (sockaddr_t *)aip->ai_addr)) {
491 struct addrinfo *nai = xzalloc(sizeof *nai);
495 ai->ai_family = e->reverse->address.sa.sa_family;
496 ai->ai_socktype = SOCK_STREAM;
497 ai->ai_protocol = IPPROTO_TCP;
498 ai->ai_addrlen = SALEN(e->reverse->address.sa);
499 ai->ai_addr = xmalloc(ai->ai_addrlen);
500 memcpy(ai->ai_addr, &e->reverse->address, ai->ai_addrlen);
506 void setup_outgoing_connection(outgoing_t *outgoing) {
507 timeout_del(&outgoing->ev);
509 node_t *n = lookup_node(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(outgoing->config_tree, outgoing->name);
520 outgoing->cfg = lookup_config(outgoing->config_tree, "Address");
524 outgoing->aip = outgoing->ai = get_known_addresses(n);
526 logger(DEBUG_ALWAYS, LOG_ERR, "No address known for %s", outgoing->name);
531 do_outgoing_connection(outgoing);
535 accept a new tcp connect and create a
538 void handle_new_meta_connection(void *data, int flags) {
539 listen_socket_t *l = data;
543 socklen_t len = sizeof sa;
545 fd = accept(l->tcp.fd, &sa.sa, &len);
548 logger(DEBUG_ALWAYS, LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
554 // Check if we get many connections from the same host
556 static sockaddr_t prev_sa;
557 static int tarpit = -1;
564 if(!sockaddrcmp_noport(&sa, &prev_sa)) {
565 static int samehost_burst;
566 static int samehost_burst_time;
568 if(now.tv_sec - samehost_burst_time > samehost_burst)
571 samehost_burst -= now.tv_sec - samehost_burst_time;
573 samehost_burst_time = now.tv_sec;
576 if(samehost_burst > max_connection_burst) {
582 memcpy(&prev_sa, &sa, sizeof sa);
584 // Check if we get many connections from different hosts
586 static int connection_burst;
587 static int connection_burst_time;
589 if(now.tv_sec - connection_burst_time > connection_burst)
590 connection_burst = 0;
592 connection_burst -= now.tv_sec - connection_burst_time;
594 connection_burst_time = now.tv_sec;
597 if(connection_burst >= max_connection_burst) {
598 connection_burst = max_connection_burst;
603 // Accept the new connection
605 c = new_connection();
606 c->name = xstrdup("<unknown>");
607 c->outcompression = mesh->self->connection->outcompression;
610 c->hostname = sockaddr2hostname(&sa);
612 c->last_ping_time = now.tv_sec;
614 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection from %s", c->hostname);
616 io_add(&c->io, handle_meta_io, c, c->socket, IO_READ);
622 c->allow_request = ID;
626 static void free_outgoing(outgoing_t *outgoing) {
627 timeout_del(&outgoing->ev);
630 freeaddrinfo(outgoing->ai);
632 if(outgoing->config_tree)
633 exit_configuration(&outgoing->config_tree);
636 free(outgoing->name);
641 void try_outgoing_connections(void) {
642 /* If there is no outgoing list yet, create one. Otherwise, mark all outgoings as deleted. */
644 if(!mesh->outgoings) {
645 mesh->outgoings = list_alloc((list_action_t)free_outgoing);
647 for list_each(outgoing_t, outgoing, mesh->outgoings)
648 outgoing->timeout = -1;
651 /* Make sure there is one outgoing_t in the list for each ConnectTo. */
653 // TODO: Drop support for ConnectTo since AutoConnect is now always on?
654 for(config_t *cfg = lookup_config(mesh->config, "ConnectTo"); cfg; cfg = lookup_config_next(mesh->config, cfg)) {
656 get_config_string(cfg, &name);
658 if(!check_id(name)) {
659 logger(DEBUG_ALWAYS, LOG_ERR,
660 "Invalid name for outgoing connection in %s line %d",
661 cfg->file, cfg->line);
668 for list_each(outgoing_t, outgoing, mesh->outgoings) {
669 if(!strcmp(outgoing->name, name)) {
671 outgoing->timeout = 0;
677 outgoing_t *outgoing = xzalloc(sizeof *outgoing);
678 outgoing->name = name;
679 list_insert_tail(mesh->outgoings, outgoing);
680 setup_outgoing_connection(outgoing);
684 /* Terminate any connections whose outgoing_t is to be deleted. */
686 for list_each(connection_t, c, mesh->connections) {
687 if(c->outgoing && c->outgoing->timeout == -1) {
689 logger(DEBUG_CONNECTIONS, LOG_INFO, "No more outgoing connection to %s", c->name);
690 terminate_connection(c, c->status.active);
694 /* Delete outgoing_ts for which there is no ConnectTo. */
696 for list_each(outgoing_t, outgoing, mesh->outgoings)
697 if(outgoing->timeout == -1)
698 list_delete_node(mesh->outgoings, node);