+#include "ed25519/sha512.h"
+
+#ifndef MSG_NOSIGNAL
+#define MSG_NOSIGNAL 0
+#endif
+
+//TODO: this can go away completely
+const var_t variables[] = {
+ /* Server configuration */
+ {"AddressFamily", VAR_SERVER},
+ {"AutoConnect", VAR_SERVER | VAR_SAFE},
+ {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
+ {"BindToInterface", VAR_SERVER},
+ {"Broadcast", VAR_SERVER | VAR_SAFE},
+ {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
+ {"DecrementTTL", VAR_SERVER},
+ {"Device", VAR_SERVER},
+ {"DeviceType", VAR_SERVER},
+ {"DirectOnly", VAR_SERVER},
+ {"ECDSAPrivateKeyFile", VAR_SERVER},
+ {"ExperimentalProtocol", VAR_SERVER},
+ {"Forwarding", VAR_SERVER},
+ {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
+ {"Hostnames", VAR_SERVER},
+ {"IffOneQueue", VAR_SERVER},
+ {"Interface", VAR_SERVER},
+ {"KeyExpire", VAR_SERVER},
+ {"ListenAddress", VAR_SERVER | VAR_MULTIPLE},
+ {"LocalDiscovery", VAR_SERVER},
+ {"MACExpire", VAR_SERVER},
+ {"MaxConnectionBurst", VAR_SERVER},
+ {"MaxOutputBufferSize", VAR_SERVER},
+ {"MaxTimeout", VAR_SERVER},
+ {"Mode", VAR_SERVER | VAR_SAFE},
+ {"Name", VAR_SERVER},
+ {"PingInterval", VAR_SERVER},
+ {"PingTimeout", VAR_SERVER},
+ {"PriorityInheritance", VAR_SERVER},
+ {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
+ {"PrivateKeyFile", VAR_SERVER},
+ {"ProcessPriority", VAR_SERVER},
+ {"Proxy", VAR_SERVER},
+ {"ReplayWindow", VAR_SERVER},
+ {"ScriptsExtension", VAR_SERVER},
+ {"ScriptsInterpreter", VAR_SERVER},
+ {"StrictSubnets", VAR_SERVER},
+ {"TunnelServer", VAR_SERVER},
+ {"VDEGroup", VAR_SERVER},
+ {"VDEPort", VAR_SERVER},
+ /* Host configuration */
+ {"Address", VAR_HOST | VAR_MULTIPLE},
+ {"Cipher", VAR_SERVER | VAR_HOST},
+ {"ClampMSS", VAR_SERVER | VAR_HOST},
+ {"Compression", VAR_SERVER | VAR_HOST},
+ {"Digest", VAR_SERVER | VAR_HOST},
+ {"ECDSAPublicKey", VAR_HOST},
+ {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
+ {"IndirectData", VAR_SERVER | VAR_HOST},
+ {"MACLength", VAR_SERVER | VAR_HOST},
+ {"PMTU", VAR_SERVER | VAR_HOST},
+ {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
+ {"Port", VAR_HOST},
+ {"PublicKey", VAR_HOST | VAR_OBSOLETE},
+ {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
+ {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
+ {"TCPOnly", VAR_SERVER | VAR_HOST},
+ {"Weight", VAR_HOST | VAR_SAFE},
+ {NULL, 0}
+};
+
+static bool fcopy(FILE *out, const char *filename) {
+ FILE *in = fopen(filename, "r");
+ if(!in) {
+ fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
+ return false;
+ }
+
+ char buf[1024];
+ size_t len;
+ while((len = fread(buf, 1, sizeof buf, in)))
+ fwrite(buf, len, 1, out);
+ fclose(in);
+ return true;
+}
+
+static int rstrip(char *value) {
+ int len = strlen(value);
+ while(len && strchr("\t\r\n ", value[len - 1]))
+ value[--len] = 0;
+ return len;
+}
+
+static void scan_for_hostname(const char *filename, char **hostname, char **port) {
+ char line[4096];
+ if(!filename || (*hostname && *port))
+ return;
+
+ FILE *f = fopen(filename, "r");
+ if(!f)
+ return;
+
+ while(fgets(line, sizeof line, f)) {
+ if(!rstrip(line))
+ continue;
+ char *p = line, *q;
+ p += strcspn(p, "\t =");
+ if(!*p)
+ continue;
+ q = p + strspn(p, "\t ");
+ if(*q == '=')
+ q += 1 + strspn(q + 1, "\t ");
+ *p = 0;
+ p = q + strcspn(q, "\t ");
+ if(*p)
+ *p++ = 0;
+ p += strspn(p, "\t ");
+ p[strcspn(p, "\t ")] = 0;
+
+ if(!*port && !strcasecmp(line, "Port")) {
+ *port = xstrdup(q);
+ } else if(!*hostname && !strcasecmp(line, "Address")) {
+ *hostname = xstrdup(q);
+ if(*p) {
+ free(*port);
+ *port = xstrdup(p);
+ }
+ }
+
+ if(*hostname && *port)
+ break;
+ }
+
+ fclose(f);
+}
+static char *get_my_hostname(meshlink_handle_t* mesh) {
+ char *hostname = NULL;
+ char *port = NULL;
+ char *hostport = NULL;
+ char *name = mesh->self->name;
+ char filename[PATH_MAX] = "";
+ char line[4096];
+ FILE *f;
+
+ // Use first Address statement in own host config file
+ snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
+ scan_for_hostname(filename, &hostname, &port);
+
+ if(hostname)
+ goto done;
+
+ // If that doesn't work, guess externally visible hostname
+ fprintf(stderr, "Trying to discover externally visible hostname...\n");
+ struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
+ struct addrinfo *aip = ai;
+ static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
+
+ while(aip) {
+ int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
+ if(s >= 0) {
+ if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
+ closesocket(s);
+ s = -1;
+ }
+ }
+ if(s >= 0) {
+ send(s, request, sizeof request - 1, 0);
+ int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
+ if(len > 0) {
+ line[len] = 0;
+ if(line[len - 1] == '\n')
+ line[--len] = 0;
+ char *p = strrchr(line, '\n');
+ if(p && p[1])
+ hostname = xstrdup(p + 1);
+ }
+ closesocket(s);
+ if(hostname)
+ break;
+ }
+ aip = aip->ai_next;
+ continue;
+ }
+
+ if(ai)
+ freeaddrinfo(ai);
+
+ // Check that the hostname is reasonable
+ if(hostname) {
+ for(char *p = hostname; *p; p++) {
+ if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
+ continue;
+ // If not, forget it.
+ free(hostname);
+ hostname = NULL;
+ break;
+ }
+ }
+
+ if(!hostname)
+ return NULL;
+
+ f = fopen(filename, "a");
+ if(f) {
+ fprintf(f, "\nAddress = %s\n", hostname);
+ fclose(f);
+ } else {
+ fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
+ }
+
+done:
+ if(port) {
+ if(strchr(hostname, ':'))
+ xasprintf(&hostport, "[%s]:%s", hostname, port);
+ else
+ xasprintf(&hostport, "%s:%s", hostname, port);
+ } else {
+ if(strchr(hostname, ':'))
+ xasprintf(&hostport, "[%s]", hostname);
+ else
+ hostport = xstrdup(hostname);
+ }
+
+ free(hostname);
+ free(port);
+ return hostport;
+}
+
+static char *get_line(const char **data) {
+ if(!data || !*data)
+ return NULL;
+
+ if(!**data) {
+ *data = NULL;
+ return NULL;
+ }
+
+ static char line[1024];
+ const char *end = strchr(*data, '\n');
+ size_t len = end ? end - *data : strlen(*data);
+ if(len >= sizeof line) {
+ fprintf(stderr, "Maximum line length exceeded!\n");
+ return NULL;
+ }
+ if(len && !isprint(**data))
+ abort();
+
+ memcpy(line, *data, len);
+ line[len] = 0;
+
+ if(end)
+ *data = end + 1;
+ else
+ *data = NULL;
+
+ return line;
+}
+
+static char *get_value(const char *data, const char *var) {
+ char *line = get_line(&data);
+ if(!line)
+ return NULL;
+
+ char *sep = line + strcspn(line, " \t=");
+ char *val = sep + strspn(sep, " \t");
+ if(*val == '=')
+ val += 1 + strspn(val + 1, " \t");
+ *sep = 0;
+ if(strcasecmp(line, var))
+ return NULL;
+ return val;
+}
+
+static bool try_bind(int port) {
+ struct addrinfo *ai = NULL;
+ struct addrinfo hint = {
+ .ai_flags = AI_PASSIVE,
+ .ai_family = AF_UNSPEC,
+ .ai_socktype = SOCK_STREAM,
+ .ai_protocol = IPPROTO_TCP,
+ };
+
+ char portstr[16];
+ snprintf(portstr, sizeof portstr, "%d", port);
+
+ if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
+ return false;
+
+ while(ai) {
+ int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
+ if(!fd) {
+ freeaddrinfo(ai);
+ return false;
+ }
+ int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
+ closesocket(fd);
+ if(result) {
+ freeaddrinfo(ai);
+ return false;
+ }
+ ai = ai->ai_next;
+ }
+
+ freeaddrinfo(ai);
+ return true;
+}
+
+static int check_port(meshlink_handle_t *mesh) {
+ if(try_bind(655))
+ return 655;
+
+ fprintf(stderr, "Warning: could not bind to port 655.\n");
+
+ for(int i = 0; i < 100; i++) {
+ int port = 0x1000 + (rand() & 0x7fff);
+ if(try_bind(port)) {
+ char filename[PATH_MAX];
+ snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
+ FILE *f = fopen(filename, "a");
+ if(!f) {
+ fprintf(stderr, "Please change MeshLink's Port manually.\n");
+ return 0;
+ }
+
+ fprintf(f, "Port = %d\n", port);
+ fclose(f);
+ fprintf(stderr, "MeshLink will instead listen on port %d.\n", port);
+ return port;
+ }
+ }
+
+ fprintf(stderr, "Please change MeshLink's Port manually.\n");
+ return 0;
+}
+
+static bool finalize_join(meshlink_handle_t *mesh) {
+ char *name = xstrdup(get_value(mesh->data, "Name"));
+ if(!name) {
+ fprintf(stderr, "No Name found in invitation!\n");
+ return false;
+ }
+
+ if(!check_id(name)) {
+ fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
+ return false;
+ }
+
+ char filename[PATH_MAX];
+ snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
+
+ FILE *f = fopen(filename, "w");
+ if(!f) {
+ fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
+ return false;
+ }
+
+ fprintf(f, "Name = %s\n", name);
+
+ snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
+ FILE *fh = fopen(filename, "w");
+ if(!fh) {
+ fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
+ fclose(f);
+ return false;
+ }
+
+ // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
+ // Other chunks go unfiltered to their respective host config files
+ const char *p = mesh->data;
+ char *l, *value;
+
+ while((l = get_line(&p))) {
+ // Ignore comments
+ if(*l == '#')
+ continue;
+
+ // Split line into variable and value
+ int len = strcspn(l, "\t =");
+ value = l + len;
+ value += strspn(value, "\t ");
+ if(*value == '=') {
+ value++;
+ value += strspn(value, "\t ");
+ }
+ l[len] = 0;
+
+ // Is it a Name?
+ if(!strcasecmp(l, "Name"))
+ if(strcmp(value, name))
+ break;
+ else
+ continue;
+ else if(!strcasecmp(l, "NetName"))
+ continue;
+
+ // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
+ bool found = false;
+ int i;
+ for(i = 0; variables[i].name; i++) {
+ if(strcasecmp(l, variables[i].name))
+ continue;
+ found = true;
+ break;
+ }
+
+ // Ignore unknown and unsafe variables
+ if(!found) {
+ fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
+ continue;
+ } else if(!(variables[i].type & VAR_SAFE)) {
+ fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
+ continue;
+ }
+
+ // Copy the safe variable to the right config file
+ fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
+ }
+
+ fclose(f);
+
+ while(l && !strcasecmp(l, "Name")) {
+ if(!check_id(value)) {
+ fprintf(stderr, "Invalid Name found in invitation.\n");
+ return false;
+ }
+
+ if(!strcmp(value, name)) {
+ fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
+ return false;
+ }
+
+ snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
+ f = fopen(filename, "w");
+
+ if(!f) {
+ fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
+ return false;
+ }
+
+ while((l = get_line(&p))) {
+ if(!strcmp(l, "#---------------------------------------------------------------#"))
+ continue;
+ int len = strcspn(l, "\t =");
+ if(len == 4 && !strncasecmp(l, "Name", 4)) {
+ value = l + len;
+ value += strspn(value, "\t ");
+ if(*value == '=') {
+ value++;
+ value += strspn(value, "\t ");
+ }
+ l[len] = 0;
+ break;
+ }
+
+ fputs(l, f);
+ fputc('\n', f);
+ }
+
+ fclose(f);
+ }
+
+ char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
+ if(!b64key)
+ return false;
+
+ fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
+ fprintf(fh, "Port = %s\n", mesh->myport);
+
+ fclose(fh);
+
+ sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
+ free(b64key);
+
+ free(mesh->self->name);
+ free(mesh->self->connection->name);
+ mesh->self->name = xstrdup(name);
+ mesh->self->connection->name = xstrdup(name);
+
+ fprintf(stderr, "Configuration stored in: %s\n", mesh->confbase);
+
+ load_all_nodes(mesh);
+
+ return true;
+}
+
+static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
+ meshlink_handle_t* mesh = handle;
+ while(len) {
+ int result = send(mesh->sock, data, len, 0);
+ if(result == -1 && errno == EINTR)
+ continue;
+ else if(result <= 0)
+ return false;
+ data += result;
+ len -= result;
+ }
+ return true;
+}
+
+static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
+ meshlink_handle_t* mesh = handle;
+ switch(type) {
+ case SPTPS_HANDSHAKE:
+ return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof mesh->cookie);
+
+ case 0:
+ mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
+ memcpy(mesh->data + mesh->thedatalen, msg, len);
+ mesh->thedatalen += len;
+ mesh->data[mesh->thedatalen] = 0;
+ break;
+
+ case 1:
+ return finalize_join(mesh);
+
+ case 2:
+ fprintf(stderr, "Invitation succesfully accepted.\n");
+ shutdown(mesh->sock, SHUT_RDWR);
+ mesh->success = true;
+ break;
+
+ default:
+ return false;
+ }
+
+ return true;
+}
+
+static bool recvline(meshlink_handle_t* mesh, size_t len) {
+ char *newline = NULL;
+
+ if(!mesh->sock)
+ abort();
+
+ while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
+ int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof mesh->buffer - mesh->blen, 0);
+ if(result == -1 && errno == EINTR)
+ continue;
+ else if(result <= 0)
+ return false;
+ mesh->blen += result;
+ }
+
+ if(newline - mesh->buffer >= len)
+ return false;
+
+ len = newline - mesh->buffer;
+
+ memcpy(mesh->line, mesh->buffer, len);
+ mesh->line[len] = 0;
+ memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
+ mesh->blen -= len + 1;
+
+ return true;
+}
+static bool sendline(int fd, char *format, ...) {
+ static char buffer[4096];
+ char *p = buffer;
+ int blen = 0;
+ va_list ap;
+
+ va_start(ap, format);
+ blen = vsnprintf(buffer, sizeof buffer, format, ap);
+ va_end(ap);
+
+ if(blen < 1 || blen >= sizeof buffer)
+ return false;
+
+ buffer[blen] = '\n';
+ blen++;
+
+ while(blen) {
+ int result = send(fd, p, blen, MSG_NOSIGNAL);
+ if(result == -1 && errno == EINTR)
+ continue;
+ else if(result <= 0)
+ return false;
+ p += result;
+ blen -= result;
+ }
+
+ return true;
+}