2 meshlink.c -- Implementation of the MeshLink API.
3 Copyright (C) 2014-2021 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.
26 #include "meshlink_internal.h"
36 #include "ed25519/sha512.h"
40 #define MSG_NOSIGNAL 0
42 __thread meshlink_errno_t meshlink_errno;
43 meshlink_log_cb_t global_log_cb;
44 meshlink_log_level_t global_log_level;
46 typedef bool (*search_node_by_condition_t)(const node_t *, const void *);
48 static int rstrip(char *value) {
49 int len = strlen(value);
51 while(len && strchr("\t\r\n ", value[len - 1])) {
58 static bool is_valid_hostname(const char *hostname) {
63 for(const char *p = hostname; *p; p++) {
64 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
72 static bool is_valid_port(const char *port) {
79 unsigned long int result = strtoul(port, &end, 10);
80 return result && result < 65536 && !*end;
83 for(const char *p = port; *p; p++) {
84 if(!(isalnum(*p) || *p == '-')) {
92 static void set_timeout(int sock, int timeout) {
97 tv.tv_sec = timeout / 1000;
98 tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
100 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
101 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
104 struct socket_in_netns_params {
113 static void *socket_in_netns_thread(void *arg) {
114 struct socket_in_netns_params *params = arg;
116 if(setns(params->netns, CLONE_NEWNET) == -1) {
117 meshlink_errno = MESHLINK_EINVAL;
121 params->fd = socket(params->domain, params->type, params->protocol);
127 static int socket_in_netns(int domain, int type, int protocol, int netns) {
129 return socket(domain, type, protocol);
133 struct socket_in_netns_params params = {domain, type, protocol, netns, -1};
137 if(pthread_create(&thr, NULL, socket_in_netns_thread, ¶ms) == 0) {
138 if(pthread_join(thr, NULL) != 0) {
150 static bool write_main_config_files(meshlink_handle_t *mesh) {
151 if(!mesh->confbase) {
157 /* Write the main config file */
158 packmsg_output_t out = {buf, sizeof buf};
160 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
161 packmsg_add_str(&out, mesh->name);
162 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
163 packmsg_add_nil(&out); // Invitation keys are not supported
164 packmsg_add_uint16(&out, atoi(mesh->myport));
166 if(!packmsg_output_ok(&out)) {
170 config_t config = {buf, packmsg_output_size(&out, buf)};
172 if(!main_config_write(mesh, "current", &config, mesh->config_key)) {
176 /* Write our own host config file */
177 if(!node_write_config(mesh, mesh->self, true)) {
185 meshlink_handle_t *mesh;
187 char cookie[18 + 32];
198 static bool finalize_join(join_state_t *state, const void *buf, uint16_t len) {
199 meshlink_handle_t *mesh = state->mesh;
200 packmsg_input_t in = {buf, len};
201 uint32_t version = packmsg_get_uint32(&in);
203 if(version != MESHLINK_INVITATION_VERSION) {
204 logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
208 char *name = packmsg_get_str_dup(&in);
209 packmsg_skip_element(&in); // submesh_name
210 dev_class_t devclass = packmsg_get_int32(&in);
211 uint32_t count = packmsg_get_array(&in);
213 if(!name || !check_id(name)) {
214 logger(mesh, MESHLINK_DEBUG, "No valid Name found in invitation!\n");
220 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
226 free(mesh->self->name);
228 mesh->self->name = xstrdup(name);
229 mesh->self->devclass = devclass == DEV_CLASS_UNKNOWN ? mesh->devclass : devclass;
231 // Initialize configuration directory
232 if(!config_init(mesh, "current")) {
236 if(!write_main_config_files(mesh)) {
240 // Write host config files
241 for(uint32_t i = 0; i < count; i++) {
243 uint32_t data_len = packmsg_get_bin_raw(&in, &data);
246 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
250 packmsg_input_t in2 = {data, data_len};
251 uint32_t version2 = packmsg_get_uint32(&in2);
252 char *name2 = packmsg_get_str_dup(&in2);
254 if(!packmsg_input_ok(&in2) || version2 != MESHLINK_CONFIG_VERSION || !check_id(name2)) {
256 packmsg_input_invalidate(&in);
260 if(!check_id(name2)) {
265 if(!strcmp(name2, mesh->name)) {
266 logger(mesh, MESHLINK_ERROR, "Secondary chunk would overwrite our own host config file.\n");
268 meshlink_errno = MESHLINK_EPEER;
272 node_t *n = new_node();
275 config_t config = {data, data_len};
277 if(!node_read_from_config(mesh, n, &config)) {
279 logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
280 meshlink_errno = MESHLINK_EPEER;
285 /* The first host config file is of the inviter itself;
286 * remember the address we are currently using for the invitation connection.
289 socklen_t salen = sizeof(sa);
291 if(getpeername(state->sock, &sa.sa, &salen) == 0) {
292 node_add_recent_address(mesh, n, &sa);
296 if(!node_write_config(mesh, n, true)) {
304 /* Ensure the configuration directory metadata is on disk */
305 if(!config_sync(mesh, "current") || (mesh->confbase && !sync_path(mesh->confbase))) {
309 if(!mesh->inviter_commits_first) {
310 devtool_set_inviter_commits_first(false);
313 sptps_send_record(&state->sptps, 1, ecdsa_get_public_key(mesh->private_key), 32);
315 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
320 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
322 join_state_t *state = handle;
323 const char *ptr = data;
326 int result = send(state->sock, ptr, len, 0);
328 if(result == -1 && errno == EINTR) {
330 } else if(result <= 0) {
341 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
342 join_state_t *state = handle;
343 meshlink_handle_t *mesh = state->mesh;
345 if(mesh->inviter_commits_first) {
347 case SPTPS_HANDSHAKE:
348 return sptps_send_record(&state->sptps, 2, state->cookie, 18 + 32);
354 if(!finalize_join(state, msg, len)) {
358 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
359 shutdown(state->sock, SHUT_RDWR);
360 state->success = true;
368 case SPTPS_HANDSHAKE:
369 return sptps_send_record(&state->sptps, 0, state->cookie, 18);
372 return finalize_join(state, msg, len);
375 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
376 shutdown(state->sock, SHUT_RDWR);
377 state->success = true;
388 static bool recvline(join_state_t *state) {
389 char *newline = NULL;
391 while(!(newline = memchr(state->buffer, '\n', state->blen))) {
392 int result = recv(state->sock, state->buffer + state->blen, sizeof(state)->buffer - state->blen, 0);
394 if(result == -1 && errno == EINTR) {
396 } else if(result <= 0) {
400 state->blen += result;
403 if((size_t)(newline - state->buffer) >= sizeof(state->line)) {
407 size_t len = newline - state->buffer;
409 memcpy(state->line, state->buffer, len);
410 state->line[len] = 0;
411 memmove(state->buffer, newline + 1, state->blen - len - 1);
412 state->blen -= len + 1;
417 static bool sendline(int fd, const char *format, ...) {
423 va_start(ap, format);
424 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
427 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
435 int result = send(fd, p, blen, MSG_NOSIGNAL);
437 if(result == -1 && errno == EINTR) {
439 } else if(result <= 0) {
450 static const char *errstr[] = {
451 [MESHLINK_OK] = "No error",
452 [MESHLINK_EINVAL] = "Invalid argument",
453 [MESHLINK_ENOMEM] = "Out of memory",
454 [MESHLINK_ENOENT] = "No such node",
455 [MESHLINK_EEXIST] = "Node already exists",
456 [MESHLINK_EINTERNAL] = "Internal error",
457 [MESHLINK_ERESOLV] = "Could not resolve hostname",
458 [MESHLINK_ESTORAGE] = "Storage error",
459 [MESHLINK_ENETWORK] = "Network error",
460 [MESHLINK_EPEER] = "Error communicating with peer",
461 [MESHLINK_ENOTSUP] = "Operation not supported",
462 [MESHLINK_EBUSY] = "MeshLink instance already in use",
463 [MESHLINK_EBLACKLISTED] = "Node is blacklisted",
466 const char *meshlink_strerror(meshlink_errno_t err) {
467 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
468 return "Invalid error code";
474 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
475 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
477 mesh->private_key = ecdsa_generate();
479 if(!mesh->private_key) {
480 logger(mesh, MESHLINK_ERROR, "Error during key generation!\n");
481 meshlink_errno = MESHLINK_EINTERNAL;
485 logger(mesh, MESHLINK_DEBUG, "Done.\n");
490 static struct timespec idle(event_loop_t *loop, void *data) {
494 return (struct timespec) {
499 static bool meshlink_setup(meshlink_handle_t *mesh) {
500 if(!config_destroy(mesh->confbase, "new")) {
501 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/new: %s\n", mesh->confbase, strerror(errno));
502 meshlink_errno = MESHLINK_ESTORAGE;
506 if(!config_destroy(mesh->confbase, "old")) {
507 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
508 meshlink_errno = MESHLINK_ESTORAGE;
512 if(!config_init(mesh, "current")) {
513 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
514 meshlink_errno = MESHLINK_ESTORAGE;
518 if(!ecdsa_keygen(mesh)) {
519 meshlink_errno = MESHLINK_EINTERNAL;
523 mesh->myport = xstrdup("0");
525 /* Create a node for ourself */
527 mesh->self = new_node();
528 mesh->self->name = xstrdup(mesh->name);
529 mesh->self->devclass = mesh->devclass;
530 mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
531 mesh->self->session_id = mesh->session_id;
533 if(!write_main_config_files(mesh)) {
534 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
535 meshlink_errno = MESHLINK_ESTORAGE;
539 /* Ensure the configuration directory metadata is on disk */
540 if(!config_sync(mesh, "current")) {
547 static bool meshlink_read_config(meshlink_handle_t *mesh) {
550 if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
551 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
555 packmsg_input_t in = {config.buf, config.len};
556 const void *private_key;
558 uint32_t version = packmsg_get_uint32(&in);
559 char *name = packmsg_get_str_dup(&in);
560 uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
561 packmsg_skip_element(&in); // Invitation key is not supported
562 uint16_t myport = packmsg_get_uint16(&in);
564 if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96) {
565 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
567 config_free(&config);
571 if(mesh->name && strcmp(mesh->name, name)) {
572 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
573 meshlink_errno = MESHLINK_ESTORAGE;
575 config_free(&config);
581 xasprintf(&mesh->myport, "%u", myport);
582 mesh->private_key = ecdsa_set_private_key(private_key);
583 config_free(&config);
585 /* Create a node for ourself and read our host configuration file */
587 mesh->self = new_node();
588 mesh->self->name = xstrdup(name);
589 mesh->self->devclass = mesh->devclass;
590 mesh->self->session_id = mesh->session_id;
592 if(!node_read_public_key(mesh, mesh->self)) {
593 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
594 meshlink_errno = MESHLINK_ESTORAGE;
595 free_node(mesh->self);
604 static void *setup_network_in_netns_thread(void *arg) {
605 meshlink_handle_t *mesh = arg;
607 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
611 bool success = setup_network(mesh);
612 return success ? arg : NULL;
616 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
617 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_init(%s, %s, %s, %d)", confbase, name, appname, devclass);
619 if(!confbase || !*confbase) {
620 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
621 meshlink_errno = MESHLINK_EINVAL;
625 if(!appname || !*appname) {
626 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
627 meshlink_errno = MESHLINK_EINVAL;
631 if(strchr(appname, ' ')) {
632 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
633 meshlink_errno = MESHLINK_EINVAL;
637 if(name && !check_id(name)) {
638 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
639 meshlink_errno = MESHLINK_EINVAL;
643 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
644 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
645 meshlink_errno = MESHLINK_EINVAL;
649 meshlink_open_params_t *params = xzalloc(sizeof * params);
651 params->confbase = xstrdup(confbase);
652 params->name = name ? xstrdup(name) : NULL;
653 params->appname = xstrdup(appname);
654 params->devclass = devclass;
657 xasprintf(¶ms->lock_filename, "%s" SLASH "meshlink.lock", confbase);
662 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
663 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_netnst(%d)", netns);
666 meshlink_errno = MESHLINK_EINVAL;
670 params->netns = netns;
675 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
676 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_key(%p, %zu)", key, keylen);
679 meshlink_errno = MESHLINK_EINVAL;
683 if((!key && keylen) || (key && !keylen)) {
684 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
685 meshlink_errno = MESHLINK_EINVAL;
690 params->keylen = keylen;
695 bool meshlink_open_params_set_storage_policy(meshlink_open_params_t *params, meshlink_storage_policy_t policy) {
696 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_policy(%d)", policy);
699 meshlink_errno = MESHLINK_EINVAL;
703 params->storage_policy = policy;
708 bool meshlink_open_params_set_lock_filename(meshlink_open_params_t *params, const char *filename) {
709 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_lock_filename(%s)", filename);
711 if(!params || !filename) {
712 meshlink_errno = MESHLINK_EINVAL;
716 free(params->lock_filename);
717 params->lock_filename = xstrdup(filename);
722 bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
723 logger(NULL, MESHLINK_DEBUG, "meshlink_encrypted_key_rotate(%p, %zu)", new_key, new_keylen);
725 if(!mesh || !new_key || !new_keylen) {
726 logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
727 meshlink_errno = MESHLINK_EINVAL;
731 if(pthread_mutex_lock(&mesh->mutex) != 0) {
735 // Create hash for the new key
736 void *new_config_key;
737 new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
739 if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
740 logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
741 meshlink_errno = MESHLINK_EINTERNAL;
742 pthread_mutex_unlock(&mesh->mutex);
746 // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
748 if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
749 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
750 meshlink_errno = MESHLINK_ESTORAGE;
751 pthread_mutex_unlock(&mesh->mutex);
755 devtool_keyrotate_probe(1);
757 // Rename confbase/current/ to confbase/old
759 if(!config_rename(mesh, "current", "old")) {
760 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
761 meshlink_errno = MESHLINK_ESTORAGE;
762 pthread_mutex_unlock(&mesh->mutex);
766 devtool_keyrotate_probe(2);
768 // Rename confbase/new/ to confbase/current
770 if(!config_rename(mesh, "new", "current")) {
771 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
772 meshlink_errno = MESHLINK_ESTORAGE;
773 pthread_mutex_unlock(&mesh->mutex);
777 devtool_keyrotate_probe(3);
779 // Cleanup the "old" confbase sub-directory
781 if(!config_destroy(mesh->confbase, "old")) {
782 pthread_mutex_unlock(&mesh->mutex);
786 // Change the mesh handle key with new key
788 free(mesh->config_key);
789 mesh->config_key = new_config_key;
791 pthread_mutex_unlock(&mesh->mutex);
796 void meshlink_open_params_free(meshlink_open_params_t *params) {
797 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_free()");
800 meshlink_errno = MESHLINK_EINVAL;
804 free(params->confbase);
806 free(params->appname);
807 free(params->lock_filename);
812 /// Device class traits
813 static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
814 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
815 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
816 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
817 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN
820 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
821 logger(NULL, MESHLINK_DEBUG, "meshlink_open(%s, %s, %s, %d)", confbase, name, appname, devclass);
823 if(!confbase || !*confbase) {
824 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
825 meshlink_errno = MESHLINK_EINVAL;
829 char lock_filename[PATH_MAX];
830 snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
832 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
833 meshlink_open_params_t params = {
834 .confbase = (char *)confbase,
835 .lock_filename = lock_filename,
836 .name = (char *)name,
837 .appname = (char *)appname,
838 .devclass = devclass,
842 return meshlink_open_ex(¶ms);
845 meshlink_handle_t *meshlink_open_encrypted(const char *confbase, const char *name, const char *appname, dev_class_t devclass, const void *key, size_t keylen) {
846 logger(NULL, MESHLINK_DEBUG, "meshlink_open_encrypted(%s, %s, %s, %d, %p, %zu)", confbase, name, appname, devclass, key, keylen);
848 if(!confbase || !*confbase) {
849 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
850 meshlink_errno = MESHLINK_EINVAL;
854 char lock_filename[PATH_MAX];
855 snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
857 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
858 meshlink_open_params_t params = {
859 .confbase = (char *)confbase,
860 .lock_filename = lock_filename,
861 .name = (char *)name,
862 .appname = (char *)appname,
863 .devclass = devclass,
867 if(!meshlink_open_params_set_storage_key(¶ms, key, keylen)) {
871 return meshlink_open_ex(¶ms);
874 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
875 logger(NULL, MESHLINK_DEBUG, "meshlink_open_ephemeral(%s, %s, %d)", name, appname, devclass);
878 logger(NULL, MESHLINK_ERROR, "No name given!\n");
879 meshlink_errno = MESHLINK_EINVAL;
883 if(!check_id(name)) {
884 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
885 meshlink_errno = MESHLINK_EINVAL;
889 if(!appname || !*appname) {
890 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
891 meshlink_errno = MESHLINK_EINVAL;
895 if(strchr(appname, ' ')) {
896 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
897 meshlink_errno = MESHLINK_EINVAL;
901 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
902 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
903 meshlink_errno = MESHLINK_EINVAL;
907 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
908 meshlink_open_params_t params = {
909 .name = (char *)name,
910 .appname = (char *)appname,
911 .devclass = devclass,
915 return meshlink_open_ex(¶ms);
918 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
919 logger(NULL, MESHLINK_DEBUG, "meshlink_open_ex()");
921 // Validate arguments provided by the application
922 if(!params->appname || !*params->appname) {
923 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
924 meshlink_errno = MESHLINK_EINVAL;
928 if(strchr(params->appname, ' ')) {
929 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
930 meshlink_errno = MESHLINK_EINVAL;
934 if(params->name && !check_id(params->name)) {
935 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
936 meshlink_errno = MESHLINK_EINVAL;
940 if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
941 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
942 meshlink_errno = MESHLINK_EINVAL;
946 if((params->key && !params->keylen) || (!params->key && params->keylen)) {
947 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
948 meshlink_errno = MESHLINK_EINVAL;
952 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
954 if(params->confbase) {
955 mesh->confbase = xstrdup(params->confbase);
958 mesh->appname = xstrdup(params->appname);
959 mesh->devclass = params->devclass;
960 mesh->netns = params->netns;
961 mesh->log_cb = global_log_cb;
962 mesh->log_level = global_log_level;
963 mesh->packet = xmalloc(sizeof(vpn_packet_t));
965 randomize(&mesh->prng_state, sizeof(mesh->prng_state));
968 randomize(&mesh->session_id, sizeof(mesh->session_id));
969 } while(mesh->session_id == 0);
971 memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
973 mesh->name = params->name ? xstrdup(params->name) : NULL;
977 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
979 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
980 logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
981 meshlink_close(mesh);
982 meshlink_errno = MESHLINK_EINTERNAL;
987 // initialize mutexes and conds
988 pthread_mutexattr_t attr;
989 pthread_mutexattr_init(&attr);
991 if(pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) != 0) {
995 pthread_mutex_init(&mesh->mutex, &attr);
996 pthread_cond_init(&mesh->cond, NULL);
998 mesh->threadstarted = false;
999 event_loop_init(&mesh->loop);
1000 mesh->loop.data = mesh;
1002 meshlink_queue_init(&mesh->outpacketqueue);
1004 // Atomically lock the configuration directory.
1005 if(!main_config_lock(mesh, params->lock_filename)) {
1006 meshlink_close(mesh);
1010 // If no configuration exists yet, create it.
1012 bool new_configuration = false;
1014 if(!meshlink_confbase_exists(mesh)) {
1016 logger(NULL, MESHLINK_ERROR, "No configuration files found!\n");
1017 meshlink_close(mesh);
1018 meshlink_errno = MESHLINK_ESTORAGE;
1022 if(!meshlink_setup(mesh)) {
1023 logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1024 meshlink_close(mesh);
1028 new_configuration = true;
1030 if(!meshlink_read_config(mesh)) {
1031 logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1032 meshlink_close(mesh);
1037 mesh->storage_policy = params->storage_policy;
1040 struct WSAData wsa_state;
1041 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1044 // Setup up everything
1045 // TODO: we should not open listening sockets yet
1047 bool success = false;
1049 if(mesh->netns != -1) {
1053 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1054 void *retval = NULL;
1055 success = pthread_join(thr, &retval) == 0 && retval;
1059 meshlink_errno = MESHLINK_EINTERNAL;
1062 #endif // HAVE_SETNS
1064 success = setup_network(mesh);
1068 meshlink_close(mesh);
1069 meshlink_errno = MESHLINK_ENETWORK;
1073 if(!node_write_config(mesh, mesh->self, new_configuration)) {
1074 logger(NULL, MESHLINK_ERROR, "Cannot update configuration\n");
1078 idle_set(&mesh->loop, idle, mesh);
1080 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1084 static void *meshlink_main_loop(void *arg) {
1085 meshlink_handle_t *mesh = arg;
1087 if(mesh->netns != -1) {
1090 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1091 pthread_cond_signal(&mesh->cond);
1096 pthread_cond_signal(&mesh->cond);
1098 #endif // HAVE_SETNS
1101 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1105 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1106 pthread_cond_broadcast(&mesh->cond);
1108 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1110 pthread_mutex_unlock(&mesh->mutex);
1115 bool meshlink_start(meshlink_handle_t *mesh) {
1117 meshlink_errno = MESHLINK_EINVAL;
1121 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1123 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1128 assert(mesh->private_key);
1129 assert(mesh->self->ecdsa);
1130 assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1132 if(mesh->threadstarted) {
1133 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1134 pthread_mutex_unlock(&mesh->mutex);
1138 // Reset node connection timers
1140 mesh->peer->last_connect_try = 0;
1143 //Check that a valid name is set
1145 logger(mesh, MESHLINK_ERROR, "No name given!\n");
1146 meshlink_errno = MESHLINK_EINVAL;
1147 pthread_mutex_unlock(&mesh->mutex);
1151 init_outgoings(mesh);
1153 // Start the main thread
1155 event_loop_start(&mesh->loop);
1157 // Ensure we have a decent amount of stack space. Musl's default of 80 kB is too small.
1158 pthread_attr_t attr;
1159 pthread_attr_init(&attr);
1160 pthread_attr_setstacksize(&attr, 1024 * 1024);
1162 if(pthread_create(&mesh->thread, &attr, meshlink_main_loop, mesh) != 0) {
1163 logger(mesh, MESHLINK_ERROR, "Could not start thread: %s\n", strerror(errno));
1164 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1165 meshlink_errno = MESHLINK_EINTERNAL;
1166 event_loop_stop(&mesh->loop);
1167 pthread_mutex_unlock(&mesh->mutex);
1171 pthread_cond_wait(&mesh->cond, &mesh->mutex);
1172 mesh->threadstarted = true;
1174 pthread_mutex_unlock(&mesh->mutex);
1178 void meshlink_stop(meshlink_handle_t *mesh) {
1179 logger(mesh, MESHLINK_DEBUG, "meshlink_stop()\n");
1182 meshlink_errno = MESHLINK_EINVAL;
1186 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1190 // Shut down the main thread
1191 event_loop_stop(&mesh->loop);
1193 // TODO: send something to a local socket to kick the event loop
1195 if(mesh->threadstarted) {
1196 // Wait for the main thread to finish
1197 pthread_mutex_unlock(&mesh->mutex);
1199 if(pthread_join(mesh->thread, NULL) != 0) {
1203 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1207 mesh->threadstarted = false;
1210 // Close all metaconnections
1211 if(mesh->connection) {
1212 mesh->connection->outgoing = NULL;
1213 terminate_connection(mesh, mesh->connection, false);
1216 exit_outgoings(mesh);
1218 // Try to write out any changed node config files, ignore errors at this point.
1219 if(mesh->peer && mesh->peer->status.dirty) {
1220 if(!node_write_config(mesh, mesh->peer, false)) {
1225 pthread_mutex_unlock(&mesh->mutex);
1228 void meshlink_close(meshlink_handle_t *mesh) {
1229 logger(mesh, MESHLINK_DEBUG, "meshlink_close()\n");
1232 meshlink_errno = MESHLINK_EINVAL;
1236 // stop can be called even if mesh has not been started
1237 meshlink_stop(mesh);
1239 // lock is not released after this
1240 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1244 // Close and free all resources used.
1246 close_network_connections(mesh);
1248 logger(mesh, MESHLINK_INFO, "Terminating");
1250 event_loop_exit(&mesh->loop);
1254 if(mesh->confbase) {
1260 if(mesh->netns != -1) {
1264 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1268 meshlink_queue_exit(&mesh->outpacketqueue);
1271 free(mesh->appname);
1272 free(mesh->confbase);
1273 free(mesh->config_key);
1274 free(mesh->external_address_url);
1276 ecdsa_free(mesh->private_key);
1278 main_config_unlock(mesh);
1280 pthread_mutex_unlock(&mesh->mutex);
1281 pthread_mutex_destroy(&mesh->mutex);
1283 memset(mesh, 0, sizeof(*mesh));
1288 bool meshlink_destroy_ex(const meshlink_open_params_t *params) {
1289 logger(NULL, MESHLINK_DEBUG, "meshlink_destroy_ex()\n");
1292 meshlink_errno = MESHLINK_EINVAL;
1296 if(!params->confbase) {
1297 /* Ephemeral instances */
1301 /* Exit early if the confbase directory itself doesn't exist */
1302 if(access(params->confbase, F_OK) && errno == ENOENT) {
1306 /* Take the lock the same way meshlink_open() would. */
1307 FILE *lockfile = fopen(params->lock_filename, "w+");
1310 logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", params->lock_filename, strerror(errno));
1311 meshlink_errno = MESHLINK_ESTORAGE;
1316 fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
1320 // TODO: use _locking()?
1323 if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
1324 logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", params->lock_filename);
1326 meshlink_errno = MESHLINK_EBUSY;
1332 if(!config_destroy(params->confbase, "current") || !config_destroy(params->confbase, "new") || !config_destroy(params->confbase, "old")) {
1333 logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", params->confbase, strerror(errno));
1337 if(unlink(params->lock_filename)) {
1338 logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", params->lock_filename, strerror(errno));
1340 meshlink_errno = MESHLINK_ESTORAGE;
1346 if(!sync_path(params->confbase)) {
1347 logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", params->confbase, strerror(errno));
1348 meshlink_errno = MESHLINK_ESTORAGE;
1355 bool meshlink_destroy(const char *confbase) {
1356 logger(NULL, MESHLINK_DEBUG, "meshlink_destroy(%s)", confbase);
1358 char lock_filename[PATH_MAX];
1359 snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
1361 meshlink_open_params_t params = {
1362 .confbase = (char *)confbase,
1363 .lock_filename = lock_filename,
1366 return meshlink_destroy_ex(¶ms);
1369 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1370 logger(mesh, MESHLINK_DEBUG, "meshlink_set_receive_cb(%p)", (void *)(intptr_t)cb);
1373 meshlink_errno = MESHLINK_EINVAL;
1377 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1381 mesh->receive_cb = cb;
1382 pthread_mutex_unlock(&mesh->mutex);
1385 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1386 logger(mesh, MESHLINK_DEBUG, "meshlink_set_connection_try_cb(%p)", (void *)(intptr_t)cb);
1389 meshlink_errno = MESHLINK_EINVAL;
1393 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1397 mesh->connection_try_cb = cb;
1398 pthread_mutex_unlock(&mesh->mutex);
1401 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1402 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_status_cb(%p)", (void *)(intptr_t)cb);
1405 meshlink_errno = MESHLINK_EINVAL;
1409 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1413 mesh->node_status_cb = cb;
1414 pthread_mutex_unlock(&mesh->mutex);
1417 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1418 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_duplicate_cb(%p)", (void *)(intptr_t)cb);
1421 meshlink_errno = MESHLINK_EINVAL;
1425 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1429 mesh->node_duplicate_cb = cb;
1430 pthread_mutex_unlock(&mesh->mutex);
1433 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1434 logger(mesh, MESHLINK_DEBUG, "meshlink_set_log_cb(%p)", (void *)(intptr_t)cb);
1437 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1442 mesh->log_level = cb ? level : 0;
1443 pthread_mutex_unlock(&mesh->mutex);
1446 global_log_level = cb ? level : 0;
1450 void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
1451 logger(mesh, MESHLINK_DEBUG, "meshlink_set_error_cb(%p)", (void *)(intptr_t)cb);
1454 meshlink_errno = MESHLINK_EINVAL;
1458 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1462 mesh->error_cb = cb;
1463 pthread_mutex_unlock(&mesh->mutex);
1466 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1467 logger(mesh, MESHLINK_DEBUG, "meshlink_send(%s, %p, %zu)", destination ? destination->name : "(null)", data, len);
1469 // Validate arguments
1470 if(!mesh || !destination) {
1471 meshlink_errno = MESHLINK_EINVAL;
1479 if(!data || len > MTU) {
1480 meshlink_errno = MESHLINK_EINVAL;
1484 // Prepare the packet
1485 vpn_packet_t *packet = malloc(sizeof(*packet));
1488 meshlink_errno = MESHLINK_ENOMEM;
1493 memcpy(packet->data, data, len);
1496 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1498 meshlink_errno = MESHLINK_ENOMEM;
1502 logger(mesh, MESHLINK_DEBUG, "Adding packet of %zu bytes to packet queue", len);
1504 // Notify event loop
1505 signal_trigger(&mesh->loop, &mesh->datafromapp);
1510 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
1512 meshlink_handle_t *mesh = data;
1514 logger(mesh, MESHLINK_DEBUG, "Flushing the packet queue");
1516 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1517 logger(mesh, MESHLINK_DEBUG, "Removing packet of %d bytes from packet queue", packet->len);
1518 send_raw_packet(mesh, mesh->peer->connection, packet);
1523 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1524 if(!mesh || !node) {
1525 meshlink_errno = MESHLINK_EINVAL;
1529 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1533 node_t *n = (node_t *)node;
1535 if(!node_read_public_key(mesh, n) || !n->ecdsa) {
1536 meshlink_errno = MESHLINK_EINTERNAL;
1537 pthread_mutex_unlock(&mesh->mutex);
1541 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1544 meshlink_errno = MESHLINK_EINTERNAL;
1547 pthread_mutex_unlock(&mesh->mutex);
1551 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1553 meshlink_errno = MESHLINK_EINVAL;
1557 return (meshlink_node_t *)mesh->self;
1560 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1561 if(!mesh || !name) {
1562 meshlink_errno = MESHLINK_EINVAL;
1568 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1572 n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1573 pthread_mutex_unlock(&mesh->mutex);
1576 meshlink_errno = MESHLINK_ENOENT;
1579 return (meshlink_node_t *)n;
1582 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1583 logger(mesh, MESHLINK_DEBUG, "meshlink_sign(%p, %zu, %p, %p)", data, len, signature, (void *)siglen);
1585 if(!mesh || !data || !len || !signature || !siglen) {
1586 meshlink_errno = MESHLINK_EINVAL;
1590 if(*siglen < MESHLINK_SIGLEN) {
1591 meshlink_errno = MESHLINK_EINVAL;
1595 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1599 if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
1600 meshlink_errno = MESHLINK_EINTERNAL;
1601 pthread_mutex_unlock(&mesh->mutex);
1605 *siglen = MESHLINK_SIGLEN;
1606 pthread_mutex_unlock(&mesh->mutex);
1610 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1611 logger(mesh, MESHLINK_DEBUG, "meshlink_verify(%p, %zu, %p, %zu)", data, len, signature, siglen);
1613 if(!mesh || !source || !data || !len || !signature) {
1614 meshlink_errno = MESHLINK_EINVAL;
1618 if(siglen != MESHLINK_SIGLEN) {
1619 meshlink_errno = MESHLINK_EINVAL;
1623 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1629 struct node_t *n = (struct node_t *)source;
1631 if(!node_read_public_key(mesh, n)) {
1632 meshlink_errno = MESHLINK_EINTERNAL;
1635 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1638 pthread_mutex_unlock(&mesh->mutex);
1642 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
1643 logger(mesh, MESHLINK_DEBUG, "meshlink_set_canonical_address(%s, %s, %s)", node ? node->name : "(null)", address ? address : "(null)", port ? port : "(null)");
1645 if(!mesh || !node || !address) {
1646 meshlink_errno = MESHLINK_EINVAL;
1650 if(!is_valid_hostname(address)) {
1651 logger(mesh, MESHLINK_ERROR, "Invalid character in address: %s", address);
1652 meshlink_errno = MESHLINK_EINVAL;
1656 if((node_t *)node != mesh->self && !port) {
1657 logger(mesh, MESHLINK_ERROR, "Missing port number!");
1658 meshlink_errno = MESHLINK_EINVAL;
1663 if(port && !is_valid_port(port)) {
1664 logger(mesh, MESHLINK_ERROR, "Invalid character in port: %s", address);
1665 meshlink_errno = MESHLINK_EINVAL;
1669 char *canonical_address;
1671 xasprintf(&canonical_address, "%s %s", address, port ? port : mesh->myport);
1673 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1677 node_t *n = (node_t *)node;
1678 free(n->canonical_address);
1679 n->canonical_address = canonical_address;
1681 if(!node_write_config(mesh, n, false)) {
1682 pthread_mutex_unlock(&mesh->mutex);
1686 pthread_mutex_unlock(&mesh->mutex);
1688 return config_sync(mesh, "current");
1691 bool meshlink_clear_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node) {
1692 logger(mesh, MESHLINK_DEBUG, "meshlink_clear_canonical_address(%s)", node ? node->name : "(null)");
1694 if(!mesh || !node) {
1695 meshlink_errno = MESHLINK_EINVAL;
1699 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1703 node_t *n = (node_t *)node;
1704 free(n->canonical_address);
1705 n->canonical_address = NULL;
1707 if(!node_write_config(mesh, n, false)) {
1708 pthread_mutex_unlock(&mesh->mutex);
1712 pthread_mutex_unlock(&mesh->mutex);
1714 return config_sync(mesh, "current");
1717 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1718 logger(mesh, MESHLINK_DEBUG, "meshlink_join(%s)", invitation ? invitation : "(null)");
1720 if(!mesh || !invitation) {
1721 meshlink_errno = MESHLINK_EINVAL;
1725 if(mesh->storage_policy == MESHLINK_STORAGE_DISABLED) {
1726 meshlink_errno = MESHLINK_EINVAL;
1730 join_state_t state = {
1735 ecdsa_t *key = NULL;
1736 ecdsa_t *hiskey = NULL;
1738 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1739 char copy[strlen(invitation) + 1];
1741 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1745 //Before doing meshlink_join make sure we are not connected to another mesh
1746 if(mesh->threadstarted) {
1747 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
1748 meshlink_errno = MESHLINK_EINVAL;
1752 // Refuse to join a mesh if we are already part of one. We are part of one if we know at least one other node.
1754 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
1755 meshlink_errno = MESHLINK_EINVAL;
1759 strcpy(copy, invitation);
1761 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
1763 char *slash = strchr(copy, '/');
1771 if(strlen(slash) != 48) {
1775 char *address = copy;
1778 if(!b64decode(slash, state.hash, 18) || !b64decode(slash + 24, state.cookie, 18)) {
1782 if(mesh->inviter_commits_first) {
1783 memcpy(state.cookie + 18, ecdsa_get_public_key(mesh->private_key), 32);
1786 // Generate a throw-away key for the invitation.
1787 key = ecdsa_generate();
1790 meshlink_errno = MESHLINK_EINTERNAL;
1794 char *b64key = ecdsa_get_base64_public_key(key);
1797 while(address && *address) {
1798 // We allow commas in the address part to support multiple addresses in one invitation URL.
1799 comma = strchr(address, ',');
1805 // Split of the port
1806 port = strrchr(address, ':');
1814 // IPv6 address are enclosed in brackets, per RFC 3986
1815 if(*address == '[') {
1817 char *bracket = strchr(address, ']');
1830 // Connect to the meshlink daemon mentioned in the URL.
1831 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1834 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
1835 state.sock = socket_in_netns(aip->ai_family, SOCK_STREAM, IPPROTO_TCP, mesh->netns);
1837 if(state.sock == -1) {
1838 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
1839 meshlink_errno = MESHLINK_ENETWORK;
1845 setsockopt(state.sock, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe));
1848 set_timeout(state.sock, 5000);
1850 if(connect(state.sock, aip->ai_addr, aip->ai_addrlen)) {
1851 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1852 meshlink_errno = MESHLINK_ENETWORK;
1853 closesocket(state.sock);
1863 meshlink_errno = MESHLINK_ERESOLV;
1866 if(state.sock != -1 || !comma) {
1873 if(state.sock == -1) {
1877 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
1879 // Tell him we have an invitation, and give him our throw-away key.
1883 if(!sendline(state.sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
1884 logger(mesh, MESHLINK_ERROR, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1885 meshlink_errno = MESHLINK_ENETWORK;
1891 char hisname[4096] = "";
1892 int code, hismajor, hisminor = 0;
1894 if(!recvline(&state) || sscanf(state.line, "%d %s %d.%d", &code, hisname, &hismajor, &hisminor) < 3 || code != 0 || hismajor != PROT_MAJOR || !check_id(hisname) || !recvline(&state) || !rstrip(state.line) || sscanf(state.line, "%d ", &code) != 1 || code != ACK || strlen(state.line) < 3) {
1895 logger(mesh, MESHLINK_ERROR, "Cannot read greeting from peer\n");
1896 meshlink_errno = MESHLINK_ENETWORK;
1900 // Check if the hash of the key he gave us matches the hash in the URL.
1901 char *fingerprint = state.line + 2;
1904 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1905 logger(mesh, MESHLINK_ERROR, "Could not create hash\n%s\n", state.line + 2);
1906 meshlink_errno = MESHLINK_EINTERNAL;
1910 if(memcmp(hishash, state.hash, 18)) {
1911 logger(mesh, MESHLINK_ERROR, "Peer has an invalid key!\n%s\n", state.line + 2);
1912 meshlink_errno = MESHLINK_EPEER;
1916 hiskey = ecdsa_set_base64_public_key(fingerprint);
1919 meshlink_errno = MESHLINK_EINTERNAL;
1923 // Start an SPTPS session
1924 if(!sptps_start(&state.sptps, &state, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
1925 meshlink_errno = MESHLINK_EINTERNAL;
1929 // Feed rest of input buffer to SPTPS
1930 if(!sptps_receive_data(&state.sptps, state.buffer, state.blen)) {
1931 meshlink_errno = MESHLINK_EPEER;
1936 logger(mesh, MESHLINK_DEBUG, "Starting invitation recv loop: %d %zu\n", state.sock, sizeof(state.line));
1938 while((len = recv(state.sock, state.line, sizeof(state.line), 0))) {
1940 if(errno == EINTR) {
1944 logger(mesh, MESHLINK_ERROR, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1945 meshlink_errno = MESHLINK_ENETWORK;
1949 if(!sptps_receive_data(&state.sptps, state.line, len)) {
1950 meshlink_errno = MESHLINK_EPEER;
1955 if(!state.success) {
1956 logger(mesh, MESHLINK_ERROR, "Connection closed by peer, invitation cancelled.\n");
1957 meshlink_errno = MESHLINK_EPEER;
1961 sptps_stop(&state.sptps);
1964 closesocket(state.sock);
1966 pthread_mutex_unlock(&mesh->mutex);
1970 logger(mesh, MESHLINK_ERROR, "Invalid invitation URL\n");
1971 meshlink_errno = MESHLINK_EINVAL;
1973 sptps_stop(&state.sptps);
1977 if(state.sock != -1) {
1978 closesocket(state.sock);
1981 pthread_mutex_unlock(&mesh->mutex);
1985 char *meshlink_export(meshlink_handle_t *mesh) {
1987 meshlink_errno = MESHLINK_EINVAL;
1991 // Create a config file on the fly.
1994 packmsg_output_t out = {buf, sizeof(buf)};
1995 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
1996 packmsg_add_str(&out, mesh->name);
1997 packmsg_add_str(&out, CORE_MESH);
1999 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2003 packmsg_add_int32(&out, mesh->self->devclass);
2004 packmsg_add_bool(&out, mesh->self->status.blacklisted);
2005 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2007 if(mesh->self->canonical_address && !strchr(mesh->self->canonical_address, ' ')) {
2008 char *canonical_address = NULL;
2009 xasprintf(&canonical_address, "%s %s", mesh->self->canonical_address, mesh->myport);
2010 packmsg_add_str(&out, canonical_address);
2011 free(canonical_address);
2013 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2018 for(uint32_t i = 0; i < MAX_RECENT; i++) {
2019 if(mesh->self->recent[i].sa.sa_family) {
2026 packmsg_add_array(&out, count);
2028 for(uint32_t i = 0; i < count; i++) {
2029 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2032 packmsg_add_int64(&out, 0);
2033 packmsg_add_int64(&out, 0);
2035 pthread_mutex_unlock(&mesh->mutex);
2037 if(!packmsg_output_ok(&out)) {
2038 logger(mesh, MESHLINK_ERROR, "Error creating export data\n");
2039 meshlink_errno = MESHLINK_EINTERNAL;
2043 // Prepare a base64-encoded packmsg array containing our config file
2045 uint32_t len = packmsg_output_size(&out, buf);
2046 uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2047 uint8_t *buf2 = xmalloc(len2);
2048 packmsg_output_t out2 = {buf2, len2};
2049 packmsg_add_array(&out2, 1);
2050 packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2052 if(!packmsg_output_ok(&out2)) {
2053 logger(mesh, MESHLINK_ERROR, "Error creating export data\n");
2054 meshlink_errno = MESHLINK_EINTERNAL;
2059 b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2061 return (char *)buf2;
2064 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2065 logger(mesh, MESHLINK_DEBUG, "meshlink_import(%p)", (const void *)data);
2067 if(!mesh || !data) {
2068 meshlink_errno = MESHLINK_EINVAL;
2072 size_t datalen = strlen(data);
2073 uint8_t *buf = xmalloc(datalen);
2074 int buflen = b64decode(data, buf, datalen);
2077 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2079 meshlink_errno = MESHLINK_EPEER;
2083 packmsg_input_t in = {buf, buflen};
2084 uint32_t count = packmsg_get_array(&in);
2087 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2089 meshlink_errno = MESHLINK_EPEER;
2093 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2099 uint32_t len2 = packmsg_get_bin_raw(&in, &data2);
2105 packmsg_input_t in2 = {data2, len2};
2106 uint32_t version = packmsg_get_uint32(&in2);
2107 char *name = packmsg_get_str_dup(&in2);
2109 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
2111 packmsg_input_invalidate(&in);
2115 if(!check_id(name)) {
2120 node_t *n = lookup_node(mesh, name);
2123 logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
2131 config_t config = {data2, len2};
2133 if(!node_read_from_config(mesh, n, &config)) {
2135 packmsg_input_invalidate(&in);
2139 if(!node_write_config(mesh, n, true)) {
2148 pthread_mutex_unlock(&mesh->mutex);
2152 if(!packmsg_done(&in)) {
2153 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2154 meshlink_errno = MESHLINK_EPEER;
2158 if(!config_sync(mesh, "current")) {
2165 /* Hint that a hostname may be found at an address
2166 * See header file for detailed comment.
2168 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2169 logger(mesh, MESHLINK_DEBUG, "meshlink_hint_address(%s, %p)", node ? node->name : "(null)", (const void *)addr);
2171 if(!mesh || !node || !addr) {
2172 meshlink_errno = EINVAL;
2176 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2180 node_t *n = (node_t *)node;
2182 if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
2183 if(!node_write_config(mesh, n, false)) {
2184 logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
2188 pthread_mutex_unlock(&mesh->mutex);
2189 // @TODO do we want to fire off a connection attempt right away?
2192 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2193 if(mesh->node_status_cb) {
2194 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
2198 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
2199 if(!mesh->node_duplicate_cb || n->status.duplicate) {
2203 n->status.duplicate = true;
2204 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
2207 void meshlink_hint_network_change(struct meshlink_handle *mesh) {
2208 logger(mesh, MESHLINK_DEBUG, "meshlink_hint_network_change()");
2211 meshlink_errno = MESHLINK_EINVAL;
2215 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2219 pthread_mutex_unlock(&mesh->mutex);
2222 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
2223 logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_timeouts(%d, %d, %d)", devclass, pinginterval, pingtimeout);
2225 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
2226 meshlink_errno = EINVAL;
2230 if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
2231 meshlink_errno = EINVAL;
2235 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2239 mesh->dev_class_traits[devclass].pinginterval = pinginterval;
2240 mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
2241 pthread_mutex_unlock(&mesh->mutex);
2244 void meshlink_set_dev_class_fast_retry_period(meshlink_handle_t *mesh, dev_class_t devclass, int fast_retry_period) {
2245 logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_fast_retry_period(%d, %d)", devclass, fast_retry_period);
2247 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
2248 meshlink_errno = EINVAL;
2252 if(fast_retry_period < 0) {
2253 meshlink_errno = EINVAL;
2257 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2261 mesh->dev_class_traits[devclass].fast_retry_period = fast_retry_period;
2262 pthread_mutex_unlock(&mesh->mutex);
2265 void meshlink_set_dev_class_maxtimeout(struct meshlink_handle *mesh, dev_class_t devclass, int maxtimeout) {
2266 logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_fast_maxtimeout(%d, %d)", devclass, maxtimeout);
2268 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
2269 meshlink_errno = EINVAL;
2273 if(maxtimeout < 0) {
2274 meshlink_errno = EINVAL;
2278 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2282 mesh->dev_class_traits[devclass].maxtimeout = maxtimeout;
2283 pthread_mutex_unlock(&mesh->mutex);
2286 void meshlink_reset_timers(struct meshlink_handle *mesh) {
2287 logger(mesh, MESHLINK_DEBUG, "meshlink_reset_timers()");
2293 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2297 handle_network_change(mesh, true);
2299 pthread_mutex_unlock(&mesh->mutex);
2302 void meshlink_set_inviter_commits_first(struct meshlink_handle *mesh, bool inviter_commits_first) {
2303 logger(mesh, MESHLINK_DEBUG, "meshlink_set_inviter_commits_first(%d)", inviter_commits_first);
2306 meshlink_errno = EINVAL;
2310 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2314 mesh->inviter_commits_first = inviter_commits_first;
2315 pthread_mutex_unlock(&mesh->mutex);
2318 void meshlink_set_storage_policy(struct meshlink_handle *mesh, meshlink_storage_policy_t policy) {
2319 logger(mesh, MESHLINK_DEBUG, "meshlink_set_storage_policy(%d)", policy);
2322 meshlink_errno = EINVAL;
2326 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2330 mesh->storage_policy = policy;
2331 pthread_mutex_unlock(&mesh->mutex);
2334 void handle_network_change(meshlink_handle_t *mesh, bool online) {
2337 if(!mesh->loop.running) {
2342 signal_trigger(&mesh->loop, &mesh->datafromapp);
2345 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t cb_errno) {
2346 // We should only call the callback function if we are in the background thread.
2347 if(!mesh->error_cb) {
2351 if(!mesh->threadstarted) {
2355 if(mesh->thread == pthread_self()) {
2356 mesh->error_cb(mesh, cb_errno);
2360 static void __attribute__((constructor)) meshlink_init(void) {
2364 static void __attribute__((destructor)) meshlink_exit(void) {