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