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