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