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 static const int max_connection_burst = 100;
47 static void configure_tcp(connection_t *c) {
49 int flags = fcntl(c->socket, F_GETFL);
51 if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0) {
52 logger(c->mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "fcntl", strerror(errno));
56 unsigned long arg = 1;
58 if(ioctlsocket(c->socket, FIONBIO, &arg) != 0) {
59 logger(c->mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
64 #if defined(SOL_TCP) && defined(TCP_NODELAY)
66 setsockopt(c->socket, SOL_TCP, TCP_NODELAY, (void *)&nodelay, sizeof(nodelay));
69 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
70 int lowdelay = IPTOS_LOWDELAY;
71 setsockopt(c->socket, IPPROTO_IP, IP_TOS, (void *)&lowdelay, sizeof(lowdelay));
75 bool setup_listen_socket(meshlink_handle_t *mesh, int nfd, int sa_family) {
77 fcntl(nfd, F_SETFD, FD_CLOEXEC);
81 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
83 #if defined(IPV6_V6ONLY)
85 if(sa_family == AF_INET6) {
86 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
90 #warning IPV6_V6ONLY not defined
94 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
101 bool setup_vpn_in_socket(meshlink_handle_t *mesh, int nfd, int sa_family) {
103 fcntl(nfd, F_SETFD, FD_CLOEXEC);
108 int flags = fcntl(nfd, F_GETFL);
110 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
112 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "fcntl",
119 unsigned long arg = 1;
121 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
123 logger(mesh, MESHLINK_ERROR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
130 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
131 setsockopt(nfd, SOL_SOCKET, SO_BROADCAST, (void *)&option, sizeof(option));
133 #if defined(IPV6_V6ONLY)
135 if(sa_family == AF_INET6) {
136 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
141 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
142 #define IP_DONTFRAGMENT IP_DONTFRAG
145 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
146 option = IP_PMTUDISC_DO;
147 setsockopt(nfd, IPPROTO_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
148 #elif defined(IP_DONTFRAGMENT)
150 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
153 #if defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
154 option = IPV6_PMTUDISC_DO;
155 setsockopt(nfd, IPPROTO_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
156 #elif defined(IPV6_DONTFRAG)
158 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
162 } /* int setup_vpn_in_socket */
164 static void retry_outgoing_handler(event_loop_t *loop, void *data) {
167 meshlink_handle_t *mesh = loop->data;
168 outgoing_t *outgoing = data;
169 setup_outgoing_connection(mesh, outgoing);
172 void retry_outgoing(meshlink_handle_t *mesh, outgoing_t *outgoing) {
173 if(!mesh->reachable && mesh->loop.now.tv_sec < mesh->last_unreachable + mesh->dev_class_traits[mesh->devclass].fast_retry_period) {
174 outgoing->timeout = 1;
176 outgoing->timeout += 5;
179 if(outgoing->timeout > mesh->maxtimeout) {
180 outgoing->timeout = mesh->maxtimeout;
183 timeout_add(&mesh->loop, &outgoing->ev, retry_outgoing_handler, outgoing, &(struct timeval) {
184 outgoing->timeout, prng(mesh, TIMER_FUDGE)
187 logger(mesh, MESHLINK_INFO, "Trying to re-establish outgoing connection in %d seconds", outgoing->timeout);
190 void finish_connecting(meshlink_handle_t *mesh, connection_t *c) {
191 logger(mesh, MESHLINK_INFO, "Connected to %s", c->name);
193 c->last_ping_time = mesh->loop.now.tv_sec;
194 c->status.connecting = false;
199 static void handle_meta_write(meshlink_handle_t *mesh, connection_t *c) {
200 if(c->outbuf.len <= c->outbuf.offset) {
204 ssize_t outlen = send(c->socket, c->outbuf.data + c->outbuf.offset, c->outbuf.len - c->outbuf.offset, MSG_NOSIGNAL);
207 if(!errno || errno == EPIPE) {
208 logger(mesh, MESHLINK_INFO, "Connection closed by %s", c->name);
209 } else if(sockwouldblock(sockerrno)) {
210 logger(mesh, MESHLINK_DEBUG, "Sending %lu bytes to %s would block", (unsigned long)(c->outbuf.len - c->outbuf.offset), c->name);
213 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));
216 terminate_connection(mesh, c, c->status.active);
220 buffer_read(&c->outbuf, outlen);
223 io_set(&mesh->loop, &c->io, IO_READ);
227 static void handle_meta_io(event_loop_t *loop, void *data, int flags) {
228 meshlink_handle_t *mesh = loop->data;
229 connection_t *c = data;
231 if(c->status.connecting) {
232 c->status.connecting = false;
235 socklen_t len = sizeof(result);
236 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
239 finish_connecting(mesh, c);
241 logger(mesh, MESHLINK_DEBUG, "Error while connecting to %s: %s", c->name, sockstrerror(result));
242 terminate_connection(mesh, c, false);
247 if(flags & IO_WRITE) {
248 handle_meta_write(mesh, c);
250 handle_meta_connection_data(mesh, c);
254 // Find edges pointing to this node, and use them to build a list of unique, known addresses.
255 static struct addrinfo *get_known_addresses(node_t *n) {
256 struct addrinfo *ai = NULL;
258 for splay_each(edge_t, e, n->edge_tree) {
265 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
266 if(!sockaddrcmp(&e->reverse->address, (sockaddr_t *)aip->ai_addr)) {
276 // Create a new struct addrinfo, and put it at the head of the list.
277 struct addrinfo *nai = xzalloc(sizeof(*nai) + SALEN(e->reverse->address.sa));
281 ai->ai_family = e->reverse->address.sa.sa_family;
282 ai->ai_socktype = SOCK_STREAM;
283 ai->ai_protocol = IPPROTO_TCP;
284 ai->ai_addrlen = SALEN(e->reverse->address.sa);
285 ai->ai_addr = (struct sockaddr *)(nai + 1);
286 memcpy(ai->ai_addr, &e->reverse->address, ai->ai_addrlen);
292 // Build a list of recently seen addresses.
293 static struct addrinfo *get_recent_addresses(node_t *n) {
294 struct addrinfo *ai = NULL;
295 struct addrinfo *aip;
297 for(int i = 0; i < 5; i++) {
298 if(!n->recent[i].sa.sa_family) {
302 // Create a new struct addrinfo, and put it at the end of the list.
303 struct addrinfo *nai = xzalloc(sizeof(*nai) + SALEN(n->recent[i].sa));
313 nai->ai_family = n->recent[i].sa.sa_family;
314 nai->ai_socktype = SOCK_STREAM;
315 nai->ai_protocol = IPPROTO_TCP;
316 nai->ai_addrlen = SALEN(n->recent[i].sa);
317 nai->ai_addr = (struct sockaddr *)(nai + 1);
318 memcpy(nai->ai_addr, &n->recent[i], nai->ai_addrlen);
324 // Free struct addrinfo list from get_known_addresses().
325 static void free_known_addresses(struct addrinfo *ai) {
326 for(struct addrinfo *aip = ai, *next; aip; aip = next) {
332 static struct addrinfo *get_canonical_address(node_t *n) {
333 if(!n->canonical_address) {
337 char *address = xstrdup(n->canonical_address);
338 char *port = strchr(address, ' ');
347 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
353 static bool get_next_outgoing_address(meshlink_handle_t *mesh, outgoing_t *outgoing) {
358 if(outgoing->state == OUTGOING_START) {
360 outgoing->state = OUTGOING_CANONICAL;
363 if(outgoing->state == OUTGOING_CANONICAL) {
365 outgoing->ai = get_canonical_address(outgoing->node);
366 outgoing->aip = outgoing->ai;
368 outgoing->aip = outgoing->aip->ai_next;
375 freeaddrinfo(outgoing->ai);
377 outgoing->aip = NULL;
378 outgoing->state = OUTGOING_RECENT;
381 if(outgoing->state == OUTGOING_RECENT) {
383 outgoing->ai = get_recent_addresses(outgoing->node);
384 outgoing->aip = outgoing->ai;
386 outgoing->aip = outgoing->aip->ai_next;
393 free_known_addresses(outgoing->ai);
395 outgoing->aip = NULL;
396 outgoing->state = OUTGOING_KNOWN;
399 if(outgoing->state == OUTGOING_KNOWN) {
401 outgoing->ai = get_known_addresses(outgoing->node);
402 outgoing->aip = outgoing->ai;
404 outgoing->aip = outgoing->aip->ai_next;
411 free_known_addresses(outgoing->ai);
413 outgoing->aip = NULL;
414 outgoing->state = OUTGOING_END;
418 outgoing->state = OUTGOING_NO_KNOWN_ADDRESSES;
424 void do_outgoing_connection(meshlink_handle_t *mesh, outgoing_t *outgoing) {
425 struct addrinfo *proxyai = NULL;
430 if(!get_next_outgoing_address(mesh, outgoing)) {
431 if(outgoing->state == OUTGOING_NO_KNOWN_ADDRESSES) {
432 logger(mesh, MESHLINK_ERROR, "No known addresses for %s", outgoing->node->name);
434 logger(mesh, MESHLINK_ERROR, "Could not set up a meta connection to %s", outgoing->node->name);
435 retry_outgoing(mesh, outgoing);
441 connection_t *c = new_connection();
442 c->outgoing = outgoing;
444 memcpy(&c->address, outgoing->aip->ai_addr, outgoing->aip->ai_addrlen);
446 char *hostname = sockaddr2hostname(&c->address);
448 logger(mesh, MESHLINK_INFO, "Trying to connect to %s at %s", outgoing->node->name, hostname);
450 if(!mesh->proxytype) {
451 c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
454 proxyai = str2addrinfo(mesh->proxyhost, mesh->proxyport, SOCK_STREAM);
462 logger(mesh, MESHLINK_INFO, "Using proxy at %s port %s", mesh->proxyhost, mesh->proxyport);
463 c->socket = socket(proxyai->ai_family, SOCK_STREAM, IPPROTO_TCP);
467 if(c->socket == -1) {
468 logger(mesh, MESHLINK_ERROR, "Creating socket for %s at %s failed: %s", c->name, hostname, sockstrerror(sockerrno));
477 fcntl(c->socket, F_SETFD, FD_CLOEXEC);
480 #if defined(IPV6_V6ONLY)
482 if(c->address.sa.sa_family == AF_INET6) {
483 static const int option = 1;
484 setsockopt(c->socket, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
491 if(!mesh->proxytype) {
492 result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
494 result = connect(c->socket, proxyai->ai_addr, proxyai->ai_addrlen);
495 freeaddrinfo(proxyai);
498 if(result == -1 && !sockinprogress(sockerrno)) {
499 logger(mesh, MESHLINK_ERROR, "Could not connect to %s: %s", outgoing->node->name, sockstrerror(sockerrno));
505 /* Now that there is a working socket, fill in the rest and register this connection. */
507 c->status.connecting = true;
508 c->status.initiator = true;
509 c->name = xstrdup(outgoing->node->name);
510 c->last_ping_time = mesh->loop.now.tv_sec;
512 connection_add(mesh, c);
514 io_add(&mesh->loop, &c->io, handle_meta_io, c, c->socket, IO_READ | IO_WRITE);
517 void reset_outgoing(outgoing_t *outgoing) {
519 if(outgoing->state == OUTGOING_RECENT || outgoing->state == OUTGOING_KNOWN) {
520 free_known_addresses(outgoing->ai);
522 freeaddrinfo(outgoing->ai);
527 outgoing->aip = NULL;
528 outgoing->state = OUTGOING_START;
531 void setup_outgoing_connection(meshlink_handle_t *mesh, outgoing_t *outgoing) {
532 timeout_del(&mesh->loop, &outgoing->ev);
534 if(outgoing->node->connection) {
535 logger(mesh, MESHLINK_INFO, "Already connected to %s", outgoing->node->name);
537 outgoing->node->connection->outgoing = outgoing;
541 reset_outgoing(outgoing);
543 if(outgoing->node->status.blacklisted) {
547 if(mesh->connection_try_cb) {
548 mesh->connection_try_cb(mesh, (meshlink_node_t *)outgoing->node);
551 do_outgoing_connection(mesh, outgoing);
554 /// Delayed close of a filedescriptor.
555 static void tarpit(meshlink_handle_t *mesh, int fd) {
560 if(mesh->pits[mesh->next_pit]) {
561 closesocket(mesh->pits[mesh->next_pit]);
564 mesh->pits[mesh->next_pit++] = fd;
566 if(mesh->next_pit >= (int)(sizeof mesh->pits / sizeof mesh->pits[0])) {
572 accept a new tcp connect and create a
575 void handle_new_meta_connection(event_loop_t *loop, void *data, int flags) {
577 meshlink_handle_t *mesh = loop->data;
578 listen_socket_t *l = data;
582 socklen_t len = sizeof(sa);
584 memset(&sa, 0, sizeof(sa));
586 fd = accept(l->tcp.fd, &sa.sa, &len);
589 if(errno == EINVAL) { // TODO: check if Windows agrees
590 event_loop_stop(loop);
594 logger(mesh, MESHLINK_ERROR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
600 /* Rate limit incoming connections to max_connection_burst/second. */
602 if(mesh->loop.now.tv_sec != mesh->connection_burst_time) {
603 mesh->connection_burst_time = mesh->loop.now.tv_sec;
604 mesh->connection_burst = 0;
607 if(mesh->connection_burst >= max_connection_burst) {
612 mesh->connection_burst++;
614 // Accept the new connection
616 c = new_connection();
617 c->name = xstrdup("<unknown>");
621 c->last_ping_time = mesh->loop.now.tv_sec;
623 char *hostname = sockaddr2hostname(&sa);
624 logger(mesh, MESHLINK_INFO, "Connection from %s", hostname);
627 io_add(&mesh->loop, &c->io, handle_meta_io, c, c->socket, IO_READ);
631 connection_add(mesh, c);
633 c->allow_request = ID;
637 static void free_outgoing(outgoing_t *outgoing) {
638 meshlink_handle_t *mesh = outgoing->node->mesh;
640 timeout_del(&mesh->loop, &outgoing->ev);
643 if(outgoing->state == OUTGOING_RECENT || outgoing->state == OUTGOING_KNOWN) {
644 free_known_addresses(outgoing->ai);
646 freeaddrinfo(outgoing->ai);
653 void init_outgoings(meshlink_handle_t *mesh) {
654 mesh->outgoings = list_alloc((list_action_t)free_outgoing);
657 void exit_outgoings(meshlink_handle_t *mesh) {
658 if(mesh->outgoings) {
659 list_delete_list(mesh->outgoings);
660 mesh->outgoings = NULL;