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