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"
44 #define MSG_NOSIGNAL 0
47 __thread meshlink_errno_t meshlink_errno;
49 //TODO: this can go away completely
50 const var_t variables[] = {
51 /* Server configuration */
52 {"AddressFamily", VAR_SERVER},
53 {"AutoConnect", VAR_SERVER | VAR_SAFE},
54 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
55 {"BindToInterface", VAR_SERVER},
56 {"Broadcast", VAR_SERVER | VAR_SAFE},
57 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
58 {"DecrementTTL", VAR_SERVER},
59 {"Device", VAR_SERVER},
60 {"DeviceType", VAR_SERVER},
61 {"DirectOnly", VAR_SERVER},
62 {"ECDSAPrivateKeyFile", VAR_SERVER},
63 {"ExperimentalProtocol", VAR_SERVER},
64 {"Forwarding", VAR_SERVER},
65 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
66 {"Hostnames", VAR_SERVER},
67 {"IffOneQueue", VAR_SERVER},
68 {"Interface", VAR_SERVER},
69 {"KeyExpire", VAR_SERVER},
70 {"ListenAddress", VAR_SERVER | VAR_MULTIPLE},
71 {"LocalDiscovery", VAR_SERVER},
72 {"MACExpire", VAR_SERVER},
73 {"MaxConnectionBurst", VAR_SERVER},
74 {"MaxOutputBufferSize", VAR_SERVER},
75 {"MaxTimeout", VAR_SERVER},
76 {"Mode", VAR_SERVER | VAR_SAFE},
78 {"PingInterval", VAR_SERVER},
79 {"PingTimeout", VAR_SERVER},
80 {"PriorityInheritance", VAR_SERVER},
81 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
82 {"PrivateKeyFile", VAR_SERVER},
83 {"ProcessPriority", VAR_SERVER},
84 {"Proxy", VAR_SERVER},
85 {"ReplayWindow", VAR_SERVER},
86 {"ScriptsExtension", VAR_SERVER},
87 {"ScriptsInterpreter", VAR_SERVER},
88 {"StrictSubnets", VAR_SERVER},
89 {"TunnelServer", VAR_SERVER},
90 {"VDEGroup", VAR_SERVER},
91 {"VDEPort", VAR_SERVER},
92 /* Host configuration */
93 {"Address", VAR_HOST | VAR_MULTIPLE},
94 {"Cipher", VAR_SERVER | VAR_HOST},
95 {"ClampMSS", VAR_SERVER | VAR_HOST},
96 {"Compression", VAR_SERVER | VAR_HOST},
97 {"Digest", VAR_SERVER | VAR_HOST},
98 {"ECDSAPublicKey", VAR_HOST},
99 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
100 {"IndirectData", VAR_SERVER | VAR_HOST},
101 {"MACLength", VAR_SERVER | VAR_HOST},
102 {"PMTU", VAR_SERVER | VAR_HOST},
103 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
105 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
106 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
107 {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
108 {"TCPOnly", VAR_SERVER | VAR_HOST},
109 {"Weight", VAR_HOST | VAR_SAFE},
113 static bool fcopy(FILE *out, const char *filename) {
114 FILE *in = fopen(filename, "r");
116 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
122 while((len = fread(buf, 1, sizeof buf, in)))
123 fwrite(buf, len, 1, out);
128 static int rstrip(char *value) {
129 int len = strlen(value);
130 while(len && strchr("\t\r\n ", value[len - 1]))
135 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
137 if(!filename || (*hostname && *port))
140 FILE *f = fopen(filename, "r");
144 while(fgets(line, sizeof line, f)) {
148 p += strcspn(p, "\t =");
151 q = p + strspn(p, "\t ");
153 q += 1 + strspn(q + 1, "\t ");
155 p = q + strcspn(q, "\t ");
158 p += strspn(p, "\t ");
159 p[strcspn(p, "\t ")] = 0;
161 if(!*port && !strcasecmp(line, "Port")) {
163 } else if(!*hostname && !strcasecmp(line, "Address")) {
164 *hostname = xstrdup(q);
171 if(*hostname && *port)
177 static char *get_my_hostname(meshlink_handle_t* mesh) {
178 char *hostname = NULL;
180 char *hostport = NULL;
181 char *name = mesh->self->name;
182 char filename[PATH_MAX] = "";
186 // Use first Address statement in own host config file
187 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
188 scan_for_hostname(filename, &hostname, &port);
193 // If that doesn't work, guess externally visible hostname
194 fprintf(stderr, "Trying to discover externally visible hostname...\n");
195 struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
196 struct addrinfo *aip = ai;
197 static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
200 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
202 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
208 send(s, request, sizeof request - 1, 0);
209 int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
212 if(line[len - 1] == '\n')
214 char *p = strrchr(line, '\n');
216 hostname = xstrdup(p + 1);
229 // Check that the hostname is reasonable
231 for(char *p = hostname; *p; p++) {
232 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
234 // If not, forget it.
244 f = fopen(filename, "a");
246 fprintf(f, "\nAddress = %s\n", hostname);
249 fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
254 if(strchr(hostname, ':'))
255 xasprintf(&hostport, "[%s]:%s", hostname, port);
257 xasprintf(&hostport, "%s:%s", hostname, port);
259 if(strchr(hostname, ':'))
260 xasprintf(&hostport, "[%s]", hostname);
262 hostport = xstrdup(hostname);
270 static char *get_line(const char **data) {
279 static char line[1024];
280 const char *end = strchr(*data, '\n');
281 size_t len = end ? end - *data : strlen(*data);
282 if(len >= sizeof line) {
283 fprintf(stderr, "Maximum line length exceeded!\n");
286 if(len && !isprint(**data))
289 memcpy(line, *data, len);
300 static char *get_value(const char *data, const char *var) {
301 char *line = get_line(&data);
305 char *sep = line + strcspn(line, " \t=");
306 char *val = sep + strspn(sep, " \t");
308 val += 1 + strspn(val + 1, " \t");
310 if(strcasecmp(line, var))
315 static bool try_bind(int port) {
316 struct addrinfo *ai = NULL;
317 struct addrinfo hint = {
318 .ai_flags = AI_PASSIVE,
319 .ai_family = AF_UNSPEC,
320 .ai_socktype = SOCK_STREAM,
321 .ai_protocol = IPPROTO_TCP,
325 snprintf(portstr, sizeof portstr, "%d", port);
327 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
331 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
336 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
349 static int check_port(meshlink_handle_t *mesh) {
350 for(int i = 0; i < 1000; i++) {
351 int port = 0x1000 + (rand() & 0x7fff);
353 char filename[PATH_MAX];
354 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
355 FILE *f = fopen(filename, "a");
357 fprintf(stderr, "Please change MeshLink's Port manually.\n");
361 fprintf(f, "Port = %d\n", port);
367 fprintf(stderr, "Please change MeshLink's Port manually.\n");
371 static bool finalize_join(meshlink_handle_t *mesh) {
372 char *name = xstrdup(get_value(mesh->data, "Name"));
374 fprintf(stderr, "No Name found in invitation!\n");
378 if(!check_id(name)) {
379 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
383 char filename[PATH_MAX];
384 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
386 FILE *f = fopen(filename, "w");
388 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
392 fprintf(f, "Name = %s\n", name);
394 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
395 FILE *fh = fopen(filename, "w");
397 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
402 // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
403 // Other chunks go unfiltered to their respective host config files
404 const char *p = mesh->data;
407 while((l = get_line(&p))) {
412 // Split line into variable and value
413 int len = strcspn(l, "\t =");
415 value += strspn(value, "\t ");
418 value += strspn(value, "\t ");
423 if(!strcasecmp(l, "Name"))
424 if(strcmp(value, name))
428 else if(!strcasecmp(l, "NetName"))
431 // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
434 for(i = 0; variables[i].name; i++) {
435 if(strcasecmp(l, variables[i].name))
441 // Ignore unknown and unsafe variables
443 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
445 } else if(!(variables[i].type & VAR_SAFE)) {
446 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
450 // Copy the safe variable to the right config file
451 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
456 while(l && !strcasecmp(l, "Name")) {
457 if(!check_id(value)) {
458 fprintf(stderr, "Invalid Name found in invitation.\n");
462 if(!strcmp(value, name)) {
463 fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
467 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
468 f = fopen(filename, "w");
471 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
475 while((l = get_line(&p))) {
476 if(!strcmp(l, "#---------------------------------------------------------------#"))
478 int len = strcspn(l, "\t =");
479 if(len == 4 && !strncasecmp(l, "Name", 4)) {
481 value += strspn(value, "\t ");
484 value += strspn(value, "\t ");
497 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
501 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
502 fprintf(fh, "Port = %s\n", mesh->myport);
506 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
509 free(mesh->self->name);
510 free(mesh->self->connection->name);
511 mesh->self->name = xstrdup(name);
512 mesh->self->connection->name = name;
514 fprintf(stderr, "Configuration stored in: %s\n", mesh->confbase);
516 load_all_nodes(mesh);
521 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
522 meshlink_handle_t* mesh = handle;
524 int result = send(mesh->sock, data, len, 0);
525 if(result == -1 && errno == EINTR)
535 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
536 meshlink_handle_t* mesh = handle;
538 case SPTPS_HANDSHAKE:
539 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof mesh->cookie);
542 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
543 memcpy(mesh->data + mesh->thedatalen, msg, len);
544 mesh->thedatalen += len;
545 mesh->data[mesh->thedatalen] = 0;
549 return finalize_join(mesh);
552 fprintf(stderr, "Invitation succesfully accepted.\n");
553 shutdown(mesh->sock, SHUT_RDWR);
554 mesh->success = true;
564 static bool recvline(meshlink_handle_t* mesh, size_t len) {
565 char *newline = NULL;
570 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
571 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof mesh->buffer - mesh->blen, 0);
572 if(result == -1 && errno == EINTR)
576 mesh->blen += result;
579 if(newline - mesh->buffer >= len)
582 len = newline - mesh->buffer;
584 memcpy(mesh->line, mesh->buffer, len);
586 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
587 mesh->blen -= len + 1;
591 static bool sendline(int fd, char *format, ...) {
592 static char buffer[4096];
597 va_start(ap, format);
598 blen = vsnprintf(buffer, sizeof buffer, format, ap);
601 if(blen < 1 || blen >= sizeof buffer)
608 int result = send(fd, p, blen, MSG_NOSIGNAL);
609 if(result == -1 && errno == EINTR)
620 static const char *errstr[] = {
621 [MESHLINK_OK] = "No error",
622 [MESHLINK_EINVAL] = "Invalid argument",
623 [MESHLINK_ENOMEM] = "Out of memory",
624 [MESHLINK_ENOENT] = "No such node",
625 [MESHLINK_EEXIST] = "Node already exists",
626 [MESHLINK_EINTERNAL] = "Internal error",
627 [MESHLINK_ERESOLV] = "Could not resolve hostname",
628 [MESHLINK_ESTORAGE] = "Storage error",
629 [MESHLINK_ENETWORK] = "Network error",
630 [MESHLINK_EPEER] = "Error communicating with peer",
633 const char *meshlink_strerror(meshlink_errno_t err) {
634 if(err < 0 || err >= sizeof errstr / sizeof *errstr)
635 return "Invalid error code";
639 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
642 char pubname[PATH_MAX], privname[PATH_MAX];
644 fprintf(stderr, "Generating ECDSA keypair:\n");
646 if(!(key = ecdsa_generate())) {
647 fprintf(stderr, "Error during key generation!\n");
648 meshlink_errno = MESHLINK_EINTERNAL;
651 fprintf(stderr, "Done.\n");
653 snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
654 f = fopen(privname, "w");
657 meshlink_errno = MESHLINK_ESTORAGE;
662 fchmod(fileno(f), 0600);
665 if(!ecdsa_write_pem_private_key(key, f)) {
666 fprintf(stderr, "Error writing private key!\n");
669 meshlink_errno = MESHLINK_EINTERNAL;
675 snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
676 f = fopen(pubname, "a");
679 meshlink_errno = MESHLINK_ESTORAGE;
683 char *pubkey = ecdsa_get_base64_public_key(key);
684 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
693 static bool meshlink_setup(meshlink_handle_t *mesh) {
694 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
695 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
696 meshlink_errno = MESHLINK_ESTORAGE;
700 char filename[PATH_MAX];
701 snprintf(filename, sizeof filename, "%s" SLASH "hosts", mesh->confbase);
703 if(mkdir(filename, 0777) && errno != EEXIST) {
704 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
705 meshlink_errno = MESHLINK_ESTORAGE;
709 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
711 if(!access(filename, F_OK)) {
712 fprintf(stderr, "Configuration file %s already exists!\n", filename);
713 meshlink_errno = MESHLINK_EEXIST;
717 FILE *f = fopen(filename, "w");
719 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
720 meshlink_errno = MESHLINK_ESTORAGE;
724 fprintf(f, "Name = %s\n", mesh->name);
727 if(!ecdsa_keygen(mesh)) {
728 meshlink_errno = MESHLINK_EINTERNAL;
738 meshlink_handle_t *meshlink_open(const char *confbase, const char *name) {
739 return meshlink_open_with_size(confbase, name, sizeof(meshlink_handle_t) );
743 meshlink_handle_t *meshlink_open_with_size(const char *confbase, const char *name, size_t size) {
744 // Validate arguments provided by the application
745 bool usingname = false;
747 if(!confbase || !*confbase) {
748 fprintf(stderr, "No confbase given!\n");
749 meshlink_errno = MESHLINK_EINVAL;
753 if(!name || !*name) {
754 fprintf(stderr, "No name given!\n");
757 else { //check name only if there is a name != NULL
759 if(!check_id(name)) {
760 fprintf(stderr, "Invalid name given!\n");
761 meshlink_errno = MESHLINK_EINVAL;
763 } else { usingname = true;}
766 meshlink_handle_t *mesh = xzalloc(size);
767 mesh->confbase = xstrdup(confbase);
768 if (usingname) mesh->name = xstrdup(name);
769 pthread_mutex_init ( &(mesh->nodes_mutex), NULL);
770 mesh->threadstarted = false;
771 event_loop_init(&mesh->loop);
772 mesh->loop.data = mesh;
774 // TODO: should be set by a function.
775 mesh->debug_level = 5;
777 // Check whether meshlink.conf already exists
779 char filename[PATH_MAX];
780 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
782 if(access(filename, R_OK)) {
783 if(errno == ENOENT) {
785 if(!meshlink_setup(mesh)) {
786 // meshlink_errno is set by meshlink_setup()
790 fprintf(stderr, "Cannot not read from %s: %s\n", filename, strerror(errno));
791 meshlink_close(mesh);
792 meshlink_errno = MESHLINK_ESTORAGE;
797 // Read the configuration
799 init_configuration(&mesh->config);
801 if(!read_server_config(mesh)) {
802 meshlink_close(mesh);
803 meshlink_errno = MESHLINK_ESTORAGE;
808 struct WSAData wsa_state;
809 WSAStartup(MAKEWORD(2, 2), &wsa_state);
812 // Setup up everything
813 // TODO: we should not open listening sockets yet
815 if(!setup_network(mesh)) {
816 meshlink_close(mesh);
817 meshlink_errno = MESHLINK_ENETWORK;
824 static void *meshlink_main_loop(void *arg) {
825 meshlink_handle_t *mesh = arg;
827 try_outgoing_connections(mesh);
829 fprintf(stderr, "Starting main_loop...\n");
831 fprintf(stderr, "main_loop returned.\n");
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;
865 void meshlink_stop(meshlink_handle_t *mesh) {
867 meshlink_errno = MESHLINK_EINVAL;
871 listen_socket_t *s = &mesh->listen_socket[0];
873 // Shut down a listening socket to signal the main thread to shut down
875 shutdown(s->tcp.fd, SHUT_RDWR);
877 // Wait for the main thread to finish
879 pthread_join(mesh->thread, NULL);
880 mesh->threadstarted = false;
884 closesocket(s->tcp.fd);
885 io_del(&mesh->loop, &s->tcp);
886 s->tcp.fd = setup_listen_socket(&s->sa);
888 logger(DEBUG_ALWAYS, LOG_ERR, "Could not repair listenen socket!");
890 io_add(&mesh->loop, &s->tcp, handle_new_meta_connection, s, s->tcp.fd, IO_READ);
893 void meshlink_close(meshlink_handle_t *mesh) {
894 if(!mesh || !mesh->confbase) {
895 meshlink_errno = MESHLINK_EINVAL;
899 // Close and free all resources used.
901 close_network_connections(mesh);
903 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
905 exit_configuration(&mesh->config);
906 event_loop_exit(&mesh->loop);
913 ecdsa_free(mesh->invitation_key);
916 free(mesh->confbase);
918 memset(mesh, 0, sizeof *mesh);
923 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
925 meshlink_errno = MESHLINK_EINVAL;
929 mesh->receive_cb = cb;
932 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
934 meshlink_errno = MESHLINK_EINVAL;
938 mesh->node_status_cb = cb;
941 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
943 meshlink_errno = MESHLINK_EINVAL;
948 mesh->log_level = level;
951 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
952 if(!mesh || !destination) {
953 meshlink_errno = MESHLINK_EINVAL;
961 meshlink_errno = MESHLINK_EINVAL;
965 //add packet to the queue
966 outpacketqueue_t *packet_in_queue = xzalloc(sizeof *packet_in_queue);
967 packet_in_queue->destination=destination;
968 packet_in_queue->data=data;
969 packet_in_queue->len=len;
970 if(!meshlink_queue_push(&mesh->outpacketqueue, packet_in_queue)) {
971 free(packet_in_queue);
976 signal_trigger(&(mesh->loop),&(mesh->datafromapp));
980 void meshlink_send_from_queue(event_loop_t* el,meshlink_handle_t *mesh) {
982 meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
984 outpacketqueue_t* p = meshlink_queue_pop(&mesh->outpacketqueue);
988 if (sizeof(meshlink_packethdr_t) + p->len > MAXSIZE) {
993 packet.probe = false;
994 memset(hdr, 0, sizeof *hdr);
995 memcpy(hdr->destination, p->destination->name, sizeof hdr->destination);
996 memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
998 packet.len = sizeof *hdr + p->len;
999 memcpy(packet.data + sizeof *hdr, p->data, p->len);
1001 mesh->self->in_packets++;
1002 mesh->self->in_bytes += packet.len;
1003 route(mesh, mesh->self, &packet);
1007 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1008 if(!mesh || !destination) {
1009 meshlink_errno = MESHLINK_EINVAL;
1013 node_t *n = (node_t *)destination;
1014 if(!n->status.reachable)
1016 else if(n->mtuprobes > 30 && n->minmtu)
1022 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1023 if(!mesh || !node) {
1024 meshlink_errno = MESHLINK_EINVAL;
1028 node_t *n = (node_t *)node;
1030 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1031 meshlink_errno = MESHLINK_EINTERNAL;
1035 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1038 meshlink_errno = MESHLINK_EINTERNAL;
1043 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1044 if(!mesh || !name) {
1045 meshlink_errno = MESHLINK_EINVAL;
1049 return (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1052 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1053 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1054 meshlink_errno = MESHLINK_EINVAL;
1058 meshlink_node_t **result;
1061 pthread_mutex_lock(&(mesh->nodes_mutex));
1063 *nmemb = mesh->nodes->count;
1064 result = realloc(nodes, *nmemb * sizeof *nodes);
1067 meshlink_node_t **p = result;
1068 for splay_each(node_t, n, mesh->nodes)
1069 *p++ = (meshlink_node_t *)n;
1073 meshlink_errno = MESHLINK_ENOMEM;
1076 pthread_mutex_unlock(&(mesh->nodes_mutex));
1081 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1082 if(!mesh || !data || !len || !signature || !siglen) {
1083 meshlink_errno = MESHLINK_EINVAL;
1087 if(*siglen < MESHLINK_SIGLEN) {
1088 meshlink_errno = MESHLINK_EINVAL;
1092 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1093 meshlink_errno = MESHLINK_EINTERNAL;
1097 *siglen = MESHLINK_SIGLEN;
1101 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1102 if(!mesh || !data || !len || !signature) {
1103 meshlink_errno = MESHLINK_EINVAL;
1107 if(siglen != MESHLINK_SIGLEN) {
1108 meshlink_errno = MESHLINK_EINVAL;
1112 struct node_t *n = (struct node_t *)source;
1113 node_read_ecdsa_public_key(mesh, n);
1115 meshlink_errno = MESHLINK_EINTERNAL;
1119 return ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1122 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1123 char filename[PATH_MAX];
1125 snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
1126 if(mkdir(filename, 0700) && errno != EEXIST) {
1127 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
1128 meshlink_errno = MESHLINK_ESTORAGE;
1132 // Count the number of valid invitations, clean up old ones
1133 DIR *dir = opendir(filename);
1135 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
1136 meshlink_errno = MESHLINK_ESTORAGE;
1143 time_t deadline = time(NULL) - 604800; // 1 week in the past
1145 while((ent = readdir(dir))) {
1146 if(strlen(ent->d_name) != 24)
1148 char invname[PATH_MAX];
1150 snprintf(invname, sizeof invname, "%s" SLASH "%s", filename, ent->d_name);
1151 if(!stat(invname, &st)) {
1152 if(mesh->invitation_key && deadline < st.st_mtime)
1157 fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
1163 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
1165 meshlink_errno = MESHLINK_ESTORAGE;
1171 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1173 // Remove the key if there are no outstanding invitations.
1176 if(mesh->invitation_key) {
1177 ecdsa_free(mesh->invitation_key);
1178 mesh->invitation_key = NULL;
1182 if(mesh->invitation_key)
1185 // Create a new key if necessary.
1186 FILE *f = fopen(filename, "r");
1188 if(errno != ENOENT) {
1189 fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
1190 meshlink_errno = MESHLINK_ESTORAGE;
1194 mesh->invitation_key = ecdsa_generate();
1195 if(!mesh->invitation_key) {
1196 fprintf(stderr, "Could not generate a new key!\n");
1197 meshlink_errno = MESHLINK_EINTERNAL;
1200 f = fopen(filename, "w");
1202 fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
1203 meshlink_errno = MESHLINK_ESTORAGE;
1206 chmod(filename, 0600);
1207 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1210 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1212 if(!mesh->invitation_key) {
1213 fprintf(stderr, "Could not read private key from %s\n", filename);
1214 meshlink_errno = MESHLINK_ESTORAGE;
1218 return mesh->invitation_key;
1221 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1222 if(!mesh || !address) {
1223 meshlink_errno = MESHLINK_EINVAL;
1227 for(const char *p = address; *p; p++) {
1228 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
1230 fprintf(stderr, "Invalid character in address: %s\n", address);
1231 meshlink_errno = MESHLINK_EINVAL;
1235 return append_config_file(mesh, mesh->self->name, "Address", address);
1238 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1240 meshlink_errno = MESHLINK_EINVAL;
1244 // Check validity of the new node's name
1245 if(!check_id(name)) {
1246 fprintf(stderr, "Invalid name for node.\n");
1247 meshlink_errno = MESHLINK_EINVAL;
1251 // Ensure no host configuration file with that name exists
1252 char filename[PATH_MAX];
1253 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1254 if(!access(filename, F_OK)) {
1255 fprintf(stderr, "A host config file for %s already exists!\n", name);
1256 meshlink_errno = MESHLINK_EEXIST;
1260 // Ensure no other nodes know about this name
1261 if(meshlink_get_node(mesh, name)) {
1262 fprintf(stderr, "A node with name %s is already known!\n", name);
1263 meshlink_errno = MESHLINK_EEXIST;
1267 // Get the local address
1268 char *address = get_my_hostname(mesh);
1270 fprintf(stderr, "No Address known for ourselves!\n");
1271 meshlink_errno = MESHLINK_ERESOLV;
1275 if(!refresh_invitation_key(mesh)) {
1276 meshlink_errno = MESHLINK_EINTERNAL;
1282 // Create a hash of the key.
1283 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1284 sha512(fingerprint, strlen(fingerprint), hash);
1285 b64encode_urlsafe(hash, hash, 18);
1287 // Create a random cookie for this invitation.
1289 randomize(cookie, 18);
1291 // Create a filename that doesn't reveal the cookie itself
1292 char buf[18 + strlen(fingerprint)];
1293 char cookiehash[64];
1294 memcpy(buf, cookie, 18);
1295 memcpy(buf + 18, fingerprint, sizeof buf - 18);
1296 sha512(buf, sizeof buf, cookiehash);
1297 b64encode_urlsafe(cookiehash, cookiehash, 18);
1299 b64encode_urlsafe(cookie, cookie, 18);
1303 // Create a file containing the details of the invitation.
1304 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1305 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1307 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1308 meshlink_errno = MESHLINK_ESTORAGE;
1311 FILE *f = fdopen(ifd, "w");
1315 // Fill in the details.
1316 fprintf(f, "Name = %s\n", name);
1318 // fprintf(f, "NetName = %s\n", netname);
1319 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1321 // Copy Broadcast and Mode
1322 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
1323 FILE *tc = fopen(filename, "r");
1326 while(fgets(buf, sizeof buf, tc)) {
1327 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1328 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1330 // Make sure there is a newline character.
1331 if(!strchr(buf, '\n'))
1337 fprintf(stderr, "Could not create %s: %s\n", filename, strerror(errno));
1338 meshlink_errno = MESHLINK_ESTORAGE;
1342 fprintf(f, "#---------------------------------------------------------------#\n");
1343 fprintf(f, "Name = %s\n", mesh->self->name);
1345 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1349 // Create an URL from the local address, key hash and cookie
1351 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1357 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1358 if(!mesh || !invitation) {
1359 meshlink_errno = MESHLINK_EINVAL;
1363 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1364 char copy[strlen(invitation) + 1];
1365 strcpy(copy, invitation);
1367 // Split the invitation URL into hostname, port, key hash and cookie.
1369 char *slash = strchr(copy, '/');
1375 if(strlen(slash) != 48)
1378 char *address = copy;
1380 if(*address == '[') {
1382 char *bracket = strchr(address, ']');
1386 if(bracket[1] == ':')
1389 port = strchr(address, ':');
1397 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1400 // Generate a throw-away key for the invitation.
1401 ecdsa_t *key = ecdsa_generate();
1403 meshlink_errno = MESHLINK_EINTERNAL;
1407 char *b64key = ecdsa_get_base64_public_key(key);
1409 //Before doing meshlink_join make sure we are not connected to another mesh
1410 if ( mesh->threadstarted ){
1414 // Connect to the meshlink daemon mentioned in the URL.
1415 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1417 meshlink_errno = MESHLINK_ERESOLV;
1421 mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1422 if(mesh->sock <= 0) {
1423 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
1425 meshlink_errno = MESHLINK_ENETWORK;
1429 if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1430 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1431 closesocket(mesh->sock);
1433 meshlink_errno = MESHLINK_ENETWORK;
1439 fprintf(stderr, "Connected to %s port %s...\n", address, port);
1441 // Tell him we have an invitation, and give him our throw-away key.
1445 if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1446 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1447 closesocket(mesh->sock);
1448 meshlink_errno = MESHLINK_ENETWORK;
1454 char hisname[4096] = "";
1455 int code, hismajor, hisminor = 0;
1457 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) {
1458 fprintf(stderr, "Cannot read greeting from peer\n");
1459 closesocket(mesh->sock);
1460 meshlink_errno = MESHLINK_ENETWORK;
1464 // Check if the hash of the key he gave us matches the hash in the URL.
1465 char *fingerprint = mesh->line + 2;
1467 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1468 fprintf(stderr, "Could not create hash\n%s\n", mesh->line + 2);
1469 meshlink_errno = MESHLINK_EINTERNAL;
1472 if(memcmp(hishash, mesh->hash, 18)) {
1473 fprintf(stderr, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1474 meshlink_errno = MESHLINK_EPEER;
1479 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1481 meshlink_errno = MESHLINK_EINTERNAL;
1485 // Start an SPTPS session
1486 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive)) {
1487 meshlink_errno = MESHLINK_EINTERNAL;
1491 // Feed rest of input buffer to SPTPS
1492 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
1493 meshlink_errno = MESHLINK_EPEER;
1499 while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1503 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1504 meshlink_errno = MESHLINK_ENETWORK;
1508 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
1509 meshlink_errno = MESHLINK_EPEER;
1514 sptps_stop(&mesh->sptps);
1517 closesocket(mesh->sock);
1519 if(!mesh->success) {
1520 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
1521 meshlink_errno = MESHLINK_EPEER;
1528 fprintf(stderr, "Invalid invitation URL or you are already connected to a Mesh ?\n");
1529 meshlink_errno = MESHLINK_EINVAL;
1533 char *meshlink_export(meshlink_handle_t *mesh) {
1535 meshlink_errno = MESHLINK_EINVAL;
1539 char filename[PATH_MAX];
1540 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1541 FILE *f = fopen(filename, "r");
1543 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
1544 meshlink_errno = MESHLINK_ESTORAGE;
1548 fseek(f, 0, SEEK_END);
1549 int fsize = ftell(f);
1552 size_t len = fsize + 9 + strlen(mesh->self->name);
1553 char *buf = xmalloc(len);
1554 snprintf(buf, len, "Name = %s\n", mesh->self->name);
1555 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
1556 fprintf(stderr, "Error reading from %s: %s\n", filename, strerror(errno));
1558 meshlink_errno = MESHLINK_ESTORAGE;
1567 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1568 if(!mesh || !data) {
1569 meshlink_errno = MESHLINK_EINVAL;
1573 if(strncmp(data, "Name = ", 7)) {
1574 fprintf(stderr, "Invalid data\n");
1575 meshlink_errno = MESHLINK_EPEER;
1579 char *end = strchr(data + 7, '\n');
1581 fprintf(stderr, "Invalid data\n");
1582 meshlink_errno = MESHLINK_EPEER;
1586 int len = end - (data + 7);
1588 memcpy(name, data + 7, len);
1590 if(!check_id(name)) {
1591 fprintf(stderr, "Invalid Name\n");
1592 meshlink_errno = MESHLINK_EPEER;
1596 char filename[PATH_MAX];
1597 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1598 if(!access(filename, F_OK)) {
1599 fprintf(stderr, "File %s already exists, not importing\n", filename);
1600 meshlink_errno = MESHLINK_EEXIST;
1604 if(errno != ENOENT) {
1605 fprintf(stderr, "Error accessing %s: %s\n", filename, strerror(errno));
1606 meshlink_errno = MESHLINK_ESTORAGE;
1610 FILE *f = fopen(filename, "w");
1612 fprintf(stderr, "Could not create %s: %s\n", filename, strerror(errno));
1613 meshlink_errno = MESHLINK_ESTORAGE;
1617 fwrite(end + 1, strlen(end + 1), 1, f);
1620 load_all_nodes(mesh);
1625 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1626 if(!mesh || !node) {
1627 meshlink_errno = MESHLINK_EINVAL;
1633 n->status.blacklisted=true;
1634 fprintf(stderr, "Blacklisted %s.\n",node->name);
1636 //Make blacklisting persistent in the config file
1637 append_config_file(mesh, n->name, "blacklisted", "yes");
1642 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1643 if(!mesh || !node) {
1644 meshlink_errno = MESHLINK_EINVAL;
1648 node_t *n = (node_t *)node;
1649 n->status.blacklisted = false;
1651 //TODO: remove blacklisted = yes from the config file
1656 static void __attribute__((constructor)) meshlink_init(void) {
1660 static void __attribute__((destructor)) meshlink_exit(void) {