]> git.meshlink.io Git - meshlink-tiny/blob - src/net_socket.c
29e37254986b2ab96b2f79ec09b2393f481951fe
[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 "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         buffer_read(&c->outbuf, outlen);
140
141         if(!c->outbuf.len) {
142                 io_set(&mesh->loop, &c->io, IO_READ);
143         }
144 }
145
146 void flush_meta(meshlink_handle_t *mesh, connection_t *c) {
147         handle_meta_write(mesh, c);
148 }
149
150 static void handle_meta_io(event_loop_t *loop, void *data, int flags) {
151         meshlink_handle_t *mesh = loop->data;
152         connection_t *c = data;
153
154         if(c->status.connecting) {
155                 c->status.connecting = false;
156
157                 int result;
158                 socklen_t len = sizeof(result);
159                 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
160
161                 if(!result) {
162                         finish_connecting(mesh, c);
163                 } else {
164                         logger(mesh, MESHLINK_ERROR, "Error while connecting to %s: %s", c->name, sockstrerror(result));
165                         terminate_connection(mesh, c, false);
166                         return;
167                 }
168         }
169
170         if(flags & IO_WRITE) {
171                 handle_meta_write(mesh, c);
172         } else {
173                 handle_meta_connection_data(mesh, c);
174         }
175 }
176
177 // Build a list of recently seen addresses.
178 static struct addrinfo *get_recent_addresses(node_t *n) {
179         struct addrinfo *ai = NULL;
180         struct addrinfo *aip;
181
182         for(int i = 0; i < 5; i++) {
183                 if(!n->recent[i].sa.sa_family) {
184                         break;
185                 }
186
187                 // Create a new struct addrinfo, and put it at the end of the list.
188                 struct addrinfo *nai = xzalloc(sizeof(*nai) + SALEN(n->recent[i].sa));
189
190                 if(!ai) {
191                         ai = nai;
192                 } else {
193                         aip->ai_next = nai;
194                 }
195
196                 aip = nai;
197
198                 nai->ai_family = n->recent[i].sa.sa_family;
199                 nai->ai_socktype = SOCK_STREAM;
200                 nai->ai_protocol = IPPROTO_TCP;
201                 nai->ai_addrlen = SALEN(n->recent[i].sa);
202                 nai->ai_addr = (struct sockaddr *)(nai + 1);
203                 memcpy(nai->ai_addr, &n->recent[i], nai->ai_addrlen);
204         }
205
206         return ai;
207 }
208
209 // Free struct addrinfo list from get_known_addresses().
210 static void free_known_addresses(struct addrinfo *ai) {
211         for(struct addrinfo *aip = ai, *next; aip; aip = next) {
212                 next = aip->ai_next;
213                 free(aip);
214         }
215 }
216
217 static void canonical_resolve_cb(meshlink_handle_t *mesh, char *host, char *serv, void *data, struct addrinfo *ai, int err) {
218         (void)serv;
219         (void)err;
220         node_t *n = data;
221
222         free(host);
223         free(serv);
224
225         for list_each(outgoing_t, outgoing, mesh->outgoings) {
226                 if(outgoing->node == n) {
227                         if(outgoing->state == OUTGOING_CANONICAL_RESOLVE) {
228                                 outgoing->ai = ai;
229                                 outgoing->aip = NULL;
230                                 outgoing->state = OUTGOING_CANONICAL;
231                                 do_outgoing_connection(mesh, outgoing);
232                         }
233
234                         return;
235                 }
236         }
237 }
238
239 static bool get_next_outgoing_address(meshlink_handle_t *mesh, outgoing_t *outgoing) {
240         (void)mesh;
241
242         bool start = false;
243
244         if(outgoing->state == OUTGOING_START) {
245                 start = true;
246                 outgoing->state = OUTGOING_CANONICAL_RESOLVE;
247         }
248
249         if(outgoing->state == OUTGOING_CANONICAL_RESOLVE) {
250                 node_t *n = outgoing->node;
251
252                 if(n->canonical_address) {
253                         char *address = xstrdup(n->canonical_address);
254                         char *port = strchr(address, ' ');
255
256                         if(port) {
257                                 *port++ = 0;
258                                 port = xstrdup(port);
259                                 adns_queue(mesh, address, port, canonical_resolve_cb, outgoing->node, 2);
260                                 return false;
261                         } else {
262                                 logger(mesh, MESHLINK_ERROR, "Canonical address for %s is missing port number", n->name);
263                                 free(address);
264                                 outgoing->state = OUTGOING_RECENT;
265                         }
266
267                 } else {
268                         outgoing->state = OUTGOING_RECENT;
269                 }
270         }
271
272         if(outgoing->state == OUTGOING_CANONICAL) {
273                 if(!outgoing->aip) {
274                         outgoing->aip = outgoing->ai;
275                 } else {
276                         outgoing->aip = outgoing->aip->ai_next;
277                 }
278
279                 if(outgoing->aip) {
280                         return true;
281                 }
282
283                 if(outgoing->ai) {
284                         freeaddrinfo(outgoing->ai);
285                 }
286
287                 outgoing->ai = NULL;
288                 outgoing->aip = NULL;
289                 outgoing->state = OUTGOING_END;
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_END;
308         }
309
310         if(start) {
311                 outgoing->state = OUTGOING_NO_KNOWN_ADDRESSES;
312         }
313
314         return false;
315 }
316
317 void do_outgoing_connection(meshlink_handle_t *mesh, outgoing_t *outgoing) {
318 begin:
319
320         if(!get_next_outgoing_address(mesh, outgoing)) {
321                 if(outgoing->state == OUTGOING_CANONICAL_RESOLVE) {
322                         /* We are waiting for a callback from the ADNS thread */
323                 } else if(outgoing->state == OUTGOING_NO_KNOWN_ADDRESSES) {
324                         logger(mesh, MESHLINK_ERROR, "No known addresses for %s", outgoing->node->name);
325                         list_delete(mesh->outgoings, outgoing);
326                 } else {
327                         logger(mesh, MESHLINK_ERROR, "Could not set up a meta connection to %s", outgoing->node->name);
328                         retry_outgoing(mesh, outgoing);
329                 }
330
331                 return;
332         }
333
334         connection_t *c = new_connection();
335         c->outgoing = outgoing;
336
337         memcpy(&c->address, outgoing->aip->ai_addr, outgoing->aip->ai_addrlen);
338
339         if(mesh->log_level <= MESHLINK_INFO) {
340                 char *hostname = sockaddr2hostname(&c->address);
341                 logger(mesh, MESHLINK_INFO, "Trying to connect to %s at %s", outgoing->node->name, hostname);
342                 free(hostname);
343         }
344
345         c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
346
347         if(c->socket == -1) {
348                 if(mesh->log_level <= MESHLINK_ERROR) {
349                         char *hostname = sockaddr2hostname(&c->address);
350                         logger(mesh, MESHLINK_ERROR, "Creating socket for %s at %s failed: %s", c->name, hostname, sockstrerror(sockerrno));
351                         free(hostname);
352                 }
353
354                 free_connection(c);
355                 goto begin;
356         }
357
358         configure_tcp(c);
359
360 #ifdef FD_CLOEXEC
361         fcntl(c->socket, F_SETFD, FD_CLOEXEC);
362 #endif
363
364 #if defined(IPV6_V6ONLY)
365
366         if(c->address.sa.sa_family == AF_INET6) {
367                 static const int option = 1;
368                 setsockopt(c->socket, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
369         }
370
371 #endif
372
373         /* Connect */
374
375         int result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
376
377         if(result == -1 && !sockinprogress(sockerrno)) {
378                 if(mesh->log_level <= MESHLINK_ERROR) {
379                         char *hostname = sockaddr2hostname(&c->address);
380                         logger(mesh, MESHLINK_ERROR, "Could not connect to %s: %s", outgoing->node->name, sockstrerror(sockerrno));
381                         free(hostname);
382                 }
383
384                 free_connection(c);
385                 goto begin;
386         }
387
388         /* Now that there is a working socket, fill in the rest and register this connection. */
389
390         c->status.connecting = true;
391         c->status.initiator = true;
392         c->name = xstrdup(outgoing->node->name);
393         c->last_ping_time = mesh->loop.now.tv_sec;
394
395         connection_add(mesh, c);
396
397         io_add(&mesh->loop, &c->io, handle_meta_io, c, c->socket, IO_READ | IO_WRITE);
398 }
399
400 void reset_outgoing(outgoing_t *outgoing) {
401         if(outgoing->ai) {
402                 if(outgoing->state == OUTGOING_RECENT || outgoing->state == OUTGOING_KNOWN) {
403                         free_known_addresses(outgoing->ai);
404                 } else {
405                         freeaddrinfo(outgoing->ai);
406                 }
407         }
408
409         outgoing->ai = NULL;
410         outgoing->aip = NULL;
411         outgoing->state = OUTGOING_START;
412 }
413
414 void setup_outgoing_connection(meshlink_handle_t *mesh, outgoing_t *outgoing) {
415         timeout_del(&mesh->loop, &outgoing->ev);
416
417         if(outgoing->node->connection) {
418                 logger(mesh, MESHLINK_INFO, "Already connected to %s", outgoing->node->name);
419
420                 outgoing->node->connection->outgoing = outgoing;
421                 return;
422         }
423
424         reset_outgoing(outgoing);
425
426         if(outgoing->node->status.blacklisted) {
427                 return;
428         }
429
430         if(mesh->connection_try_cb) {
431                 mesh->connection_try_cb(mesh, (meshlink_node_t *)outgoing->node);
432         }
433
434         do_outgoing_connection(mesh, outgoing);
435 }
436
437 /// Delayed close of a filedescriptor.
438 static void tarpit(meshlink_handle_t *mesh, int fd) {
439         if(!fd) {
440                 return;
441         }
442
443         if(mesh->pits[mesh->next_pit]) {
444                 closesocket(mesh->pits[mesh->next_pit]);
445         }
446
447         mesh->pits[mesh->next_pit++] = fd;
448
449         if(mesh->next_pit >= (int)(sizeof mesh->pits / sizeof mesh->pits[0])) {
450                 mesh->next_pit = 0;
451         }
452 }
453
454 /*
455   accept a new tcp connect and create a
456   new connection
457 */
458 void handle_new_meta_connection(event_loop_t *loop, void *data, int flags) {
459         (void)flags;
460         meshlink_handle_t *mesh = loop->data;
461         listen_socket_t *l = data;
462         connection_t *c;
463         sockaddr_t sa;
464         int fd;
465         socklen_t len = sizeof(sa);
466
467         memset(&sa, 0, sizeof(sa));
468
469         fd = accept(l->tcp.fd, &sa.sa, &len);
470
471         if(fd < 0) {
472                 if(sockwouldblock(errno)) {
473                         return;
474                 }
475
476                 if(errno == EINVAL) { // TODO: check if Windows agrees
477                         event_loop_stop(loop);
478                         return;
479                 }
480
481                 logger(mesh, MESHLINK_ERROR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
482                 return;
483         }
484
485         sockaddrunmap(&sa);
486
487         /* Rate limit incoming connections to max_connection_burst/second. */
488
489         if(mesh->loop.now.tv_sec != mesh->connection_burst_time) {
490                 mesh->connection_burst_time = mesh->loop.now.tv_sec;
491                 mesh->connection_burst = 0;
492         }
493
494         if(mesh->connection_burst >= max_connection_burst) {
495                 tarpit(mesh, fd);
496                 return;
497         }
498
499         mesh->connection_burst++;
500
501         // Accept the new connection
502
503         c = new_connection();
504         c->name = xstrdup("<unknown>");
505
506         c->address = sa;
507         c->socket = fd;
508         c->last_ping_time = mesh->loop.now.tv_sec;
509
510         char *hostname = sockaddr2hostname(&sa);
511         logger(mesh, MESHLINK_INFO, "Connection from %s", hostname);
512         free(hostname);
513
514         io_add(&mesh->loop, &c->io, handle_meta_io, c, c->socket, IO_READ);
515
516         configure_tcp(c);
517
518         connection_add(mesh, c);
519
520         c->allow_request = ID;
521         send_id(mesh, c);
522 }
523
524 static void free_outgoing(outgoing_t *outgoing) {
525         meshlink_handle_t *mesh = outgoing->node->mesh;
526
527         timeout_del(&mesh->loop, &outgoing->ev);
528
529         if(outgoing->ai) {
530                 if(outgoing->state == OUTGOING_RECENT || outgoing->state == OUTGOING_KNOWN) {
531                         free_known_addresses(outgoing->ai);
532                 } else {
533                         freeaddrinfo(outgoing->ai);
534                 }
535         }
536
537         free(outgoing);
538 }
539
540 void init_outgoings(meshlink_handle_t *mesh) {
541         mesh->outgoings = list_alloc((list_action_t)free_outgoing);
542 }
543
544 void exit_outgoings(meshlink_handle_t *mesh) {
545         if(mesh->outgoings) {
546                 list_delete_list(mesh->outgoings);
547                 mesh->outgoings = NULL;
548         }
549 }