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 bool timespec_lt(const struct timespec *a, const struct timespec *b) {
492 if(a->tv_sec == b->tv_sec) {
493 return a->tv_nsec < b->tv_nsec;
495 return a->tv_sec < b->tv_sec;
499 static struct timespec idle(event_loop_t *loop, void *data) {
501 meshlink_handle_t *mesh = data;
502 struct timespec t, tmin = {3600, 0};
504 for splay_each(node_t, n, mesh->nodes) {
509 t = utcp_timeout(n->utcp);
511 if(timespec_lt(&t, &tmin)) {
519 static bool meshlink_setup(meshlink_handle_t *mesh) {
520 if(!config_destroy(mesh->confbase, "new")) {
521 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/new: %s\n", mesh->confbase, strerror(errno));
522 meshlink_errno = MESHLINK_ESTORAGE;
526 if(!config_destroy(mesh->confbase, "old")) {
527 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
528 meshlink_errno = MESHLINK_ESTORAGE;
532 if(!config_init(mesh, "current")) {
533 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
534 meshlink_errno = MESHLINK_ESTORAGE;
538 if(!ecdsa_keygen(mesh)) {
539 meshlink_errno = MESHLINK_EINTERNAL;
543 mesh->myport = xstrdup("0");
545 /* Create a node for ourself */
547 mesh->self = new_node();
548 mesh->self->name = xstrdup(mesh->name);
549 mesh->self->devclass = mesh->devclass;
550 mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
551 mesh->self->session_id = mesh->session_id;
553 if(!write_main_config_files(mesh)) {
554 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
555 meshlink_errno = MESHLINK_ESTORAGE;
559 /* Ensure the configuration directory metadata is on disk */
560 if(!config_sync(mesh, "current")) {
567 static bool meshlink_read_config(meshlink_handle_t *mesh) {
570 if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
571 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
575 packmsg_input_t in = {config.buf, config.len};
576 const void *private_key;
578 uint32_t version = packmsg_get_uint32(&in);
579 char *name = packmsg_get_str_dup(&in);
580 uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
581 packmsg_skip_element(&in); // Invitation key is not supported
582 uint16_t myport = packmsg_get_uint16(&in);
584 if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96) {
585 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
587 config_free(&config);
591 if(mesh->name && strcmp(mesh->name, name)) {
592 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
593 meshlink_errno = MESHLINK_ESTORAGE;
595 config_free(&config);
601 xasprintf(&mesh->myport, "%u", myport);
602 mesh->private_key = ecdsa_set_private_key(private_key);
603 config_free(&config);
605 /* Create a node for ourself and read our host configuration file */
607 mesh->self = new_node();
608 mesh->self->name = xstrdup(name);
609 mesh->self->devclass = mesh->devclass;
610 mesh->self->session_id = mesh->session_id;
612 if(!node_read_public_key(mesh, mesh->self)) {
613 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
614 meshlink_errno = MESHLINK_ESTORAGE;
615 free_node(mesh->self);
624 static void *setup_network_in_netns_thread(void *arg) {
625 meshlink_handle_t *mesh = arg;
627 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
631 bool success = setup_network(mesh);
632 return success ? arg : NULL;
636 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
637 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_init(%s, %s, %s, %d)", confbase, name, appname, devclass);
639 if(!confbase || !*confbase) {
640 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
641 meshlink_errno = MESHLINK_EINVAL;
645 if(!appname || !*appname) {
646 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
647 meshlink_errno = MESHLINK_EINVAL;
651 if(strchr(appname, ' ')) {
652 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
653 meshlink_errno = MESHLINK_EINVAL;
657 if(name && !check_id(name)) {
658 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
659 meshlink_errno = MESHLINK_EINVAL;
663 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
664 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
665 meshlink_errno = MESHLINK_EINVAL;
669 meshlink_open_params_t *params = xzalloc(sizeof * params);
671 params->confbase = xstrdup(confbase);
672 params->name = name ? xstrdup(name) : NULL;
673 params->appname = xstrdup(appname);
674 params->devclass = devclass;
677 xasprintf(¶ms->lock_filename, "%s" SLASH "meshlink.lock", confbase);
682 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
683 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_netnst(%d)", netns);
686 meshlink_errno = MESHLINK_EINVAL;
690 params->netns = netns;
695 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
696 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_key(%p, %zu)", key, keylen);
699 meshlink_errno = MESHLINK_EINVAL;
703 if((!key && keylen) || (key && !keylen)) {
704 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
705 meshlink_errno = MESHLINK_EINVAL;
710 params->keylen = keylen;
715 bool meshlink_open_params_set_storage_policy(meshlink_open_params_t *params, meshlink_storage_policy_t policy) {
716 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_policy(%d)", policy);
719 meshlink_errno = MESHLINK_EINVAL;
723 params->storage_policy = policy;
728 bool meshlink_open_params_set_lock_filename(meshlink_open_params_t *params, const char *filename) {
729 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_lock_filename(%s)", filename);
731 if(!params || !filename) {
732 meshlink_errno = MESHLINK_EINVAL;
736 free(params->lock_filename);
737 params->lock_filename = xstrdup(filename);
742 bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
743 logger(NULL, MESHLINK_DEBUG, "meshlink_encrypted_key_rotate(%p, %zu)", new_key, new_keylen);
745 if(!mesh || !new_key || !new_keylen) {
746 logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
747 meshlink_errno = MESHLINK_EINVAL;
751 if(pthread_mutex_lock(&mesh->mutex) != 0) {
755 // Create hash for the new key
756 void *new_config_key;
757 new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
759 if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
760 logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
761 meshlink_errno = MESHLINK_EINTERNAL;
762 pthread_mutex_unlock(&mesh->mutex);
766 // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
768 if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
769 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
770 meshlink_errno = MESHLINK_ESTORAGE;
771 pthread_mutex_unlock(&mesh->mutex);
775 devtool_keyrotate_probe(1);
777 // Rename confbase/current/ to confbase/old
779 if(!config_rename(mesh, "current", "old")) {
780 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
781 meshlink_errno = MESHLINK_ESTORAGE;
782 pthread_mutex_unlock(&mesh->mutex);
786 devtool_keyrotate_probe(2);
788 // Rename confbase/new/ to confbase/current
790 if(!config_rename(mesh, "new", "current")) {
791 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
792 meshlink_errno = MESHLINK_ESTORAGE;
793 pthread_mutex_unlock(&mesh->mutex);
797 devtool_keyrotate_probe(3);
799 // Cleanup the "old" confbase sub-directory
801 if(!config_destroy(mesh->confbase, "old")) {
802 pthread_mutex_unlock(&mesh->mutex);
806 // Change the mesh handle key with new key
808 free(mesh->config_key);
809 mesh->config_key = new_config_key;
811 pthread_mutex_unlock(&mesh->mutex);
816 void meshlink_open_params_free(meshlink_open_params_t *params) {
817 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_free()");
820 meshlink_errno = MESHLINK_EINVAL;
824 free(params->confbase);
826 free(params->appname);
827 free(params->lock_filename);
832 /// Device class traits
833 static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
834 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
835 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
836 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
837 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN
840 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
841 logger(NULL, MESHLINK_DEBUG, "meshlink_open(%s, %s, %s, %d)", confbase, name, appname, devclass);
843 if(!confbase || !*confbase) {
844 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
845 meshlink_errno = MESHLINK_EINVAL;
849 char lock_filename[PATH_MAX];
850 snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
852 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
853 meshlink_open_params_t params = {
854 .confbase = (char *)confbase,
855 .lock_filename = lock_filename,
856 .name = (char *)name,
857 .appname = (char *)appname,
858 .devclass = devclass,
862 return meshlink_open_ex(¶ms);
865 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) {
866 logger(NULL, MESHLINK_DEBUG, "meshlink_open_encrypted(%s, %s, %s, %d, %p, %zu)", confbase, name, appname, devclass, key, keylen);
868 if(!confbase || !*confbase) {
869 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
870 meshlink_errno = MESHLINK_EINVAL;
874 char lock_filename[PATH_MAX];
875 snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
877 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
878 meshlink_open_params_t params = {
879 .confbase = (char *)confbase,
880 .lock_filename = lock_filename,
881 .name = (char *)name,
882 .appname = (char *)appname,
883 .devclass = devclass,
887 if(!meshlink_open_params_set_storage_key(¶ms, key, keylen)) {
891 return meshlink_open_ex(¶ms);
894 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
895 logger(NULL, MESHLINK_DEBUG, "meshlink_open_ephemeral(%s, %s, %d)", name, appname, devclass);
898 logger(NULL, MESHLINK_ERROR, "No name given!\n");
899 meshlink_errno = MESHLINK_EINVAL;
903 if(!check_id(name)) {
904 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
905 meshlink_errno = MESHLINK_EINVAL;
909 if(!appname || !*appname) {
910 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
911 meshlink_errno = MESHLINK_EINVAL;
915 if(strchr(appname, ' ')) {
916 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
917 meshlink_errno = MESHLINK_EINVAL;
921 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
922 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
923 meshlink_errno = MESHLINK_EINVAL;
927 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
928 meshlink_open_params_t params = {
929 .name = (char *)name,
930 .appname = (char *)appname,
931 .devclass = devclass,
935 return meshlink_open_ex(¶ms);
938 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
939 logger(NULL, MESHLINK_DEBUG, "meshlink_open_ex()");
941 // Validate arguments provided by the application
942 if(!params->appname || !*params->appname) {
943 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
944 meshlink_errno = MESHLINK_EINVAL;
948 if(strchr(params->appname, ' ')) {
949 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
950 meshlink_errno = MESHLINK_EINVAL;
954 if(params->name && !check_id(params->name)) {
955 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
956 meshlink_errno = MESHLINK_EINVAL;
960 if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
961 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
962 meshlink_errno = MESHLINK_EINVAL;
966 if((params->key && !params->keylen) || (!params->key && params->keylen)) {
967 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
968 meshlink_errno = MESHLINK_EINVAL;
972 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
974 if(params->confbase) {
975 mesh->confbase = xstrdup(params->confbase);
978 mesh->appname = xstrdup(params->appname);
979 mesh->devclass = params->devclass;
980 mesh->netns = params->netns;
981 mesh->log_cb = global_log_cb;
982 mesh->log_level = global_log_level;
983 mesh->packet = xmalloc(sizeof(vpn_packet_t));
985 randomize(&mesh->prng_state, sizeof(mesh->prng_state));
988 randomize(&mesh->session_id, sizeof(mesh->session_id));
989 } while(mesh->session_id == 0);
991 memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
993 mesh->name = params->name ? xstrdup(params->name) : NULL;
997 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
999 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
1000 logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
1001 meshlink_close(mesh);
1002 meshlink_errno = MESHLINK_EINTERNAL;
1007 // initialize mutexes and conds
1008 pthread_mutexattr_t attr;
1009 pthread_mutexattr_init(&attr);
1011 if(pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) != 0) {
1015 pthread_mutex_init(&mesh->mutex, &attr);
1016 pthread_cond_init(&mesh->cond, NULL);
1018 mesh->threadstarted = false;
1019 event_loop_init(&mesh->loop);
1020 mesh->loop.data = mesh;
1022 meshlink_queue_init(&mesh->outpacketqueue);
1024 // Atomically lock the configuration directory.
1025 if(!main_config_lock(mesh, params->lock_filename)) {
1026 meshlink_close(mesh);
1030 // If no configuration exists yet, create it.
1032 bool new_configuration = false;
1034 if(!meshlink_confbase_exists(mesh)) {
1036 logger(NULL, MESHLINK_ERROR, "No configuration files found!\n");
1037 meshlink_close(mesh);
1038 meshlink_errno = MESHLINK_ESTORAGE;
1042 if(!meshlink_setup(mesh)) {
1043 logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1044 meshlink_close(mesh);
1048 new_configuration = true;
1050 if(!meshlink_read_config(mesh)) {
1051 logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1052 meshlink_close(mesh);
1057 mesh->storage_policy = params->storage_policy;
1060 struct WSAData wsa_state;
1061 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1064 // Setup up everything
1065 // TODO: we should not open listening sockets yet
1067 bool success = false;
1069 if(mesh->netns != -1) {
1073 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1074 void *retval = NULL;
1075 success = pthread_join(thr, &retval) == 0 && retval;
1079 meshlink_errno = MESHLINK_EINTERNAL;
1082 #endif // HAVE_SETNS
1084 success = setup_network(mesh);
1088 meshlink_close(mesh);
1089 meshlink_errno = MESHLINK_ENETWORK;
1093 if(!node_write_config(mesh, mesh->self, new_configuration)) {
1094 logger(NULL, MESHLINK_ERROR, "Cannot update configuration\n");
1098 idle_set(&mesh->loop, idle, mesh);
1100 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1104 static void *meshlink_main_loop(void *arg) {
1105 meshlink_handle_t *mesh = arg;
1107 if(mesh->netns != -1) {
1110 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1111 pthread_cond_signal(&mesh->cond);
1116 pthread_cond_signal(&mesh->cond);
1118 #endif // HAVE_SETNS
1121 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1125 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1126 pthread_cond_broadcast(&mesh->cond);
1128 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1130 pthread_mutex_unlock(&mesh->mutex);
1135 bool meshlink_start(meshlink_handle_t *mesh) {
1137 meshlink_errno = MESHLINK_EINVAL;
1141 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1143 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1148 assert(mesh->private_key);
1149 assert(mesh->self->ecdsa);
1150 assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1152 if(mesh->threadstarted) {
1153 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1154 pthread_mutex_unlock(&mesh->mutex);
1158 // Reset node connection timers
1159 for splay_each(node_t, n, mesh->nodes) {
1160 n->last_connect_try = 0;
1164 //Check that a valid name is set
1166 logger(mesh, MESHLINK_ERROR, "No name given!\n");
1167 meshlink_errno = MESHLINK_EINVAL;
1168 pthread_mutex_unlock(&mesh->mutex);
1172 init_outgoings(mesh);
1174 // Start the main thread
1176 event_loop_start(&mesh->loop);
1178 // Ensure we have a decent amount of stack space. Musl's default of 80 kB is too small.
1179 pthread_attr_t attr;
1180 pthread_attr_init(&attr);
1181 pthread_attr_setstacksize(&attr, 1024 * 1024);
1183 if(pthread_create(&mesh->thread, &attr, meshlink_main_loop, mesh) != 0) {
1184 logger(mesh, MESHLINK_ERROR, "Could not start thread: %s\n", strerror(errno));
1185 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1186 meshlink_errno = MESHLINK_EINTERNAL;
1187 event_loop_stop(&mesh->loop);
1188 pthread_mutex_unlock(&mesh->mutex);
1192 pthread_cond_wait(&mesh->cond, &mesh->mutex);
1193 mesh->threadstarted = true;
1195 pthread_mutex_unlock(&mesh->mutex);
1199 void meshlink_stop(meshlink_handle_t *mesh) {
1200 logger(mesh, MESHLINK_DEBUG, "meshlink_stop()\n");
1203 meshlink_errno = MESHLINK_EINVAL;
1207 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1211 // Shut down the main thread
1212 event_loop_stop(&mesh->loop);
1214 // TODO: send something to a local socket to kick the event loop
1216 if(mesh->threadstarted) {
1217 // Wait for the main thread to finish
1218 pthread_mutex_unlock(&mesh->mutex);
1220 if(pthread_join(mesh->thread, NULL) != 0) {
1224 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1228 mesh->threadstarted = false;
1231 // Close all metaconnections
1232 if(mesh->connections) {
1233 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1235 connection_t *c = node->data;
1237 terminate_connection(mesh, c, false);
1241 exit_outgoings(mesh);
1243 // Try to write out any changed node config files, ignore errors at this point.
1245 for splay_each(node_t, n, mesh->nodes) {
1246 if(n->status.dirty) {
1247 if(!node_write_config(mesh, n, false)) {
1254 pthread_mutex_unlock(&mesh->mutex);
1257 void meshlink_close(meshlink_handle_t *mesh) {
1258 logger(mesh, MESHLINK_DEBUG, "meshlink_close()\n");
1261 meshlink_errno = MESHLINK_EINVAL;
1265 // stop can be called even if mesh has not been started
1266 meshlink_stop(mesh);
1268 // lock is not released after this
1269 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1273 // Close and free all resources used.
1275 close_network_connections(mesh);
1277 logger(mesh, MESHLINK_INFO, "Terminating");
1279 event_loop_exit(&mesh->loop);
1283 if(mesh->confbase) {
1289 if(mesh->netns != -1) {
1293 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1297 meshlink_queue_exit(&mesh->outpacketqueue);
1300 free(mesh->appname);
1301 free(mesh->confbase);
1302 free(mesh->config_key);
1303 free(mesh->external_address_url);
1305 ecdsa_free(mesh->private_key);
1307 main_config_unlock(mesh);
1309 pthread_mutex_unlock(&mesh->mutex);
1310 pthread_mutex_destroy(&mesh->mutex);
1312 memset(mesh, 0, sizeof(*mesh));
1317 bool meshlink_destroy_ex(const meshlink_open_params_t *params) {
1318 logger(NULL, MESHLINK_DEBUG, "meshlink_destroy_ex()\n");
1321 meshlink_errno = MESHLINK_EINVAL;
1325 if(!params->confbase) {
1326 /* Ephemeral instances */
1330 /* Exit early if the confbase directory itself doesn't exist */
1331 if(access(params->confbase, F_OK) && errno == ENOENT) {
1335 /* Take the lock the same way meshlink_open() would. */
1336 FILE *lockfile = fopen(params->lock_filename, "w+");
1339 logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", params->lock_filename, strerror(errno));
1340 meshlink_errno = MESHLINK_ESTORAGE;
1345 fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
1349 // TODO: use _locking()?
1352 if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
1353 logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", params->lock_filename);
1355 meshlink_errno = MESHLINK_EBUSY;
1361 if(!config_destroy(params->confbase, "current") || !config_destroy(params->confbase, "new") || !config_destroy(params->confbase, "old")) {
1362 logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", params->confbase, strerror(errno));
1366 if(unlink(params->lock_filename)) {
1367 logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", params->lock_filename, strerror(errno));
1369 meshlink_errno = MESHLINK_ESTORAGE;
1375 if(!sync_path(params->confbase)) {
1376 logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", params->confbase, strerror(errno));
1377 meshlink_errno = MESHLINK_ESTORAGE;
1384 bool meshlink_destroy(const char *confbase) {
1385 logger(NULL, MESHLINK_DEBUG, "meshlink_destroy(%s)", confbase);
1387 char lock_filename[PATH_MAX];
1388 snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
1390 meshlink_open_params_t params = {
1391 .confbase = (char *)confbase,
1392 .lock_filename = lock_filename,
1395 return meshlink_destroy_ex(¶ms);
1398 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1399 logger(mesh, MESHLINK_DEBUG, "meshlink_set_receive_cb(%p)", (void *)(intptr_t)cb);
1402 meshlink_errno = MESHLINK_EINVAL;
1406 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1410 mesh->receive_cb = cb;
1411 pthread_mutex_unlock(&mesh->mutex);
1414 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1415 logger(mesh, MESHLINK_DEBUG, "meshlink_set_connection_try_cb(%p)", (void *)(intptr_t)cb);
1418 meshlink_errno = MESHLINK_EINVAL;
1422 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1426 mesh->connection_try_cb = cb;
1427 pthread_mutex_unlock(&mesh->mutex);
1430 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1431 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_status_cb(%p)", (void *)(intptr_t)cb);
1434 meshlink_errno = MESHLINK_EINVAL;
1438 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1442 mesh->node_status_cb = cb;
1443 pthread_mutex_unlock(&mesh->mutex);
1446 void meshlink_set_node_pmtu_cb(meshlink_handle_t *mesh, meshlink_node_pmtu_cb_t cb) {
1447 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_pmtu_cb(%p)", (void *)(intptr_t)cb);
1450 meshlink_errno = MESHLINK_EINVAL;
1454 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1458 mesh->node_pmtu_cb = cb;
1459 pthread_mutex_unlock(&mesh->mutex);
1462 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1463 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_duplicate_cb(%p)", (void *)(intptr_t)cb);
1466 meshlink_errno = MESHLINK_EINVAL;
1470 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1474 mesh->node_duplicate_cb = cb;
1475 pthread_mutex_unlock(&mesh->mutex);
1478 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1479 logger(mesh, MESHLINK_DEBUG, "meshlink_set_log_cb(%p)", (void *)(intptr_t)cb);
1482 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1487 mesh->log_level = cb ? level : 0;
1488 pthread_mutex_unlock(&mesh->mutex);
1491 global_log_level = cb ? level : 0;
1495 void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
1496 logger(mesh, MESHLINK_DEBUG, "meshlink_set_error_cb(%p)", (void *)(intptr_t)cb);
1499 meshlink_errno = MESHLINK_EINVAL;
1503 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1507 mesh->error_cb = cb;
1508 pthread_mutex_unlock(&mesh->mutex);
1511 static bool prepare_packet(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len, vpn_packet_t *packet) {
1512 meshlink_packethdr_t *hdr;
1514 if(len > MAXSIZE - sizeof(*hdr)) {
1515 meshlink_errno = MESHLINK_EINVAL;
1519 node_t *n = (node_t *)destination;
1521 if(n->status.blacklisted) {
1522 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1523 meshlink_errno = MESHLINK_EBLACKLISTED;
1527 // Prepare the packet
1528 packet->probe = false;
1529 packet->tcp = false;
1530 packet->len = len + sizeof(*hdr);
1532 hdr = (meshlink_packethdr_t *)packet->data;
1533 memset(hdr, 0, sizeof(*hdr));
1534 // leave the last byte as 0 to make sure strings are always
1535 // null-terminated if they are longer than the buffer
1536 strncpy((char *)hdr->destination, destination->name, sizeof(hdr->destination) - 1);
1537 strncpy((char *)hdr->source, mesh->self->name, sizeof(hdr->source) - 1);
1539 memcpy(packet->data + sizeof(*hdr), data, len);
1544 static bool meshlink_send_immediate(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1546 assert(destination);
1550 // Prepare the packet
1551 if(!prepare_packet(mesh, destination, data, len, mesh->packet)) {
1555 // Send it immediately
1556 route(mesh, mesh->self, mesh->packet);
1561 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1562 logger(mesh, MESHLINK_DEBUG, "meshlink_send(%s, %p, %zu)", destination ? destination->name : "(null)", data, len);
1564 // Validate arguments
1565 if(!mesh || !destination) {
1566 meshlink_errno = MESHLINK_EINVAL;
1575 meshlink_errno = MESHLINK_EINVAL;
1579 // Prepare the packet
1580 vpn_packet_t *packet = malloc(sizeof(*packet));
1583 meshlink_errno = MESHLINK_ENOMEM;
1587 if(!prepare_packet(mesh, destination, data, len, packet)) {
1593 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1595 meshlink_errno = MESHLINK_ENOMEM;
1599 logger(mesh, MESHLINK_DEBUG, "Adding packet of %zu bytes to packet queue", len);
1601 // Notify event loop
1602 signal_trigger(&mesh->loop, &mesh->datafromapp);
1607 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
1609 meshlink_handle_t *mesh = data;
1611 logger(mesh, MESHLINK_DEBUG, "Flushing the packet queue");
1613 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1614 logger(mesh, MESHLINK_DEBUG, "Removing packet of %d bytes from packet queue", packet->len);
1615 mesh->self->in_packets++;
1616 mesh->self->in_bytes += packet->len;
1617 route(mesh, mesh->self, packet);
1622 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1623 if(!mesh || !destination) {
1624 meshlink_errno = MESHLINK_EINVAL;
1628 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1632 node_t *n = (node_t *)destination;
1634 if(!n->status.reachable) {
1635 pthread_mutex_unlock(&mesh->mutex);
1638 } else if(n->mtuprobes > 30 && n->minmtu) {
1639 pthread_mutex_unlock(&mesh->mutex);
1642 pthread_mutex_unlock(&mesh->mutex);
1647 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1648 if(!mesh || !node) {
1649 meshlink_errno = MESHLINK_EINVAL;
1653 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1657 node_t *n = (node_t *)node;
1659 if(!node_read_public_key(mesh, n) || !n->ecdsa) {
1660 meshlink_errno = MESHLINK_EINTERNAL;
1661 pthread_mutex_unlock(&mesh->mutex);
1665 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1668 meshlink_errno = MESHLINK_EINTERNAL;
1671 pthread_mutex_unlock(&mesh->mutex);
1675 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1677 meshlink_errno = MESHLINK_EINVAL;
1681 return (meshlink_node_t *)mesh->self;
1684 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1685 if(!mesh || !name) {
1686 meshlink_errno = MESHLINK_EINVAL;
1692 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1696 n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1697 pthread_mutex_unlock(&mesh->mutex);
1700 meshlink_errno = MESHLINK_ENOENT;
1703 return (meshlink_node_t *)n;
1706 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1707 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1708 meshlink_errno = MESHLINK_EINVAL;
1712 meshlink_node_t **result;
1715 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1719 *nmemb = mesh->nodes->count;
1720 result = realloc(nodes, *nmemb * sizeof(*nodes));
1723 meshlink_node_t **p = result;
1725 for splay_each(node_t, n, mesh->nodes) {
1726 *p++ = (meshlink_node_t *)n;
1731 meshlink_errno = MESHLINK_ENOMEM;
1734 pthread_mutex_unlock(&mesh->mutex);
1739 static meshlink_node_t **meshlink_get_all_nodes_by_condition(meshlink_handle_t *mesh, const void *condition, meshlink_node_t **nodes, size_t *nmemb, search_node_by_condition_t search_node) {
1740 meshlink_node_t **result;
1742 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1748 for splay_each(node_t, n, mesh->nodes) {
1749 if(search_node(n, condition)) {
1756 pthread_mutex_unlock(&mesh->mutex);
1760 result = realloc(nodes, *nmemb * sizeof(*nodes));
1763 meshlink_node_t **p = result;
1765 for splay_each(node_t, n, mesh->nodes) {
1766 if(search_node(n, condition)) {
1767 *p++ = (meshlink_node_t *)n;
1773 meshlink_errno = MESHLINK_ENOMEM;
1776 pthread_mutex_unlock(&mesh->mutex);
1781 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
1782 dev_class_t *devclass = (dev_class_t *)condition;
1784 if(*devclass == (dev_class_t)node->devclass) {
1797 meshlink_node_t **meshlink_get_all_nodes_by_dev_class(meshlink_handle_t *mesh, dev_class_t devclass, meshlink_node_t **nodes, size_t *nmemb) {
1798 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT || !nmemb) {
1799 meshlink_errno = MESHLINK_EINVAL;
1803 return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
1806 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
1807 if(!mesh || !node) {
1808 meshlink_errno = MESHLINK_EINVAL;
1812 dev_class_t devclass;
1814 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1818 devclass = ((node_t *)node)->devclass;
1820 pthread_mutex_unlock(&mesh->mutex);
1825 bool meshlink_get_node_reachability(struct meshlink_handle *mesh, struct meshlink_node *node, time_t *last_reachable, time_t *last_unreachable) {
1826 if(!mesh || !node) {
1827 meshlink_errno = MESHLINK_EINVAL;
1831 node_t *n = (node_t *)node;
1834 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1838 reachable = n->status.reachable && !n->status.blacklisted;
1840 // TODO: handle reachable times?
1841 (void)last_reachable;
1842 (void)last_unreachable;
1844 pthread_mutex_unlock(&mesh->mutex);
1849 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1850 logger(mesh, MESHLINK_DEBUG, "meshlink_sign(%p, %zu, %p, %p)", data, len, signature, (void *)siglen);
1852 if(!mesh || !data || !len || !signature || !siglen) {
1853 meshlink_errno = MESHLINK_EINVAL;
1857 if(*siglen < MESHLINK_SIGLEN) {
1858 meshlink_errno = MESHLINK_EINVAL;
1862 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1866 if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
1867 meshlink_errno = MESHLINK_EINTERNAL;
1868 pthread_mutex_unlock(&mesh->mutex);
1872 *siglen = MESHLINK_SIGLEN;
1873 pthread_mutex_unlock(&mesh->mutex);
1877 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1878 logger(mesh, MESHLINK_DEBUG, "meshlink_verify(%p, %zu, %p, %zu)", data, len, signature, siglen);
1880 if(!mesh || !source || !data || !len || !signature) {
1881 meshlink_errno = MESHLINK_EINVAL;
1885 if(siglen != MESHLINK_SIGLEN) {
1886 meshlink_errno = MESHLINK_EINVAL;
1890 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1896 struct node_t *n = (struct node_t *)source;
1898 if(!node_read_public_key(mesh, n)) {
1899 meshlink_errno = MESHLINK_EINTERNAL;
1902 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1905 pthread_mutex_unlock(&mesh->mutex);
1909 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
1910 logger(mesh, MESHLINK_DEBUG, "meshlink_set_canonical_address(%s, %s, %s)", node ? node->name : "(null)", address ? address : "(null)", port ? port : "(null)");
1912 if(!mesh || !node || !address) {
1913 meshlink_errno = MESHLINK_EINVAL;
1917 if(!is_valid_hostname(address)) {
1918 logger(mesh, MESHLINK_ERROR, "Invalid character in address: %s", address);
1919 meshlink_errno = MESHLINK_EINVAL;
1923 if((node_t *)node != mesh->self && !port) {
1924 logger(mesh, MESHLINK_ERROR, "Missing port number!");
1925 meshlink_errno = MESHLINK_EINVAL;
1930 if(port && !is_valid_port(port)) {
1931 logger(mesh, MESHLINK_ERROR, "Invalid character in port: %s", address);
1932 meshlink_errno = MESHLINK_EINVAL;
1936 char *canonical_address;
1938 xasprintf(&canonical_address, "%s %s", address, port ? port : mesh->myport);
1940 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1944 node_t *n = (node_t *)node;
1945 free(n->canonical_address);
1946 n->canonical_address = canonical_address;
1948 if(!node_write_config(mesh, n, false)) {
1949 pthread_mutex_unlock(&mesh->mutex);
1953 pthread_mutex_unlock(&mesh->mutex);
1955 return config_sync(mesh, "current");
1958 bool meshlink_clear_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node) {
1959 logger(mesh, MESHLINK_DEBUG, "meshlink_clear_canonical_address(%s)", node ? node->name : "(null)");
1961 if(!mesh || !node) {
1962 meshlink_errno = MESHLINK_EINVAL;
1966 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1970 node_t *n = (node_t *)node;
1971 free(n->canonical_address);
1972 n->canonical_address = NULL;
1974 if(!node_write_config(mesh, n, false)) {
1975 pthread_mutex_unlock(&mesh->mutex);
1979 pthread_mutex_unlock(&mesh->mutex);
1981 return config_sync(mesh, "current");
1984 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1985 logger(mesh, MESHLINK_DEBUG, "meshlink_join(%s)", invitation ? invitation : "(null)");
1987 if(!mesh || !invitation) {
1988 meshlink_errno = MESHLINK_EINVAL;
1992 if(mesh->storage_policy == MESHLINK_STORAGE_DISABLED) {
1993 meshlink_errno = MESHLINK_EINVAL;
1997 join_state_t state = {
2002 ecdsa_t *key = NULL;
2003 ecdsa_t *hiskey = NULL;
2005 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2006 char copy[strlen(invitation) + 1];
2008 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2012 //Before doing meshlink_join make sure we are not connected to another mesh
2013 if(mesh->threadstarted) {
2014 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
2015 meshlink_errno = MESHLINK_EINVAL;
2019 // 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.
2020 if(mesh->nodes->count > 1) {
2021 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
2022 meshlink_errno = MESHLINK_EINVAL;
2026 strcpy(copy, invitation);
2028 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2030 char *slash = strchr(copy, '/');
2038 if(strlen(slash) != 48) {
2042 char *address = copy;
2045 if(!b64decode(slash, state.hash, 18) || !b64decode(slash + 24, state.cookie, 18)) {
2049 if(mesh->inviter_commits_first) {
2050 memcpy(state.cookie + 18, ecdsa_get_public_key(mesh->private_key), 32);
2053 // Generate a throw-away key for the invitation.
2054 key = ecdsa_generate();
2057 meshlink_errno = MESHLINK_EINTERNAL;
2061 char *b64key = ecdsa_get_base64_public_key(key);
2064 while(address && *address) {
2065 // We allow commas in the address part to support multiple addresses in one invitation URL.
2066 comma = strchr(address, ',');
2072 // Split of the port
2073 port = strrchr(address, ':');
2081 // IPv6 address are enclosed in brackets, per RFC 3986
2082 if(*address == '[') {
2084 char *bracket = strchr(address, ']');
2097 // Connect to the meshlink daemon mentioned in the URL.
2098 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2101 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2102 state.sock = socket_in_netns(aip->ai_family, SOCK_STREAM, IPPROTO_TCP, mesh->netns);
2104 if(state.sock == -1) {
2105 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2106 meshlink_errno = MESHLINK_ENETWORK;
2112 setsockopt(state.sock, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe));
2115 set_timeout(state.sock, 5000);
2117 if(connect(state.sock, aip->ai_addr, aip->ai_addrlen)) {
2118 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2119 meshlink_errno = MESHLINK_ENETWORK;
2120 closesocket(state.sock);
2130 meshlink_errno = MESHLINK_ERESOLV;
2133 if(state.sock != -1 || !comma) {
2140 if(state.sock == -1) {
2144 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2146 // Tell him we have an invitation, and give him our throw-away key.
2150 if(!sendline(state.sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
2151 logger(mesh, MESHLINK_ERROR, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2152 meshlink_errno = MESHLINK_ENETWORK;
2158 char hisname[4096] = "";
2159 int code, hismajor, hisminor = 0;
2161 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) {
2162 logger(mesh, MESHLINK_ERROR, "Cannot read greeting from peer\n");
2163 meshlink_errno = MESHLINK_ENETWORK;
2167 // Check if the hash of the key he gave us matches the hash in the URL.
2168 char *fingerprint = state.line + 2;
2171 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2172 logger(mesh, MESHLINK_ERROR, "Could not create hash\n%s\n", state.line + 2);
2173 meshlink_errno = MESHLINK_EINTERNAL;
2177 if(memcmp(hishash, state.hash, 18)) {
2178 logger(mesh, MESHLINK_ERROR, "Peer has an invalid key!\n%s\n", state.line + 2);
2179 meshlink_errno = MESHLINK_EPEER;
2183 hiskey = ecdsa_set_base64_public_key(fingerprint);
2186 meshlink_errno = MESHLINK_EINTERNAL;
2190 // Start an SPTPS session
2191 if(!sptps_start(&state.sptps, &state, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2192 meshlink_errno = MESHLINK_EINTERNAL;
2196 // Feed rest of input buffer to SPTPS
2197 if(!sptps_receive_data(&state.sptps, state.buffer, state.blen)) {
2198 meshlink_errno = MESHLINK_EPEER;
2203 logger(mesh, MESHLINK_DEBUG, "Starting invitation recv loop: %d %zu\n", state.sock, sizeof(state.line));
2205 while((len = recv(state.sock, state.line, sizeof(state.line), 0))) {
2207 if(errno == EINTR) {
2211 logger(mesh, MESHLINK_ERROR, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2212 meshlink_errno = MESHLINK_ENETWORK;
2216 if(!sptps_receive_data(&state.sptps, state.line, len)) {
2217 meshlink_errno = MESHLINK_EPEER;
2222 if(!state.success) {
2223 logger(mesh, MESHLINK_ERROR, "Connection closed by peer, invitation cancelled.\n");
2224 meshlink_errno = MESHLINK_EPEER;
2228 sptps_stop(&state.sptps);
2231 closesocket(state.sock);
2233 pthread_mutex_unlock(&mesh->mutex);
2237 logger(mesh, MESHLINK_ERROR, "Invalid invitation URL\n");
2238 meshlink_errno = MESHLINK_EINVAL;
2240 sptps_stop(&state.sptps);
2244 if(state.sock != -1) {
2245 closesocket(state.sock);
2248 pthread_mutex_unlock(&mesh->mutex);
2252 char *meshlink_export(meshlink_handle_t *mesh) {
2254 meshlink_errno = MESHLINK_EINVAL;
2258 // Create a config file on the fly.
2261 packmsg_output_t out = {buf, sizeof(buf)};
2262 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
2263 packmsg_add_str(&out, mesh->name);
2264 packmsg_add_str(&out, CORE_MESH);
2266 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2270 packmsg_add_int32(&out, mesh->self->devclass);
2271 packmsg_add_bool(&out, mesh->self->status.blacklisted);
2272 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2274 if(mesh->self->canonical_address && !strchr(mesh->self->canonical_address, ' ')) {
2275 char *canonical_address = NULL;
2276 xasprintf(&canonical_address, "%s %s", mesh->self->canonical_address, mesh->myport);
2277 packmsg_add_str(&out, canonical_address);
2278 free(canonical_address);
2280 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2285 for(uint32_t i = 0; i < MAX_RECENT; i++) {
2286 if(mesh->self->recent[i].sa.sa_family) {
2293 packmsg_add_array(&out, count);
2295 for(uint32_t i = 0; i < count; i++) {
2296 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2299 packmsg_add_int64(&out, 0);
2300 packmsg_add_int64(&out, 0);
2302 pthread_mutex_unlock(&mesh->mutex);
2304 if(!packmsg_output_ok(&out)) {
2305 logger(mesh, MESHLINK_ERROR, "Error creating export data\n");
2306 meshlink_errno = MESHLINK_EINTERNAL;
2310 // Prepare a base64-encoded packmsg array containing our config file
2312 uint32_t len = packmsg_output_size(&out, buf);
2313 uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2314 uint8_t *buf2 = xmalloc(len2);
2315 packmsg_output_t out2 = {buf2, len2};
2316 packmsg_add_array(&out2, 1);
2317 packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2319 if(!packmsg_output_ok(&out2)) {
2320 logger(mesh, MESHLINK_ERROR, "Error creating export data\n");
2321 meshlink_errno = MESHLINK_EINTERNAL;
2326 b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2328 return (char *)buf2;
2331 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2332 logger(mesh, MESHLINK_DEBUG, "meshlink_import(%p)", (const void *)data);
2334 if(!mesh || !data) {
2335 meshlink_errno = MESHLINK_EINVAL;
2339 size_t datalen = strlen(data);
2340 uint8_t *buf = xmalloc(datalen);
2341 int buflen = b64decode(data, buf, datalen);
2344 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2346 meshlink_errno = MESHLINK_EPEER;
2350 packmsg_input_t in = {buf, buflen};
2351 uint32_t count = packmsg_get_array(&in);
2354 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2356 meshlink_errno = MESHLINK_EPEER;
2360 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2366 uint32_t len2 = packmsg_get_bin_raw(&in, &data2);
2372 packmsg_input_t in2 = {data2, len2};
2373 uint32_t version = packmsg_get_uint32(&in2);
2374 char *name = packmsg_get_str_dup(&in2);
2376 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
2378 packmsg_input_invalidate(&in);
2382 if(!check_id(name)) {
2387 node_t *n = lookup_node(mesh, name);
2390 logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
2398 config_t config = {data2, len2};
2400 if(!node_read_from_config(mesh, n, &config)) {
2402 packmsg_input_invalidate(&in);
2406 if(!node_write_config(mesh, n, true)) {
2415 pthread_mutex_unlock(&mesh->mutex);
2419 if(!packmsg_done(&in)) {
2420 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2421 meshlink_errno = MESHLINK_EPEER;
2425 if(!config_sync(mesh, "current")) {
2432 bool meshlink_forget_node(meshlink_handle_t *mesh, meshlink_node_t *node) {
2433 logger(mesh, MESHLINK_DEBUG, "meshlink_forget_node(%s)", node ? node->name : "(null)");
2435 if(!mesh || !node) {
2436 meshlink_errno = MESHLINK_EINVAL;
2440 node_t *n = (node_t *)node;
2442 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2446 /* Check that the node is not reachable */
2447 if(n->status.reachable || n->connection) {
2448 pthread_mutex_unlock(&mesh->mutex);
2449 logger(mesh, MESHLINK_WARNING, "Could not forget %s: still reachable", n->name);
2453 /* Check that we don't have any active UTCP connections */
2454 if(n->utcp && utcp_is_active(n->utcp)) {
2455 pthread_mutex_unlock(&mesh->mutex);
2456 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active UTCP connections", n->name);
2460 /* Check that we have no active connections to this node */
2461 for list_each(connection_t, c, mesh->connections) {
2463 pthread_mutex_unlock(&mesh->mutex);
2464 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active connection", n->name);
2469 /* Remove any pending outgoings to this node */
2470 if(mesh->outgoings) {
2471 for list_each(outgoing_t, outgoing, mesh->outgoings) {
2472 if(outgoing->node == n) {
2473 list_delete_node(mesh->outgoings, list_node);
2478 /* Delete the config file for this node */
2479 if(!config_delete(mesh, "current", n->name)) {
2480 pthread_mutex_unlock(&mesh->mutex);
2484 /* Delete the node struct and any remaining edges referencing this node */
2487 pthread_mutex_unlock(&mesh->mutex);
2489 return config_sync(mesh, "current");
2492 /* Hint that a hostname may be found at an address
2493 * See header file for detailed comment.
2495 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2496 logger(mesh, MESHLINK_DEBUG, "meshlink_hint_address(%s, %p)", node ? node->name : "(null)", (const void *)addr);
2498 if(!mesh || !node || !addr) {
2499 meshlink_errno = EINVAL;
2503 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2507 node_t *n = (node_t *)node;
2509 if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
2510 if(!node_write_config(mesh, n, false)) {
2511 logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
2515 pthread_mutex_unlock(&mesh->mutex);
2516 // @TODO do we want to fire off a connection attempt right away?
2519 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2521 node_t *n = utcp->priv;
2522 meshlink_handle_t *mesh = n->mesh;
2524 if(mesh->channel_accept_cb && mesh->channel_listen_cb) {
2525 return mesh->channel_listen_cb(mesh, (meshlink_node_t *)n, port);
2527 return mesh->channel_accept_cb;
2531 /* Finish one AIO buffer, return true if the channel is still open. */
2532 static bool aio_finish_one(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t **head) {
2533 meshlink_aio_buffer_t *aio = *head;
2537 channel->in_callback = true;
2540 if(aio->cb.buffer) {
2541 aio->cb.buffer(mesh, channel, aio->data, aio->done, aio->priv);
2545 aio->cb.fd(mesh, channel, aio->fd, aio->done, aio->priv);
2549 channel->in_callback = false;
2562 /* Finish all AIO buffers, return true if the channel is still open. */
2563 static bool aio_abort(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t **head) {
2565 if(!aio_finish_one(mesh, channel, head)) {
2573 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2574 meshlink_channel_t *channel = connection->priv;
2580 node_t *n = channel->node;
2581 meshlink_handle_t *mesh = n->mesh;
2583 if(n->status.destroyed) {
2584 meshlink_channel_close(mesh, channel);
2588 const char *p = data;
2591 while(channel->aio_receive) {
2593 /* This receive callback signalled an error, abort all outstanding AIO buffers. */
2594 if(!aio_abort(mesh, channel, &channel->aio_receive)) {
2601 meshlink_aio_buffer_t *aio = channel->aio_receive;
2602 size_t todo = aio->len - aio->done;
2609 memcpy((char *)aio->data + aio->done, p, todo);
2611 ssize_t result = write(aio->fd, p, todo);
2614 if(result < 0 && errno == EINTR) {
2618 /* Writing to fd failed, cancel just this AIO buffer. */
2619 logger(mesh, MESHLINK_ERROR, "Writing to AIO fd %d failed: %s", aio->fd, strerror(errno));
2621 if(!aio_finish_one(mesh, channel, &channel->aio_receive)) {
2635 if(aio->done == aio->len) {
2636 if(!aio_finish_one(mesh, channel, &channel->aio_receive)) {
2646 if(channel->receive_cb) {
2647 channel->receive_cb(mesh, channel, p, left);
2653 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2654 node_t *n = utcp_connection->utcp->priv;
2660 meshlink_handle_t *mesh = n->mesh;
2662 if(!mesh->channel_accept_cb) {
2666 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2668 channel->c = utcp_connection;
2670 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2671 utcp_accept(utcp_connection, channel_recv, channel);
2677 static void channel_retransmit(struct utcp_connection *utcp_connection) {
2678 node_t *n = utcp_connection->utcp->priv;
2679 meshlink_handle_t *mesh = n->mesh;
2681 if(n->mtuprobes == 31 && n->mtutimeout.cb) {
2682 timeout_set(&mesh->loop, &n->mtutimeout, &(struct timespec) {
2688 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2689 node_t *n = utcp->priv;
2691 if(n->status.destroyed) {
2695 meshlink_handle_t *mesh = n->mesh;
2696 return meshlink_send_immediate(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2699 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2700 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_receive_cb(%p, %p)", (void *)channel, (void *)(intptr_t)cb);
2702 if(!mesh || !channel) {
2703 meshlink_errno = MESHLINK_EINVAL;
2707 channel->receive_cb = cb;
2710 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2712 node_t *n = (node_t *)source;
2718 utcp_recv(n->utcp, data, len);
2721 static void channel_poll(struct utcp_connection *connection, size_t len) {
2722 meshlink_channel_t *channel = connection->priv;
2728 node_t *n = channel->node;
2729 meshlink_handle_t *mesh = n->mesh;
2731 while(channel->aio_send) {
2733 /* This poll callback signalled an error, abort all outstanding AIO buffers. */
2734 if(!aio_abort(mesh, channel, &channel->aio_send)) {
2741 /* We have at least one AIO buffer. Send as much as possible from the buffers. */
2742 meshlink_aio_buffer_t *aio = channel->aio_send;
2743 size_t todo = aio->len - aio->done;
2751 sent = utcp_send(connection, (char *)aio->data + aio->done, todo);
2753 /* Limit the amount we read at once to avoid stack overflows */
2759 ssize_t result = read(aio->fd, buf, todo);
2763 sent = utcp_send(connection, buf, todo);
2765 if(result < 0 && errno == EINTR) {
2769 /* Reading from fd failed, cancel just this AIO buffer. */
2771 logger(mesh, MESHLINK_ERROR, "Reading from AIO fd %d failed: %s", aio->fd, strerror(errno));
2774 if(!aio_finish_one(mesh, channel, &channel->aio_send)) {
2782 if(sent != (ssize_t)todo) {
2783 /* Sending failed, abort all outstanding AIO buffers and send a poll callback. */
2784 if(!aio_abort(mesh, channel, &channel->aio_send)) {
2795 /* If we didn't finish this buffer, exit early. */
2796 if(aio->done < aio->len) {
2800 /* Signal completion of this buffer, and go to the next one. */
2801 if(!aio_finish_one(mesh, channel, &channel->aio_send)) {
2810 if(channel->poll_cb) {
2811 channel->poll_cb(mesh, channel, len);
2813 utcp_set_poll_cb(connection, NULL);
2817 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2818 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_poll_cb(%p, %p)", (void *)channel, (void *)(intptr_t)cb);
2820 if(!mesh || !channel) {
2821 meshlink_errno = MESHLINK_EINVAL;
2825 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2829 channel->poll_cb = cb;
2830 utcp_set_poll_cb(channel->c, (cb || channel->aio_send) ? channel_poll : NULL);
2831 pthread_mutex_unlock(&mesh->mutex);
2834 void meshlink_set_channel_listen_cb(meshlink_handle_t *mesh, meshlink_channel_listen_cb_t cb) {
2835 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_listen_cb(%p)", (void *)(intptr_t)cb);
2838 meshlink_errno = MESHLINK_EINVAL;
2842 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2846 mesh->channel_listen_cb = cb;
2848 pthread_mutex_unlock(&mesh->mutex);
2851 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2852 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_accept_cb(%p)", (void *)(intptr_t)cb);
2855 meshlink_errno = MESHLINK_EINVAL;
2859 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2863 mesh->channel_accept_cb = cb;
2864 mesh->receive_cb = channel_receive;
2866 for splay_each(node_t, n, mesh->nodes) {
2867 if(!n->utcp && n != mesh->self) {
2868 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2869 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
2870 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
2874 pthread_mutex_unlock(&mesh->mutex);
2877 void meshlink_set_channel_sndbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
2878 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_sndbuf(%p, %zu)", (void *)channel, size);
2880 meshlink_set_channel_sndbuf_storage(mesh, channel, NULL, size);
2883 void meshlink_set_channel_rcvbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
2884 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_rcvbuf(%p, %zu)", (void *)channel, size);
2886 meshlink_set_channel_rcvbuf_storage(mesh, channel, NULL, size);
2889 void meshlink_set_channel_sndbuf_storage(meshlink_handle_t *mesh, meshlink_channel_t *channel, void *buf, size_t size) {
2890 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_sndbuf_storage(%p, %p, %zu)", (void *)channel, buf, size);
2892 if(!mesh || !channel) {
2893 meshlink_errno = MESHLINK_EINVAL;
2897 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2901 utcp_set_sndbuf(channel->c, buf, size);
2902 pthread_mutex_unlock(&mesh->mutex);
2905 void meshlink_set_channel_rcvbuf_storage(meshlink_handle_t *mesh, meshlink_channel_t *channel, void *buf, size_t size) {
2906 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_rcvbuf_storage(%p, %p, %zu)", (void *)channel, buf, size);
2908 if(!mesh || !channel) {
2909 meshlink_errno = MESHLINK_EINVAL;
2913 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2917 utcp_set_rcvbuf(channel->c, buf, size);
2918 pthread_mutex_unlock(&mesh->mutex);
2921 void meshlink_set_channel_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel, uint32_t flags) {
2922 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_flags(%p, %u)", (void *)channel, flags);
2924 if(!mesh || !channel) {
2925 meshlink_errno = MESHLINK_EINVAL;
2929 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2933 utcp_set_flags(channel->c, flags);
2934 pthread_mutex_unlock(&mesh->mutex);
2937 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) {
2938 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);
2941 abort(); // TODO: handle non-NULL data
2944 if(!mesh || !node) {
2945 meshlink_errno = MESHLINK_EINVAL;
2949 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2953 node_t *n = (node_t *)node;
2956 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2957 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
2958 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
2959 mesh->receive_cb = channel_receive;
2962 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2963 pthread_mutex_unlock(&mesh->mutex);
2968 if(n->status.blacklisted) {
2969 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
2970 meshlink_errno = MESHLINK_EBLACKLISTED;
2971 pthread_mutex_unlock(&mesh->mutex);
2975 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2977 channel->receive_cb = cb;
2980 channel->priv = (void *)data;
2983 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2985 pthread_mutex_unlock(&mesh->mutex);
2988 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2996 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) {
2997 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_open_ex(%s, %u, %p, %p, %zu)", node ? node->name : "(null)", port, (void *)(intptr_t)cb, data, len);
2999 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3002 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3003 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_shutdown(%p, %d)", (void *)channel, direction);
3005 if(!mesh || !channel) {
3006 meshlink_errno = MESHLINK_EINVAL;
3010 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3014 utcp_shutdown(channel->c, direction);
3015 pthread_mutex_unlock(&mesh->mutex);
3018 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3019 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_close(%p)", (void *)channel);
3021 if(!mesh || !channel) {
3022 meshlink_errno = MESHLINK_EINVAL;
3026 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3031 utcp_close(channel->c);
3034 /* Clean up any outstanding AIO buffers. */
3035 aio_abort(mesh, channel, &channel->aio_send);
3036 aio_abort(mesh, channel, &channel->aio_receive);
3039 if(!channel->in_callback) {
3043 pthread_mutex_unlock(&mesh->mutex);
3046 void meshlink_channel_abort(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3047 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_abort(%p)", (void *)channel);
3049 if(!mesh || !channel) {
3050 meshlink_errno = MESHLINK_EINVAL;
3054 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3059 utcp_abort(channel->c);
3062 /* Clean up any outstanding AIO buffers. */
3063 aio_abort(mesh, channel, &channel->aio_send);
3064 aio_abort(mesh, channel, &channel->aio_receive);
3067 if(!channel->in_callback) {
3071 pthread_mutex_unlock(&mesh->mutex);
3074 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3075 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_send(%p, %p, %zu)", (void *)channel, data, len);
3077 if(!mesh || !channel) {
3078 meshlink_errno = MESHLINK_EINVAL;
3087 meshlink_errno = MESHLINK_EINVAL;
3091 // TODO: more finegrained locking.
3092 // Ideally we want to put the data into the UTCP connection's send buffer.
3093 // Then, preferably only if there is room in the receiver window,
3094 // kick the meshlink thread to go send packets.
3098 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3102 /* Disallow direct calls to utcp_send() while we still have AIO active. */
3103 if(channel->aio_send) {
3106 retval = utcp_send(channel->c, data, len);
3109 pthread_mutex_unlock(&mesh->mutex);
3112 meshlink_errno = MESHLINK_ENETWORK;
3118 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) {
3119 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_send(%p, %p, %zu, %p, %p)", (void *)channel, data, len, (void *)(intptr_t)cb, priv);
3121 if(!mesh || !channel) {
3122 meshlink_errno = MESHLINK_EINVAL;
3127 meshlink_errno = MESHLINK_EINVAL;
3131 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3134 aio->cb.buffer = cb;
3137 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3141 /* Append the AIO buffer descriptor to the end of the chain */
3142 meshlink_aio_buffer_t **p = &channel->aio_send;
3150 /* Ensure the poll callback is set, and call it right now to push data if possible */
3151 utcp_set_poll_cb(channel->c, channel_poll);
3152 size_t todo = MIN(len, utcp_get_rcvbuf_free(channel->c));
3155 channel_poll(channel->c, todo);
3158 pthread_mutex_unlock(&mesh->mutex);
3163 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) {
3164 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_fd_send(%p, %d, %zu, %p, %p)", (void *)channel, fd, len, (void *)(intptr_t)cb, priv);
3166 if(!mesh || !channel) {
3167 meshlink_errno = MESHLINK_EINVAL;
3171 if(!len || fd == -1) {
3172 meshlink_errno = MESHLINK_EINVAL;
3176 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3182 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3186 /* Append the AIO buffer descriptor to the end of the chain */
3187 meshlink_aio_buffer_t **p = &channel->aio_send;
3195 /* Ensure the poll callback is set, and call it right now to push data if possible */
3196 utcp_set_poll_cb(channel->c, channel_poll);
3197 size_t left = utcp_get_rcvbuf_free(channel->c);
3200 channel_poll(channel->c, left);
3203 pthread_mutex_unlock(&mesh->mutex);
3208 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) {
3209 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_receive(%p, %p, %zu, %p, %p)", (void *)channel, data, len, (void *)(intptr_t)cb, priv);
3211 if(!mesh || !channel) {
3212 meshlink_errno = MESHLINK_EINVAL;
3217 meshlink_errno = MESHLINK_EINVAL;
3221 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3224 aio->cb.buffer = cb;
3227 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3231 /* Append the AIO buffer descriptor to the end of the chain */
3232 meshlink_aio_buffer_t **p = &channel->aio_receive;
3240 pthread_mutex_unlock(&mesh->mutex);
3245 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) {
3246 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_fd_receive(%p, %d, %zu, %p, %p)", (void *)channel, fd, len, (void *)(intptr_t)cb, priv);
3248 if(!mesh || !channel) {
3249 meshlink_errno = MESHLINK_EINVAL;
3253 if(!len || fd == -1) {
3254 meshlink_errno = MESHLINK_EINVAL;
3258 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3264 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3268 /* Append the AIO buffer descriptor to the end of the chain */
3269 meshlink_aio_buffer_t **p = &channel->aio_receive;
3277 pthread_mutex_unlock(&mesh->mutex);
3282 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3283 if(!mesh || !channel) {
3284 meshlink_errno = MESHLINK_EINVAL;
3288 return channel->c->flags;
3291 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3292 if(!mesh || !channel) {
3293 meshlink_errno = MESHLINK_EINVAL;
3297 return utcp_get_sendq(channel->c);
3300 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3301 if(!mesh || !channel) {
3302 meshlink_errno = MESHLINK_EINVAL;
3306 return utcp_get_recvq(channel->c);
3309 size_t meshlink_channel_get_mss(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3310 if(!mesh || !channel) {
3311 meshlink_errno = MESHLINK_EINVAL;
3315 return utcp_get_mss(channel->node->utcp);
3318 void meshlink_set_node_channel_timeout(meshlink_handle_t *mesh, meshlink_node_t *node, int timeout) {
3319 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_channel_timeout(%s, %d)", node ? node->name : "(null)", timeout);
3321 if(!mesh || !node) {
3322 meshlink_errno = MESHLINK_EINVAL;
3326 node_t *n = (node_t *)node;
3328 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3333 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3334 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
3335 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
3338 utcp_set_user_timeout(n->utcp, timeout);
3340 pthread_mutex_unlock(&mesh->mutex);
3343 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
3344 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
3345 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3346 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
3347 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
3350 if(mesh->node_status_cb) {
3351 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
3354 if(mesh->node_pmtu_cb) {
3355 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3359 void update_node_pmtu(meshlink_handle_t *mesh, node_t *n) {
3360 utcp_set_mtu(n->utcp, (n->minmtu > MINMTU ? n->minmtu : MINMTU) - sizeof(meshlink_packethdr_t));
3362 if(mesh->node_pmtu_cb && !n->status.blacklisted) {
3363 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3367 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
3368 if(!mesh->node_duplicate_cb || n->status.duplicate) {
3372 n->status.duplicate = true;
3373 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
3376 void meshlink_hint_network_change(struct meshlink_handle *mesh) {
3377 logger(mesh, MESHLINK_DEBUG, "meshlink_hint_network_change()");
3380 meshlink_errno = MESHLINK_EINVAL;
3384 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3388 pthread_mutex_unlock(&mesh->mutex);
3391 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
3392 logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_timeouts(%d, %d, %d)", devclass, pinginterval, pingtimeout);
3394 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3395 meshlink_errno = EINVAL;
3399 if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
3400 meshlink_errno = EINVAL;
3404 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3408 mesh->dev_class_traits[devclass].pinginterval = pinginterval;
3409 mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
3410 pthread_mutex_unlock(&mesh->mutex);
3413 void meshlink_set_dev_class_fast_retry_period(meshlink_handle_t *mesh, dev_class_t devclass, int fast_retry_period) {
3414 logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_fast_retry_period(%d, %d)", devclass, fast_retry_period);
3416 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3417 meshlink_errno = EINVAL;
3421 if(fast_retry_period < 0) {
3422 meshlink_errno = EINVAL;
3426 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3430 mesh->dev_class_traits[devclass].fast_retry_period = fast_retry_period;
3431 pthread_mutex_unlock(&mesh->mutex);
3434 void meshlink_set_dev_class_maxtimeout(struct meshlink_handle *mesh, dev_class_t devclass, int maxtimeout) {
3435 logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_fast_maxtimeout(%d, %d)", devclass, maxtimeout);
3437 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3438 meshlink_errno = EINVAL;
3442 if(maxtimeout < 0) {
3443 meshlink_errno = EINVAL;
3447 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3451 mesh->dev_class_traits[devclass].maxtimeout = maxtimeout;
3452 pthread_mutex_unlock(&mesh->mutex);
3455 void meshlink_reset_timers(struct meshlink_handle *mesh) {
3456 logger(mesh, MESHLINK_DEBUG, "meshlink_reset_timers()");
3462 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3466 handle_network_change(mesh, true);
3468 pthread_mutex_unlock(&mesh->mutex);
3471 void meshlink_set_inviter_commits_first(struct meshlink_handle *mesh, bool inviter_commits_first) {
3472 logger(mesh, MESHLINK_DEBUG, "meshlink_set_inviter_commits_first(%d)", inviter_commits_first);
3475 meshlink_errno = EINVAL;
3479 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3483 mesh->inviter_commits_first = inviter_commits_first;
3484 pthread_mutex_unlock(&mesh->mutex);
3487 void meshlink_set_scheduling_granularity(struct meshlink_handle *mesh, long granularity) {
3488 logger(mesh, MESHLINK_DEBUG, "meshlink_set_scheduling_granularity(%ld)", granularity);
3490 if(!mesh || granularity < 0) {
3491 meshlink_errno = EINVAL;
3495 utcp_set_clock_granularity(granularity);
3498 void meshlink_set_storage_policy(struct meshlink_handle *mesh, meshlink_storage_policy_t policy) {
3499 logger(mesh, MESHLINK_DEBUG, "meshlink_set_storage_policy(%d)", policy);
3502 meshlink_errno = EINVAL;
3506 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3510 mesh->storage_policy = policy;
3511 pthread_mutex_unlock(&mesh->mutex);
3514 void handle_network_change(meshlink_handle_t *mesh, bool online) {
3517 if(!mesh->connections || !mesh->loop.running) {
3522 signal_trigger(&mesh->loop, &mesh->datafromapp);
3525 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t cb_errno) {
3526 // We should only call the callback function if we are in the background thread.
3527 if(!mesh->error_cb) {
3531 if(!mesh->threadstarted) {
3535 if(mesh->thread == pthread_self()) {
3536 mesh->error_cb(mesh, cb_errno);
3540 static void __attribute__((constructor)) meshlink_init(void) {
3542 utcp_set_clock_granularity(10000);
3545 static void __attribute__((destructor)) meshlink_exit(void) {