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));
74 #if defined(SO_NOSIGPIPE)
76 setsockopt(c->socket, SOL_SOCKET, SO_NOSIGPIPE, (void *)&nosigpipe, sizeof(nosigpipe));
80 static void retry_outgoing_handler(event_loop_t *loop, void *data) {
83 meshlink_handle_t *mesh = loop->data;
84 outgoing_t *outgoing = data;
85 setup_outgoing_connection(mesh, outgoing);
88 void retry_outgoing(meshlink_handle_t *mesh, outgoing_t *outgoing) {
89 if(!mesh->reachable && mesh->loop.now.tv_sec < mesh->last_unreachable + mesh->dev_class_traits[outgoing->node->devclass].fast_retry_period) {
90 outgoing->timeout = 1;
92 outgoing->timeout += 5;
95 int maxtimeout = mesh->dev_class_traits[outgoing->node->devclass].maxtimeout;
97 if(outgoing->timeout > maxtimeout) {
98 outgoing->timeout = maxtimeout;
101 timeout_add(&mesh->loop, &outgoing->ev, retry_outgoing_handler, outgoing, &(struct timespec) {
102 outgoing->timeout, prng(mesh, TIMER_FUDGE)
105 logger(mesh, MESHLINK_INFO, "Trying to re-establish outgoing connection in %d seconds", outgoing->timeout);
108 void finish_connecting(meshlink_handle_t *mesh, connection_t *c) {
109 logger(mesh, MESHLINK_INFO, "Connected to %s", c->name);
111 c->last_ping_time = mesh->loop.now.tv_sec;
112 c->status.connecting = false;
117 static void handle_meta_write(meshlink_handle_t *mesh, connection_t *c) {
118 if(c->outbuf.len <= c->outbuf.offset) {
122 ssize_t outlen = send(c->socket, c->outbuf.data + c->outbuf.offset, c->outbuf.len - c->outbuf.offset, MSG_NOSIGNAL);
125 if(!errno || errno == EPIPE) {
126 logger(mesh, MESHLINK_INFO, "Connection closed by %s", c->name);
127 } else if(sockwouldblock(sockerrno)) {
128 logger(mesh, MESHLINK_DEBUG, "Sending %lu bytes to %s would block", (unsigned long)(c->outbuf.len - c->outbuf.offset), c->name);
131 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));
134 terminate_connection(mesh, c, c->status.active);
138 buffer_read(&c->outbuf, outlen);
141 io_set(&mesh->loop, &c->io, IO_READ);
145 void flush_meta(meshlink_handle_t *mesh, connection_t *c) {
146 handle_meta_write(mesh, c);
149 static void handle_meta_io(event_loop_t *loop, void *data, int flags) {
150 meshlink_handle_t *mesh = loop->data;
151 connection_t *c = data;
153 if(c->status.connecting) {
154 c->status.connecting = false;
157 socklen_t len = sizeof(result);
158 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
161 finish_connecting(mesh, c);
163 logger(mesh, MESHLINK_ERROR, "Error while connecting to %s: %s", c->name, sockstrerror(result));
164 terminate_connection(mesh, c, false);
169 if(flags & IO_WRITE) {
170 handle_meta_write(mesh, c);
172 handle_meta_connection_data(mesh, c);
176 // Build a list of recently seen addresses.
177 static struct addrinfo *get_recent_addresses(node_t *n) {
178 struct addrinfo *ai = NULL;
179 struct addrinfo *aip;
181 for(int i = 0; i < 5; i++) {
182 if(!n->recent[i].sa.sa_family) {
186 // Create a new struct addrinfo, and put it at the end of the list.
187 struct addrinfo *nai = xzalloc(sizeof(*nai) + SALEN(n->recent[i].sa));
197 nai->ai_family = n->recent[i].sa.sa_family;
198 nai->ai_socktype = SOCK_STREAM;
199 nai->ai_protocol = IPPROTO_TCP;
200 nai->ai_addrlen = SALEN(n->recent[i].sa);
201 nai->ai_addr = (struct sockaddr *)(nai + 1);
202 memcpy(nai->ai_addr, &n->recent[i], nai->ai_addrlen);
208 // Free struct addrinfo list from get_known_addresses().
209 static void free_known_addresses(struct addrinfo *ai) {
210 for(struct addrinfo *aip = ai, *next; aip; aip = next) {
216 static bool get_next_outgoing_address(meshlink_handle_t *mesh, outgoing_t *outgoing) {
221 if(outgoing->state == OUTGOING_START) {
223 outgoing->state = OUTGOING_CANONICAL_RESOLVE;
226 if(outgoing->state == OUTGOING_CANONICAL_RESOLVE) {
227 node_t *n = outgoing->node;
229 if(n->canonical_address) {
230 char *address = xstrdup(n->canonical_address);
231 char *port = strchr(address, ' ');
235 outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
236 outgoing->aip = NULL;
237 outgoing->state = OUTGOING_CANONICAL;
239 logger(mesh, MESHLINK_ERROR, "Canonical address for %s is missing port number", n->name);
240 outgoing->state = OUTGOING_RECENT;
245 outgoing->state = OUTGOING_RECENT;
249 if(outgoing->state == OUTGOING_CANONICAL) {
251 outgoing->aip = outgoing->ai;
253 outgoing->aip = outgoing->aip->ai_next;
261 freeaddrinfo(outgoing->ai);
265 outgoing->aip = NULL;
266 outgoing->state = OUTGOING_END;
269 if(outgoing->state == OUTGOING_RECENT) {
271 outgoing->ai = get_recent_addresses(outgoing->node);
272 outgoing->aip = outgoing->ai;
274 outgoing->aip = outgoing->aip->ai_next;
281 free_known_addresses(outgoing->ai);
283 outgoing->aip = NULL;
284 outgoing->state = OUTGOING_END;
288 outgoing->state = OUTGOING_NO_KNOWN_ADDRESSES;
294 void do_outgoing_connection(meshlink_handle_t *mesh, outgoing_t *outgoing) {
297 if(!get_next_outgoing_address(mesh, outgoing)) {
298 if(outgoing->state == OUTGOING_CANONICAL_RESOLVE) {
299 /* We are waiting for a callback from the ADNS thread */
300 } else if(outgoing->state == OUTGOING_NO_KNOWN_ADDRESSES) {
301 logger(mesh, MESHLINK_ERROR, "No known addresses for %s", outgoing->node->name);
302 list_delete(mesh->outgoings, outgoing);
304 logger(mesh, MESHLINK_ERROR, "Could not set up a meta connection to %s", outgoing->node->name);
305 retry_outgoing(mesh, outgoing);
311 connection_t *c = new_connection();
312 c->outgoing = outgoing;
314 memcpy(&c->address, outgoing->aip->ai_addr, outgoing->aip->ai_addrlen);
316 if(mesh->log_level <= MESHLINK_INFO) {
317 char *hostname = sockaddr2hostname(&c->address);
318 logger(mesh, MESHLINK_INFO, "Trying to connect to %s at %s", outgoing->node->name, hostname);
322 c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
324 if(c->socket == -1) {
325 if(mesh->log_level <= MESHLINK_ERROR) {
326 char *hostname = sockaddr2hostname(&c->address);
327 logger(mesh, MESHLINK_ERROR, "Creating socket for %s at %s failed: %s", c->name, hostname, sockstrerror(sockerrno));
338 fcntl(c->socket, F_SETFD, FD_CLOEXEC);
341 #if defined(IPV6_V6ONLY)
343 if(c->address.sa.sa_family == AF_INET6) {
344 static const int option = 1;
345 setsockopt(c->socket, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
352 int result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
354 if(result == -1 && !sockinprogress(sockerrno)) {
355 if(mesh->log_level <= MESHLINK_ERROR) {
356 char *hostname = sockaddr2hostname(&c->address);
357 logger(mesh, MESHLINK_ERROR, "Could not connect to %s: %s", outgoing->node->name, sockstrerror(sockerrno));
365 /* Now that there is a working socket, fill in the rest and register this connection. */
367 c->status.connecting = true;
368 c->status.initiator = true;
369 c->name = xstrdup(outgoing->node->name);
370 c->last_ping_time = mesh->loop.now.tv_sec;
372 connection_add(mesh, c);
374 io_add(&mesh->loop, &c->io, handle_meta_io, c, c->socket, IO_READ | IO_WRITE);
377 void reset_outgoing(outgoing_t *outgoing) {
379 if(outgoing->state == OUTGOING_RECENT || outgoing->state == OUTGOING_KNOWN) {
380 free_known_addresses(outgoing->ai);
382 freeaddrinfo(outgoing->ai);
387 outgoing->aip = NULL;
388 outgoing->state = OUTGOING_START;
391 void setup_outgoing_connection(meshlink_handle_t *mesh, outgoing_t *outgoing) {
392 timeout_del(&mesh->loop, &outgoing->ev);
394 if(outgoing->node->connection) {
395 logger(mesh, MESHLINK_INFO, "Already connected to %s", outgoing->node->name);
397 outgoing->node->connection->outgoing = outgoing;
401 reset_outgoing(outgoing);
403 if(outgoing->node->status.blacklisted) {
407 if(mesh->connection_try_cb) {
408 mesh->connection_try_cb(mesh, (meshlink_node_t *)outgoing->node);
411 do_outgoing_connection(mesh, outgoing);
414 /// Delayed close of a filedescriptor.
415 static void tarpit(meshlink_handle_t *mesh, int fd) {
420 if(mesh->pits[mesh->next_pit]) {
421 closesocket(mesh->pits[mesh->next_pit]);
424 mesh->pits[mesh->next_pit++] = fd;
426 if(mesh->next_pit >= (int)(sizeof mesh->pits / sizeof mesh->pits[0])) {
432 accept a new tcp connect and create a
435 void handle_new_meta_connection(event_loop_t *loop, void *data, int flags) {
437 meshlink_handle_t *mesh = loop->data;
438 listen_socket_t *l = data;
442 socklen_t len = sizeof(sa);
444 memset(&sa, 0, sizeof(sa));
446 fd = accept(l->tcp.fd, &sa.sa, &len);
449 if(sockwouldblock(errno)) {
453 if(errno == EINVAL) { // TODO: check if Windows agrees
454 event_loop_stop(loop);
458 logger(mesh, MESHLINK_ERROR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
464 /* Rate limit incoming connections to max_connection_burst/second. */
466 if(mesh->loop.now.tv_sec != mesh->connection_burst_time) {
467 mesh->connection_burst_time = mesh->loop.now.tv_sec;
468 mesh->connection_burst = 0;
471 if(mesh->connection_burst >= max_connection_burst) {
476 mesh->connection_burst++;
478 // Accept the new connection
480 c = new_connection();
481 c->name = xstrdup("<unknown>");
485 c->last_ping_time = mesh->loop.now.tv_sec;
487 char *hostname = sockaddr2hostname(&sa);
488 logger(mesh, MESHLINK_INFO, "Connection from %s", hostname);
491 io_add(&mesh->loop, &c->io, handle_meta_io, c, c->socket, IO_READ);
495 connection_add(mesh, c);
497 c->allow_request = ID;
501 static void free_outgoing(outgoing_t *outgoing) {
502 meshlink_handle_t *mesh = outgoing->node->mesh;
504 timeout_del(&mesh->loop, &outgoing->ev);
507 if(outgoing->state == OUTGOING_RECENT || outgoing->state == OUTGOING_KNOWN) {
508 free_known_addresses(outgoing->ai);
510 freeaddrinfo(outgoing->ai);
517 void init_outgoings(meshlink_handle_t *mesh) {
518 mesh->outgoings = list_alloc((list_action_t)free_outgoing);
521 void exit_outgoings(meshlink_handle_t *mesh) {
522 if(mesh->outgoings) {
523 list_delete_list(mesh->outgoings);
524 mesh->outgoings = NULL;