2 meshlink.c -- Implementation of the MeshLink API.
3 Copyright (C) 2014 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 */
34 #include "meshlink_internal.h"
41 #include "ed25519/sha512.h"
42 #include "discovery.h"
45 #define MSG_NOSIGNAL 0
48 __thread meshlink_errno_t meshlink_errno;
50 //TODO: this can go away completely
51 const var_t variables[] = {
52 /* Server configuration */
53 {"AddressFamily", VAR_SERVER},
54 {"AutoConnect", VAR_SERVER | VAR_SAFE},
55 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
56 {"BindToInterface", VAR_SERVER},
57 {"Broadcast", VAR_SERVER | VAR_SAFE},
58 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
59 {"DecrementTTL", VAR_SERVER},
60 {"Device", VAR_SERVER},
61 {"DeviceType", VAR_SERVER},
62 {"DirectOnly", VAR_SERVER},
63 {"ECDSAPrivateKeyFile", VAR_SERVER},
64 {"ExperimentalProtocol", VAR_SERVER},
65 {"Forwarding", VAR_SERVER},
66 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
67 {"Hostnames", VAR_SERVER},
68 {"IffOneQueue", VAR_SERVER},
69 {"Interface", VAR_SERVER},
70 {"KeyExpire", VAR_SERVER},
71 {"ListenAddress", VAR_SERVER | VAR_MULTIPLE},
72 {"LocalDiscovery", VAR_SERVER},
73 {"MACExpire", VAR_SERVER},
74 {"MaxConnectionBurst", VAR_SERVER},
75 {"MaxOutputBufferSize", VAR_SERVER},
76 {"MaxTimeout", VAR_SERVER},
77 {"Mode", VAR_SERVER | VAR_SAFE},
79 {"PingInterval", VAR_SERVER},
80 {"PingTimeout", VAR_SERVER},
81 {"PriorityInheritance", VAR_SERVER},
82 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
83 {"PrivateKeyFile", VAR_SERVER},
84 {"ProcessPriority", VAR_SERVER},
85 {"Proxy", VAR_SERVER},
86 {"ReplayWindow", VAR_SERVER},
87 {"ScriptsExtension", VAR_SERVER},
88 {"ScriptsInterpreter", VAR_SERVER},
89 {"StrictSubnets", VAR_SERVER},
90 {"TunnelServer", VAR_SERVER},
91 {"VDEGroup", VAR_SERVER},
92 {"VDEPort", VAR_SERVER},
93 /* Host configuration */
94 {"Address", VAR_HOST | VAR_MULTIPLE},
95 {"Cipher", VAR_SERVER | VAR_HOST},
96 {"ClampMSS", VAR_SERVER | VAR_HOST},
97 {"Compression", VAR_SERVER | VAR_HOST},
98 {"Digest", VAR_SERVER | VAR_HOST},
99 {"ECDSAPublicKey", VAR_HOST},
100 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
101 {"IndirectData", VAR_SERVER | VAR_HOST},
102 {"MACLength", VAR_SERVER | VAR_HOST},
103 {"PMTU", VAR_SERVER | VAR_HOST},
104 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
106 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
107 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
108 {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
109 {"TCPOnly", VAR_SERVER | VAR_HOST},
110 {"Weight", VAR_HOST | VAR_SAFE},
114 static bool fcopy(FILE *out, const char *filename) {
115 FILE *in = fopen(filename, "r");
117 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
123 while((len = fread(buf, 1, sizeof buf, in)))
124 fwrite(buf, len, 1, out);
129 static int rstrip(char *value) {
130 int len = strlen(value);
131 while(len && strchr("\t\r\n ", value[len - 1]))
136 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
138 if(!filename || (*hostname && *port))
141 FILE *f = fopen(filename, "r");
145 while(fgets(line, sizeof line, f)) {
149 p += strcspn(p, "\t =");
152 q = p + strspn(p, "\t ");
154 q += 1 + strspn(q + 1, "\t ");
156 p = q + strcspn(q, "\t ");
159 p += strspn(p, "\t ");
160 p[strcspn(p, "\t ")] = 0;
162 if(!*port && !strcasecmp(line, "Port")) {
164 } else if(!*hostname && !strcasecmp(line, "Address")) {
165 *hostname = xstrdup(q);
172 if(*hostname && *port)
178 static char *get_my_hostname(meshlink_handle_t* mesh) {
179 char *hostname = NULL;
181 char *hostport = NULL;
182 char *name = mesh->self->name;
183 char filename[PATH_MAX] = "";
187 // Use first Address statement in own host config file
188 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
189 scan_for_hostname(filename, &hostname, &port);
194 // If that doesn't work, guess externally visible hostname
195 fprintf(stderr, "Trying to discover externally visible hostname...\n");
196 struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
197 struct addrinfo *aip = ai;
198 static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
201 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
203 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
209 send(s, request, sizeof request - 1, 0);
210 int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
213 if(line[len - 1] == '\n')
215 char *p = strrchr(line, '\n');
217 hostname = xstrdup(p + 1);
230 // Check that the hostname is reasonable
232 for(char *p = hostname; *p; p++) {
233 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
235 // If not, forget it.
245 f = fopen(filename, "a");
247 fprintf(f, "\nAddress = %s\n", hostname);
250 fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
255 if(strchr(hostname, ':'))
256 xasprintf(&hostport, "[%s]:%s", hostname, port);
258 xasprintf(&hostport, "%s:%s", hostname, port);
260 if(strchr(hostname, ':'))
261 xasprintf(&hostport, "[%s]", hostname);
263 hostport = xstrdup(hostname);
271 static char *get_line(const char **data) {
280 static char line[1024];
281 const char *end = strchr(*data, '\n');
282 size_t len = end ? end - *data : strlen(*data);
283 if(len >= sizeof line) {
284 fprintf(stderr, "Maximum line length exceeded!\n");
287 if(len && !isprint(**data))
290 memcpy(line, *data, len);
301 static char *get_value(const char *data, const char *var) {
302 char *line = get_line(&data);
306 char *sep = line + strcspn(line, " \t=");
307 char *val = sep + strspn(sep, " \t");
309 val += 1 + strspn(val + 1, " \t");
311 if(strcasecmp(line, var))
316 static bool try_bind(int port) {
317 struct addrinfo *ai = NULL;
318 struct addrinfo hint = {
319 .ai_flags = AI_PASSIVE,
320 .ai_family = AF_UNSPEC,
321 .ai_socktype = SOCK_STREAM,
322 .ai_protocol = IPPROTO_TCP,
326 snprintf(portstr, sizeof portstr, "%d", port);
328 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
332 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
337 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
350 static int check_port(meshlink_handle_t *mesh) {
354 fprintf(stderr, "Warning: could not bind to port 655.\n");
356 for(int i = 0; i < 100; i++) {
357 int port = 0x1000 + (rand() & 0x7fff);
359 char filename[PATH_MAX];
360 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
361 FILE *f = fopen(filename, "a");
363 fprintf(stderr, "Please change MeshLink's Port manually.\n");
367 fprintf(f, "Port = %d\n", port);
369 fprintf(stderr, "MeshLink will instead listen on port %d.\n", port);
374 fprintf(stderr, "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 fprintf(stderr, "No Name found in invitation!\n");
385 if(!check_id(name)) {
386 fprintf(stderr, "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 fprintf(stderr, "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 fprintf(stderr, "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 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
452 } else if(!(variables[i].type & VAR_SAFE)) {
453 fprintf(stderr, "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 fprintf(stderr, "Invalid Name found in invitation.\n");
469 if(!strcmp(value, name)) {
470 fprintf(stderr, "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 fprintf(stderr, "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);
508 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
509 fprintf(fh, "Port = %s\n", mesh->myport);
513 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
516 free(mesh->self->name);
517 free(mesh->self->connection->name);
518 mesh->self->name = xstrdup(name);
519 mesh->self->connection->name = name;
521 fprintf(stderr, "Configuration stored in: %s\n", mesh->confbase);
523 load_all_nodes(mesh);
528 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
529 meshlink_handle_t* mesh = handle;
531 int result = send(mesh->sock, data, len, 0);
532 if(result == -1 && errno == EINTR)
542 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
543 meshlink_handle_t* mesh = handle;
545 case SPTPS_HANDSHAKE:
546 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof mesh->cookie);
549 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
550 memcpy(mesh->data + mesh->thedatalen, msg, len);
551 mesh->thedatalen += len;
552 mesh->data[mesh->thedatalen] = 0;
556 return finalize_join(mesh);
559 fprintf(stderr, "Invitation succesfully accepted.\n");
560 shutdown(mesh->sock, SHUT_RDWR);
561 mesh->success = true;
571 static bool recvline(meshlink_handle_t* mesh, size_t len) {
572 char *newline = NULL;
577 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
578 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof mesh->buffer - mesh->blen, 0);
579 if(result == -1 && errno == EINTR)
583 mesh->blen += result;
586 if(newline - mesh->buffer >= len)
589 len = newline - mesh->buffer;
591 memcpy(mesh->line, mesh->buffer, len);
593 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
594 mesh->blen -= len + 1;
598 static bool sendline(int fd, char *format, ...) {
599 static char buffer[4096];
604 va_start(ap, format);
605 blen = vsnprintf(buffer, sizeof buffer, format, ap);
608 if(blen < 1 || blen >= sizeof buffer)
615 int result = send(fd, p, blen, MSG_NOSIGNAL);
616 if(result == -1 && errno == EINTR)
627 static const char *errstr[] = {
628 [MESHLINK_OK] = "No error",
629 [MESHLINK_EINVAL] = "Invalid argument",
630 [MESHLINK_ENOMEM] = "Out of memory",
631 [MESHLINK_ENOENT] = "No such node",
632 [MESHLINK_EEXIST] = "Node already exists",
633 [MESHLINK_EINTERNAL] = "Internal error",
634 [MESHLINK_ERESOLV] = "Could not resolve hostname",
635 [MESHLINK_ESTORAGE] = "Storage error",
636 [MESHLINK_ENETWORK] = "Network error",
637 [MESHLINK_EPEER] = "Error communicating with peer",
640 const char *meshlink_strerror(meshlink_errno_t err) {
641 if(err < 0 || err >= sizeof errstr / sizeof *errstr)
642 return "Invalid error code";
646 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
649 char pubname[PATH_MAX], privname[PATH_MAX];
651 fprintf(stderr, "Generating ECDSA keypair:\n");
653 if(!(key = ecdsa_generate())) {
654 fprintf(stderr, "Error during key generation!\n");
655 meshlink_errno = MESHLINK_EINTERNAL;
658 fprintf(stderr, "Done.\n");
660 snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
661 f = fopen(privname, "w");
664 meshlink_errno = MESHLINK_ESTORAGE;
669 fchmod(fileno(f), 0600);
672 if(!ecdsa_write_pem_private_key(key, f)) {
673 fprintf(stderr, "Error writing private key!\n");
676 meshlink_errno = MESHLINK_EINTERNAL;
682 snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
683 f = fopen(pubname, "a");
686 meshlink_errno = MESHLINK_ESTORAGE;
690 char *pubkey = ecdsa_get_base64_public_key(key);
691 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
700 static bool meshlink_setup(meshlink_handle_t *mesh) {
701 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
702 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
703 meshlink_errno = MESHLINK_ESTORAGE;
707 char filename[PATH_MAX];
708 snprintf(filename, sizeof filename, "%s" SLASH "hosts", mesh->confbase);
710 if(mkdir(filename, 0777) && errno != EEXIST) {
711 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
712 meshlink_errno = MESHLINK_ESTORAGE;
716 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
718 if(!access(filename, F_OK)) {
719 fprintf(stderr, "Configuration file %s already exists!\n", filename);
720 meshlink_errno = MESHLINK_EEXIST;
724 FILE *f = fopen(filename, "w");
726 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
727 meshlink_errno = MESHLINK_ESTORAGE;
731 fprintf(f, "Name = %s\n", mesh->name);
734 if(!ecdsa_keygen(mesh)) {
735 meshlink_errno = MESHLINK_EINTERNAL;
744 meshlink_handle_t *meshlink_open(const char *confbase, const char *name) {
745 // Validate arguments provided by the application
746 bool usingname = false;
748 if(!confbase || !*confbase) {
749 fprintf(stderr, "No confbase given!\n");
750 meshlink_errno = MESHLINK_EINVAL;
754 if(!name || !*name) {
755 fprintf(stderr, "No name given!\n");
758 else { //check name only if there is a name != NULL
760 if(!check_id(name)) {
761 fprintf(stderr, "Invalid name given!\n");
762 meshlink_errno = MESHLINK_EINVAL;
764 } else { usingname = true;}
767 meshlink_handle_t *mesh = xzalloc(sizeof *mesh);
768 mesh->confbase = xstrdup(confbase);
769 if (usingname) mesh->name = xstrdup(name);
770 pthread_mutex_init ( &(mesh->outpacketqueue_mutex), NULL);
771 pthread_mutex_init ( &(mesh->nodes_mutex), NULL);
772 mesh->threadstarted = false;
773 event_loop_init(&mesh->loop);
774 mesh->loop.data = mesh;
776 // TODO: should be set by a function.
777 mesh->debug_level = 5;
779 // Check whether meshlink.conf already exists
781 char filename[PATH_MAX];
782 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
784 if(access(filename, R_OK)) {
785 if(errno == ENOENT) {
787 if(!meshlink_setup(mesh)) {
788 // meshlink_errno is set by meshlink_setup()
792 fprintf(stderr, "Cannot not read from %s: %s\n", filename, strerror(errno));
793 meshlink_close(mesh);
794 meshlink_errno = MESHLINK_ESTORAGE;
799 // Read the configuration
801 init_configuration(&mesh->config);
803 if(!read_server_config(mesh)) {
804 meshlink_close(mesh);
805 meshlink_errno = MESHLINK_ESTORAGE;
810 struct WSAData wsa_state;
811 WSAStartup(MAKEWORD(2, 2), &wsa_state);
814 // Setup up everything
815 // TODO: we should not open listening sockets yet
817 if(!setup_network(mesh)) {
818 meshlink_close(mesh);
819 meshlink_errno = MESHLINK_ENETWORK;
826 static void *meshlink_main_loop(void *arg) {
827 meshlink_handle_t *mesh = arg;
829 try_outgoing_connections(mesh);
836 bool meshlink_start(meshlink_handle_t *mesh) {
838 meshlink_errno = MESHLINK_EINVAL;
842 // TODO: open listening sockets first
844 //Check that a valid name is set
846 fprintf(stderr, "No name given!\n");
847 meshlink_errno = MESHLINK_EINVAL;
851 // Start the main thread
853 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
854 fprintf(stderr, "Could not start thread: %s\n", strerror(errno));
855 memset(&mesh->thread, 0, sizeof mesh->thread);
856 meshlink_errno = MESHLINK_EINTERNAL;
860 mesh->threadstarted=true;
863 if(!discovery_start(mesh))
869 void meshlink_stop(meshlink_handle_t *mesh) {
871 meshlink_errno = MESHLINK_EINVAL;
876 discovery_stop(mesh);
878 // Shut down the listening sockets to signal the main thread to shut down
880 for(int i = 0; i < mesh->listen_sockets; i++) {
881 shutdown(mesh->listen_socket[i].tcp.fd, SHUT_RDWR);
882 shutdown(mesh->listen_socket[i].udp.fd, SHUT_RDWR);
885 // Wait for the main thread to finish
887 pthread_join(mesh->thread, NULL);
890 void meshlink_close(meshlink_handle_t *mesh) {
891 if(!mesh || !mesh->confbase) {
892 meshlink_errno = MESHLINK_EINVAL;
896 // Close and free all resources used.
898 close_network_connections(mesh);
900 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
902 exit_configuration(&mesh->config);
903 event_loop_exit(&mesh->loop);
910 ecdsa_free(mesh->invitation_key);
913 free(mesh->confbase);
915 memset(mesh, 0, sizeof *mesh);
920 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
922 meshlink_errno = MESHLINK_EINVAL;
926 mesh->receive_cb = cb;
929 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
931 meshlink_errno = MESHLINK_EINVAL;
935 mesh->node_status_cb = cb;
938 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
940 meshlink_errno = MESHLINK_EINVAL;
945 mesh->log_level = level;
948 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
949 if(!mesh || !destination) {
950 meshlink_errno = MESHLINK_EINVAL;
958 meshlink_errno = MESHLINK_EINVAL;
962 /* If there is no outgoing list yet, create one. */
964 if(!mesh->outpacketqueue)
965 mesh->outpacketqueue = list_alloc(NULL);
967 //add packet to the queue
968 outpacketqueue_t *packet_in_queue = xzalloc(sizeof *packet_in_queue);
969 packet_in_queue->destination=destination;
970 packet_in_queue->data=data;
971 packet_in_queue->len=len;
972 pthread_mutex_lock(&(mesh->outpacketqueue_mutex));
973 list_insert_head(mesh->outpacketqueue,packet_in_queue);
974 pthread_mutex_unlock(&(mesh->outpacketqueue_mutex));
977 signal_trigger(&(mesh->loop),&(mesh->datafromapp));
981 void meshlink_send_from_queue(event_loop_t* el,meshlink_handle_t *mesh) {
983 meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
985 outpacketqueue_t* p = list_get_tail(mesh->outpacketqueue);
987 list_delete_tail(mesh->outpacketqueue);
990 if (sizeof(meshlink_packethdr_t) + p->len > MAXSIZE) {
995 packet.probe = false;
996 memset(hdr, 0, sizeof *hdr);
997 memcpy(hdr->destination, p->destination->name, sizeof hdr->destination);
998 memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
1000 packet.len = sizeof *hdr + p->len;
1001 memcpy(packet.data + sizeof *hdr, p->data, p->len);
1003 mesh->self->in_packets++;
1004 mesh->self->in_bytes += packet.len;
1005 route(mesh, mesh->self, &packet);
1009 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1010 if(!mesh || !destination) {
1011 meshlink_errno = MESHLINK_EINVAL;
1015 node_t *n = (node_t *)destination;
1016 if(!n->status.reachable)
1018 else if(n->mtuprobes > 30 && n->minmtu)
1024 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1025 if(!mesh || !node) {
1026 meshlink_errno = MESHLINK_EINVAL;
1030 node_t *n = (node_t *)node;
1032 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1033 meshlink_errno = MESHLINK_EINTERNAL;
1037 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1040 meshlink_errno = MESHLINK_EINTERNAL;
1045 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1046 if(!mesh || !name) {
1047 meshlink_errno = MESHLINK_EINVAL;
1051 return (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1054 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1055 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1056 meshlink_errno = MESHLINK_EINVAL;
1060 meshlink_node_t **result;
1063 pthread_mutex_lock(&(mesh->nodes_mutex));
1065 *nmemb = mesh->nodes->count;
1066 result = realloc(nodes, *nmemb * sizeof *nodes);
1069 meshlink_node_t **p = result;
1070 for splay_each(node_t, n, mesh->nodes)
1071 *p++ = (meshlink_node_t *)n;
1075 meshlink_errno = MESHLINK_ENOMEM;
1078 pthread_mutex_unlock(&(mesh->nodes_mutex));
1083 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1084 if(!mesh || !data || !len || !signature || !siglen) {
1085 meshlink_errno = MESHLINK_EINVAL;
1089 if(*siglen < MESHLINK_SIGLEN) {
1090 meshlink_errno = MESHLINK_EINVAL;
1094 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1095 meshlink_errno = MESHLINK_EINTERNAL;
1099 *siglen = MESHLINK_SIGLEN;
1103 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1104 if(!mesh || !data || !len || !signature) {
1105 meshlink_errno = MESHLINK_EINVAL;
1109 if(siglen != MESHLINK_SIGLEN) {
1110 meshlink_errno = MESHLINK_EINVAL;
1114 struct node_t *n = (struct node_t *)source;
1115 node_read_ecdsa_public_key(mesh, n);
1117 meshlink_errno = MESHLINK_EINTERNAL;
1121 return ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1124 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1125 char filename[PATH_MAX];
1127 snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
1128 if(mkdir(filename, 0700) && errno != EEXIST) {
1129 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
1130 meshlink_errno = MESHLINK_ESTORAGE;
1134 // Count the number of valid invitations, clean up old ones
1135 DIR *dir = opendir(filename);
1137 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
1138 meshlink_errno = MESHLINK_ESTORAGE;
1145 time_t deadline = time(NULL) - 604800; // 1 week in the past
1147 while((ent = readdir(dir))) {
1148 if(strlen(ent->d_name) != 24)
1150 char invname[PATH_MAX];
1152 snprintf(invname, sizeof invname, "%s" SLASH "%s", filename, ent->d_name);
1153 if(!stat(invname, &st)) {
1154 if(mesh->invitation_key && deadline < st.st_mtime)
1159 fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
1165 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
1167 meshlink_errno = MESHLINK_ESTORAGE;
1173 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1175 // Remove the key if there are no outstanding invitations.
1178 if(mesh->invitation_key) {
1179 ecdsa_free(mesh->invitation_key);
1180 mesh->invitation_key = NULL;
1184 if(mesh->invitation_key)
1187 // Create a new key if necessary.
1188 FILE *f = fopen(filename, "r");
1190 if(errno != ENOENT) {
1191 fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
1192 meshlink_errno = MESHLINK_ESTORAGE;
1196 mesh->invitation_key = ecdsa_generate();
1197 if(!mesh->invitation_key) {
1198 fprintf(stderr, "Could not generate a new key!\n");
1199 meshlink_errno = MESHLINK_EINTERNAL;
1202 f = fopen(filename, "w");
1204 fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
1205 meshlink_errno = MESHLINK_ESTORAGE;
1208 chmod(filename, 0600);
1209 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1212 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1214 if(!mesh->invitation_key) {
1215 fprintf(stderr, "Could not read private key from %s\n", filename);
1216 meshlink_errno = MESHLINK_ESTORAGE;
1220 return mesh->invitation_key;
1223 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1224 if(!mesh || !address) {
1225 meshlink_errno = MESHLINK_EINVAL;
1229 for(const char *p = address; *p; p++) {
1230 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
1232 fprintf(stderr, "Invalid character in address: %s\n", address);
1233 meshlink_errno = MESHLINK_EINVAL;
1237 return append_config_file(mesh, mesh->self->name, "Address", address);
1240 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1242 meshlink_errno = MESHLINK_EINVAL;
1246 // Check validity of the new node's name
1247 if(!check_id(name)) {
1248 fprintf(stderr, "Invalid name for node.\n");
1249 meshlink_errno = MESHLINK_EINVAL;
1253 // Ensure no host configuration file with that name exists
1254 char filename[PATH_MAX];
1255 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1256 if(!access(filename, F_OK)) {
1257 fprintf(stderr, "A host config file for %s already exists!\n", name);
1258 meshlink_errno = MESHLINK_EEXIST;
1262 // Ensure no other nodes know about this name
1263 if(meshlink_get_node(mesh, name)) {
1264 fprintf(stderr, "A node with name %s is already known!\n", name);
1265 meshlink_errno = MESHLINK_EEXIST;
1269 // Get the local address
1270 char *address = get_my_hostname(mesh);
1272 fprintf(stderr, "No Address known for ourselves!\n");
1273 meshlink_errno = MESHLINK_ERESOLV;
1277 if(!refresh_invitation_key(mesh)) {
1278 meshlink_errno = MESHLINK_EINTERNAL;
1284 // Create a hash of the key.
1285 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1286 sha512(fingerprint, strlen(fingerprint), hash);
1287 b64encode_urlsafe(hash, hash, 18);
1289 // Create a random cookie for this invitation.
1291 randomize(cookie, 18);
1293 // Create a filename that doesn't reveal the cookie itself
1294 char buf[18 + strlen(fingerprint)];
1295 char cookiehash[64];
1296 memcpy(buf, cookie, 18);
1297 memcpy(buf + 18, fingerprint, sizeof buf - 18);
1298 sha512(buf, sizeof buf, cookiehash);
1299 b64encode_urlsafe(cookiehash, cookiehash, 18);
1301 b64encode_urlsafe(cookie, cookie, 18);
1305 // Create a file containing the details of the invitation.
1306 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1307 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1309 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1310 meshlink_errno = MESHLINK_ESTORAGE;
1313 FILE *f = fdopen(ifd, "w");
1317 // Fill in the details.
1318 fprintf(f, "Name = %s\n", name);
1320 // fprintf(f, "NetName = %s\n", netname);
1321 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1323 // Copy Broadcast and Mode
1324 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
1325 FILE *tc = fopen(filename, "r");
1328 while(fgets(buf, sizeof buf, tc)) {
1329 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1330 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1332 // Make sure there is a newline character.
1333 if(!strchr(buf, '\n'))
1339 fprintf(stderr, "Could not create %s: %s\n", filename, strerror(errno));
1340 meshlink_errno = MESHLINK_ESTORAGE;
1344 fprintf(f, "#---------------------------------------------------------------#\n");
1345 fprintf(f, "Name = %s\n", mesh->self->name);
1347 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1351 // Create an URL from the local address, key hash and cookie
1353 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1359 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1360 if(!mesh || !invitation) {
1361 meshlink_errno = MESHLINK_EINVAL;
1365 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1366 char copy[strlen(invitation) + 1];
1367 strcpy(copy, invitation);
1369 // Split the invitation URL into hostname, port, key hash and cookie.
1371 char *slash = strchr(copy, '/');
1377 if(strlen(slash) != 48)
1380 char *address = copy;
1382 if(*address == '[') {
1384 char *bracket = strchr(address, ']');
1388 if(bracket[1] == ':')
1391 port = strchr(address, ':');
1399 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1402 // Generate a throw-away key for the invitation.
1403 ecdsa_t *key = ecdsa_generate();
1405 meshlink_errno = MESHLINK_EINTERNAL;
1409 char *b64key = ecdsa_get_base64_public_key(key);
1411 //Before doing meshlink_join make sure we are not connected to another mesh
1412 if ( mesh->threadstarted ){
1416 // Connect to the meshlink daemon mentioned in the URL.
1417 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1419 meshlink_errno = MESHLINK_ERESOLV;
1423 mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1424 if(mesh->sock <= 0) {
1425 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
1427 meshlink_errno = MESHLINK_ENETWORK;
1431 if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1432 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1433 closesocket(mesh->sock);
1435 meshlink_errno = MESHLINK_ENETWORK;
1441 fprintf(stderr, "Connected to %s port %s...\n", address, port);
1443 // Tell him we have an invitation, and give him our throw-away key.
1447 if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1448 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1449 closesocket(mesh->sock);
1450 meshlink_errno = MESHLINK_ENETWORK;
1456 char hisname[4096] = "";
1457 int code, hismajor, hisminor = 0;
1459 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) {
1460 fprintf(stderr, "Cannot read greeting from peer\n");
1461 closesocket(mesh->sock);
1462 meshlink_errno = MESHLINK_ENETWORK;
1466 // Check if the hash of the key he gave us matches the hash in the URL.
1467 char *fingerprint = mesh->line + 2;
1469 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1470 fprintf(stderr, "Could not create hash\n%s\n", mesh->line + 2);
1471 meshlink_errno = MESHLINK_EINTERNAL;
1474 if(memcmp(hishash, mesh->hash, 18)) {
1475 fprintf(stderr, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1476 meshlink_errno = MESHLINK_EPEER;
1481 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1483 meshlink_errno = MESHLINK_EINTERNAL;
1487 // Start an SPTPS session
1488 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive)) {
1489 meshlink_errno = MESHLINK_EINTERNAL;
1493 // Feed rest of input buffer to SPTPS
1494 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
1495 meshlink_errno = MESHLINK_EPEER;
1501 while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1505 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1506 meshlink_errno = MESHLINK_ENETWORK;
1510 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
1511 meshlink_errno = MESHLINK_EPEER;
1516 sptps_stop(&mesh->sptps);
1519 closesocket(mesh->sock);
1521 if(!mesh->success) {
1522 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
1523 meshlink_errno = MESHLINK_EPEER;
1530 fprintf(stderr, "Invalid invitation URL or you are already connected to a Mesh ?\n");
1531 meshlink_errno = MESHLINK_EINVAL;
1535 char *meshlink_export(meshlink_handle_t *mesh) {
1537 meshlink_errno = MESHLINK_EINVAL;
1541 char filename[PATH_MAX];
1542 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1543 FILE *f = fopen(filename, "r");
1545 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
1546 meshlink_errno = MESHLINK_ESTORAGE;
1550 fseek(f, 0, SEEK_END);
1551 int fsize = ftell(f);
1554 size_t len = fsize + 9 + strlen(mesh->self->name);
1555 char *buf = xmalloc(len);
1556 snprintf(buf, len, "Name = %s\n", mesh->self->name);
1557 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
1558 fprintf(stderr, "Error reading from %s: %s\n", filename, strerror(errno));
1560 meshlink_errno = MESHLINK_ESTORAGE;
1569 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1570 if(!mesh || !data) {
1571 meshlink_errno = MESHLINK_EINVAL;
1575 if(strncmp(data, "Name = ", 7)) {
1576 fprintf(stderr, "Invalid data\n");
1577 meshlink_errno = MESHLINK_EPEER;
1581 char *end = strchr(data + 7, '\n');
1583 fprintf(stderr, "Invalid data\n");
1584 meshlink_errno = MESHLINK_EPEER;
1588 int len = end - (data + 7);
1590 memcpy(name, data + 7, len);
1592 if(!check_id(name)) {
1593 fprintf(stderr, "Invalid Name\n");
1594 meshlink_errno = MESHLINK_EPEER;
1598 char filename[PATH_MAX];
1599 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1600 if(!access(filename, F_OK)) {
1601 fprintf(stderr, "File %s already exists, not importing\n", filename);
1602 meshlink_errno = MESHLINK_EEXIST;
1606 if(errno != ENOENT) {
1607 fprintf(stderr, "Error accessing %s: %s\n", filename, strerror(errno));
1608 meshlink_errno = MESHLINK_ESTORAGE;
1612 FILE *f = fopen(filename, "w");
1614 fprintf(stderr, "Could not create %s: %s\n", filename, strerror(errno));
1615 meshlink_errno = MESHLINK_ESTORAGE;
1619 fwrite(end + 1, strlen(end + 1), 1, f);
1622 load_all_nodes(mesh);
1627 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1628 if(!mesh || !node) {
1629 meshlink_errno = MESHLINK_EINVAL;
1635 n->status.blacklisted=true;
1636 fprintf(stderr, "Blacklisted %s.\n",node->name);
1638 //Make blacklisting persistent in the config file
1639 append_config_file(mesh, n->name, "blacklisted", "yes");
1644 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1645 if(!mesh || !node) {
1646 meshlink_errno = MESHLINK_EINVAL;
1650 node_t *n = (node_t *)node;
1651 n->status.blacklisted = false;
1653 //TODO: remove blacklisted = yes from the config file
1658 static void __attribute__((constructor)) meshlink_init(void) {
1662 static void __attribute__((destructor)) meshlink_exit(void) {