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);
316 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
322 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
324 join_state_t *state = handle;
325 const char *ptr = data;
328 int result = send(state->sock, ptr, len, 0);
330 if(result == -1 && errno == EINTR) {
332 } else if(result <= 0) {
343 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
344 join_state_t *state = handle;
345 meshlink_handle_t *mesh = state->mesh;
347 if(mesh->inviter_commits_first) {
349 case SPTPS_HANDSHAKE:
350 return sptps_send_record(&state->sptps, 2, state->cookie, 18 + 32);
356 if(!finalize_join(state, msg, len)) {
360 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
361 shutdown(state->sock, SHUT_RDWR);
362 state->success = true;
370 case SPTPS_HANDSHAKE:
371 return sptps_send_record(&state->sptps, 0, state->cookie, 18);
374 return finalize_join(state, msg, len);
377 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
378 shutdown(state->sock, SHUT_RDWR);
379 state->success = true;
390 static bool recvline(join_state_t *state) {
391 char *newline = NULL;
393 while(!(newline = memchr(state->buffer, '\n', state->blen))) {
394 int result = recv(state->sock, state->buffer + state->blen, sizeof(state)->buffer - state->blen, 0);
396 if(result == -1 && errno == EINTR) {
398 } else if(result <= 0) {
402 state->blen += result;
405 if((size_t)(newline - state->buffer) >= sizeof(state->line)) {
409 size_t len = newline - state->buffer;
411 memcpy(state->line, state->buffer, len);
412 state->line[len] = 0;
413 memmove(state->buffer, newline + 1, state->blen - len - 1);
414 state->blen -= len + 1;
419 static bool sendline(int fd, const char *format, ...) {
425 va_start(ap, format);
426 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
429 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
437 int result = send(fd, p, blen, MSG_NOSIGNAL);
439 if(result == -1 && errno == EINTR) {
441 } else if(result <= 0) {
452 static const char *errstr[] = {
453 [MESHLINK_OK] = "No error",
454 [MESHLINK_EINVAL] = "Invalid argument",
455 [MESHLINK_ENOMEM] = "Out of memory",
456 [MESHLINK_ENOENT] = "No such node",
457 [MESHLINK_EEXIST] = "Node already exists",
458 [MESHLINK_EINTERNAL] = "Internal error",
459 [MESHLINK_ERESOLV] = "Could not resolve hostname",
460 [MESHLINK_ESTORAGE] = "Storage error",
461 [MESHLINK_ENETWORK] = "Network error",
462 [MESHLINK_EPEER] = "Error communicating with peer",
463 [MESHLINK_ENOTSUP] = "Operation not supported",
464 [MESHLINK_EBUSY] = "MeshLink instance already in use",
465 [MESHLINK_EBLACKLISTED] = "Node is blacklisted",
468 const char *meshlink_strerror(meshlink_errno_t err) {
469 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
470 return "Invalid error code";
476 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
477 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
479 mesh->private_key = ecdsa_generate();
481 if(!mesh->private_key) {
482 logger(mesh, MESHLINK_ERROR, "Error during key generation!\n");
483 meshlink_errno = MESHLINK_EINTERNAL;
487 logger(mesh, MESHLINK_DEBUG, "Done.\n");
492 static struct timespec idle(event_loop_t *loop, void *data) {
496 return (struct timespec) {
501 static bool meshlink_setup(meshlink_handle_t *mesh) {
502 if(!config_destroy(mesh->confbase, "new")) {
503 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/new: %s\n", mesh->confbase, strerror(errno));
504 meshlink_errno = MESHLINK_ESTORAGE;
508 if(!config_destroy(mesh->confbase, "old")) {
509 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
510 meshlink_errno = MESHLINK_ESTORAGE;
514 if(!config_init(mesh, "current")) {
515 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
516 meshlink_errno = MESHLINK_ESTORAGE;
520 if(!ecdsa_keygen(mesh)) {
521 meshlink_errno = MESHLINK_EINTERNAL;
525 mesh->myport = xstrdup("0");
527 /* Create a node for ourself */
529 mesh->self = new_node();
530 mesh->self->name = xstrdup(mesh->name);
531 mesh->self->devclass = mesh->devclass;
532 mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
533 mesh->self->session_id = mesh->session_id;
535 if(!write_main_config_files(mesh)) {
536 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
537 meshlink_errno = MESHLINK_ESTORAGE;
541 /* Ensure the configuration directory metadata is on disk */
542 if(!config_sync(mesh, "current")) {
549 static bool meshlink_read_config(meshlink_handle_t *mesh) {
552 if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
553 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
557 packmsg_input_t in = {config.buf, config.len};
558 const void *private_key;
560 uint32_t version = packmsg_get_uint32(&in);
561 char *name = packmsg_get_str_dup(&in);
562 uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
563 packmsg_skip_element(&in); // Invitation key is not supported
564 uint16_t myport = packmsg_get_uint16(&in);
566 if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96) {
567 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
569 config_free(&config);
573 if(mesh->name && strcmp(mesh->name, name)) {
574 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
575 meshlink_errno = MESHLINK_ESTORAGE;
577 config_free(&config);
583 xasprintf(&mesh->myport, "%u", myport);
584 mesh->private_key = ecdsa_set_private_key(private_key);
585 config_free(&config);
587 /* Create a node for ourself and read our host configuration file */
589 mesh->self = new_node();
590 mesh->self->name = xstrdup(name);
591 mesh->self->devclass = mesh->devclass;
592 mesh->self->session_id = mesh->session_id;
594 if(!node_read_public_key(mesh, mesh->self)) {
595 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
596 meshlink_errno = MESHLINK_ESTORAGE;
597 free_node(mesh->self);
606 static void *setup_network_in_netns_thread(void *arg) {
607 meshlink_handle_t *mesh = arg;
609 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
613 bool success = setup_network(mesh);
614 return success ? arg : NULL;
618 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
619 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_init(%s, %s, %s, %d)", confbase, name, appname, devclass);
621 if(!confbase || !*confbase) {
622 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
623 meshlink_errno = MESHLINK_EINVAL;
627 if(!appname || !*appname) {
628 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
629 meshlink_errno = MESHLINK_EINVAL;
633 if(strchr(appname, ' ')) {
634 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
635 meshlink_errno = MESHLINK_EINVAL;
639 if(name && !check_id(name)) {
640 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
641 meshlink_errno = MESHLINK_EINVAL;
645 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
646 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
647 meshlink_errno = MESHLINK_EINVAL;
651 meshlink_open_params_t *params = xzalloc(sizeof * params);
653 params->confbase = xstrdup(confbase);
654 params->name = name ? xstrdup(name) : NULL;
655 params->appname = xstrdup(appname);
656 params->devclass = devclass;
659 xasprintf(¶ms->lock_filename, "%s" SLASH "meshlink.lock", confbase);
664 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
665 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_netnst(%d)", netns);
668 meshlink_errno = MESHLINK_EINVAL;
672 params->netns = netns;
677 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
678 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_key(%p, %zu)", key, keylen);
681 meshlink_errno = MESHLINK_EINVAL;
685 if((!key && keylen) || (key && !keylen)) {
686 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
687 meshlink_errno = MESHLINK_EINVAL;
692 params->keylen = keylen;
697 bool meshlink_open_params_set_storage_policy(meshlink_open_params_t *params, meshlink_storage_policy_t policy) {
698 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_policy(%d)", policy);
701 meshlink_errno = MESHLINK_EINVAL;
705 params->storage_policy = policy;
710 bool meshlink_open_params_set_lock_filename(meshlink_open_params_t *params, const char *filename) {
711 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_lock_filename(%s)", filename);
713 if(!params || !filename) {
714 meshlink_errno = MESHLINK_EINVAL;
718 free(params->lock_filename);
719 params->lock_filename = xstrdup(filename);
724 bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
725 logger(NULL, MESHLINK_DEBUG, "meshlink_encrypted_key_rotate(%p, %zu)", new_key, new_keylen);
727 if(!mesh || !new_key || !new_keylen) {
728 logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
729 meshlink_errno = MESHLINK_EINVAL;
733 if(pthread_mutex_lock(&mesh->mutex) != 0) {
737 // Create hash for the new key
738 void *new_config_key;
739 new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
741 if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
742 logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
743 meshlink_errno = MESHLINK_EINTERNAL;
744 pthread_mutex_unlock(&mesh->mutex);
748 // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
750 if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
751 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
752 meshlink_errno = MESHLINK_ESTORAGE;
753 pthread_mutex_unlock(&mesh->mutex);
757 devtool_keyrotate_probe(1);
759 // Rename confbase/current/ to confbase/old
761 if(!config_rename(mesh, "current", "old")) {
762 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
763 meshlink_errno = MESHLINK_ESTORAGE;
764 pthread_mutex_unlock(&mesh->mutex);
768 devtool_keyrotate_probe(2);
770 // Rename confbase/new/ to confbase/current
772 if(!config_rename(mesh, "new", "current")) {
773 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
774 meshlink_errno = MESHLINK_ESTORAGE;
775 pthread_mutex_unlock(&mesh->mutex);
779 devtool_keyrotate_probe(3);
781 // Cleanup the "old" confbase sub-directory
783 if(!config_destroy(mesh->confbase, "old")) {
784 pthread_mutex_unlock(&mesh->mutex);
788 // Change the mesh handle key with new key
790 free(mesh->config_key);
791 mesh->config_key = new_config_key;
793 pthread_mutex_unlock(&mesh->mutex);
798 void meshlink_open_params_free(meshlink_open_params_t *params) {
799 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_free()");
802 meshlink_errno = MESHLINK_EINVAL;
806 free(params->confbase);
808 free(params->appname);
809 free(params->lock_filename);
814 /// Device class traits
815 static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
816 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
817 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
818 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
819 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN
822 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
823 logger(NULL, MESHLINK_DEBUG, "meshlink_open(%s, %s, %s, %d)", confbase, name, appname, devclass);
825 if(!confbase || !*confbase) {
826 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
827 meshlink_errno = MESHLINK_EINVAL;
831 char lock_filename[PATH_MAX];
832 snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
834 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
835 meshlink_open_params_t params = {
836 .confbase = (char *)confbase,
837 .lock_filename = lock_filename,
838 .name = (char *)name,
839 .appname = (char *)appname,
840 .devclass = devclass,
844 return meshlink_open_ex(¶ms);
847 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) {
848 logger(NULL, MESHLINK_DEBUG, "meshlink_open_encrypted(%s, %s, %s, %d, %p, %zu)", confbase, name, appname, devclass, key, keylen);
850 if(!confbase || !*confbase) {
851 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
852 meshlink_errno = MESHLINK_EINVAL;
856 char lock_filename[PATH_MAX];
857 snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
859 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
860 meshlink_open_params_t params = {
861 .confbase = (char *)confbase,
862 .lock_filename = lock_filename,
863 .name = (char *)name,
864 .appname = (char *)appname,
865 .devclass = devclass,
869 if(!meshlink_open_params_set_storage_key(¶ms, key, keylen)) {
873 return meshlink_open_ex(¶ms);
876 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
877 logger(NULL, MESHLINK_DEBUG, "meshlink_open_ephemeral(%s, %s, %d)", name, appname, devclass);
880 logger(NULL, MESHLINK_ERROR, "No name given!\n");
881 meshlink_errno = MESHLINK_EINVAL;
885 if(!check_id(name)) {
886 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
887 meshlink_errno = MESHLINK_EINVAL;
891 if(!appname || !*appname) {
892 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
893 meshlink_errno = MESHLINK_EINVAL;
897 if(strchr(appname, ' ')) {
898 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
899 meshlink_errno = MESHLINK_EINVAL;
903 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
904 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
905 meshlink_errno = MESHLINK_EINVAL;
909 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
910 meshlink_open_params_t params = {
911 .name = (char *)name,
912 .appname = (char *)appname,
913 .devclass = devclass,
917 return meshlink_open_ex(¶ms);
920 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
921 logger(NULL, MESHLINK_DEBUG, "meshlink_open_ex()");
923 // Validate arguments provided by the application
924 if(!params->appname || !*params->appname) {
925 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
926 meshlink_errno = MESHLINK_EINVAL;
930 if(strchr(params->appname, ' ')) {
931 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
932 meshlink_errno = MESHLINK_EINVAL;
936 if(params->name && !check_id(params->name)) {
937 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
938 meshlink_errno = MESHLINK_EINVAL;
942 if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
943 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
944 meshlink_errno = MESHLINK_EINVAL;
948 if((params->key && !params->keylen) || (!params->key && params->keylen)) {
949 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
950 meshlink_errno = MESHLINK_EINVAL;
954 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
956 if(params->confbase) {
957 mesh->confbase = xstrdup(params->confbase);
960 mesh->appname = xstrdup(params->appname);
961 mesh->devclass = params->devclass;
962 mesh->netns = params->netns;
963 mesh->log_cb = global_log_cb;
964 mesh->log_level = global_log_level;
965 mesh->packet = xmalloc(sizeof(vpn_packet_t));
967 randomize(&mesh->prng_state, sizeof(mesh->prng_state));
970 randomize(&mesh->session_id, sizeof(mesh->session_id));
971 } while(mesh->session_id == 0);
973 memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
975 mesh->name = params->name ? xstrdup(params->name) : NULL;
979 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
981 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
982 logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
983 meshlink_close(mesh);
984 meshlink_errno = MESHLINK_EINTERNAL;
989 // initialize mutexes and conds
990 pthread_mutexattr_t attr;
991 pthread_mutexattr_init(&attr);
993 if(pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) != 0) {
997 pthread_mutex_init(&mesh->mutex, &attr);
998 pthread_cond_init(&mesh->cond, NULL);
1000 mesh->threadstarted = false;
1001 event_loop_init(&mesh->loop);
1002 mesh->loop.data = mesh;
1004 meshlink_queue_init(&mesh->outpacketqueue);
1006 // Atomically lock the configuration directory.
1007 if(!main_config_lock(mesh, params->lock_filename)) {
1008 meshlink_close(mesh);
1012 // If no configuration exists yet, create it.
1014 bool new_configuration = false;
1016 if(!meshlink_confbase_exists(mesh)) {
1018 logger(NULL, MESHLINK_ERROR, "No configuration files found!\n");
1019 meshlink_close(mesh);
1020 meshlink_errno = MESHLINK_ESTORAGE;
1024 if(!meshlink_setup(mesh)) {
1025 logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1026 meshlink_close(mesh);
1030 new_configuration = true;
1032 if(!meshlink_read_config(mesh)) {
1033 logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1034 meshlink_close(mesh);
1039 mesh->storage_policy = params->storage_policy;
1042 struct WSAData wsa_state;
1043 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1046 // Setup up everything
1047 // TODO: we should not open listening sockets yet
1049 bool success = false;
1051 if(mesh->netns != -1) {
1055 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1056 void *retval = NULL;
1057 success = pthread_join(thr, &retval) == 0 && retval;
1061 meshlink_errno = MESHLINK_EINTERNAL;
1064 #endif // HAVE_SETNS
1066 success = setup_network(mesh);
1070 meshlink_close(mesh);
1071 meshlink_errno = MESHLINK_ENETWORK;
1075 if(!node_write_config(mesh, mesh->self, new_configuration)) {
1076 logger(NULL, MESHLINK_ERROR, "Cannot update configuration\n");
1080 idle_set(&mesh->loop, idle, mesh);
1082 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1086 static void *meshlink_main_loop(void *arg) {
1087 meshlink_handle_t *mesh = arg;
1089 if(mesh->netns != -1) {
1092 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1093 pthread_cond_signal(&mesh->cond);
1098 pthread_cond_signal(&mesh->cond);
1100 #endif // HAVE_SETNS
1103 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1107 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1108 pthread_cond_broadcast(&mesh->cond);
1110 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1112 pthread_mutex_unlock(&mesh->mutex);
1117 bool meshlink_start(meshlink_handle_t *mesh) {
1119 meshlink_errno = MESHLINK_EINVAL;
1123 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1125 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1130 assert(mesh->private_key);
1131 assert(mesh->self->ecdsa);
1132 assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1134 if(mesh->threadstarted) {
1135 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1136 pthread_mutex_unlock(&mesh->mutex);
1140 // Reset node connection timers
1142 mesh->peer->last_connect_try = 0;
1145 //Check that a valid name is set
1147 logger(mesh, MESHLINK_ERROR, "No name given!\n");
1148 meshlink_errno = MESHLINK_EINVAL;
1149 pthread_mutex_unlock(&mesh->mutex);
1153 init_outgoings(mesh);
1155 // Start the main thread
1157 event_loop_start(&mesh->loop);
1159 // Ensure we have a decent amount of stack space. Musl's default of 80 kB is too small.
1160 pthread_attr_t attr;
1161 pthread_attr_init(&attr);
1162 pthread_attr_setstacksize(&attr, 1024 * 1024);
1164 if(pthread_create(&mesh->thread, &attr, meshlink_main_loop, mesh) != 0) {
1165 logger(mesh, MESHLINK_ERROR, "Could not start thread: %s\n", strerror(errno));
1166 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1167 meshlink_errno = MESHLINK_EINTERNAL;
1168 event_loop_stop(&mesh->loop);
1169 pthread_mutex_unlock(&mesh->mutex);
1173 pthread_cond_wait(&mesh->cond, &mesh->mutex);
1174 mesh->threadstarted = true;
1176 pthread_mutex_unlock(&mesh->mutex);
1180 void meshlink_stop(meshlink_handle_t *mesh) {
1181 logger(mesh, MESHLINK_DEBUG, "meshlink_stop()\n");
1184 meshlink_errno = MESHLINK_EINVAL;
1188 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1192 // Shut down the main thread
1193 event_loop_stop(&mesh->loop);
1195 // TODO: send something to a local socket to kick the event loop
1197 if(mesh->threadstarted) {
1198 // Wait for the main thread to finish
1199 pthread_mutex_unlock(&mesh->mutex);
1201 if(pthread_join(mesh->thread, NULL) != 0) {
1205 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1209 mesh->threadstarted = false;
1212 // Close all metaconnections
1213 if(mesh->connection) {
1214 mesh->connection->outgoing = NULL;
1215 terminate_connection(mesh, mesh->connection, false);
1218 exit_outgoings(mesh);
1220 // Try to write out any changed node config files, ignore errors at this point.
1221 if(mesh->peer && mesh->peer->status.dirty) {
1222 if(!node_write_config(mesh, mesh->peer, false)) {
1227 pthread_mutex_unlock(&mesh->mutex);
1230 void meshlink_close(meshlink_handle_t *mesh) {
1231 logger(mesh, MESHLINK_DEBUG, "meshlink_close()\n");
1234 meshlink_errno = MESHLINK_EINVAL;
1238 // stop can be called even if mesh has not been started
1239 meshlink_stop(mesh);
1241 // lock is not released after this
1242 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1246 // Close and free all resources used.
1248 close_network_connections(mesh);
1250 logger(mesh, MESHLINK_INFO, "Terminating");
1252 event_loop_exit(&mesh->loop);
1256 if(mesh->confbase) {
1262 if(mesh->netns != -1) {
1266 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1270 meshlink_queue_exit(&mesh->outpacketqueue);
1273 free(mesh->appname);
1274 free(mesh->confbase);
1275 free(mesh->config_key);
1276 free(mesh->external_address_url);
1278 ecdsa_free(mesh->private_key);
1280 main_config_unlock(mesh);
1282 pthread_mutex_unlock(&mesh->mutex);
1283 pthread_mutex_destroy(&mesh->mutex);
1285 memset(mesh, 0, sizeof(*mesh));
1290 bool meshlink_destroy_ex(const meshlink_open_params_t *params) {
1291 logger(NULL, MESHLINK_DEBUG, "meshlink_destroy_ex()\n");
1294 meshlink_errno = MESHLINK_EINVAL;
1298 if(!params->confbase) {
1299 /* Ephemeral instances */
1303 /* Exit early if the confbase directory itself doesn't exist */
1304 if(access(params->confbase, F_OK) && errno == ENOENT) {
1308 /* Take the lock the same way meshlink_open() would. */
1309 FILE *lockfile = fopen(params->lock_filename, "w+");
1312 logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", params->lock_filename, strerror(errno));
1313 meshlink_errno = MESHLINK_ESTORAGE;
1318 fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
1322 // TODO: use _locking()?
1325 if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
1326 logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", params->lock_filename);
1328 meshlink_errno = MESHLINK_EBUSY;
1334 if(!config_destroy(params->confbase, "current") || !config_destroy(params->confbase, "new") || !config_destroy(params->confbase, "old")) {
1335 logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", params->confbase, strerror(errno));
1339 if(unlink(params->lock_filename)) {
1340 logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", params->lock_filename, strerror(errno));
1342 meshlink_errno = MESHLINK_ESTORAGE;
1348 if(!sync_path(params->confbase)) {
1349 logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", params->confbase, strerror(errno));
1350 meshlink_errno = MESHLINK_ESTORAGE;
1357 bool meshlink_destroy(const char *confbase) {
1358 logger(NULL, MESHLINK_DEBUG, "meshlink_destroy(%s)", confbase);
1360 char lock_filename[PATH_MAX];
1361 snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
1363 meshlink_open_params_t params = {
1364 .confbase = (char *)confbase,
1365 .lock_filename = lock_filename,
1368 return meshlink_destroy_ex(¶ms);
1371 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1372 logger(mesh, MESHLINK_DEBUG, "meshlink_set_receive_cb(%p)", (void *)(intptr_t)cb);
1375 meshlink_errno = MESHLINK_EINVAL;
1379 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1383 mesh->receive_cb = cb;
1384 pthread_mutex_unlock(&mesh->mutex);
1387 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1388 logger(mesh, MESHLINK_DEBUG, "meshlink_set_connection_try_cb(%p)", (void *)(intptr_t)cb);
1391 meshlink_errno = MESHLINK_EINVAL;
1395 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1399 mesh->connection_try_cb = cb;
1400 pthread_mutex_unlock(&mesh->mutex);
1403 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1404 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_status_cb(%p)", (void *)(intptr_t)cb);
1407 meshlink_errno = MESHLINK_EINVAL;
1411 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1415 mesh->node_status_cb = cb;
1416 pthread_mutex_unlock(&mesh->mutex);
1419 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1420 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_duplicate_cb(%p)", (void *)(intptr_t)cb);
1423 meshlink_errno = MESHLINK_EINVAL;
1427 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1431 mesh->node_duplicate_cb = cb;
1432 pthread_mutex_unlock(&mesh->mutex);
1435 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1436 logger(mesh, MESHLINK_DEBUG, "meshlink_set_log_cb(%p)", (void *)(intptr_t)cb);
1439 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1444 mesh->log_level = cb ? level : 0;
1445 pthread_mutex_unlock(&mesh->mutex);
1448 global_log_level = cb ? level : 0;
1452 void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
1453 logger(mesh, MESHLINK_DEBUG, "meshlink_set_error_cb(%p)", (void *)(intptr_t)cb);
1456 meshlink_errno = MESHLINK_EINVAL;
1460 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1464 mesh->error_cb = cb;
1465 pthread_mutex_unlock(&mesh->mutex);
1468 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1469 logger(mesh, MESHLINK_DEBUG, "meshlink_send(%s, %p, %zu)", destination ? destination->name : "(null)", data, len);
1471 // Validate arguments
1472 if(!mesh || !destination) {
1473 meshlink_errno = MESHLINK_EINVAL;
1481 if(!data || len > MTU) {
1482 meshlink_errno = MESHLINK_EINVAL;
1486 // Prepare the packet
1487 vpn_packet_t *packet = malloc(sizeof(*packet));
1490 meshlink_errno = MESHLINK_ENOMEM;
1495 memcpy(packet->data, data, len);
1498 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1500 meshlink_errno = MESHLINK_ENOMEM;
1504 logger(mesh, MESHLINK_DEBUG, "Adding packet of %zu bytes to packet queue", len);
1506 // Notify event loop
1507 signal_trigger(&mesh->loop, &mesh->datafromapp);
1512 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
1514 meshlink_handle_t *mesh = data;
1516 logger(mesh, MESHLINK_DEBUG, "Flushing the packet queue");
1518 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1519 logger(mesh, MESHLINK_DEBUG, "Removing packet of %d bytes from packet queue", packet->len);
1520 send_raw_packet(mesh, mesh->peer->connection, packet);
1525 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1526 if(!mesh || !node) {
1527 meshlink_errno = MESHLINK_EINVAL;
1531 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1535 node_t *n = (node_t *)node;
1537 if(!node_read_public_key(mesh, n) || !n->ecdsa) {
1538 meshlink_errno = MESHLINK_EINTERNAL;
1539 pthread_mutex_unlock(&mesh->mutex);
1543 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1546 meshlink_errno = MESHLINK_EINTERNAL;
1549 pthread_mutex_unlock(&mesh->mutex);
1553 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1555 meshlink_errno = MESHLINK_EINVAL;
1559 return (meshlink_node_t *)mesh->self;
1562 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1563 if(!mesh || !name) {
1564 meshlink_errno = MESHLINK_EINVAL;
1570 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1574 n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1575 pthread_mutex_unlock(&mesh->mutex);
1578 meshlink_errno = MESHLINK_ENOENT;
1581 return (meshlink_node_t *)n;
1584 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1585 logger(mesh, MESHLINK_DEBUG, "meshlink_sign(%p, %zu, %p, %p)", data, len, signature, (void *)siglen);
1587 if(!mesh || !data || !len || !signature || !siglen) {
1588 meshlink_errno = MESHLINK_EINVAL;
1592 if(*siglen < MESHLINK_SIGLEN) {
1593 meshlink_errno = MESHLINK_EINVAL;
1597 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1601 if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
1602 meshlink_errno = MESHLINK_EINTERNAL;
1603 pthread_mutex_unlock(&mesh->mutex);
1607 *siglen = MESHLINK_SIGLEN;
1608 pthread_mutex_unlock(&mesh->mutex);
1612 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1613 logger(mesh, MESHLINK_DEBUG, "meshlink_verify(%p, %zu, %p, %zu)", data, len, signature, siglen);
1615 if(!mesh || !source || !data || !len || !signature) {
1616 meshlink_errno = MESHLINK_EINVAL;
1620 if(siglen != MESHLINK_SIGLEN) {
1621 meshlink_errno = MESHLINK_EINVAL;
1625 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1631 struct node_t *n = (struct node_t *)source;
1633 if(!node_read_public_key(mesh, n)) {
1634 meshlink_errno = MESHLINK_EINTERNAL;
1637 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1640 pthread_mutex_unlock(&mesh->mutex);
1644 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
1645 logger(mesh, MESHLINK_DEBUG, "meshlink_set_canonical_address(%s, %s, %s)", node ? node->name : "(null)", address ? address : "(null)", port ? port : "(null)");
1647 if(!mesh || !node || !address) {
1648 meshlink_errno = MESHLINK_EINVAL;
1652 if(!is_valid_hostname(address)) {
1653 logger(mesh, MESHLINK_ERROR, "Invalid character in address: %s", address);
1654 meshlink_errno = MESHLINK_EINVAL;
1658 if((node_t *)node != mesh->self && !port) {
1659 logger(mesh, MESHLINK_ERROR, "Missing port number!");
1660 meshlink_errno = MESHLINK_EINVAL;
1665 if(port && !is_valid_port(port)) {
1666 logger(mesh, MESHLINK_ERROR, "Invalid character in port: %s", address);
1667 meshlink_errno = MESHLINK_EINVAL;
1671 char *canonical_address;
1673 xasprintf(&canonical_address, "%s %s", address, port ? port : mesh->myport);
1675 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1679 node_t *n = (node_t *)node;
1680 free(n->canonical_address);
1681 n->canonical_address = canonical_address;
1683 if(!node_write_config(mesh, n, false)) {
1684 pthread_mutex_unlock(&mesh->mutex);
1688 pthread_mutex_unlock(&mesh->mutex);
1690 return config_sync(mesh, "current");
1693 bool meshlink_clear_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node) {
1694 logger(mesh, MESHLINK_DEBUG, "meshlink_clear_canonical_address(%s)", node ? node->name : "(null)");
1696 if(!mesh || !node) {
1697 meshlink_errno = MESHLINK_EINVAL;
1701 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1705 node_t *n = (node_t *)node;
1706 free(n->canonical_address);
1707 n->canonical_address = NULL;
1709 if(!node_write_config(mesh, n, false)) {
1710 pthread_mutex_unlock(&mesh->mutex);
1714 pthread_mutex_unlock(&mesh->mutex);
1716 return config_sync(mesh, "current");
1719 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1720 logger(mesh, MESHLINK_DEBUG, "meshlink_join(%s)", invitation ? invitation : "(null)");
1722 if(!mesh || !invitation) {
1723 meshlink_errno = MESHLINK_EINVAL;
1727 if(mesh->storage_policy == MESHLINK_STORAGE_DISABLED) {
1728 meshlink_errno = MESHLINK_EINVAL;
1732 join_state_t state = {
1737 ecdsa_t *key = NULL;
1738 ecdsa_t *hiskey = NULL;
1740 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1741 char copy[strlen(invitation) + 1];
1743 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1747 //Before doing meshlink_join make sure we are not connected to another mesh
1748 if(mesh->threadstarted) {
1749 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
1750 meshlink_errno = MESHLINK_EINVAL;
1754 // 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.
1756 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
1757 meshlink_errno = MESHLINK_EINVAL;
1761 strcpy(copy, invitation);
1763 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
1765 char *slash = strchr(copy, '/');
1773 if(strlen(slash) != 48) {
1777 char *address = copy;
1780 if(!b64decode(slash, state.hash, 18) || !b64decode(slash + 24, state.cookie, 18)) {
1784 if(mesh->inviter_commits_first) {
1785 memcpy(state.cookie + 18, ecdsa_get_public_key(mesh->private_key), 32);
1788 // Generate a throw-away key for the invitation.
1789 key = ecdsa_generate();
1792 meshlink_errno = MESHLINK_EINTERNAL;
1796 char *b64key = ecdsa_get_base64_public_key(key);
1799 while(address && *address) {
1800 // We allow commas in the address part to support multiple addresses in one invitation URL.
1801 comma = strchr(address, ',');
1807 // Split of the port
1808 port = strrchr(address, ':');
1816 // IPv6 address are enclosed in brackets, per RFC 3986
1817 if(*address == '[') {
1819 char *bracket = strchr(address, ']');
1832 // Connect to the meshlink daemon mentioned in the URL.
1833 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1836 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
1837 state.sock = socket_in_netns(aip->ai_family, SOCK_STREAM, IPPROTO_TCP, mesh->netns);
1839 if(state.sock == -1) {
1840 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
1841 meshlink_errno = MESHLINK_ENETWORK;
1847 setsockopt(state.sock, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe));
1850 set_timeout(state.sock, 5000);
1852 if(connect(state.sock, aip->ai_addr, aip->ai_addrlen)) {
1853 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1854 meshlink_errno = MESHLINK_ENETWORK;
1855 closesocket(state.sock);
1865 meshlink_errno = MESHLINK_ERESOLV;
1868 if(state.sock != -1 || !comma) {
1875 if(state.sock == -1) {
1879 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
1881 // Tell him we have an invitation, and give him our throw-away key.
1885 if(!sendline(state.sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
1886 logger(mesh, MESHLINK_ERROR, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1887 meshlink_errno = MESHLINK_ENETWORK;
1893 char hisname[4096] = "";
1894 int code, hismajor, hisminor = 0;
1896 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) {
1897 logger(mesh, MESHLINK_ERROR, "Cannot read greeting from peer\n");
1898 meshlink_errno = MESHLINK_ENETWORK;
1902 // Check if the hash of the key he gave us matches the hash in the URL.
1903 char *fingerprint = state.line + 2;
1906 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1907 logger(mesh, MESHLINK_ERROR, "Could not create hash\n%s\n", state.line + 2);
1908 meshlink_errno = MESHLINK_EINTERNAL;
1912 if(memcmp(hishash, state.hash, 18)) {
1913 logger(mesh, MESHLINK_ERROR, "Peer has an invalid key!\n%s\n", state.line + 2);
1914 meshlink_errno = MESHLINK_EPEER;
1918 hiskey = ecdsa_set_base64_public_key(fingerprint);
1921 meshlink_errno = MESHLINK_EINTERNAL;
1925 // Start an SPTPS session
1926 if(!sptps_start(&state.sptps, &state, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
1927 meshlink_errno = MESHLINK_EINTERNAL;
1931 // Feed rest of input buffer to SPTPS
1932 if(!sptps_receive_data(&state.sptps, state.buffer, state.blen)) {
1933 meshlink_errno = MESHLINK_EPEER;
1938 logger(mesh, MESHLINK_DEBUG, "Starting invitation recv loop: %d %zu\n", state.sock, sizeof(state.line));
1940 while((len = recv(state.sock, state.line, sizeof(state.line), 0))) {
1942 if(errno == EINTR) {
1946 logger(mesh, MESHLINK_ERROR, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1947 meshlink_errno = MESHLINK_ENETWORK;
1951 if(!sptps_receive_data(&state.sptps, state.line, len)) {
1952 meshlink_errno = MESHLINK_EPEER;
1957 if(!state.success) {
1958 logger(mesh, MESHLINK_ERROR, "Connection closed by peer, invitation cancelled.\n");
1959 meshlink_errno = MESHLINK_EPEER;
1963 sptps_stop(&state.sptps);
1966 closesocket(state.sock);
1968 pthread_mutex_unlock(&mesh->mutex);
1972 logger(mesh, MESHLINK_ERROR, "Invalid invitation URL\n");
1973 meshlink_errno = MESHLINK_EINVAL;
1975 sptps_stop(&state.sptps);
1979 if(state.sock != -1) {
1980 closesocket(state.sock);
1983 pthread_mutex_unlock(&mesh->mutex);
1987 char *meshlink_export(meshlink_handle_t *mesh) {
1989 meshlink_errno = MESHLINK_EINVAL;
1993 // Create a config file on the fly.
1996 packmsg_output_t out = {buf, sizeof(buf)};
1997 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
1998 packmsg_add_str(&out, mesh->name);
1999 packmsg_add_str(&out, CORE_MESH);
2001 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2005 packmsg_add_int32(&out, mesh->self->devclass);
2006 packmsg_add_bool(&out, mesh->self->status.blacklisted);
2007 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2009 if(mesh->self->canonical_address && !strchr(mesh->self->canonical_address, ' ')) {
2010 char *canonical_address = NULL;
2011 xasprintf(&canonical_address, "%s %s", mesh->self->canonical_address, mesh->myport);
2012 packmsg_add_str(&out, canonical_address);
2013 free(canonical_address);
2015 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2020 for(uint32_t i = 0; i < MAX_RECENT; i++) {
2021 if(mesh->self->recent[i].sa.sa_family) {
2028 packmsg_add_array(&out, count);
2030 for(uint32_t i = 0; i < count; i++) {
2031 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2034 packmsg_add_int64(&out, 0);
2035 packmsg_add_int64(&out, 0);
2037 pthread_mutex_unlock(&mesh->mutex);
2039 if(!packmsg_output_ok(&out)) {
2040 logger(mesh, MESHLINK_ERROR, "Error creating export data\n");
2041 meshlink_errno = MESHLINK_EINTERNAL;
2045 // Prepare a base64-encoded packmsg array containing our config file
2047 uint32_t len = packmsg_output_size(&out, buf);
2048 uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2049 uint8_t *buf2 = xmalloc(len2);
2050 packmsg_output_t out2 = {buf2, len2};
2051 packmsg_add_array(&out2, 1);
2052 packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2054 if(!packmsg_output_ok(&out2)) {
2055 logger(mesh, MESHLINK_ERROR, "Error creating export data\n");
2056 meshlink_errno = MESHLINK_EINTERNAL;
2061 b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2063 return (char *)buf2;
2066 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2067 logger(mesh, MESHLINK_DEBUG, "meshlink_import(%p)", (const void *)data);
2069 if(!mesh || !data) {
2070 meshlink_errno = MESHLINK_EINVAL;
2074 size_t datalen = strlen(data);
2075 uint8_t *buf = xmalloc(datalen);
2076 int buflen = b64decode(data, buf, datalen);
2079 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2081 meshlink_errno = MESHLINK_EPEER;
2085 packmsg_input_t in = {buf, buflen};
2086 uint32_t count = packmsg_get_array(&in);
2089 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2091 meshlink_errno = MESHLINK_EPEER;
2095 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2101 uint32_t len2 = packmsg_get_bin_raw(&in, &data2);
2107 packmsg_input_t in2 = {data2, len2};
2108 uint32_t version = packmsg_get_uint32(&in2);
2109 char *name = packmsg_get_str_dup(&in2);
2111 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
2113 packmsg_input_invalidate(&in);
2117 if(!check_id(name)) {
2122 node_t *n = lookup_node(mesh, name);
2125 logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
2133 config_t config = {data2, len2};
2135 if(!node_read_from_config(mesh, n, &config)) {
2137 packmsg_input_invalidate(&in);
2141 if(!node_write_config(mesh, n, true)) {
2150 pthread_mutex_unlock(&mesh->mutex);
2154 if(!packmsg_done(&in)) {
2155 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2156 meshlink_errno = MESHLINK_EPEER;
2160 if(!config_sync(mesh, "current")) {
2167 /* Hint that a hostname may be found at an address
2168 * See header file for detailed comment.
2170 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2171 logger(mesh, MESHLINK_DEBUG, "meshlink_hint_address(%s, %p)", node ? node->name : "(null)", (const void *)addr);
2173 if(!mesh || !node || !addr) {
2174 meshlink_errno = EINVAL;
2178 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2182 node_t *n = (node_t *)node;
2184 if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
2185 if(!node_write_config(mesh, n, false)) {
2186 logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
2190 pthread_mutex_unlock(&mesh->mutex);
2191 // @TODO do we want to fire off a connection attempt right away?
2194 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2195 if(mesh->node_status_cb) {
2196 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
2200 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
2201 if(!mesh->node_duplicate_cb || n->status.duplicate) {
2205 n->status.duplicate = true;
2206 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
2209 void meshlink_hint_network_change(struct meshlink_handle *mesh) {
2210 logger(mesh, MESHLINK_DEBUG, "meshlink_hint_network_change()");
2213 meshlink_errno = MESHLINK_EINVAL;
2217 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2221 pthread_mutex_unlock(&mesh->mutex);
2224 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
2225 logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_timeouts(%d, %d, %d)", devclass, pinginterval, pingtimeout);
2227 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
2228 meshlink_errno = EINVAL;
2232 if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
2233 meshlink_errno = EINVAL;
2237 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2241 mesh->dev_class_traits[devclass].pinginterval = pinginterval;
2242 mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
2243 pthread_mutex_unlock(&mesh->mutex);
2246 void meshlink_set_dev_class_fast_retry_period(meshlink_handle_t *mesh, dev_class_t devclass, int fast_retry_period) {
2247 logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_fast_retry_period(%d, %d)", devclass, fast_retry_period);
2249 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
2250 meshlink_errno = EINVAL;
2254 if(fast_retry_period < 0) {
2255 meshlink_errno = EINVAL;
2259 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2263 mesh->dev_class_traits[devclass].fast_retry_period = fast_retry_period;
2264 pthread_mutex_unlock(&mesh->mutex);
2267 void meshlink_set_dev_class_maxtimeout(struct meshlink_handle *mesh, dev_class_t devclass, int maxtimeout) {
2268 logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_fast_maxtimeout(%d, %d)", devclass, maxtimeout);
2270 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
2271 meshlink_errno = EINVAL;
2275 if(maxtimeout < 0) {
2276 meshlink_errno = EINVAL;
2280 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2284 mesh->dev_class_traits[devclass].maxtimeout = maxtimeout;
2285 pthread_mutex_unlock(&mesh->mutex);
2288 void meshlink_reset_timers(struct meshlink_handle *mesh) {
2289 logger(mesh, MESHLINK_DEBUG, "meshlink_reset_timers()");
2295 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2299 handle_network_change(mesh, true);
2301 pthread_mutex_unlock(&mesh->mutex);
2304 void meshlink_set_inviter_commits_first(struct meshlink_handle *mesh, bool inviter_commits_first) {
2305 logger(mesh, MESHLINK_DEBUG, "meshlink_set_inviter_commits_first(%d)", inviter_commits_first);
2308 meshlink_errno = EINVAL;
2312 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2316 mesh->inviter_commits_first = inviter_commits_first;
2317 pthread_mutex_unlock(&mesh->mutex);
2320 void meshlink_set_storage_policy(struct meshlink_handle *mesh, meshlink_storage_policy_t policy) {
2321 logger(mesh, MESHLINK_DEBUG, "meshlink_set_storage_policy(%d)", policy);
2324 meshlink_errno = EINVAL;
2328 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2332 mesh->storage_policy = policy;
2333 pthread_mutex_unlock(&mesh->mutex);
2336 void handle_network_change(meshlink_handle_t *mesh, bool online) {
2339 if(!mesh->loop.running) {
2344 signal_trigger(&mesh->loop, &mesh->datafromapp);
2347 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t cb_errno) {
2348 // We should only call the callback function if we are in the background thread.
2349 if(!mesh->error_cb) {
2353 if(!mesh->threadstarted) {
2357 if(mesh->thread == pthread_self()) {
2358 mesh->error_cb(mesh, cb_errno);
2362 static void __attribute__((constructor)) meshlink_init(void) {
2366 static void __attribute__((destructor)) meshlink_exit(void) {