]> git.meshlink.io Git - meshlink/blob - src/net_setup.c
Add support for encrypted storage.
[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, 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                 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) || strncmp(name, n->name, len)) {
57                 config_free(config);
58                 return false;
59         }
60
61         return true;
62 }
63
64 /// Read device class, blacklist status and submesh from a host config file. Used at startup when reading all host config files.
65 bool node_read_partial(meshlink_handle_t *mesh, node_t *n) {
66         config_t config;
67         packmsg_input_t in;
68
69         if(!node_get_config(mesh, n, &config, &in)) {
70                 return false;
71         }
72
73         char *submesh_name = packmsg_get_str_dup(&in);
74
75         if(!strcmp(submesh_name, CORE_MESH)) {
76                 free(submesh_name);
77                 n->submesh = NULL;
78         } else {
79                 n->submesh = lookup_or_create_submesh(mesh, submesh_name);
80                 free(submesh_name);
81
82                 if(!n->submesh) {
83                         config_free(&config);
84                         return false;
85                 }
86         }
87
88         int32_t devclass = packmsg_get_int32(&in);
89         bool blacklisted = packmsg_get_bool(&in);
90         config_free(&config);
91
92         if(!packmsg_input_ok(&in) || devclass < 0 || devclass > _DEV_CLASS_MAX) {
93                 return false;
94         }
95
96         n->devclass = devclass;
97         n->status.blacklisted = blacklisted;
98         return true;
99 }
100
101 /// Read the public key from a host config file. Used whenever we need to start an SPTPS session.
102 bool node_read_public_key(meshlink_handle_t *mesh, node_t *n) {
103         if(ecdsa_active(n->ecdsa)) {
104                 return true;
105         }
106
107         config_t config;
108         packmsg_input_t in;
109
110         if(!node_get_config(mesh, n, &config, &in)) {
111                 return false;
112         }
113
114         packmsg_skip_element(&in); /* submesh */
115         packmsg_get_int32(&in); /* devclass */
116         packmsg_get_bool(&in); /* blacklisted */
117
118         const void *key;
119         uint32_t len = packmsg_get_bin_raw(&in, &key);
120
121         if(len != 32) {
122                 config_free(&config);
123                 return false;
124         }
125
126         n->ecdsa = ecdsa_set_public_key(key);
127         config_free(&config);
128         return true;
129 }
130
131 /// Read the full host config file. Used whenever we need to start an SPTPS session.
132 bool node_read_full(meshlink_handle_t *mesh, node_t *n) {
133         if(n->canonical_address) {
134                 return true;
135         }
136
137         config_t config;
138         packmsg_input_t in;
139
140         if(!node_get_config(mesh, n, &config, &in)) {
141                 return false;
142         }
143
144         char *submesh_name = packmsg_get_str_dup(&in);
145
146         if(!strcmp(submesh_name, CORE_MESH)) {
147                 free(submesh_name);
148                 n->submesh = NULL;
149         } else {
150                 n->submesh = lookup_or_create_submesh(mesh, submesh_name);
151                 free(submesh_name);
152
153                 if(!n->submesh) {
154                         return false;
155                 }
156         }
157
158         packmsg_get_int32(&in); /* devclass */
159         packmsg_get_bool(&in); /* blacklisted */
160         const void *key;
161         uint32_t len = packmsg_get_bin_raw(&in, &key); /* public key */
162
163         if(len != 32) {
164                 return false;
165         }
166
167         if(!ecdsa_active(n->ecdsa)) {
168                 n->ecdsa = ecdsa_set_public_key(key);
169         }
170
171         n->canonical_address = packmsg_get_str_dup(&in);
172
173         uint32_t count = packmsg_get_array(&in);
174
175         if(count > 5) {
176                 count = 5;
177         }
178
179         for(uint32_t i = 0; i < count; i++) {
180                 n->recent[i] = packmsg_get_sockaddr(&in);
181         }
182
183         config_free(&config);
184
185         return packmsg_done(&in);
186 }
187
188 bool node_write_config(meshlink_handle_t *mesh, node_t *n) {
189         uint8_t buf[4096];
190         packmsg_output_t out = {buf, sizeof(buf)};
191
192         packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
193         packmsg_add_str(&out, n->name);
194         packmsg_add_str(&out, n->submesh ? n->submesh->name : CORE_MESH);
195         packmsg_add_int32(&out, n->devclass);
196         assert(n->devclass != 3);
197         packmsg_add_bool(&out, n->status.blacklisted);
198
199         if(ecdsa_active(n->ecdsa)) {
200                 packmsg_add_bin(&out, ecdsa_get_public_key(n->ecdsa), 32);
201         } else {
202                 packmsg_add_bin(&out, "", 0);
203         }
204
205         packmsg_add_str(&out, n->canonical_address ? n->canonical_address : "");
206
207         uint32_t count = 0;
208
209         for(uint32_t i = 0; i < 5; i++) {
210                 if(n->recent[i].sa.sa_family) {
211                         count++;
212                 } else {
213                         break;
214                 }
215         }
216
217         packmsg_add_array(&out, count);
218
219         for(uint32_t i = 0; i < count; i++) {
220                 packmsg_add_sockaddr(&out, &n->recent[i]);
221         }
222
223         if(!packmsg_output_ok(&out)) {
224                 return false;
225         }
226
227         config_t config = {buf, packmsg_output_size(&out, buf)};
228         return config_write(mesh, n->name, &config);
229 }
230
231 void load_all_nodes(meshlink_handle_t *mesh) {
232         DIR *dir;
233         struct dirent *ent;
234         char dname[PATH_MAX];
235
236         snprintf(dname, PATH_MAX, "%s" SLASH "hosts", mesh->confbase);
237         dir = opendir(dname);
238
239         if(!dir) {
240                 logger(mesh, MESHLINK_ERROR, "Could not open %s: %s", dname, strerror(errno));
241                 return;
242         }
243
244         while((ent = readdir(dir))) {
245                 if(!check_id(ent->d_name)) {
246                         continue;
247                 }
248
249                 node_t *n = lookup_node(mesh, ent->d_name);
250
251                 if(n) {
252                         continue;
253                 }
254
255                 n = new_node();
256                 n->name = xstrdup(ent->d_name);
257                 node_read_partial(mesh, n);
258                 node_add(mesh, n);
259         }
260
261         closedir(dir);
262 }
263
264 /*
265   Add listening sockets.
266 */
267 static bool add_listen_address(meshlink_handle_t *mesh, char *address, bool bindto) {
268         char *port = mesh->myport;
269
270         if(address) {
271                 char *space = strchr(address, ' ');
272
273                 if(space) {
274                         *space++ = 0;
275                         port = space;
276                 }
277
278                 if(!strcmp(address, "*")) {
279                         *address = 0;
280                 }
281         }
282
283         struct addrinfo *ai;
284
285         struct addrinfo hint = {
286                 .ai_family = addressfamily,
287                 .ai_socktype = SOCK_STREAM,
288                 .ai_protocol = IPPROTO_TCP,
289                 .ai_flags = AI_PASSIVE,
290         };
291
292         int err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
293
294         free(address);
295
296         if(err || !ai) {
297                 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getaddrinfo", err == EAI_SYSTEM ? strerror(err) : gai_strerror(err));
298                 return false;
299         }
300
301         bool success = false;
302
303         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
304                 // Ignore duplicate addresses
305                 bool found = false;
306
307                 for(int i = 0; i < mesh->listen_sockets; i++)
308                         if(!memcmp(&mesh->listen_socket[i].sa, aip->ai_addr, aip->ai_addrlen)) {
309                                 found = true;
310                                 break;
311                         }
312
313                 if(found) {
314                         continue;
315                 }
316
317                 if(mesh->listen_sockets >= MAXSOCKETS) {
318                         logger(mesh, MESHLINK_ERROR, "Too many listening sockets");
319                         return false;
320                 }
321
322                 int tcp_fd = setup_listen_socket((sockaddr_t *) aip->ai_addr);
323
324                 if(tcp_fd < 0) {
325                         continue;
326                 }
327
328                 int udp_fd = setup_vpn_in_socket(mesh, (sockaddr_t *) aip->ai_addr);
329
330                 if(udp_fd < 0) {
331                         close(tcp_fd);
332                         continue;
333                 }
334
335                 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);
336                 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);
337
338                 if(mesh->log_level >= MESHLINK_INFO) {
339                         char *hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
340                         logger(mesh, MESHLINK_INFO, "Listening on %s", hostname);
341                         free(hostname);
342                 }
343
344                 mesh->listen_socket[mesh->listen_sockets].bindto = bindto;
345                 memcpy(&mesh->listen_socket[mesh->listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
346                 mesh->listen_sockets++;
347                 success = true;
348         }
349
350         freeaddrinfo(ai);
351         return success;
352 }
353
354 /*
355   Configure node_t mesh->self and set up the local sockets (listen only)
356 */
357 bool setup_myself(meshlink_handle_t *mesh) {
358         /* Set some defaults */
359
360         mesh->localdiscovery = true;
361         keylifetime = 3600; // TODO: check if this can be removed as well
362         mesh->maxtimeout = 900;
363         mesh->self->options |= OPTION_PMTU_DISCOVERY;
364
365         /* Done */
366
367         mesh->self->nexthop = mesh->self;
368         mesh->self->via = mesh->self;
369         mesh->self->status.reachable = true;
370         mesh->self->last_state_change = mesh->loop.now.tv_sec;
371
372         node_add(mesh, mesh->self);
373
374         graph(mesh);
375
376         load_all_nodes(mesh);
377
378         /* Open sockets */
379
380         mesh->listen_sockets = 0;
381
382         if(!add_listen_address(mesh, NULL, NULL)) {
383                 if(strcmp(mesh->myport, "0")) {
384                         logger(mesh, MESHLINK_INFO, "Could not bind to port %s, asking OS to choose one for us", mesh->myport);
385                         free(mesh->myport);
386                         mesh->myport = strdup("0");
387
388                         if(!mesh->myport) {
389                                 return false;
390                         }
391
392                         if(!add_listen_address(mesh, NULL, NULL)) {
393                                 return false;
394                         }
395                 } else {
396                         return false;
397                 }
398         }
399
400         if(!mesh->listen_sockets) {
401                 logger(mesh, MESHLINK_ERROR, "Unable to create any listening socket!");
402                 return false;
403         }
404
405         /* Done. */
406
407         mesh->last_config_check = mesh->loop.now.tv_sec;
408
409         return true;
410 }
411
412 /*
413   initialize network
414 */
415 bool setup_network(meshlink_handle_t *mesh) {
416         init_connections(mesh);
417         init_submeshes(mesh);
418         init_nodes(mesh);
419         init_edges(mesh);
420         init_requests(mesh);
421
422         mesh->pinginterval = 60;
423         mesh->pingtimeout = 5;
424         maxoutbufsize = 10 * MTU;
425
426         if(!setup_myself(mesh)) {
427                 return false;
428         }
429
430         return true;
431 }
432
433 /*
434   close all open network connections
435 */
436 void close_network_connections(meshlink_handle_t *mesh) {
437         if(mesh->connections) {
438                 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
439                         next = node->next;
440                         connection_t *c = node->data;
441                         c->outgoing = NULL;
442                         terminate_connection(mesh, c, false);
443                 }
444         }
445
446         for(int i = 0; i < mesh->listen_sockets; i++) {
447                 io_del(&mesh->loop, &mesh->listen_socket[i].tcp);
448                 io_del(&mesh->loop, &mesh->listen_socket[i].udp);
449                 close(mesh->listen_socket[i].tcp.fd);
450                 close(mesh->listen_socket[i].udp.fd);
451         }
452
453         exit_requests(mesh);
454         exit_edges(mesh);
455         exit_nodes(mesh);
456         exit_connections(mesh);
457
458         if(mesh->myport) {
459                 free(mesh->myport);
460         }
461
462         return;
463 }