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)
185 static bool is_valid_hostname(const char *hostname) {
186 for(const char *p = hostname; *p; p++) {
187 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':'))
194 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
195 char *hostname = NULL;
197 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
198 struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
199 struct addrinfo *aip = ai;
200 static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
204 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
206 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
212 send(s, request, sizeof request - 1, 0);
213 int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
216 if(line[len - 1] == '\n')
218 char *p = strrchr(line, '\n');
220 hostname = xstrdup(p + 1);
233 // Check that the hostname is reasonable
234 if(hostname && !is_valid_hostname(hostname)) {
240 meshlink_errno = MESHLINK_ERESOLV;
245 static char *get_my_hostname(meshlink_handle_t* mesh) {
246 char *hostname = NULL;
248 char *hostport = NULL;
249 char *name = mesh->self->name;
250 char filename[PATH_MAX] = "";
253 // Use first Address statement in own host config file
254 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
255 scan_for_hostname(filename, &hostname, &port);
260 hostname = meshlink_get_external_address(mesh);
264 f = fopen(filename, "a");
266 fprintf(f, "\nAddress = %s\n", hostname);
269 logger(mesh, MESHLINK_DEBUG, "Could not append Address to %s: %s\n", filename, strerror(errno));
274 if(strchr(hostname, ':'))
275 xasprintf(&hostport, "[%s]:%s", hostname, port);
277 xasprintf(&hostport, "%s:%s", hostname, port);
279 if(strchr(hostname, ':'))
280 xasprintf(&hostport, "[%s]", hostname);
282 hostport = xstrdup(hostname);
290 static char *get_line(const char **data) {
299 static char line[1024];
300 const char *end = strchr(*data, '\n');
301 size_t len = end ? end - *data : strlen(*data);
302 if(len >= sizeof line) {
303 logger(NULL, MESHLINK_ERROR, "Maximum line length exceeded!\n");
306 if(len && !isprint(**data))
309 memcpy(line, *data, len);
320 static char *get_value(const char *data, const char *var) {
321 char *line = get_line(&data);
325 char *sep = line + strcspn(line, " \t=");
326 char *val = sep + strspn(sep, " \t");
328 val += 1 + strspn(val + 1, " \t");
330 if(strcasecmp(line, var))
335 static bool try_bind(int port) {
336 struct addrinfo *ai = NULL;
337 struct addrinfo hint = {
338 .ai_flags = AI_PASSIVE,
339 .ai_family = AF_UNSPEC,
340 .ai_socktype = SOCK_STREAM,
341 .ai_protocol = IPPROTO_TCP,
345 snprintf(portstr, sizeof portstr, "%d", port);
347 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
351 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
356 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
369 static int check_port(meshlink_handle_t *mesh) {
370 for(int i = 0; i < 1000; i++) {
371 int port = 0x1000 + (rand() & 0x7fff);
373 char filename[PATH_MAX];
374 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
375 FILE *f = fopen(filename, "a");
377 logger(mesh, MESHLINK_DEBUG, "Please change MeshLink's Port manually.\n");
381 fprintf(f, "Port = %d\n", port);
387 logger(mesh, MESHLINK_DEBUG, "Please change MeshLink's Port manually.\n");
391 static bool finalize_join(meshlink_handle_t *mesh) {
392 char *name = xstrdup(get_value(mesh->data, "Name"));
394 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
398 if(!check_id(name)) {
399 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
403 char filename[PATH_MAX];
404 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
406 FILE *f = fopen(filename, "w");
408 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
412 fprintf(f, "Name = %s\n", name);
414 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
415 FILE *fh = fopen(filename, "w");
417 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
422 // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
423 // Other chunks go unfiltered to their respective host config files
424 const char *p = mesh->data;
427 while((l = get_line(&p))) {
432 // Split line into variable and value
433 int len = strcspn(l, "\t =");
435 value += strspn(value, "\t ");
438 value += strspn(value, "\t ");
443 if(!strcasecmp(l, "Name"))
444 if(strcmp(value, name))
448 else if(!strcasecmp(l, "NetName"))
451 // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
454 for(i = 0; variables[i].name; i++) {
455 if(strcasecmp(l, variables[i].name))
461 // Ignore unknown and unsafe variables
463 logger(mesh, MESHLINK_DEBUG, "Ignoring unknown variable '%s' in invitation.\n", l);
465 } else if(!(variables[i].type & VAR_SAFE)) {
466 logger(mesh, MESHLINK_DEBUG, "Ignoring unsafe variable '%s' in invitation.\n", l);
470 // Copy the safe variable to the right config file
471 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
476 while(l && !strcasecmp(l, "Name")) {
477 if(!check_id(value)) {
478 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation.\n");
482 if(!strcmp(value, name)) {
483 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
487 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
488 f = fopen(filename, "w");
491 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
495 while((l = get_line(&p))) {
496 if(!strcmp(l, "#---------------------------------------------------------------#"))
498 int len = strcspn(l, "\t =");
499 if(len == 4 && !strncasecmp(l, "Name", 4)) {
501 value += strspn(value, "\t ");
504 value += strspn(value, "\t ");
517 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
523 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
524 fprintf(fh, "Port = %s\n", mesh->myport);
528 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
531 free(mesh->self->name);
532 free(mesh->self->connection->name);
533 mesh->self->name = xstrdup(name);
534 mesh->self->connection->name = name;
536 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
538 load_all_nodes(mesh);
543 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
544 meshlink_handle_t* mesh = handle;
546 int result = send(mesh->sock, data, len, 0);
547 if(result == -1 && errno == EINTR)
557 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
558 meshlink_handle_t* mesh = handle;
560 case SPTPS_HANDSHAKE:
561 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof mesh->cookie);
564 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
565 memcpy(mesh->data + mesh->thedatalen, msg, len);
566 mesh->thedatalen += len;
567 mesh->data[mesh->thedatalen] = 0;
571 mesh->thedatalen = 0;
572 return finalize_join(mesh);
575 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
576 shutdown(mesh->sock, SHUT_RDWR);
577 mesh->success = true;
587 static bool recvline(meshlink_handle_t* mesh, size_t len) {
588 char *newline = NULL;
593 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
594 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof mesh->buffer - mesh->blen, 0);
595 if(result == -1 && errno == EINTR)
599 mesh->blen += result;
602 if(newline - mesh->buffer >= len)
605 len = newline - mesh->buffer;
607 memcpy(mesh->line, mesh->buffer, len);
609 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
610 mesh->blen -= len + 1;
614 static bool sendline(int fd, char *format, ...) {
615 static char buffer[4096];
620 va_start(ap, format);
621 blen = vsnprintf(buffer, sizeof buffer, format, ap);
624 if(blen < 1 || blen >= sizeof buffer)
631 int result = send(fd, p, blen, MSG_NOSIGNAL);
632 if(result == -1 && errno == EINTR)
643 static const char *errstr[] = {
644 [MESHLINK_OK] = "No error",
645 [MESHLINK_EINVAL] = "Invalid argument",
646 [MESHLINK_ENOMEM] = "Out of memory",
647 [MESHLINK_ENOENT] = "No such node",
648 [MESHLINK_EEXIST] = "Node already exists",
649 [MESHLINK_EINTERNAL] = "Internal error",
650 [MESHLINK_ERESOLV] = "Could not resolve hostname",
651 [MESHLINK_ESTORAGE] = "Storage error",
652 [MESHLINK_ENETWORK] = "Network error",
653 [MESHLINK_EPEER] = "Error communicating with peer",
656 const char *meshlink_strerror(meshlink_errno_t err) {
657 if(err < 0 || err >= sizeof errstr / sizeof *errstr)
658 return "Invalid error code";
662 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
665 char pubname[PATH_MAX], privname[PATH_MAX];
667 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
669 if(!(key = ecdsa_generate())) {
670 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
671 meshlink_errno = MESHLINK_EINTERNAL;
674 logger(mesh, MESHLINK_DEBUG, "Done.\n");
676 snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
677 f = fopen(privname, "wb");
680 meshlink_errno = MESHLINK_ESTORAGE;
685 fchmod(fileno(f), 0600);
688 if(!ecdsa_write_pem_private_key(key, f)) {
689 logger(mesh, MESHLINK_DEBUG, "Error writing private key!\n");
692 meshlink_errno = MESHLINK_EINTERNAL;
698 snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
699 f = fopen(pubname, "a");
702 meshlink_errno = MESHLINK_ESTORAGE;
706 char *pubkey = ecdsa_get_base64_public_key(key);
707 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
716 static struct timeval idle(event_loop_t *loop, void *data) {
717 meshlink_handle_t *mesh = data;
718 struct timeval t, tmin = {3600, 0};
719 for splay_each(node_t, n, mesh->nodes) {
722 t = utcp_timeout(n->utcp);
723 if(timercmp(&t, &tmin, <))
729 // Find out what local address a socket would use if we connect to the given address.
730 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
731 // of both endpoints, but this will actually not send any UDP packet.
732 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen) {
733 struct addrinfo *rai = NULL;
734 const struct addrinfo hint = {
735 .ai_family = AF_UNSPEC,
736 .ai_socktype = SOCK_DGRAM,
737 .ai_protocol = IPPROTO_UDP,
740 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai)
743 int sock = socket(rai->ai_family, rai->ai_socktype, rai->ai_protocol);
749 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
756 struct sockaddr_storage sn;
757 socklen_t sl = sizeof sn;
759 if(getsockname(sock, (struct sockaddr *)&sn, &sl))
762 if(getnameinfo((struct sockaddr *)&sn, sl, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV))
768 // Get our local address(es) by simulating connecting to an Internet host.
769 static void add_local_addresses(meshlink_handle_t *mesh) {
770 char host[NI_MAXHOST];
771 char entry[MAX_STRING_SIZE];
775 if(getlocaladdrname("93.184.216.34", host, sizeof host)) {
776 snprintf(entry, sizeof entry, "%s %s", host, mesh->myport);
777 append_config_file(mesh, mesh->name, "Address", entry);
782 if(getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", host, sizeof host)) {
783 snprintf(entry, sizeof entry, "%s %s", host, mesh->myport);
784 append_config_file(mesh, mesh->name, "Address", entry);
788 static bool meshlink_setup(meshlink_handle_t *mesh) {
789 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
790 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
791 meshlink_errno = MESHLINK_ESTORAGE;
795 char filename[PATH_MAX];
796 snprintf(filename, sizeof filename, "%s" SLASH "hosts", mesh->confbase);
798 if(mkdir(filename, 0777) && errno != EEXIST) {
799 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
800 meshlink_errno = MESHLINK_ESTORAGE;
804 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
806 if(!access(filename, F_OK)) {
807 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
808 meshlink_errno = MESHLINK_EEXIST;
812 FILE *f = fopen(filename, "w");
814 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
815 meshlink_errno = MESHLINK_ESTORAGE;
819 fprintf(f, "Name = %s\n", mesh->name);
822 if(!ecdsa_keygen(mesh)) {
823 meshlink_errno = MESHLINK_EINTERNAL;
832 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char* appname, dev_class_t devclass) {
833 // Validate arguments provided by the application
834 bool usingname = false;
836 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
838 if(!confbase || !*confbase) {
839 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
840 meshlink_errno = MESHLINK_EINVAL;
844 if(!appname || !*appname) {
845 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
846 meshlink_errno = MESHLINK_EINVAL;
850 if(!name || !*name) {
851 logger(NULL, MESHLINK_ERROR, "No name given!\n");
854 else { //check name only if there is a name != NULL
856 if(!check_id(name)) {
857 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
858 meshlink_errno = MESHLINK_EINVAL;
860 } else { usingname = true;}
863 if(devclass < 0 || devclass > _DEV_CLASS_MAX) {
864 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
865 meshlink_errno = MESHLINK_EINVAL;
869 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
870 mesh->confbase = xstrdup(confbase);
871 mesh->appname = xstrdup(appname);
872 mesh->devclass = devclass;
873 if (usingname) mesh->name = xstrdup(name);
876 pthread_mutexattr_t attr;
877 pthread_mutexattr_init(&attr);
878 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
879 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
881 mesh->threadstarted = false;
882 event_loop_init(&mesh->loop);
883 mesh->loop.data = mesh;
885 // Check whether meshlink.conf already exists
887 char filename[PATH_MAX];
888 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
890 if(access(filename, R_OK)) {
891 if(errno == ENOENT) {
893 if(!meshlink_setup(mesh)) {
894 // meshlink_errno is set by meshlink_setup()
898 logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
899 meshlink_close(mesh);
900 meshlink_errno = MESHLINK_ESTORAGE;
905 // Read the configuration
907 init_configuration(&mesh->config);
909 if(!read_server_config(mesh)) {
910 meshlink_close(mesh);
911 meshlink_errno = MESHLINK_ESTORAGE;
916 struct WSAData wsa_state;
917 WSAStartup(MAKEWORD(2, 2), &wsa_state);
920 // Setup up everything
921 // TODO: we should not open listening sockets yet
923 if(!setup_network(mesh)) {
924 meshlink_close(mesh);
925 meshlink_errno = MESHLINK_ENETWORK;
929 add_local_addresses(mesh);
931 idle_set(&mesh->loop, idle, mesh);
933 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
937 static void *meshlink_main_loop(void *arg) {
938 meshlink_handle_t *mesh = arg;
940 pthread_mutex_lock(&(mesh->mesh_mutex));
942 try_outgoing_connections(mesh);
944 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
946 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
948 pthread_mutex_unlock(&(mesh->mesh_mutex));
952 bool meshlink_start(meshlink_handle_t *mesh) {
954 meshlink_errno = MESHLINK_EINVAL;
958 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
960 pthread_mutex_lock(&(mesh->mesh_mutex));
962 if(mesh->threadstarted) {
963 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
964 pthread_mutex_unlock(&(mesh->mesh_mutex));
968 if(mesh->listen_socket[0].tcp.fd < 0) {
969 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
970 meshlink_errno = MESHLINK_ENETWORK;
974 mesh->thedatalen = 0;
976 // TODO: open listening sockets first
978 //Check that a valid name is set
980 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
981 meshlink_errno = MESHLINK_EINVAL;
982 pthread_mutex_unlock(&(mesh->mesh_mutex));
986 // Start the main thread
988 event_loop_start(&mesh->loop);
990 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
991 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
992 memset(&mesh->thread, 0, sizeof mesh->thread);
993 meshlink_errno = MESHLINK_EINTERNAL;
994 pthread_mutex_unlock(&(mesh->mesh_mutex));
998 mesh->threadstarted=true;
1000 discovery_start(mesh);
1002 pthread_mutex_unlock(&(mesh->mesh_mutex));
1006 void meshlink_stop(meshlink_handle_t *mesh) {
1008 meshlink_errno = MESHLINK_EINVAL;
1012 pthread_mutex_lock(&(mesh->mesh_mutex));
1013 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1016 discovery_stop(mesh);
1018 pthread_mutex_lock(&(mesh->mesh_mutex));
1019 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1021 // Shut down the main thread
1022 event_loop_stop(&mesh->loop);
1024 // Send ourselves a UDP packet to kick the event loop
1025 listen_socket_t *s = &mesh->listen_socket[0];
1026 if(sendto(s->udp.fd, "", 1, MSG_NOSIGNAL, &s->sa.sa, SALEN(s->sa.sa)) == -1)
1027 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself");
1029 // Wait for the main thread to finish
1030 pthread_mutex_unlock(&(mesh->mesh_mutex));
1031 pthread_join(mesh->thread, NULL);
1032 pthread_mutex_lock(&(mesh->mesh_mutex));
1034 mesh->threadstarted = false;
1036 pthread_mutex_unlock(&(mesh->mesh_mutex));
1039 void meshlink_close(meshlink_handle_t *mesh) {
1040 if(!mesh || !mesh->confbase) {
1041 meshlink_errno = MESHLINK_EINVAL;
1045 // stop can be called even if mesh has not been started
1046 meshlink_stop(mesh);
1048 // lock is not released after this
1049 pthread_mutex_lock(&(mesh->mesh_mutex));
1051 // Close and free all resources used.
1053 close_network_connections(mesh);
1055 logger(mesh, MESHLINK_INFO, "Terminating");
1057 exit_configuration(&mesh->config);
1058 event_loop_exit(&mesh->loop);
1065 ecdsa_free(mesh->invitation_key);
1068 free(mesh->appname);
1069 free(mesh->confbase);
1070 pthread_mutex_destroy(&(mesh->mesh_mutex));
1072 memset(mesh, 0, sizeof *mesh);
1077 static void deltree(const char *dirname) {
1078 DIR *d = opendir(dirname);
1081 while((ent = readdir(d))) {
1082 if(ent->d_name[0] == '.')
1084 char filename[PATH_MAX];
1085 snprintf(filename, sizeof filename, "%s" SLASH "%s", dirname, ent->d_name);
1086 if(unlink(filename))
1095 bool meshlink_destroy(const char *confbase) {
1097 meshlink_errno = MESHLINK_EINVAL;
1101 char filename[PATH_MAX];
1102 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
1104 if(unlink(filename)) {
1105 if(errno == ENOENT) {
1106 meshlink_errno = MESHLINK_ENOENT;
1109 logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", filename, strerror(errno));
1110 meshlink_errno = MESHLINK_ESTORAGE;
1120 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1122 meshlink_errno = MESHLINK_EINVAL;
1126 pthread_mutex_lock(&(mesh->mesh_mutex));
1127 mesh->receive_cb = cb;
1128 pthread_mutex_unlock(&(mesh->mesh_mutex));
1131 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1133 meshlink_errno = MESHLINK_EINVAL;
1137 pthread_mutex_lock(&(mesh->mesh_mutex));
1138 mesh->node_status_cb = cb;
1139 pthread_mutex_unlock(&(mesh->mesh_mutex));
1142 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1144 pthread_mutex_lock(&(mesh->mesh_mutex));
1146 mesh->log_level = cb ? level : 0;
1147 pthread_mutex_unlock(&(mesh->mesh_mutex));
1150 global_log_level = cb ? level : 0;
1154 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1155 meshlink_packethdr_t *hdr;
1157 // Validate arguments
1158 if(!mesh || !destination || len >= MAXSIZE - sizeof *hdr) {
1159 meshlink_errno = MESHLINK_EINVAL;
1167 meshlink_errno = MESHLINK_EINVAL;
1171 // Prepare the packet
1172 vpn_packet_t *packet = malloc(sizeof *packet);
1174 meshlink_errno = MESHLINK_ENOMEM;
1178 packet->probe = false;
1179 packet->tcp = false;
1180 packet->len = len + sizeof *hdr;
1182 hdr = (meshlink_packethdr_t *)packet->data;
1183 memset(hdr, 0, sizeof *hdr);
1184 // leave the last byte as 0 to make sure strings are always
1185 // null-terminated if they are longer than the buffer
1186 strncpy(hdr->destination, destination->name, (sizeof hdr->destination) - 1);
1187 strncpy(hdr->source, mesh->self->name, (sizeof hdr->source) -1 );
1189 memcpy(packet->data + sizeof *hdr, data, len);
1192 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1194 meshlink_errno = MESHLINK_ENOMEM;
1198 // Notify event loop
1199 signal_trigger(&(mesh->loop),&(mesh->datafromapp));
1204 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1205 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1209 mesh->self->in_packets++;
1210 mesh->self->in_bytes += packet->len;
1211 route(mesh, mesh->self, packet);
1214 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1215 if(!mesh || !destination) {
1216 meshlink_errno = MESHLINK_EINVAL;
1219 pthread_mutex_lock(&(mesh->mesh_mutex));
1221 node_t *n = (node_t *)destination;
1222 if(!n->status.reachable) {
1223 pthread_mutex_unlock(&(mesh->mesh_mutex));
1227 else if(n->mtuprobes > 30 && n->minmtu) {
1228 pthread_mutex_unlock(&(mesh->mesh_mutex));
1232 pthread_mutex_unlock(&(mesh->mesh_mutex));
1237 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1238 if(!mesh || !node) {
1239 meshlink_errno = MESHLINK_EINVAL;
1242 pthread_mutex_lock(&(mesh->mesh_mutex));
1244 node_t *n = (node_t *)node;
1246 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1247 meshlink_errno = MESHLINK_EINTERNAL;
1248 pthread_mutex_unlock(&(mesh->mesh_mutex));
1252 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1255 meshlink_errno = MESHLINK_EINTERNAL;
1257 pthread_mutex_unlock(&(mesh->mesh_mutex));
1261 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1263 meshlink_errno = MESHLINK_EINVAL;
1267 return (meshlink_node_t *)mesh->self;
1270 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1271 if(!mesh || !name) {
1272 meshlink_errno = MESHLINK_EINVAL;
1276 meshlink_node_t *node = NULL;
1278 pthread_mutex_lock(&(mesh->mesh_mutex));
1279 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1280 pthread_mutex_unlock(&(mesh->mesh_mutex));
1284 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1285 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1286 meshlink_errno = MESHLINK_EINVAL;
1290 meshlink_node_t **result;
1293 pthread_mutex_lock(&(mesh->mesh_mutex));
1295 *nmemb = mesh->nodes->count;
1296 result = realloc(nodes, *nmemb * sizeof *nodes);
1299 meshlink_node_t **p = result;
1300 for splay_each(node_t, n, mesh->nodes)
1301 *p++ = (meshlink_node_t *)n;
1305 meshlink_errno = MESHLINK_ENOMEM;
1308 pthread_mutex_unlock(&(mesh->mesh_mutex));
1313 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1314 if(!mesh || !data || !len || !signature || !siglen) {
1315 meshlink_errno = MESHLINK_EINVAL;
1319 if(*siglen < MESHLINK_SIGLEN) {
1320 meshlink_errno = MESHLINK_EINVAL;
1324 pthread_mutex_lock(&(mesh->mesh_mutex));
1326 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1327 meshlink_errno = MESHLINK_EINTERNAL;
1328 pthread_mutex_unlock(&(mesh->mesh_mutex));
1332 *siglen = MESHLINK_SIGLEN;
1333 pthread_mutex_unlock(&(mesh->mesh_mutex));
1337 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1338 if(!mesh || !data || !len || !signature) {
1339 meshlink_errno = MESHLINK_EINVAL;
1343 if(siglen != MESHLINK_SIGLEN) {
1344 meshlink_errno = MESHLINK_EINVAL;
1348 pthread_mutex_lock(&(mesh->mesh_mutex));
1352 struct node_t *n = (struct node_t *)source;
1353 node_read_ecdsa_public_key(mesh, n);
1355 meshlink_errno = MESHLINK_EINTERNAL;
1358 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1360 pthread_mutex_unlock(&(mesh->mesh_mutex));
1364 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1365 char filename[PATH_MAX];
1367 pthread_mutex_lock(&(mesh->mesh_mutex));
1369 snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
1370 if(mkdir(filename, 0700) && errno != EEXIST) {
1371 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1372 meshlink_errno = MESHLINK_ESTORAGE;
1373 pthread_mutex_unlock(&(mesh->mesh_mutex));
1377 // Count the number of valid invitations, clean up old ones
1378 DIR *dir = opendir(filename);
1380 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1381 meshlink_errno = MESHLINK_ESTORAGE;
1382 pthread_mutex_unlock(&(mesh->mesh_mutex));
1389 time_t deadline = time(NULL) - 604800; // 1 week in the past
1391 while((ent = readdir(dir))) {
1392 if(strlen(ent->d_name) != 24)
1394 char invname[PATH_MAX];
1396 snprintf(invname, sizeof invname, "%s" SLASH "%s", filename, ent->d_name);
1397 if(!stat(invname, &st)) {
1398 if(mesh->invitation_key && deadline < st.st_mtime)
1403 logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1409 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
1411 meshlink_errno = MESHLINK_ESTORAGE;
1412 pthread_mutex_unlock(&(mesh->mesh_mutex));
1418 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1420 // Remove the key if there are no outstanding invitations.
1423 if(mesh->invitation_key) {
1424 ecdsa_free(mesh->invitation_key);
1425 mesh->invitation_key = NULL;
1429 if(mesh->invitation_key) {
1430 pthread_mutex_unlock(&(mesh->mesh_mutex));
1434 // Create a new key if necessary.
1435 FILE *f = fopen(filename, "rb");
1437 if(errno != ENOENT) {
1438 logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
1439 meshlink_errno = MESHLINK_ESTORAGE;
1440 pthread_mutex_unlock(&(mesh->mesh_mutex));
1444 mesh->invitation_key = ecdsa_generate();
1445 if(!mesh->invitation_key) {
1446 logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
1447 meshlink_errno = MESHLINK_EINTERNAL;
1448 pthread_mutex_unlock(&(mesh->mesh_mutex));
1451 f = fopen(filename, "wb");
1453 logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
1454 meshlink_errno = MESHLINK_ESTORAGE;
1455 pthread_mutex_unlock(&(mesh->mesh_mutex));
1458 chmod(filename, 0600);
1459 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1462 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1464 if(!mesh->invitation_key) {
1465 logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
1466 meshlink_errno = MESHLINK_ESTORAGE;
1470 pthread_mutex_unlock(&(mesh->mesh_mutex));
1471 return mesh->invitation_key;
1474 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1475 if(!mesh || !address) {
1476 meshlink_errno = MESHLINK_EINVAL;
1480 if(!is_valid_hostname(address)) {
1481 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1482 meshlink_errno = MESHLINK_EINVAL;
1488 pthread_mutex_lock(&(mesh->mesh_mutex));
1489 rval = append_config_file(mesh, mesh->self->name, "Address", address);
1490 pthread_mutex_unlock(&(mesh->mesh_mutex));
1495 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
1497 meshlink_errno = MESHLINK_EINVAL;
1501 char *address = meshlink_get_external_address(mesh);
1507 pthread_mutex_lock(&(mesh->mesh_mutex));
1508 rval = append_config_file(mesh, mesh->self->name, "Address", address);
1509 pthread_mutex_unlock(&(mesh->mesh_mutex));
1515 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1517 meshlink_errno = MESHLINK_EINVAL;
1521 pthread_mutex_lock(&(mesh->mesh_mutex));
1523 // Check validity of the new node's name
1524 if(!check_id(name)) {
1525 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
1526 meshlink_errno = MESHLINK_EINVAL;
1527 pthread_mutex_unlock(&(mesh->mesh_mutex));
1531 // Ensure no host configuration file with that name exists
1532 char filename[PATH_MAX];
1533 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1534 if(!access(filename, F_OK)) {
1535 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
1536 meshlink_errno = MESHLINK_EEXIST;
1537 pthread_mutex_unlock(&(mesh->mesh_mutex));
1541 // Ensure no other nodes know about this name
1542 if(meshlink_get_node(mesh, name)) {
1543 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
1544 meshlink_errno = MESHLINK_EEXIST;
1545 pthread_mutex_unlock(&(mesh->mesh_mutex));
1549 // Get the local address
1550 char *address = get_my_hostname(mesh);
1552 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
1553 meshlink_errno = MESHLINK_ERESOLV;
1554 pthread_mutex_unlock(&(mesh->mesh_mutex));
1558 if(!refresh_invitation_key(mesh)) {
1559 meshlink_errno = MESHLINK_EINTERNAL;
1560 pthread_mutex_unlock(&(mesh->mesh_mutex));
1566 // Create a hash of the key.
1567 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1568 sha512(fingerprint, strlen(fingerprint), hash);
1569 b64encode_urlsafe(hash, hash, 18);
1571 // Create a random cookie for this invitation.
1573 randomize(cookie, 18);
1575 // Create a filename that doesn't reveal the cookie itself
1576 char buf[18 + strlen(fingerprint)];
1577 char cookiehash[64];
1578 memcpy(buf, cookie, 18);
1579 memcpy(buf + 18, fingerprint, sizeof buf - 18);
1580 sha512(buf, sizeof buf, cookiehash);
1581 b64encode_urlsafe(cookiehash, cookiehash, 18);
1583 b64encode_urlsafe(cookie, cookie, 18);
1587 // Create a file containing the details of the invitation.
1588 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1589 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1591 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1592 meshlink_errno = MESHLINK_ESTORAGE;
1593 pthread_mutex_unlock(&(mesh->mesh_mutex));
1596 FILE *f = fdopen(ifd, "w");
1600 // Fill in the details.
1601 fprintf(f, "Name = %s\n", name);
1603 // fprintf(f, "NetName = %s\n", netname);
1604 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1606 // Copy Broadcast and Mode
1607 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
1608 FILE *tc = fopen(filename, "r");
1611 while(fgets(buf, sizeof buf, tc)) {
1612 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1613 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1615 // Make sure there is a newline character.
1616 if(!strchr(buf, '\n'))
1622 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1623 meshlink_errno = MESHLINK_ESTORAGE;
1624 pthread_mutex_unlock(&(mesh->mesh_mutex));
1628 fprintf(f, "#---------------------------------------------------------------#\n");
1629 fprintf(f, "Name = %s\n", mesh->self->name);
1631 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1635 // Create an URL from the local address, key hash and cookie
1637 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1640 pthread_mutex_unlock(&(mesh->mesh_mutex));
1644 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1645 if(!mesh || !invitation) {
1646 meshlink_errno = MESHLINK_EINVAL;
1650 pthread_mutex_lock(&(mesh->mesh_mutex));
1652 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1653 char copy[strlen(invitation) + 1];
1654 strcpy(copy, invitation);
1656 // Split the invitation URL into hostname, port, key hash and cookie.
1658 char *slash = strchr(copy, '/');
1664 if(strlen(slash) != 48)
1667 char *address = copy;
1669 if(*address == '[') {
1671 char *bracket = strchr(address, ']');
1675 if(bracket[1] == ':')
1678 port = strchr(address, ':');
1686 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1689 // Generate a throw-away key for the invitation.
1690 ecdsa_t *key = ecdsa_generate();
1692 meshlink_errno = MESHLINK_EINTERNAL;
1693 pthread_mutex_unlock(&(mesh->mesh_mutex));
1697 char *b64key = ecdsa_get_base64_public_key(key);
1699 //Before doing meshlink_join make sure we are not connected to another mesh
1700 if ( mesh->threadstarted ){
1704 // Connect to the meshlink daemon mentioned in the URL.
1705 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1707 meshlink_errno = MESHLINK_ERESOLV;
1708 pthread_mutex_unlock(&(mesh->mesh_mutex));
1712 mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1713 if(mesh->sock <= 0) {
1714 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
1716 meshlink_errno = MESHLINK_ENETWORK;
1717 pthread_mutex_unlock(&(mesh->mesh_mutex));
1721 if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1722 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1723 closesocket(mesh->sock);
1725 meshlink_errno = MESHLINK_ENETWORK;
1726 pthread_mutex_unlock(&(mesh->mesh_mutex));
1732 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
1734 // Tell him we have an invitation, and give him our throw-away key.
1738 if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1739 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1740 closesocket(mesh->sock);
1741 meshlink_errno = MESHLINK_ENETWORK;
1742 pthread_mutex_unlock(&(mesh->mesh_mutex));
1748 char hisname[4096] = "";
1749 int code, hismajor, hisminor = 0;
1751 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) {
1752 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
1753 closesocket(mesh->sock);
1754 meshlink_errno = MESHLINK_ENETWORK;
1755 pthread_mutex_unlock(&(mesh->mesh_mutex));
1759 // Check if the hash of the key he gave us matches the hash in the URL.
1760 char *fingerprint = mesh->line + 2;
1762 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1763 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
1764 meshlink_errno = MESHLINK_EINTERNAL;
1765 pthread_mutex_unlock(&(mesh->mesh_mutex));
1768 if(memcmp(hishash, mesh->hash, 18)) {
1769 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1770 meshlink_errno = MESHLINK_EPEER;
1771 pthread_mutex_unlock(&(mesh->mesh_mutex));
1776 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1778 meshlink_errno = MESHLINK_EINTERNAL;
1779 pthread_mutex_unlock(&(mesh->mesh_mutex));
1783 // Start an SPTPS session
1784 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive)) {
1785 meshlink_errno = MESHLINK_EINTERNAL;
1786 pthread_mutex_unlock(&(mesh->mesh_mutex));
1790 // Feed rest of input buffer to SPTPS
1791 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
1792 meshlink_errno = MESHLINK_EPEER;
1793 pthread_mutex_unlock(&(mesh->mesh_mutex));
1799 while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1803 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1804 meshlink_errno = MESHLINK_ENETWORK;
1805 pthread_mutex_unlock(&(mesh->mesh_mutex));
1809 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
1810 meshlink_errno = MESHLINK_EPEER;
1811 pthread_mutex_unlock(&(mesh->mesh_mutex));
1816 sptps_stop(&mesh->sptps);
1819 closesocket(mesh->sock);
1821 if(!mesh->success) {
1822 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
1823 meshlink_errno = MESHLINK_EPEER;
1824 pthread_mutex_unlock(&(mesh->mesh_mutex));
1828 pthread_mutex_unlock(&(mesh->mesh_mutex));
1832 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL or you are already connected to a Mesh ?\n");
1833 meshlink_errno = MESHLINK_EINVAL;
1834 pthread_mutex_unlock(&(mesh->mesh_mutex));
1838 char *meshlink_export(meshlink_handle_t *mesh) {
1840 meshlink_errno = MESHLINK_EINVAL;
1844 pthread_mutex_lock(&(mesh->mesh_mutex));
1846 char filename[PATH_MAX];
1847 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1848 FILE *f = fopen(filename, "r");
1850 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
1851 meshlink_errno = MESHLINK_ESTORAGE;
1852 pthread_mutex_unlock(&(mesh->mesh_mutex));
1856 fseek(f, 0, SEEK_END);
1857 int fsize = ftell(f);
1860 size_t len = fsize + 9 + strlen(mesh->self->name);
1861 char *buf = xmalloc(len);
1862 snprintf(buf, len, "Name = %s\n", mesh->self->name);
1863 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
1864 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
1866 meshlink_errno = MESHLINK_ESTORAGE;
1867 pthread_mutex_unlock(&(mesh->mesh_mutex));
1874 pthread_mutex_unlock(&(mesh->mesh_mutex));
1878 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1879 if(!mesh || !data) {
1880 meshlink_errno = MESHLINK_EINVAL;
1884 pthread_mutex_lock(&(mesh->mesh_mutex));
1886 if(strncmp(data, "Name = ", 7)) {
1887 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
1888 meshlink_errno = MESHLINK_EPEER;
1889 pthread_mutex_unlock(&(mesh->mesh_mutex));
1893 char *end = strchr(data + 7, '\n');
1895 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
1896 meshlink_errno = MESHLINK_EPEER;
1897 pthread_mutex_unlock(&(mesh->mesh_mutex));
1901 int len = end - (data + 7);
1903 memcpy(name, data + 7, len);
1905 if(!check_id(name)) {
1906 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
1907 meshlink_errno = MESHLINK_EPEER;
1908 pthread_mutex_unlock(&(mesh->mesh_mutex));
1912 char filename[PATH_MAX];
1913 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1914 if(!access(filename, F_OK)) {
1915 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
1916 meshlink_errno = MESHLINK_EEXIST;
1917 pthread_mutex_unlock(&(mesh->mesh_mutex));
1921 if(errno != ENOENT) {
1922 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
1923 meshlink_errno = MESHLINK_ESTORAGE;
1924 pthread_mutex_unlock(&(mesh->mesh_mutex));
1928 FILE *f = fopen(filename, "w");
1930 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1931 meshlink_errno = MESHLINK_ESTORAGE;
1932 pthread_mutex_unlock(&(mesh->mesh_mutex));
1936 fwrite(end + 1, strlen(end + 1), 1, f);
1939 load_all_nodes(mesh);
1941 pthread_mutex_unlock(&(mesh->mesh_mutex));
1945 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1946 if(!mesh || !node) {
1947 meshlink_errno = MESHLINK_EINVAL;
1951 pthread_mutex_lock(&(mesh->mesh_mutex));
1955 n->status.blacklisted=true;
1956 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n",node->name);
1958 //Make blacklisting persistent in the config file
1959 append_config_file(mesh, n->name, "blacklisted", "yes");
1961 pthread_mutex_unlock(&(mesh->mesh_mutex));
1965 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1966 if(!mesh || !node) {
1967 meshlink_errno = MESHLINK_EINVAL;
1971 pthread_mutex_lock(&(mesh->mesh_mutex));
1973 node_t *n = (node_t *)node;
1974 n->status.blacklisted = false;
1976 //TODO: remove blacklisted = yes from the config file
1978 pthread_mutex_unlock(&(mesh->mesh_mutex));
1982 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
1983 mesh->default_blacklist = blacklist;
1986 /* Hint that a hostname may be found at an address
1987 * See header file for detailed comment.
1989 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
1990 if(!mesh || !node || !addr)
1993 // Ignore hints about ourself.
1994 if((node_t *)node == mesh->self)
1997 pthread_mutex_lock(&(mesh->mesh_mutex));
1999 char *host = NULL, *port = NULL, *str = NULL;
2000 sockaddr2str((const sockaddr_t *)addr, &host, &port);
2003 xasprintf(&str, "%s %s", host, port);
2004 if ( (strncmp ("fe80",host,4) != 0) && ( strncmp("127.",host,4) != 0 ) && ( strcmp("localhost",host) !=0 ) )
2005 append_config_file(mesh, node->name, "Address", str);
2007 logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
2014 pthread_mutex_unlock(&(mesh->mesh_mutex));
2015 // @TODO do we want to fire off a connection attempt right away?
2018 /* Return an array of edges in the current network graph.
2019 * Data captures the current state and will not be updated.
2020 * Caller must deallocate data when done.
2022 meshlink_edge_t **meshlink_get_all_edges_state(meshlink_handle_t *mesh, meshlink_edge_t **edges, size_t *nmemb) {
2023 if(!mesh || !nmemb || (*nmemb && !edges)) {
2024 meshlink_errno = MESHLINK_EINVAL;
2028 pthread_mutex_lock(&(mesh->mesh_mutex));
2030 meshlink_edge_t **result = NULL;
2031 meshlink_edge_t *copy = NULL;
2032 int result_size = 0;
2034 result_size = mesh->edges->count;
2036 // if result is smaller than edges, we have to dealloc all the excess meshlink_edge_t
2037 if(result_size > *nmemb) {
2038 result = realloc(edges, result_size * sizeof (meshlink_edge_t*));
2044 meshlink_edge_t **p = result;
2046 for splay_each(edge_t, e, mesh->edges) {
2047 // skip edges that do not represent a two-directional connection
2048 if((!e->reverse) || (e->reverse->to != e->from)) {
2053 // the first *nmemb members of result can be re-used
2055 copy = xzalloc(sizeof *copy);
2060 copy->from = (meshlink_node_t*)e->from;
2061 copy->to = (meshlink_node_t*)e->to;
2062 copy->address = e->address.storage;
2063 copy->options = e->options;
2064 copy->weight = e->weight;
2067 // shrink result to the actual amount of memory used
2068 for(int i = *nmemb; i > result_size; i--) {
2069 free(result[i - 1]);
2071 result = realloc(result, result_size * sizeof (meshlink_edge_t*));
2072 *nmemb = result_size;
2075 meshlink_errno = MESHLINK_ENOMEM;
2078 pthread_mutex_unlock(&(mesh->mesh_mutex));
2083 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2088 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2089 meshlink_channel_t *channel = connection->priv;
2092 node_t *n = channel->node;
2093 meshlink_handle_t *mesh = n->mesh;
2094 if(!channel->receive_cb)
2097 channel->receive_cb(mesh, channel, data, len);
2102 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2103 node_t *n = utcp_connection->utcp->priv;
2106 meshlink_handle_t *mesh = n->mesh;
2107 if(!mesh->channel_accept_cb)
2109 meshlink_channel_t *channel = xzalloc(sizeof *channel);
2111 channel->c = utcp_connection;
2112 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0))
2113 utcp_accept(utcp_connection, channel_recv, channel);
2118 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2119 node_t *n = utcp->priv;
2120 meshlink_handle_t *mesh = n->mesh;
2121 char hex[len * 2 + 1];
2122 bin2hex(data, hex, len);
2123 logger(mesh, MESHLINK_WARNING, "channel_send(%p, %p, %zu): %s\n", utcp, data, len, hex);
2124 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? len : -1;
2127 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2128 if(!mesh || !channel) {
2129 meshlink_errno = MESHLINK_EINVAL;
2133 channel->receive_cb = cb;
2136 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2137 node_t *n = (node_t *)source;
2140 char hex[len * 2 + 1];
2141 bin2hex(data, hex, len);
2142 logger(mesh, MESHLINK_WARNING, "channel_receive(%p, %p, %zu): %s\n", n->utcp, data, len, hex);
2143 utcp_recv(n->utcp, data, len);
2146 static void channel_poll(struct utcp_connection *connection, size_t len) {
2147 meshlink_channel_t *channel = connection->priv;
2150 node_t *n = channel->node;
2151 meshlink_handle_t *mesh = n->mesh;
2152 if(channel->poll_cb)
2153 channel->poll_cb(mesh, channel, len);
2156 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2157 channel->poll_cb = cb;
2158 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2161 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2163 meshlink_errno = MESHLINK_EINVAL;
2167 pthread_mutex_lock(&mesh->mesh_mutex);
2168 mesh->channel_accept_cb = cb;
2169 mesh->receive_cb = channel_receive;
2170 for splay_each(node_t, n, mesh->nodes) {
2171 if(!n->utcp && n != mesh->self) {
2172 logger(mesh, MESHLINK_WARNING, "utcp_init on node %s", n->name);
2173 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2176 pthread_mutex_unlock(&mesh->mesh_mutex);
2179 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) {
2180 if(!mesh || !node) {
2181 meshlink_errno = MESHLINK_EINVAL;
2185 logger(mesh, MESHLINK_WARNING, "meshlink_channel_open(%p, %s, %u, %p, %p, %zu)\n", mesh, node->name, port, cb, data, len);
2186 node_t *n = (node_t *)node;
2188 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2189 mesh->receive_cb = channel_receive;
2191 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2195 meshlink_channel_t *channel = xzalloc(sizeof *channel);
2197 channel->receive_cb = cb;
2198 channel->c = utcp_connect(n->utcp, port, channel_recv, channel);
2200 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2207 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2208 if(!mesh || !channel) {
2209 meshlink_errno = MESHLINK_EINVAL;
2213 utcp_shutdown(channel->c, direction);
2216 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2217 if(!mesh || !channel) {
2218 meshlink_errno = MESHLINK_EINVAL;
2222 utcp_close(channel->c);
2226 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2227 if(!mesh || !channel) {
2228 meshlink_errno = MESHLINK_EINVAL;
2236 meshlink_errno = MESHLINK_EINVAL;
2240 // TODO: more finegrained locking.
2241 // Ideally we want to put the data into the UTCP connection's send buffer.
2242 // Then, preferrably only if there is room in the receiver window,
2243 // kick the meshlink thread to go send packets.
2245 pthread_mutex_lock(&mesh->mesh_mutex);
2246 ssize_t retval = utcp_send(channel->c, data, len);
2247 pthread_mutex_unlock(&mesh->mesh_mutex);
2250 meshlink_errno = MESHLINK_ENETWORK;
2254 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2255 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp)
2256 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2257 if(mesh->node_status_cb)
2258 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
2261 static void __attribute__((constructor)) meshlink_init(void) {
2265 static void __attribute__((destructor)) meshlink_exit(void) {
2269 /// Device class traits
2270 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX +1] = {
2271 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2272 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
2273 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
2274 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN