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"
38 #include "ed25519/sha512.h"
42 #define MSG_NOSIGNAL 0
44 __thread meshlink_errno_t meshlink_errno;
45 meshlink_log_cb_t global_log_cb;
46 meshlink_log_level_t global_log_level;
48 typedef bool (*search_node_by_condition_t)(const node_t *, const void *);
50 static int rstrip(char *value) {
51 int len = strlen(value);
53 while(len && strchr("\t\r\n ", value[len - 1])) {
60 static bool is_valid_hostname(const char *hostname) {
65 for(const char *p = hostname; *p; p++) {
66 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
74 static bool is_valid_port(const char *port) {
81 unsigned long int result = strtoul(port, &end, 10);
82 return result && result < 65536 && !*end;
85 for(const char *p = port; *p; p++) {
86 if(!(isalnum(*p) || *p == '-')) {
94 static void set_timeout(int sock, int timeout) {
99 tv.tv_sec = timeout / 1000;
100 tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
102 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
103 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
106 struct socket_in_netns_params {
115 static void *socket_in_netns_thread(void *arg) {
116 struct socket_in_netns_params *params = arg;
118 if(setns(params->netns, CLONE_NEWNET) == -1) {
119 meshlink_errno = MESHLINK_EINVAL;
123 params->fd = socket(params->domain, params->type, params->protocol);
129 static int socket_in_netns(int domain, int type, int protocol, int netns) {
131 return socket(domain, type, protocol);
135 struct socket_in_netns_params params = {domain, type, protocol, netns, -1};
139 if(pthread_create(&thr, NULL, socket_in_netns_thread, ¶ms) == 0) {
140 if(pthread_join(thr, NULL) != 0) {
152 static bool write_main_config_files(meshlink_handle_t *mesh) {
153 if(!mesh->confbase) {
159 /* Write the main config file */
160 packmsg_output_t out = {buf, sizeof buf};
162 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
163 packmsg_add_str(&out, mesh->name);
164 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
165 packmsg_add_nil(&out); // Invitation keys are not supported
166 packmsg_add_uint16(&out, atoi(mesh->myport));
168 if(!packmsg_output_ok(&out)) {
172 config_t config = {buf, packmsg_output_size(&out, buf)};
174 if(!main_config_write(mesh, "current", &config, mesh->config_key)) {
178 /* Write our own host config file */
179 if(!node_write_config(mesh, mesh->self, true)) {
187 meshlink_handle_t *mesh;
189 char cookie[18 + 32];
200 static bool finalize_join(join_state_t *state, const void *buf, uint16_t len) {
201 meshlink_handle_t *mesh = state->mesh;
202 packmsg_input_t in = {buf, len};
203 uint32_t version = packmsg_get_uint32(&in);
205 if(version != MESHLINK_INVITATION_VERSION) {
206 logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
210 char *name = packmsg_get_str_dup(&in);
211 char *submesh_name = packmsg_get_str_dup(&in);
212 dev_class_t devclass = packmsg_get_int32(&in);
213 uint32_t count = packmsg_get_array(&in);
215 if(!name || !check_id(name)) {
216 logger(mesh, MESHLINK_DEBUG, "No valid Name found in invitation!\n");
222 if(!submesh_name || (strcmp(submesh_name, CORE_MESH) && !check_id(submesh_name))) {
223 logger(mesh, MESHLINK_DEBUG, "No valid Submesh found in invitation!\n");
230 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
237 free(mesh->self->name);
239 mesh->self->name = xstrdup(name);
240 mesh->self->submesh = strcmp(submesh_name, CORE_MESH) ? lookup_or_create_submesh(mesh, submesh_name) : NULL;
242 mesh->self->devclass = devclass == DEV_CLASS_UNKNOWN ? mesh->devclass : devclass;
244 // Initialize configuration directory
245 if(!config_init(mesh, "current")) {
249 if(!write_main_config_files(mesh)) {
253 // Write host config files
254 for(uint32_t i = 0; i < count; i++) {
256 uint32_t data_len = packmsg_get_bin_raw(&in, &data);
259 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
263 packmsg_input_t in2 = {data, data_len};
264 uint32_t version2 = packmsg_get_uint32(&in2);
265 char *name2 = packmsg_get_str_dup(&in2);
267 if(!packmsg_input_ok(&in2) || version2 != MESHLINK_CONFIG_VERSION || !check_id(name2)) {
269 packmsg_input_invalidate(&in);
273 if(!check_id(name2)) {
278 if(!strcmp(name2, mesh->name)) {
279 logger(mesh, MESHLINK_ERROR, "Secondary chunk would overwrite our own host config file.\n");
281 meshlink_errno = MESHLINK_EPEER;
285 node_t *n = new_node();
288 config_t config = {data, data_len};
290 if(!node_read_from_config(mesh, n, &config)) {
292 logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
293 meshlink_errno = MESHLINK_EPEER;
298 /* The first host config file is of the inviter itself;
299 * remember the address we are currently using for the invitation connection.
302 socklen_t salen = sizeof(sa);
304 if(getpeername(state->sock, &sa.sa, &salen) == 0) {
305 node_add_recent_address(mesh, n, &sa);
309 if(!node_write_config(mesh, n, true)) {
317 /* Ensure the configuration directory metadata is on disk */
318 if(!config_sync(mesh, "current") || (mesh->confbase && !sync_path(mesh->confbase))) {
322 if(!mesh->inviter_commits_first) {
323 devtool_set_inviter_commits_first(false);
326 sptps_send_record(&state->sptps, 1, ecdsa_get_public_key(mesh->private_key), 32);
328 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
333 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
335 join_state_t *state = handle;
336 const char *ptr = data;
339 int result = send(state->sock, ptr, len, 0);
341 if(result == -1 && errno == EINTR) {
343 } else if(result <= 0) {
354 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
355 join_state_t *state = handle;
356 meshlink_handle_t *mesh = state->mesh;
358 if(mesh->inviter_commits_first) {
360 case SPTPS_HANDSHAKE:
361 return sptps_send_record(&state->sptps, 2, state->cookie, 18 + 32);
367 if(!finalize_join(state, msg, len)) {
371 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
372 shutdown(state->sock, SHUT_RDWR);
373 state->success = true;
381 case SPTPS_HANDSHAKE:
382 return sptps_send_record(&state->sptps, 0, state->cookie, 18);
385 return finalize_join(state, msg, len);
388 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
389 shutdown(state->sock, SHUT_RDWR);
390 state->success = true;
401 static bool recvline(join_state_t *state) {
402 char *newline = NULL;
404 while(!(newline = memchr(state->buffer, '\n', state->blen))) {
405 int result = recv(state->sock, state->buffer + state->blen, sizeof(state)->buffer - state->blen, 0);
407 if(result == -1 && errno == EINTR) {
409 } else if(result <= 0) {
413 state->blen += result;
416 if((size_t)(newline - state->buffer) >= sizeof(state->line)) {
420 size_t len = newline - state->buffer;
422 memcpy(state->line, state->buffer, len);
423 state->line[len] = 0;
424 memmove(state->buffer, newline + 1, state->blen - len - 1);
425 state->blen -= len + 1;
430 static bool sendline(int fd, const char *format, ...) {
436 va_start(ap, format);
437 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
440 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
448 int result = send(fd, p, blen, MSG_NOSIGNAL);
450 if(result == -1 && errno == EINTR) {
452 } else if(result <= 0) {
463 static const char *errstr[] = {
464 [MESHLINK_OK] = "No error",
465 [MESHLINK_EINVAL] = "Invalid argument",
466 [MESHLINK_ENOMEM] = "Out of memory",
467 [MESHLINK_ENOENT] = "No such node",
468 [MESHLINK_EEXIST] = "Node already exists",
469 [MESHLINK_EINTERNAL] = "Internal error",
470 [MESHLINK_ERESOLV] = "Could not resolve hostname",
471 [MESHLINK_ESTORAGE] = "Storage error",
472 [MESHLINK_ENETWORK] = "Network error",
473 [MESHLINK_EPEER] = "Error communicating with peer",
474 [MESHLINK_ENOTSUP] = "Operation not supported",
475 [MESHLINK_EBUSY] = "MeshLink instance already in use",
476 [MESHLINK_EBLACKLISTED] = "Node is blacklisted",
479 const char *meshlink_strerror(meshlink_errno_t err) {
480 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
481 return "Invalid error code";
487 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
488 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
490 mesh->private_key = ecdsa_generate();
492 if(!mesh->private_key) {
493 logger(mesh, MESHLINK_ERROR, "Error during key generation!\n");
494 meshlink_errno = MESHLINK_EINTERNAL;
498 logger(mesh, MESHLINK_DEBUG, "Done.\n");
503 static bool timespec_lt(const struct timespec *a, const struct timespec *b) {
504 if(a->tv_sec == b->tv_sec) {
505 return a->tv_nsec < b->tv_nsec;
507 return a->tv_sec < b->tv_sec;
511 static struct timespec idle(event_loop_t *loop, void *data) {
513 meshlink_handle_t *mesh = data;
514 struct timespec t, tmin = {3600, 0};
516 for splay_each(node_t, n, mesh->nodes) {
521 t = utcp_timeout(n->utcp);
523 if(timespec_lt(&t, &tmin)) {
531 static bool meshlink_setup(meshlink_handle_t *mesh) {
532 if(!config_destroy(mesh->confbase, "new")) {
533 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/new: %s\n", mesh->confbase, strerror(errno));
534 meshlink_errno = MESHLINK_ESTORAGE;
538 if(!config_destroy(mesh->confbase, "old")) {
539 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
540 meshlink_errno = MESHLINK_ESTORAGE;
544 if(!config_init(mesh, "current")) {
545 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
546 meshlink_errno = MESHLINK_ESTORAGE;
550 if(!ecdsa_keygen(mesh)) {
551 meshlink_errno = MESHLINK_EINTERNAL;
555 mesh->myport = xstrdup("0");
557 /* Create a node for ourself */
559 mesh->self = new_node();
560 mesh->self->name = xstrdup(mesh->name);
561 mesh->self->devclass = mesh->devclass;
562 mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
563 mesh->self->session_id = mesh->session_id;
565 if(!write_main_config_files(mesh)) {
566 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
567 meshlink_errno = MESHLINK_ESTORAGE;
571 /* Ensure the configuration directory metadata is on disk */
572 if(!config_sync(mesh, "current")) {
579 static bool meshlink_read_config(meshlink_handle_t *mesh) {
582 if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
583 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
587 packmsg_input_t in = {config.buf, config.len};
588 const void *private_key;
590 uint32_t version = packmsg_get_uint32(&in);
591 char *name = packmsg_get_str_dup(&in);
592 uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
593 packmsg_skip_element(&in); // Invitation key is not supported
594 uint16_t myport = packmsg_get_uint16(&in);
596 if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96) {
597 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
599 config_free(&config);
603 if(mesh->name && strcmp(mesh->name, name)) {
604 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
605 meshlink_errno = MESHLINK_ESTORAGE;
607 config_free(&config);
613 xasprintf(&mesh->myport, "%u", myport);
614 mesh->private_key = ecdsa_set_private_key(private_key);
615 config_free(&config);
617 /* Create a node for ourself and read our host configuration file */
619 mesh->self = new_node();
620 mesh->self->name = xstrdup(name);
621 mesh->self->devclass = mesh->devclass;
622 mesh->self->session_id = mesh->session_id;
624 if(!node_read_public_key(mesh, mesh->self)) {
625 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
626 meshlink_errno = MESHLINK_ESTORAGE;
627 free_node(mesh->self);
636 static void *setup_network_in_netns_thread(void *arg) {
637 meshlink_handle_t *mesh = arg;
639 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
643 bool success = setup_network(mesh);
644 return success ? arg : NULL;
648 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
649 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_init(%s, %s, %s, %d)", confbase, name, appname, devclass);
651 if(!confbase || !*confbase) {
652 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
653 meshlink_errno = MESHLINK_EINVAL;
657 if(!appname || !*appname) {
658 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
659 meshlink_errno = MESHLINK_EINVAL;
663 if(strchr(appname, ' ')) {
664 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
665 meshlink_errno = MESHLINK_EINVAL;
669 if(name && !check_id(name)) {
670 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
671 meshlink_errno = MESHLINK_EINVAL;
675 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
676 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
677 meshlink_errno = MESHLINK_EINVAL;
681 meshlink_open_params_t *params = xzalloc(sizeof * params);
683 params->confbase = xstrdup(confbase);
684 params->name = name ? xstrdup(name) : NULL;
685 params->appname = xstrdup(appname);
686 params->devclass = devclass;
689 xasprintf(¶ms->lock_filename, "%s" SLASH "meshlink.lock", confbase);
694 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
695 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_netnst(%d)", netns);
698 meshlink_errno = MESHLINK_EINVAL;
702 params->netns = netns;
707 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
708 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_key(%p, %zu)", key, keylen);
711 meshlink_errno = MESHLINK_EINVAL;
715 if((!key && keylen) || (key && !keylen)) {
716 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
717 meshlink_errno = MESHLINK_EINVAL;
722 params->keylen = keylen;
727 bool meshlink_open_params_set_storage_policy(meshlink_open_params_t *params, meshlink_storage_policy_t policy) {
728 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_policy(%d)", policy);
731 meshlink_errno = MESHLINK_EINVAL;
735 params->storage_policy = policy;
740 bool meshlink_open_params_set_lock_filename(meshlink_open_params_t *params, const char *filename) {
741 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_lock_filename(%s)", filename);
743 if(!params || !filename) {
744 meshlink_errno = MESHLINK_EINVAL;
748 free(params->lock_filename);
749 params->lock_filename = xstrdup(filename);
754 bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
755 logger(NULL, MESHLINK_DEBUG, "meshlink_encrypted_key_rotate(%p, %zu)", new_key, new_keylen);
757 if(!mesh || !new_key || !new_keylen) {
758 logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
759 meshlink_errno = MESHLINK_EINVAL;
763 if(pthread_mutex_lock(&mesh->mutex) != 0) {
767 // Create hash for the new key
768 void *new_config_key;
769 new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
771 if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
772 logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
773 meshlink_errno = MESHLINK_EINTERNAL;
774 pthread_mutex_unlock(&mesh->mutex);
778 // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
780 if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
781 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
782 meshlink_errno = MESHLINK_ESTORAGE;
783 pthread_mutex_unlock(&mesh->mutex);
787 devtool_keyrotate_probe(1);
789 // Rename confbase/current/ to confbase/old
791 if(!config_rename(mesh, "current", "old")) {
792 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
793 meshlink_errno = MESHLINK_ESTORAGE;
794 pthread_mutex_unlock(&mesh->mutex);
798 devtool_keyrotate_probe(2);
800 // Rename confbase/new/ to confbase/current
802 if(!config_rename(mesh, "new", "current")) {
803 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
804 meshlink_errno = MESHLINK_ESTORAGE;
805 pthread_mutex_unlock(&mesh->mutex);
809 devtool_keyrotate_probe(3);
811 // Cleanup the "old" confbase sub-directory
813 if(!config_destroy(mesh->confbase, "old")) {
814 pthread_mutex_unlock(&mesh->mutex);
818 // Change the mesh handle key with new key
820 free(mesh->config_key);
821 mesh->config_key = new_config_key;
823 pthread_mutex_unlock(&mesh->mutex);
828 void meshlink_open_params_free(meshlink_open_params_t *params) {
829 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_free()");
832 meshlink_errno = MESHLINK_EINVAL;
836 free(params->confbase);
838 free(params->appname);
839 free(params->lock_filename);
844 /// Device class traits
845 static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
846 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
847 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
848 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
849 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN
852 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
853 logger(NULL, MESHLINK_DEBUG, "meshlink_open(%s, %s, %s, %d)", confbase, name, appname, devclass);
855 if(!confbase || !*confbase) {
856 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
857 meshlink_errno = MESHLINK_EINVAL;
861 char lock_filename[PATH_MAX];
862 snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
864 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
865 meshlink_open_params_t params = {
866 .confbase = (char *)confbase,
867 .lock_filename = lock_filename,
868 .name = (char *)name,
869 .appname = (char *)appname,
870 .devclass = devclass,
874 return meshlink_open_ex(¶ms);
877 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) {
878 logger(NULL, MESHLINK_DEBUG, "meshlink_open_encrypted(%s, %s, %s, %d, %p, %zu)", confbase, name, appname, devclass, key, keylen);
880 if(!confbase || !*confbase) {
881 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
882 meshlink_errno = MESHLINK_EINVAL;
886 char lock_filename[PATH_MAX];
887 snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
889 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
890 meshlink_open_params_t params = {
891 .confbase = (char *)confbase,
892 .lock_filename = lock_filename,
893 .name = (char *)name,
894 .appname = (char *)appname,
895 .devclass = devclass,
899 if(!meshlink_open_params_set_storage_key(¶ms, key, keylen)) {
903 return meshlink_open_ex(¶ms);
906 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
907 logger(NULL, MESHLINK_DEBUG, "meshlink_open_ephemeral(%s, %s, %d)", name, appname, devclass);
910 logger(NULL, MESHLINK_ERROR, "No name given!\n");
911 meshlink_errno = MESHLINK_EINVAL;
915 if(!check_id(name)) {
916 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
917 meshlink_errno = MESHLINK_EINVAL;
921 if(!appname || !*appname) {
922 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
923 meshlink_errno = MESHLINK_EINVAL;
927 if(strchr(appname, ' ')) {
928 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
929 meshlink_errno = MESHLINK_EINVAL;
933 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
934 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
935 meshlink_errno = MESHLINK_EINVAL;
939 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
940 meshlink_open_params_t params = {
941 .name = (char *)name,
942 .appname = (char *)appname,
943 .devclass = devclass,
947 return meshlink_open_ex(¶ms);
950 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
951 logger(NULL, MESHLINK_DEBUG, "meshlink_open_ex()");
953 // Validate arguments provided by the application
954 if(!params->appname || !*params->appname) {
955 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
956 meshlink_errno = MESHLINK_EINVAL;
960 if(strchr(params->appname, ' ')) {
961 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
962 meshlink_errno = MESHLINK_EINVAL;
966 if(params->name && !check_id(params->name)) {
967 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
968 meshlink_errno = MESHLINK_EINVAL;
972 if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
973 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
974 meshlink_errno = MESHLINK_EINVAL;
978 if((params->key && !params->keylen) || (!params->key && params->keylen)) {
979 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
980 meshlink_errno = MESHLINK_EINVAL;
984 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
986 if(params->confbase) {
987 mesh->confbase = xstrdup(params->confbase);
990 mesh->appname = xstrdup(params->appname);
991 mesh->devclass = params->devclass;
992 mesh->netns = params->netns;
993 mesh->submeshes = NULL;
994 mesh->log_cb = global_log_cb;
995 mesh->log_level = global_log_level;
996 mesh->packet = xmalloc(sizeof(vpn_packet_t));
998 randomize(&mesh->prng_state, sizeof(mesh->prng_state));
1001 randomize(&mesh->session_id, sizeof(mesh->session_id));
1002 } while(mesh->session_id == 0);
1004 memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
1006 mesh->name = params->name ? xstrdup(params->name) : NULL;
1010 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1012 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
1013 logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
1014 meshlink_close(mesh);
1015 meshlink_errno = MESHLINK_EINTERNAL;
1020 // initialize mutexes and conds
1021 pthread_mutexattr_t attr;
1022 pthread_mutexattr_init(&attr);
1024 if(pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) != 0) {
1028 pthread_mutex_init(&mesh->mutex, &attr);
1029 pthread_cond_init(&mesh->cond, NULL);
1031 mesh->threadstarted = false;
1032 event_loop_init(&mesh->loop);
1033 mesh->loop.data = mesh;
1035 meshlink_queue_init(&mesh->outpacketqueue);
1037 // Atomically lock the configuration directory.
1038 if(!main_config_lock(mesh, params->lock_filename)) {
1039 meshlink_close(mesh);
1043 // If no configuration exists yet, create it.
1045 bool new_configuration = false;
1047 if(!meshlink_confbase_exists(mesh)) {
1049 logger(NULL, MESHLINK_ERROR, "No configuration files found!\n");
1050 meshlink_close(mesh);
1051 meshlink_errno = MESHLINK_ESTORAGE;
1055 if(!meshlink_setup(mesh)) {
1056 logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1057 meshlink_close(mesh);
1061 new_configuration = true;
1063 if(!meshlink_read_config(mesh)) {
1064 logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1065 meshlink_close(mesh);
1070 mesh->storage_policy = params->storage_policy;
1073 struct WSAData wsa_state;
1074 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1077 // Setup up everything
1078 // TODO: we should not open listening sockets yet
1080 bool success = false;
1082 if(mesh->netns != -1) {
1086 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1087 void *retval = NULL;
1088 success = pthread_join(thr, &retval) == 0 && retval;
1092 meshlink_errno = MESHLINK_EINTERNAL;
1095 #endif // HAVE_SETNS
1097 success = setup_network(mesh);
1101 meshlink_close(mesh);
1102 meshlink_errno = MESHLINK_ENETWORK;
1106 if(!node_write_config(mesh, mesh->self, new_configuration)) {
1107 logger(NULL, MESHLINK_ERROR, "Cannot update configuration\n");
1111 idle_set(&mesh->loop, idle, mesh);
1113 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1117 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t *mesh, const char *submesh) {
1118 logger(NULL, MESHLINK_DEBUG, "meshlink_submesh_open(%s)", submesh);
1120 meshlink_submesh_t *s = NULL;
1123 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1124 meshlink_errno = MESHLINK_EINVAL;
1128 if(!submesh || !*submesh) {
1129 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1130 meshlink_errno = MESHLINK_EINVAL;
1135 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1139 s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
1141 pthread_mutex_unlock(&mesh->mutex);
1146 static void *meshlink_main_loop(void *arg) {
1147 meshlink_handle_t *mesh = arg;
1149 if(mesh->netns != -1) {
1152 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1153 pthread_cond_signal(&mesh->cond);
1158 pthread_cond_signal(&mesh->cond);
1160 #endif // HAVE_SETNS
1163 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1167 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1168 pthread_cond_broadcast(&mesh->cond);
1170 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1172 pthread_mutex_unlock(&mesh->mutex);
1177 bool meshlink_start(meshlink_handle_t *mesh) {
1179 meshlink_errno = MESHLINK_EINVAL;
1183 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1185 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1190 assert(mesh->private_key);
1191 assert(mesh->self->ecdsa);
1192 assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1194 if(mesh->threadstarted) {
1195 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1196 pthread_mutex_unlock(&mesh->mutex);
1200 // Reset node connection timers
1201 for splay_each(node_t, n, mesh->nodes) {
1202 n->last_connect_try = 0;
1206 //Check that a valid name is set
1208 logger(mesh, MESHLINK_ERROR, "No name given!\n");
1209 meshlink_errno = MESHLINK_EINVAL;
1210 pthread_mutex_unlock(&mesh->mutex);
1214 init_outgoings(mesh);
1216 // Start the main thread
1218 event_loop_start(&mesh->loop);
1220 // Ensure we have a decent amount of stack space. Musl's default of 80 kB is too small.
1221 pthread_attr_t attr;
1222 pthread_attr_init(&attr);
1223 pthread_attr_setstacksize(&attr, 1024 * 1024);
1225 if(pthread_create(&mesh->thread, &attr, meshlink_main_loop, mesh) != 0) {
1226 logger(mesh, MESHLINK_ERROR, "Could not start thread: %s\n", strerror(errno));
1227 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1228 meshlink_errno = MESHLINK_EINTERNAL;
1229 event_loop_stop(&mesh->loop);
1230 pthread_mutex_unlock(&mesh->mutex);
1234 pthread_cond_wait(&mesh->cond, &mesh->mutex);
1235 mesh->threadstarted = true;
1237 pthread_mutex_unlock(&mesh->mutex);
1241 void meshlink_stop(meshlink_handle_t *mesh) {
1242 logger(mesh, MESHLINK_DEBUG, "meshlink_stop()\n");
1245 meshlink_errno = MESHLINK_EINVAL;
1249 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1253 // Shut down the main thread
1254 event_loop_stop(&mesh->loop);
1256 // TODO: send something to a local socket to kick the event loop
1258 if(mesh->threadstarted) {
1259 // Wait for the main thread to finish
1260 pthread_mutex_unlock(&mesh->mutex);
1262 if(pthread_join(mesh->thread, NULL) != 0) {
1266 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1270 mesh->threadstarted = false;
1273 // Close all metaconnections
1274 if(mesh->connections) {
1275 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1277 connection_t *c = node->data;
1279 terminate_connection(mesh, c, false);
1283 exit_outgoings(mesh);
1285 // Try to write out any changed node config files, ignore errors at this point.
1287 for splay_each(node_t, n, mesh->nodes) {
1288 if(n->status.dirty) {
1289 if(!node_write_config(mesh, n, false)) {
1296 pthread_mutex_unlock(&mesh->mutex);
1299 void meshlink_close(meshlink_handle_t *mesh) {
1300 logger(mesh, MESHLINK_DEBUG, "meshlink_close()\n");
1303 meshlink_errno = MESHLINK_EINVAL;
1307 // stop can be called even if mesh has not been started
1308 meshlink_stop(mesh);
1310 // lock is not released after this
1311 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1315 // Close and free all resources used.
1317 close_network_connections(mesh);
1319 logger(mesh, MESHLINK_INFO, "Terminating");
1321 event_loop_exit(&mesh->loop);
1325 if(mesh->confbase) {
1331 if(mesh->netns != -1) {
1335 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1339 meshlink_queue_exit(&mesh->outpacketqueue);
1342 free(mesh->appname);
1343 free(mesh->confbase);
1344 free(mesh->config_key);
1345 free(mesh->external_address_url);
1347 ecdsa_free(mesh->private_key);
1349 main_config_unlock(mesh);
1351 pthread_mutex_unlock(&mesh->mutex);
1352 pthread_mutex_destroy(&mesh->mutex);
1354 memset(mesh, 0, sizeof(*mesh));
1359 bool meshlink_destroy_ex(const meshlink_open_params_t *params) {
1360 logger(NULL, MESHLINK_DEBUG, "meshlink_destroy_ex()\n");
1363 meshlink_errno = MESHLINK_EINVAL;
1367 if(!params->confbase) {
1368 /* Ephemeral instances */
1372 /* Exit early if the confbase directory itself doesn't exist */
1373 if(access(params->confbase, F_OK) && errno == ENOENT) {
1377 /* Take the lock the same way meshlink_open() would. */
1378 FILE *lockfile = fopen(params->lock_filename, "w+");
1381 logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", params->lock_filename, strerror(errno));
1382 meshlink_errno = MESHLINK_ESTORAGE;
1387 fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
1391 // TODO: use _locking()?
1394 if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
1395 logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", params->lock_filename);
1397 meshlink_errno = MESHLINK_EBUSY;
1403 if(!config_destroy(params->confbase, "current") || !config_destroy(params->confbase, "new") || !config_destroy(params->confbase, "old")) {
1404 logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", params->confbase, strerror(errno));
1408 if(unlink(params->lock_filename)) {
1409 logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", params->lock_filename, strerror(errno));
1411 meshlink_errno = MESHLINK_ESTORAGE;
1417 if(!sync_path(params->confbase)) {
1418 logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", params->confbase, strerror(errno));
1419 meshlink_errno = MESHLINK_ESTORAGE;
1426 bool meshlink_destroy(const char *confbase) {
1427 logger(NULL, MESHLINK_DEBUG, "meshlink_destroy(%s)", confbase);
1429 char lock_filename[PATH_MAX];
1430 snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
1432 meshlink_open_params_t params = {
1433 .confbase = (char *)confbase,
1434 .lock_filename = lock_filename,
1437 return meshlink_destroy_ex(¶ms);
1440 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1441 logger(mesh, MESHLINK_DEBUG, "meshlink_set_receive_cb(%p)", (void *)(intptr_t)cb);
1444 meshlink_errno = MESHLINK_EINVAL;
1448 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1452 mesh->receive_cb = cb;
1453 pthread_mutex_unlock(&mesh->mutex);
1456 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1457 logger(mesh, MESHLINK_DEBUG, "meshlink_set_connection_try_cb(%p)", (void *)(intptr_t)cb);
1460 meshlink_errno = MESHLINK_EINVAL;
1464 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1468 mesh->connection_try_cb = cb;
1469 pthread_mutex_unlock(&mesh->mutex);
1472 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1473 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_status_cb(%p)", (void *)(intptr_t)cb);
1476 meshlink_errno = MESHLINK_EINVAL;
1480 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1484 mesh->node_status_cb = cb;
1485 pthread_mutex_unlock(&mesh->mutex);
1488 void meshlink_set_node_pmtu_cb(meshlink_handle_t *mesh, meshlink_node_pmtu_cb_t cb) {
1489 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_pmtu_cb(%p)", (void *)(intptr_t)cb);
1492 meshlink_errno = MESHLINK_EINVAL;
1496 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1500 mesh->node_pmtu_cb = cb;
1501 pthread_mutex_unlock(&mesh->mutex);
1504 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1505 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_duplicate_cb(%p)", (void *)(intptr_t)cb);
1508 meshlink_errno = MESHLINK_EINVAL;
1512 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1516 mesh->node_duplicate_cb = cb;
1517 pthread_mutex_unlock(&mesh->mutex);
1520 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1521 logger(mesh, MESHLINK_DEBUG, "meshlink_set_log_cb(%p)", (void *)(intptr_t)cb);
1524 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1529 mesh->log_level = cb ? level : 0;
1530 pthread_mutex_unlock(&mesh->mutex);
1533 global_log_level = cb ? level : 0;
1537 void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
1538 logger(mesh, MESHLINK_DEBUG, "meshlink_set_error_cb(%p)", (void *)(intptr_t)cb);
1541 meshlink_errno = MESHLINK_EINVAL;
1545 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1549 mesh->error_cb = cb;
1550 pthread_mutex_unlock(&mesh->mutex);
1553 static bool prepare_packet(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len, vpn_packet_t *packet) {
1554 meshlink_packethdr_t *hdr;
1556 if(len > MAXSIZE - sizeof(*hdr)) {
1557 meshlink_errno = MESHLINK_EINVAL;
1561 node_t *n = (node_t *)destination;
1563 if(n->status.blacklisted) {
1564 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1565 meshlink_errno = MESHLINK_EBLACKLISTED;
1569 // Prepare the packet
1570 packet->probe = false;
1571 packet->tcp = false;
1572 packet->len = len + sizeof(*hdr);
1574 hdr = (meshlink_packethdr_t *)packet->data;
1575 memset(hdr, 0, sizeof(*hdr));
1576 // leave the last byte as 0 to make sure strings are always
1577 // null-terminated if they are longer than the buffer
1578 strncpy((char *)hdr->destination, destination->name, sizeof(hdr->destination) - 1);
1579 strncpy((char *)hdr->source, mesh->self->name, sizeof(hdr->source) - 1);
1581 memcpy(packet->data + sizeof(*hdr), data, len);
1586 static bool meshlink_send_immediate(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1588 assert(destination);
1592 // Prepare the packet
1593 if(!prepare_packet(mesh, destination, data, len, mesh->packet)) {
1597 // Send it immediately
1598 route(mesh, mesh->self, mesh->packet);
1603 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1604 logger(mesh, MESHLINK_DEBUG, "meshlink_send(%s, %p, %zu)", destination ? destination->name : "(null)", data, len);
1606 // Validate arguments
1607 if(!mesh || !destination) {
1608 meshlink_errno = MESHLINK_EINVAL;
1617 meshlink_errno = MESHLINK_EINVAL;
1621 // Prepare the packet
1622 vpn_packet_t *packet = malloc(sizeof(*packet));
1625 meshlink_errno = MESHLINK_ENOMEM;
1629 if(!prepare_packet(mesh, destination, data, len, packet)) {
1635 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1637 meshlink_errno = MESHLINK_ENOMEM;
1641 logger(mesh, MESHLINK_DEBUG, "Adding packet of %zu bytes to packet queue", len);
1643 // Notify event loop
1644 signal_trigger(&mesh->loop, &mesh->datafromapp);
1649 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
1651 meshlink_handle_t *mesh = data;
1653 logger(mesh, MESHLINK_DEBUG, "Flushing the packet queue");
1655 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1656 logger(mesh, MESHLINK_DEBUG, "Removing packet of %d bytes from packet queue", packet->len);
1657 mesh->self->in_packets++;
1658 mesh->self->in_bytes += packet->len;
1659 route(mesh, mesh->self, packet);
1664 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1665 if(!mesh || !destination) {
1666 meshlink_errno = MESHLINK_EINVAL;
1670 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1674 node_t *n = (node_t *)destination;
1676 if(!n->status.reachable) {
1677 pthread_mutex_unlock(&mesh->mutex);
1680 } else if(n->mtuprobes > 30 && n->minmtu) {
1681 pthread_mutex_unlock(&mesh->mutex);
1684 pthread_mutex_unlock(&mesh->mutex);
1689 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1690 if(!mesh || !node) {
1691 meshlink_errno = MESHLINK_EINVAL;
1695 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1699 node_t *n = (node_t *)node;
1701 if(!node_read_public_key(mesh, n) || !n->ecdsa) {
1702 meshlink_errno = MESHLINK_EINTERNAL;
1703 pthread_mutex_unlock(&mesh->mutex);
1707 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1710 meshlink_errno = MESHLINK_EINTERNAL;
1713 pthread_mutex_unlock(&mesh->mutex);
1717 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1719 meshlink_errno = MESHLINK_EINVAL;
1723 return (meshlink_node_t *)mesh->self;
1726 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1727 if(!mesh || !name) {
1728 meshlink_errno = MESHLINK_EINVAL;
1734 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1738 n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1739 pthread_mutex_unlock(&mesh->mutex);
1742 meshlink_errno = MESHLINK_ENOENT;
1745 return (meshlink_node_t *)n;
1748 meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
1749 if(!mesh || !name) {
1750 meshlink_errno = MESHLINK_EINVAL;
1754 meshlink_submesh_t *submesh = NULL;
1756 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1760 submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
1761 pthread_mutex_unlock(&mesh->mutex);
1764 meshlink_errno = MESHLINK_ENOENT;
1770 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1771 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1772 meshlink_errno = MESHLINK_EINVAL;
1776 meshlink_node_t **result;
1779 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1783 *nmemb = mesh->nodes->count;
1784 result = realloc(nodes, *nmemb * sizeof(*nodes));
1787 meshlink_node_t **p = result;
1789 for splay_each(node_t, n, mesh->nodes) {
1790 *p++ = (meshlink_node_t *)n;
1795 meshlink_errno = MESHLINK_ENOMEM;
1798 pthread_mutex_unlock(&mesh->mutex);
1803 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) {
1804 meshlink_node_t **result;
1806 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1812 for splay_each(node_t, n, mesh->nodes) {
1813 if(search_node(n, condition)) {
1820 pthread_mutex_unlock(&mesh->mutex);
1824 result = realloc(nodes, *nmemb * sizeof(*nodes));
1827 meshlink_node_t **p = result;
1829 for splay_each(node_t, n, mesh->nodes) {
1830 if(search_node(n, condition)) {
1831 *p++ = (meshlink_node_t *)n;
1837 meshlink_errno = MESHLINK_ENOMEM;
1840 pthread_mutex_unlock(&mesh->mutex);
1845 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
1846 dev_class_t *devclass = (dev_class_t *)condition;
1848 if(*devclass == (dev_class_t)node->devclass) {
1855 static bool search_node_by_submesh(const node_t *node, const void *condition) {
1856 if(condition == node->submesh) {
1868 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) {
1869 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT || !nmemb) {
1870 meshlink_errno = MESHLINK_EINVAL;
1874 return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
1877 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
1878 if(!mesh || !submesh || !nmemb) {
1879 meshlink_errno = MESHLINK_EINVAL;
1883 return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
1886 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
1887 if(!mesh || !node) {
1888 meshlink_errno = MESHLINK_EINVAL;
1892 dev_class_t devclass;
1894 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1898 devclass = ((node_t *)node)->devclass;
1900 pthread_mutex_unlock(&mesh->mutex);
1905 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
1906 if(!mesh || !node) {
1907 meshlink_errno = MESHLINK_EINVAL;
1911 node_t *n = (node_t *)node;
1913 meshlink_submesh_t *s;
1915 s = (meshlink_submesh_t *)n->submesh;
1920 bool meshlink_get_node_reachability(struct meshlink_handle *mesh, struct meshlink_node *node, time_t *last_reachable, time_t *last_unreachable) {
1921 if(!mesh || !node) {
1922 meshlink_errno = MESHLINK_EINVAL;
1926 node_t *n = (node_t *)node;
1929 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1933 reachable = n->status.reachable && !n->status.blacklisted;
1935 // TODO: handle reachable times?
1936 (void)last_reachable;
1937 (void)last_unreachable;
1939 pthread_mutex_unlock(&mesh->mutex);
1944 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1945 logger(mesh, MESHLINK_DEBUG, "meshlink_sign(%p, %zu, %p, %p)", data, len, signature, (void *)siglen);
1947 if(!mesh || !data || !len || !signature || !siglen) {
1948 meshlink_errno = MESHLINK_EINVAL;
1952 if(*siglen < MESHLINK_SIGLEN) {
1953 meshlink_errno = MESHLINK_EINVAL;
1957 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1961 if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
1962 meshlink_errno = MESHLINK_EINTERNAL;
1963 pthread_mutex_unlock(&mesh->mutex);
1967 *siglen = MESHLINK_SIGLEN;
1968 pthread_mutex_unlock(&mesh->mutex);
1972 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1973 logger(mesh, MESHLINK_DEBUG, "meshlink_verify(%p, %zu, %p, %zu)", data, len, signature, siglen);
1975 if(!mesh || !source || !data || !len || !signature) {
1976 meshlink_errno = MESHLINK_EINVAL;
1980 if(siglen != MESHLINK_SIGLEN) {
1981 meshlink_errno = MESHLINK_EINVAL;
1985 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1991 struct node_t *n = (struct node_t *)source;
1993 if(!node_read_public_key(mesh, n)) {
1994 meshlink_errno = MESHLINK_EINTERNAL;
1997 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
2000 pthread_mutex_unlock(&mesh->mutex);
2004 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2005 logger(mesh, MESHLINK_DEBUG, "meshlink_set_canonical_address(%s, %s, %s)", node ? node->name : "(null)", address ? address : "(null)", port ? port : "(null)");
2007 if(!mesh || !node || !address) {
2008 meshlink_errno = MESHLINK_EINVAL;
2012 if(!is_valid_hostname(address)) {
2013 logger(mesh, MESHLINK_ERROR, "Invalid character in address: %s", address);
2014 meshlink_errno = MESHLINK_EINVAL;
2018 if((node_t *)node != mesh->self && !port) {
2019 logger(mesh, MESHLINK_ERROR, "Missing port number!");
2020 meshlink_errno = MESHLINK_EINVAL;
2025 if(port && !is_valid_port(port)) {
2026 logger(mesh, MESHLINK_ERROR, "Invalid character in port: %s", address);
2027 meshlink_errno = MESHLINK_EINVAL;
2031 char *canonical_address;
2033 xasprintf(&canonical_address, "%s %s", address, port ? port : mesh->myport);
2035 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2039 node_t *n = (node_t *)node;
2040 free(n->canonical_address);
2041 n->canonical_address = canonical_address;
2043 if(!node_write_config(mesh, n, false)) {
2044 pthread_mutex_unlock(&mesh->mutex);
2048 pthread_mutex_unlock(&mesh->mutex);
2050 return config_sync(mesh, "current");
2053 bool meshlink_clear_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node) {
2054 logger(mesh, MESHLINK_DEBUG, "meshlink_clear_canonical_address(%s)", node ? node->name : "(null)");
2056 if(!mesh || !node) {
2057 meshlink_errno = MESHLINK_EINVAL;
2061 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2065 node_t *n = (node_t *)node;
2066 free(n->canonical_address);
2067 n->canonical_address = NULL;
2069 if(!node_write_config(mesh, n, false)) {
2070 pthread_mutex_unlock(&mesh->mutex);
2074 pthread_mutex_unlock(&mesh->mutex);
2076 return config_sync(mesh, "current");
2079 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2080 logger(mesh, MESHLINK_DEBUG, "meshlink_join(%s)", invitation ? invitation : "(null)");
2082 if(!mesh || !invitation) {
2083 meshlink_errno = MESHLINK_EINVAL;
2087 if(mesh->storage_policy == MESHLINK_STORAGE_DISABLED) {
2088 meshlink_errno = MESHLINK_EINVAL;
2092 join_state_t state = {
2097 ecdsa_t *key = NULL;
2098 ecdsa_t *hiskey = NULL;
2100 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2101 char copy[strlen(invitation) + 1];
2103 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2107 //Before doing meshlink_join make sure we are not connected to another mesh
2108 if(mesh->threadstarted) {
2109 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
2110 meshlink_errno = MESHLINK_EINVAL;
2114 // 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.
2115 if(mesh->nodes->count > 1) {
2116 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
2117 meshlink_errno = MESHLINK_EINVAL;
2121 strcpy(copy, invitation);
2123 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2125 char *slash = strchr(copy, '/');
2133 if(strlen(slash) != 48) {
2137 char *address = copy;
2140 if(!b64decode(slash, state.hash, 18) || !b64decode(slash + 24, state.cookie, 18)) {
2144 if(mesh->inviter_commits_first) {
2145 memcpy(state.cookie + 18, ecdsa_get_public_key(mesh->private_key), 32);
2148 // Generate a throw-away key for the invitation.
2149 key = ecdsa_generate();
2152 meshlink_errno = MESHLINK_EINTERNAL;
2156 char *b64key = ecdsa_get_base64_public_key(key);
2159 while(address && *address) {
2160 // We allow commas in the address part to support multiple addresses in one invitation URL.
2161 comma = strchr(address, ',');
2167 // Split of the port
2168 port = strrchr(address, ':');
2176 // IPv6 address are enclosed in brackets, per RFC 3986
2177 if(*address == '[') {
2179 char *bracket = strchr(address, ']');
2192 // Connect to the meshlink daemon mentioned in the URL.
2193 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2196 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2197 state.sock = socket_in_netns(aip->ai_family, SOCK_STREAM, IPPROTO_TCP, mesh->netns);
2199 if(state.sock == -1) {
2200 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2201 meshlink_errno = MESHLINK_ENETWORK;
2207 setsockopt(state.sock, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe));
2210 set_timeout(state.sock, 5000);
2212 if(connect(state.sock, aip->ai_addr, aip->ai_addrlen)) {
2213 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2214 meshlink_errno = MESHLINK_ENETWORK;
2215 closesocket(state.sock);
2225 meshlink_errno = MESHLINK_ERESOLV;
2228 if(state.sock != -1 || !comma) {
2235 if(state.sock == -1) {
2239 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2241 // Tell him we have an invitation, and give him our throw-away key.
2245 if(!sendline(state.sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
2246 logger(mesh, MESHLINK_ERROR, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2247 meshlink_errno = MESHLINK_ENETWORK;
2253 char hisname[4096] = "";
2254 int code, hismajor, hisminor = 0;
2256 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) {
2257 logger(mesh, MESHLINK_ERROR, "Cannot read greeting from peer\n");
2258 meshlink_errno = MESHLINK_ENETWORK;
2262 // Check if the hash of the key he gave us matches the hash in the URL.
2263 char *fingerprint = state.line + 2;
2266 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2267 logger(mesh, MESHLINK_ERROR, "Could not create hash\n%s\n", state.line + 2);
2268 meshlink_errno = MESHLINK_EINTERNAL;
2272 if(memcmp(hishash, state.hash, 18)) {
2273 logger(mesh, MESHLINK_ERROR, "Peer has an invalid key!\n%s\n", state.line + 2);
2274 meshlink_errno = MESHLINK_EPEER;
2278 hiskey = ecdsa_set_base64_public_key(fingerprint);
2281 meshlink_errno = MESHLINK_EINTERNAL;
2285 // Start an SPTPS session
2286 if(!sptps_start(&state.sptps, &state, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2287 meshlink_errno = MESHLINK_EINTERNAL;
2291 // Feed rest of input buffer to SPTPS
2292 if(!sptps_receive_data(&state.sptps, state.buffer, state.blen)) {
2293 meshlink_errno = MESHLINK_EPEER;
2298 logger(mesh, MESHLINK_DEBUG, "Starting invitation recv loop: %d %zu\n", state.sock, sizeof(state.line));
2300 while((len = recv(state.sock, state.line, sizeof(state.line), 0))) {
2302 if(errno == EINTR) {
2306 logger(mesh, MESHLINK_ERROR, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2307 meshlink_errno = MESHLINK_ENETWORK;
2311 if(!sptps_receive_data(&state.sptps, state.line, len)) {
2312 meshlink_errno = MESHLINK_EPEER;
2317 if(!state.success) {
2318 logger(mesh, MESHLINK_ERROR, "Connection closed by peer, invitation cancelled.\n");
2319 meshlink_errno = MESHLINK_EPEER;
2323 sptps_stop(&state.sptps);
2326 closesocket(state.sock);
2328 pthread_mutex_unlock(&mesh->mutex);
2332 logger(mesh, MESHLINK_ERROR, "Invalid invitation URL\n");
2333 meshlink_errno = MESHLINK_EINVAL;
2335 sptps_stop(&state.sptps);
2339 if(state.sock != -1) {
2340 closesocket(state.sock);
2343 pthread_mutex_unlock(&mesh->mutex);
2347 char *meshlink_export(meshlink_handle_t *mesh) {
2349 meshlink_errno = MESHLINK_EINVAL;
2353 // Create a config file on the fly.
2356 packmsg_output_t out = {buf, sizeof(buf)};
2357 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
2358 packmsg_add_str(&out, mesh->name);
2359 packmsg_add_str(&out, CORE_MESH);
2361 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2365 packmsg_add_int32(&out, mesh->self->devclass);
2366 packmsg_add_bool(&out, mesh->self->status.blacklisted);
2367 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2369 if(mesh->self->canonical_address && !strchr(mesh->self->canonical_address, ' ')) {
2370 char *canonical_address = NULL;
2371 xasprintf(&canonical_address, "%s %s", mesh->self->canonical_address, mesh->myport);
2372 packmsg_add_str(&out, canonical_address);
2373 free(canonical_address);
2375 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2380 for(uint32_t i = 0; i < MAX_RECENT; i++) {
2381 if(mesh->self->recent[i].sa.sa_family) {
2388 packmsg_add_array(&out, count);
2390 for(uint32_t i = 0; i < count; i++) {
2391 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2394 packmsg_add_int64(&out, 0);
2395 packmsg_add_int64(&out, 0);
2397 pthread_mutex_unlock(&mesh->mutex);
2399 if(!packmsg_output_ok(&out)) {
2400 logger(mesh, MESHLINK_ERROR, "Error creating export data\n");
2401 meshlink_errno = MESHLINK_EINTERNAL;
2405 // Prepare a base64-encoded packmsg array containing our config file
2407 uint32_t len = packmsg_output_size(&out, buf);
2408 uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2409 uint8_t *buf2 = xmalloc(len2);
2410 packmsg_output_t out2 = {buf2, len2};
2411 packmsg_add_array(&out2, 1);
2412 packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2414 if(!packmsg_output_ok(&out2)) {
2415 logger(mesh, MESHLINK_ERROR, "Error creating export data\n");
2416 meshlink_errno = MESHLINK_EINTERNAL;
2421 b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2423 return (char *)buf2;
2426 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2427 logger(mesh, MESHLINK_DEBUG, "meshlink_import(%p)", (const void *)data);
2429 if(!mesh || !data) {
2430 meshlink_errno = MESHLINK_EINVAL;
2434 size_t datalen = strlen(data);
2435 uint8_t *buf = xmalloc(datalen);
2436 int buflen = b64decode(data, buf, datalen);
2439 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2441 meshlink_errno = MESHLINK_EPEER;
2445 packmsg_input_t in = {buf, buflen};
2446 uint32_t count = packmsg_get_array(&in);
2449 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2451 meshlink_errno = MESHLINK_EPEER;
2455 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2461 uint32_t len2 = packmsg_get_bin_raw(&in, &data2);
2467 packmsg_input_t in2 = {data2, len2};
2468 uint32_t version = packmsg_get_uint32(&in2);
2469 char *name = packmsg_get_str_dup(&in2);
2471 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
2473 packmsg_input_invalidate(&in);
2477 if(!check_id(name)) {
2482 node_t *n = lookup_node(mesh, name);
2485 logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
2493 config_t config = {data2, len2};
2495 if(!node_read_from_config(mesh, n, &config)) {
2497 packmsg_input_invalidate(&in);
2501 if(!node_write_config(mesh, n, true)) {
2510 pthread_mutex_unlock(&mesh->mutex);
2514 if(!packmsg_done(&in)) {
2515 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2516 meshlink_errno = MESHLINK_EPEER;
2520 if(!config_sync(mesh, "current")) {
2527 bool meshlink_forget_node(meshlink_handle_t *mesh, meshlink_node_t *node) {
2528 logger(mesh, MESHLINK_DEBUG, "meshlink_forget_node(%s)", node ? node->name : "(null)");
2530 if(!mesh || !node) {
2531 meshlink_errno = MESHLINK_EINVAL;
2535 node_t *n = (node_t *)node;
2537 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2541 /* Check that the node is not reachable */
2542 if(n->status.reachable || n->connection) {
2543 pthread_mutex_unlock(&mesh->mutex);
2544 logger(mesh, MESHLINK_WARNING, "Could not forget %s: still reachable", n->name);
2548 /* Check that we don't have any active UTCP connections */
2549 if(n->utcp && utcp_is_active(n->utcp)) {
2550 pthread_mutex_unlock(&mesh->mutex);
2551 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active UTCP connections", n->name);
2555 /* Check that we have no active connections to this node */
2556 for list_each(connection_t, c, mesh->connections) {
2558 pthread_mutex_unlock(&mesh->mutex);
2559 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active connection", n->name);
2564 /* Remove any pending outgoings to this node */
2565 if(mesh->outgoings) {
2566 for list_each(outgoing_t, outgoing, mesh->outgoings) {
2567 if(outgoing->node == n) {
2568 list_delete_node(mesh->outgoings, list_node);
2573 /* Delete the config file for this node */
2574 if(!config_delete(mesh, "current", n->name)) {
2575 pthread_mutex_unlock(&mesh->mutex);
2579 /* Delete the node struct and any remaining edges referencing this node */
2582 pthread_mutex_unlock(&mesh->mutex);
2584 return config_sync(mesh, "current");
2587 /* Hint that a hostname may be found at an address
2588 * See header file for detailed comment.
2590 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2591 logger(mesh, MESHLINK_DEBUG, "meshlink_hint_address(%s, %p)", node ? node->name : "(null)", (const void *)addr);
2593 if(!mesh || !node || !addr) {
2594 meshlink_errno = EINVAL;
2598 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2602 node_t *n = (node_t *)node;
2604 if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
2605 if(!node_write_config(mesh, n, false)) {
2606 logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
2610 pthread_mutex_unlock(&mesh->mutex);
2611 // @TODO do we want to fire off a connection attempt right away?
2614 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2616 node_t *n = utcp->priv;
2617 meshlink_handle_t *mesh = n->mesh;
2619 if(mesh->channel_accept_cb && mesh->channel_listen_cb) {
2620 return mesh->channel_listen_cb(mesh, (meshlink_node_t *)n, port);
2622 return mesh->channel_accept_cb;
2626 /* Finish one AIO buffer, return true if the channel is still open. */
2627 static bool aio_finish_one(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t **head) {
2628 meshlink_aio_buffer_t *aio = *head;
2632 channel->in_callback = true;
2635 if(aio->cb.buffer) {
2636 aio->cb.buffer(mesh, channel, aio->data, aio->done, aio->priv);
2640 aio->cb.fd(mesh, channel, aio->fd, aio->done, aio->priv);
2644 channel->in_callback = false;
2657 /* Finish all AIO buffers, return true if the channel is still open. */
2658 static bool aio_abort(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t **head) {
2660 if(!aio_finish_one(mesh, channel, head)) {
2668 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2669 meshlink_channel_t *channel = connection->priv;
2675 node_t *n = channel->node;
2676 meshlink_handle_t *mesh = n->mesh;
2678 if(n->status.destroyed) {
2679 meshlink_channel_close(mesh, channel);
2683 const char *p = data;
2686 while(channel->aio_receive) {
2688 /* This receive callback signalled an error, abort all outstanding AIO buffers. */
2689 if(!aio_abort(mesh, channel, &channel->aio_receive)) {
2696 meshlink_aio_buffer_t *aio = channel->aio_receive;
2697 size_t todo = aio->len - aio->done;
2704 memcpy((char *)aio->data + aio->done, p, todo);
2706 ssize_t result = write(aio->fd, p, todo);
2709 if(result < 0 && errno == EINTR) {
2713 /* Writing to fd failed, cancel just this AIO buffer. */
2714 logger(mesh, MESHLINK_ERROR, "Writing to AIO fd %d failed: %s", aio->fd, strerror(errno));
2716 if(!aio_finish_one(mesh, channel, &channel->aio_receive)) {
2730 if(aio->done == aio->len) {
2731 if(!aio_finish_one(mesh, channel, &channel->aio_receive)) {
2741 if(channel->receive_cb) {
2742 channel->receive_cb(mesh, channel, p, left);
2748 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2749 node_t *n = utcp_connection->utcp->priv;
2755 meshlink_handle_t *mesh = n->mesh;
2757 if(!mesh->channel_accept_cb) {
2761 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2763 channel->c = utcp_connection;
2765 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2766 utcp_accept(utcp_connection, channel_recv, channel);
2772 static void channel_retransmit(struct utcp_connection *utcp_connection) {
2773 node_t *n = utcp_connection->utcp->priv;
2774 meshlink_handle_t *mesh = n->mesh;
2776 if(n->mtuprobes == 31 && n->mtutimeout.cb) {
2777 timeout_set(&mesh->loop, &n->mtutimeout, &(struct timespec) {
2783 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2784 node_t *n = utcp->priv;
2786 if(n->status.destroyed) {
2790 meshlink_handle_t *mesh = n->mesh;
2791 return meshlink_send_immediate(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2794 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2795 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_receive_cb(%p, %p)", (void *)channel, (void *)(intptr_t)cb);
2797 if(!mesh || !channel) {
2798 meshlink_errno = MESHLINK_EINVAL;
2802 channel->receive_cb = cb;
2805 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2807 node_t *n = (node_t *)source;
2813 utcp_recv(n->utcp, data, len);
2816 static void channel_poll(struct utcp_connection *connection, size_t len) {
2817 meshlink_channel_t *channel = connection->priv;
2823 node_t *n = channel->node;
2824 meshlink_handle_t *mesh = n->mesh;
2826 while(channel->aio_send) {
2828 /* This poll callback signalled an error, abort all outstanding AIO buffers. */
2829 if(!aio_abort(mesh, channel, &channel->aio_send)) {
2836 /* We have at least one AIO buffer. Send as much as possible from the buffers. */
2837 meshlink_aio_buffer_t *aio = channel->aio_send;
2838 size_t todo = aio->len - aio->done;
2846 sent = utcp_send(connection, (char *)aio->data + aio->done, todo);
2848 /* Limit the amount we read at once to avoid stack overflows */
2854 ssize_t result = read(aio->fd, buf, todo);
2858 sent = utcp_send(connection, buf, todo);
2860 if(result < 0 && errno == EINTR) {
2864 /* Reading from fd failed, cancel just this AIO buffer. */
2866 logger(mesh, MESHLINK_ERROR, "Reading from AIO fd %d failed: %s", aio->fd, strerror(errno));
2869 if(!aio_finish_one(mesh, channel, &channel->aio_send)) {
2877 if(sent != (ssize_t)todo) {
2878 /* Sending failed, abort all outstanding AIO buffers and send a poll callback. */
2879 if(!aio_abort(mesh, channel, &channel->aio_send)) {
2890 /* If we didn't finish this buffer, exit early. */
2891 if(aio->done < aio->len) {
2895 /* Signal completion of this buffer, and go to the next one. */
2896 if(!aio_finish_one(mesh, channel, &channel->aio_send)) {
2905 if(channel->poll_cb) {
2906 channel->poll_cb(mesh, channel, len);
2908 utcp_set_poll_cb(connection, NULL);
2912 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2913 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_poll_cb(%p, %p)", (void *)channel, (void *)(intptr_t)cb);
2915 if(!mesh || !channel) {
2916 meshlink_errno = MESHLINK_EINVAL;
2920 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2924 channel->poll_cb = cb;
2925 utcp_set_poll_cb(channel->c, (cb || channel->aio_send) ? channel_poll : NULL);
2926 pthread_mutex_unlock(&mesh->mutex);
2929 void meshlink_set_channel_listen_cb(meshlink_handle_t *mesh, meshlink_channel_listen_cb_t cb) {
2930 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_listen_cb(%p)", (void *)(intptr_t)cb);
2933 meshlink_errno = MESHLINK_EINVAL;
2937 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2941 mesh->channel_listen_cb = cb;
2943 pthread_mutex_unlock(&mesh->mutex);
2946 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2947 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_accept_cb(%p)", (void *)(intptr_t)cb);
2950 meshlink_errno = MESHLINK_EINVAL;
2954 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2958 mesh->channel_accept_cb = cb;
2959 mesh->receive_cb = channel_receive;
2961 for splay_each(node_t, n, mesh->nodes) {
2962 if(!n->utcp && n != mesh->self) {
2963 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2964 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
2965 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
2969 pthread_mutex_unlock(&mesh->mutex);
2972 void meshlink_set_channel_sndbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
2973 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_sndbuf(%p, %zu)", (void *)channel, size);
2975 meshlink_set_channel_sndbuf_storage(mesh, channel, NULL, size);
2978 void meshlink_set_channel_rcvbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
2979 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_rcvbuf(%p, %zu)", (void *)channel, size);
2981 meshlink_set_channel_rcvbuf_storage(mesh, channel, NULL, size);
2984 void meshlink_set_channel_sndbuf_storage(meshlink_handle_t *mesh, meshlink_channel_t *channel, void *buf, size_t size) {
2985 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_sndbuf_storage(%p, %p, %zu)", (void *)channel, buf, size);
2987 if(!mesh || !channel) {
2988 meshlink_errno = MESHLINK_EINVAL;
2992 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2996 utcp_set_sndbuf(channel->c, buf, size);
2997 pthread_mutex_unlock(&mesh->mutex);
3000 void meshlink_set_channel_rcvbuf_storage(meshlink_handle_t *mesh, meshlink_channel_t *channel, void *buf, size_t size) {
3001 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_rcvbuf_storage(%p, %p, %zu)", (void *)channel, buf, size);
3003 if(!mesh || !channel) {
3004 meshlink_errno = MESHLINK_EINVAL;
3008 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3012 utcp_set_rcvbuf(channel->c, buf, size);
3013 pthread_mutex_unlock(&mesh->mutex);
3016 void meshlink_set_channel_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel, uint32_t flags) {
3017 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_flags(%p, %u)", (void *)channel, flags);
3019 if(!mesh || !channel) {
3020 meshlink_errno = MESHLINK_EINVAL;
3024 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3028 utcp_set_flags(channel->c, flags);
3029 pthread_mutex_unlock(&mesh->mutex);
3032 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) {
3033 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);
3036 abort(); // TODO: handle non-NULL data
3039 if(!mesh || !node) {
3040 meshlink_errno = MESHLINK_EINVAL;
3044 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3048 node_t *n = (node_t *)node;
3051 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3052 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
3053 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
3054 mesh->receive_cb = channel_receive;
3057 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3058 pthread_mutex_unlock(&mesh->mutex);
3063 if(n->status.blacklisted) {
3064 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
3065 meshlink_errno = MESHLINK_EBLACKLISTED;
3066 pthread_mutex_unlock(&mesh->mutex);
3070 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3072 channel->receive_cb = cb;
3075 channel->priv = (void *)data;
3078 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
3080 pthread_mutex_unlock(&mesh->mutex);
3083 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3091 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) {
3092 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_open_ex(%s, %u, %p, %p, %zu)", node ? node->name : "(null)", port, (void *)(intptr_t)cb, data, len);
3094 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3097 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3098 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_shutdown(%p, %d)", (void *)channel, direction);
3100 if(!mesh || !channel) {
3101 meshlink_errno = MESHLINK_EINVAL;
3105 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3109 utcp_shutdown(channel->c, direction);
3110 pthread_mutex_unlock(&mesh->mutex);
3113 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3114 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_close(%p)", (void *)channel);
3116 if(!mesh || !channel) {
3117 meshlink_errno = MESHLINK_EINVAL;
3121 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3126 utcp_close(channel->c);
3129 /* Clean up any outstanding AIO buffers. */
3130 aio_abort(mesh, channel, &channel->aio_send);
3131 aio_abort(mesh, channel, &channel->aio_receive);
3134 if(!channel->in_callback) {
3138 pthread_mutex_unlock(&mesh->mutex);
3141 void meshlink_channel_abort(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3142 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_abort(%p)", (void *)channel);
3144 if(!mesh || !channel) {
3145 meshlink_errno = MESHLINK_EINVAL;
3149 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3154 utcp_abort(channel->c);
3157 /* Clean up any outstanding AIO buffers. */
3158 aio_abort(mesh, channel, &channel->aio_send);
3159 aio_abort(mesh, channel, &channel->aio_receive);
3162 if(!channel->in_callback) {
3166 pthread_mutex_unlock(&mesh->mutex);
3169 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3170 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_send(%p, %p, %zu)", (void *)channel, data, len);
3172 if(!mesh || !channel) {
3173 meshlink_errno = MESHLINK_EINVAL;
3182 meshlink_errno = MESHLINK_EINVAL;
3186 // TODO: more finegrained locking.
3187 // Ideally we want to put the data into the UTCP connection's send buffer.
3188 // Then, preferably only if there is room in the receiver window,
3189 // kick the meshlink thread to go send packets.
3193 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3197 /* Disallow direct calls to utcp_send() while we still have AIO active. */
3198 if(channel->aio_send) {
3201 retval = utcp_send(channel->c, data, len);
3204 pthread_mutex_unlock(&mesh->mutex);
3207 meshlink_errno = MESHLINK_ENETWORK;
3213 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) {
3214 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_send(%p, %p, %zu, %p, %p)", (void *)channel, data, len, (void *)(intptr_t)cb, priv);
3216 if(!mesh || !channel) {
3217 meshlink_errno = MESHLINK_EINVAL;
3222 meshlink_errno = MESHLINK_EINVAL;
3226 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3229 aio->cb.buffer = cb;
3232 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3236 /* Append the AIO buffer descriptor to the end of the chain */
3237 meshlink_aio_buffer_t **p = &channel->aio_send;
3245 /* Ensure the poll callback is set, and call it right now to push data if possible */
3246 utcp_set_poll_cb(channel->c, channel_poll);
3247 size_t todo = MIN(len, utcp_get_rcvbuf_free(channel->c));
3250 channel_poll(channel->c, todo);
3253 pthread_mutex_unlock(&mesh->mutex);
3258 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) {
3259 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_fd_send(%p, %d, %zu, %p, %p)", (void *)channel, fd, len, (void *)(intptr_t)cb, priv);
3261 if(!mesh || !channel) {
3262 meshlink_errno = MESHLINK_EINVAL;
3266 if(!len || fd == -1) {
3267 meshlink_errno = MESHLINK_EINVAL;
3271 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3277 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3281 /* Append the AIO buffer descriptor to the end of the chain */
3282 meshlink_aio_buffer_t **p = &channel->aio_send;
3290 /* Ensure the poll callback is set, and call it right now to push data if possible */
3291 utcp_set_poll_cb(channel->c, channel_poll);
3292 size_t left = utcp_get_rcvbuf_free(channel->c);
3295 channel_poll(channel->c, left);
3298 pthread_mutex_unlock(&mesh->mutex);
3303 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) {
3304 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_receive(%p, %p, %zu, %p, %p)", (void *)channel, data, len, (void *)(intptr_t)cb, priv);
3306 if(!mesh || !channel) {
3307 meshlink_errno = MESHLINK_EINVAL;
3312 meshlink_errno = MESHLINK_EINVAL;
3316 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3319 aio->cb.buffer = cb;
3322 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3326 /* Append the AIO buffer descriptor to the end of the chain */
3327 meshlink_aio_buffer_t **p = &channel->aio_receive;
3335 pthread_mutex_unlock(&mesh->mutex);
3340 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) {
3341 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_fd_receive(%p, %d, %zu, %p, %p)", (void *)channel, fd, len, (void *)(intptr_t)cb, priv);
3343 if(!mesh || !channel) {
3344 meshlink_errno = MESHLINK_EINVAL;
3348 if(!len || fd == -1) {
3349 meshlink_errno = MESHLINK_EINVAL;
3353 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3359 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3363 /* Append the AIO buffer descriptor to the end of the chain */
3364 meshlink_aio_buffer_t **p = &channel->aio_receive;
3372 pthread_mutex_unlock(&mesh->mutex);
3377 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3378 if(!mesh || !channel) {
3379 meshlink_errno = MESHLINK_EINVAL;
3383 return channel->c->flags;
3386 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3387 if(!mesh || !channel) {
3388 meshlink_errno = MESHLINK_EINVAL;
3392 return utcp_get_sendq(channel->c);
3395 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3396 if(!mesh || !channel) {
3397 meshlink_errno = MESHLINK_EINVAL;
3401 return utcp_get_recvq(channel->c);
3404 size_t meshlink_channel_get_mss(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3405 if(!mesh || !channel) {
3406 meshlink_errno = MESHLINK_EINVAL;
3410 return utcp_get_mss(channel->node->utcp);
3413 void meshlink_set_node_channel_timeout(meshlink_handle_t *mesh, meshlink_node_t *node, int timeout) {
3414 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_channel_timeout(%s, %d)", node ? node->name : "(null)", timeout);
3416 if(!mesh || !node) {
3417 meshlink_errno = MESHLINK_EINVAL;
3421 node_t *n = (node_t *)node;
3423 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3428 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3429 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
3430 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
3433 utcp_set_user_timeout(n->utcp, timeout);
3435 pthread_mutex_unlock(&mesh->mutex);
3438 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
3439 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
3440 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3441 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
3442 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
3445 if(mesh->node_status_cb) {
3446 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
3449 if(mesh->node_pmtu_cb) {
3450 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3454 void update_node_pmtu(meshlink_handle_t *mesh, node_t *n) {
3455 utcp_set_mtu(n->utcp, (n->minmtu > MINMTU ? n->minmtu : MINMTU) - sizeof(meshlink_packethdr_t));
3457 if(mesh->node_pmtu_cb && !n->status.blacklisted) {
3458 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3462 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
3463 if(!mesh->node_duplicate_cb || n->status.duplicate) {
3467 n->status.duplicate = true;
3468 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
3471 void meshlink_hint_network_change(struct meshlink_handle *mesh) {
3472 logger(mesh, MESHLINK_DEBUG, "meshlink_hint_network_change()");
3475 meshlink_errno = MESHLINK_EINVAL;
3479 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3483 pthread_mutex_unlock(&mesh->mutex);
3486 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
3487 logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_timeouts(%d, %d, %d)", devclass, pinginterval, pingtimeout);
3489 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3490 meshlink_errno = EINVAL;
3494 if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
3495 meshlink_errno = EINVAL;
3499 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3503 mesh->dev_class_traits[devclass].pinginterval = pinginterval;
3504 mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
3505 pthread_mutex_unlock(&mesh->mutex);
3508 void meshlink_set_dev_class_fast_retry_period(meshlink_handle_t *mesh, dev_class_t devclass, int fast_retry_period) {
3509 logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_fast_retry_period(%d, %d)", devclass, fast_retry_period);
3511 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3512 meshlink_errno = EINVAL;
3516 if(fast_retry_period < 0) {
3517 meshlink_errno = EINVAL;
3521 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3525 mesh->dev_class_traits[devclass].fast_retry_period = fast_retry_period;
3526 pthread_mutex_unlock(&mesh->mutex);
3529 void meshlink_set_dev_class_maxtimeout(struct meshlink_handle *mesh, dev_class_t devclass, int maxtimeout) {
3530 logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_fast_maxtimeout(%d, %d)", devclass, maxtimeout);
3532 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3533 meshlink_errno = EINVAL;
3537 if(maxtimeout < 0) {
3538 meshlink_errno = EINVAL;
3542 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3546 mesh->dev_class_traits[devclass].maxtimeout = maxtimeout;
3547 pthread_mutex_unlock(&mesh->mutex);
3550 void meshlink_reset_timers(struct meshlink_handle *mesh) {
3551 logger(mesh, MESHLINK_DEBUG, "meshlink_reset_timers()");
3557 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3561 handle_network_change(mesh, true);
3563 pthread_mutex_unlock(&mesh->mutex);
3566 void meshlink_set_inviter_commits_first(struct meshlink_handle *mesh, bool inviter_commits_first) {
3567 logger(mesh, MESHLINK_DEBUG, "meshlink_set_inviter_commits_first(%d)", inviter_commits_first);
3570 meshlink_errno = EINVAL;
3574 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3578 mesh->inviter_commits_first = inviter_commits_first;
3579 pthread_mutex_unlock(&mesh->mutex);
3582 void meshlink_set_scheduling_granularity(struct meshlink_handle *mesh, long granularity) {
3583 logger(mesh, MESHLINK_DEBUG, "meshlink_set_scheduling_granularity(%ld)", granularity);
3585 if(!mesh || granularity < 0) {
3586 meshlink_errno = EINVAL;
3590 utcp_set_clock_granularity(granularity);
3593 void meshlink_set_storage_policy(struct meshlink_handle *mesh, meshlink_storage_policy_t policy) {
3594 logger(mesh, MESHLINK_DEBUG, "meshlink_set_storage_policy(%d)", policy);
3597 meshlink_errno = EINVAL;
3601 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3605 mesh->storage_policy = policy;
3606 pthread_mutex_unlock(&mesh->mutex);
3609 void handle_network_change(meshlink_handle_t *mesh, bool online) {
3612 if(!mesh->connections || !mesh->loop.running) {
3617 signal_trigger(&mesh->loop, &mesh->datafromapp);
3620 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t cb_errno) {
3621 // We should only call the callback function if we are in the background thread.
3622 if(!mesh->error_cb) {
3626 if(!mesh->threadstarted) {
3630 if(mesh->thread == pthread_self()) {
3631 mesh->error_cb(mesh, cb_errno);
3635 static void __attribute__((constructor)) meshlink_init(void) {
3637 utcp_set_clock_granularity(10000);
3640 static void __attribute__((destructor)) meshlink_exit(void) {