]> git.meshlink.io Git - meshlink/blob - src/net_socket.c
6af4f7386bcc37530057fc5251de2ff0103a1137
[meshlink] / src / net_socket.c
1 /*
2     net_socket.c -- Handle various kinds of sockets.
3     Copyright (C) 2014-2017 Guus Sliepen <guus@meshlink.io>
4
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.
9
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.
14
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.
18 */
19
20 #include "system.h"
21
22 #include "adns.h"
23 #include "conf.h"
24 #include "connection.h"
25 #include "list.h"
26 #include "logger.h"
27 #include "meshlink_internal.h"
28 #include "meta.h"
29 #include "net.h"
30 #include "netutl.h"
31 #include "protocol.h"
32 #include "utils.h"
33 #include "xalloc.h"
34
35 /* Needed on Mac OS/X */
36 #ifndef SOL_TCP
37 #define SOL_TCP IPPROTO_TCP
38 #endif
39
40 #ifndef MSG_NOSIGNAL
41 #define MSG_NOSIGNAL 0
42 #endif
43
44 static const int max_connection_burst = 100;
45
46 /* Setup sockets */
47
48 static void configure_tcp(connection_t *c) {
49 #ifdef O_NONBLOCK
50         int flags = fcntl(c->socket, F_GETFL);
51
52         if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0) {
53                 logger(c->mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "fcntl", strerror(errno));
54         }
55
56 #elif defined(WIN32)
57         unsigned long arg = 1;
58
59         if(ioctlsocket(c->socket, FIONBIO, &arg) != 0) {
60                 logger(c->mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
61         }
62
63 #endif
64
65 #if defined(SOL_TCP) && defined(TCP_NODELAY)
66         int nodelay = 1;
67         setsockopt(c->socket, SOL_TCP, TCP_NODELAY, (void *)&nodelay, sizeof(nodelay));
68 #endif
69
70 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
71         int lowdelay = IPTOS_LOWDELAY;
72         setsockopt(c->socket, IPPROTO_IP, IP_TOS, (void *)&lowdelay, sizeof(lowdelay));
73 #endif
74
75 #if defined(SO_NOSIGPIPE)
76         int nosigpipe = 1;
77         setsockopt(c->socket, SOL_SOCKET, SO_NOSIGPIPE, (void *)&nosigpipe, sizeof(nosigpipe));
78 #endif
79 }
80
81 static void retry_outgoing_handler(event_loop_t *loop, void *data) {
82         assert(data);
83
84         meshlink_handle_t *mesh = loop->data;
85         outgoing_t *outgoing = data;
86         setup_outgoing_connection(mesh, outgoing);
87 }
88
89 void retry_outgoing(meshlink_handle_t *mesh, outgoing_t *outgoing) {
90         if(!mesh->reachable && mesh->loop.now.tv_sec < mesh->last_unreachable + mesh->dev_class_traits[mesh->devclass].fast_retry_period) {
91                 outgoing->timeout = 1;
92         } else {
93                 outgoing->timeout += 5;
94         }
95
96         if(outgoing->timeout > mesh->dev_class_traits[mesh->devclass].maxtimeout) {
97                 outgoing->timeout = mesh->dev_class_traits[mesh->devclass].maxtimeout;
98         }
99
100         timeout_add(&mesh->loop, &outgoing->ev, retry_outgoing_handler, outgoing, &(struct timespec) {
101                 outgoing->timeout, prng(mesh, TIMER_FUDGE)
102         });
103
104         logger(mesh, MESHLINK_INFO, "Trying to re-establish outgoing connection in %d seconds", outgoing->timeout);
105 }
106
107 void finish_connecting(meshlink_handle_t *mesh, connection_t *c) {
108         logger(mesh, MESHLINK_INFO, "Connected to %s", c->name);
109
110         c->last_ping_time = mesh->loop.now.tv_sec;
111         c->status.connecting = false;
112
113         send_id(mesh, c);
114 }
115
116 static void handle_meta_write(meshlink_handle_t *mesh, connection_t *c) {
117         if(c->outbuf.len <= c->outbuf.offset) {
118                 return;
119         }
120
121         ssize_t outlen = send(c->socket, c->outbuf.data + c->outbuf.offset, c->outbuf.len - c->outbuf.offset, MSG_NOSIGNAL);
122
123         if(outlen <= 0) {
124                 if(!errno || errno == EPIPE) {
125                         logger(mesh, MESHLINK_INFO, "Connection closed by %s", c->name);
126                 } else if(sockwouldblock(sockerrno)) {
127                         logger(mesh, MESHLINK_DEBUG, "Sending %lu bytes to %s would block", (unsigned long)(c->outbuf.len - c->outbuf.offset), c->name);
128                         return;
129                 } else {
130                         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));
131                 }
132
133                 terminate_connection(mesh, c, c->status.active);
134                 return;
135         }
136
137         buffer_read(&c->outbuf, outlen);
138
139         if(!c->outbuf.len) {
140                 io_set(&mesh->loop, &c->io, IO_READ);
141         }
142 }
143
144 static void handle_meta_io(event_loop_t *loop, void *data, int flags) {
145         meshlink_handle_t *mesh = loop->data;
146         connection_t *c = data;
147
148         if(c->status.connecting) {
149                 c->status.connecting = false;
150
151                 int result;
152                 socklen_t len = sizeof(result);
153                 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
154
155                 if(!result) {
156                         finish_connecting(mesh, c);
157                 } else {
158                         logger(mesh, MESHLINK_DEBUG, "Error while connecting to %s: %s", c->name, sockstrerror(result));
159                         terminate_connection(mesh, c, false);
160                         return;
161                 }
162         }
163
164         if(flags & IO_WRITE) {
165                 handle_meta_write(mesh, c);
166         } else {
167                 handle_meta_connection_data(mesh, c);
168         }
169 }
170
171 // Find edges pointing to this node, and use them to build a list of unique, known addresses.
172 static struct addrinfo *get_known_addresses(node_t *n) {
173         struct addrinfo *ai = NULL;
174
175         for splay_each(edge_t, e, n->edge_tree) {
176                 if(!e->reverse) {
177                         continue;
178                 }
179
180                 bool found = false;
181
182                 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
183                         if(!sockaddrcmp(&e->reverse->address, (sockaddr_t *)aip->ai_addr)) {
184                                 found = true;
185                                 break;
186                         }
187                 }
188
189                 if(found) {
190                         continue;
191                 }
192
193                 // Create a new struct addrinfo, and put it at the head of the list.
194                 struct addrinfo *nai = xzalloc(sizeof(*nai) + SALEN(e->reverse->address.sa));
195                 nai->ai_next = ai;
196                 ai = nai;
197
198                 ai->ai_family = e->reverse->address.sa.sa_family;
199                 ai->ai_socktype = SOCK_STREAM;
200                 ai->ai_protocol = IPPROTO_TCP;
201                 ai->ai_addrlen = SALEN(e->reverse->address.sa);
202                 ai->ai_addr = (struct sockaddr *)(nai + 1);
203                 memcpy(ai->ai_addr, &e->reverse->address, ai->ai_addrlen);
204         }
205
206         return ai;
207 }
208
209 // Build a list of recently seen addresses.
210 static struct addrinfo *get_recent_addresses(node_t *n) {
211         struct addrinfo *ai = NULL;
212         struct addrinfo *aip;
213
214         for(int i = 0; i < 5; i++) {
215                 if(!n->recent[i].sa.sa_family) {
216                         break;
217                 }
218
219                 // Create a new struct addrinfo, and put it at the end of the list.
220                 struct addrinfo *nai = xzalloc(sizeof(*nai) + SALEN(n->recent[i].sa));
221
222                 if(!ai) {
223                         ai = nai;
224                 } else {
225                         aip->ai_next = nai;
226                 }
227
228                 aip = nai;
229
230                 nai->ai_family = n->recent[i].sa.sa_family;
231                 nai->ai_socktype = SOCK_STREAM;
232                 nai->ai_protocol = IPPROTO_TCP;
233                 nai->ai_addrlen = SALEN(n->recent[i].sa);
234                 nai->ai_addr = (struct sockaddr *)(nai + 1);
235                 memcpy(nai->ai_addr, &n->recent[i], nai->ai_addrlen);
236         }
237
238         return ai;
239 }
240
241 // Free struct addrinfo list from get_known_addresses().
242 static void free_known_addresses(struct addrinfo *ai) {
243         for(struct addrinfo *aip = ai, *next; aip; aip = next) {
244                 next = aip->ai_next;
245                 free(aip);
246         }
247 }
248
249 static void canonical_resolve_cb(meshlink_handle_t *mesh, char *host, char *serv, void *data, struct addrinfo *ai, int err) {
250         (void)serv;
251         (void)err;
252         node_t *n = data;
253
254         free(host);
255         free(serv);
256
257         for list_each(outgoing_t, outgoing, mesh->outgoings) {
258                 if(outgoing->node == n) {
259                         if(outgoing->state == OUTGOING_CANONICAL_RESOLVE) {
260                                 outgoing->ai = ai;
261                                 outgoing->aip = NULL;
262                                 outgoing->state = OUTGOING_CANONICAL;
263                                 do_outgoing_connection(mesh, outgoing);
264                         }
265
266                         return;
267                 }
268         }
269 }
270
271 static bool get_next_outgoing_address(meshlink_handle_t *mesh, outgoing_t *outgoing) {
272         (void)mesh;
273
274         bool start = false;
275
276         if(outgoing->state == OUTGOING_START) {
277                 start = true;
278                 outgoing->state = OUTGOING_CANONICAL_RESOLVE;
279         }
280
281         if(outgoing->state == OUTGOING_CANONICAL_RESOLVE) {
282                 node_t *n = outgoing->node;
283
284                 if(n->canonical_address) {
285                         char *address = xstrdup(n->canonical_address);
286                         char *port = strchr(address, ' ');
287
288                         if(port) {
289                                 *port++ = 0;
290                                 port = xstrdup(port);
291                                 adns_queue(mesh, address, port, canonical_resolve_cb, outgoing->node, 2);
292                                 return false;
293                         } else {
294                                 logger(mesh, MESHLINK_ERROR, "Canonical address for %s is missing port number", n->name);
295                                 free(address);
296                                 outgoing->state = OUTGOING_RECENT;
297                         }
298
299                 } else {
300                         outgoing->state = OUTGOING_RECENT;
301                 }
302         }
303
304         if(outgoing->state == OUTGOING_CANONICAL) {
305                 if(!outgoing->aip) {
306                         outgoing->aip = outgoing->ai;
307                 } else {
308                         outgoing->aip = outgoing->aip->ai_next;
309                 }
310
311                 if(outgoing->aip) {
312                         return true;
313                 }
314
315                 if(outgoing->ai) {
316                         freeaddrinfo(outgoing->ai);
317                 }
318
319                 outgoing->ai = NULL;
320                 outgoing->aip = NULL;
321                 outgoing->state = OUTGOING_RECENT;
322         }
323
324         if(outgoing->state == OUTGOING_RECENT) {
325                 if(!outgoing->aip) {
326                         outgoing->ai = get_recent_addresses(outgoing->node);
327                         outgoing->aip = outgoing->ai;
328                 } else {
329                         outgoing->aip = outgoing->aip->ai_next;
330                 }
331
332                 if(outgoing->aip) {
333                         return true;
334                 }
335
336                 free_known_addresses(outgoing->ai);
337                 outgoing->ai = NULL;
338                 outgoing->aip = NULL;
339                 outgoing->state = OUTGOING_KNOWN;
340         }
341
342         if(outgoing->state == OUTGOING_KNOWN) {
343                 if(!outgoing->aip) {
344                         outgoing->ai = get_known_addresses(outgoing->node);
345                         outgoing->aip = outgoing->ai;
346                 } else {
347                         outgoing->aip = outgoing->aip->ai_next;
348                 }
349
350                 if(outgoing->aip) {
351                         return true;
352                 }
353
354                 free_known_addresses(outgoing->ai);
355                 outgoing->ai = NULL;
356                 outgoing->aip = NULL;
357                 outgoing->state = OUTGOING_END;
358         }
359
360         if(start) {
361                 outgoing->state = OUTGOING_NO_KNOWN_ADDRESSES;
362         }
363
364         return false;
365 }
366
367 void do_outgoing_connection(meshlink_handle_t *mesh, outgoing_t *outgoing) {
368 begin:
369
370         if(!get_next_outgoing_address(mesh, outgoing)) {
371                 if(outgoing->state == OUTGOING_CANONICAL_RESOLVE) {
372                         /* We are waiting for a callback from the ADNS thread */
373                 } else if(outgoing->state == OUTGOING_NO_KNOWN_ADDRESSES) {
374                         logger(mesh, MESHLINK_ERROR, "No known addresses for %s", outgoing->node->name);
375                 } else {
376                         logger(mesh, MESHLINK_ERROR, "Could not set up a meta connection to %s", outgoing->node->name);
377                         retry_outgoing(mesh, outgoing);
378                 }
379
380                 return;
381         }
382
383         connection_t *c = new_connection();
384         c->outgoing = outgoing;
385
386         memcpy(&c->address, outgoing->aip->ai_addr, outgoing->aip->ai_addrlen);
387
388         if(mesh->log_level <= MESHLINK_INFO) {
389                 char *hostname = sockaddr2hostname(&c->address);
390                 logger(mesh, MESHLINK_INFO, "Trying to connect to %s at %s", outgoing->node->name, hostname);
391                 free(hostname);
392         }
393
394         c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
395
396         if(c->socket == -1) {
397                 if(mesh->log_level <= MESHLINK_ERROR) {
398                         char *hostname = sockaddr2hostname(&c->address);
399                         logger(mesh, MESHLINK_ERROR, "Creating socket for %s at %s failed: %s", c->name, hostname, sockstrerror(sockerrno));
400                         free(hostname);
401                 }
402
403                 free_connection(c);
404                 goto begin;
405         }
406
407         configure_tcp(c);
408
409 #ifdef FD_CLOEXEC
410         fcntl(c->socket, F_SETFD, FD_CLOEXEC);
411 #endif
412
413 #if defined(IPV6_V6ONLY)
414
415         if(c->address.sa.sa_family == AF_INET6) {
416                 static const int option = 1;
417                 setsockopt(c->socket, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
418         }
419
420 #endif
421
422         /* Connect */
423
424         int result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
425
426         if(result == -1 && !sockinprogress(sockerrno)) {
427                 if(mesh->log_level <= MESHLINK_ERROR) {
428                         char *hostname = sockaddr2hostname(&c->address);
429                         logger(mesh, MESHLINK_ERROR, "Could not connect to %s: %s", outgoing->node->name, sockstrerror(sockerrno));
430                         free(hostname);
431                 }
432
433                 free_connection(c);
434                 goto begin;
435         }
436
437         /* Now that there is a working socket, fill in the rest and register this connection. */
438
439         c->status.connecting = true;
440         c->status.initiator = true;
441         c->name = xstrdup(outgoing->node->name);
442         c->last_ping_time = mesh->loop.now.tv_sec;
443
444         connection_add(mesh, c);
445
446         io_add(&mesh->loop, &c->io, handle_meta_io, c, c->socket, IO_READ | IO_WRITE);
447 }
448
449 void reset_outgoing(outgoing_t *outgoing) {
450         if(outgoing->ai) {
451                 if(outgoing->state == OUTGOING_RECENT || outgoing->state == OUTGOING_KNOWN) {
452                         free_known_addresses(outgoing->ai);
453                 } else {
454                         freeaddrinfo(outgoing->ai);
455                 }
456         }
457
458         outgoing->ai = NULL;
459         outgoing->aip = NULL;
460         outgoing->state = OUTGOING_START;
461 }
462
463 void setup_outgoing_connection(meshlink_handle_t *mesh, outgoing_t *outgoing) {
464         timeout_del(&mesh->loop, &outgoing->ev);
465
466         if(outgoing->node->connection) {
467                 logger(mesh, MESHLINK_INFO, "Already connected to %s", outgoing->node->name);
468
469                 outgoing->node->connection->outgoing = outgoing;
470                 return;
471         }
472
473         reset_outgoing(outgoing);
474
475         if(outgoing->node->status.blacklisted) {
476                 return;
477         }
478
479         if(mesh->connection_try_cb) {
480                 mesh->connection_try_cb(mesh, (meshlink_node_t *)outgoing->node);
481         }
482
483         do_outgoing_connection(mesh, outgoing);
484 }
485
486 /// Delayed close of a filedescriptor.
487 static void tarpit(meshlink_handle_t *mesh, int fd) {
488         if(!fd) {
489                 return;
490         }
491
492         if(mesh->pits[mesh->next_pit]) {
493                 closesocket(mesh->pits[mesh->next_pit]);
494         }
495
496         mesh->pits[mesh->next_pit++] = fd;
497
498         if(mesh->next_pit >= (int)(sizeof mesh->pits / sizeof mesh->pits[0])) {
499                 mesh->next_pit = 0;
500         }
501 }
502
503 /*
504   accept a new tcp connect and create a
505   new connection
506 */
507 void handle_new_meta_connection(event_loop_t *loop, void *data, int flags) {
508         (void)flags;
509         meshlink_handle_t *mesh = loop->data;
510         listen_socket_t *l = data;
511         connection_t *c;
512         sockaddr_t sa;
513         int fd;
514         socklen_t len = sizeof(sa);
515
516         memset(&sa, 0, sizeof(sa));
517
518         fd = accept(l->tcp.fd, &sa.sa, &len);
519
520         if(fd < 0) {
521                 if(errno == EINVAL) { // TODO: check if Windows agrees
522                         event_loop_stop(loop);
523                         return;
524                 }
525
526                 logger(mesh, MESHLINK_ERROR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
527                 return;
528         }
529
530         sockaddrunmap(&sa);
531
532         /* Rate limit incoming connections to max_connection_burst/second. */
533
534         if(mesh->loop.now.tv_sec != mesh->connection_burst_time) {
535                 mesh->connection_burst_time = mesh->loop.now.tv_sec;
536                 mesh->connection_burst = 0;
537         }
538
539         if(mesh->connection_burst >= max_connection_burst) {
540                 tarpit(mesh, fd);
541                 return;
542         }
543
544         mesh->connection_burst++;
545
546         // Accept the new connection
547
548         c = new_connection();
549         c->name = xstrdup("<unknown>");
550
551         c->address = sa;
552         c->socket = fd;
553         c->last_ping_time = mesh->loop.now.tv_sec;
554
555         char *hostname = sockaddr2hostname(&sa);
556         logger(mesh, MESHLINK_INFO, "Connection from %s", hostname);
557         free(hostname);
558
559         io_add(&mesh->loop, &c->io, handle_meta_io, c, c->socket, IO_READ);
560
561         configure_tcp(c);
562
563         connection_add(mesh, c);
564
565         c->allow_request = ID;
566         send_id(mesh, c);
567 }
568
569 static void free_outgoing(outgoing_t *outgoing) {
570         meshlink_handle_t *mesh = outgoing->node->mesh;
571
572         timeout_del(&mesh->loop, &outgoing->ev);
573
574         if(outgoing->ai) {
575                 if(outgoing->state == OUTGOING_RECENT || outgoing->state == OUTGOING_KNOWN) {
576                         free_known_addresses(outgoing->ai);
577                 } else {
578                         freeaddrinfo(outgoing->ai);
579                 }
580         }
581
582         free(outgoing);
583 }
584
585 void init_outgoings(meshlink_handle_t *mesh) {
586         mesh->outgoings = list_alloc((list_action_t)free_outgoing);
587 }
588
589 void exit_outgoings(meshlink_handle_t *mesh) {
590         if(mesh->outgoings) {
591                 list_delete_list(mesh->outgoings);
592                 mesh->outgoings = NULL;
593         }
594 }