]> git.meshlink.io Git - meshlink-tiny/blob - src/net_setup.c
Remove graph, edges and communication via UDP.
[meshlink-tiny] / src / net_setup.c
1 /*
2     net_setup.c -- Setup.
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 "ecdsa.h"
25 #include "logger.h"
26 #include "meshlink_internal.h"
27 #include "net.h"
28 #include "netutl.h"
29 #include "packmsg.h"
30 #include "protocol.h"
31 #include "route.h"
32 #include "utils.h"
33 #include "xalloc.h"
34 #include "submesh.h"
35
36 /// Helper function to start parsing a host config file
37 static bool node_get_config(meshlink_handle_t *mesh, node_t *n, config_t *config, packmsg_input_t *in) {
38         if(!config_read(mesh, "current", n->name, config, mesh->config_key)) {
39                 return false;
40         }
41
42         in->ptr = config->buf;
43         in->len = config->len;
44
45         uint32_t version = packmsg_get_uint32(in);
46
47         if(version != MESHLINK_CONFIG_VERSION) {
48                 logger(mesh, MESHLINK_ERROR, "Invalid config file for node %s", n->name);
49                 config_free(config);
50                 return false;
51         }
52
53         const char *name;
54         uint32_t len = packmsg_get_str_raw(in, &name);
55
56         if(len != strlen(n->name) || !name || strncmp(name, n->name, len)) {
57                 logger(mesh, MESHLINK_ERROR, "Invalid config file for node %s", n->name);
58                 config_free(config);
59                 return false;
60         }
61
62         return true;
63 }
64
65 /// Read the public key from a host config file. Used whenever we need to start an SPTPS session.
66 bool node_read_public_key(meshlink_handle_t *mesh, node_t *n) {
67         if(ecdsa_active(n->ecdsa)) {
68                 return true;
69         }
70
71         config_t config;
72         packmsg_input_t in;
73
74         if(!node_get_config(mesh, n, &config, &in)) {
75                 return false;
76         }
77
78         packmsg_skip_element(&in); /* submesh */
79         packmsg_get_int32(&in); /* devclass */
80         packmsg_get_bool(&in); /* blacklisted */
81
82         const void *key;
83         uint32_t len = packmsg_get_bin_raw(&in, &key);
84
85         if(len != 32) {
86                 config_free(&config);
87                 return false;
88         }
89
90         n->ecdsa = ecdsa_set_public_key(key);
91
92         // While we are at it, read known address information
93         if(!n->canonical_address) {
94                 n->canonical_address = packmsg_get_str_dup(&in);
95
96                 if(!*n->canonical_address) {
97                         free(n->canonical_address);
98                         n->canonical_address = NULL;
99                 }
100         } else {
101                 packmsg_skip_element(&in);
102         }
103
104         // Append any known addresses in the config file to the list we currently have
105         uint32_t known_count = 0;
106
107         for(uint32_t i = 0; i < MAX_RECENT; i++) {
108                 if(n->recent[i].sa.sa_family) {
109                         known_count++;
110                 }
111         }
112
113         uint32_t count = packmsg_get_array(&in);
114
115         for(uint32_t i = 0; i < count; i++) {
116                 if(i < MAX_RECENT - known_count) {
117                         n->recent[i + known_count] = packmsg_get_sockaddr(&in);
118                 } else {
119                         packmsg_skip_element(&in);
120                 }
121         }
122
123         packmsg_skip_element(&in); // last_reachable
124         packmsg_skip_element(&in); // last_unreachable
125
126         config_free(&config);
127         return true;
128 }
129
130 /// Fill in node details from a config blob.
131 bool node_read_from_config(meshlink_handle_t *mesh, node_t *n, const config_t *config) {
132         if(n->canonical_address) {
133                 return true;
134         }
135
136         packmsg_input_t in = {config->buf, config->len};
137         uint32_t version = packmsg_get_uint32(&in);
138
139         if(version != MESHLINK_CONFIG_VERSION) {
140                 return false;
141         }
142
143         char *name = packmsg_get_str_dup(&in);
144
145         if(!name) {
146                 return false;
147         }
148
149         if(n->name) {
150                 if(strcmp(n->name, name)) {
151                         free(name);
152                         return false;
153                 }
154
155                 free(name);
156         } else {
157                 n->name = name;
158         }
159
160         char *submesh_name = packmsg_get_str_dup(&in);
161
162         if(!strcmp(submesh_name, CORE_MESH)) {
163                 free(submesh_name);
164                 n->submesh = NULL;
165         } else {
166                 n->submesh = lookup_or_create_submesh(mesh, submesh_name);
167                 free(submesh_name);
168
169                 if(!n->submesh) {
170                         return false;
171                 }
172         }
173
174         n->devclass = packmsg_get_int32(&in);
175         n->status.blacklisted = packmsg_get_bool(&in);
176         const void *key;
177         uint32_t len = packmsg_get_bin_raw(&in, &key);
178
179         if(len) {
180                 if(len != 32) {
181                         return false;
182                 }
183
184                 if(!ecdsa_active(n->ecdsa)) {
185                         n->ecdsa = ecdsa_set_public_key(key);
186                 }
187         }
188
189         n->canonical_address = packmsg_get_str_dup(&in);
190
191         if(!*n->canonical_address) {
192                 free(n->canonical_address);
193                 n->canonical_address = NULL;
194         }
195
196         uint32_t count = packmsg_get_array(&in);
197
198         for(uint32_t i = 0; i < count; i++) {
199                 if(i < MAX_RECENT) {
200                         n->recent[i] = packmsg_get_sockaddr(&in);
201                 } else {
202                         packmsg_skip_element(&in);
203                 }
204         }
205
206         packmsg_skip_element(&in); // last_reachable
207         packmsg_skip_element(&in); // last_unreachable
208
209         return packmsg_done(&in);
210 }
211
212 bool node_write_config(meshlink_handle_t *mesh, node_t *n, bool new_key) {
213         if(!mesh->confbase) {
214                 return true;
215         }
216
217         switch(mesh->storage_policy) {
218         case MESHLINK_STORAGE_KEYS_ONLY:
219                 if(!new_key) {
220                         return true;
221                 }
222
223                 break;
224
225         case MESHLINK_STORAGE_DISABLED:
226                 return true;
227
228         default:
229                 break;
230         }
231
232         uint8_t buf[4096];
233         packmsg_output_t out = {buf, sizeof(buf)};
234
235         packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
236         packmsg_add_str(&out, n->name);
237         packmsg_add_str(&out, n->submesh ? n->submesh->name : CORE_MESH);
238         packmsg_add_int32(&out, n->devclass);
239         packmsg_add_bool(&out, n->status.blacklisted);
240
241         if(ecdsa_active(n->ecdsa)) {
242                 packmsg_add_bin(&out, ecdsa_get_public_key(n->ecdsa), 32);
243         } else {
244                 packmsg_add_bin(&out, "", 0);
245         }
246
247         packmsg_add_str(&out, n->canonical_address ? n->canonical_address : "");
248
249         uint32_t count = 0;
250
251         for(uint32_t i = 0; i < MAX_RECENT; i++) {
252                 if(n->recent[i].sa.sa_family) {
253                         count++;
254                 } else {
255                         break;
256                 }
257         }
258
259         packmsg_add_array(&out, count);
260
261         for(uint32_t i = 0; i < count; i++) {
262                 packmsg_add_sockaddr(&out, &n->recent[i]);
263         }
264
265         packmsg_add_int64(&out, 0); // last_reachable
266         packmsg_add_int64(&out, 0); // last_unreachable
267
268         if(!packmsg_output_ok(&out)) {
269                 meshlink_errno = MESHLINK_EINTERNAL;
270                 return false;
271         }
272
273         config_t config = {buf, packmsg_output_size(&out, buf)};
274
275         if(!config_write(mesh, "current", n->name, &config, mesh->config_key)) {
276                 call_error_cb(mesh, MESHLINK_ESTORAGE);
277                 return false;
278         }
279
280         n->status.dirty = false;
281         return true;
282 }
283
284 static bool load_node(meshlink_handle_t *mesh, const char *name, void *priv) {
285         (void)priv;
286
287         if(!check_id(name)) {
288                 // Check if this is a temporary file, if so remove it
289                 const char *suffix = strstr(name, ".tmp");
290
291                 if(suffix && !suffix[4]) {
292                         char filename[PATH_MAX];
293                         snprintf(filename, sizeof(filename), "%s" SLASH "current" SLASH "hosts", mesh->confbase);
294                         unlink(filename);
295                 }
296
297                 return true;
298         }
299
300         node_t *n = lookup_node(mesh, name);
301
302         if(n) {
303                 return true;
304         }
305
306         n = new_node();
307         n->name = xstrdup(name);
308
309         config_t config;
310         packmsg_input_t in;
311
312         if(!node_get_config(mesh, n, &config, &in)) {
313                 free_node(n);
314                 return false;
315         }
316
317         if(!node_read_from_config(mesh, n, &config)) {
318                 logger(mesh, MESHLINK_ERROR, "Invalid config file for node %s", n->name);
319                 config_free(&config);
320                 free_node(n);
321                 return false;
322         }
323
324         config_free(&config);
325
326         node_add(mesh, n);
327
328         return true;
329 }
330
331 int setup_tcp_listen_socket(meshlink_handle_t *mesh, const struct addrinfo *aip) {
332         int nfd = socket(aip->ai_family, SOCK_STREAM, IPPROTO_TCP);
333
334         if(nfd == -1) {
335                 return -1;
336         }
337
338 #ifdef FD_CLOEXEC
339         fcntl(nfd, F_SETFD, FD_CLOEXEC);
340 #endif
341
342 #ifdef O_NONBLOCK
343         int flags = fcntl(nfd, F_GETFL);
344
345         if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
346                 closesocket(nfd);
347                 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "fcntl", strerror(errno));
348                 return -1;
349         }
350
351 #elif defined(WIN32)
352         unsigned long arg = 1;
353
354         if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
355                 closesocket(nfd);
356                 logger(mesh, MESHLINK_ERROR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
357                 return -1;
358         }
359
360 #endif
361         int option = 1;
362         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
363
364 #if defined(IPV6_V6ONLY)
365
366         if(aip->ai_family == AF_INET6) {
367                 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
368         }
369
370 #else
371 #warning IPV6_V6ONLY not defined
372 #endif
373
374         if(bind(nfd, aip->ai_addr, aip->ai_addrlen)) {
375                 closesocket(nfd);
376                 return -1;
377         }
378
379         if(listen(nfd, 3)) {
380                 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
381                 closesocket(nfd);
382                 return -1;
383         }
384
385         return nfd;
386 }
387
388 /*
389   Add listening sockets.
390 */
391 static bool add_listen_sockets(meshlink_handle_t *mesh) {
392         struct addrinfo *ai;
393
394         struct addrinfo hint = {
395                 .ai_family = AF_UNSPEC,
396                 .ai_socktype = SOCK_STREAM,
397                 .ai_protocol = IPPROTO_TCP,
398                 .ai_flags = AI_PASSIVE | AI_NUMERICSERV,
399         };
400
401         int err = getaddrinfo(NULL, mesh->myport, &hint, &ai);
402
403         if(err || !ai) {
404                 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getaddrinfo", err == EAI_SYSTEM ? strerror(err) : gai_strerror(err));
405                 return false;
406         }
407
408         bool success = false;
409
410         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
411                 // Ignore duplicate addresses
412                 bool found = false;
413
414                 for(int i = 0; i < mesh->listen_sockets; i++) {
415                         if(!memcmp(&mesh->listen_socket[i].sa, aip->ai_addr, aip->ai_addrlen)) {
416                                 found = true;
417                                 break;
418                         }
419                 }
420
421                 if(found) {
422                         continue;
423                 }
424
425                 if(mesh->listen_sockets >= MAXSOCKETS) {
426                         logger(mesh, MESHLINK_ERROR, "Too many listening sockets");
427                         return false;
428                 }
429
430                 /* Try to bind to TCP */
431
432                 int tcp_fd = setup_tcp_listen_socket(mesh, aip);
433
434                 if(tcp_fd == -1) {
435                         if(errno == EADDRINUSE) {
436                                 /* If this port is in use for any address family, avoid it. */
437                                 success = false;
438                                 break;
439                         } else {
440                                 continue;
441                         }
442                 }
443
444                 io_add(&mesh->loop, &mesh->listen_socket[mesh->listen_sockets].tcp, handle_new_meta_connection, &mesh->listen_socket[mesh->listen_sockets], tcp_fd, IO_READ);
445
446                 if(mesh->log_level <= MESHLINK_INFO) {
447                         char *hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
448                         logger(mesh, MESHLINK_INFO, "Listening on %s", hostname);
449                         free(hostname);
450                 }
451
452                 memcpy(&mesh->listen_socket[mesh->listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
453                 memcpy(&mesh->listen_socket[mesh->listen_sockets].broadcast_sa, aip->ai_addr, aip->ai_addrlen);
454
455                 if(aip->ai_family == AF_INET6) {
456                         mesh->listen_socket[mesh->listen_sockets].broadcast_sa.in6.sin6_addr.s6_addr[0x0] = 0xff;
457                         mesh->listen_socket[mesh->listen_sockets].broadcast_sa.in6.sin6_addr.s6_addr[0x1] = 0x02;
458                         mesh->listen_socket[mesh->listen_sockets].broadcast_sa.in6.sin6_addr.s6_addr[0xf] = 0x01;
459                 } else {
460                         mesh->listen_socket[mesh->listen_sockets].broadcast_sa.in.sin_addr.s_addr = 0xffffffff;
461                 }
462
463                 mesh->listen_sockets++;
464                 success = true;
465         }
466
467         freeaddrinfo(ai);
468
469         if(!success) {
470                 for(int i = 0; i < mesh->listen_sockets; i++) {
471                         io_del(&mesh->loop, &mesh->listen_socket[i].tcp);
472                         closesocket(mesh->listen_socket[i].tcp.fd);
473                 }
474
475                 mesh->listen_sockets = 0;
476         }
477
478         return success;
479 }
480
481 /*
482   Configure node_t mesh->self and set up the local sockets (listen only)
483 */
484 static bool setup_myself(meshlink_handle_t *mesh) {
485         mesh->self->nexthop = mesh->self;
486
487         node_add(mesh, mesh->self);
488
489         if(!config_scan_all(mesh, "current", "hosts", load_node, NULL)) {
490                 logger(mesh, MESHLINK_WARNING, "Could not scan all host config files");
491         }
492
493         /* Open sockets */
494
495         mesh->listen_sockets = 0;
496
497         if(!add_listen_sockets(mesh)) {
498                 if(strcmp(mesh->myport, "0")) {
499                         logger(mesh, MESHLINK_WARNING, "Could not bind to port %s, trying to find an alternative port", mesh->myport);
500
501                         if(!check_port(mesh)) {
502                                 logger(mesh, MESHLINK_WARNING, "Could not bind to any port, trying to bind to port 0");
503                                 free(mesh->myport);
504                                 mesh->myport = xstrdup("0");
505                         }
506
507                         if(!add_listen_sockets(mesh)) {
508                                 return false;
509                         }
510                 } else {
511                         return false;
512                 }
513         }
514
515         if(!mesh->listen_sockets) {
516                 logger(mesh, MESHLINK_ERROR, "Unable to create any listening socket!");
517                 return false;
518         }
519
520         /* Done. */
521
522         mesh->last_unreachable = mesh->loop.now.tv_sec;
523
524         return true;
525 }
526
527 /*
528   initialize network
529 */
530 bool setup_network(meshlink_handle_t *mesh) {
531         init_connections(mesh);
532         init_submeshes(mesh);
533         init_nodes(mesh);
534         init_requests(mesh);
535
536         if(!setup_myself(mesh)) {
537                 return false;
538         }
539
540         return true;
541 }
542
543 /*
544   close all open network connections
545 */
546 void close_network_connections(meshlink_handle_t *mesh) {
547         if(mesh->connections) {
548                 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
549                         next = node->next;
550                         connection_t *c = node->data;
551                         c->outgoing = NULL;
552                         terminate_connection(mesh, c, false);
553                 }
554         }
555
556         for(int i = 0; i < mesh->listen_sockets; i++) {
557                 io_del(&mesh->loop, &mesh->listen_socket[i].tcp);
558                 closesocket(mesh->listen_socket[i].tcp.fd);
559         }
560
561         exit_requests(mesh);
562         exit_nodes(mesh);
563         exit_submeshes(mesh);
564         exit_connections(mesh);
565
566         free(mesh->myport);
567         mesh->myport = NULL;
568
569         mesh->self = NULL;
570
571         return;
572 }