]> git.meshlink.io Git - meshlink/blob - src/net_setup.c
ec16b400873f15742ac2e998b287797771ad4c87
[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_read(mesh, "current", n->name, config, mesh->config_key)) {
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         } else {
97                 packmsg_skip_element(&in);
98         }
99
100         // Append any known addresses in the config file to the list we currently have
101         uint32_t known_count = 0;
102
103         for(uint32_t i = 0; i < MAX_RECENT; i++) {
104                 if(n->recent[i].sa.sa_family) {
105                         known_count++;
106                 }
107         }
108
109         uint32_t count = packmsg_get_array(&in);
110
111         for(uint32_t i = 0; i < count; i++) {
112                 if(i < MAX_RECENT - known_count) {
113                         n->recent[i + known_count] = packmsg_get_sockaddr(&in);
114                 } else {
115                         packmsg_skip_element(&in);
116                 }
117         }
118
119         }
120
121         config_free(&config);
122         return true;
123 }
124
125 /// Fill in node details from a config blob.
126 bool node_read_from_config(meshlink_handle_t *mesh, node_t *n, const config_t *config) {
127         if(n->canonical_address) {
128                 return true;
129         }
130
131         packmsg_input_t in = {config->buf, config->len};
132         uint32_t version = packmsg_get_uint32(&in);
133
134         if(version != MESHLINK_CONFIG_VERSION) {
135                 return false;
136         }
137
138         char *name = packmsg_get_str_dup(&in);
139
140         if(!name) {
141                 return false;
142         }
143
144         if(n->name) {
145                 if(strcmp(n->name, name)) {
146                         free(name);
147                         return false;
148                 }
149
150                 free(name);
151         } else {
152                 n->name = name;
153         }
154
155         char *submesh_name = packmsg_get_str_dup(&in);
156
157         if(!strcmp(submesh_name, CORE_MESH)) {
158                 free(submesh_name);
159                 n->submesh = NULL;
160         } else {
161                 n->submesh = lookup_or_create_submesh(mesh, submesh_name);
162                 free(submesh_name);
163
164                 if(!n->submesh) {
165                         return false;
166                 }
167         }
168
169         n->devclass = packmsg_get_int32(&in);
170         n->status.blacklisted = packmsg_get_bool(&in);
171         const void *key;
172         uint32_t len = packmsg_get_bin_raw(&in, &key);
173
174         if(len) {
175                 if(len != 32) {
176                         return false;
177                 }
178
179                 if(!ecdsa_active(n->ecdsa)) {
180                         n->ecdsa = ecdsa_set_public_key(key);
181                 }
182         }
183
184         n->canonical_address = packmsg_get_str_dup(&in);
185         uint32_t count = packmsg_get_array(&in);
186
187         for(uint32_t i = 0; i < count; i++) {
188                 if(i < MAX_RECENT) {
189                         n->recent[i] = packmsg_get_sockaddr(&in);
190                 } else {
191                         packmsg_skip_element(&in);
192                 }
193         }
194
195         return packmsg_done(&in);
196 }
197
198 bool node_write_config(meshlink_handle_t *mesh, node_t *n) {
199         if(!mesh->confbase) {
200                 return true;
201         }
202
203         uint8_t buf[4096];
204         packmsg_output_t out = {buf, sizeof(buf)};
205
206         packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
207         packmsg_add_str(&out, n->name);
208         packmsg_add_str(&out, n->submesh ? n->submesh->name : CORE_MESH);
209         packmsg_add_int32(&out, n->devclass);
210         packmsg_add_bool(&out, n->status.blacklisted);
211
212         if(ecdsa_active(n->ecdsa)) {
213                 packmsg_add_bin(&out, ecdsa_get_public_key(n->ecdsa), 32);
214         } else {
215                 packmsg_add_bin(&out, "", 0);
216         }
217
218         packmsg_add_str(&out, n->canonical_address ? n->canonical_address : "");
219
220         uint32_t count = 0;
221
222         for(uint32_t i = 0; i < MAX_RECENT; i++) {
223                 if(n->recent[i].sa.sa_family) {
224                         count++;
225                 } else {
226                         break;
227                 }
228         }
229
230         packmsg_add_array(&out, count);
231
232         for(uint32_t i = 0; i < count; i++) {
233                 packmsg_add_sockaddr(&out, &n->recent[i]);
234         }
235
236         if(!packmsg_output_ok(&out)) {
237                 meshlink_errno = MESHLINK_EINTERNAL;
238                 return false;
239         }
240
241         config_t config = {buf, packmsg_output_size(&out, buf)};
242
243         if(!config_write(mesh, "current", n->name, &config, mesh->config_key)) {
244                 call_error_cb(mesh, MESHLINK_ESTORAGE);
245                 return false;
246         }
247
248         return true;
249 }
250
251 static bool load_node(meshlink_handle_t *mesh, const char *name, void *priv) {
252         (void)priv;
253
254         if(!check_id(name)) {
255                 return true;
256         }
257
258         node_t *n = lookup_node(mesh, name);
259
260         if(n) {
261                 return true;
262         }
263
264         n = new_node();
265         n->name = xstrdup(name);
266
267         config_t config;
268         packmsg_input_t in;
269
270         if(!node_get_config(mesh, n, &config, &in)) {
271                 free_node(n);
272                 return false;
273         }
274
275         if(!node_read_from_config(mesh, n, &config)) {
276                 logger(mesh, MESHLINK_ERROR, "Invalid config file for node %s", n->name);
277                 config_free(&config);
278                 free_node(n);
279                 return false;
280         }
281
282         config_free(&config);
283
284         node_add(mesh, n);
285
286         return true;
287 }
288
289 /*
290   Add listening sockets.
291 */
292 static bool add_listen_address(meshlink_handle_t *mesh, char *address, bool bindto) {
293         char *port = mesh->myport;
294
295         if(address) {
296                 char *space = strchr(address, ' ');
297
298                 if(space) {
299                         *space++ = 0;
300                         port = space;
301                 }
302
303                 if(!strcmp(address, "*")) {
304                         *address = 0;
305                 }
306         }
307
308         struct addrinfo *ai;
309
310         struct addrinfo hint = {
311                 .ai_family = AF_UNSPEC,
312                 .ai_socktype = SOCK_STREAM,
313                 .ai_protocol = IPPROTO_TCP,
314                 .ai_flags = AI_PASSIVE,
315         };
316
317         int err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
318
319         free(address);
320
321         if(err || !ai) {
322                 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getaddrinfo", err == EAI_SYSTEM ? strerror(err) : gai_strerror(err));
323                 return false;
324         }
325
326         bool success = false;
327
328         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
329                 // Ignore duplicate addresses
330                 bool found = false;
331
332                 for(int i = 0; i < mesh->listen_sockets; i++)
333                         if(!memcmp(&mesh->listen_socket[i].sa, aip->ai_addr, aip->ai_addrlen)) {
334                                 found = true;
335                                 break;
336                         }
337
338                 if(found) {
339                         continue;
340                 }
341
342                 if(mesh->listen_sockets >= MAXSOCKETS) {
343                         logger(mesh, MESHLINK_ERROR, "Too many listening sockets");
344                         return false;
345                 }
346
347                 int tcp_fd = setup_listen_socket((sockaddr_t *) aip->ai_addr);
348
349                 if(tcp_fd < 0) {
350                         continue;
351                 }
352
353                 int udp_fd = setup_vpn_in_socket(mesh, (sockaddr_t *) aip->ai_addr);
354
355                 if(udp_fd < 0) {
356                         close(tcp_fd);
357                         continue;
358                 }
359
360                 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);
361                 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);
362
363                 if(mesh->log_level >= MESHLINK_INFO) {
364                         char *hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
365                         logger(mesh, MESHLINK_INFO, "Listening on %s", hostname);
366                         free(hostname);
367                 }
368
369                 mesh->listen_socket[mesh->listen_sockets].bindto = bindto;
370                 memcpy(&mesh->listen_socket[mesh->listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
371                 memcpy(&mesh->listen_socket[mesh->listen_sockets].broadcast_sa, aip->ai_addr, aip->ai_addrlen);
372
373                 if(aip->ai_family == AF_INET6) {
374                         mesh->listen_socket[mesh->listen_sockets].broadcast_sa.in6.sin6_addr.s6_addr[0x0] = 0xff;
375                         mesh->listen_socket[mesh->listen_sockets].broadcast_sa.in6.sin6_addr.s6_addr[0x1] = 0x02;
376                         mesh->listen_socket[mesh->listen_sockets].broadcast_sa.in6.sin6_addr.s6_addr[0xf] = 0x01;
377                 } else {
378                         mesh->listen_socket[mesh->listen_sockets].broadcast_sa.in.sin_addr.s_addr = 0xffffffff;
379                 }
380
381                 mesh->listen_sockets++;
382                 success = true;
383         }
384
385         freeaddrinfo(ai);
386         return success;
387 }
388
389 /*
390   Configure node_t mesh->self and set up the local sockets (listen only)
391 */
392 bool setup_myself(meshlink_handle_t *mesh) {
393         /* Set some defaults */
394
395         mesh->maxtimeout = 900;
396
397         /* Done */
398
399         mesh->self->nexthop = mesh->self;
400         mesh->self->status.reachable = true;
401         mesh->self->last_state_change = mesh->loop.now.tv_sec;
402
403         node_add(mesh, mesh->self);
404
405         graph(mesh);
406
407         if(!config_scan_all(mesh, "current", "hosts", load_node, NULL)) {
408                 logger(mesh, MESHLINK_WARNING, "Could not scan all host config files");
409         }
410
411         /* Open sockets */
412
413         mesh->listen_sockets = 0;
414
415         if(!add_listen_address(mesh, NULL, NULL)) {
416                 if(strcmp(mesh->myport, "0")) {
417                         logger(mesh, MESHLINK_INFO, "Could not bind to port %s, asking OS to choose one for us", mesh->myport);
418                         free(mesh->myport);
419                         mesh->myport = strdup("0");
420
421                         if(!mesh->myport) {
422                                 return false;
423                         }
424
425                         if(!add_listen_address(mesh, NULL, NULL)) {
426                                 return false;
427                         }
428                 } else {
429                         return false;
430                 }
431         }
432
433         if(!mesh->listen_sockets) {
434                 logger(mesh, MESHLINK_ERROR, "Unable to create any listening socket!");
435                 return false;
436         }
437
438         /* Done. */
439
440         mesh->last_config_check = mesh->loop.now.tv_sec;
441
442         return true;
443 }
444
445 /*
446   initialize network
447 */
448 bool setup_network(meshlink_handle_t *mesh) {
449         init_connections(mesh);
450         init_submeshes(mesh);
451         init_nodes(mesh);
452         init_edges(mesh);
453         init_requests(mesh);
454
455         if(!setup_myself(mesh)) {
456                 return false;
457         }
458
459         return true;
460 }
461
462 /*
463   close all open network connections
464 */
465 void close_network_connections(meshlink_handle_t *mesh) {
466         if(mesh->connections) {
467                 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
468                         next = node->next;
469                         connection_t *c = node->data;
470                         c->outgoing = NULL;
471                         terminate_connection(mesh, c, false);
472                 }
473         }
474
475         for(int i = 0; i < mesh->listen_sockets; i++) {
476                 io_del(&mesh->loop, &mesh->listen_socket[i].tcp);
477                 io_del(&mesh->loop, &mesh->listen_socket[i].udp);
478                 close(mesh->listen_socket[i].tcp.fd);
479                 close(mesh->listen_socket[i].udp.fd);
480         }
481
482         exit_requests(mesh);
483         exit_edges(mesh);
484         exit_nodes(mesh);
485         exit_submeshes(mesh);
486         exit_connections(mesh);
487
488         free(mesh->myport);
489         mesh->myport = NULL;
490
491         mesh->self = NULL;
492
493         return;
494 }