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 *);
50 static int rstrip(char *value) {
51 int len = strlen(value);
53 while(len && strchr("\t\r\n ", value[len - 1])) {
60 static bool is_valid_hostname(const char *hostname) {
65 for(const char *p = hostname; *p; p++) {
66 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
74 static bool is_valid_port(const char *port) {
81 unsigned long int result = strtoul(port, &end, 10);
82 return result && result < 65536 && !*end;
85 for(const char *p = port; *p; p++) {
86 if(!(isalnum(*p) || *p == '-')) {
94 static void set_timeout(int sock, int timeout) {
99 tv.tv_sec = timeout / 1000;
100 tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
102 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
103 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
106 struct socket_in_netns_params {
115 static void *socket_in_netns_thread(void *arg) {
116 struct socket_in_netns_params *params = arg;
118 if(setns(params->netns, CLONE_NEWNET) == -1) {
119 meshlink_errno = MESHLINK_EINVAL;
123 params->fd = socket(params->domain, params->type, params->protocol);
129 static int socket_in_netns(int domain, int type, int protocol, int netns) {
131 return socket(domain, type, protocol);
135 struct socket_in_netns_params params = {domain, type, protocol, netns, -1};
139 if(pthread_create(&thr, NULL, socket_in_netns_thread, ¶ms) == 0) {
140 if(pthread_join(thr, NULL) != 0) {
152 static bool write_main_config_files(meshlink_handle_t *mesh) {
153 if(!mesh->confbase) {
157 uint8_t buf[BUFSIZE];
159 /* Write the main config file */
160 packmsg_output_t out = {buf, sizeof buf};
162 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
163 packmsg_add_str(&out, mesh->name);
164 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
165 packmsg_add_nil(&out); // Invitation keys are not supported
166 packmsg_add_uint16(&out, atoi(mesh->myport));
168 if(!packmsg_output_ok(&out)) {
172 config_t config = {buf, packmsg_output_size(&out, buf)};
174 if(!main_config_write(mesh, "current", &config, mesh->config_key)) {
178 /* Write our own host config file */
179 if(!node_write_config(mesh, mesh->self, true)) {
187 meshlink_handle_t *mesh;
189 char cookie[18 + 32];
197 char buffer[BUFSIZE];
200 static bool finalize_join(join_state_t *state, const void *buf, uint16_t len) {
201 meshlink_handle_t *mesh = state->mesh;
202 packmsg_input_t in = {buf, len};
203 uint32_t version = packmsg_get_uint32(&in);
205 if(version != MESHLINK_INVITATION_VERSION) {
206 logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
210 char *name = packmsg_get_str_dup(&in);
211 packmsg_skip_element(&in); // submesh_name
212 dev_class_t devclass = packmsg_get_int32(&in);
213 uint32_t count = packmsg_get_array(&in);
215 if(!name || !check_id(name)) {
216 logger(mesh, MESHLINK_DEBUG, "No valid Name found in invitation!\n");
222 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
228 free(mesh->self->name);
230 mesh->self->name = xstrdup(name);
231 mesh->self->devclass = devclass == DEV_CLASS_UNKNOWN ? mesh->devclass : devclass;
233 // Initialize configuration directory
234 if(!config_init(mesh, "current")) {
238 if(!write_main_config_files(mesh)) {
242 // Write host config files
243 for(uint32_t i = 0; i < count; i++) {
245 uint32_t data_len = packmsg_get_bin_raw(&in, &data);
248 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
252 packmsg_input_t in2 = {data, data_len};
253 uint32_t version2 = packmsg_get_uint32(&in2);
254 char *name2 = packmsg_get_str_dup(&in2);
256 if(!packmsg_input_ok(&in2) || version2 != MESHLINK_CONFIG_VERSION || !check_id(name2)) {
258 packmsg_input_invalidate(&in);
262 if(!check_id(name2)) {
267 if(!strcmp(name2, mesh->name)) {
268 logger(mesh, MESHLINK_ERROR, "Secondary chunk would overwrite our own host config file.\n");
270 meshlink_errno = MESHLINK_EPEER;
274 node_t *n = new_node();
277 config_t config = {data, data_len};
279 if(!node_read_from_config(mesh, n, &config)) {
281 logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
282 meshlink_errno = MESHLINK_EPEER;
287 /* The first host config file is of the inviter itself;
288 * remember the address we are currently using for the invitation connection.
291 socklen_t salen = sizeof(sa);
293 if(getpeername(state->sock, &sa.sa, &salen) == 0) {
294 node_add_recent_address(mesh, n, &sa);
298 if(!node_write_config(mesh, n, true)) {
306 /* Ensure the configuration directory metadata is on disk */
307 if(!config_sync(mesh, "current") || (mesh->confbase && !sync_path(mesh->confbase))) {
311 if(!mesh->inviter_commits_first) {
312 devtool_set_inviter_commits_first(false);
315 sptps_send_record(&state->sptps, 1, ecdsa_get_public_key(mesh->private_key), 32);
318 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
324 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
326 join_state_t *state = handle;
327 const char *ptr = data;
330 int result = send(state->sock, ptr, len, 0);
332 if(result == -1 && errno == EINTR) {
334 } else if(result <= 0) {
345 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
346 join_state_t *state = handle;
347 meshlink_handle_t *mesh = state->mesh;
349 if(mesh->inviter_commits_first) {
351 case SPTPS_HANDSHAKE:
352 return sptps_send_record(&state->sptps, 2, state->cookie, 18 + 32);
358 if(!finalize_join(state, msg, len)) {
362 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
363 shutdown(state->sock, SHUT_RDWR);
364 state->success = true;
372 case SPTPS_HANDSHAKE:
373 return sptps_send_record(&state->sptps, 0, state->cookie, 18);
376 return finalize_join(state, msg, len);
379 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
380 shutdown(state->sock, SHUT_RDWR);
381 state->success = true;
392 static bool recvline(join_state_t *state) {
393 char *newline = NULL;
395 while(!(newline = memchr(state->buffer, '\n', state->blen))) {
396 int result = recv(state->sock, state->buffer + state->blen, sizeof(state)->buffer - state->blen, 0);
398 if(result == -1 && errno == EINTR) {
400 } else if(result <= 0) {
404 state->blen += result;
407 if((size_t)(newline - state->buffer) >= sizeof(state->line)) {
411 size_t len = newline - state->buffer;
413 memcpy(state->line, state->buffer, len);
414 state->line[len] = 0;
415 memmove(state->buffer, newline + 1, state->blen - len - 1);
416 state->blen -= len + 1;
421 static bool sendline(int fd, const char *format, ...) {
422 char buffer[BUFSIZE];
427 va_start(ap, format);
428 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
431 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
439 int result = send(fd, p, blen, MSG_NOSIGNAL);
441 if(result == -1 && errno == EINTR) {
443 } else if(result <= 0) {
454 static const char *errstr[] = {
455 [MESHLINK_OK] = "No error",
456 [MESHLINK_EINVAL] = "Invalid argument",
457 [MESHLINK_ENOMEM] = "Out of memory",
458 [MESHLINK_ENOENT] = "No such node",
459 [MESHLINK_EEXIST] = "Node already exists",
460 [MESHLINK_EINTERNAL] = "Internal error",
461 [MESHLINK_ERESOLV] = "Could not resolve hostname",
462 [MESHLINK_ESTORAGE] = "Storage error",
463 [MESHLINK_ENETWORK] = "Network error",
464 [MESHLINK_EPEER] = "Error communicating with peer",
465 [MESHLINK_ENOTSUP] = "Operation not supported",
466 [MESHLINK_EBUSY] = "MeshLink instance already in use",
467 [MESHLINK_EBLACKLISTED] = "Node is blacklisted",
470 const char *meshlink_strerror(meshlink_errno_t err) {
471 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
472 return "Invalid error code";
478 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
479 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
481 mesh->private_key = ecdsa_generate();
483 if(!mesh->private_key) {
484 logger(mesh, MESHLINK_ERROR, "Error during key generation!\n");
485 meshlink_errno = MESHLINK_EINTERNAL;
489 logger(mesh, MESHLINK_DEBUG, "Done.\n");
494 static struct timespec idle(event_loop_t *loop, void *data) {
498 return (struct timespec) {
503 static bool meshlink_setup(meshlink_handle_t *mesh) {
504 if(!config_destroy(mesh->confbase, "new")) {
505 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/new: %s\n", mesh->confbase, strerror(errno));
506 meshlink_errno = MESHLINK_ESTORAGE;
510 if(!config_destroy(mesh->confbase, "old")) {
511 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
512 meshlink_errno = MESHLINK_ESTORAGE;
516 if(!config_init(mesh, "current")) {
517 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
518 meshlink_errno = MESHLINK_ESTORAGE;
522 if(!ecdsa_keygen(mesh)) {
523 meshlink_errno = MESHLINK_EINTERNAL;
527 mesh->myport = xstrdup("0");
529 /* Create a node for ourself */
531 mesh->self = new_node();
532 mesh->self->name = xstrdup(mesh->name);
533 mesh->self->devclass = mesh->devclass;
534 mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
535 mesh->self->session_id = mesh->session_id;
537 if(!write_main_config_files(mesh)) {
538 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
539 meshlink_errno = MESHLINK_ESTORAGE;
543 /* Ensure the configuration directory metadata is on disk */
544 if(!config_sync(mesh, "current")) {
551 static bool meshlink_read_config(meshlink_handle_t *mesh) {
554 if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
555 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
559 packmsg_input_t in = {config.buf, config.len};
560 const void *private_key;
562 uint32_t version = packmsg_get_uint32(&in);
563 char *name = packmsg_get_str_dup(&in);
564 uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
565 packmsg_skip_element(&in); // Invitation key is not supported
566 uint16_t myport = packmsg_get_uint16(&in);
568 if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96) {
569 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
571 config_free(&config);
575 if(mesh->name && strcmp(mesh->name, name)) {
576 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
577 meshlink_errno = MESHLINK_ESTORAGE;
579 config_free(&config);
585 xasprintf(&mesh->myport, "%u", myport);
586 mesh->private_key = ecdsa_set_private_key(private_key);
587 config_free(&config);
589 /* Create a node for ourself and read our host configuration file */
591 mesh->self = new_node();
592 mesh->self->name = xstrdup(name);
593 mesh->self->devclass = mesh->devclass;
594 mesh->self->session_id = mesh->session_id;
596 if(!node_read_public_key(mesh, mesh->self)) {
597 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
598 meshlink_errno = MESHLINK_ESTORAGE;
599 free_node(mesh->self);
608 static void *setup_network_in_netns_thread(void *arg) {
609 meshlink_handle_t *mesh = arg;
611 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
615 bool success = setup_network(mesh);
616 return success ? arg : NULL;
620 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
621 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_init(%s, %s, %s, %d)", confbase, name, appname, devclass);
623 if(!confbase || !*confbase) {
624 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
625 meshlink_errno = MESHLINK_EINVAL;
629 if(!appname || !*appname) {
630 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
631 meshlink_errno = MESHLINK_EINVAL;
635 if(strchr(appname, ' ')) {
636 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
637 meshlink_errno = MESHLINK_EINVAL;
641 if(name && !check_id(name)) {
642 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
643 meshlink_errno = MESHLINK_EINVAL;
647 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
648 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
649 meshlink_errno = MESHLINK_EINVAL;
653 meshlink_open_params_t *params = xzalloc(sizeof * params);
655 params->confbase = xstrdup(confbase);
656 params->name = name ? xstrdup(name) : NULL;
657 params->appname = xstrdup(appname);
658 params->devclass = devclass;
661 xasprintf(¶ms->lock_filename, "%s" SLASH "meshlink.lock", confbase);
666 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
667 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_netnst(%d)", netns);
670 meshlink_errno = MESHLINK_EINVAL;
674 params->netns = netns;
679 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
680 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_key(%p, %zu)", key, keylen);
683 meshlink_errno = MESHLINK_EINVAL;
687 if((!key && keylen) || (key && !keylen)) {
688 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
689 meshlink_errno = MESHLINK_EINVAL;
694 params->keylen = keylen;
699 bool meshlink_open_params_set_storage_policy(meshlink_open_params_t *params, meshlink_storage_policy_t policy) {
700 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_policy(%d)", policy);
703 meshlink_errno = MESHLINK_EINVAL;
707 params->storage_policy = policy;
712 bool meshlink_open_params_set_lock_filename(meshlink_open_params_t *params, const char *filename) {
713 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_lock_filename(%s)", filename);
715 if(!params || !filename) {
716 meshlink_errno = MESHLINK_EINVAL;
720 free(params->lock_filename);
721 params->lock_filename = xstrdup(filename);
726 bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
727 logger(NULL, MESHLINK_DEBUG, "meshlink_encrypted_key_rotate(%p, %zu)", new_key, new_keylen);
729 if(!mesh || !new_key || !new_keylen) {
730 logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
731 meshlink_errno = MESHLINK_EINVAL;
735 if(pthread_mutex_lock(&mesh->mutex) != 0) {
739 // Create hash for the new key
740 void *new_config_key;
741 new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
743 if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
744 logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
745 meshlink_errno = MESHLINK_EINTERNAL;
746 pthread_mutex_unlock(&mesh->mutex);
750 // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
752 if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
753 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
754 meshlink_errno = MESHLINK_ESTORAGE;
755 pthread_mutex_unlock(&mesh->mutex);
759 devtool_keyrotate_probe(1);
761 // Rename confbase/current/ to confbase/old
763 if(!config_rename(mesh, "current", "old")) {
764 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
765 meshlink_errno = MESHLINK_ESTORAGE;
766 pthread_mutex_unlock(&mesh->mutex);
770 devtool_keyrotate_probe(2);
772 // Rename confbase/new/ to confbase/current
774 if(!config_rename(mesh, "new", "current")) {
775 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
776 meshlink_errno = MESHLINK_ESTORAGE;
777 pthread_mutex_unlock(&mesh->mutex);
781 devtool_keyrotate_probe(3);
783 // Cleanup the "old" confbase sub-directory
785 if(!config_destroy(mesh->confbase, "old")) {
786 pthread_mutex_unlock(&mesh->mutex);
790 // Change the mesh handle key with new key
792 free(mesh->config_key);
793 mesh->config_key = new_config_key;
795 pthread_mutex_unlock(&mesh->mutex);
800 void meshlink_open_params_free(meshlink_open_params_t *params) {
801 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_free()");
804 meshlink_errno = MESHLINK_EINVAL;
808 free(params->confbase);
810 free(params->appname);
811 free(params->lock_filename);
816 /// Device class traits
817 static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
818 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
819 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
820 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
821 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN
824 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
825 logger(NULL, MESHLINK_DEBUG, "meshlink_open(%s, %s, %s, %d)", confbase, name, appname, devclass);
827 if(!confbase || !*confbase) {
828 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
829 meshlink_errno = MESHLINK_EINVAL;
833 char lock_filename[PATH_MAX];
834 snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
836 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
837 meshlink_open_params_t params = {
838 .confbase = (char *)confbase,
839 .lock_filename = lock_filename,
840 .name = (char *)name,
841 .appname = (char *)appname,
842 .devclass = devclass,
846 return meshlink_open_ex(¶ms);
849 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) {
850 logger(NULL, MESHLINK_DEBUG, "meshlink_open_encrypted(%s, %s, %s, %d, %p, %zu)", confbase, name, appname, devclass, key, keylen);
852 if(!confbase || !*confbase) {
853 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
854 meshlink_errno = MESHLINK_EINVAL;
858 char lock_filename[PATH_MAX];
859 snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
861 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
862 meshlink_open_params_t params = {
863 .confbase = (char *)confbase,
864 .lock_filename = lock_filename,
865 .name = (char *)name,
866 .appname = (char *)appname,
867 .devclass = devclass,
871 if(!meshlink_open_params_set_storage_key(¶ms, key, keylen)) {
875 return meshlink_open_ex(¶ms);
878 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
879 logger(NULL, MESHLINK_DEBUG, "meshlink_open_ephemeral(%s, %s, %d)", name, appname, devclass);
882 logger(NULL, MESHLINK_ERROR, "No name given!\n");
883 meshlink_errno = MESHLINK_EINVAL;
887 if(!check_id(name)) {
888 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
889 meshlink_errno = MESHLINK_EINVAL;
893 if(!appname || !*appname) {
894 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
895 meshlink_errno = MESHLINK_EINVAL;
899 if(strchr(appname, ' ')) {
900 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
901 meshlink_errno = MESHLINK_EINVAL;
905 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
906 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
907 meshlink_errno = MESHLINK_EINVAL;
911 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
912 meshlink_open_params_t params = {
913 .name = (char *)name,
914 .appname = (char *)appname,
915 .devclass = devclass,
919 return meshlink_open_ex(¶ms);
922 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
923 logger(NULL, MESHLINK_DEBUG, "meshlink_open_ex()");
925 // Validate arguments provided by the application
926 if(!params->appname || !*params->appname) {
927 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
928 meshlink_errno = MESHLINK_EINVAL;
932 if(strchr(params->appname, ' ')) {
933 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
934 meshlink_errno = MESHLINK_EINVAL;
938 if(params->name && !check_id(params->name)) {
939 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
940 meshlink_errno = MESHLINK_EINVAL;
944 if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
945 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
946 meshlink_errno = MESHLINK_EINVAL;
950 if((params->key && !params->keylen) || (!params->key && params->keylen)) {
951 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
952 meshlink_errno = MESHLINK_EINVAL;
956 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
958 if(params->confbase) {
959 mesh->confbase = xstrdup(params->confbase);
962 mesh->appname = xstrdup(params->appname);
963 mesh->devclass = params->devclass;
964 mesh->netns = params->netns;
965 mesh->log_cb = global_log_cb;
966 mesh->log_level = global_log_level;
967 mesh->packet = xmalloc(sizeof(vpn_packet_t));
969 randomize(&mesh->prng_state, sizeof(mesh->prng_state));
972 randomize(&mesh->session_id, sizeof(mesh->session_id));
973 } while(mesh->session_id == 0);
975 memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
977 mesh->name = params->name ? xstrdup(params->name) : NULL;
981 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
983 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
984 logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
985 meshlink_close(mesh);
986 meshlink_errno = MESHLINK_EINTERNAL;
991 // initialize mutexes and conds
992 pthread_mutexattr_t attr;
993 pthread_mutexattr_init(&attr);
995 if(pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) != 0) {
999 pthread_mutex_init(&mesh->mutex, &attr);
1000 pthread_cond_init(&mesh->cond, NULL);
1002 mesh->threadstarted = false;
1003 event_loop_init(&mesh->loop);
1004 mesh->loop.data = mesh;
1006 meshlink_queue_init(&mesh->outpacketqueue);
1008 // Atomically lock the configuration directory.
1009 if(!main_config_lock(mesh, params->lock_filename)) {
1010 meshlink_close(mesh);
1014 // If no configuration exists yet, create it.
1016 bool new_configuration = false;
1018 if(!meshlink_confbase_exists(mesh)) {
1020 logger(NULL, MESHLINK_ERROR, "No configuration files found!\n");
1021 meshlink_close(mesh);
1022 meshlink_errno = MESHLINK_ESTORAGE;
1026 if(!meshlink_setup(mesh)) {
1027 logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1028 meshlink_close(mesh);
1032 new_configuration = true;
1034 if(!meshlink_read_config(mesh)) {
1035 logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1036 meshlink_close(mesh);
1041 mesh->storage_policy = params->storage_policy;
1044 struct WSAData wsa_state;
1045 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1048 // Setup up everything
1049 // TODO: we should not open listening sockets yet
1051 bool success = false;
1053 if(mesh->netns != -1) {
1057 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1058 void *retval = NULL;
1059 success = pthread_join(thr, &retval) == 0 && retval;
1063 meshlink_errno = MESHLINK_EINTERNAL;
1066 #endif // HAVE_SETNS
1068 success = setup_network(mesh);
1072 meshlink_close(mesh);
1073 meshlink_errno = MESHLINK_ENETWORK;
1077 if(!node_write_config(mesh, mesh->self, new_configuration)) {
1078 logger(NULL, MESHLINK_ERROR, "Cannot update configuration\n");
1082 idle_set(&mesh->loop, idle, mesh);
1084 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1088 static void *meshlink_main_loop(void *arg) {
1089 meshlink_handle_t *mesh = arg;
1091 if(mesh->netns != -1) {
1094 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1095 pthread_cond_signal(&mesh->cond);
1100 pthread_cond_signal(&mesh->cond);
1102 #endif // HAVE_SETNS
1105 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1109 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1110 pthread_cond_broadcast(&mesh->cond);
1112 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1114 pthread_mutex_unlock(&mesh->mutex);
1119 bool meshlink_start(meshlink_handle_t *mesh) {
1121 meshlink_errno = MESHLINK_EINVAL;
1125 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1127 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1132 assert(mesh->private_key);
1133 assert(mesh->self->ecdsa);
1134 assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1136 if(mesh->threadstarted) {
1137 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1138 pthread_mutex_unlock(&mesh->mutex);
1142 // Reset node connection timers
1144 mesh->peer->last_connect_try = 0;
1147 //Check that a valid name is set
1149 logger(mesh, MESHLINK_ERROR, "No name given!\n");
1150 meshlink_errno = MESHLINK_EINVAL;
1151 pthread_mutex_unlock(&mesh->mutex);
1155 init_outgoings(mesh);
1157 // Start the main thread
1159 event_loop_start(&mesh->loop);
1161 // Ensure we have a decent amount of stack space. Musl's default of 80 kB is too small.
1162 pthread_attr_t attr;
1163 pthread_attr_init(&attr);
1164 pthread_attr_setstacksize(&attr, 16 * 1024);
1166 if(pthread_create(&mesh->thread, &attr, meshlink_main_loop, mesh) != 0) {
1167 logger(mesh, MESHLINK_ERROR, "Could not start thread: %s\n", strerror(errno));
1168 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1169 meshlink_errno = MESHLINK_EINTERNAL;
1170 event_loop_stop(&mesh->loop);
1171 pthread_mutex_unlock(&mesh->mutex);
1175 pthread_cond_wait(&mesh->cond, &mesh->mutex);
1176 mesh->threadstarted = true;
1178 pthread_mutex_unlock(&mesh->mutex);
1182 void meshlink_stop(meshlink_handle_t *mesh) {
1183 logger(mesh, MESHLINK_DEBUG, "meshlink_stop()\n");
1186 meshlink_errno = MESHLINK_EINVAL;
1190 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1194 // Shut down the main thread
1195 event_loop_stop(&mesh->loop);
1197 // TODO: send something to a local socket to kick the event loop
1199 if(mesh->threadstarted) {
1200 // Wait for the main thread to finish
1201 pthread_mutex_unlock(&mesh->mutex);
1203 if(pthread_join(mesh->thread, NULL) != 0) {
1207 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1211 mesh->threadstarted = false;
1214 // Close all metaconnections
1215 if(mesh->connection) {
1216 mesh->connection->outgoing = NULL;
1217 terminate_connection(mesh, mesh->connection, false);
1220 exit_outgoings(mesh);
1222 // Try to write out any changed node config files, ignore errors at this point.
1223 if(mesh->peer && mesh->peer->status.dirty) {
1224 if(!node_write_config(mesh, mesh->peer, false)) {
1229 pthread_mutex_unlock(&mesh->mutex);
1232 void meshlink_close(meshlink_handle_t *mesh) {
1233 logger(mesh, MESHLINK_DEBUG, "meshlink_close()\n");
1236 meshlink_errno = MESHLINK_EINVAL;
1240 // stop can be called even if mesh has not been started
1241 meshlink_stop(mesh);
1243 // lock is not released after this
1244 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1248 // Close and free all resources used.
1250 close_network_connections(mesh);
1252 logger(mesh, MESHLINK_INFO, "Terminating");
1254 event_loop_exit(&mesh->loop);
1258 if(mesh->confbase) {
1264 if(mesh->netns != -1) {
1268 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1272 meshlink_queue_exit(&mesh->outpacketqueue);
1275 free(mesh->appname);
1276 free(mesh->confbase);
1277 free(mesh->config_key);
1278 free(mesh->external_address_url);
1280 ecdsa_free(mesh->private_key);
1282 main_config_unlock(mesh);
1284 pthread_mutex_unlock(&mesh->mutex);
1285 pthread_mutex_destroy(&mesh->mutex);
1287 memset(mesh, 0, sizeof(*mesh));
1292 bool meshlink_destroy_ex(const meshlink_open_params_t *params) {
1293 logger(NULL, MESHLINK_DEBUG, "meshlink_destroy_ex()\n");
1296 meshlink_errno = MESHLINK_EINVAL;
1300 if(!params->confbase) {
1301 /* Ephemeral instances */
1305 /* Exit early if the confbase directory itself doesn't exist */
1306 if(access(params->confbase, F_OK) && errno == ENOENT) {
1310 /* Take the lock the same way meshlink_open() would. */
1311 FILE *lockfile = fopen(params->lock_filename, "w+");
1314 logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", params->lock_filename, strerror(errno));
1315 meshlink_errno = MESHLINK_ESTORAGE;
1320 fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
1324 // TODO: use _locking()?
1327 if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
1328 logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", params->lock_filename);
1330 meshlink_errno = MESHLINK_EBUSY;
1336 if(!config_destroy(params->confbase, "current") || !config_destroy(params->confbase, "new") || !config_destroy(params->confbase, "old")) {
1337 logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", params->confbase, strerror(errno));
1341 if(unlink(params->lock_filename)) {
1342 logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", params->lock_filename, strerror(errno));
1344 meshlink_errno = MESHLINK_ESTORAGE;
1350 if(!sync_path(params->confbase)) {
1351 logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", params->confbase, strerror(errno));
1352 meshlink_errno = MESHLINK_ESTORAGE;
1359 bool meshlink_destroy(const char *confbase) {
1360 logger(NULL, MESHLINK_DEBUG, "meshlink_destroy(%s)", confbase);
1362 char lock_filename[PATH_MAX];
1363 snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
1365 meshlink_open_params_t params = {
1366 .confbase = (char *)confbase,
1367 .lock_filename = lock_filename,
1370 return meshlink_destroy_ex(¶ms);
1373 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1374 logger(mesh, MESHLINK_DEBUG, "meshlink_set_receive_cb(%p)", (void *)(intptr_t)cb);
1377 meshlink_errno = MESHLINK_EINVAL;
1381 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1385 mesh->receive_cb = cb;
1386 pthread_mutex_unlock(&mesh->mutex);
1389 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1390 logger(mesh, MESHLINK_DEBUG, "meshlink_set_connection_try_cb(%p)", (void *)(intptr_t)cb);
1393 meshlink_errno = MESHLINK_EINVAL;
1397 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1401 mesh->connection_try_cb = cb;
1402 pthread_mutex_unlock(&mesh->mutex);
1405 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1406 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_status_cb(%p)", (void *)(intptr_t)cb);
1409 meshlink_errno = MESHLINK_EINVAL;
1413 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1417 mesh->node_status_cb = cb;
1418 pthread_mutex_unlock(&mesh->mutex);
1421 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1422 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_duplicate_cb(%p)", (void *)(intptr_t)cb);
1425 meshlink_errno = MESHLINK_EINVAL;
1429 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1433 mesh->node_duplicate_cb = cb;
1434 pthread_mutex_unlock(&mesh->mutex);
1437 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1438 logger(mesh, MESHLINK_DEBUG, "meshlink_set_log_cb(%p)", (void *)(intptr_t)cb);
1441 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1446 mesh->log_level = cb ? level : 0;
1447 pthread_mutex_unlock(&mesh->mutex);
1450 global_log_level = cb ? level : 0;
1454 void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
1455 logger(mesh, MESHLINK_DEBUG, "meshlink_set_error_cb(%p)", (void *)(intptr_t)cb);
1458 meshlink_errno = MESHLINK_EINVAL;
1462 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1466 mesh->error_cb = cb;
1467 pthread_mutex_unlock(&mesh->mutex);
1470 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1471 logger(mesh, MESHLINK_DEBUG, "meshlink_send(%s, %p, %zu)", destination ? destination->name : "(null)", data, len);
1473 // Validate arguments
1474 if(!mesh || !destination) {
1475 meshlink_errno = MESHLINK_EINVAL;
1483 if(!data || len > MTU) {
1484 meshlink_errno = MESHLINK_EINVAL;
1488 // Prepare the packet
1489 vpn_packet_t *packet = malloc(sizeof(*packet));
1492 meshlink_errno = MESHLINK_ENOMEM;
1497 memcpy(packet->data, data, len);
1500 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1502 meshlink_errno = MESHLINK_ENOMEM;
1506 logger(mesh, MESHLINK_DEBUG, "Adding packet of %zu bytes to packet queue", len);
1508 // Notify event loop
1509 signal_trigger(&mesh->loop, &mesh->datafromapp);
1514 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
1516 meshlink_handle_t *mesh = data;
1518 logger(mesh, MESHLINK_DEBUG, "Flushing the packet queue");
1520 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1521 logger(mesh, MESHLINK_DEBUG, "Removing packet of %d bytes from packet queue", packet->len);
1522 send_raw_packet(mesh, mesh->peer->connection, packet);
1527 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1528 if(!mesh || !node) {
1529 meshlink_errno = MESHLINK_EINVAL;
1533 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1537 node_t *n = (node_t *)node;
1539 if(!node_read_public_key(mesh, n) || !n->ecdsa) {
1540 meshlink_errno = MESHLINK_EINTERNAL;
1541 pthread_mutex_unlock(&mesh->mutex);
1545 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1548 meshlink_errno = MESHLINK_EINTERNAL;
1551 pthread_mutex_unlock(&mesh->mutex);
1555 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1557 meshlink_errno = MESHLINK_EINVAL;
1561 return (meshlink_node_t *)mesh->self;
1564 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1565 if(!mesh || !name) {
1566 meshlink_errno = MESHLINK_EINVAL;
1572 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1576 n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1577 pthread_mutex_unlock(&mesh->mutex);
1580 meshlink_errno = MESHLINK_ENOENT;
1583 return (meshlink_node_t *)n;
1586 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1587 logger(mesh, MESHLINK_DEBUG, "meshlink_sign(%p, %zu, %p, %p)", data, len, signature, (void *)siglen);
1589 if(!mesh || !data || !len || !signature || !siglen) {
1590 meshlink_errno = MESHLINK_EINVAL;
1594 if(*siglen < MESHLINK_SIGLEN) {
1595 meshlink_errno = MESHLINK_EINVAL;
1599 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1603 if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
1604 meshlink_errno = MESHLINK_EINTERNAL;
1605 pthread_mutex_unlock(&mesh->mutex);
1609 *siglen = MESHLINK_SIGLEN;
1610 pthread_mutex_unlock(&mesh->mutex);
1614 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1615 logger(mesh, MESHLINK_DEBUG, "meshlink_verify(%p, %zu, %p, %zu)", data, len, signature, siglen);
1617 if(!mesh || !source || !data || !len || !signature) {
1618 meshlink_errno = MESHLINK_EINVAL;
1622 if(siglen != MESHLINK_SIGLEN) {
1623 meshlink_errno = MESHLINK_EINVAL;
1627 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1633 struct node_t *n = (struct node_t *)source;
1635 if(!node_read_public_key(mesh, n)) {
1636 meshlink_errno = MESHLINK_EINTERNAL;
1639 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1642 pthread_mutex_unlock(&mesh->mutex);
1646 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
1647 logger(mesh, MESHLINK_DEBUG, "meshlink_set_canonical_address(%s, %s, %s)", node ? node->name : "(null)", address ? address : "(null)", port ? port : "(null)");
1649 if(!mesh || !node || !address) {
1650 meshlink_errno = MESHLINK_EINVAL;
1654 if(!is_valid_hostname(address)) {
1655 logger(mesh, MESHLINK_ERROR, "Invalid character in address: %s", address);
1656 meshlink_errno = MESHLINK_EINVAL;
1660 if((node_t *)node != mesh->self && !port) {
1661 logger(mesh, MESHLINK_ERROR, "Missing port number!");
1662 meshlink_errno = MESHLINK_EINVAL;
1667 if(port && !is_valid_port(port)) {
1668 logger(mesh, MESHLINK_ERROR, "Invalid character in port: %s", address);
1669 meshlink_errno = MESHLINK_EINVAL;
1673 char *canonical_address;
1675 xasprintf(&canonical_address, "%s %s", address, port ? port : mesh->myport);
1677 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1681 node_t *n = (node_t *)node;
1682 free(n->canonical_address);
1683 n->canonical_address = canonical_address;
1685 if(!node_write_config(mesh, n, false)) {
1686 pthread_mutex_unlock(&mesh->mutex);
1690 pthread_mutex_unlock(&mesh->mutex);
1692 return config_sync(mesh, "current");
1695 bool meshlink_clear_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node) {
1696 logger(mesh, MESHLINK_DEBUG, "meshlink_clear_canonical_address(%s)", node ? node->name : "(null)");
1698 if(!mesh || !node) {
1699 meshlink_errno = MESHLINK_EINVAL;
1703 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1707 node_t *n = (node_t *)node;
1708 free(n->canonical_address);
1709 n->canonical_address = NULL;
1711 if(!node_write_config(mesh, n, false)) {
1712 pthread_mutex_unlock(&mesh->mutex);
1716 pthread_mutex_unlock(&mesh->mutex);
1718 return config_sync(mesh, "current");
1721 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1722 logger(mesh, MESHLINK_DEBUG, "meshlink_join(%s)", invitation ? invitation : "(null)");
1724 if(!mesh || !invitation) {
1725 meshlink_errno = MESHLINK_EINVAL;
1729 if(mesh->storage_policy == MESHLINK_STORAGE_DISABLED) {
1730 meshlink_errno = MESHLINK_EINVAL;
1734 join_state_t *state = xzalloc(sizeof * state);
1738 ecdsa_t *key = NULL;
1739 ecdsa_t *hiskey = NULL;
1741 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1742 char *copy = xstrdup(invitation);
1744 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1748 //Before doing meshlink_join make sure we are not connected to another mesh
1749 if(mesh->threadstarted) {
1750 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
1751 meshlink_errno = MESHLINK_EINVAL;
1755 // 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.
1757 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
1758 meshlink_errno = MESHLINK_EINVAL;
1762 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
1764 char *slash = strchr(copy, '/');
1772 if(strlen(slash) != 48) {
1776 char *address = copy;
1779 if(!b64decode(slash, state->hash, 18) || !b64decode(slash + 24, state->cookie, 18)) {
1783 logger(mesh, MESHLINK_DEBUG, "Done");
1785 if(mesh->inviter_commits_first) {
1786 memcpy(state->cookie + 18, ecdsa_get_public_key(mesh->private_key), 32);
1789 // Generate a throw-away key for the invitation.
1790 key = ecdsa_generate();
1791 logger(mesh, MESHLINK_DEBUG, "Done");
1794 meshlink_errno = MESHLINK_EINTERNAL;
1798 char *b64key = ecdsa_get_base64_public_key(key);
1801 while(address && *address) {
1802 // We allow commas in the address part to support multiple addresses in one invitation URL.
1803 comma = strchr(address, ',');
1809 // Split of the port
1810 port = strrchr(address, ':');
1818 // IPv6 address are enclosed in brackets, per RFC 3986
1819 if(*address == '[') {
1821 char *bracket = strchr(address, ']');
1834 // Connect to the meshlink daemon mentioned in the URL.
1835 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1838 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
1839 state->sock = socket_in_netns(aip->ai_family, SOCK_STREAM, IPPROTO_TCP, mesh->netns);
1841 if(state->sock == -1) {
1842 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
1843 meshlink_errno = MESHLINK_ENETWORK;
1849 setsockopt(state->sock, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe));
1852 set_timeout(state->sock, 5000);
1854 if(connect(state->sock, aip->ai_addr, aip->ai_addrlen)) {
1855 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1856 meshlink_errno = MESHLINK_ENETWORK;
1857 closesocket(state->sock);
1867 meshlink_errno = MESHLINK_ERESOLV;
1870 if(state->sock != -1 || !comma) {
1877 if(state->sock == -1) {
1881 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
1883 // Tell him we have an invitation, and give him our throw-away key.
1887 if(!sendline(state->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
1888 logger(mesh, MESHLINK_ERROR, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1889 meshlink_errno = MESHLINK_ENETWORK;
1895 char hisname[BUFSIZE] = "";
1896 int code, hismajor, hisminor = 0;
1898 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) {
1899 logger(mesh, MESHLINK_ERROR, "Cannot read greeting from peer\n");
1900 meshlink_errno = MESHLINK_ENETWORK;
1904 // Check if the hash of the key he gave us matches the hash in the URL.
1905 char *fingerprint = state->line + 2;
1908 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1909 logger(mesh, MESHLINK_ERROR, "Could not create hash\n%s\n", state->line + 2);
1910 meshlink_errno = MESHLINK_EINTERNAL;
1914 if(memcmp(hishash, state->hash, 18)) {
1915 logger(mesh, MESHLINK_ERROR, "Peer has an invalid key!\n%s\n", state->line + 2);
1916 meshlink_errno = MESHLINK_EPEER;
1920 hiskey = ecdsa_set_base64_public_key(fingerprint);
1923 meshlink_errno = MESHLINK_EINTERNAL;
1927 // Start an SPTPS session
1928 if(!sptps_start(&state->sptps, state, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
1929 meshlink_errno = MESHLINK_EINTERNAL;
1933 // Feed rest of input buffer to SPTPS
1934 if(!sptps_receive_data(&state->sptps, state->buffer, state->blen)) {
1935 meshlink_errno = MESHLINK_EPEER;
1940 logger(mesh, MESHLINK_DEBUG, "Starting invitation recv loop: %d %zu\n", state->sock, sizeof(state->line));
1942 while((len = recv(state->sock, state->line, sizeof(state->line), 0))) {
1944 if(errno == EINTR) {
1948 if(errno == ENOTCONN) {
1952 logger(mesh, MESHLINK_ERROR, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1953 meshlink_errno = MESHLINK_ENETWORK;
1957 if(!sptps_receive_data(&state->sptps, state->line, len)) {
1958 meshlink_errno = MESHLINK_EPEER;
1962 if(state->success) {
1967 if(!state->success) {
1968 logger(mesh, MESHLINK_ERROR, "Connection closed by peer, invitation cancelled.\n");
1969 meshlink_errno = MESHLINK_EPEER;
1973 sptps_stop(&state->sptps);
1976 closesocket(state->sock);
1978 pthread_mutex_unlock(&mesh->mutex);
1982 logger(mesh, MESHLINK_ERROR, "Invalid invitation URL\n");
1983 meshlink_errno = MESHLINK_EINVAL;
1985 sptps_stop(&state->sptps);
1989 if(state->sock != -1) {
1990 closesocket(state->sock);
1993 pthread_mutex_unlock(&mesh->mutex);
1998 char *meshlink_export(meshlink_handle_t *mesh) {
2000 meshlink_errno = MESHLINK_EINVAL;
2004 // Create a config file on the fly.
2006 uint8_t buf[BUFSIZE];
2007 packmsg_output_t out = {buf, sizeof(buf)};
2008 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
2009 packmsg_add_str(&out, mesh->name);
2010 packmsg_add_str(&out, CORE_MESH);
2012 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2016 packmsg_add_int32(&out, mesh->self->devclass);
2017 packmsg_add_bool(&out, mesh->self->status.blacklisted);
2018 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2020 if(mesh->self->canonical_address && !strchr(mesh->self->canonical_address, ' ')) {
2021 char *canonical_address = NULL;
2022 xasprintf(&canonical_address, "%s %s", mesh->self->canonical_address, mesh->myport);
2023 packmsg_add_str(&out, canonical_address);
2024 free(canonical_address);
2026 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2031 for(uint32_t i = 0; i < MAX_RECENT; i++) {
2032 if(mesh->self->recent[i].sa.sa_family) {
2039 packmsg_add_array(&out, count);
2041 for(uint32_t i = 0; i < count; i++) {
2042 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2045 packmsg_add_int64(&out, 0);
2046 packmsg_add_int64(&out, 0);
2048 pthread_mutex_unlock(&mesh->mutex);
2050 if(!packmsg_output_ok(&out)) {
2051 logger(mesh, MESHLINK_ERROR, "Error creating export data\n");
2052 meshlink_errno = MESHLINK_EINTERNAL;
2056 // Prepare a base64-encoded packmsg array containing our config file
2058 uint32_t len = packmsg_output_size(&out, buf);
2059 uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2060 uint8_t *buf2 = xmalloc(len2);
2061 packmsg_output_t out2 = {buf2, len2};
2062 packmsg_add_array(&out2, 1);
2063 packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2065 if(!packmsg_output_ok(&out2)) {
2066 logger(mesh, MESHLINK_ERROR, "Error creating export data\n");
2067 meshlink_errno = MESHLINK_EINTERNAL;
2072 b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2074 return (char *)buf2;
2077 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2078 logger(mesh, MESHLINK_DEBUG, "meshlink_import(%p)", (const void *)data);
2080 if(!mesh || !data) {
2081 meshlink_errno = MESHLINK_EINVAL;
2085 size_t datalen = strlen(data);
2086 uint8_t *buf = xmalloc(datalen);
2087 int buflen = b64decode(data, buf, datalen);
2090 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2092 meshlink_errno = MESHLINK_EPEER;
2096 packmsg_input_t in = {buf, buflen};
2097 uint32_t count = packmsg_get_array(&in);
2100 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2102 meshlink_errno = MESHLINK_EPEER;
2106 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2112 uint32_t len2 = packmsg_get_bin_raw(&in, &data2);
2118 packmsg_input_t in2 = {data2, len2};
2119 uint32_t version = packmsg_get_uint32(&in2);
2120 char *name = packmsg_get_str_dup(&in2);
2122 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
2124 packmsg_input_invalidate(&in);
2128 if(!check_id(name)) {
2133 node_t *n = lookup_node(mesh, name);
2136 logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
2144 config_t config = {data2, len2};
2146 if(!node_read_from_config(mesh, n, &config)) {
2148 packmsg_input_invalidate(&in);
2152 if(!node_write_config(mesh, n, true)) {
2161 pthread_mutex_unlock(&mesh->mutex);
2165 if(!packmsg_done(&in)) {
2166 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2167 meshlink_errno = MESHLINK_EPEER;
2171 if(!config_sync(mesh, "current")) {
2178 /* Hint that a hostname may be found at an address
2179 * See header file for detailed comment.
2181 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2182 logger(mesh, MESHLINK_DEBUG, "meshlink_hint_address(%s, %p)", node ? node->name : "(null)", (const void *)addr);
2184 if(!mesh || !node || !addr) {
2185 meshlink_errno = EINVAL;
2189 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2193 node_t *n = (node_t *)node;
2195 if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
2196 if(!node_write_config(mesh, n, false)) {
2197 logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
2201 pthread_mutex_unlock(&mesh->mutex);
2202 // @TODO do we want to fire off a connection attempt right away?
2205 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2206 if(mesh->node_status_cb) {
2207 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
2211 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
2212 if(!mesh->node_duplicate_cb || n->status.duplicate) {
2216 n->status.duplicate = true;
2217 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
2220 void meshlink_hint_network_change(struct meshlink_handle *mesh) {
2221 logger(mesh, MESHLINK_DEBUG, "meshlink_hint_network_change()");
2224 meshlink_errno = MESHLINK_EINVAL;
2228 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2232 pthread_mutex_unlock(&mesh->mutex);
2235 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
2236 logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_timeouts(%d, %d, %d)", devclass, pinginterval, pingtimeout);
2238 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
2239 meshlink_errno = EINVAL;
2243 if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
2244 meshlink_errno = EINVAL;
2248 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2252 mesh->dev_class_traits[devclass].pinginterval = pinginterval;
2253 mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
2254 pthread_mutex_unlock(&mesh->mutex);
2257 void meshlink_set_dev_class_fast_retry_period(meshlink_handle_t *mesh, dev_class_t devclass, int fast_retry_period) {
2258 logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_fast_retry_period(%d, %d)", devclass, fast_retry_period);
2260 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
2261 meshlink_errno = EINVAL;
2265 if(fast_retry_period < 0) {
2266 meshlink_errno = EINVAL;
2270 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2274 mesh->dev_class_traits[devclass].fast_retry_period = fast_retry_period;
2275 pthread_mutex_unlock(&mesh->mutex);
2278 void meshlink_set_dev_class_maxtimeout(struct meshlink_handle *mesh, dev_class_t devclass, int maxtimeout) {
2279 logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_fast_maxtimeout(%d, %d)", devclass, maxtimeout);
2281 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
2282 meshlink_errno = EINVAL;
2286 if(maxtimeout < 0) {
2287 meshlink_errno = EINVAL;
2291 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2295 mesh->dev_class_traits[devclass].maxtimeout = maxtimeout;
2296 pthread_mutex_unlock(&mesh->mutex);
2299 void meshlink_reset_timers(struct meshlink_handle *mesh) {
2300 logger(mesh, MESHLINK_DEBUG, "meshlink_reset_timers()");
2306 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2310 handle_network_change(mesh, true);
2312 pthread_mutex_unlock(&mesh->mutex);
2315 void meshlink_set_inviter_commits_first(struct meshlink_handle *mesh, bool inviter_commits_first) {
2316 logger(mesh, MESHLINK_DEBUG, "meshlink_set_inviter_commits_first(%d)", inviter_commits_first);
2319 meshlink_errno = EINVAL;
2323 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2327 mesh->inviter_commits_first = inviter_commits_first;
2328 pthread_mutex_unlock(&mesh->mutex);
2331 void meshlink_set_storage_policy(struct meshlink_handle *mesh, meshlink_storage_policy_t policy) {
2332 logger(mesh, MESHLINK_DEBUG, "meshlink_set_storage_policy(%d)", policy);
2335 meshlink_errno = EINVAL;
2339 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2343 mesh->storage_policy = policy;
2344 pthread_mutex_unlock(&mesh->mutex);
2347 void handle_network_change(meshlink_handle_t *mesh, bool online) {
2350 if(!mesh->loop.running) {
2355 signal_trigger(&mesh->loop, &mesh->datafromapp);
2358 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t cb_errno) {
2359 // We should only call the callback function if we are in the background thread.
2360 if(!mesh->error_cb) {
2364 if(!mesh->threadstarted) {
2368 if(mesh->thread == pthread_self()) {
2369 mesh->error_cb(mesh, cb_errno);
2373 static void __attribute__((constructor)) meshlink_init(void) {
2377 static void __attribute__((destructor)) meshlink_exit(void) {