2 net_socket.c -- Handle various kinds of sockets.
3 Copyright (C) 2014-2017 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
40 #define MSG_NOSIGNAL 0
43 int addressfamily = AF_UNSPEC;
44 int seconds_till_retry = 5;
45 int max_connection_burst = 100;
49 static void configure_tcp(connection_t *c) {
51 int flags = fcntl(c->socket, F_GETFL);
53 if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0) {
54 logger(c->mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "fcntl", strerror(errno));
58 unsigned long arg = 1;
60 if(ioctlsocket(c->socket, FIONBIO, &arg) != 0) {
61 logger(c->mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
66 #if defined(SOL_TCP) && defined(TCP_NODELAY)
68 setsockopt(c->socket, SOL_TCP, TCP_NODELAY, (void *)&nodelay, sizeof(nodelay));
71 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
72 int lowdelay = IPTOS_LOWDELAY;
73 setsockopt(c->socket, IPPROTO_IP, IP_TOS, (void *)&lowdelay, sizeof(lowdelay));
77 static bool bind_to_address(meshlink_handle_t *mesh, connection_t *c) {
80 for(int i = 0; i < mesh->listen_sockets && mesh->listen_socket[i].bindto; i++) {
81 if(mesh->listen_socket[i].sa.sa.sa_family != c->address.sa.sa_family) {
96 sockaddr_t sa = mesh->listen_socket[s].sa;
98 if(sa.sa.sa_family == AF_INET) {
100 } else if(sa.sa.sa_family == AF_INET6) {
101 sa.in6.sin6_port = 0;
104 if(bind(c->socket, &sa.sa, SALEN(sa.sa))) {
105 logger(mesh, MESHLINK_WARNING, "Can't bind outgoing socket: %s", strerror(errno));
112 int setup_listen_socket(const sockaddr_t *sa) {
117 nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
120 logger(NULL, MESHLINK_ERROR, "Creating metasocket failed: %s", sockstrerror(sockerrno));
125 fcntl(nfd, F_SETFD, FD_CLOEXEC);
128 /* Optimize TCP settings */
131 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
133 #if defined(IPV6_V6ONLY)
135 if(sa->sa.sa_family == AF_INET6) {
136 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
140 #warning IPV6_V6ONLY not defined
143 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
145 addrstr = sockaddr2hostname(sa);
146 logger(NULL, MESHLINK_ERROR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
153 logger(NULL, MESHLINK_ERROR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
160 int setup_vpn_in_socket(meshlink_handle_t *mesh, const sockaddr_t *sa) {
165 nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
168 logger(mesh, MESHLINK_ERROR, "Creating UDP socket failed: %s", sockstrerror(sockerrno));
173 fcntl(nfd, F_SETFD, FD_CLOEXEC);
178 int flags = fcntl(nfd, F_GETFL);
180 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
182 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "fcntl",
189 unsigned long arg = 1;
191 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
193 logger(mesh, MESHLINK_ERROR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
200 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
201 setsockopt(nfd, SOL_SOCKET, SO_BROADCAST, (void *)&option, sizeof(option));
203 #if defined(IPV6_V6ONLY)
205 if(sa->sa.sa_family == AF_INET6) {
206 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
211 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
212 #define IP_DONTFRAGMENT IP_DONTFRAG
215 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
217 if(mesh->self->options & OPTION_PMTU_DISCOVERY) {
218 option = IP_PMTUDISC_DO;
219 setsockopt(nfd, IPPROTO_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
222 #elif defined(IP_DONTFRAGMENT)
224 if(mesh->self->options & OPTION_PMTU_DISCOVERY) {
226 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
230 #warning No way to disable IPv4 fragmentation
233 #if defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
235 if(mesh->self->options & OPTION_PMTU_DISCOVERY) {
236 option = IPV6_PMTUDISC_DO;
237 setsockopt(nfd, IPPROTO_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
240 #elif defined(IPV6_DONTFRAG)
242 if(mesh->self->options & OPTION_PMTU_DISCOVERY) {
244 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
248 #warning No way to disable IPv6 fragmentation
251 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
253 addrstr = sockaddr2hostname(sa);
254 logger(mesh, MESHLINK_ERROR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
260 } /* int setup_vpn_in_socket */
262 static void retry_outgoing_handler(event_loop_t *loop, void *data) {
263 meshlink_handle_t *mesh = loop->data;
264 outgoing_t *outgoing = data;
265 setup_outgoing_connection(mesh, outgoing);
268 void retry_outgoing(meshlink_handle_t *mesh, outgoing_t *outgoing) {
269 outgoing->timeout += 5;
271 if(outgoing->timeout > mesh->maxtimeout) {
272 outgoing->timeout = mesh->maxtimeout;
275 timeout_add(&mesh->loop, &outgoing->ev, retry_outgoing_handler, outgoing, &(struct timeval) {
276 outgoing->timeout, rand() % 100000
279 logger(mesh, MESHLINK_INFO, "Trying to re-establish outgoing connection in %d seconds", outgoing->timeout);
282 void finish_connecting(meshlink_handle_t *mesh, connection_t *c) {
283 logger(mesh, MESHLINK_INFO, "Connected to %s", c->name);
285 c->last_ping_time = mesh->loop.now.tv_sec;
286 c->status.connecting = false;
291 static void handle_meta_write(meshlink_handle_t *mesh, connection_t *c) {
292 if(c->outbuf.len <= c->outbuf.offset) {
296 ssize_t outlen = send(c->socket, c->outbuf.data + c->outbuf.offset, c->outbuf.len - c->outbuf.offset, MSG_NOSIGNAL);
299 if(!errno || errno == EPIPE) {
300 logger(mesh, MESHLINK_INFO, "Connection closed by %s", c->name);
301 } else if(sockwouldblock(sockerrno)) {
302 logger(mesh, MESHLINK_DEBUG, "Sending %lu bytes to %s would block", (unsigned long)(c->outbuf.len - c->outbuf.offset), c->name);
305 logger(mesh, MESHLINK_ERROR, "Could not send %lu bytes of data to %s: %s", (unsigned long)(c->outbuf.len - c->outbuf.offset), c->name, strerror(errno));
308 terminate_connection(mesh, c, c->status.active);
312 buffer_read(&c->outbuf, outlen);
315 io_set(&mesh->loop, &c->io, IO_READ);
319 static void handle_meta_io(event_loop_t *loop, void *data, int flags) {
320 meshlink_handle_t *mesh = loop->data;
321 connection_t *c = data;
323 if(c->status.connecting) {
324 c->status.connecting = false;
327 socklen_t len = sizeof(result);
328 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
331 finish_connecting(mesh, c);
333 logger(mesh, MESHLINK_DEBUG, "Error while connecting to %s: %s", c->name, sockstrerror(result));
334 terminate_connection(mesh, c, false);
339 if(flags & IO_WRITE) {
340 handle_meta_write(mesh, c);
342 handle_meta_connection_data(mesh, c);
346 // Find edges pointing to this node, and use them to build a list of unique, known addresses.
347 static struct addrinfo *get_known_addresses(node_t *n) {
348 struct addrinfo *ai = NULL;
350 for splay_each(edge_t, e, n->edge_tree) {
357 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
358 if(!sockaddrcmp(&e->reverse->address, (sockaddr_t *)aip->ai_addr)) {
368 // Create a new struct addrinfo, and put it at the head of the list.
369 struct addrinfo *nai = xzalloc(sizeof(*nai) + SALEN(e->reverse->address.sa));
373 ai->ai_family = e->reverse->address.sa.sa_family;
374 ai->ai_socktype = SOCK_STREAM;
375 ai->ai_protocol = IPPROTO_TCP;
376 ai->ai_addrlen = SALEN(e->reverse->address.sa);
377 ai->ai_addr = (struct sockaddr *)(nai + 1);
378 memcpy(ai->ai_addr, &e->reverse->address, ai->ai_addrlen);
384 // Build a list of recently seen addresses.
385 static struct addrinfo *get_recent_addresses(node_t *n) {
386 struct addrinfo *ai = NULL;
387 struct addrinfo *aip;
389 for(int i = 0; i < 5; i++) {
390 if(!n->recent[i].sa.sa_family) {
394 // Create a new struct addrinfo, and put it at the end of the list.
395 struct addrinfo *nai = xzalloc(sizeof(*nai) + SALEN(n->recent[i].sa));
405 nai->ai_family = n->recent[i].sa.sa_family;
406 nai->ai_socktype = SOCK_STREAM;
407 nai->ai_protocol = IPPROTO_TCP;
408 nai->ai_addrlen = SALEN(n->recent[i].sa);
409 nai->ai_addr = (struct sockaddr *)(nai + 1);
410 memcpy(nai->ai_addr, &n->recent[i], nai->ai_addrlen);
416 // Free struct addrinfo list from get_known_addresses().
417 static void free_known_addresses(struct addrinfo *ai) {
418 for(struct addrinfo *aip = ai, *next; aip; aip = next) {
424 static struct addrinfo *get_canonical_address(node_t *n) {
425 if(!n->canonical_address) {
429 char *address = xstrdup(n->canonical_address);
430 char *port = strchr(address, ' ');
439 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
445 static bool get_next_outgoing_address(meshlink_handle_t *mesh, outgoing_t *outgoing) {
450 if(outgoing->state == OUTGOING_START) {
452 outgoing->state = OUTGOING_CANONICAL;
455 if(outgoing->state == OUTGOING_CANONICAL) {
457 outgoing->ai = get_canonical_address(outgoing->node);
458 outgoing->aip = outgoing->ai;
460 outgoing->aip = outgoing->aip->ai_next;
467 freeaddrinfo(outgoing->ai);
469 outgoing->aip = NULL;
470 outgoing->state = OUTGOING_RECENT;
473 if(outgoing->state == OUTGOING_RECENT) {
475 outgoing->ai = get_recent_addresses(outgoing->node);
476 outgoing->aip = outgoing->ai;
478 outgoing->aip = outgoing->aip->ai_next;
485 free_known_addresses(outgoing->ai);
487 outgoing->aip = NULL;
488 outgoing->state = OUTGOING_KNOWN;
491 if(outgoing->state == OUTGOING_KNOWN) {
493 outgoing->ai = get_known_addresses(outgoing->node);
494 outgoing->aip = outgoing->ai;
496 outgoing->aip = outgoing->aip->ai_next;
503 free_known_addresses(outgoing->ai);
505 outgoing->aip = NULL;
506 outgoing->state = OUTGOING_END;
510 outgoing->state = OUTGOING_NO_KNOWN_ADDRESSES;
516 bool do_outgoing_connection(meshlink_handle_t *mesh, outgoing_t *outgoing) {
517 struct addrinfo *proxyai = NULL;
522 if(!get_next_outgoing_address(mesh, outgoing)) {
523 if(outgoing->state == OUTGOING_NO_KNOWN_ADDRESSES) {
524 logger(mesh, MESHLINK_ERROR, "No known addresses for %s", outgoing->node->name);
526 logger(mesh, MESHLINK_ERROR, "Could not set up a meta connection to %s", outgoing->node->name);
527 retry_outgoing(mesh, outgoing);
533 connection_t *c = new_connection();
534 c->outgoing = outgoing;
536 memcpy(&c->address, outgoing->aip->ai_addr, outgoing->aip->ai_addrlen);
538 char *hostname = sockaddr2hostname(&c->address);
540 logger(mesh, MESHLINK_INFO, "Trying to connect to %s at %s", outgoing->node->name, hostname);
542 if(!mesh->proxytype) {
543 c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
546 proxyai = str2addrinfo(mesh->proxyhost, mesh->proxyport, SOCK_STREAM);
554 logger(mesh, MESHLINK_INFO, "Using proxy at %s port %s", mesh->proxyhost, mesh->proxyport);
555 c->socket = socket(proxyai->ai_family, SOCK_STREAM, IPPROTO_TCP);
559 if(c->socket == -1) {
560 logger(mesh, MESHLINK_ERROR, "Creating socket for %s at %s failed: %s", c->name, hostname, sockstrerror(sockerrno));
569 fcntl(c->socket, F_SETFD, FD_CLOEXEC);
572 #if defined(IPV6_V6ONLY)
574 if(c->address.sa.sa_family == AF_INET6) {
575 static const int option = 1;
576 setsockopt(c->socket, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
581 bind_to_address(mesh, c);
585 if(!mesh->proxytype) {
586 result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
588 result = connect(c->socket, proxyai->ai_addr, proxyai->ai_addrlen);
589 freeaddrinfo(proxyai);
592 if(result == -1 && !sockinprogress(sockerrno)) {
593 logger(mesh, MESHLINK_ERROR, "Could not connect to %s: %s", outgoing->node->name, sockstrerror(sockerrno));
599 /* Now that there is a working socket, fill in the rest and register this connection. */
601 c->status.connecting = true;
602 c->name = xstrdup(outgoing->node->name);
603 c->last_ping_time = mesh->loop.now.tv_sec;
605 connection_add(mesh, c);
607 io_add(&mesh->loop, &c->io, handle_meta_io, c, c->socket, IO_READ | IO_WRITE);
612 void setup_outgoing_connection(meshlink_handle_t *mesh, outgoing_t *outgoing) {
613 timeout_del(&mesh->loop, &outgoing->ev);
615 if(outgoing->node->connection) {
616 logger(mesh, MESHLINK_INFO, "Already connected to %s", outgoing->node->name);
618 outgoing->node->connection->outgoing = outgoing;
624 if(outgoing->state == OUTGOING_RECENT || outgoing->state == OUTGOING_KNOWN) {
625 free_known_addresses(outgoing->ai);
627 freeaddrinfo(outgoing->ai);
631 outgoing->state = OUTGOING_START;
633 if(outgoing->node->status.blacklisted) {
637 if(mesh->connection_try_cb) {
638 mesh->connection_try_cb(mesh, (meshlink_node_t *)outgoing->node);
641 do_outgoing_connection(mesh, outgoing);
644 /// Delayed close of a filedescriptor.
645 static void tarpit(int fd) {
646 static int pits[10] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
647 static int next_pit = 0;
649 if(pits[next_pit] != -1) {
650 closesocket(pits[next_pit]);
653 pits[next_pit++] = fd;
655 if(next_pit >= (int)(sizeof pits / sizeof pits[0])) {
661 accept a new tcp connect and create a
664 void handle_new_meta_connection(event_loop_t *loop, void *data, int flags) {
666 meshlink_handle_t *mesh = loop->data;
667 listen_socket_t *l = data;
671 socklen_t len = sizeof(sa);
673 memset(&sa, 0, sizeof(sa));
675 fd = accept(l->tcp.fd, &sa.sa, &len);
678 if(errno == EINVAL) { // TODO: check if Windows agrees
679 event_loop_stop(loop);
683 logger(mesh, MESHLINK_ERROR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
689 /* Rate limit incoming connections to max_connection_burst/second. */
691 static int connection_burst;
692 static int connection_burst_time;
694 if(mesh->loop.now.tv_sec != connection_burst_time) {
695 connection_burst_time = mesh->loop.now.tv_sec;
696 connection_burst = 0;
699 if(connection_burst >= max_connection_burst) {
706 // Accept the new connection
708 c = new_connection();
709 c->name = xstrdup("<unknown>");
713 c->last_ping_time = mesh->loop.now.tv_sec;
715 char *hostname = sockaddr2hostname(&sa);
716 logger(mesh, MESHLINK_INFO, "Connection from %s", hostname);
719 io_add(&mesh->loop, &c->io, handle_meta_io, c, c->socket, IO_READ);
723 connection_add(mesh, c);
725 c->allow_request = ID;
729 static void free_outgoing(outgoing_t *outgoing) {
730 meshlink_handle_t *mesh = outgoing->node->mesh;
732 timeout_del(&mesh->loop, &outgoing->ev);
735 if(outgoing->state == OUTGOING_RECENT || outgoing->state == OUTGOING_KNOWN) {
736 free_known_addresses(outgoing->ai);
738 freeaddrinfo(outgoing->ai);
745 void init_outgoings(meshlink_handle_t *mesh) {
746 mesh->outgoings = list_alloc((list_action_t)free_outgoing);
749 void exit_outgoings(meshlink_handle_t *mesh) {
750 if(mesh->outgoings) {
751 list_delete_list(mesh->outgoings);
752 mesh->outgoings = NULL;