]> git.meshlink.io Git - meshlink/blob - src/net_setup.c
Move the routing header out of the SPTPS payload.
[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 "protocol.h"
31 #include "utils.h"
32 #include "xalloc.h"
33
34 bool node_read_ecdsa_public_key(meshlink_handle_t *mesh, node_t *n) {
35         if(ecdsa_active(n->ecdsa)) {
36                 return true;
37         }
38
39         splay_tree_t *config_tree;
40         char *p;
41
42         init_configuration(&config_tree);
43
44         if(!read_host_config(mesh, config_tree, n->name)) {
45                 goto exit;
46         }
47
48         /* First, check for simple ECDSAPublicKey statement */
49
50         if(get_config_string(lookup_config(config_tree, "ECDSAPublicKey"), &p)) {
51                 n->ecdsa = ecdsa_set_base64_public_key(p);
52                 free(p);
53         }
54
55 exit:
56         exit_configuration(&config_tree);
57         return n->ecdsa;
58 }
59
60 bool read_ecdsa_public_key(meshlink_handle_t *mesh, connection_t *c) {
61         if(ecdsa_active(c->ecdsa)) {
62                 return true;
63         }
64
65         char *p;
66
67         if(!c->config_tree) {
68                 init_configuration(&c->config_tree);
69
70                 if(!read_host_config(mesh, c->config_tree, c->name)) {
71                         return false;
72                 }
73         }
74
75         /* First, check for simple ECDSAPublicKey statement */
76
77         if(get_config_string(lookup_config(c->config_tree, "ECDSAPublicKey"), &p)) {
78                 c->ecdsa = ecdsa_set_base64_public_key(p);
79                 free(p);
80                 return c->ecdsa;
81         }
82
83         return false;
84 }
85
86 bool read_ecdsa_private_key(meshlink_handle_t *mesh) {
87         FILE *fp;
88         char filename[PATH_MAX];
89
90         snprintf(filename, PATH_MAX, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
91         fp = fopen(filename, "rb");
92
93         if(!fp) {
94                 logger(mesh, MESHLINK_ERROR, "Error reading ECDSA private key file: %s", strerror(errno));
95                 return false;
96         }
97
98         mesh->self->connection->ecdsa = ecdsa_read_pem_private_key(fp);
99         fclose(fp);
100
101         if(!mesh->self->connection->ecdsa) {
102                 logger(mesh, MESHLINK_ERROR, "Reading ECDSA private key file failed: %s", strerror(errno));
103         }
104
105         return mesh->self->connection->ecdsa;
106 }
107
108 static bool read_invitation_key(meshlink_handle_t *mesh) {
109         FILE *fp;
110         char filename[PATH_MAX];
111
112         if(mesh->invitation_key) {
113                 ecdsa_free(mesh->invitation_key);
114                 mesh->invitation_key = NULL;
115         }
116
117         snprintf(filename, PATH_MAX, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
118
119         fp = fopen(filename, "rb");
120
121         if(fp) {
122                 mesh->invitation_key = ecdsa_read_pem_private_key(fp);
123                 fclose(fp);
124
125                 if(!mesh->invitation_key) {
126                         logger(mesh, MESHLINK_ERROR, "Reading ECDSA private key file `%s' failed: %s", filename, strerror(errno));
127                 }
128         }
129
130         return mesh->invitation_key;
131 }
132
133 bool node_read_devclass(meshlink_handle_t *mesh, node_t *n) {
134
135         splay_tree_t *config_tree;
136         char *p;
137
138         init_configuration(&config_tree);
139
140         if(!read_host_config(mesh, config_tree, n->name)) {
141                 goto exit;
142         }
143
144         if(get_config_string(lookup_config(config_tree, "DeviceClass"), &p)) {
145                 n->devclass = atoi(p);
146                 free(p);
147         }
148
149         if((int)n->devclass < 0 || n->devclass > _DEV_CLASS_MAX) {
150                 n->devclass = _DEV_CLASS_MAX;
151         }
152
153 exit:
154         exit_configuration(&config_tree);
155         return n->devclass != 0;
156 }
157
158 bool node_write_devclass(meshlink_handle_t *mesh, node_t *n) {
159
160         if((int)n->devclass < 0 || n->devclass > _DEV_CLASS_MAX) {
161                 return false;
162         }
163
164         bool result = false;
165
166         splay_tree_t *config_tree;
167         init_configuration(&config_tree);
168
169         // ignore read errors; in case the file does not exist we will create it
170         read_host_config(mesh, config_tree, n->name);
171
172         config_t *cnf = lookup_config(config_tree, "DeviceClass");
173
174         if(!cnf) {
175                 cnf = new_config();
176                 cnf->variable = xstrdup("DeviceClass");
177                 config_add(config_tree, cnf);
178         }
179
180         set_config_int(cnf, n->devclass);
181
182         if(!write_host_config(mesh, config_tree, n->name)) {
183                 goto fail;
184         }
185
186         result = true;
187
188 fail:
189         exit_configuration(&config_tree);
190         return result;
191 }
192
193 void load_all_nodes(meshlink_handle_t *mesh) {
194         DIR *dir;
195         struct dirent *ent;
196         char dname[PATH_MAX];
197
198         snprintf(dname, PATH_MAX, "%s" SLASH "hosts", mesh->confbase);
199         dir = opendir(dname);
200
201         if(!dir) {
202                 logger(mesh, MESHLINK_ERROR, "Could not open %s: %s", dname, strerror(errno));
203                 return;
204         }
205
206         while((ent = readdir(dir))) {
207                 if(!check_id(ent->d_name)) {
208                         continue;
209                 }
210
211                 node_t *n = lookup_node(mesh, ent->d_name);
212
213                 if(n) {
214                         continue;
215                 }
216
217                 n = new_node();
218                 n->name = xstrdup(ent->d_name);
219                 node_read_devclass(mesh, n);
220                 node_add(mesh, n);
221         }
222
223         closedir(dir);
224 }
225
226
227 char *get_name(meshlink_handle_t *mesh) {
228         char *name = NULL;
229
230         get_config_string(lookup_config(mesh->config, "Name"), &name);
231
232         if(!name) {
233                 return NULL;
234         }
235
236         if(!check_id(name)) {
237                 logger(mesh, MESHLINK_ERROR, "Invalid name for mesh->self!");
238                 free(name);
239                 return NULL;
240         }
241
242         return name;
243 }
244
245 bool setup_myself_reloadable(meshlink_handle_t *mesh) {
246         mesh->localdiscovery = true;
247         keylifetime = 3600; // TODO: check if this can be removed as well
248         mesh->maxtimeout = 900;
249         mesh->self->options |= OPTION_PMTU_DISCOVERY;
250
251         read_invitation_key(mesh);
252
253         return true;
254 }
255
256 /*
257   Add listening sockets.
258 */
259 static bool add_listen_address(meshlink_handle_t *mesh, char *address, bool bindto) {
260         char *port = mesh->myport;
261
262         if(address) {
263                 char *space = strchr(address, ' ');
264
265                 if(space) {
266                         *space++ = 0;
267                         port = space;
268                 }
269
270                 if(!strcmp(address, "*")) {
271                         *address = 0;
272                 }
273         }
274
275         struct addrinfo *ai;
276
277         struct addrinfo hint = {
278                 .ai_family = addressfamily,
279                 .ai_socktype = SOCK_STREAM,
280                 .ai_protocol = IPPROTO_TCP,
281                 .ai_flags = AI_PASSIVE,
282         };
283
284         int err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
285
286         free(address);
287
288         if(err || !ai) {
289                 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getaddrinfo", err == EAI_SYSTEM ? strerror(err) : gai_strerror(err));
290                 return false;
291         }
292
293         bool success = false;
294
295         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
296                 // Ignore duplicate addresses
297                 bool found = false;
298
299                 for(int i = 0; i < mesh->listen_sockets; i++)
300                         if(!memcmp(&mesh->listen_socket[i].sa, aip->ai_addr, aip->ai_addrlen)) {
301                                 found = true;
302                                 break;
303                         }
304
305                 if(found) {
306                         continue;
307                 }
308
309                 if(mesh->listen_sockets >= MAXSOCKETS) {
310                         logger(mesh, MESHLINK_ERROR, "Too many listening sockets");
311                         return false;
312                 }
313
314                 int tcp_fd = setup_listen_socket((sockaddr_t *) aip->ai_addr);
315
316                 if(tcp_fd < 0) {
317                         continue;
318                 }
319
320                 int udp_fd = setup_vpn_in_socket(mesh, (sockaddr_t *) aip->ai_addr);
321
322                 if(udp_fd < 0) {
323                         close(tcp_fd);
324                         continue;
325                 }
326
327                 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);
328                 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);
329
330                 if(mesh->log_level >= MESHLINK_INFO) {
331                         char *hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
332                         logger(mesh, MESHLINK_INFO, "Listening on %s", hostname);
333                         free(hostname);
334                 }
335
336                 mesh->listen_socket[mesh->listen_sockets].bindto = bindto;
337                 memcpy(&mesh->listen_socket[mesh->listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
338                 mesh->listen_sockets++;
339                 success = true;
340         }
341
342         freeaddrinfo(ai);
343         return success;
344 }
345
346 /*
347   Configure node_t mesh->self and set up the local sockets (listen only)
348 */
349 bool setup_myself(meshlink_handle_t *mesh) {
350         char *name;
351         char *address = NULL;
352
353         if(!(name = get_name(mesh))) {
354                 logger(mesh, MESHLINK_ERROR, "Name for MeshLink instance required!");
355                 return false;
356         }
357
358         mesh->self = new_node();
359         mesh->self->connection = new_connection();
360         mesh->self->name = name;
361         mesh->self->devclass = mesh->devclass;
362         mesh->self->connection->name = xstrdup(name);
363         read_host_config(mesh, mesh->config, name);
364
365         if(!get_config_string(lookup_config(mesh->config, "Port"), &mesh->myport)) {
366                 int port = check_port(mesh);
367
368                 if(port == 0) {
369                         return false;
370                 }
371
372                 xasprintf(&mesh->myport, "%d", port);
373         }
374
375         mesh->self->connection->options = 0;
376         mesh->self->connection->protocol_major = PROT_MAJOR;
377         mesh->self->connection->protocol_minor = PROT_MINOR;
378
379         mesh->self->options |= PROT_MINOR << 24;
380
381         if(!read_ecdsa_private_key(mesh)) {
382                 return false;
383         }
384
385         /* Ensure mesh->myport is numeric */
386
387         if(!atoi(mesh->myport)) {
388                 struct addrinfo *ai = str2addrinfo("localhost", mesh->myport, SOCK_DGRAM);
389                 sockaddr_t sa;
390
391                 if(!ai || !ai->ai_addr) {
392                         return false;
393                 }
394
395                 free(mesh->myport);
396                 memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
397                 sockaddr2str(&sa, NULL, &mesh->myport);
398         }
399
400         /* Check some options */
401
402         if(!setup_myself_reloadable(mesh)) {
403                 return false;
404         }
405
406         /* Compression */
407
408         // TODO: drop compression in the packet layer?
409         mesh->self->incompression = 0;
410         mesh->self->connection->outcompression = 0;
411
412         /* Done */
413
414         mesh->self->nexthop = mesh->self;
415         mesh->self->via = mesh->self;
416         mesh->self->status.reachable = true;
417         mesh->self->last_state_change = mesh->loop.now.tv_sec;
418
419         node_write_devclass(mesh, mesh->self);
420         node_add(mesh, mesh->self);
421
422         graph(mesh);
423
424         load_all_nodes(mesh);
425
426         /* Open sockets */
427
428         mesh->listen_sockets = 0;
429
430         if(!add_listen_address(mesh, address, NULL)) {
431                 if(strcmp(mesh->myport, "0")) {
432                         logger(mesh, MESHLINK_INFO, "Could not bind to port %s, asking OS to choose one for us", mesh->myport);
433                         free(mesh->myport);
434                         mesh->myport = strdup("0");
435
436                         if(!mesh->myport) {
437                                 return false;
438                         }
439
440                         if(!add_listen_address(mesh, address, NULL)) {
441                                 return false;
442                         }
443                 } else {
444                         return false;
445                 }
446         }
447
448         if(!mesh->listen_sockets) {
449                 logger(mesh, MESHLINK_ERROR, "Unable to create any listening socket!");
450                 return false;
451         }
452
453         /* Done. */
454
455         mesh->last_config_check = mesh->loop.now.tv_sec;
456
457         return true;
458 }
459
460 /*
461   initialize network
462 */
463 bool setup_network(meshlink_handle_t *mesh) {
464         init_connections(mesh);
465         init_nodes(mesh);
466         init_edges(mesh);
467         init_requests(mesh);
468
469         mesh->pinginterval = 60;
470         mesh->pingtimeout = 5;
471
472         if(!setup_myself(mesh)) {
473                 return false;
474         }
475
476         return true;
477 }
478
479 /*
480   close all open network connections
481 */
482 void close_network_connections(meshlink_handle_t *mesh) {
483         if(mesh->connections) {
484                 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
485                         next = node->next;
486                         connection_t *c = node->data;
487                         c->outgoing = NULL;
488                         terminate_connection(mesh, c, false);
489                 }
490         }
491
492         if(mesh->outgoings) {
493                 list_delete_list(mesh->outgoings);
494         }
495
496         if(mesh->self && mesh->self->connection) {
497                 terminate_connection(mesh, mesh->self->connection, false);
498                 free_connection(mesh->self->connection);
499         }
500
501         for(int i = 0; i < mesh->listen_sockets; i++) {
502                 io_del(&mesh->loop, &mesh->listen_socket[i].tcp);
503                 io_del(&mesh->loop, &mesh->listen_socket[i].udp);
504                 close(mesh->listen_socket[i].tcp.fd);
505                 close(mesh->listen_socket[i].udp.fd);
506         }
507
508         exit_requests(mesh);
509         exit_edges(mesh);
510         exit_nodes(mesh);
511         exit_connections(mesh);
512
513         if(mesh->myport) {
514                 free(mesh->myport);
515         }
516
517         return;
518 }