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