]> git.meshlink.io Git - meshlink-tiny/blob - src/net_socket.c
7f575dcf8183464c5c89afa0eb1e68aa433213cf
[meshlink-tiny] / 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 #if defined(SO_NOSIGPIPE)
75         int nosigpipe = 1;
76         setsockopt(c->socket, SOL_SOCKET, SO_NOSIGPIPE, (void *)&nosigpipe, sizeof(nosigpipe));
77 #endif
78 }
79
80 static void retry_outgoing_handler(event_loop_t *loop, void *data) {
81         assert(data);
82
83         meshlink_handle_t *mesh = loop->data;
84         outgoing_t *outgoing = data;
85         setup_outgoing_connection(mesh, outgoing);
86 }
87
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;
91         } else {
92                 outgoing->timeout += 5;
93         }
94
95         int maxtimeout = mesh->dev_class_traits[outgoing->node->devclass].maxtimeout;
96
97         if(outgoing->timeout > maxtimeout) {
98                 outgoing->timeout = maxtimeout;
99         }
100
101         timeout_add(&mesh->loop, &outgoing->ev, retry_outgoing_handler, outgoing, &(struct timespec) {
102                 outgoing->timeout, prng(mesh, TIMER_FUDGE)
103         });
104
105         logger(mesh, MESHLINK_INFO, "Trying to re-establish outgoing connection in %d seconds", outgoing->timeout);
106 }
107
108 void finish_connecting(meshlink_handle_t *mesh, connection_t *c) {
109         logger(mesh, MESHLINK_INFO, "Connected to %s", c->name);
110
111         c->last_ping_time = mesh->loop.now.tv_sec;
112         c->status.connecting = false;
113
114         send_id(mesh, c);
115 }
116
117 static void handle_meta_write(meshlink_handle_t *mesh, connection_t *c) {
118         if(c->outbuf.len <= c->outbuf.offset) {
119                 return;
120         }
121
122         ssize_t outlen = send(c->socket, c->outbuf.data + c->outbuf.offset, c->outbuf.len - c->outbuf.offset, MSG_NOSIGNAL);
123
124         if(outlen <= 0) {
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);
129                         return;
130                 } else {
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));
132                 }
133
134                 terminate_connection(mesh, c, c->status.active);
135                 return;
136         }
137
138         buffer_read(&c->outbuf, outlen);
139
140         if(!c->outbuf.len) {
141                 io_set(&mesh->loop, &c->io, IO_READ);
142         }
143 }
144
145 void flush_meta(meshlink_handle_t *mesh, connection_t *c) {
146         handle_meta_write(mesh, c);
147 }
148
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;
152
153         if(c->status.connecting) {
154                 c->status.connecting = false;
155
156                 int result;
157                 socklen_t len = sizeof(result);
158                 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
159
160                 if(!result) {
161                         finish_connecting(mesh, c);
162                 } else {
163                         logger(mesh, MESHLINK_ERROR, "Error while connecting to %s: %s", c->name, sockstrerror(result));
164                         terminate_connection(mesh, c, false);
165                         return;
166                 }
167         }
168
169         if(flags & IO_WRITE) {
170                 handle_meta_write(mesh, c);
171         } else {
172                 handle_meta_connection_data(mesh, c);
173         }
174 }
175
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;
180
181         for(int i = 0; i < 5; i++) {
182                 if(!n->recent[i].sa.sa_family) {
183                         break;
184                 }
185
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));
188
189                 if(!ai) {
190                         ai = nai;
191                 } else {
192                         aip->ai_next = nai;
193                 }
194
195                 aip = nai;
196
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);
203         }
204
205         return ai;
206 }
207
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) {
211                 next = aip->ai_next;
212                 free(aip);
213         }
214 }
215
216 static bool get_next_outgoing_address(meshlink_handle_t *mesh, outgoing_t *outgoing) {
217         (void)mesh;
218
219         bool start = false;
220
221         if(outgoing->state == OUTGOING_START) {
222                 start = true;
223                 outgoing->state = OUTGOING_CANONICAL_RESOLVE;
224         }
225
226         if(outgoing->state == OUTGOING_CANONICAL_RESOLVE) {
227                 node_t *n = outgoing->node;
228
229                 if(n->canonical_address) {
230                         char *address = xstrdup(n->canonical_address);
231                         char *port = strchr(address, ' ');
232
233                         if(port) {
234                                 *port++ = 0;
235                                 outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
236                                 outgoing->aip = NULL;
237                                 outgoing->state = OUTGOING_CANONICAL;
238                         } else {
239                                 logger(mesh, MESHLINK_ERROR, "Canonical address for %s is missing port number", n->name);
240                                 outgoing->state = OUTGOING_RECENT;
241                         }
242
243                         free(address);
244                 } else {
245                         outgoing->state = OUTGOING_RECENT;
246                 }
247         }
248
249         if(outgoing->state == OUTGOING_CANONICAL) {
250                 if(!outgoing->aip) {
251                         outgoing->aip = outgoing->ai;
252                 } else {
253                         outgoing->aip = outgoing->aip->ai_next;
254                 }
255
256                 if(outgoing->aip) {
257                         return true;
258                 }
259
260                 if(outgoing->ai) {
261                         freeaddrinfo(outgoing->ai);
262                 }
263
264                 outgoing->ai = NULL;
265                 outgoing->aip = NULL;
266                 outgoing->state = OUTGOING_END;
267         }
268
269         if(outgoing->state == OUTGOING_RECENT) {
270                 if(!outgoing->aip) {
271                         outgoing->ai = get_recent_addresses(outgoing->node);
272                         outgoing->aip = outgoing->ai;
273                 } else {
274                         outgoing->aip = outgoing->aip->ai_next;
275                 }
276
277                 if(outgoing->aip) {
278                         return true;
279                 }
280
281                 free_known_addresses(outgoing->ai);
282                 outgoing->ai = NULL;
283                 outgoing->aip = NULL;
284                 outgoing->state = OUTGOING_END;
285         }
286
287         if(start) {
288                 outgoing->state = OUTGOING_NO_KNOWN_ADDRESSES;
289         }
290
291         return false;
292 }
293
294 void do_outgoing_connection(meshlink_handle_t *mesh, outgoing_t *outgoing) {
295 begin:
296
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);
303                 } else {
304                         logger(mesh, MESHLINK_ERROR, "Could not set up a meta connection to %s", outgoing->node->name);
305                         retry_outgoing(mesh, outgoing);
306                 }
307
308                 return;
309         }
310
311         connection_t *c = new_connection();
312         c->outgoing = outgoing;
313
314         memcpy(&c->address, outgoing->aip->ai_addr, outgoing->aip->ai_addrlen);
315
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);
319                 free(hostname);
320         }
321
322         c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
323
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));
328                         free(hostname);
329                 }
330
331                 free_connection(c);
332                 goto begin;
333         }
334
335         configure_tcp(c);
336
337 #ifdef FD_CLOEXEC
338         fcntl(c->socket, F_SETFD, FD_CLOEXEC);
339 #endif
340
341 #if defined(IPV6_V6ONLY)
342
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));
346         }
347
348 #endif
349
350         /* Connect */
351
352         int result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
353
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));
358                         free(hostname);
359                 }
360
361                 free_connection(c);
362                 goto begin;
363         }
364
365         /* Now that there is a working socket, fill in the rest and register this connection. */
366
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;
371
372         connection_add(mesh, c);
373
374         io_add(&mesh->loop, &c->io, handle_meta_io, c, c->socket, IO_READ | IO_WRITE);
375 }
376
377 void reset_outgoing(outgoing_t *outgoing) {
378         if(outgoing->ai) {
379                 if(outgoing->state == OUTGOING_RECENT || outgoing->state == OUTGOING_KNOWN) {
380                         free_known_addresses(outgoing->ai);
381                 } else {
382                         freeaddrinfo(outgoing->ai);
383                 }
384         }
385
386         outgoing->ai = NULL;
387         outgoing->aip = NULL;
388         outgoing->state = OUTGOING_START;
389 }
390
391 void setup_outgoing_connection(meshlink_handle_t *mesh, outgoing_t *outgoing) {
392         timeout_del(&mesh->loop, &outgoing->ev);
393
394         if(outgoing->node->connection) {
395                 logger(mesh, MESHLINK_INFO, "Already connected to %s", outgoing->node->name);
396
397                 outgoing->node->connection->outgoing = outgoing;
398                 return;
399         }
400
401         reset_outgoing(outgoing);
402
403         if(outgoing->node->status.blacklisted) {
404                 return;
405         }
406
407         if(mesh->connection_try_cb) {
408                 mesh->connection_try_cb(mesh, (meshlink_node_t *)outgoing->node);
409         }
410
411         do_outgoing_connection(mesh, outgoing);
412 }
413
414 /// Delayed close of a filedescriptor.
415 static void tarpit(meshlink_handle_t *mesh, int fd) {
416         if(!fd) {
417                 return;
418         }
419
420         if(mesh->pits[mesh->next_pit]) {
421                 closesocket(mesh->pits[mesh->next_pit]);
422         }
423
424         mesh->pits[mesh->next_pit++] = fd;
425
426         if(mesh->next_pit >= (int)(sizeof mesh->pits / sizeof mesh->pits[0])) {
427                 mesh->next_pit = 0;
428         }
429 }
430
431 /*
432   accept a new tcp connect and create a
433   new connection
434 */
435 void handle_new_meta_connection(event_loop_t *loop, void *data, int flags) {
436         (void)flags;
437         meshlink_handle_t *mesh = loop->data;
438         listen_socket_t *l = data;
439         connection_t *c;
440         sockaddr_t sa;
441         int fd;
442         socklen_t len = sizeof(sa);
443
444         memset(&sa, 0, sizeof(sa));
445
446         fd = accept(l->tcp.fd, &sa.sa, &len);
447
448         if(fd < 0) {
449                 if(sockwouldblock(errno)) {
450                         return;
451                 }
452
453                 if(errno == EINVAL) { // TODO: check if Windows agrees
454                         event_loop_stop(loop);
455                         return;
456                 }
457
458                 logger(mesh, MESHLINK_ERROR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
459                 return;
460         }
461
462         sockaddrunmap(&sa);
463
464         /* Rate limit incoming connections to max_connection_burst/second. */
465
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;
469         }
470
471         if(mesh->connection_burst >= max_connection_burst) {
472                 tarpit(mesh, fd);
473                 return;
474         }
475
476         mesh->connection_burst++;
477
478         // Accept the new connection
479
480         c = new_connection();
481         c->name = xstrdup("<unknown>");
482
483         c->address = sa;
484         c->socket = fd;
485         c->last_ping_time = mesh->loop.now.tv_sec;
486
487         char *hostname = sockaddr2hostname(&sa);
488         logger(mesh, MESHLINK_INFO, "Connection from %s", hostname);
489         free(hostname);
490
491         io_add(&mesh->loop, &c->io, handle_meta_io, c, c->socket, IO_READ);
492
493         configure_tcp(c);
494
495         connection_add(mesh, c);
496
497         c->allow_request = ID;
498         send_id(mesh, c);
499 }
500
501 static void free_outgoing(outgoing_t *outgoing) {
502         meshlink_handle_t *mesh = outgoing->node->mesh;
503
504         timeout_del(&mesh->loop, &outgoing->ev);
505
506         if(outgoing->ai) {
507                 if(outgoing->state == OUTGOING_RECENT || outgoing->state == OUTGOING_KNOWN) {
508                         free_known_addresses(outgoing->ai);
509                 } else {
510                         freeaddrinfo(outgoing->ai);
511                 }
512         }
513
514         free(outgoing);
515 }
516
517 void init_outgoings(meshlink_handle_t *mesh) {
518         mesh->outgoings = list_alloc((list_action_t)free_outgoing);
519 }
520
521 void exit_outgoings(meshlink_handle_t *mesh) {
522         if(mesh->outgoings) {
523                 list_delete_list(mesh->outgoings);
524                 mesh->outgoings = NULL;
525         }
526 }