]> git.meshlink.io Git - meshlink/blob - src/net_setup.c
Really bind to a free port if the configured port is not available.
[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, "rb");
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, "rb");
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
127         splay_tree_t *config_tree;
128         char *p;
129
130         init_configuration(&config_tree);
131         if(!read_host_config(mesh, config_tree, n->name))
132                 goto exit;
133
134         if(get_config_string(lookup_config(config_tree, "DeviceClass"), &p)) {
135                 n->devclass = atoi(p);
136                 free(p);
137         }
138
139         if(n->devclass < 0 || n->devclass > _DEV_CLASS_MAX)
140                 n->devclass = _DEV_CLASS_MAX;
141
142 exit:
143         exit_configuration(&config_tree);
144         return n->devclass != 0;
145 }
146
147 bool node_write_devclass(meshlink_handle_t *mesh, node_t *n) {
148
149         if(n->devclass < 0 || n->devclass > _DEV_CLASS_MAX)
150                 return false;
151
152         bool result = false;
153
154         splay_tree_t *config_tree;
155         init_configuration(&config_tree);
156
157         // ignore read errors; in case the file does not exist we will create it
158         read_host_config(mesh, config_tree, n->name);
159
160         config_t *cnf = lookup_config(config_tree, "DeviceClass");
161
162         if(!cnf) {
163                 cnf = new_config();
164                 cnf->variable = xstrdup("DeviceClass");
165                 config_add(config_tree, cnf);
166         }
167
168         set_config_int(cnf, n->devclass);
169
170         if(!write_host_config(mesh, config_tree, n->name))
171                 goto fail;
172
173         result = true;
174
175 fail:
176         exit_configuration(&config_tree);
177         return result;
178 }
179
180 void load_all_nodes(meshlink_handle_t *mesh) {
181         DIR *dir;
182         struct dirent *ent;
183         char dname[PATH_MAX];
184
185         snprintf(dname, PATH_MAX, "%s" SLASH "hosts", mesh->confbase);
186         dir = opendir(dname);
187         if(!dir) {
188                 logger(mesh, MESHLINK_ERROR, "Could not open %s: %s", dname, strerror(errno));
189                 return;
190         }
191
192         while((ent = readdir(dir))) {
193                 if(!check_id(ent->d_name))
194                         continue;
195
196                 node_t *n = lookup_node(mesh, ent->d_name);
197                 if(n)
198                         continue;
199
200                 n = new_node();
201                 n->name = xstrdup(ent->d_name);
202                 node_read_devclass(mesh, n);
203                 node_add(mesh, n);
204         }
205
206         closedir(dir);
207 }
208
209
210 char *get_name(meshlink_handle_t *mesh) {
211         char *name = NULL;
212
213         get_config_string(lookup_config(mesh->config, "Name"), &name);
214
215         if(!name)
216                 return NULL;
217
218         if(!check_id(name)) {
219                 logger(mesh, MESHLINK_ERROR, "Invalid name for mesh->self!");
220                 free(name);
221                 return NULL;
222         }
223
224         return name;
225 }
226
227 bool setup_myself_reloadable(meshlink_handle_t *mesh) {
228         mesh->localdiscovery = true;
229         keylifetime = 3600; // TODO: check if this can be removed as well
230         mesh->maxtimeout = 900;
231         mesh->self->options |= OPTION_PMTU_DISCOVERY;
232
233         read_invitation_key(mesh);
234
235         return true;
236 }
237
238 /*
239   Add listening sockets.
240 */
241 static bool add_listen_address(meshlink_handle_t *mesh, char *address, bool bindto) {
242         char *port = mesh->myport;
243
244         if(address) {
245                 char *space = strchr(address, ' ');
246                 if(space) {
247                         *space++ = 0;
248                         port = space;
249                 }
250
251                 if(!strcmp(address, "*"))
252                         *address = 0;
253         }
254
255         struct addrinfo *ai, hint = {0};
256         hint.ai_family = addressfamily;
257         hint.ai_socktype = SOCK_STREAM;
258         hint.ai_protocol = IPPROTO_TCP;
259         hint.ai_flags = AI_PASSIVE;
260
261         int err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
262         free(address);
263
264         if(err || !ai) {
265                 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getaddrinfo", err == EAI_SYSTEM ? strerror(err) : gai_strerror(err));
266                 return false;
267         }
268
269         bool success = false;
270
271         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
272                 // Ignore duplicate addresses
273                 bool found = false;
274
275                 for(int i = 0; i < mesh->listen_sockets; i++)
276                         if(!memcmp(&mesh->listen_socket[i].sa, aip->ai_addr, aip->ai_addrlen)) {
277                                 found = true;
278                                 break;
279                         }
280
281                 if(found)
282                         continue;
283
284                 if(mesh->listen_sockets >= MAXSOCKETS) {
285                         logger(mesh, MESHLINK_ERROR, "Too many listening sockets");
286                         return false;
287                 }
288
289                 int tcp_fd = setup_listen_socket((sockaddr_t *) aip->ai_addr);
290
291                 if(tcp_fd < 0)
292                         continue;
293
294                 int udp_fd = setup_vpn_in_socket(mesh, (sockaddr_t *) aip->ai_addr);
295
296                 if(udp_fd < 0) {
297                         close(tcp_fd);
298                         continue;
299                 }
300
301                 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);
302                 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);
303
304                 if(mesh->log_level >= MESHLINK_INFO) {
305                         char *hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
306                         logger(mesh, MESHLINK_INFO, "Listening on %s", hostname);
307                         free(hostname);
308                 }
309
310                 mesh->listen_socket[mesh->listen_sockets].bindto = bindto;
311                 memcpy(&mesh->listen_socket[mesh->listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
312                 mesh->listen_sockets++;
313                 success = true;
314         }
315
316         freeaddrinfo(ai);
317         return success;
318 }
319
320 /*
321   Configure node_t mesh->self and set up the local sockets (listen only)
322 */
323 bool setup_myself(meshlink_handle_t *mesh) {
324         char *name;
325         char *address = NULL;
326
327         if(!(name = get_name(mesh))) {
328                 logger(mesh, MESHLINK_ERROR, "Name for MeshLink instance required!");
329                 return false;
330         }
331
332         mesh->self = new_node();
333         mesh->self->connection = new_connection();
334         mesh->self->name = name;
335         mesh->self->devclass = mesh->devclass;
336         mesh->self->connection->name = xstrdup(name);
337         read_host_config(mesh, mesh->config, name);
338
339         if(!get_config_string(lookup_config(mesh->config, "Port"), &mesh->myport)) {
340                 logger(mesh, MESHLINK_ERROR, "Port for MeshLink instance required!");
341                 return false;
342         }
343
344         mesh->self->connection->options = 0;
345         mesh->self->connection->protocol_major = PROT_MAJOR;
346         mesh->self->connection->protocol_minor = PROT_MINOR;
347
348         mesh->self->options |= PROT_MINOR << 24;
349
350         if(!read_ecdsa_private_key(mesh))
351                 return false;
352
353         /* Ensure mesh->myport is numeric */
354
355         if(!atoi(mesh->myport)) {
356                 struct addrinfo *ai = str2addrinfo("localhost", mesh->myport, SOCK_DGRAM);
357                 sockaddr_t sa;
358                 if(!ai || !ai->ai_addr)
359                         return false;
360                 free(mesh->myport);
361                 memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
362                 sockaddr2str(&sa, NULL, &mesh->myport);
363         }
364
365         /* Check some options */
366
367         if(!setup_myself_reloadable(mesh))
368                 return false;
369
370         /* Compression */
371
372         // TODO: drop compression in the packet layer?
373         mesh->self->incompression = 0;
374         mesh->self->connection->outcompression = 0;
375
376         /* Done */
377
378         mesh->self->nexthop = mesh->self;
379         mesh->self->via = mesh->self;
380         mesh->self->status.reachable = true;
381         mesh->self->last_state_change = mesh->loop.now.tv_sec;
382
383         node_write_devclass(mesh, mesh->self);
384         node_add(mesh, mesh->self);
385
386         graph(mesh);
387
388         load_all_nodes(mesh);
389
390         /* Open sockets */
391
392         mesh->listen_sockets = 0;
393
394         if(!add_listen_address(mesh, address, NULL)) {
395                 if(strcmp(mesh->myport, "0")) {
396                         logger(mesh, MESHLINK_INFO, "Could not bind to port %s, asking OS to choose one for us", mesh->myport);
397                         free(mesh->myport);
398                         mesh->myport = strdup("0");
399                         if(!mesh->myport)
400                                 return false;
401                         if(!add_listen_address(mesh, address, NULL))
402                                 return false;
403                 } else
404                         return false;
405         }
406
407         if(!mesh->listen_sockets) {
408                 logger(mesh, MESHLINK_ERROR, "Unable to create any listening socket!");
409                 return false;
410         }
411
412         /* Done. */
413
414         mesh->last_config_check = mesh->loop.now.tv_sec;
415
416         return true;
417 }
418
419 /*
420   initialize network
421 */
422 bool setup_network(meshlink_handle_t *mesh) {
423         init_connections(mesh);
424         init_nodes(mesh);
425         init_edges(mesh);
426         init_requests(mesh);
427
428         mesh->pinginterval = 60;
429         mesh->pingtimeout = 5;
430         maxoutbufsize = 10 * MTU;
431
432         if(!setup_myself(mesh))
433                 return false;
434
435         return true;
436 }
437
438 /*
439   close all open network connections
440 */
441 void close_network_connections(meshlink_handle_t *mesh) {
442         if(mesh->connections) {
443                 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
444                         next = node->next;
445                         connection_t *c = node->data;
446                         c->outgoing = NULL;
447                         terminate_connection(mesh, c, false);
448                 }
449         }
450
451         if(mesh->outgoings)
452                 list_delete_list(mesh->outgoings);
453
454         if(mesh->self && mesh->self->connection) {
455                 terminate_connection(mesh, mesh->self->connection, false);
456                 free_connection(mesh->self->connection);
457         }
458
459         for(int i = 0; i < mesh->listen_sockets; i++) {
460                 io_del(&mesh->loop, &mesh->listen_socket[i].tcp);
461                 io_del(&mesh->loop, &mesh->listen_socket[i].udp);
462                 close(mesh->listen_socket[i].tcp.fd);
463                 close(mesh->listen_socket[i].udp.fd);
464         }
465
466         exit_requests(mesh);
467         exit_edges(mesh);
468         exit_nodes(mesh);
469         exit_connections(mesh);
470
471         if(mesh->myport) free(mesh->myport);
472
473         return;
474 }