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