3 Copyright (C) 2014-2017 Guus Sliepen <guus@meshlink.io>
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.
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.
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.
23 #include "connection.h"
27 #include "meshlink_internal.h"
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)) {
43 in->ptr = config->buf;
44 in->len = config->len;
46 uint32_t version = packmsg_get_uint32(in);
48 if(version != MESHLINK_CONFIG_VERSION) {
49 logger(mesh, MESHLINK_ERROR, "Invalid config file for node %s", n->name);
55 uint32_t len = packmsg_get_str_raw(in, &name);
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);
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)) {
75 if(!node_get_config(mesh, n, &config, &in)) {
79 packmsg_skip_element(&in); /* submesh */
80 packmsg_get_int32(&in); /* devclass */
81 packmsg_get_bool(&in); /* blacklisted */
84 uint32_t len = packmsg_get_bin_raw(&in, &key);
91 n->ecdsa = ecdsa_set_public_key(key);
93 // While we are at it, read known address information
94 if(!n->canonical_address) {
95 n->canonical_address = packmsg_get_str_dup(&in);
97 if(!*n->canonical_address) {
98 free(n->canonical_address);
99 n->canonical_address = NULL;
102 packmsg_skip_element(&in);
105 // Append any known addresses in the config file to the list we currently have
106 uint32_t known_count = 0;
108 for(uint32_t i = 0; i < MAX_RECENT; i++) {
109 if(n->recent[i].sa.sa_family) {
114 uint32_t count = packmsg_get_array(&in);
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);
120 packmsg_skip_element(&in);
124 time_t last_reachable = packmsg_get_int64(&in);
125 time_t last_unreachable = packmsg_get_int64(&in);
127 if(!n->last_reachable) {
128 n->last_reachable = last_reachable;
131 if(!n->last_unreachable) {
132 n->last_unreachable = last_unreachable;
135 config_free(&config);
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) {
145 packmsg_input_t in = {config->buf, config->len};
146 uint32_t version = packmsg_get_uint32(&in);
148 if(version != MESHLINK_CONFIG_VERSION) {
152 char *name = packmsg_get_str_dup(&in);
159 if(strcmp(n->name, name)) {
169 char *submesh_name = packmsg_get_str_dup(&in);
171 if(!strcmp(submesh_name, CORE_MESH)) {
175 n->submesh = lookup_or_create_submesh(mesh, submesh_name);
183 n->devclass = packmsg_get_int32(&in);
184 n->status.blacklisted = packmsg_get_bool(&in);
186 uint32_t len = packmsg_get_bin_raw(&in, &key);
193 if(!ecdsa_active(n->ecdsa)) {
194 n->ecdsa = ecdsa_set_public_key(key);
198 n->canonical_address = packmsg_get_str_dup(&in);
200 if(!*n->canonical_address) {
201 free(n->canonical_address);
202 n->canonical_address = NULL;
205 uint32_t count = packmsg_get_array(&in);
207 for(uint32_t i = 0; i < count; i++) {
209 n->recent[i] = packmsg_get_sockaddr(&in);
211 packmsg_skip_element(&in);
215 n->last_reachable = packmsg_get_int64(&in);
216 n->last_unreachable = packmsg_get_int64(&in);
218 return packmsg_done(&in);
221 bool node_write_config(meshlink_handle_t *mesh, node_t *n, bool new_key) {
222 if(!mesh->confbase) {
226 switch(mesh->storage_policy) {
227 case MESHLINK_STORAGE_KEYS_ONLY:
234 case MESHLINK_STORAGE_DISABLED:
242 packmsg_output_t out = {buf, sizeof(buf)};
244 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
245 packmsg_add_str(&out, n->name);
246 packmsg_add_str(&out, n->submesh ? n->submesh->name : CORE_MESH);
247 packmsg_add_int32(&out, n->devclass);
248 packmsg_add_bool(&out, n->status.blacklisted);
250 if(ecdsa_active(n->ecdsa)) {
251 packmsg_add_bin(&out, ecdsa_get_public_key(n->ecdsa), 32);
253 packmsg_add_bin(&out, "", 0);
256 packmsg_add_str(&out, n->canonical_address ? n->canonical_address : "");
260 for(uint32_t i = 0; i < MAX_RECENT; i++) {
261 if(n->recent[i].sa.sa_family) {
268 packmsg_add_array(&out, count);
270 for(uint32_t i = 0; i < count; i++) {
271 packmsg_add_sockaddr(&out, &n->recent[i]);
274 packmsg_add_int64(&out, n->last_reachable);
275 packmsg_add_int64(&out, n->last_unreachable);
277 if(!packmsg_output_ok(&out)) {
278 meshlink_errno = MESHLINK_EINTERNAL;
282 config_t config = {buf, packmsg_output_size(&out, buf)};
284 if(!config_write(mesh, "current", n->name, &config, mesh->config_key)) {
285 call_error_cb(mesh, MESHLINK_ESTORAGE);
289 n->status.dirty = false;
293 static bool load_node(meshlink_handle_t *mesh, const char *name, void *priv) {
296 if(!check_id(name)) {
297 // Check if this is a temporary file, if so remove it
298 const char *suffix = strstr(name, ".tmp");
300 if(suffix && !suffix[4]) {
301 char filename[PATH_MAX];
302 snprintf(filename, sizeof(filename), "%s" SLASH "current" SLASH "hosts", mesh->confbase);
309 node_t *n = lookup_node(mesh, name);
316 n->name = xstrdup(name);
321 if(!node_get_config(mesh, n, &config, &in)) {
326 if(!node_read_from_config(mesh, n, &config)) {
327 logger(mesh, MESHLINK_ERROR, "Invalid config file for node %s", n->name);
328 config_free(&config);
333 config_free(&config);
340 int setup_tcp_listen_socket(meshlink_handle_t *mesh, const struct addrinfo *aip) {
341 int nfd = socket(aip->ai_family, SOCK_STREAM, IPPROTO_TCP);
348 fcntl(nfd, F_SETFD, FD_CLOEXEC);
352 int flags = fcntl(nfd, F_GETFL);
354 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
356 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "fcntl", strerror(errno));
361 unsigned long arg = 1;
363 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
365 logger(mesh, MESHLINK_ERROR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
371 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
373 #if defined(IPV6_V6ONLY)
375 if(aip->ai_family == AF_INET6) {
376 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
380 #warning IPV6_V6ONLY not defined
383 if(bind(nfd, aip->ai_addr, aip->ai_addrlen)) {
389 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
397 int setup_udp_listen_socket(meshlink_handle_t *mesh, const struct addrinfo *aip) {
398 int nfd = socket(aip->ai_family, SOCK_DGRAM, IPPROTO_UDP);
405 fcntl(nfd, F_SETFD, FD_CLOEXEC);
409 int flags = fcntl(nfd, F_GETFL);
411 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
413 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "fcntl", strerror(errno));
418 unsigned long arg = 1;
420 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
422 logger(mesh, MESHLINK_ERROR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
429 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
430 setsockopt(nfd, SOL_SOCKET, SO_BROADCAST, (void *)&option, sizeof(option));
432 #if defined(IPV6_V6ONLY)
434 if(aip->ai_family == AF_INET6) {
435 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
440 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
441 #define IP_DONTFRAGMENT IP_DONTFRAG
444 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
445 option = IP_PMTUDISC_DO;
446 setsockopt(nfd, IPPROTO_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
447 #elif defined(IP_DONTFRAGMENT)
449 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
452 if(aip->ai_family == AF_INET6) {
453 #if defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
454 option = IPV6_PMTUDISC_DO;
455 setsockopt(nfd, IPPROTO_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
456 #elif defined(IPV6_DONTFRAG)
458 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
462 if(bind(nfd, aip->ai_addr, aip->ai_addrlen)) {
471 Add listening sockets.
473 static bool add_listen_sockets(meshlink_handle_t *mesh) {
476 struct addrinfo hint = {
477 .ai_family = AF_UNSPEC,
478 .ai_socktype = SOCK_STREAM,
479 .ai_protocol = IPPROTO_TCP,
480 .ai_flags = AI_PASSIVE | AI_NUMERICSERV,
483 int err = getaddrinfo(NULL, mesh->myport, &hint, &ai);
486 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getaddrinfo", err == EAI_SYSTEM ? strerror(err) : gai_strerror(err));
490 bool success = false;
492 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
493 // Ignore duplicate addresses
496 for(int i = 0; i < mesh->listen_sockets; i++) {
497 if(!memcmp(&mesh->listen_socket[i].sa, aip->ai_addr, aip->ai_addrlen)) {
507 if(mesh->listen_sockets >= MAXSOCKETS) {
508 logger(mesh, MESHLINK_ERROR, "Too many listening sockets");
512 /* Try to bind to TCP */
514 int tcp_fd = setup_tcp_listen_socket(mesh, aip);
517 if(errno == EADDRINUSE) {
518 /* If this port is in use for any address family, avoid it. */
526 /* If TCP worked, then we require that UDP works as well. */
528 int udp_fd = setup_udp_listen_socket(mesh, aip);
536 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);
537 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);
539 if(mesh->log_level <= MESHLINK_INFO) {
540 char *hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
541 logger(mesh, MESHLINK_INFO, "Listening on %s", hostname);
545 memcpy(&mesh->listen_socket[mesh->listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
546 memcpy(&mesh->listen_socket[mesh->listen_sockets].broadcast_sa, aip->ai_addr, aip->ai_addrlen);
548 if(aip->ai_family == AF_INET6) {
549 mesh->listen_socket[mesh->listen_sockets].broadcast_sa.in6.sin6_addr.s6_addr[0x0] = 0xff;
550 mesh->listen_socket[mesh->listen_sockets].broadcast_sa.in6.sin6_addr.s6_addr[0x1] = 0x02;
551 mesh->listen_socket[mesh->listen_sockets].broadcast_sa.in6.sin6_addr.s6_addr[0xf] = 0x01;
553 mesh->listen_socket[mesh->listen_sockets].broadcast_sa.in.sin_addr.s_addr = 0xffffffff;
556 mesh->listen_sockets++;
563 for(int i = 0; i < mesh->listen_sockets; i++) {
564 io_del(&mesh->loop, &mesh->listen_socket[i].tcp);
565 io_del(&mesh->loop, &mesh->listen_socket[i].udp);
566 closesocket(mesh->listen_socket[i].tcp.fd);
567 closesocket(mesh->listen_socket[i].udp.fd);
570 mesh->listen_sockets = 0;
577 Configure node_t mesh->self and set up the local sockets (listen only)
579 static bool setup_myself(meshlink_handle_t *mesh) {
580 mesh->self->nexthop = mesh->self;
582 node_add(mesh, mesh->self);
584 if(!config_scan_all(mesh, "current", "hosts", load_node, NULL)) {
585 logger(mesh, MESHLINK_WARNING, "Could not scan all host config files");
590 mesh->listen_sockets = 0;
592 if(!add_listen_sockets(mesh)) {
593 if(strcmp(mesh->myport, "0")) {
594 logger(mesh, MESHLINK_WARNING, "Could not bind to port %s, trying to find an alternative port", mesh->myport);
596 if(!check_port(mesh)) {
597 logger(mesh, MESHLINK_WARNING, "Could not bind to any port, trying to bind to port 0");
599 mesh->myport = xstrdup("0");
602 if(!add_listen_sockets(mesh)) {
610 if(!mesh->listen_sockets) {
611 logger(mesh, MESHLINK_ERROR, "Unable to create any listening socket!");
617 mesh->last_unreachable = mesh->loop.now.tv_sec;
625 bool setup_network(meshlink_handle_t *mesh) {
626 init_connections(mesh);
627 init_submeshes(mesh);
632 if(!setup_myself(mesh)) {
640 close all open network connections
642 void close_network_connections(meshlink_handle_t *mesh) {
643 if(mesh->connections) {
644 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
646 connection_t *c = node->data;
648 terminate_connection(mesh, c, false);
652 for(int i = 0; i < mesh->listen_sockets; i++) {
653 io_del(&mesh->loop, &mesh->listen_socket[i].tcp);
654 io_del(&mesh->loop, &mesh->listen_socket[i].udp);
655 closesocket(mesh->listen_socket[i].tcp.fd);
656 closesocket(mesh->listen_socket[i].udp.fd);
662 exit_submeshes(mesh);
663 exit_connections(mesh);