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"
37 #include "ed25519/sha512.h"
41 #define MSG_NOSIGNAL 0
43 __thread meshlink_errno_t meshlink_errno;
44 meshlink_log_cb_t global_log_cb;
45 meshlink_log_level_t global_log_level;
47 typedef bool (*search_node_by_condition_t)(const node_t *, const void *);
49 static int rstrip(char *value) {
50 int len = strlen(value);
52 while(len && strchr("\t\r\n ", value[len - 1])) {
59 static bool is_valid_hostname(const char *hostname) {
64 for(const char *p = hostname; *p; p++) {
65 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
73 static bool is_valid_port(const char *port) {
80 unsigned long int result = strtoul(port, &end, 10);
81 return result && result < 65536 && !*end;
84 for(const char *p = port; *p; p++) {
85 if(!(isalnum(*p) || *p == '-')) {
93 static void set_timeout(int sock, int timeout) {
98 tv.tv_sec = timeout / 1000;
99 tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
101 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
102 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
105 struct socket_in_netns_params {
114 static void *socket_in_netns_thread(void *arg) {
115 struct socket_in_netns_params *params = arg;
117 if(setns(params->netns, CLONE_NEWNET) == -1) {
118 meshlink_errno = MESHLINK_EINVAL;
122 params->fd = socket(params->domain, params->type, params->protocol);
128 static int socket_in_netns(int domain, int type, int protocol, int netns) {
130 return socket(domain, type, protocol);
134 struct socket_in_netns_params params = {domain, type, protocol, netns, -1};
138 if(pthread_create(&thr, NULL, socket_in_netns_thread, ¶ms) == 0) {
139 if(pthread_join(thr, NULL) != 0) {
151 static bool write_main_config_files(meshlink_handle_t *mesh) {
152 if(!mesh->confbase) {
158 /* Write the main config file */
159 packmsg_output_t out = {buf, sizeof buf};
161 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
162 packmsg_add_str(&out, mesh->name);
163 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
164 packmsg_add_nil(&out); // Invitation keys are not supported
165 packmsg_add_uint16(&out, atoi(mesh->myport));
167 if(!packmsg_output_ok(&out)) {
171 config_t config = {buf, packmsg_output_size(&out, buf)};
173 if(!main_config_write(mesh, "current", &config, mesh->config_key)) {
177 /* Write our own host config file */
178 if(!node_write_config(mesh, mesh->self, true)) {
186 meshlink_handle_t *mesh;
188 char cookie[18 + 32];
199 static bool finalize_join(join_state_t *state, const void *buf, uint16_t len) {
200 meshlink_handle_t *mesh = state->mesh;
201 packmsg_input_t in = {buf, len};
202 uint32_t version = packmsg_get_uint32(&in);
204 if(version != MESHLINK_INVITATION_VERSION) {
205 logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
209 char *name = packmsg_get_str_dup(&in);
210 packmsg_skip_element(&in); // submesh_name
211 dev_class_t devclass = packmsg_get_int32(&in);
212 uint32_t count = packmsg_get_array(&in);
214 if(!name || !check_id(name)) {
215 logger(mesh, MESHLINK_DEBUG, "No valid Name found in invitation!\n");
221 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
227 free(mesh->self->name);
229 mesh->self->name = xstrdup(name);
230 mesh->self->devclass = devclass == DEV_CLASS_UNKNOWN ? mesh->devclass : devclass;
232 // Initialize configuration directory
233 if(!config_init(mesh, "current")) {
237 if(!write_main_config_files(mesh)) {
241 // Write host config files
242 for(uint32_t i = 0; i < count; i++) {
244 uint32_t data_len = packmsg_get_bin_raw(&in, &data);
247 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
251 packmsg_input_t in2 = {data, data_len};
252 uint32_t version2 = packmsg_get_uint32(&in2);
253 char *name2 = packmsg_get_str_dup(&in2);
255 if(!packmsg_input_ok(&in2) || version2 != MESHLINK_CONFIG_VERSION || !check_id(name2)) {
257 packmsg_input_invalidate(&in);
261 if(!check_id(name2)) {
266 if(!strcmp(name2, mesh->name)) {
267 logger(mesh, MESHLINK_ERROR, "Secondary chunk would overwrite our own host config file.\n");
269 meshlink_errno = MESHLINK_EPEER;
273 node_t *n = new_node();
276 config_t config = {data, data_len};
278 if(!node_read_from_config(mesh, n, &config)) {
280 logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
281 meshlink_errno = MESHLINK_EPEER;
286 /* The first host config file is of the inviter itself;
287 * remember the address we are currently using for the invitation connection.
290 socklen_t salen = sizeof(sa);
292 if(getpeername(state->sock, &sa.sa, &salen) == 0) {
293 node_add_recent_address(mesh, n, &sa);
297 if(!node_write_config(mesh, n, true)) {
305 /* Ensure the configuration directory metadata is on disk */
306 if(!config_sync(mesh, "current") || (mesh->confbase && !sync_path(mesh->confbase))) {
310 if(!mesh->inviter_commits_first) {
311 devtool_set_inviter_commits_first(false);
314 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);
321 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
323 join_state_t *state = handle;
324 const char *ptr = data;
327 int result = send(state->sock, ptr, len, 0);
329 if(result == -1 && errno == EINTR) {
331 } else if(result <= 0) {
342 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
343 join_state_t *state = handle;
344 meshlink_handle_t *mesh = state->mesh;
346 if(mesh->inviter_commits_first) {
348 case SPTPS_HANDSHAKE:
349 return sptps_send_record(&state->sptps, 2, state->cookie, 18 + 32);
355 if(!finalize_join(state, msg, len)) {
359 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
360 shutdown(state->sock, SHUT_RDWR);
361 state->success = true;
369 case SPTPS_HANDSHAKE:
370 return sptps_send_record(&state->sptps, 0, state->cookie, 18);
373 return finalize_join(state, msg, len);
376 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
377 shutdown(state->sock, SHUT_RDWR);
378 state->success = true;
389 static bool recvline(join_state_t *state) {
390 char *newline = NULL;
392 while(!(newline = memchr(state->buffer, '\n', state->blen))) {
393 int result = recv(state->sock, state->buffer + state->blen, sizeof(state)->buffer - state->blen, 0);
395 if(result == -1 && errno == EINTR) {
397 } else if(result <= 0) {
401 state->blen += result;
404 if((size_t)(newline - state->buffer) >= sizeof(state->line)) {
408 size_t len = newline - state->buffer;
410 memcpy(state->line, state->buffer, len);
411 state->line[len] = 0;
412 memmove(state->buffer, newline + 1, state->blen - len - 1);
413 state->blen -= len + 1;
418 static bool sendline(int fd, const char *format, ...) {
424 va_start(ap, format);
425 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
428 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
436 int result = send(fd, p, blen, MSG_NOSIGNAL);
438 if(result == -1 && errno == EINTR) {
440 } else if(result <= 0) {
451 static const char *errstr[] = {
452 [MESHLINK_OK] = "No error",
453 [MESHLINK_EINVAL] = "Invalid argument",
454 [MESHLINK_ENOMEM] = "Out of memory",
455 [MESHLINK_ENOENT] = "No such node",
456 [MESHLINK_EEXIST] = "Node already exists",
457 [MESHLINK_EINTERNAL] = "Internal error",
458 [MESHLINK_ERESOLV] = "Could not resolve hostname",
459 [MESHLINK_ESTORAGE] = "Storage error",
460 [MESHLINK_ENETWORK] = "Network error",
461 [MESHLINK_EPEER] = "Error communicating with peer",
462 [MESHLINK_ENOTSUP] = "Operation not supported",
463 [MESHLINK_EBUSY] = "MeshLink instance already in use",
464 [MESHLINK_EBLACKLISTED] = "Node is blacklisted",
467 const char *meshlink_strerror(meshlink_errno_t err) {
468 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
469 return "Invalid error code";
475 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
476 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
478 mesh->private_key = ecdsa_generate();
480 if(!mesh->private_key) {
481 logger(mesh, MESHLINK_ERROR, "Error during key generation!\n");
482 meshlink_errno = MESHLINK_EINTERNAL;
486 logger(mesh, MESHLINK_DEBUG, "Done.\n");
491 static struct timespec idle(event_loop_t *loop, void *data) {
493 meshlink_handle_t *mesh = data;
495 if(mesh->peer && mesh->peer->utcp) {
496 return utcp_timeout(mesh->peer->utcp);
498 return (struct timespec) {
504 static bool meshlink_setup(meshlink_handle_t *mesh) {
505 if(!config_destroy(mesh->confbase, "new")) {
506 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/new: %s\n", mesh->confbase, strerror(errno));
507 meshlink_errno = MESHLINK_ESTORAGE;
511 if(!config_destroy(mesh->confbase, "old")) {
512 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
513 meshlink_errno = MESHLINK_ESTORAGE;
517 if(!config_init(mesh, "current")) {
518 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
519 meshlink_errno = MESHLINK_ESTORAGE;
523 if(!ecdsa_keygen(mesh)) {
524 meshlink_errno = MESHLINK_EINTERNAL;
528 mesh->myport = xstrdup("0");
530 /* Create a node for ourself */
532 mesh->self = new_node();
533 mesh->self->name = xstrdup(mesh->name);
534 mesh->self->devclass = mesh->devclass;
535 mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
536 mesh->self->session_id = mesh->session_id;
538 if(!write_main_config_files(mesh)) {
539 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
540 meshlink_errno = MESHLINK_ESTORAGE;
544 /* Ensure the configuration directory metadata is on disk */
545 if(!config_sync(mesh, "current")) {
552 static bool meshlink_read_config(meshlink_handle_t *mesh) {
555 if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
556 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
560 packmsg_input_t in = {config.buf, config.len};
561 const void *private_key;
563 uint32_t version = packmsg_get_uint32(&in);
564 char *name = packmsg_get_str_dup(&in);
565 uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
566 packmsg_skip_element(&in); // Invitation key is not supported
567 uint16_t myport = packmsg_get_uint16(&in);
569 if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96) {
570 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
572 config_free(&config);
576 if(mesh->name && strcmp(mesh->name, name)) {
577 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
578 meshlink_errno = MESHLINK_ESTORAGE;
580 config_free(&config);
586 xasprintf(&mesh->myport, "%u", myport);
587 mesh->private_key = ecdsa_set_private_key(private_key);
588 config_free(&config);
590 /* Create a node for ourself and read our host configuration file */
592 mesh->self = new_node();
593 mesh->self->name = xstrdup(name);
594 mesh->self->devclass = mesh->devclass;
595 mesh->self->session_id = mesh->session_id;
597 if(!node_read_public_key(mesh, mesh->self)) {
598 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
599 meshlink_errno = MESHLINK_ESTORAGE;
600 free_node(mesh->self);
609 static void *setup_network_in_netns_thread(void *arg) {
610 meshlink_handle_t *mesh = arg;
612 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
616 bool success = setup_network(mesh);
617 return success ? arg : NULL;
621 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
622 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_init(%s, %s, %s, %d)", confbase, name, appname, devclass);
624 if(!confbase || !*confbase) {
625 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
626 meshlink_errno = MESHLINK_EINVAL;
630 if(!appname || !*appname) {
631 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
632 meshlink_errno = MESHLINK_EINVAL;
636 if(strchr(appname, ' ')) {
637 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
638 meshlink_errno = MESHLINK_EINVAL;
642 if(name && !check_id(name)) {
643 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
644 meshlink_errno = MESHLINK_EINVAL;
648 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
649 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
650 meshlink_errno = MESHLINK_EINVAL;
654 meshlink_open_params_t *params = xzalloc(sizeof * params);
656 params->confbase = xstrdup(confbase);
657 params->name = name ? xstrdup(name) : NULL;
658 params->appname = xstrdup(appname);
659 params->devclass = devclass;
662 xasprintf(¶ms->lock_filename, "%s" SLASH "meshlink.lock", confbase);
667 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
668 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_netnst(%d)", netns);
671 meshlink_errno = MESHLINK_EINVAL;
675 params->netns = netns;
680 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
681 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_key(%p, %zu)", key, keylen);
684 meshlink_errno = MESHLINK_EINVAL;
688 if((!key && keylen) || (key && !keylen)) {
689 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
690 meshlink_errno = MESHLINK_EINVAL;
695 params->keylen = keylen;
700 bool meshlink_open_params_set_storage_policy(meshlink_open_params_t *params, meshlink_storage_policy_t policy) {
701 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_policy(%d)", policy);
704 meshlink_errno = MESHLINK_EINVAL;
708 params->storage_policy = policy;
713 bool meshlink_open_params_set_lock_filename(meshlink_open_params_t *params, const char *filename) {
714 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_lock_filename(%s)", filename);
716 if(!params || !filename) {
717 meshlink_errno = MESHLINK_EINVAL;
721 free(params->lock_filename);
722 params->lock_filename = xstrdup(filename);
727 bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
728 logger(NULL, MESHLINK_DEBUG, "meshlink_encrypted_key_rotate(%p, %zu)", new_key, new_keylen);
730 if(!mesh || !new_key || !new_keylen) {
731 logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
732 meshlink_errno = MESHLINK_EINVAL;
736 if(pthread_mutex_lock(&mesh->mutex) != 0) {
740 // Create hash for the new key
741 void *new_config_key;
742 new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
744 if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
745 logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
746 meshlink_errno = MESHLINK_EINTERNAL;
747 pthread_mutex_unlock(&mesh->mutex);
751 // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
753 if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
754 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
755 meshlink_errno = MESHLINK_ESTORAGE;
756 pthread_mutex_unlock(&mesh->mutex);
760 devtool_keyrotate_probe(1);
762 // Rename confbase/current/ to confbase/old
764 if(!config_rename(mesh, "current", "old")) {
765 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
766 meshlink_errno = MESHLINK_ESTORAGE;
767 pthread_mutex_unlock(&mesh->mutex);
771 devtool_keyrotate_probe(2);
773 // Rename confbase/new/ to confbase/current
775 if(!config_rename(mesh, "new", "current")) {
776 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
777 meshlink_errno = MESHLINK_ESTORAGE;
778 pthread_mutex_unlock(&mesh->mutex);
782 devtool_keyrotate_probe(3);
784 // Cleanup the "old" confbase sub-directory
786 if(!config_destroy(mesh->confbase, "old")) {
787 pthread_mutex_unlock(&mesh->mutex);
791 // Change the mesh handle key with new key
793 free(mesh->config_key);
794 mesh->config_key = new_config_key;
796 pthread_mutex_unlock(&mesh->mutex);
801 void meshlink_open_params_free(meshlink_open_params_t *params) {
802 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_free()");
805 meshlink_errno = MESHLINK_EINVAL;
809 free(params->confbase);
811 free(params->appname);
812 free(params->lock_filename);
817 /// Device class traits
818 static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
819 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
820 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
821 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
822 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN
825 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
826 logger(NULL, MESHLINK_DEBUG, "meshlink_open(%s, %s, %s, %d)", confbase, name, appname, devclass);
828 if(!confbase || !*confbase) {
829 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
830 meshlink_errno = MESHLINK_EINVAL;
834 char lock_filename[PATH_MAX];
835 snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
837 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
838 meshlink_open_params_t params = {
839 .confbase = (char *)confbase,
840 .lock_filename = lock_filename,
841 .name = (char *)name,
842 .appname = (char *)appname,
843 .devclass = devclass,
847 return meshlink_open_ex(¶ms);
850 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) {
851 logger(NULL, MESHLINK_DEBUG, "meshlink_open_encrypted(%s, %s, %s, %d, %p, %zu)", confbase, name, appname, devclass, key, keylen);
853 if(!confbase || !*confbase) {
854 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
855 meshlink_errno = MESHLINK_EINVAL;
859 char lock_filename[PATH_MAX];
860 snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
862 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
863 meshlink_open_params_t params = {
864 .confbase = (char *)confbase,
865 .lock_filename = lock_filename,
866 .name = (char *)name,
867 .appname = (char *)appname,
868 .devclass = devclass,
872 if(!meshlink_open_params_set_storage_key(¶ms, key, keylen)) {
876 return meshlink_open_ex(¶ms);
879 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
880 logger(NULL, MESHLINK_DEBUG, "meshlink_open_ephemeral(%s, %s, %d)", name, appname, devclass);
883 logger(NULL, MESHLINK_ERROR, "No name given!\n");
884 meshlink_errno = MESHLINK_EINVAL;
888 if(!check_id(name)) {
889 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
890 meshlink_errno = MESHLINK_EINVAL;
894 if(!appname || !*appname) {
895 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
896 meshlink_errno = MESHLINK_EINVAL;
900 if(strchr(appname, ' ')) {
901 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
902 meshlink_errno = MESHLINK_EINVAL;
906 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
907 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
908 meshlink_errno = MESHLINK_EINVAL;
912 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
913 meshlink_open_params_t params = {
914 .name = (char *)name,
915 .appname = (char *)appname,
916 .devclass = devclass,
920 return meshlink_open_ex(¶ms);
923 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
924 logger(NULL, MESHLINK_DEBUG, "meshlink_open_ex()");
926 // Validate arguments provided by the application
927 if(!params->appname || !*params->appname) {
928 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
929 meshlink_errno = MESHLINK_EINVAL;
933 if(strchr(params->appname, ' ')) {
934 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
935 meshlink_errno = MESHLINK_EINVAL;
939 if(params->name && !check_id(params->name)) {
940 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
941 meshlink_errno = MESHLINK_EINVAL;
945 if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
946 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
947 meshlink_errno = MESHLINK_EINVAL;
951 if((params->key && !params->keylen) || (!params->key && params->keylen)) {
952 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
953 meshlink_errno = MESHLINK_EINVAL;
957 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
959 if(params->confbase) {
960 mesh->confbase = xstrdup(params->confbase);
963 mesh->appname = xstrdup(params->appname);
964 mesh->devclass = params->devclass;
965 mesh->netns = params->netns;
966 mesh->log_cb = global_log_cb;
967 mesh->log_level = global_log_level;
968 mesh->packet = xmalloc(sizeof(vpn_packet_t));
970 randomize(&mesh->prng_state, sizeof(mesh->prng_state));
973 randomize(&mesh->session_id, sizeof(mesh->session_id));
974 } while(mesh->session_id == 0);
976 memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
978 mesh->name = params->name ? xstrdup(params->name) : NULL;
982 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
984 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
985 logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
986 meshlink_close(mesh);
987 meshlink_errno = MESHLINK_EINTERNAL;
992 // initialize mutexes and conds
993 pthread_mutexattr_t attr;
994 pthread_mutexattr_init(&attr);
996 if(pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) != 0) {
1000 pthread_mutex_init(&mesh->mutex, &attr);
1001 pthread_cond_init(&mesh->cond, NULL);
1003 mesh->threadstarted = false;
1004 event_loop_init(&mesh->loop);
1005 mesh->loop.data = mesh;
1007 meshlink_queue_init(&mesh->outpacketqueue);
1009 // Atomically lock the configuration directory.
1010 if(!main_config_lock(mesh, params->lock_filename)) {
1011 meshlink_close(mesh);
1015 // If no configuration exists yet, create it.
1017 bool new_configuration = false;
1019 if(!meshlink_confbase_exists(mesh)) {
1021 logger(NULL, MESHLINK_ERROR, "No configuration files found!\n");
1022 meshlink_close(mesh);
1023 meshlink_errno = MESHLINK_ESTORAGE;
1027 if(!meshlink_setup(mesh)) {
1028 logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1029 meshlink_close(mesh);
1033 new_configuration = true;
1035 if(!meshlink_read_config(mesh)) {
1036 logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1037 meshlink_close(mesh);
1042 mesh->storage_policy = params->storage_policy;
1045 struct WSAData wsa_state;
1046 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1049 // Setup up everything
1050 // TODO: we should not open listening sockets yet
1052 bool success = false;
1054 if(mesh->netns != -1) {
1058 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1059 void *retval = NULL;
1060 success = pthread_join(thr, &retval) == 0 && retval;
1064 meshlink_errno = MESHLINK_EINTERNAL;
1067 #endif // HAVE_SETNS
1069 success = setup_network(mesh);
1073 meshlink_close(mesh);
1074 meshlink_errno = MESHLINK_ENETWORK;
1078 if(!node_write_config(mesh, mesh->self, new_configuration)) {
1079 logger(NULL, MESHLINK_ERROR, "Cannot update configuration\n");
1083 idle_set(&mesh->loop, idle, mesh);
1085 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1089 static void *meshlink_main_loop(void *arg) {
1090 meshlink_handle_t *mesh = arg;
1092 if(mesh->netns != -1) {
1095 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1096 pthread_cond_signal(&mesh->cond);
1101 pthread_cond_signal(&mesh->cond);
1103 #endif // HAVE_SETNS
1106 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1110 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1111 pthread_cond_broadcast(&mesh->cond);
1113 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1115 pthread_mutex_unlock(&mesh->mutex);
1120 bool meshlink_start(meshlink_handle_t *mesh) {
1122 meshlink_errno = MESHLINK_EINVAL;
1126 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1128 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1133 assert(mesh->private_key);
1134 assert(mesh->self->ecdsa);
1135 assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1137 if(mesh->threadstarted) {
1138 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1139 pthread_mutex_unlock(&mesh->mutex);
1143 // Reset node connection timers
1145 mesh->peer->last_connect_try = 0;
1148 //Check that a valid name is set
1150 logger(mesh, MESHLINK_ERROR, "No name given!\n");
1151 meshlink_errno = MESHLINK_EINVAL;
1152 pthread_mutex_unlock(&mesh->mutex);
1156 init_outgoings(mesh);
1158 // Start the main thread
1160 event_loop_start(&mesh->loop);
1162 // Ensure we have a decent amount of stack space. Musl's default of 80 kB is too small.
1163 pthread_attr_t attr;
1164 pthread_attr_init(&attr);
1165 pthread_attr_setstacksize(&attr, 1024 * 1024);
1167 if(pthread_create(&mesh->thread, &attr, meshlink_main_loop, mesh) != 0) {
1168 logger(mesh, MESHLINK_ERROR, "Could not start thread: %s\n", strerror(errno));
1169 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1170 meshlink_errno = MESHLINK_EINTERNAL;
1171 event_loop_stop(&mesh->loop);
1172 pthread_mutex_unlock(&mesh->mutex);
1176 pthread_cond_wait(&mesh->cond, &mesh->mutex);
1177 mesh->threadstarted = true;
1179 pthread_mutex_unlock(&mesh->mutex);
1183 void meshlink_stop(meshlink_handle_t *mesh) {
1184 logger(mesh, MESHLINK_DEBUG, "meshlink_stop()\n");
1187 meshlink_errno = MESHLINK_EINVAL;
1191 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1195 // Shut down the main thread
1196 event_loop_stop(&mesh->loop);
1198 // TODO: send something to a local socket to kick the event loop
1200 if(mesh->threadstarted) {
1201 // Wait for the main thread to finish
1202 pthread_mutex_unlock(&mesh->mutex);
1204 if(pthread_join(mesh->thread, NULL) != 0) {
1208 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1212 mesh->threadstarted = false;
1215 // Close all metaconnections
1216 if(mesh->connection) {
1217 mesh->connection->outgoing = NULL;
1218 terminate_connection(mesh, mesh->connection, false);
1221 exit_outgoings(mesh);
1223 // Try to write out any changed node config files, ignore errors at this point.
1224 if(mesh->peer && mesh->peer->status.dirty) {
1225 if(!node_write_config(mesh, mesh->peer, false)) {
1230 pthread_mutex_unlock(&mesh->mutex);
1233 void meshlink_close(meshlink_handle_t *mesh) {
1234 logger(mesh, MESHLINK_DEBUG, "meshlink_close()\n");
1237 meshlink_errno = MESHLINK_EINVAL;
1241 // stop can be called even if mesh has not been started
1242 meshlink_stop(mesh);
1244 // lock is not released after this
1245 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1249 // Close and free all resources used.
1251 close_network_connections(mesh);
1253 logger(mesh, MESHLINK_INFO, "Terminating");
1255 event_loop_exit(&mesh->loop);
1259 if(mesh->confbase) {
1265 if(mesh->netns != -1) {
1269 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1273 meshlink_queue_exit(&mesh->outpacketqueue);
1276 free(mesh->appname);
1277 free(mesh->confbase);
1278 free(mesh->config_key);
1279 free(mesh->external_address_url);
1281 ecdsa_free(mesh->private_key);
1283 main_config_unlock(mesh);
1285 pthread_mutex_unlock(&mesh->mutex);
1286 pthread_mutex_destroy(&mesh->mutex);
1288 memset(mesh, 0, sizeof(*mesh));
1293 bool meshlink_destroy_ex(const meshlink_open_params_t *params) {
1294 logger(NULL, MESHLINK_DEBUG, "meshlink_destroy_ex()\n");
1297 meshlink_errno = MESHLINK_EINVAL;
1301 if(!params->confbase) {
1302 /* Ephemeral instances */
1306 /* Exit early if the confbase directory itself doesn't exist */
1307 if(access(params->confbase, F_OK) && errno == ENOENT) {
1311 /* Take the lock the same way meshlink_open() would. */
1312 FILE *lockfile = fopen(params->lock_filename, "w+");
1315 logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", params->lock_filename, strerror(errno));
1316 meshlink_errno = MESHLINK_ESTORAGE;
1321 fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
1325 // TODO: use _locking()?
1328 if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
1329 logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", params->lock_filename);
1331 meshlink_errno = MESHLINK_EBUSY;
1337 if(!config_destroy(params->confbase, "current") || !config_destroy(params->confbase, "new") || !config_destroy(params->confbase, "old")) {
1338 logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", params->confbase, strerror(errno));
1342 if(unlink(params->lock_filename)) {
1343 logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", params->lock_filename, strerror(errno));
1345 meshlink_errno = MESHLINK_ESTORAGE;
1351 if(!sync_path(params->confbase)) {
1352 logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", params->confbase, strerror(errno));
1353 meshlink_errno = MESHLINK_ESTORAGE;
1360 bool meshlink_destroy(const char *confbase) {
1361 logger(NULL, MESHLINK_DEBUG, "meshlink_destroy(%s)", confbase);
1363 char lock_filename[PATH_MAX];
1364 snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
1366 meshlink_open_params_t params = {
1367 .confbase = (char *)confbase,
1368 .lock_filename = lock_filename,
1371 return meshlink_destroy_ex(¶ms);
1374 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1375 logger(mesh, MESHLINK_DEBUG, "meshlink_set_receive_cb(%p)", (void *)(intptr_t)cb);
1378 meshlink_errno = MESHLINK_EINVAL;
1382 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1386 mesh->receive_cb = cb;
1387 pthread_mutex_unlock(&mesh->mutex);
1390 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1391 logger(mesh, MESHLINK_DEBUG, "meshlink_set_connection_try_cb(%p)", (void *)(intptr_t)cb);
1394 meshlink_errno = MESHLINK_EINVAL;
1398 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1402 mesh->connection_try_cb = cb;
1403 pthread_mutex_unlock(&mesh->mutex);
1406 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1407 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_status_cb(%p)", (void *)(intptr_t)cb);
1410 meshlink_errno = MESHLINK_EINVAL;
1414 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1418 mesh->node_status_cb = cb;
1419 pthread_mutex_unlock(&mesh->mutex);
1422 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1423 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_duplicate_cb(%p)", (void *)(intptr_t)cb);
1426 meshlink_errno = MESHLINK_EINVAL;
1430 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1434 mesh->node_duplicate_cb = cb;
1435 pthread_mutex_unlock(&mesh->mutex);
1438 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1439 logger(mesh, MESHLINK_DEBUG, "meshlink_set_log_cb(%p)", (void *)(intptr_t)cb);
1442 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1447 mesh->log_level = cb ? level : 0;
1448 pthread_mutex_unlock(&mesh->mutex);
1451 global_log_level = cb ? level : 0;
1455 void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
1456 logger(mesh, MESHLINK_DEBUG, "meshlink_set_error_cb(%p)", (void *)(intptr_t)cb);
1459 meshlink_errno = MESHLINK_EINVAL;
1463 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1467 mesh->error_cb = cb;
1468 pthread_mutex_unlock(&mesh->mutex);
1471 static bool prepare_packet(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len, vpn_packet_t *packet) {
1472 meshlink_packethdr_t *hdr;
1474 if(len > MAXSIZE - sizeof(*hdr)) {
1475 meshlink_errno = MESHLINK_EINVAL;
1479 node_t *n = (node_t *)destination;
1481 if(n->status.blacklisted) {
1482 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1483 meshlink_errno = MESHLINK_EBLACKLISTED;
1487 // Prepare the packet
1488 packet->probe = false;
1489 packet->tcp = false;
1490 packet->len = len + sizeof(*hdr);
1492 hdr = (meshlink_packethdr_t *)packet->data;
1493 memset(hdr, 0, sizeof(*hdr));
1494 // leave the last byte as 0 to make sure strings are always
1495 // null-terminated if they are longer than the buffer
1496 strncpy((char *)hdr->destination, destination->name, sizeof(hdr->destination) - 1);
1497 strncpy((char *)hdr->source, mesh->self->name, sizeof(hdr->source) - 1);
1499 memcpy(packet->data + sizeof(*hdr), data, len);
1504 static bool meshlink_send_immediate(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1506 assert(destination);
1510 // Prepare the packet
1511 if(!prepare_packet(mesh, destination, data, len, mesh->packet)) {
1515 // Send it immediately
1516 route(mesh, mesh->self, mesh->packet);
1521 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1522 logger(mesh, MESHLINK_DEBUG, "meshlink_send(%s, %p, %zu)", destination ? destination->name : "(null)", data, len);
1524 // Validate arguments
1525 if(!mesh || !destination) {
1526 meshlink_errno = MESHLINK_EINVAL;
1535 meshlink_errno = MESHLINK_EINVAL;
1539 // Prepare the packet
1540 vpn_packet_t *packet = malloc(sizeof(*packet));
1543 meshlink_errno = MESHLINK_ENOMEM;
1547 if(!prepare_packet(mesh, destination, data, len, packet)) {
1553 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1555 meshlink_errno = MESHLINK_ENOMEM;
1559 logger(mesh, MESHLINK_DEBUG, "Adding packet of %zu bytes to packet queue", len);
1561 // Notify event loop
1562 signal_trigger(&mesh->loop, &mesh->datafromapp);
1567 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
1569 meshlink_handle_t *mesh = data;
1571 logger(mesh, MESHLINK_DEBUG, "Flushing the packet queue");
1573 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1574 logger(mesh, MESHLINK_DEBUG, "Removing packet of %d bytes from packet queue", packet->len);
1575 route(mesh, mesh->self, packet);
1580 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1581 if(!mesh || !node) {
1582 meshlink_errno = MESHLINK_EINVAL;
1586 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1590 node_t *n = (node_t *)node;
1592 if(!node_read_public_key(mesh, n) || !n->ecdsa) {
1593 meshlink_errno = MESHLINK_EINTERNAL;
1594 pthread_mutex_unlock(&mesh->mutex);
1598 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1601 meshlink_errno = MESHLINK_EINTERNAL;
1604 pthread_mutex_unlock(&mesh->mutex);
1608 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1610 meshlink_errno = MESHLINK_EINVAL;
1614 return (meshlink_node_t *)mesh->self;
1617 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1618 if(!mesh || !name) {
1619 meshlink_errno = MESHLINK_EINVAL;
1625 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1629 n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1630 pthread_mutex_unlock(&mesh->mutex);
1633 meshlink_errno = MESHLINK_ENOENT;
1636 return (meshlink_node_t *)n;
1639 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1640 logger(mesh, MESHLINK_DEBUG, "meshlink_sign(%p, %zu, %p, %p)", data, len, signature, (void *)siglen);
1642 if(!mesh || !data || !len || !signature || !siglen) {
1643 meshlink_errno = MESHLINK_EINVAL;
1647 if(*siglen < MESHLINK_SIGLEN) {
1648 meshlink_errno = MESHLINK_EINVAL;
1652 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1656 if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
1657 meshlink_errno = MESHLINK_EINTERNAL;
1658 pthread_mutex_unlock(&mesh->mutex);
1662 *siglen = MESHLINK_SIGLEN;
1663 pthread_mutex_unlock(&mesh->mutex);
1667 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1668 logger(mesh, MESHLINK_DEBUG, "meshlink_verify(%p, %zu, %p, %zu)", data, len, signature, siglen);
1670 if(!mesh || !source || !data || !len || !signature) {
1671 meshlink_errno = MESHLINK_EINVAL;
1675 if(siglen != MESHLINK_SIGLEN) {
1676 meshlink_errno = MESHLINK_EINVAL;
1680 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1686 struct node_t *n = (struct node_t *)source;
1688 if(!node_read_public_key(mesh, n)) {
1689 meshlink_errno = MESHLINK_EINTERNAL;
1692 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1695 pthread_mutex_unlock(&mesh->mutex);
1699 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
1700 logger(mesh, MESHLINK_DEBUG, "meshlink_set_canonical_address(%s, %s, %s)", node ? node->name : "(null)", address ? address : "(null)", port ? port : "(null)");
1702 if(!mesh || !node || !address) {
1703 meshlink_errno = MESHLINK_EINVAL;
1707 if(!is_valid_hostname(address)) {
1708 logger(mesh, MESHLINK_ERROR, "Invalid character in address: %s", address);
1709 meshlink_errno = MESHLINK_EINVAL;
1713 if((node_t *)node != mesh->self && !port) {
1714 logger(mesh, MESHLINK_ERROR, "Missing port number!");
1715 meshlink_errno = MESHLINK_EINVAL;
1720 if(port && !is_valid_port(port)) {
1721 logger(mesh, MESHLINK_ERROR, "Invalid character in port: %s", address);
1722 meshlink_errno = MESHLINK_EINVAL;
1726 char *canonical_address;
1728 xasprintf(&canonical_address, "%s %s", address, port ? port : mesh->myport);
1730 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1734 node_t *n = (node_t *)node;
1735 free(n->canonical_address);
1736 n->canonical_address = canonical_address;
1738 if(!node_write_config(mesh, n, false)) {
1739 pthread_mutex_unlock(&mesh->mutex);
1743 pthread_mutex_unlock(&mesh->mutex);
1745 return config_sync(mesh, "current");
1748 bool meshlink_clear_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node) {
1749 logger(mesh, MESHLINK_DEBUG, "meshlink_clear_canonical_address(%s)", node ? node->name : "(null)");
1751 if(!mesh || !node) {
1752 meshlink_errno = MESHLINK_EINVAL;
1756 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1760 node_t *n = (node_t *)node;
1761 free(n->canonical_address);
1762 n->canonical_address = NULL;
1764 if(!node_write_config(mesh, n, false)) {
1765 pthread_mutex_unlock(&mesh->mutex);
1769 pthread_mutex_unlock(&mesh->mutex);
1771 return config_sync(mesh, "current");
1774 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1775 logger(mesh, MESHLINK_DEBUG, "meshlink_join(%s)", invitation ? invitation : "(null)");
1777 if(!mesh || !invitation) {
1778 meshlink_errno = MESHLINK_EINVAL;
1782 if(mesh->storage_policy == MESHLINK_STORAGE_DISABLED) {
1783 meshlink_errno = MESHLINK_EINVAL;
1787 join_state_t state = {
1792 ecdsa_t *key = NULL;
1793 ecdsa_t *hiskey = NULL;
1795 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1796 char copy[strlen(invitation) + 1];
1798 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1802 //Before doing meshlink_join make sure we are not connected to another mesh
1803 if(mesh->threadstarted) {
1804 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
1805 meshlink_errno = MESHLINK_EINVAL;
1809 // 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.
1811 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
1812 meshlink_errno = MESHLINK_EINVAL;
1816 strcpy(copy, invitation);
1818 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
1820 char *slash = strchr(copy, '/');
1828 if(strlen(slash) != 48) {
1832 char *address = copy;
1835 if(!b64decode(slash, state.hash, 18) || !b64decode(slash + 24, state.cookie, 18)) {
1839 if(mesh->inviter_commits_first) {
1840 memcpy(state.cookie + 18, ecdsa_get_public_key(mesh->private_key), 32);
1843 // Generate a throw-away key for the invitation.
1844 key = ecdsa_generate();
1847 meshlink_errno = MESHLINK_EINTERNAL;
1851 char *b64key = ecdsa_get_base64_public_key(key);
1854 while(address && *address) {
1855 // We allow commas in the address part to support multiple addresses in one invitation URL.
1856 comma = strchr(address, ',');
1862 // Split of the port
1863 port = strrchr(address, ':');
1871 // IPv6 address are enclosed in brackets, per RFC 3986
1872 if(*address == '[') {
1874 char *bracket = strchr(address, ']');
1887 // Connect to the meshlink daemon mentioned in the URL.
1888 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1891 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
1892 state.sock = socket_in_netns(aip->ai_family, SOCK_STREAM, IPPROTO_TCP, mesh->netns);
1894 if(state.sock == -1) {
1895 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
1896 meshlink_errno = MESHLINK_ENETWORK;
1902 setsockopt(state.sock, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe));
1905 set_timeout(state.sock, 5000);
1907 if(connect(state.sock, aip->ai_addr, aip->ai_addrlen)) {
1908 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1909 meshlink_errno = MESHLINK_ENETWORK;
1910 closesocket(state.sock);
1920 meshlink_errno = MESHLINK_ERESOLV;
1923 if(state.sock != -1 || !comma) {
1930 if(state.sock == -1) {
1934 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
1936 // Tell him we have an invitation, and give him our throw-away key.
1940 if(!sendline(state.sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
1941 logger(mesh, MESHLINK_ERROR, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1942 meshlink_errno = MESHLINK_ENETWORK;
1948 char hisname[4096] = "";
1949 int code, hismajor, hisminor = 0;
1951 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) {
1952 logger(mesh, MESHLINK_ERROR, "Cannot read greeting from peer\n");
1953 meshlink_errno = MESHLINK_ENETWORK;
1957 // Check if the hash of the key he gave us matches the hash in the URL.
1958 char *fingerprint = state.line + 2;
1961 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1962 logger(mesh, MESHLINK_ERROR, "Could not create hash\n%s\n", state.line + 2);
1963 meshlink_errno = MESHLINK_EINTERNAL;
1967 if(memcmp(hishash, state.hash, 18)) {
1968 logger(mesh, MESHLINK_ERROR, "Peer has an invalid key!\n%s\n", state.line + 2);
1969 meshlink_errno = MESHLINK_EPEER;
1973 hiskey = ecdsa_set_base64_public_key(fingerprint);
1976 meshlink_errno = MESHLINK_EINTERNAL;
1980 // Start an SPTPS session
1981 if(!sptps_start(&state.sptps, &state, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
1982 meshlink_errno = MESHLINK_EINTERNAL;
1986 // Feed rest of input buffer to SPTPS
1987 if(!sptps_receive_data(&state.sptps, state.buffer, state.blen)) {
1988 meshlink_errno = MESHLINK_EPEER;
1993 logger(mesh, MESHLINK_DEBUG, "Starting invitation recv loop: %d %zu\n", state.sock, sizeof(state.line));
1995 while((len = recv(state.sock, state.line, sizeof(state.line), 0))) {
1997 if(errno == EINTR) {
2001 logger(mesh, MESHLINK_ERROR, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2002 meshlink_errno = MESHLINK_ENETWORK;
2006 if(!sptps_receive_data(&state.sptps, state.line, len)) {
2007 meshlink_errno = MESHLINK_EPEER;
2012 if(!state.success) {
2013 logger(mesh, MESHLINK_ERROR, "Connection closed by peer, invitation cancelled.\n");
2014 meshlink_errno = MESHLINK_EPEER;
2018 sptps_stop(&state.sptps);
2021 closesocket(state.sock);
2023 pthread_mutex_unlock(&mesh->mutex);
2027 logger(mesh, MESHLINK_ERROR, "Invalid invitation URL\n");
2028 meshlink_errno = MESHLINK_EINVAL;
2030 sptps_stop(&state.sptps);
2034 if(state.sock != -1) {
2035 closesocket(state.sock);
2038 pthread_mutex_unlock(&mesh->mutex);
2042 char *meshlink_export(meshlink_handle_t *mesh) {
2044 meshlink_errno = MESHLINK_EINVAL;
2048 // Create a config file on the fly.
2051 packmsg_output_t out = {buf, sizeof(buf)};
2052 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
2053 packmsg_add_str(&out, mesh->name);
2054 packmsg_add_str(&out, CORE_MESH);
2056 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2060 packmsg_add_int32(&out, mesh->self->devclass);
2061 packmsg_add_bool(&out, mesh->self->status.blacklisted);
2062 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2064 if(mesh->self->canonical_address && !strchr(mesh->self->canonical_address, ' ')) {
2065 char *canonical_address = NULL;
2066 xasprintf(&canonical_address, "%s %s", mesh->self->canonical_address, mesh->myport);
2067 packmsg_add_str(&out, canonical_address);
2068 free(canonical_address);
2070 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2075 for(uint32_t i = 0; i < MAX_RECENT; i++) {
2076 if(mesh->self->recent[i].sa.sa_family) {
2083 packmsg_add_array(&out, count);
2085 for(uint32_t i = 0; i < count; i++) {
2086 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2089 packmsg_add_int64(&out, 0);
2090 packmsg_add_int64(&out, 0);
2092 pthread_mutex_unlock(&mesh->mutex);
2094 if(!packmsg_output_ok(&out)) {
2095 logger(mesh, MESHLINK_ERROR, "Error creating export data\n");
2096 meshlink_errno = MESHLINK_EINTERNAL;
2100 // Prepare a base64-encoded packmsg array containing our config file
2102 uint32_t len = packmsg_output_size(&out, buf);
2103 uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2104 uint8_t *buf2 = xmalloc(len2);
2105 packmsg_output_t out2 = {buf2, len2};
2106 packmsg_add_array(&out2, 1);
2107 packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2109 if(!packmsg_output_ok(&out2)) {
2110 logger(mesh, MESHLINK_ERROR, "Error creating export data\n");
2111 meshlink_errno = MESHLINK_EINTERNAL;
2116 b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2118 return (char *)buf2;
2121 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2122 logger(mesh, MESHLINK_DEBUG, "meshlink_import(%p)", (const void *)data);
2124 if(!mesh || !data) {
2125 meshlink_errno = MESHLINK_EINVAL;
2129 size_t datalen = strlen(data);
2130 uint8_t *buf = xmalloc(datalen);
2131 int buflen = b64decode(data, buf, datalen);
2134 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2136 meshlink_errno = MESHLINK_EPEER;
2140 packmsg_input_t in = {buf, buflen};
2141 uint32_t count = packmsg_get_array(&in);
2144 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2146 meshlink_errno = MESHLINK_EPEER;
2150 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2156 uint32_t len2 = packmsg_get_bin_raw(&in, &data2);
2162 packmsg_input_t in2 = {data2, len2};
2163 uint32_t version = packmsg_get_uint32(&in2);
2164 char *name = packmsg_get_str_dup(&in2);
2166 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
2168 packmsg_input_invalidate(&in);
2172 if(!check_id(name)) {
2177 node_t *n = lookup_node(mesh, name);
2180 logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
2188 config_t config = {data2, len2};
2190 if(!node_read_from_config(mesh, n, &config)) {
2192 packmsg_input_invalidate(&in);
2196 if(!node_write_config(mesh, n, true)) {
2205 pthread_mutex_unlock(&mesh->mutex);
2209 if(!packmsg_done(&in)) {
2210 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2211 meshlink_errno = MESHLINK_EPEER;
2215 if(!config_sync(mesh, "current")) {
2222 /* Hint that a hostname may be found at an address
2223 * See header file for detailed comment.
2225 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2226 logger(mesh, MESHLINK_DEBUG, "meshlink_hint_address(%s, %p)", node ? node->name : "(null)", (const void *)addr);
2228 if(!mesh || !node || !addr) {
2229 meshlink_errno = EINVAL;
2233 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2237 node_t *n = (node_t *)node;
2239 if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
2240 if(!node_write_config(mesh, n, false)) {
2241 logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
2245 pthread_mutex_unlock(&mesh->mutex);
2246 // @TODO do we want to fire off a connection attempt right away?
2249 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2251 node_t *n = utcp->priv;
2252 meshlink_handle_t *mesh = n->mesh;
2254 if(mesh->channel_accept_cb && mesh->channel_listen_cb) {
2255 return mesh->channel_listen_cb(mesh, (meshlink_node_t *)n, port);
2257 return mesh->channel_accept_cb;
2261 /* Finish one AIO buffer, return true if the channel is still open. */
2262 static bool aio_finish_one(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t **head) {
2263 meshlink_aio_buffer_t *aio = *head;
2267 channel->in_callback = true;
2270 if(aio->cb.buffer) {
2271 aio->cb.buffer(mesh, channel, aio->data, aio->done, aio->priv);
2275 aio->cb.fd(mesh, channel, aio->fd, aio->done, aio->priv);
2279 channel->in_callback = false;
2292 /* Finish all AIO buffers, return true if the channel is still open. */
2293 static bool aio_abort(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t **head) {
2295 if(!aio_finish_one(mesh, channel, head)) {
2303 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2304 meshlink_channel_t *channel = connection->priv;
2310 node_t *n = channel->node;
2311 meshlink_handle_t *mesh = n->mesh;
2313 if(n->status.destroyed) {
2314 meshlink_channel_close(mesh, channel);
2318 const char *p = data;
2321 while(channel->aio_receive) {
2323 /* This receive callback signalled an error, abort all outstanding AIO buffers. */
2324 if(!aio_abort(mesh, channel, &channel->aio_receive)) {
2331 meshlink_aio_buffer_t *aio = channel->aio_receive;
2332 size_t todo = aio->len - aio->done;
2339 memcpy((char *)aio->data + aio->done, p, todo);
2341 ssize_t result = write(aio->fd, p, todo);
2344 if(result < 0 && errno == EINTR) {
2348 /* Writing to fd failed, cancel just this AIO buffer. */
2349 logger(mesh, MESHLINK_ERROR, "Writing to AIO fd %d failed: %s", aio->fd, strerror(errno));
2351 if(!aio_finish_one(mesh, channel, &channel->aio_receive)) {
2365 if(aio->done == aio->len) {
2366 if(!aio_finish_one(mesh, channel, &channel->aio_receive)) {
2376 if(channel->receive_cb) {
2377 channel->receive_cb(mesh, channel, p, left);
2383 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2384 node_t *n = utcp_connection->utcp->priv;
2390 meshlink_handle_t *mesh = n->mesh;
2392 if(!mesh->channel_accept_cb) {
2396 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2398 channel->c = utcp_connection;
2400 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2401 utcp_accept(utcp_connection, channel_recv, channel);
2407 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2408 node_t *n = utcp->priv;
2410 if(n->status.destroyed) {
2414 meshlink_handle_t *mesh = n->mesh;
2415 return meshlink_send_immediate(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2418 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2419 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_receive_cb(%p, %p)", (void *)channel, (void *)(intptr_t)cb);
2421 if(!mesh || !channel) {
2422 meshlink_errno = MESHLINK_EINVAL;
2426 channel->receive_cb = cb;
2429 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2431 node_t *n = (node_t *)source;
2437 utcp_recv(n->utcp, data, len);
2440 static void channel_poll(struct utcp_connection *connection, size_t len) {
2441 meshlink_channel_t *channel = connection->priv;
2447 node_t *n = channel->node;
2448 meshlink_handle_t *mesh = n->mesh;
2450 while(channel->aio_send) {
2452 /* This poll callback signalled an error, abort all outstanding AIO buffers. */
2453 if(!aio_abort(mesh, channel, &channel->aio_send)) {
2460 /* We have at least one AIO buffer. Send as much as possible from the buffers. */
2461 meshlink_aio_buffer_t *aio = channel->aio_send;
2462 size_t todo = aio->len - aio->done;
2470 sent = utcp_send(connection, (char *)aio->data + aio->done, todo);
2472 /* Limit the amount we read at once to avoid stack overflows */
2478 ssize_t result = read(aio->fd, buf, todo);
2482 sent = utcp_send(connection, buf, todo);
2484 if(result < 0 && errno == EINTR) {
2488 /* Reading from fd failed, cancel just this AIO buffer. */
2490 logger(mesh, MESHLINK_ERROR, "Reading from AIO fd %d failed: %s", aio->fd, strerror(errno));
2493 if(!aio_finish_one(mesh, channel, &channel->aio_send)) {
2501 if(sent != (ssize_t)todo) {
2502 /* Sending failed, abort all outstanding AIO buffers and send a poll callback. */
2503 if(!aio_abort(mesh, channel, &channel->aio_send)) {
2514 /* If we didn't finish this buffer, exit early. */
2515 if(aio->done < aio->len) {
2519 /* Signal completion of this buffer, and go to the next one. */
2520 if(!aio_finish_one(mesh, channel, &channel->aio_send)) {
2529 if(channel->poll_cb) {
2530 channel->poll_cb(mesh, channel, len);
2532 utcp_set_poll_cb(connection, NULL);
2536 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2537 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_poll_cb(%p, %p)", (void *)channel, (void *)(intptr_t)cb);
2539 if(!mesh || !channel) {
2540 meshlink_errno = MESHLINK_EINVAL;
2544 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2548 channel->poll_cb = cb;
2549 utcp_set_poll_cb(channel->c, (cb || channel->aio_send) ? channel_poll : NULL);
2550 pthread_mutex_unlock(&mesh->mutex);
2553 void meshlink_set_channel_listen_cb(meshlink_handle_t *mesh, meshlink_channel_listen_cb_t cb) {
2554 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_listen_cb(%p)", (void *)(intptr_t)cb);
2557 meshlink_errno = MESHLINK_EINVAL;
2561 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2565 mesh->channel_listen_cb = cb;
2567 pthread_mutex_unlock(&mesh->mutex);
2570 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2571 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_accept_cb(%p)", (void *)(intptr_t)cb);
2574 meshlink_errno = MESHLINK_EINVAL;
2578 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2582 mesh->channel_accept_cb = cb;
2583 mesh->receive_cb = channel_receive;
2586 mesh->peer->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, mesh->peer);
2589 pthread_mutex_unlock(&mesh->mutex);
2592 void meshlink_set_channel_sndbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
2593 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_sndbuf(%p, %zu)", (void *)channel, size);
2595 meshlink_set_channel_sndbuf_storage(mesh, channel, NULL, size);
2598 void meshlink_set_channel_rcvbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
2599 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_rcvbuf(%p, %zu)", (void *)channel, size);
2601 meshlink_set_channel_rcvbuf_storage(mesh, channel, NULL, size);
2604 void meshlink_set_channel_sndbuf_storage(meshlink_handle_t *mesh, meshlink_channel_t *channel, void *buf, size_t size) {
2605 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_sndbuf_storage(%p, %p, %zu)", (void *)channel, buf, size);
2607 if(!mesh || !channel) {
2608 meshlink_errno = MESHLINK_EINVAL;
2612 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2616 utcp_set_sndbuf(channel->c, buf, size);
2617 pthread_mutex_unlock(&mesh->mutex);
2620 void meshlink_set_channel_rcvbuf_storage(meshlink_handle_t *mesh, meshlink_channel_t *channel, void *buf, size_t size) {
2621 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_rcvbuf_storage(%p, %p, %zu)", (void *)channel, buf, size);
2623 if(!mesh || !channel) {
2624 meshlink_errno = MESHLINK_EINVAL;
2628 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2632 utcp_set_rcvbuf(channel->c, buf, size);
2633 pthread_mutex_unlock(&mesh->mutex);
2636 void meshlink_set_channel_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel, uint32_t flags) {
2637 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_flags(%p, %u)", (void *)channel, flags);
2639 if(!mesh || !channel) {
2640 meshlink_errno = MESHLINK_EINVAL;
2644 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2648 utcp_set_flags(channel->c, flags);
2649 pthread_mutex_unlock(&mesh->mutex);
2652 meshlink_channel_t *meshlink_channel_open_ex(meshlink_handle_t *mesh, meshlink_node_t *node, uint16_t port, meshlink_channel_receive_cb_t cb, const void *data, size_t len, uint32_t flags) {
2653 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_open_ex(%s, %u, %p, %p, %zu, %u)", node ? node->name : "(null)", port, (void *)(intptr_t)cb, data, len, flags);
2656 abort(); // TODO: handle non-NULL data
2659 if(!mesh || !node) {
2660 meshlink_errno = MESHLINK_EINVAL;
2664 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2668 node_t *n = (node_t *)node;
2671 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2672 mesh->receive_cb = channel_receive;
2675 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2676 pthread_mutex_unlock(&mesh->mutex);
2681 if(n->status.blacklisted) {
2682 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
2683 meshlink_errno = MESHLINK_EBLACKLISTED;
2684 pthread_mutex_unlock(&mesh->mutex);
2688 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2690 channel->receive_cb = cb;
2693 channel->priv = (void *)data;
2696 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2698 pthread_mutex_unlock(&mesh->mutex);
2701 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2709 meshlink_channel_t *meshlink_channel_open(meshlink_handle_t *mesh, meshlink_node_t *node, uint16_t port, meshlink_channel_receive_cb_t cb, const void *data, size_t len) {
2710 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_open_ex(%s, %u, %p, %p, %zu)", node ? node->name : "(null)", port, (void *)(intptr_t)cb, data, len);
2712 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2715 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2716 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_shutdown(%p, %d)", (void *)channel, direction);
2718 if(!mesh || !channel) {
2719 meshlink_errno = MESHLINK_EINVAL;
2723 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2727 utcp_shutdown(channel->c, direction);
2728 pthread_mutex_unlock(&mesh->mutex);
2731 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2732 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_close(%p)", (void *)channel);
2734 if(!mesh || !channel) {
2735 meshlink_errno = MESHLINK_EINVAL;
2739 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2744 utcp_close(channel->c);
2747 /* Clean up any outstanding AIO buffers. */
2748 aio_abort(mesh, channel, &channel->aio_send);
2749 aio_abort(mesh, channel, &channel->aio_receive);
2752 if(!channel->in_callback) {
2756 pthread_mutex_unlock(&mesh->mutex);
2759 void meshlink_channel_abort(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2760 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_abort(%p)", (void *)channel);
2762 if(!mesh || !channel) {
2763 meshlink_errno = MESHLINK_EINVAL;
2767 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2772 utcp_abort(channel->c);
2775 /* Clean up any outstanding AIO buffers. */
2776 aio_abort(mesh, channel, &channel->aio_send);
2777 aio_abort(mesh, channel, &channel->aio_receive);
2780 if(!channel->in_callback) {
2784 pthread_mutex_unlock(&mesh->mutex);
2787 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2788 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_send(%p, %p, %zu)", (void *)channel, data, len);
2790 if(!mesh || !channel) {
2791 meshlink_errno = MESHLINK_EINVAL;
2800 meshlink_errno = MESHLINK_EINVAL;
2804 // TODO: more finegrained locking.
2805 // Ideally we want to put the data into the UTCP connection's send buffer.
2806 // Then, preferably only if there is room in the receiver window,
2807 // kick the meshlink thread to go send packets.
2811 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2815 /* Disallow direct calls to utcp_send() while we still have AIO active. */
2816 if(channel->aio_send) {
2819 retval = utcp_send(channel->c, data, len);
2822 pthread_mutex_unlock(&mesh->mutex);
2825 meshlink_errno = MESHLINK_ENETWORK;
2831 bool meshlink_channel_aio_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len, meshlink_aio_cb_t cb, void *priv) {
2832 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_send(%p, %p, %zu, %p, %p)", (void *)channel, data, len, (void *)(intptr_t)cb, priv);
2834 if(!mesh || !channel) {
2835 meshlink_errno = MESHLINK_EINVAL;
2840 meshlink_errno = MESHLINK_EINVAL;
2844 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
2847 aio->cb.buffer = cb;
2850 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2854 /* Append the AIO buffer descriptor to the end of the chain */
2855 meshlink_aio_buffer_t **p = &channel->aio_send;
2863 /* Ensure the poll callback is set, and call it right now to push data if possible */
2864 utcp_set_poll_cb(channel->c, channel_poll);
2865 size_t todo = MIN(len, utcp_get_rcvbuf_free(channel->c));
2868 channel_poll(channel->c, todo);
2871 pthread_mutex_unlock(&mesh->mutex);
2876 bool meshlink_channel_aio_fd_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, int fd, size_t len, meshlink_aio_fd_cb_t cb, void *priv) {
2877 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_fd_send(%p, %d, %zu, %p, %p)", (void *)channel, fd, len, (void *)(intptr_t)cb, priv);
2879 if(!mesh || !channel) {
2880 meshlink_errno = MESHLINK_EINVAL;
2884 if(!len || fd == -1) {
2885 meshlink_errno = MESHLINK_EINVAL;
2889 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
2895 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2899 /* Append the AIO buffer descriptor to the end of the chain */
2900 meshlink_aio_buffer_t **p = &channel->aio_send;
2908 /* Ensure the poll callback is set, and call it right now to push data if possible */
2909 utcp_set_poll_cb(channel->c, channel_poll);
2910 size_t left = utcp_get_rcvbuf_free(channel->c);
2913 channel_poll(channel->c, left);
2916 pthread_mutex_unlock(&mesh->mutex);
2921 bool meshlink_channel_aio_receive(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len, meshlink_aio_cb_t cb, void *priv) {
2922 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_receive(%p, %p, %zu, %p, %p)", (void *)channel, data, len, (void *)(intptr_t)cb, priv);
2924 if(!mesh || !channel) {
2925 meshlink_errno = MESHLINK_EINVAL;
2930 meshlink_errno = MESHLINK_EINVAL;
2934 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
2937 aio->cb.buffer = cb;
2940 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2944 /* Append the AIO buffer descriptor to the end of the chain */
2945 meshlink_aio_buffer_t **p = &channel->aio_receive;
2953 pthread_mutex_unlock(&mesh->mutex);
2958 bool meshlink_channel_aio_fd_receive(meshlink_handle_t *mesh, meshlink_channel_t *channel, int fd, size_t len, meshlink_aio_fd_cb_t cb, void *priv) {
2959 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_fd_receive(%p, %d, %zu, %p, %p)", (void *)channel, fd, len, (void *)(intptr_t)cb, priv);
2961 if(!mesh || !channel) {
2962 meshlink_errno = MESHLINK_EINVAL;
2966 if(!len || fd == -1) {
2967 meshlink_errno = MESHLINK_EINVAL;
2971 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
2977 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2981 /* Append the AIO buffer descriptor to the end of the chain */
2982 meshlink_aio_buffer_t **p = &channel->aio_receive;
2990 pthread_mutex_unlock(&mesh->mutex);
2995 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2996 if(!mesh || !channel) {
2997 meshlink_errno = MESHLINK_EINVAL;
3001 return channel->c->flags;
3004 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3005 if(!mesh || !channel) {
3006 meshlink_errno = MESHLINK_EINVAL;
3010 return utcp_get_sendq(channel->c);
3013 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3014 if(!mesh || !channel) {
3015 meshlink_errno = MESHLINK_EINVAL;
3019 return utcp_get_recvq(channel->c);
3022 size_t meshlink_channel_get_mss(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3023 if(!mesh || !channel) {
3024 meshlink_errno = MESHLINK_EINVAL;
3028 return utcp_get_mss(channel->node->utcp);
3031 void meshlink_set_node_channel_timeout(meshlink_handle_t *mesh, meshlink_node_t *node, int timeout) {
3032 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_channel_timeout(%s, %d)", node ? node->name : "(null)", timeout);
3034 if(!mesh || !node) {
3035 meshlink_errno = MESHLINK_EINVAL;
3039 node_t *n = (node_t *)node;
3041 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3046 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3049 utcp_set_user_timeout(n->utcp, timeout);
3051 pthread_mutex_unlock(&mesh->mutex);
3054 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
3055 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
3056 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3059 if(mesh->node_status_cb) {
3060 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
3064 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
3065 if(!mesh->node_duplicate_cb || n->status.duplicate) {
3069 n->status.duplicate = true;
3070 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
3073 void meshlink_hint_network_change(struct meshlink_handle *mesh) {
3074 logger(mesh, MESHLINK_DEBUG, "meshlink_hint_network_change()");
3077 meshlink_errno = MESHLINK_EINVAL;
3081 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3085 pthread_mutex_unlock(&mesh->mutex);
3088 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
3089 logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_timeouts(%d, %d, %d)", devclass, pinginterval, pingtimeout);
3091 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3092 meshlink_errno = EINVAL;
3096 if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
3097 meshlink_errno = EINVAL;
3101 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3105 mesh->dev_class_traits[devclass].pinginterval = pinginterval;
3106 mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
3107 pthread_mutex_unlock(&mesh->mutex);
3110 void meshlink_set_dev_class_fast_retry_period(meshlink_handle_t *mesh, dev_class_t devclass, int fast_retry_period) {
3111 logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_fast_retry_period(%d, %d)", devclass, fast_retry_period);
3113 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3114 meshlink_errno = EINVAL;
3118 if(fast_retry_period < 0) {
3119 meshlink_errno = EINVAL;
3123 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3127 mesh->dev_class_traits[devclass].fast_retry_period = fast_retry_period;
3128 pthread_mutex_unlock(&mesh->mutex);
3131 void meshlink_set_dev_class_maxtimeout(struct meshlink_handle *mesh, dev_class_t devclass, int maxtimeout) {
3132 logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_fast_maxtimeout(%d, %d)", devclass, maxtimeout);
3134 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3135 meshlink_errno = EINVAL;
3139 if(maxtimeout < 0) {
3140 meshlink_errno = EINVAL;
3144 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3148 mesh->dev_class_traits[devclass].maxtimeout = maxtimeout;
3149 pthread_mutex_unlock(&mesh->mutex);
3152 void meshlink_reset_timers(struct meshlink_handle *mesh) {
3153 logger(mesh, MESHLINK_DEBUG, "meshlink_reset_timers()");
3159 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3163 handle_network_change(mesh, true);
3165 pthread_mutex_unlock(&mesh->mutex);
3168 void meshlink_set_inviter_commits_first(struct meshlink_handle *mesh, bool inviter_commits_first) {
3169 logger(mesh, MESHLINK_DEBUG, "meshlink_set_inviter_commits_first(%d)", inviter_commits_first);
3172 meshlink_errno = EINVAL;
3176 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3180 mesh->inviter_commits_first = inviter_commits_first;
3181 pthread_mutex_unlock(&mesh->mutex);
3184 void meshlink_set_scheduling_granularity(struct meshlink_handle *mesh, long granularity) {
3185 logger(mesh, MESHLINK_DEBUG, "meshlink_set_scheduling_granularity(%ld)", granularity);
3187 if(!mesh || granularity < 0) {
3188 meshlink_errno = EINVAL;
3192 utcp_set_clock_granularity(granularity);
3195 void meshlink_set_storage_policy(struct meshlink_handle *mesh, meshlink_storage_policy_t policy) {
3196 logger(mesh, MESHLINK_DEBUG, "meshlink_set_storage_policy(%d)", policy);
3199 meshlink_errno = EINVAL;
3203 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3207 mesh->storage_policy = policy;
3208 pthread_mutex_unlock(&mesh->mutex);
3211 void handle_network_change(meshlink_handle_t *mesh, bool online) {
3214 if(!mesh->loop.running) {
3219 signal_trigger(&mesh->loop, &mesh->datafromapp);
3222 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t cb_errno) {
3223 // We should only call the callback function if we are in the background thread.
3224 if(!mesh->error_cb) {
3228 if(!mesh->threadstarted) {
3232 if(mesh->thread == pthread_self()) {
3233 mesh->error_cb(mesh, cb_errno);
3237 static void __attribute__((constructor)) meshlink_init(void) {
3239 utcp_set_clock_granularity(10000);
3242 static void __attribute__((destructor)) meshlink_exit(void) {