2 meshlink.c -- Implementation of the MeshLink API.
3 Copyright (C) 2014, 2017 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.
19 #define VAR_SERVER 1 /* Should be in meshlink.conf */
20 #define VAR_HOST 2 /* Can be in host config file */
21 #define VAR_MULTIPLE 4 /* Multiple statements allowed */
22 #define VAR_OBSOLETE 8 /* Should not be used anymore */
23 #define VAR_SAFE 16 /* Variable is safe when accepting invitations */
24 #define MAX_ADDRESS_LENGTH 45 /* Max length of an (IPv6) address */
25 #define MAX_PORT_LENGTH 5 /* 0-65535 */
37 #include "meshlink_internal.h"
45 #include "ed25519/sha512.h"
46 #include "discovery.h"
49 #define MSG_NOSIGNAL 0
52 __thread meshlink_errno_t meshlink_errno;
53 meshlink_log_cb_t global_log_cb;
54 meshlink_log_level_t global_log_level;
56 //TODO: this can go away completely
57 const var_t variables[] = {
58 /* Server configuration */
59 {"AddressFamily", VAR_SERVER},
60 {"AutoConnect", VAR_SERVER | VAR_SAFE},
61 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
62 {"BindToInterface", VAR_SERVER},
63 {"Broadcast", VAR_SERVER | VAR_SAFE},
64 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
65 {"DecrementTTL", VAR_SERVER},
66 {"Device", VAR_SERVER},
67 {"DeviceType", VAR_SERVER},
68 {"DirectOnly", VAR_SERVER},
69 {"ECDSAPrivateKeyFile", VAR_SERVER},
70 {"ExperimentalProtocol", VAR_SERVER},
71 {"Forwarding", VAR_SERVER},
72 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
73 {"Hostnames", VAR_SERVER},
74 {"IffOneQueue", VAR_SERVER},
75 {"Interface", VAR_SERVER},
76 {"KeyExpire", VAR_SERVER},
77 {"ListenAddress", VAR_SERVER | VAR_MULTIPLE},
78 {"LocalDiscovery", VAR_SERVER},
79 {"MACExpire", VAR_SERVER},
80 {"MaxConnectionBurst", VAR_SERVER},
81 {"MaxOutputBufferSize", VAR_SERVER},
82 {"MaxTimeout", VAR_SERVER},
83 {"Mode", VAR_SERVER | VAR_SAFE},
85 {"PingInterval", VAR_SERVER},
86 {"PingTimeout", VAR_SERVER},
87 {"PriorityInheritance", VAR_SERVER},
88 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
89 {"PrivateKeyFile", VAR_SERVER},
90 {"ProcessPriority", VAR_SERVER},
91 {"Proxy", VAR_SERVER},
92 {"ReplayWindow", VAR_SERVER},
93 {"ScriptsExtension", VAR_SERVER},
94 {"ScriptsInterpreter", VAR_SERVER},
95 {"StrictSubnets", VAR_SERVER},
96 {"TunnelServer", VAR_SERVER},
97 {"VDEGroup", VAR_SERVER},
98 {"VDEPort", VAR_SERVER},
99 /* Host configuration */
100 {"Address", VAR_HOST | VAR_MULTIPLE},
101 {"Cipher", VAR_SERVER | VAR_HOST},
102 {"ClampMSS", VAR_SERVER | VAR_HOST},
103 {"Compression", VAR_SERVER | VAR_HOST},
104 {"Digest", VAR_SERVER | VAR_HOST},
105 {"ECDSAPublicKey", VAR_HOST},
106 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
107 {"IndirectData", VAR_SERVER | VAR_HOST},
108 {"MACLength", VAR_SERVER | VAR_HOST},
109 {"PMTU", VAR_SERVER | VAR_HOST},
110 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
112 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
113 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
114 {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
115 {"TCPOnly", VAR_SERVER | VAR_HOST},
116 {"Weight", VAR_HOST | VAR_SAFE},
120 static bool fcopy(FILE *out, const char *filename) {
121 FILE *in = fopen(filename, "r");
123 logger(NULL, MESHLINK_ERROR, "Could not open %s: %s\n", filename, strerror(errno));
129 while((len = fread(buf, 1, sizeof buf, in)))
130 fwrite(buf, len, 1, out);
135 static int rstrip(char *value) {
136 int len = strlen(value);
137 while(len && strchr("\t\r\n ", value[len - 1]))
142 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
144 if(!filename || (*hostname && *port))
147 FILE *f = fopen(filename, "r");
151 while(fgets(line, sizeof line, f)) {
155 p += strcspn(p, "\t =");
158 q = p + strspn(p, "\t ");
160 q += 1 + strspn(q + 1, "\t ");
162 p = q + strcspn(q, "\t ");
165 p += strspn(p, "\t ");
166 p[strcspn(p, "\t ")] = 0;
168 if(!*port && !strcasecmp(line, "Port")) {
170 } else if(!*hostname && !strcasecmp(line, "Address")) {
171 *hostname = xstrdup(q);
178 if(*hostname && *port)
184 static char *get_my_hostname(meshlink_handle_t* mesh) {
185 char *hostname = NULL;
187 char *hostport = NULL;
188 char *name = mesh->self->name;
189 char filename[PATH_MAX] = "";
193 // Use first Address statement in own host config file
194 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
195 scan_for_hostname(filename, &hostname, &port);
200 // If that doesn't work, guess externally visible hostname
201 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
202 struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
203 struct addrinfo *aip = ai;
204 static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
207 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
209 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
215 send(s, request, sizeof request - 1, 0);
216 int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
219 if(line[len - 1] == '\n')
221 char *p = strrchr(line, '\n');
223 hostname = xstrdup(p + 1);
236 // Check that the hostname is reasonable
238 for(char *p = hostname; *p; p++) {
239 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
241 // If not, forget it.
251 f = fopen(filename, "a");
253 fprintf(f, "\nAddress = %s\n", hostname);
256 logger(mesh, MESHLINK_DEBUG, "Could not append Address to %s: %s\n", filename, strerror(errno));
261 if(strchr(hostname, ':'))
262 xasprintf(&hostport, "[%s]:%s", hostname, port);
264 xasprintf(&hostport, "%s:%s", hostname, port);
266 if(strchr(hostname, ':'))
267 xasprintf(&hostport, "[%s]", hostname);
269 hostport = xstrdup(hostname);
277 static char *get_line(const char **data) {
286 static char line[1024];
287 const char *end = strchr(*data, '\n');
288 size_t len = end ? end - *data : strlen(*data);
289 if(len >= sizeof line) {
290 logger(NULL, MESHLINK_ERROR, "Maximum line length exceeded!\n");
293 if(len && !isprint(**data))
296 memcpy(line, *data, len);
307 static char *get_value(const char *data, const char *var) {
308 char *line = get_line(&data);
312 char *sep = line + strcspn(line, " \t=");
313 char *val = sep + strspn(sep, " \t");
315 val += 1 + strspn(val + 1, " \t");
317 if(strcasecmp(line, var))
322 static bool try_bind(int port) {
323 struct addrinfo *ai = NULL;
324 struct addrinfo hint = {
325 .ai_flags = AI_PASSIVE,
326 .ai_family = AF_UNSPEC,
327 .ai_socktype = SOCK_STREAM,
328 .ai_protocol = IPPROTO_TCP,
332 snprintf(portstr, sizeof portstr, "%d", port);
334 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
338 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
343 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
356 static int check_port(meshlink_handle_t *mesh) {
357 for(int i = 0; i < 1000; i++) {
358 int port = 0x1000 + (rand() & 0x7fff);
360 char filename[PATH_MAX];
361 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
362 FILE *f = fopen(filename, "a");
364 logger(mesh, MESHLINK_DEBUG, "Please change MeshLink's Port manually.\n");
368 fprintf(f, "Port = %d\n", port);
374 logger(mesh, MESHLINK_DEBUG, "Please change MeshLink's Port manually.\n");
378 static bool finalize_join(meshlink_handle_t *mesh) {
379 char *name = xstrdup(get_value(mesh->data, "Name"));
381 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
385 if(!check_id(name)) {
386 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
390 char filename[PATH_MAX];
391 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
393 FILE *f = fopen(filename, "w");
395 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
399 fprintf(f, "Name = %s\n", name);
401 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
402 FILE *fh = fopen(filename, "w");
404 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
409 // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
410 // Other chunks go unfiltered to their respective host config files
411 const char *p = mesh->data;
414 while((l = get_line(&p))) {
419 // Split line into variable and value
420 int len = strcspn(l, "\t =");
422 value += strspn(value, "\t ");
425 value += strspn(value, "\t ");
430 if(!strcasecmp(l, "Name"))
431 if(strcmp(value, name))
435 else if(!strcasecmp(l, "NetName"))
438 // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
441 for(i = 0; variables[i].name; i++) {
442 if(strcasecmp(l, variables[i].name))
448 // Ignore unknown and unsafe variables
450 logger(mesh, MESHLINK_DEBUG, "Ignoring unknown variable '%s' in invitation.\n", l);
452 } else if(!(variables[i].type & VAR_SAFE)) {
453 logger(mesh, MESHLINK_DEBUG, "Ignoring unsafe variable '%s' in invitation.\n", l);
457 // Copy the safe variable to the right config file
458 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
463 while(l && !strcasecmp(l, "Name")) {
464 if(!check_id(value)) {
465 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation.\n");
469 if(!strcmp(value, name)) {
470 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
474 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
475 f = fopen(filename, "w");
478 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
482 while((l = get_line(&p))) {
483 if(!strcmp(l, "#---------------------------------------------------------------#"))
485 int len = strcspn(l, "\t =");
486 if(len == 4 && !strncasecmp(l, "Name", 4)) {
488 value += strspn(value, "\t ");
491 value += strspn(value, "\t ");
504 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
510 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
511 fprintf(fh, "Port = %s\n", mesh->myport);
515 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
518 free(mesh->self->name);
519 free(mesh->self->connection->name);
520 mesh->self->name = xstrdup(name);
521 mesh->self->connection->name = name;
523 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
525 load_all_nodes(mesh);
530 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
531 meshlink_handle_t* mesh = handle;
533 int result = send(mesh->sock, data, len, 0);
534 if(result == -1 && errno == EINTR)
544 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
545 meshlink_handle_t* mesh = handle;
547 case SPTPS_HANDSHAKE:
548 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof mesh->cookie);
551 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
552 memcpy(mesh->data + mesh->thedatalen, msg, len);
553 mesh->thedatalen += len;
554 mesh->data[mesh->thedatalen] = 0;
558 mesh->thedatalen = 0;
559 return finalize_join(mesh);
562 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
563 shutdown(mesh->sock, SHUT_RDWR);
564 mesh->success = true;
574 static bool recvline(meshlink_handle_t* mesh, size_t len) {
575 char *newline = NULL;
580 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
581 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof mesh->buffer - mesh->blen, 0);
582 if(result == -1 && errno == EINTR)
586 mesh->blen += result;
589 if(newline - mesh->buffer >= len)
592 len = newline - mesh->buffer;
594 memcpy(mesh->line, mesh->buffer, len);
596 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
597 mesh->blen -= len + 1;
601 static bool sendline(int fd, char *format, ...) {
602 static char buffer[4096];
607 va_start(ap, format);
608 blen = vsnprintf(buffer, sizeof buffer, format, ap);
611 if(blen < 1 || blen >= sizeof buffer)
618 int result = send(fd, p, blen, MSG_NOSIGNAL);
619 if(result == -1 && errno == EINTR)
630 static const char *errstr[] = {
631 [MESHLINK_OK] = "No error",
632 [MESHLINK_EINVAL] = "Invalid argument",
633 [MESHLINK_ENOMEM] = "Out of memory",
634 [MESHLINK_ENOENT] = "No such node",
635 [MESHLINK_EEXIST] = "Node already exists",
636 [MESHLINK_EINTERNAL] = "Internal error",
637 [MESHLINK_ERESOLV] = "Could not resolve hostname",
638 [MESHLINK_ESTORAGE] = "Storage error",
639 [MESHLINK_ENETWORK] = "Network error",
640 [MESHLINK_EPEER] = "Error communicating with peer",
643 const char *meshlink_strerror(meshlink_errno_t err) {
644 if(err < 0 || err >= sizeof errstr / sizeof *errstr)
645 return "Invalid error code";
649 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
652 char pubname[PATH_MAX], privname[PATH_MAX];
654 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
656 if(!(key = ecdsa_generate())) {
657 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
658 meshlink_errno = MESHLINK_EINTERNAL;
661 logger(mesh, MESHLINK_DEBUG, "Done.\n");
663 snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
664 f = fopen(privname, "wb");
667 meshlink_errno = MESHLINK_ESTORAGE;
672 fchmod(fileno(f), 0600);
675 if(!ecdsa_write_pem_private_key(key, f)) {
676 logger(mesh, MESHLINK_DEBUG, "Error writing private key!\n");
679 meshlink_errno = MESHLINK_EINTERNAL;
685 snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
686 f = fopen(pubname, "a");
689 meshlink_errno = MESHLINK_ESTORAGE;
693 char *pubkey = ecdsa_get_base64_public_key(key);
694 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
703 static struct timeval idle(event_loop_t *loop, void *data) {
704 meshlink_handle_t *mesh = data;
705 struct timeval t, tmin = {3600, 0};
706 for splay_each(node_t, n, mesh->nodes) {
709 t = utcp_timeout(n->utcp);
710 if(timercmp(&t, &tmin, <))
716 // Find out what local address a socket would use if we connect to the given address.
717 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
718 // of both endpoints, but this will actually not send any UDP packet.
719 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen) {
720 struct addrinfo *rai = NULL;
721 const struct addrinfo hint = {
722 .ai_family = AF_UNSPEC,
723 .ai_socktype = SOCK_DGRAM,
724 .ai_protocol = IPPROTO_UDP,
727 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai)
730 int sock = socket(rai->ai_family, rai->ai_socktype, rai->ai_protocol);
736 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
743 struct sockaddr_storage sn;
744 socklen_t sl = sizeof sn;
746 if(getsockname(sock, (struct sockaddr *)&sn, &sl))
749 if(getnameinfo((struct sockaddr *)&sn, sl, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV))
755 // Get our local address(es) by simulating connecting to an Internet host.
756 static void add_local_addresses(meshlink_handle_t *mesh) {
757 char host[NI_MAXHOST];
758 char entry[MAX_STRING_SIZE];
762 if(getlocaladdrname("93.184.216.34", host, sizeof host)) {
763 snprintf(entry, sizeof entry, "%s %s", host, mesh->myport);
764 append_config_file(mesh, mesh->name, "Address", entry);
769 if(getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", host, sizeof host)) {
770 snprintf(entry, sizeof entry, "%s %s", host, mesh->myport);
771 append_config_file(mesh, mesh->name, "Address", entry);
775 static bool meshlink_setup(meshlink_handle_t *mesh) {
776 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
777 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
778 meshlink_errno = MESHLINK_ESTORAGE;
782 char filename[PATH_MAX];
783 snprintf(filename, sizeof filename, "%s" SLASH "hosts", mesh->confbase);
785 if(mkdir(filename, 0777) && errno != EEXIST) {
786 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
787 meshlink_errno = MESHLINK_ESTORAGE;
791 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
793 if(!access(filename, F_OK)) {
794 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
795 meshlink_errno = MESHLINK_EEXIST;
799 FILE *f = fopen(filename, "w");
801 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
802 meshlink_errno = MESHLINK_ESTORAGE;
806 fprintf(f, "Name = %s\n", mesh->name);
809 if(!ecdsa_keygen(mesh)) {
810 meshlink_errno = MESHLINK_EINTERNAL;
819 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char* appname, dev_class_t devclass) {
820 // Validate arguments provided by the application
821 bool usingname = false;
823 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
825 if(!confbase || !*confbase) {
826 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
827 meshlink_errno = MESHLINK_EINVAL;
831 if(!appname || !*appname) {
832 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
833 meshlink_errno = MESHLINK_EINVAL;
837 if(!name || !*name) {
838 logger(NULL, MESHLINK_ERROR, "No name given!\n");
841 else { //check name only if there is a name != NULL
843 if(!check_id(name)) {
844 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
845 meshlink_errno = MESHLINK_EINVAL;
847 } else { usingname = true;}
850 if(devclass < 0 || devclass > _DEV_CLASS_MAX) {
851 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
852 meshlink_errno = MESHLINK_EINVAL;
856 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
857 mesh->confbase = xstrdup(confbase);
858 mesh->appname = xstrdup(appname);
859 mesh->devclass = devclass;
860 if (usingname) mesh->name = xstrdup(name);
863 pthread_mutexattr_t attr;
864 pthread_mutexattr_init(&attr);
865 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
866 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
868 mesh->threadstarted = false;
869 event_loop_init(&mesh->loop);
870 mesh->loop.data = mesh;
872 // Check whether meshlink.conf already exists
874 char filename[PATH_MAX];
875 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
877 if(access(filename, R_OK)) {
878 if(errno == ENOENT) {
880 if(!meshlink_setup(mesh)) {
881 // meshlink_errno is set by meshlink_setup()
885 logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
886 meshlink_close(mesh);
887 meshlink_errno = MESHLINK_ESTORAGE;
892 // Read the configuration
894 init_configuration(&mesh->config);
896 if(!read_server_config(mesh)) {
897 meshlink_close(mesh);
898 meshlink_errno = MESHLINK_ESTORAGE;
903 struct WSAData wsa_state;
904 WSAStartup(MAKEWORD(2, 2), &wsa_state);
907 // Setup up everything
908 // TODO: we should not open listening sockets yet
910 if(!setup_network(mesh)) {
911 meshlink_close(mesh);
912 meshlink_errno = MESHLINK_ENETWORK;
916 add_local_addresses(mesh);
918 idle_set(&mesh->loop, idle, mesh);
920 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
924 static void *meshlink_main_loop(void *arg) {
925 meshlink_handle_t *mesh = arg;
927 pthread_mutex_lock(&(mesh->mesh_mutex));
929 try_outgoing_connections(mesh);
931 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
933 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
935 pthread_mutex_unlock(&(mesh->mesh_mutex));
939 bool meshlink_start(meshlink_handle_t *mesh) {
941 meshlink_errno = MESHLINK_EINVAL;
945 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
947 pthread_mutex_lock(&(mesh->mesh_mutex));
949 if(mesh->threadstarted) {
950 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
951 pthread_mutex_unlock(&(mesh->mesh_mutex));
955 if(mesh->listen_socket[0].tcp.fd < 0) {
956 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
957 meshlink_errno = MESHLINK_ENETWORK;
961 mesh->thedatalen = 0;
963 // TODO: open listening sockets first
965 //Check that a valid name is set
967 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
968 meshlink_errno = MESHLINK_EINVAL;
969 pthread_mutex_unlock(&(mesh->mesh_mutex));
973 // Start the main thread
975 event_loop_start(&mesh->loop);
977 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
978 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
979 memset(&mesh->thread, 0, sizeof mesh->thread);
980 meshlink_errno = MESHLINK_EINTERNAL;
981 pthread_mutex_unlock(&(mesh->mesh_mutex));
985 mesh->threadstarted=true;
987 discovery_start(mesh);
989 pthread_mutex_unlock(&(mesh->mesh_mutex));
993 void meshlink_stop(meshlink_handle_t *mesh) {
995 meshlink_errno = MESHLINK_EINVAL;
999 pthread_mutex_lock(&(mesh->mesh_mutex));
1000 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1003 discovery_stop(mesh);
1005 pthread_mutex_lock(&(mesh->mesh_mutex));
1006 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1008 // Shut down the main thread
1009 event_loop_stop(&mesh->loop);
1011 // Send ourselves a UDP packet to kick the event loop
1012 listen_socket_t *s = &mesh->listen_socket[0];
1013 if(sendto(s->udp.fd, "", 1, MSG_NOSIGNAL, &s->sa.sa, SALEN(s->sa.sa)) == -1)
1014 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself");
1016 // Wait for the main thread to finish
1017 pthread_mutex_unlock(&(mesh->mesh_mutex));
1018 pthread_join(mesh->thread, NULL);
1019 pthread_mutex_lock(&(mesh->mesh_mutex));
1021 mesh->threadstarted = false;
1023 pthread_mutex_unlock(&(mesh->mesh_mutex));
1026 void meshlink_close(meshlink_handle_t *mesh) {
1027 if(!mesh || !mesh->confbase) {
1028 meshlink_errno = MESHLINK_EINVAL;
1032 // stop can be called even if mesh has not been started
1033 meshlink_stop(mesh);
1035 // lock is not released after this
1036 pthread_mutex_lock(&(mesh->mesh_mutex));
1038 // Close and free all resources used.
1040 close_network_connections(mesh);
1042 logger(mesh, MESHLINK_INFO, "Terminating");
1044 exit_configuration(&mesh->config);
1045 event_loop_exit(&mesh->loop);
1052 ecdsa_free(mesh->invitation_key);
1055 free(mesh->appname);
1056 free(mesh->confbase);
1057 pthread_mutex_destroy(&(mesh->mesh_mutex));
1059 memset(mesh, 0, sizeof *mesh);
1064 static void deltree(const char *dirname) {
1065 DIR *d = opendir(dirname);
1068 while((ent = readdir(d))) {
1069 if(ent->d_name[0] == '.')
1071 char filename[PATH_MAX];
1072 snprintf(filename, sizeof filename, "%s" SLASH "%s", dirname, ent->d_name);
1073 if(unlink(filename))
1082 bool meshlink_destroy(const char *confbase) {
1084 meshlink_errno = MESHLINK_EINVAL;
1088 char filename[PATH_MAX];
1089 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
1091 if(unlink(filename)) {
1092 if(errno == ENOENT) {
1093 meshlink_errno = MESHLINK_ENOENT;
1096 logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", filename, strerror(errno));
1097 meshlink_errno = MESHLINK_ESTORAGE;
1107 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1109 meshlink_errno = MESHLINK_EINVAL;
1113 pthread_mutex_lock(&(mesh->mesh_mutex));
1114 mesh->receive_cb = cb;
1115 pthread_mutex_unlock(&(mesh->mesh_mutex));
1118 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1120 meshlink_errno = MESHLINK_EINVAL;
1124 pthread_mutex_lock(&(mesh->mesh_mutex));
1125 mesh->node_status_cb = cb;
1126 pthread_mutex_unlock(&(mesh->mesh_mutex));
1129 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1131 pthread_mutex_lock(&(mesh->mesh_mutex));
1133 mesh->log_level = cb ? level : 0;
1134 pthread_mutex_unlock(&(mesh->mesh_mutex));
1137 global_log_level = cb ? level : 0;
1141 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1142 meshlink_packethdr_t *hdr;
1144 // Validate arguments
1145 if(!mesh || !destination || len >= MAXSIZE - sizeof *hdr) {
1146 meshlink_errno = MESHLINK_EINVAL;
1154 meshlink_errno = MESHLINK_EINVAL;
1158 // Prepare the packet
1159 vpn_packet_t *packet = malloc(sizeof *packet);
1161 meshlink_errno = MESHLINK_ENOMEM;
1165 packet->probe = false;
1166 packet->tcp = false;
1167 packet->len = len + sizeof *hdr;
1169 hdr = (meshlink_packethdr_t *)packet->data;
1170 memset(hdr, 0, sizeof *hdr);
1171 // leave the last byte as 0 to make sure strings are always
1172 // null-terminated if they are longer than the buffer
1173 strncpy(hdr->destination, destination->name, (sizeof hdr->destination) - 1);
1174 strncpy(hdr->source, mesh->self->name, (sizeof hdr->source) -1 );
1176 memcpy(packet->data + sizeof *hdr, data, len);
1179 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1181 meshlink_errno = MESHLINK_ENOMEM;
1185 // Notify event loop
1186 signal_trigger(&(mesh->loop),&(mesh->datafromapp));
1191 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1192 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1196 mesh->self->in_packets++;
1197 mesh->self->in_bytes += packet->len;
1198 route(mesh, mesh->self, packet);
1201 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1202 if(!mesh || !destination) {
1203 meshlink_errno = MESHLINK_EINVAL;
1206 pthread_mutex_lock(&(mesh->mesh_mutex));
1208 node_t *n = (node_t *)destination;
1209 if(!n->status.reachable) {
1210 pthread_mutex_unlock(&(mesh->mesh_mutex));
1214 else if(n->mtuprobes > 30 && n->minmtu) {
1215 pthread_mutex_unlock(&(mesh->mesh_mutex));
1219 pthread_mutex_unlock(&(mesh->mesh_mutex));
1224 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1225 if(!mesh || !node) {
1226 meshlink_errno = MESHLINK_EINVAL;
1229 pthread_mutex_lock(&(mesh->mesh_mutex));
1231 node_t *n = (node_t *)node;
1233 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1234 meshlink_errno = MESHLINK_EINTERNAL;
1235 pthread_mutex_unlock(&(mesh->mesh_mutex));
1239 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1242 meshlink_errno = MESHLINK_EINTERNAL;
1244 pthread_mutex_unlock(&(mesh->mesh_mutex));
1248 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1250 meshlink_errno = MESHLINK_EINVAL;
1254 return (meshlink_node_t *)mesh->self;
1257 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1258 if(!mesh || !name) {
1259 meshlink_errno = MESHLINK_EINVAL;
1263 meshlink_node_t *node = NULL;
1265 pthread_mutex_lock(&(mesh->mesh_mutex));
1266 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1267 pthread_mutex_unlock(&(mesh->mesh_mutex));
1271 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1272 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1273 meshlink_errno = MESHLINK_EINVAL;
1277 meshlink_node_t **result;
1280 pthread_mutex_lock(&(mesh->mesh_mutex));
1282 *nmemb = mesh->nodes->count;
1283 result = realloc(nodes, *nmemb * sizeof *nodes);
1286 meshlink_node_t **p = result;
1287 for splay_each(node_t, n, mesh->nodes)
1288 *p++ = (meshlink_node_t *)n;
1292 meshlink_errno = MESHLINK_ENOMEM;
1295 pthread_mutex_unlock(&(mesh->mesh_mutex));
1300 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1301 if(!mesh || !data || !len || !signature || !siglen) {
1302 meshlink_errno = MESHLINK_EINVAL;
1306 if(*siglen < MESHLINK_SIGLEN) {
1307 meshlink_errno = MESHLINK_EINVAL;
1311 pthread_mutex_lock(&(mesh->mesh_mutex));
1313 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1314 meshlink_errno = MESHLINK_EINTERNAL;
1315 pthread_mutex_unlock(&(mesh->mesh_mutex));
1319 *siglen = MESHLINK_SIGLEN;
1320 pthread_mutex_unlock(&(mesh->mesh_mutex));
1324 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1325 if(!mesh || !data || !len || !signature) {
1326 meshlink_errno = MESHLINK_EINVAL;
1330 if(siglen != MESHLINK_SIGLEN) {
1331 meshlink_errno = MESHLINK_EINVAL;
1335 pthread_mutex_lock(&(mesh->mesh_mutex));
1339 struct node_t *n = (struct node_t *)source;
1340 node_read_ecdsa_public_key(mesh, n);
1342 meshlink_errno = MESHLINK_EINTERNAL;
1345 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1347 pthread_mutex_unlock(&(mesh->mesh_mutex));
1351 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1352 char filename[PATH_MAX];
1354 pthread_mutex_lock(&(mesh->mesh_mutex));
1356 snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
1357 if(mkdir(filename, 0700) && errno != EEXIST) {
1358 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1359 meshlink_errno = MESHLINK_ESTORAGE;
1360 pthread_mutex_unlock(&(mesh->mesh_mutex));
1364 // Count the number of valid invitations, clean up old ones
1365 DIR *dir = opendir(filename);
1367 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1368 meshlink_errno = MESHLINK_ESTORAGE;
1369 pthread_mutex_unlock(&(mesh->mesh_mutex));
1376 time_t deadline = time(NULL) - 604800; // 1 week in the past
1378 while((ent = readdir(dir))) {
1379 if(strlen(ent->d_name) != 24)
1381 char invname[PATH_MAX];
1383 snprintf(invname, sizeof invname, "%s" SLASH "%s", filename, ent->d_name);
1384 if(!stat(invname, &st)) {
1385 if(mesh->invitation_key && deadline < st.st_mtime)
1390 logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1396 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
1398 meshlink_errno = MESHLINK_ESTORAGE;
1399 pthread_mutex_unlock(&(mesh->mesh_mutex));
1405 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1407 // Remove the key if there are no outstanding invitations.
1410 if(mesh->invitation_key) {
1411 ecdsa_free(mesh->invitation_key);
1412 mesh->invitation_key = NULL;
1416 if(mesh->invitation_key) {
1417 pthread_mutex_unlock(&(mesh->mesh_mutex));
1421 // Create a new key if necessary.
1422 FILE *f = fopen(filename, "rb");
1424 if(errno != ENOENT) {
1425 logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
1426 meshlink_errno = MESHLINK_ESTORAGE;
1427 pthread_mutex_unlock(&(mesh->mesh_mutex));
1431 mesh->invitation_key = ecdsa_generate();
1432 if(!mesh->invitation_key) {
1433 logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
1434 meshlink_errno = MESHLINK_EINTERNAL;
1435 pthread_mutex_unlock(&(mesh->mesh_mutex));
1438 f = fopen(filename, "wb");
1440 logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
1441 meshlink_errno = MESHLINK_ESTORAGE;
1442 pthread_mutex_unlock(&(mesh->mesh_mutex));
1445 chmod(filename, 0600);
1446 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1449 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1451 if(!mesh->invitation_key) {
1452 logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
1453 meshlink_errno = MESHLINK_ESTORAGE;
1457 pthread_mutex_unlock(&(mesh->mesh_mutex));
1458 return mesh->invitation_key;
1461 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1462 if(!mesh || !address) {
1463 meshlink_errno = MESHLINK_EINVAL;
1469 pthread_mutex_lock(&(mesh->mesh_mutex));
1471 for(const char *p = address; *p; p++) {
1472 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
1474 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1475 meshlink_errno = MESHLINK_EINVAL;
1476 pthread_mutex_unlock(&(mesh->mesh_mutex));
1480 rval = append_config_file(mesh, mesh->self->name, "Address", address);
1481 pthread_mutex_unlock(&(mesh->mesh_mutex));
1485 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1487 meshlink_errno = MESHLINK_EINVAL;
1491 pthread_mutex_lock(&(mesh->mesh_mutex));
1493 // Check validity of the new node's name
1494 if(!check_id(name)) {
1495 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
1496 meshlink_errno = MESHLINK_EINVAL;
1497 pthread_mutex_unlock(&(mesh->mesh_mutex));
1501 // Ensure no host configuration file with that name exists
1502 char filename[PATH_MAX];
1503 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1504 if(!access(filename, F_OK)) {
1505 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
1506 meshlink_errno = MESHLINK_EEXIST;
1507 pthread_mutex_unlock(&(mesh->mesh_mutex));
1511 // Ensure no other nodes know about this name
1512 if(meshlink_get_node(mesh, name)) {
1513 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
1514 meshlink_errno = MESHLINK_EEXIST;
1515 pthread_mutex_unlock(&(mesh->mesh_mutex));
1519 // Get the local address
1520 char *address = get_my_hostname(mesh);
1522 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
1523 meshlink_errno = MESHLINK_ERESOLV;
1524 pthread_mutex_unlock(&(mesh->mesh_mutex));
1528 if(!refresh_invitation_key(mesh)) {
1529 meshlink_errno = MESHLINK_EINTERNAL;
1530 pthread_mutex_unlock(&(mesh->mesh_mutex));
1536 // Create a hash of the key.
1537 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1538 sha512(fingerprint, strlen(fingerprint), hash);
1539 b64encode_urlsafe(hash, hash, 18);
1541 // Create a random cookie for this invitation.
1543 randomize(cookie, 18);
1545 // Create a filename that doesn't reveal the cookie itself
1546 char buf[18 + strlen(fingerprint)];
1547 char cookiehash[64];
1548 memcpy(buf, cookie, 18);
1549 memcpy(buf + 18, fingerprint, sizeof buf - 18);
1550 sha512(buf, sizeof buf, cookiehash);
1551 b64encode_urlsafe(cookiehash, cookiehash, 18);
1553 b64encode_urlsafe(cookie, cookie, 18);
1557 // Create a file containing the details of the invitation.
1558 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1559 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1561 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1562 meshlink_errno = MESHLINK_ESTORAGE;
1563 pthread_mutex_unlock(&(mesh->mesh_mutex));
1566 FILE *f = fdopen(ifd, "w");
1570 // Fill in the details.
1571 fprintf(f, "Name = %s\n", name);
1573 // fprintf(f, "NetName = %s\n", netname);
1574 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1576 // Copy Broadcast and Mode
1577 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
1578 FILE *tc = fopen(filename, "r");
1581 while(fgets(buf, sizeof buf, tc)) {
1582 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1583 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1585 // Make sure there is a newline character.
1586 if(!strchr(buf, '\n'))
1592 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1593 meshlink_errno = MESHLINK_ESTORAGE;
1594 pthread_mutex_unlock(&(mesh->mesh_mutex));
1598 fprintf(f, "#---------------------------------------------------------------#\n");
1599 fprintf(f, "Name = %s\n", mesh->self->name);
1601 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1605 // Create an URL from the local address, key hash and cookie
1607 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1610 pthread_mutex_unlock(&(mesh->mesh_mutex));
1614 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1615 if(!mesh || !invitation) {
1616 meshlink_errno = MESHLINK_EINVAL;
1620 pthread_mutex_lock(&(mesh->mesh_mutex));
1622 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1623 char copy[strlen(invitation) + 1];
1624 strcpy(copy, invitation);
1626 // Split the invitation URL into hostname, port, key hash and cookie.
1628 char *slash = strchr(copy, '/');
1634 if(strlen(slash) != 48)
1637 char *address = copy;
1639 if(*address == '[') {
1641 char *bracket = strchr(address, ']');
1645 if(bracket[1] == ':')
1648 port = strchr(address, ':');
1656 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1659 // Generate a throw-away key for the invitation.
1660 ecdsa_t *key = ecdsa_generate();
1662 meshlink_errno = MESHLINK_EINTERNAL;
1663 pthread_mutex_unlock(&(mesh->mesh_mutex));
1667 char *b64key = ecdsa_get_base64_public_key(key);
1669 //Before doing meshlink_join make sure we are not connected to another mesh
1670 if ( mesh->threadstarted ){
1674 // Connect to the meshlink daemon mentioned in the URL.
1675 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1677 meshlink_errno = MESHLINK_ERESOLV;
1678 pthread_mutex_unlock(&(mesh->mesh_mutex));
1682 mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1683 if(mesh->sock <= 0) {
1684 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
1686 meshlink_errno = MESHLINK_ENETWORK;
1687 pthread_mutex_unlock(&(mesh->mesh_mutex));
1691 if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1692 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1693 closesocket(mesh->sock);
1695 meshlink_errno = MESHLINK_ENETWORK;
1696 pthread_mutex_unlock(&(mesh->mesh_mutex));
1702 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
1704 // Tell him we have an invitation, and give him our throw-away key.
1708 if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1709 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1710 closesocket(mesh->sock);
1711 meshlink_errno = MESHLINK_ENETWORK;
1712 pthread_mutex_unlock(&(mesh->mesh_mutex));
1718 char hisname[4096] = "";
1719 int code, hismajor, hisminor = 0;
1721 if(!recvline(mesh, sizeof mesh->line) || sscanf(mesh->line, "%d %s %d.%d", &code, hisname, &hismajor, &hisminor) < 3 || code != 0 || hismajor != PROT_MAJOR || !check_id(hisname) || !recvline(mesh, sizeof mesh->line) || !rstrip(mesh->line) || sscanf(mesh->line, "%d ", &code) != 1 || code != ACK || strlen(mesh->line) < 3) {
1722 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
1723 closesocket(mesh->sock);
1724 meshlink_errno = MESHLINK_ENETWORK;
1725 pthread_mutex_unlock(&(mesh->mesh_mutex));
1729 // Check if the hash of the key he gave us matches the hash in the URL.
1730 char *fingerprint = mesh->line + 2;
1732 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1733 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
1734 meshlink_errno = MESHLINK_EINTERNAL;
1735 pthread_mutex_unlock(&(mesh->mesh_mutex));
1738 if(memcmp(hishash, mesh->hash, 18)) {
1739 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1740 meshlink_errno = MESHLINK_EPEER;
1741 pthread_mutex_unlock(&(mesh->mesh_mutex));
1746 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1748 meshlink_errno = MESHLINK_EINTERNAL;
1749 pthread_mutex_unlock(&(mesh->mesh_mutex));
1753 // Start an SPTPS session
1754 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive)) {
1755 meshlink_errno = MESHLINK_EINTERNAL;
1756 pthread_mutex_unlock(&(mesh->mesh_mutex));
1760 // Feed rest of input buffer to SPTPS
1761 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
1762 meshlink_errno = MESHLINK_EPEER;
1763 pthread_mutex_unlock(&(mesh->mesh_mutex));
1769 while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1773 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1774 meshlink_errno = MESHLINK_ENETWORK;
1775 pthread_mutex_unlock(&(mesh->mesh_mutex));
1779 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
1780 meshlink_errno = MESHLINK_EPEER;
1781 pthread_mutex_unlock(&(mesh->mesh_mutex));
1786 sptps_stop(&mesh->sptps);
1789 closesocket(mesh->sock);
1791 if(!mesh->success) {
1792 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
1793 meshlink_errno = MESHLINK_EPEER;
1794 pthread_mutex_unlock(&(mesh->mesh_mutex));
1798 pthread_mutex_unlock(&(mesh->mesh_mutex));
1802 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL or you are already connected to a Mesh ?\n");
1803 meshlink_errno = MESHLINK_EINVAL;
1804 pthread_mutex_unlock(&(mesh->mesh_mutex));
1808 char *meshlink_export(meshlink_handle_t *mesh) {
1810 meshlink_errno = MESHLINK_EINVAL;
1814 pthread_mutex_lock(&(mesh->mesh_mutex));
1816 char filename[PATH_MAX];
1817 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1818 FILE *f = fopen(filename, "r");
1820 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
1821 meshlink_errno = MESHLINK_ESTORAGE;
1822 pthread_mutex_unlock(&(mesh->mesh_mutex));
1826 fseek(f, 0, SEEK_END);
1827 int fsize = ftell(f);
1830 size_t len = fsize + 9 + strlen(mesh->self->name);
1831 char *buf = xmalloc(len);
1832 snprintf(buf, len, "Name = %s\n", mesh->self->name);
1833 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
1834 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
1836 meshlink_errno = MESHLINK_ESTORAGE;
1837 pthread_mutex_unlock(&(mesh->mesh_mutex));
1844 pthread_mutex_unlock(&(mesh->mesh_mutex));
1848 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1849 if(!mesh || !data) {
1850 meshlink_errno = MESHLINK_EINVAL;
1854 pthread_mutex_lock(&(mesh->mesh_mutex));
1856 if(strncmp(data, "Name = ", 7)) {
1857 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
1858 meshlink_errno = MESHLINK_EPEER;
1859 pthread_mutex_unlock(&(mesh->mesh_mutex));
1863 char *end = strchr(data + 7, '\n');
1865 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
1866 meshlink_errno = MESHLINK_EPEER;
1867 pthread_mutex_unlock(&(mesh->mesh_mutex));
1871 int len = end - (data + 7);
1873 memcpy(name, data + 7, len);
1875 if(!check_id(name)) {
1876 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
1877 meshlink_errno = MESHLINK_EPEER;
1878 pthread_mutex_unlock(&(mesh->mesh_mutex));
1882 char filename[PATH_MAX];
1883 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1884 if(!access(filename, F_OK)) {
1885 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
1886 meshlink_errno = MESHLINK_EEXIST;
1887 pthread_mutex_unlock(&(mesh->mesh_mutex));
1891 if(errno != ENOENT) {
1892 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
1893 meshlink_errno = MESHLINK_ESTORAGE;
1894 pthread_mutex_unlock(&(mesh->mesh_mutex));
1898 FILE *f = fopen(filename, "w");
1900 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1901 meshlink_errno = MESHLINK_ESTORAGE;
1902 pthread_mutex_unlock(&(mesh->mesh_mutex));
1906 fwrite(end + 1, strlen(end + 1), 1, f);
1909 load_all_nodes(mesh);
1911 pthread_mutex_unlock(&(mesh->mesh_mutex));
1915 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1916 if(!mesh || !node) {
1917 meshlink_errno = MESHLINK_EINVAL;
1921 pthread_mutex_lock(&(mesh->mesh_mutex));
1925 n->status.blacklisted=true;
1926 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n",node->name);
1928 //Make blacklisting persistent in the config file
1929 append_config_file(mesh, n->name, "blacklisted", "yes");
1931 pthread_mutex_unlock(&(mesh->mesh_mutex));
1935 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1936 if(!mesh || !node) {
1937 meshlink_errno = MESHLINK_EINVAL;
1941 pthread_mutex_lock(&(mesh->mesh_mutex));
1943 node_t *n = (node_t *)node;
1944 n->status.blacklisted = false;
1946 //TODO: remove blacklisted = yes from the config file
1948 pthread_mutex_unlock(&(mesh->mesh_mutex));
1952 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
1953 mesh->default_blacklist = blacklist;
1956 /* Hint that a hostname may be found at an address
1957 * See header file for detailed comment.
1959 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
1960 if(!mesh || !node || !addr)
1963 // Ignore hints about ourself.
1964 if((node_t *)node == mesh->self)
1967 pthread_mutex_lock(&(mesh->mesh_mutex));
1969 char *host = NULL, *port = NULL, *str = NULL;
1970 sockaddr2str((const sockaddr_t *)addr, &host, &port);
1973 xasprintf(&str, "%s %s", host, port);
1974 if ( (strncmp ("fe80",host,4) != 0) && ( strncmp("127.",host,4) != 0 ) && ( strcmp("localhost",host) !=0 ) )
1975 append_config_file(mesh, node->name, "Address", str);
1977 logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
1984 pthread_mutex_unlock(&(mesh->mesh_mutex));
1985 // @TODO do we want to fire off a connection attempt right away?
1988 /* Return an array of edges in the current network graph.
1989 * Data captures the current state and will not be updated.
1990 * Caller must deallocate data when done.
1992 meshlink_edge_t **meshlink_get_all_edges_state(meshlink_handle_t *mesh, meshlink_edge_t **edges, size_t *nmemb) {
1993 if(!mesh || !nmemb || (*nmemb && !edges)) {
1994 meshlink_errno = MESHLINK_EINVAL;
1998 pthread_mutex_lock(&(mesh->mesh_mutex));
2000 meshlink_edge_t **result = NULL;
2001 meshlink_edge_t *copy = NULL;
2002 int result_size = 0;
2004 result_size = mesh->edges->count;
2006 // if result is smaller than edges, we have to dealloc all the excess meshlink_edge_t
2007 if(result_size > *nmemb) {
2008 result = realloc(edges, result_size * sizeof (meshlink_edge_t*));
2014 meshlink_edge_t **p = result;
2016 for splay_each(edge_t, e, mesh->edges) {
2017 // skip edges that do not represent a two-directional connection
2018 if((!e->reverse) || (e->reverse->to != e->from)) {
2023 // the first *nmemb members of result can be re-used
2025 copy = xzalloc(sizeof *copy);
2030 copy->from = (meshlink_node_t*)e->from;
2031 copy->to = (meshlink_node_t*)e->to;
2032 copy->address = e->address.storage;
2033 copy->options = e->options;
2034 copy->weight = e->weight;
2037 // shrink result to the actual amount of memory used
2038 for(int i = *nmemb; i > result_size; i--) {
2039 free(result[i - 1]);
2041 result = realloc(result, result_size * sizeof (meshlink_edge_t*));
2042 *nmemb = result_size;
2045 meshlink_errno = MESHLINK_ENOMEM;
2048 pthread_mutex_unlock(&(mesh->mesh_mutex));
2053 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2058 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2059 meshlink_channel_t *channel = connection->priv;
2062 node_t *n = channel->node;
2063 meshlink_handle_t *mesh = n->mesh;
2064 if(!channel->receive_cb)
2067 channel->receive_cb(mesh, channel, data, len);
2072 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2073 node_t *n = utcp_connection->utcp->priv;
2076 meshlink_handle_t *mesh = n->mesh;
2077 if(!mesh->channel_accept_cb)
2079 meshlink_channel_t *channel = xzalloc(sizeof *channel);
2081 channel->c = utcp_connection;
2082 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0))
2083 utcp_accept(utcp_connection, channel_recv, channel);
2088 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2089 node_t *n = utcp->priv;
2090 meshlink_handle_t *mesh = n->mesh;
2091 char hex[len * 2 + 1];
2092 bin2hex(data, hex, len);
2093 logger(mesh, MESHLINK_WARNING, "channel_send(%p, %p, %zu): %s\n", utcp, data, len, hex);
2094 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? len : -1;
2097 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2098 if(!mesh || !channel) {
2099 meshlink_errno = MESHLINK_EINVAL;
2103 channel->receive_cb = cb;
2106 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2107 node_t *n = (node_t *)source;
2110 char hex[len * 2 + 1];
2111 bin2hex(data, hex, len);
2112 logger(mesh, MESHLINK_WARNING, "channel_receive(%p, %p, %zu): %s\n", n->utcp, data, len, hex);
2113 utcp_recv(n->utcp, data, len);
2116 static void channel_poll(struct utcp_connection *connection, size_t len) {
2117 meshlink_channel_t *channel = connection->priv;
2120 node_t *n = channel->node;
2121 meshlink_handle_t *mesh = n->mesh;
2122 if(channel->poll_cb)
2123 channel->poll_cb(mesh, channel, len);
2126 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2127 channel->poll_cb = cb;
2128 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2131 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2133 meshlink_errno = MESHLINK_EINVAL;
2137 pthread_mutex_lock(&mesh->mesh_mutex);
2138 mesh->channel_accept_cb = cb;
2139 mesh->receive_cb = channel_receive;
2140 for splay_each(node_t, n, mesh->nodes) {
2141 if(!n->utcp && n != mesh->self) {
2142 logger(mesh, MESHLINK_WARNING, "utcp_init on node %s", n->name);
2143 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2146 pthread_mutex_unlock(&mesh->mesh_mutex);
2149 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) {
2150 if(!mesh || !node) {
2151 meshlink_errno = MESHLINK_EINVAL;
2155 logger(mesh, MESHLINK_WARNING, "meshlink_channel_open(%p, %s, %u, %p, %p, %zu)\n", mesh, node->name, port, cb, data, len);
2156 node_t *n = (node_t *)node;
2158 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2159 mesh->receive_cb = channel_receive;
2161 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2165 meshlink_channel_t *channel = xzalloc(sizeof *channel);
2167 channel->receive_cb = cb;
2168 channel->c = utcp_connect(n->utcp, port, channel_recv, channel);
2170 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2177 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2178 if(!mesh || !channel) {
2179 meshlink_errno = MESHLINK_EINVAL;
2183 utcp_shutdown(channel->c, direction);
2186 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2187 if(!mesh || !channel) {
2188 meshlink_errno = MESHLINK_EINVAL;
2192 utcp_close(channel->c);
2196 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2197 if(!mesh || !channel) {
2198 meshlink_errno = MESHLINK_EINVAL;
2206 meshlink_errno = MESHLINK_EINVAL;
2210 // TODO: more finegrained locking.
2211 // Ideally we want to put the data into the UTCP connection's send buffer.
2212 // Then, preferrably only if there is room in the receiver window,
2213 // kick the meshlink thread to go send packets.
2215 pthread_mutex_lock(&mesh->mesh_mutex);
2216 ssize_t retval = utcp_send(channel->c, data, len);
2217 pthread_mutex_unlock(&mesh->mesh_mutex);
2220 meshlink_errno = MESHLINK_ENETWORK;
2224 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2225 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp)
2226 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2227 if(mesh->node_status_cb)
2228 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
2231 static void __attribute__((constructor)) meshlink_init(void) {
2235 static void __attribute__((destructor)) meshlink_exit(void) {
2239 /// Device class traits
2240 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX +1] = {
2241 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2242 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
2243 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
2244 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN