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