]> git.meshlink.io Git - meshlink/blob - src/net_setup.c
Avoid allocating packet buffers unnecessarily.
[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, "current", n->name, config, mesh->config_key)) {
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                 logger(mesh, MESHLINK_ERROR, "Invalid config file for node %s", n->name);
50                 config_free(config);
51                 return false;
52         }
53
54         const char *name;
55         uint32_t len = packmsg_get_str_raw(in, &name);
56
57         if(len != strlen(n->name) || !name || strncmp(name, n->name, len)) {
58                 logger(mesh, MESHLINK_ERROR, "Invalid config file for node %s", n->name);
59                 config_free(config);
60                 return false;
61         }
62
63         return true;
64 }
65
66 /// Read the public key from a host config file. Used whenever we need to start an SPTPS session.
67 bool node_read_public_key(meshlink_handle_t *mesh, node_t *n) {
68         if(ecdsa_active(n->ecdsa)) {
69                 return true;
70         }
71
72         config_t config;
73         packmsg_input_t in;
74
75         if(!node_get_config(mesh, n, &config, &in)) {
76                 return false;
77         }
78
79         packmsg_skip_element(&in); /* submesh */
80         packmsg_get_int32(&in); /* devclass */
81         packmsg_get_bool(&in); /* blacklisted */
82
83         const void *key;
84         uint32_t len = packmsg_get_bin_raw(&in, &key);
85
86         if(len != 32) {
87                 config_free(&config);
88                 return false;
89         }
90
91         n->ecdsa = ecdsa_set_public_key(key);
92
93         // While we are at it, read known address information
94         if(!n->canonical_address) {
95                 n->canonical_address = packmsg_get_str_dup(&in);
96         } else {
97                 packmsg_skip_element(&in);
98         }
99
100         // Append any known addresses in the config file to the list we currently have
101         uint32_t known_count = 0;
102
103         for(uint32_t i = 0; i < MAX_RECENT; i++) {
104                 if(n->recent[i].sa.sa_family) {
105                         known_count++;
106                 }
107         }
108
109         uint32_t count = packmsg_get_array(&in);
110
111         for(uint32_t i = 0; i < count; i++) {
112                 if(i < MAX_RECENT - known_count) {
113                         n->recent[i + known_count] = packmsg_get_sockaddr(&in);
114                 } else {
115                         packmsg_skip_element(&in);
116                 }
117         }
118
119         time_t last_reachable = packmsg_get_int64(&in);
120         time_t last_unreachable = packmsg_get_int64(&in);
121
122         if(!n->last_reachable) {
123                 n->last_reachable = last_reachable;
124         }
125
126         if(!n->last_unreachable) {
127                 n->last_unreachable = last_unreachable;
128         }
129
130         config_free(&config);
131         return true;
132 }
133
134 /// Fill in node details from a config blob.
135 bool node_read_from_config(meshlink_handle_t *mesh, node_t *n, const config_t *config) {
136         if(n->canonical_address) {
137                 return true;
138         }
139
140         packmsg_input_t in = {config->buf, config->len};
141         uint32_t version = packmsg_get_uint32(&in);
142
143         if(version != MESHLINK_CONFIG_VERSION) {
144                 return false;
145         }
146
147         char *name = packmsg_get_str_dup(&in);
148
149         if(!name) {
150                 return false;
151         }
152
153         if(n->name) {
154                 if(strcmp(n->name, name)) {
155                         free(name);
156                         return false;
157                 }
158
159                 free(name);
160         } else {
161                 n->name = name;
162         }
163
164         char *submesh_name = packmsg_get_str_dup(&in);
165
166         if(!strcmp(submesh_name, CORE_MESH)) {
167                 free(submesh_name);
168                 n->submesh = NULL;
169         } else {
170                 n->submesh = lookup_or_create_submesh(mesh, submesh_name);
171                 free(submesh_name);
172
173                 if(!n->submesh) {
174                         return false;
175                 }
176         }
177
178         n->devclass = packmsg_get_int32(&in);
179         n->status.blacklisted = packmsg_get_bool(&in);
180         const void *key;
181         uint32_t len = packmsg_get_bin_raw(&in, &key);
182
183         if(len) {
184                 if(len != 32) {
185                         return false;
186                 }
187
188                 if(!ecdsa_active(n->ecdsa)) {
189                         n->ecdsa = ecdsa_set_public_key(key);
190                 }
191         }
192
193         n->canonical_address = packmsg_get_str_dup(&in);
194         uint32_t count = packmsg_get_array(&in);
195
196         for(uint32_t i = 0; i < count; i++) {
197                 if(i < MAX_RECENT) {
198                         n->recent[i] = packmsg_get_sockaddr(&in);
199                 } else {
200                         packmsg_skip_element(&in);
201                 }
202         }
203
204         n->last_reachable = packmsg_get_int64(&in);
205         n->last_unreachable = packmsg_get_int64(&in);
206
207         return packmsg_done(&in);
208 }
209
210 bool node_write_config(meshlink_handle_t *mesh, node_t *n) {
211         if(!mesh->confbase) {
212                 return true;
213         }
214
215         uint8_t buf[4096];
216         packmsg_output_t out = {buf, sizeof(buf)};
217
218         packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
219         packmsg_add_str(&out, n->name);
220         packmsg_add_str(&out, n->submesh ? n->submesh->name : CORE_MESH);
221         packmsg_add_int32(&out, n->devclass);
222         packmsg_add_bool(&out, n->status.blacklisted);
223
224         if(ecdsa_active(n->ecdsa)) {
225                 packmsg_add_bin(&out, ecdsa_get_public_key(n->ecdsa), 32);
226         } else {
227                 packmsg_add_bin(&out, "", 0);
228         }
229
230         packmsg_add_str(&out, n->canonical_address ? n->canonical_address : "");
231
232         uint32_t count = 0;
233
234         for(uint32_t i = 0; i < MAX_RECENT; i++) {
235                 if(n->recent[i].sa.sa_family) {
236                         count++;
237                 } else {
238                         break;
239                 }
240         }
241
242         packmsg_add_array(&out, count);
243
244         for(uint32_t i = 0; i < count; i++) {
245                 packmsg_add_sockaddr(&out, &n->recent[i]);
246         }
247
248         packmsg_add_int64(&out, n->last_reachable);
249         packmsg_add_int64(&out, n->last_unreachable);
250
251         if(!packmsg_output_ok(&out)) {
252                 meshlink_errno = MESHLINK_EINTERNAL;
253                 return false;
254         }
255
256         config_t config = {buf, packmsg_output_size(&out, buf)};
257
258         if(!config_write(mesh, "current", n->name, &config, mesh->config_key)) {
259                 call_error_cb(mesh, MESHLINK_ESTORAGE);
260                 return false;
261         }
262
263         return true;
264 }
265
266 static bool load_node(meshlink_handle_t *mesh, const char *name, void *priv) {
267         (void)priv;
268
269         if(!check_id(name)) {
270                 return true;
271         }
272
273         node_t *n = lookup_node(mesh, name);
274
275         if(n) {
276                 return true;
277         }
278
279         n = new_node();
280         n->name = xstrdup(name);
281
282         config_t config;
283         packmsg_input_t in;
284
285         if(!node_get_config(mesh, n, &config, &in)) {
286                 free_node(n);
287                 return false;
288         }
289
290         if(!node_read_from_config(mesh, n, &config)) {
291                 logger(mesh, MESHLINK_ERROR, "Invalid config file for node %s", n->name);
292                 config_free(&config);
293                 free_node(n);
294                 return false;
295         }
296
297         config_free(&config);
298
299         node_add(mesh, n);
300
301         return true;
302 }
303
304 int setup_tcp_listen_socket(meshlink_handle_t *mesh, const struct addrinfo *aip) {
305         int nfd = socket(aip->ai_family, SOCK_STREAM, IPPROTO_TCP);
306
307         if(nfd == -1) {
308                 return -1;
309         }
310
311 #ifdef FD_CLOEXEC
312         fcntl(nfd, F_SETFD, FD_CLOEXEC);
313 #endif
314
315         int option = 1;
316         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
317
318 #if defined(IPV6_V6ONLY)
319
320         if(aip->ai_family == AF_INET6) {
321                 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
322         }
323
324 #else
325 #warning IPV6_V6ONLY not defined
326 #endif
327
328         if(bind(nfd, aip->ai_addr, aip->ai_addrlen)) {
329                 closesocket(nfd);
330                 return -1;
331         }
332
333         if(listen(nfd, 3)) {
334                 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
335                 closesocket(nfd);
336                 return -1;
337         }
338
339         return nfd;
340 }
341
342 int setup_udp_listen_socket(meshlink_handle_t *mesh, const struct addrinfo *aip) {
343         int nfd = socket(aip->ai_family, SOCK_DGRAM, IPPROTO_UDP);
344
345         if(nfd == -1) {
346                 return -1;
347         }
348
349 #ifdef FD_CLOEXEC
350         fcntl(nfd, F_SETFD, FD_CLOEXEC);
351 #endif
352
353 #ifdef O_NONBLOCK
354         int flags = fcntl(nfd, F_GETFL);
355
356         if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
357                 closesocket(nfd);
358                 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "fcntl", strerror(errno));
359                 return -1;
360         }
361
362 #elif defined(WIN32)
363         unsigned long arg = 1;
364
365         if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
366                 closesocket(nfd);
367                 logger(mesh, MESHLINK_ERROR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
368                 return -1;
369         }
370
371 #endif
372
373         int option = 1;
374         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
375         setsockopt(nfd, SOL_SOCKET, SO_BROADCAST, (void *)&option, sizeof(option));
376
377 #if defined(IPV6_V6ONLY)
378
379         if(aip->ai_family == AF_INET6) {
380                 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
381         }
382
383 #endif
384
385 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
386 #define IP_DONTFRAGMENT IP_DONTFRAG
387 #endif
388
389 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
390         option = IP_PMTUDISC_DO;
391         setsockopt(nfd, IPPROTO_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
392 #elif defined(IP_DONTFRAGMENT)
393         option = 1;
394         setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
395 #endif
396
397         if(aip->ai_family == AF_INET6) {
398 #if defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
399                 option = IPV6_PMTUDISC_DO;
400                 setsockopt(nfd, IPPROTO_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
401 #elif defined(IPV6_DONTFRAG)
402                 option = 1;
403                 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
404 #endif
405         }
406
407         if(bind(nfd, aip->ai_addr, aip->ai_addrlen)) {
408                 closesocket(nfd);
409                 return -1;
410         }
411
412         return nfd;
413 }
414
415 /*
416   Add listening sockets.
417 */
418 static bool add_listen_sockets(meshlink_handle_t *mesh) {
419         struct addrinfo *ai;
420
421         struct addrinfo hint = {
422                 .ai_family = AF_UNSPEC,
423                 .ai_socktype = SOCK_STREAM,
424                 .ai_protocol = IPPROTO_TCP,
425                 .ai_flags = AI_PASSIVE,
426         };
427
428         int err = getaddrinfo(NULL, mesh->myport, &hint, &ai);
429
430         if(err || !ai) {
431                 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getaddrinfo", err == EAI_SYSTEM ? strerror(err) : gai_strerror(err));
432                 return false;
433         }
434
435         bool success = false;
436
437         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
438                 // Ignore duplicate addresses
439                 bool found = false;
440
441                 for(int i = 0; i < mesh->listen_sockets; i++) {
442                         if(!memcmp(&mesh->listen_socket[i].sa, aip->ai_addr, aip->ai_addrlen)) {
443                                 found = true;
444                                 break;
445                         }
446                 }
447
448                 if(found) {
449                         continue;
450                 }
451
452                 if(mesh->listen_sockets >= MAXSOCKETS) {
453                         logger(mesh, MESHLINK_ERROR, "Too many listening sockets");
454                         return false;
455                 }
456
457                 /* Try to bind to TCP */
458
459                 int tcp_fd = setup_tcp_listen_socket(mesh, aip);
460
461                 if(tcp_fd == -1) {
462                         if(errno == EADDRINUSE) {
463                                 /* If this port is in use for any address family, avoid it. */
464                                 success = false;
465                                 break;
466                         } else {
467                                 continue;
468                         }
469                 }
470
471                 /* If TCP worked, then we require that UDP works as well. */
472
473                 int udp_fd = setup_udp_listen_socket(mesh, aip);
474
475                 if(udp_fd == -1) {
476                         closesocket(tcp_fd);
477                         success = false;
478                         break;
479                 }
480
481                 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);
482                 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);
483
484                 if(mesh->log_level <= MESHLINK_INFO) {
485                         char *hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
486                         logger(mesh, MESHLINK_INFO, "Listening on %s", hostname);
487                         free(hostname);
488                 }
489
490                 memcpy(&mesh->listen_socket[mesh->listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
491                 memcpy(&mesh->listen_socket[mesh->listen_sockets].broadcast_sa, aip->ai_addr, aip->ai_addrlen);
492
493                 if(aip->ai_family == AF_INET6) {
494                         mesh->listen_socket[mesh->listen_sockets].broadcast_sa.in6.sin6_addr.s6_addr[0x0] = 0xff;
495                         mesh->listen_socket[mesh->listen_sockets].broadcast_sa.in6.sin6_addr.s6_addr[0x1] = 0x02;
496                         mesh->listen_socket[mesh->listen_sockets].broadcast_sa.in6.sin6_addr.s6_addr[0xf] = 0x01;
497                 } else {
498                         mesh->listen_socket[mesh->listen_sockets].broadcast_sa.in.sin_addr.s_addr = 0xffffffff;
499                 }
500
501                 mesh->listen_sockets++;
502                 success = true;
503         }
504
505         freeaddrinfo(ai);
506
507         if(!success) {
508                 for(int i = 0; i < mesh->listen_sockets; i++) {
509                         io_del(&mesh->loop, &mesh->listen_socket[i].tcp);
510                         io_del(&mesh->loop, &mesh->listen_socket[i].udp);
511                         close(mesh->listen_socket[i].tcp.fd);
512                         close(mesh->listen_socket[i].udp.fd);
513                 }
514
515                 mesh->listen_sockets = 0;
516         }
517
518         return success;
519 }
520
521 /*
522   Configure node_t mesh->self and set up the local sockets (listen only)
523 */
524 bool setup_myself(meshlink_handle_t *mesh) {
525         /* Set some defaults */
526
527         mesh->maxtimeout = 900;
528
529         /* Done */
530
531         mesh->self->nexthop = mesh->self;
532
533         node_add(mesh, mesh->self);
534
535         if(!config_scan_all(mesh, "current", "hosts", load_node, NULL)) {
536                 logger(mesh, MESHLINK_WARNING, "Could not scan all host config files");
537         }
538
539         /* Open sockets */
540
541         mesh->listen_sockets = 0;
542
543         if(!add_listen_sockets(mesh)) {
544                 if(strcmp(mesh->myport, "0")) {
545                         logger(mesh, MESHLINK_WARNING, "Could not bind to port %s, trying to find an alternative port", mesh->myport);
546
547                         if(!check_port(mesh)) {
548                                 logger(mesh, MESHLINK_WARNING, "Could not bind to any port, trying to bind to port 0");
549                                 free(mesh->myport);
550                                 mesh->myport = xstrdup("0");
551                         }
552
553                         if(!add_listen_sockets(mesh)) {
554                                 return false;
555                         }
556                 } else {
557                         return false;
558                 }
559         }
560
561         if(!mesh->listen_sockets) {
562                 logger(mesh, MESHLINK_ERROR, "Unable to create any listening socket!");
563                 return false;
564         }
565
566         /* Done. */
567
568         mesh->last_unreachable = mesh->loop.now.tv_sec;
569
570         return true;
571 }
572
573 /*
574   initialize network
575 */
576 bool setup_network(meshlink_handle_t *mesh) {
577         init_connections(mesh);
578         init_submeshes(mesh);
579         init_nodes(mesh);
580         init_edges(mesh);
581         init_requests(mesh);
582
583         if(!setup_myself(mesh)) {
584                 return false;
585         }
586
587         return true;
588 }
589
590 /*
591   close all open network connections
592 */
593 void close_network_connections(meshlink_handle_t *mesh) {
594         if(mesh->connections) {
595                 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
596                         next = node->next;
597                         connection_t *c = node->data;
598                         c->outgoing = NULL;
599                         terminate_connection(mesh, c, false);
600                 }
601         }
602
603         for(int i = 0; i < mesh->listen_sockets; i++) {
604                 io_del(&mesh->loop, &mesh->listen_socket[i].tcp);
605                 io_del(&mesh->loop, &mesh->listen_socket[i].udp);
606                 close(mesh->listen_socket[i].tcp.fd);
607                 close(mesh->listen_socket[i].udp.fd);
608         }
609
610         exit_requests(mesh);
611         exit_edges(mesh);
612         exit_nodes(mesh);
613         exit_submeshes(mesh);
614         exit_connections(mesh);
615
616         free(mesh->myport);
617         mesh->myport = NULL;
618
619         mesh->self = NULL;
620
621         return;
622 }