]> git.meshlink.io Git - meshlink/blob - src/meshlink.c
Add an astylerc file and reformat all code.
[meshlink] / src / meshlink.c
1 /*
2     meshlink.c -- Implementation of the MeshLink API.
3     Copyright (C) 2014, 2017 Guus Sliepen <guus@meshlink.io>
4
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.
9
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.
14
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.
18 */
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 */
26 typedef struct {
27         const char *name;
28         int type;
29 } var_t;
30
31 #include "system.h"
32 #include <pthread.h>
33
34 #include "crypto.h"
35 #include "ecdsagen.h"
36 #include "logger.h"
37 #include "meshlink_internal.h"
38 #include "netutl.h"
39 #include "node.h"
40 #include "protocol.h"
41 #include "route.h"
42 #include "sockaddr.h"
43 #include "utils.h"
44 #include "xalloc.h"
45 #include "ed25519/sha512.h"
46 #include "discovery.h"
47
48 #ifndef MSG_NOSIGNAL
49 #define MSG_NOSIGNAL 0
50 #endif
51
52 __thread meshlink_errno_t meshlink_errno;
53 meshlink_log_cb_t global_log_cb;
54 meshlink_log_level_t global_log_level;
55
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},
84         {"Name", VAR_SERVER},
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},
111         {"Port", 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},
117         {NULL, 0}
118 };
119
120 static bool fcopy(FILE *out, const char *filename) {
121         FILE *in = fopen(filename, "r");
122         if(!in) {
123                 logger(NULL, MESHLINK_ERROR, "Could not open %s: %s\n", filename, strerror(errno));
124                 return false;
125         }
126
127         char buf[1024];
128         size_t len;
129         while((len = fread(buf, 1, sizeof buf, in)))
130                 fwrite(buf, len, 1, out);
131         fclose(in);
132         return true;
133 }
134
135 static int rstrip(char *value) {
136         int len = strlen(value);
137         while(len && strchr("\t\r\n ", value[len - 1]))
138                 value[--len] = 0;
139         return len;
140 }
141
142 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
143         char line[4096];
144         if(!filename || (*hostname && *port))
145                 return;
146
147         FILE *f = fopen(filename, "r");
148         if(!f)
149                 return;
150
151         while(fgets(line, sizeof line, f)) {
152                 if(!rstrip(line))
153                         continue;
154                 char *p = line, *q;
155                 p += strcspn(p, "\t =");
156                 if(!*p)
157                         continue;
158                 q = p + strspn(p, "\t ");
159                 if(*q == '=')
160                         q += 1 + strspn(q + 1, "\t ");
161                 *p = 0;
162                 p = q + strcspn(q, "\t ");
163                 if(*p)
164                         *p++ = 0;
165                 p += strspn(p, "\t ");
166                 p[strcspn(p, "\t ")] = 0;
167
168                 if(!*port && !strcasecmp(line, "Port"))
169                         *port = xstrdup(q);
170                 else if(!*hostname && !strcasecmp(line, "Address")) {
171                         *hostname = xstrdup(q);
172                         if(*p) {
173                                 free(*port);
174                                 *port = xstrdup(p);
175                         }
176                 }
177
178                 if(*hostname && *port)
179                         break;
180         }
181
182         fclose(f);
183 }
184
185 static bool is_valid_hostname(const char *hostname) {
186         for(const char *p = hostname; *p; p++) {
187                 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':'))
188                         return false;
189         }
190
191         return true;
192 }
193
194 static void set_timeout(int sock, int timeout) {
195 #ifdef _WIN32
196         DWORD tv = timeout;
197 #else
198         struct timeval tv;
199         tv.tv_sec = timeout / 1000;
200         tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
201 #endif
202         setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
203         setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv);
204 }
205
206 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
207         char *hostname = NULL;
208
209         logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
210         struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
211         struct addrinfo *aip = ai;
212         static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
213         char line[256];
214
215         while(aip) {
216                 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
217                 if(s >= 0) {
218                         set_timeout(s, 5000);
219                         if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
220                                 closesocket(s);
221                                 s = -1;
222                         }
223                 }
224                 if(s >= 0) {
225                         send(s, request, sizeof request - 1, 0);
226                         int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
227                         if(len > 0) {
228                                 line[len] = 0;
229                                 if(line[len - 1] == '\n')
230                                         line[--len] = 0;
231                                 char *p = strrchr(line, '\n');
232                                 if(p && p[1])
233                                         hostname = xstrdup(p + 1);
234                         }
235                         closesocket(s);
236                         if(hostname)
237                                 break;
238                 }
239                 aip = aip->ai_next;
240                 continue;
241         }
242
243         if(ai)
244                 freeaddrinfo(ai);
245
246         // Check that the hostname is reasonable
247         if(hostname && !is_valid_hostname(hostname)) {
248                 free(hostname);
249                 hostname = NULL;
250         }
251
252         if(!hostname)
253                 meshlink_errno = MESHLINK_ERESOLV;
254
255         return hostname;
256 }
257
258 static char *get_my_hostname(meshlink_handle_t* mesh) {
259         char *hostname = NULL;
260         char *port = NULL;
261         char *hostport = NULL;
262         char *name = mesh->self->name;
263         char filename[PATH_MAX] = "";
264         FILE *f;
265
266         // Use first Address statement in own host config file
267         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
268         scan_for_hostname(filename, &hostname, &port);
269
270         if(hostname)
271                 goto done;
272
273         hostname = meshlink_get_external_address(mesh);
274         if(!hostname)
275                 return NULL;
276
277         f = fopen(filename, "a");
278         if(f) {
279                 fprintf(f, "\nAddress = %s\n", hostname);
280                 fclose(f);
281         } else
282                 logger(mesh, MESHLINK_DEBUG, "Could not append Address to %s: %s\n", filename, strerror(errno));
283
284 done:
285         if(port) {
286                 if(strchr(hostname, ':'))
287                         xasprintf(&hostport, "[%s]:%s", hostname, port);
288                 else
289                         xasprintf(&hostport, "%s:%s", hostname, port);
290         } else {
291                 if(strchr(hostname, ':'))
292                         xasprintf(&hostport, "[%s]", hostname);
293                 else
294                         hostport = xstrdup(hostname);
295         }
296
297         free(hostname);
298         free(port);
299         return hostport;
300 }
301
302 static char *get_line(const char **data) {
303         if(!data || !*data)
304                 return NULL;
305
306         if(!**data) {
307                 *data = NULL;
308                 return NULL;
309         }
310
311         static char line[1024];
312         const char *end = strchr(*data, '\n');
313         size_t len = end ? end - *data : strlen(*data);
314         if(len >= sizeof line) {
315                 logger(NULL, MESHLINK_ERROR, "Maximum line length exceeded!\n");
316                 return NULL;
317         }
318         if(len && !isprint(**data))
319                 abort();
320
321         memcpy(line, *data, len);
322         line[len] = 0;
323
324         if(end)
325                 *data = end + 1;
326         else
327                 *data = NULL;
328
329         return line;
330 }
331
332 static char *get_value(const char *data, const char *var) {
333         char *line = get_line(&data);
334         if(!line)
335                 return NULL;
336
337         char *sep = line + strcspn(line, " \t=");
338         char *val = sep + strspn(sep, " \t");
339         if(*val == '=')
340                 val += 1 + strspn(val + 1, " \t");
341         *sep = 0;
342         if(strcasecmp(line, var))
343                 return NULL;
344         return val;
345 }
346
347 static bool try_bind(int port) {
348         struct addrinfo *ai = NULL;
349         struct addrinfo hint = {
350                 .ai_flags = AI_PASSIVE,
351                 .ai_family = AF_UNSPEC,
352                 .ai_socktype = SOCK_STREAM,
353                 .ai_protocol = IPPROTO_TCP,
354         };
355
356         char portstr[16];
357         snprintf(portstr, sizeof portstr, "%d", port);
358
359         if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
360                 return false;
361
362         while(ai) {
363                 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
364                 if(!fd) {
365                         freeaddrinfo(ai);
366                         return false;
367                 }
368                 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
369                 closesocket(fd);
370                 if(result) {
371                         freeaddrinfo(ai);
372                         return false;
373                 }
374                 ai = ai->ai_next;
375         }
376
377         freeaddrinfo(ai);
378         return true;
379 }
380
381 static int check_port(meshlink_handle_t *mesh) {
382         for(int i = 0; i < 1000; i++) {
383                 int port = 0x1000 + (rand() & 0x7fff);
384                 if(try_bind(port)) {
385                         char filename[PATH_MAX];
386                         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
387                         FILE *f = fopen(filename, "a");
388                         if(!f) {
389                                 logger(mesh, MESHLINK_DEBUG, "Please change MeshLink's Port manually.\n");
390                                 return 0;
391                         }
392
393                         fprintf(f, "Port = %d\n", port);
394                         fclose(f);
395                         return port;
396                 }
397         }
398
399         logger(mesh, MESHLINK_DEBUG, "Please change MeshLink's Port manually.\n");
400         return 0;
401 }
402
403 static bool finalize_join(meshlink_handle_t *mesh) {
404         char *name = xstrdup(get_value(mesh->data, "Name"));
405         if(!name) {
406                 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
407                 return false;
408         }
409
410         if(!check_id(name)) {
411                 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
412                 return false;
413         }
414
415         char filename[PATH_MAX];
416         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
417
418         FILE *f = fopen(filename, "w");
419         if(!f) {
420                 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
421                 return false;
422         }
423
424         fprintf(f, "Name = %s\n", name);
425
426         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
427         FILE *fh = fopen(filename, "w");
428         if(!fh) {
429                 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
430                 fclose(f);
431                 return false;
432         }
433
434         // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
435         // Other chunks go unfiltered to their respective host config files
436         const char *p = mesh->data;
437         char *l, *value;
438
439         while((l = get_line(&p))) {
440                 // Ignore comments
441                 if(*l == '#')
442                         continue;
443
444                 // Split line into variable and value
445                 int len = strcspn(l, "\t =");
446                 value = l + len;
447                 value += strspn(value, "\t ");
448                 if(*value == '=') {
449                         value++;
450                         value += strspn(value, "\t ");
451                 }
452                 l[len] = 0;
453
454                 // Is it a Name?
455                 if(!strcasecmp(l, "Name"))
456                         if(strcmp(value, name))
457                                 break;
458                         else
459                                 continue;
460                 else if(!strcasecmp(l, "NetName"))
461                         continue;
462
463                 // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
464                 bool found = false;
465                 int i;
466                 for(i = 0; variables[i].name; i++) {
467                         if(strcasecmp(l, variables[i].name))
468                                 continue;
469                         found = true;
470                         break;
471                 }
472
473                 // Ignore unknown and unsafe variables
474                 if(!found) {
475                         logger(mesh, MESHLINK_DEBUG, "Ignoring unknown variable '%s' in invitation.\n", l);
476                         continue;
477                 } else if(!(variables[i].type & VAR_SAFE)) {
478                         logger(mesh, MESHLINK_DEBUG, "Ignoring unsafe variable '%s' in invitation.\n", l);
479                         continue;
480                 }
481
482                 // Copy the safe variable to the right config file
483                 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
484         }
485
486         fclose(f);
487
488         while(l && !strcasecmp(l, "Name")) {
489                 if(!check_id(value)) {
490                         logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation.\n");
491                         return false;
492                 }
493
494                 if(!strcmp(value, name)) {
495                         logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
496                         return false;
497                 }
498
499                 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
500                 f = fopen(filename, "w");
501
502                 if(!f) {
503                         logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
504                         return false;
505                 }
506
507                 while((l = get_line(&p))) {
508                         if(!strcmp(l, "#---------------------------------------------------------------#"))
509                                 continue;
510                         int len = strcspn(l, "\t =");
511                         if(len == 4 && !strncasecmp(l, "Name", 4)) {
512                                 value = l + len;
513                                 value += strspn(value, "\t ");
514                                 if(*value == '=') {
515                                         value++;
516                                         value += strspn(value, "\t ");
517                                 }
518                                 l[len] = 0;
519                                 break;
520                         }
521
522                         fputs(l, f);
523                         fputc('\n', f);
524                 }
525
526                 fclose(f);
527         }
528
529         char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
530         if(!b64key) {
531                 fclose(fh);
532                 return false;
533         }
534
535         fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
536         fprintf(fh, "Port = %s\n", mesh->myport);
537
538         fclose(fh);
539
540         sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
541         free(b64key);
542
543         free(mesh->self->name);
544         free(mesh->self->connection->name);
545         mesh->self->name = xstrdup(name);
546         mesh->self->connection->name = name;
547
548         logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
549
550         load_all_nodes(mesh);
551
552         return true;
553 }
554
555 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
556         meshlink_handle_t* mesh = handle;
557         while(len) {
558                 int result = send(mesh->sock, data, len, 0);
559                 if(result == -1 && errno == EINTR)
560                         continue;
561                 else if(result <= 0)
562                         return false;
563                 data += result;
564                 len -= result;
565         }
566         return true;
567 }
568
569 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
570         meshlink_handle_t* mesh = handle;
571         switch(type) {
572         case SPTPS_HANDSHAKE:
573                 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof mesh->cookie);
574
575         case 0:
576                 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
577                 memcpy(mesh->data + mesh->thedatalen, msg, len);
578                 mesh->thedatalen += len;
579                 mesh->data[mesh->thedatalen] = 0;
580                 break;
581
582         case 1:
583                 mesh->thedatalen = 0;
584                 return finalize_join(mesh);
585
586         case 2:
587                 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
588                 shutdown(mesh->sock, SHUT_RDWR);
589                 mesh->success = true;
590                 break;
591
592         default:
593                 return false;
594         }
595
596         return true;
597 }
598
599 static bool recvline(meshlink_handle_t* mesh, size_t len) {
600         char *newline = NULL;
601
602         if(!mesh->sock)
603                 abort();
604
605         while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
606                 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof mesh->buffer - mesh->blen, 0);
607                 if(result == -1 && errno == EINTR)
608                         continue;
609                 else if(result <= 0)
610                         return false;
611                 mesh->blen += result;
612         }
613
614         if(newline - mesh->buffer >= len)
615                 return false;
616
617         len = newline - mesh->buffer;
618
619         memcpy(mesh->line, mesh->buffer, len);
620         mesh->line[len] = 0;
621         memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
622         mesh->blen -= len + 1;
623
624         return true;
625 }
626 static bool sendline(int fd, char *format, ...) {
627         static char buffer[4096];
628         char *p = buffer;
629         int blen = 0;
630         va_list ap;
631
632         va_start(ap, format);
633         blen = vsnprintf(buffer, sizeof buffer, format, ap);
634         va_end(ap);
635
636         if(blen < 1 || blen >= sizeof buffer)
637                 return false;
638
639         buffer[blen] = '\n';
640         blen++;
641
642         while(blen) {
643                 int result = send(fd, p, blen, MSG_NOSIGNAL);
644                 if(result == -1 && errno == EINTR)
645                         continue;
646                 else if(result <= 0)
647                         return false;
648                 p += result;
649                 blen -= result;
650         }
651
652         return true;
653 }
654
655 static const char *errstr[] = {
656         [MESHLINK_OK] = "No error",
657         [MESHLINK_EINVAL] = "Invalid argument",
658         [MESHLINK_ENOMEM] = "Out of memory",
659         [MESHLINK_ENOENT] = "No such node",
660         [MESHLINK_EEXIST] = "Node already exists",
661         [MESHLINK_EINTERNAL] = "Internal error",
662         [MESHLINK_ERESOLV] = "Could not resolve hostname",
663         [MESHLINK_ESTORAGE] = "Storage error",
664         [MESHLINK_ENETWORK] = "Network error",
665         [MESHLINK_EPEER] = "Error communicating with peer",
666 };
667
668 const char *meshlink_strerror(meshlink_errno_t err) {
669         if(err < 0 || err >= sizeof errstr / sizeof *errstr)
670                 return "Invalid error code";
671         return errstr[err];
672 }
673
674 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
675         ecdsa_t *key;
676         FILE *f;
677         char pubname[PATH_MAX], privname[PATH_MAX];
678
679         logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
680
681         if(!(key = ecdsa_generate())) {
682                 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
683                 meshlink_errno = MESHLINK_EINTERNAL;
684                 return false;
685         } else
686                 logger(mesh, MESHLINK_DEBUG, "Done.\n");
687
688         snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
689         f = fopen(privname, "wb");
690
691         if(!f) {
692                 meshlink_errno = MESHLINK_ESTORAGE;
693                 return false;
694         }
695
696 #ifdef HAVE_FCHMOD
697         fchmod(fileno(f), 0600);
698 #endif
699
700         if(!ecdsa_write_pem_private_key(key, f)) {
701                 logger(mesh, MESHLINK_DEBUG, "Error writing private key!\n");
702                 ecdsa_free(key);
703                 fclose(f);
704                 meshlink_errno = MESHLINK_EINTERNAL;
705                 return false;
706         }
707
708         fclose(f);
709
710         snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
711         f = fopen(pubname, "a");
712
713         if(!f) {
714                 meshlink_errno = MESHLINK_ESTORAGE;
715                 return false;
716         }
717
718         char *pubkey = ecdsa_get_base64_public_key(key);
719         fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
720         free(pubkey);
721
722         fclose(f);
723         ecdsa_free(key);
724
725         return true;
726 }
727
728 static struct timeval idle(event_loop_t *loop, void *data) {
729         meshlink_handle_t *mesh = data;
730         struct timeval t, tmin = {3600, 0};
731         for splay_each(node_t, n, mesh->nodes) {
732                 if(!n->utcp)
733                         continue;
734                 t = utcp_timeout(n->utcp);
735                 if(timercmp(&t, &tmin, <))
736                         tmin = t;
737         }
738         return tmin;
739 }
740
741 // Find out what local address a socket would use if we connect to the given address.
742 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
743 // of both endpoints, but this will actually not send any UDP packet.
744 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen) {
745         struct addrinfo *rai = NULL;
746         const struct addrinfo hint = {
747                 .ai_family = AF_UNSPEC,
748                 .ai_socktype = SOCK_DGRAM,
749                 .ai_protocol = IPPROTO_UDP,
750         };
751
752         if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai)
753                 return false;
754
755         int sock = socket(rai->ai_family, rai->ai_socktype, rai->ai_protocol);
756         if(sock == -1) {
757                 freeaddrinfo(rai);
758                 return false;
759         }
760
761         if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
762                 freeaddrinfo(rai);
763                 return false;
764         }
765
766         freeaddrinfo(rai);
767
768         struct sockaddr_storage sn;
769         socklen_t sl = sizeof sn;
770
771         if(getsockname(sock, (struct sockaddr *)&sn, &sl))
772                 return false;
773
774         if(getnameinfo((struct sockaddr *)&sn, sl, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV))
775                 return false;
776
777         return true;
778 }
779
780 // Get our local address(es) by simulating connecting to an Internet host.
781 static void add_local_addresses(meshlink_handle_t *mesh) {
782         char host[NI_MAXHOST];
783         char entry[MAX_STRING_SIZE];
784
785         // IPv4 example.org
786
787         if(getlocaladdrname("93.184.216.34", host, sizeof host)) {
788                 snprintf(entry, sizeof entry, "%s %s", host, mesh->myport);
789                 append_config_file(mesh, mesh->name, "Address", entry);
790         }
791
792         // IPv6 example.org
793
794         if(getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", host, sizeof host)) {
795                 snprintf(entry, sizeof entry, "%s %s", host, mesh->myport);
796                 append_config_file(mesh, mesh->name, "Address", entry);
797         }
798 }
799
800 static bool meshlink_setup(meshlink_handle_t *mesh) {
801         if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
802                 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
803                 meshlink_errno = MESHLINK_ESTORAGE;
804                 return false;
805         }
806
807         char filename[PATH_MAX];
808         snprintf(filename, sizeof filename, "%s" SLASH "hosts", mesh->confbase);
809
810         if(mkdir(filename, 0777) && errno != EEXIST) {
811                 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
812                 meshlink_errno = MESHLINK_ESTORAGE;
813                 return false;
814         }
815
816         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
817
818         if(!access(filename, F_OK)) {
819                 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
820                 meshlink_errno = MESHLINK_EEXIST;
821                 return false;
822         }
823
824         FILE *f = fopen(filename, "w");
825         if(!f) {
826                 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
827                 meshlink_errno = MESHLINK_ESTORAGE;
828                 return false;
829         }
830
831         fprintf(f, "Name = %s\n", mesh->name);
832         fclose(f);
833
834         if(!ecdsa_keygen(mesh)) {
835                 meshlink_errno = MESHLINK_EINTERNAL;
836                 return false;
837         }
838
839         check_port(mesh);
840
841         return true;
842 }
843
844 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char* appname, dev_class_t devclass) {
845         // Validate arguments provided by the application
846         bool usingname = false;
847
848         logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
849
850         if(!confbase || !*confbase) {
851                 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
852                 meshlink_errno = MESHLINK_EINVAL;
853                 return NULL;
854         }
855
856         if(!appname || !*appname) {
857                 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
858                 meshlink_errno = MESHLINK_EINVAL;
859                 return NULL;
860         }
861
862         if(!name || !*name) {
863                 logger(NULL, MESHLINK_ERROR, "No name given!\n");
864                 //return NULL;
865         } else { //check name only if there is a name != NULL
866
867                 if(!check_id(name)) {
868                         logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
869                         meshlink_errno = MESHLINK_EINVAL;
870                         return NULL;
871                 } else
872                         usingname = true;
873         }
874
875         if(devclass < 0 || devclass > _DEV_CLASS_MAX) {
876                 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
877                 meshlink_errno = MESHLINK_EINVAL;
878                 return NULL;
879         }
880
881         meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
882         mesh->confbase = xstrdup(confbase);
883         mesh->appname = xstrdup(appname);
884         mesh->devclass = devclass;
885         if(usingname) mesh->name = xstrdup(name);
886
887         // initialize mutex
888         pthread_mutexattr_t attr;
889         pthread_mutexattr_init(&attr);
890         pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
891         pthread_mutex_init(&(mesh->mesh_mutex), &attr);
892
893         mesh->threadstarted = false;
894         event_loop_init(&mesh->loop);
895         mesh->loop.data = mesh;
896
897         // Check whether meshlink.conf already exists
898
899         char filename[PATH_MAX];
900         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
901
902         if(access(filename, R_OK)) {
903                 if(errno == ENOENT) {
904                         // If not, create it
905                         if(!meshlink_setup(mesh)) {
906                                 // meshlink_errno is set by meshlink_setup()
907                                 return NULL;
908                         }
909                 } else {
910                         logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
911                         meshlink_close(mesh);
912                         meshlink_errno = MESHLINK_ESTORAGE;
913                         return NULL;
914                 }
915         }
916
917         // Read the configuration
918
919         init_configuration(&mesh->config);
920
921         if(!read_server_config(mesh)) {
922                 meshlink_close(mesh);
923                 meshlink_errno = MESHLINK_ESTORAGE;
924                 return NULL;
925         };
926
927 #ifdef HAVE_MINGW
928         struct WSAData wsa_state;
929         WSAStartup(MAKEWORD(2, 2), &wsa_state);
930 #endif
931
932         // Setup up everything
933         // TODO: we should not open listening sockets yet
934
935         if(!setup_network(mesh)) {
936                 meshlink_close(mesh);
937                 meshlink_errno = MESHLINK_ENETWORK;
938                 return NULL;
939         }
940
941         add_local_addresses(mesh);
942
943         idle_set(&mesh->loop, idle, mesh);
944
945         logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
946         return mesh;
947 }
948
949 static void *meshlink_main_loop(void *arg) {
950         meshlink_handle_t *mesh = arg;
951
952         pthread_mutex_lock(&(mesh->mesh_mutex));
953
954         try_outgoing_connections(mesh);
955
956         logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
957         main_loop(mesh);
958         logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
959
960         pthread_mutex_unlock(&(mesh->mesh_mutex));
961         return NULL;
962 }
963
964 bool meshlink_start(meshlink_handle_t *mesh) {
965         if(!mesh) {
966                 meshlink_errno = MESHLINK_EINVAL;
967                 return false;
968         }
969
970         logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
971
972         pthread_mutex_lock(&(mesh->mesh_mutex));
973
974         if(mesh->threadstarted) {
975                 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
976                 pthread_mutex_unlock(&(mesh->mesh_mutex));
977                 return true;
978         }
979
980         if(mesh->listen_socket[0].tcp.fd < 0) {
981                 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
982                 meshlink_errno = MESHLINK_ENETWORK;
983                 return false;
984         }
985
986         mesh->thedatalen = 0;
987
988         // TODO: open listening sockets first
989
990         //Check that a valid name is set
991         if(!mesh->name) {
992                 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
993                 meshlink_errno = MESHLINK_EINVAL;
994                 pthread_mutex_unlock(&(mesh->mesh_mutex));
995                 return false;
996         }
997
998         // Start the main thread
999
1000         event_loop_start(&mesh->loop);
1001
1002         if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1003                 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1004                 memset(&mesh->thread, 0, sizeof mesh->thread);
1005                 meshlink_errno = MESHLINK_EINTERNAL;
1006                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1007                 return false;
1008         }
1009
1010         mesh->threadstarted=true;
1011
1012         discovery_start(mesh);
1013
1014         pthread_mutex_unlock(&(mesh->mesh_mutex));
1015         return true;
1016 }
1017
1018 void meshlink_stop(meshlink_handle_t *mesh) {
1019         if(!mesh) {
1020                 meshlink_errno = MESHLINK_EINVAL;
1021                 return;
1022         }
1023
1024         pthread_mutex_lock(&(mesh->mesh_mutex));
1025         logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1026
1027         // Stop discovery
1028         discovery_stop(mesh);
1029
1030         // Shut down the main thread
1031         event_loop_stop(&mesh->loop);
1032
1033         // Send ourselves a UDP packet to kick the event loop
1034         listen_socket_t *s = &mesh->listen_socket[0];
1035         if(sendto(s->udp.fd, "", 1, MSG_NOSIGNAL, &s->sa.sa, SALEN(s->sa.sa)) == -1)
1036                 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself");
1037
1038         // Wait for the main thread to finish
1039         pthread_mutex_unlock(&(mesh->mesh_mutex));
1040         pthread_join(mesh->thread, NULL);
1041         pthread_mutex_lock(&(mesh->mesh_mutex));
1042
1043         mesh->threadstarted = false;
1044
1045         pthread_mutex_unlock(&(mesh->mesh_mutex));
1046 }
1047
1048 void meshlink_close(meshlink_handle_t *mesh) {
1049         if(!mesh || !mesh->confbase) {
1050                 meshlink_errno = MESHLINK_EINVAL;
1051                 return;
1052         }
1053
1054         // stop can be called even if mesh has not been started
1055         meshlink_stop(mesh);
1056
1057         // lock is not released after this
1058         pthread_mutex_lock(&(mesh->mesh_mutex));
1059
1060         // Close and free all resources used.
1061
1062         close_network_connections(mesh);
1063
1064         logger(mesh, MESHLINK_INFO, "Terminating");
1065
1066         exit_configuration(&mesh->config);
1067         event_loop_exit(&mesh->loop);
1068
1069 #ifdef HAVE_MINGW
1070         if(mesh->confbase)
1071                 WSACleanup();
1072 #endif
1073
1074         ecdsa_free(mesh->invitation_key);
1075
1076         free(mesh->name);
1077         free(mesh->appname);
1078         free(mesh->confbase);
1079         pthread_mutex_destroy(&(mesh->mesh_mutex));
1080
1081         memset(mesh, 0, sizeof *mesh);
1082
1083         free(mesh);
1084 }
1085
1086 static void deltree(const char *dirname) {
1087         DIR *d = opendir(dirname);
1088         if(d) {
1089                 struct dirent *ent;
1090                 while((ent = readdir(d))) {
1091                         if(ent->d_name[0] == '.')
1092                                 continue;
1093                         char filename[PATH_MAX];
1094                         snprintf(filename, sizeof filename, "%s" SLASH "%s", dirname, ent->d_name);
1095                         if(unlink(filename))
1096                                 deltree(filename);
1097                 }
1098                 closedir(d);
1099         }
1100         rmdir(dirname);
1101         return;
1102 }
1103
1104 bool meshlink_destroy(const char *confbase) {
1105         if(!confbase) {
1106                 meshlink_errno = MESHLINK_EINVAL;
1107                 return false;
1108         }
1109
1110         char filename[PATH_MAX];
1111         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
1112
1113         if(unlink(filename)) {
1114                 if(errno == ENOENT) {
1115                         meshlink_errno = MESHLINK_ENOENT;
1116                         return false;
1117                 } else {
1118                         logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", filename, strerror(errno));
1119                         meshlink_errno = MESHLINK_ESTORAGE;
1120                         return false;
1121                 }
1122         }
1123
1124         deltree(confbase);
1125
1126         return true;
1127 }
1128
1129 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1130         if(!mesh) {
1131                 meshlink_errno = MESHLINK_EINVAL;
1132                 return;
1133         }
1134
1135         pthread_mutex_lock(&(mesh->mesh_mutex));
1136         mesh->receive_cb = cb;
1137         pthread_mutex_unlock(&(mesh->mesh_mutex));
1138 }
1139
1140 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1141         if(!mesh) {
1142                 meshlink_errno = MESHLINK_EINVAL;
1143                 return;
1144         }
1145
1146         pthread_mutex_lock(&(mesh->mesh_mutex));
1147         mesh->node_status_cb = cb;
1148         pthread_mutex_unlock(&(mesh->mesh_mutex));
1149 }
1150
1151 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1152         if(mesh) {
1153                 pthread_mutex_lock(&(mesh->mesh_mutex));
1154                 mesh->log_cb = cb;
1155                 mesh->log_level = cb ? level : 0;
1156                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1157         } else {
1158                 global_log_cb = cb;
1159                 global_log_level = cb ? level : 0;
1160         }
1161 }
1162
1163 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1164         meshlink_packethdr_t *hdr;
1165
1166         // Validate arguments
1167         if(!mesh || !destination || len >= MAXSIZE - sizeof *hdr) {
1168                 meshlink_errno = MESHLINK_EINVAL;
1169                 return false;
1170         }
1171
1172         if(!len)
1173                 return true;
1174
1175         if(!data) {
1176                 meshlink_errno = MESHLINK_EINVAL;
1177                 return false;
1178         }
1179
1180         // Prepare the packet
1181         vpn_packet_t *packet = malloc(sizeof *packet);
1182         if(!packet) {
1183                 meshlink_errno = MESHLINK_ENOMEM;
1184                 return false;
1185         }
1186
1187         packet->probe = false;
1188         packet->tcp = false;
1189         packet->len = len + sizeof *hdr;
1190
1191         hdr = (meshlink_packethdr_t *)packet->data;
1192         memset(hdr, 0, sizeof *hdr);
1193         // leave the last byte as 0 to make sure strings are always
1194         // null-terminated if they are longer than the buffer
1195         strncpy(hdr->destination, destination->name, (sizeof hdr->destination) - 1);
1196         strncpy(hdr->source, mesh->self->name, (sizeof hdr->source) -1);
1197
1198         memcpy(packet->data + sizeof *hdr, data, len);
1199
1200         // Queue it
1201         if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1202                 free(packet);
1203                 meshlink_errno = MESHLINK_ENOMEM;
1204                 return false;
1205         }
1206
1207         // Notify event loop
1208         signal_trigger(&(mesh->loop),&(mesh->datafromapp));
1209
1210         return true;
1211 }
1212
1213 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1214         vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1215         if(!packet)
1216                 return;
1217
1218         mesh->self->in_packets++;
1219         mesh->self->in_bytes += packet->len;
1220         route(mesh, mesh->self, packet);
1221 }
1222
1223 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1224         if(!mesh || !destination) {
1225                 meshlink_errno = MESHLINK_EINVAL;
1226                 return -1;
1227         }
1228         pthread_mutex_lock(&(mesh->mesh_mutex));
1229
1230         node_t *n = (node_t *)destination;
1231         if(!n->status.reachable) {
1232                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1233                 return 0;
1234
1235         } else if(n->mtuprobes > 30 && n->minmtu) {
1236                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1237                 return n->minmtu;
1238         } else {
1239                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1240                 return MTU;
1241         }
1242 }
1243
1244 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1245         if(!mesh || !node) {
1246                 meshlink_errno = MESHLINK_EINVAL;
1247                 return NULL;
1248         }
1249         pthread_mutex_lock(&(mesh->mesh_mutex));
1250
1251         node_t *n = (node_t *)node;
1252
1253         if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1254                 meshlink_errno = MESHLINK_EINTERNAL;
1255                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1256                 return false;
1257         }
1258
1259         char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1260
1261         if(!fingerprint)
1262                 meshlink_errno = MESHLINK_EINTERNAL;
1263
1264         pthread_mutex_unlock(&(mesh->mesh_mutex));
1265         return fingerprint;
1266 }
1267
1268 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1269         if(!mesh) {
1270                 meshlink_errno = MESHLINK_EINVAL;
1271                 return NULL;
1272         }
1273
1274         return (meshlink_node_t *)mesh->self;
1275 }
1276
1277 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1278         if(!mesh || !name) {
1279                 meshlink_errno = MESHLINK_EINVAL;
1280                 return NULL;
1281         }
1282
1283         meshlink_node_t *node = NULL;
1284
1285         pthread_mutex_lock(&(mesh->mesh_mutex));
1286         node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1287         pthread_mutex_unlock(&(mesh->mesh_mutex));
1288         return node;
1289 }
1290
1291 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1292         if(!mesh || !nmemb || (*nmemb && !nodes)) {
1293                 meshlink_errno = MESHLINK_EINVAL;
1294                 return NULL;
1295         }
1296
1297         meshlink_node_t **result;
1298
1299         //lock mesh->nodes
1300         pthread_mutex_lock(&(mesh->mesh_mutex));
1301
1302         *nmemb = mesh->nodes->count;
1303         result = realloc(nodes, *nmemb * sizeof *nodes);
1304
1305         if(result) {
1306                 meshlink_node_t **p = result;
1307                 for splay_each(node_t, n, mesh->nodes)
1308                         *p++ = (meshlink_node_t *)n;
1309         } else {
1310                 *nmemb = 0;
1311                 free(nodes);
1312                 meshlink_errno = MESHLINK_ENOMEM;
1313         }
1314
1315         pthread_mutex_unlock(&(mesh->mesh_mutex));
1316
1317         return result;
1318 }
1319
1320 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1321         if(!mesh || !data || !len || !signature || !siglen) {
1322                 meshlink_errno = MESHLINK_EINVAL;
1323                 return false;
1324         }
1325
1326         if(*siglen < MESHLINK_SIGLEN) {
1327                 meshlink_errno = MESHLINK_EINVAL;
1328                 return false;
1329         }
1330
1331         pthread_mutex_lock(&(mesh->mesh_mutex));
1332
1333         if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1334                 meshlink_errno = MESHLINK_EINTERNAL;
1335                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1336                 return false;
1337         }
1338
1339         *siglen = MESHLINK_SIGLEN;
1340         pthread_mutex_unlock(&(mesh->mesh_mutex));
1341         return true;
1342 }
1343
1344 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1345         if(!mesh || !data || !len || !signature) {
1346                 meshlink_errno = MESHLINK_EINVAL;
1347                 return false;
1348         }
1349
1350         if(siglen != MESHLINK_SIGLEN) {
1351                 meshlink_errno = MESHLINK_EINVAL;
1352                 return false;
1353         }
1354
1355         pthread_mutex_lock(&(mesh->mesh_mutex));
1356
1357         bool rval = false;
1358
1359         struct node_t *n = (struct node_t *)source;
1360         node_read_ecdsa_public_key(mesh, n);
1361         if(!n->ecdsa) {
1362                 meshlink_errno = MESHLINK_EINTERNAL;
1363                 rval = false;
1364         } else
1365                 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1366         pthread_mutex_unlock(&(mesh->mesh_mutex));
1367         return rval;
1368 }
1369
1370 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1371         char filename[PATH_MAX];
1372
1373         pthread_mutex_lock(&(mesh->mesh_mutex));
1374
1375         snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
1376         if(mkdir(filename, 0700) && errno != EEXIST) {
1377                 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1378                 meshlink_errno = MESHLINK_ESTORAGE;
1379                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1380                 return false;
1381         }
1382
1383         // Count the number of valid invitations, clean up old ones
1384         DIR *dir = opendir(filename);
1385         if(!dir) {
1386                 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1387                 meshlink_errno = MESHLINK_ESTORAGE;
1388                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1389                 return false;
1390         }
1391
1392         errno = 0;
1393         int count = 0;
1394         struct dirent *ent;
1395         time_t deadline = time(NULL) - 604800; // 1 week in the past
1396
1397         while((ent = readdir(dir))) {
1398                 if(strlen(ent->d_name) != 24)
1399                         continue;
1400                 char invname[PATH_MAX];
1401                 struct stat st;
1402                 snprintf(invname, sizeof invname, "%s" SLASH "%s", filename, ent->d_name);
1403                 if(!stat(invname, &st)) {
1404                         if(mesh->invitation_key && deadline < st.st_mtime)
1405                                 count++;
1406                         else
1407                                 unlink(invname);
1408                 } else {
1409                         logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1410                         errno = 0;
1411                 }
1412         }
1413
1414         if(errno) {
1415                 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
1416                 closedir(dir);
1417                 meshlink_errno = MESHLINK_ESTORAGE;
1418                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1419                 return false;
1420         }
1421
1422         closedir(dir);
1423
1424         snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1425
1426         // Remove the key if there are no outstanding invitations.
1427         if(!count) {
1428                 unlink(filename);
1429                 if(mesh->invitation_key) {
1430                         ecdsa_free(mesh->invitation_key);
1431                         mesh->invitation_key = NULL;
1432                 }
1433         }
1434
1435         if(mesh->invitation_key) {
1436                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1437                 return true;
1438         }
1439
1440         // Create a new key if necessary.
1441         FILE *f = fopen(filename, "rb");
1442         if(!f) {
1443                 if(errno != ENOENT) {
1444                         logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
1445                         meshlink_errno = MESHLINK_ESTORAGE;
1446                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1447                         return false;
1448                 }
1449
1450                 mesh->invitation_key = ecdsa_generate();
1451                 if(!mesh->invitation_key) {
1452                         logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
1453                         meshlink_errno = MESHLINK_EINTERNAL;
1454                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1455                         return false;
1456                 }
1457                 f = fopen(filename, "wb");
1458                 if(!f) {
1459                         logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
1460                         meshlink_errno = MESHLINK_ESTORAGE;
1461                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1462                         return false;
1463                 }
1464                 chmod(filename, 0600);
1465                 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1466                 fclose(f);
1467         } else {
1468                 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1469                 fclose(f);
1470                 if(!mesh->invitation_key) {
1471                         logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
1472                         meshlink_errno = MESHLINK_ESTORAGE;
1473                 }
1474         }
1475
1476         pthread_mutex_unlock(&(mesh->mesh_mutex));
1477         return mesh->invitation_key;
1478 }
1479
1480 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1481         if(!mesh || !address) {
1482                 meshlink_errno = MESHLINK_EINVAL;
1483                 return false;
1484         }
1485
1486         if(!is_valid_hostname(address)) {
1487                 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1488                 meshlink_errno = MESHLINK_EINVAL;
1489                 return false;
1490         }
1491
1492         bool rval = false;
1493
1494         pthread_mutex_lock(&(mesh->mesh_mutex));
1495         rval = append_config_file(mesh, mesh->self->name, "Address", address);
1496         pthread_mutex_unlock(&(mesh->mesh_mutex));
1497
1498         return rval;
1499 }
1500
1501 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
1502         if(!mesh) {
1503                 meshlink_errno = MESHLINK_EINVAL;
1504                 return false;
1505         }
1506
1507         char *address = meshlink_get_external_address(mesh);
1508         if(!address)
1509                 return false;
1510
1511         bool rval = false;
1512
1513         pthread_mutex_lock(&(mesh->mesh_mutex));
1514         rval = append_config_file(mesh, mesh->self->name, "Address", address);
1515         pthread_mutex_unlock(&(mesh->mesh_mutex));
1516
1517         free(address);
1518         return rval;
1519 }
1520
1521 int meshlink_get_port(meshlink_handle_t *mesh) {
1522         if(!mesh) {
1523                 meshlink_errno = MESHLINK_EINVAL;
1524                 return -1;
1525         }
1526
1527         if(!mesh->myport) {
1528                 meshlink_errno = MESHLINK_EINTERNAL;
1529                 return -1;
1530         }
1531
1532         return atoi(mesh->myport);
1533 }
1534
1535 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
1536         if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
1537                 meshlink_errno = MESHLINK_EINVAL;
1538                 return false;
1539         }
1540
1541         if(mesh->myport && port == atoi(mesh->myport))
1542                 return true;
1543
1544         if(!try_bind(port)) {
1545                 meshlink_errno = MESHLINK_ENETWORK;
1546                 return false;
1547         }
1548
1549         bool rval = false;
1550
1551         pthread_mutex_lock(&(mesh->mesh_mutex));
1552         if(mesh->threadstarted) {
1553                 meshlink_errno = MESHLINK_EINVAL;
1554                 goto done;
1555         }
1556
1557         close_network_connections(mesh);
1558         exit_configuration(&mesh->config);
1559
1560         char portstr[10];
1561         snprintf(portstr, sizeof portstr, "%d", port);
1562         portstr[sizeof portstr - 1] = 0;
1563
1564         modify_config_file(mesh, mesh->name, "Port", portstr, true);
1565
1566         init_configuration(&mesh->config);
1567
1568         if(!read_server_config(mesh))
1569                 meshlink_errno = MESHLINK_ESTORAGE;
1570         else if(!setup_network(mesh))
1571                 meshlink_errno = MESHLINK_ENETWORK;
1572         else
1573                 rval = true;
1574
1575 done:
1576         pthread_mutex_unlock(&(mesh->mesh_mutex));
1577
1578         return rval;
1579 }
1580
1581 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1582         if(!mesh) {
1583                 meshlink_errno = MESHLINK_EINVAL;
1584                 return NULL;
1585         }
1586
1587         pthread_mutex_lock(&(mesh->mesh_mutex));
1588
1589         // Check validity of the new node's name
1590         if(!check_id(name)) {
1591                 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
1592                 meshlink_errno = MESHLINK_EINVAL;
1593                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1594                 return NULL;
1595         }
1596
1597         // Ensure no host configuration file with that name exists
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                 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
1602                 meshlink_errno = MESHLINK_EEXIST;
1603                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1604                 return NULL;
1605         }
1606
1607         // Ensure no other nodes know about this name
1608         if(meshlink_get_node(mesh, name)) {
1609                 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
1610                 meshlink_errno = MESHLINK_EEXIST;
1611                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1612                 return NULL;
1613         }
1614
1615         // Get the local address
1616         char *address = get_my_hostname(mesh);
1617         if(!address) {
1618                 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
1619                 meshlink_errno = MESHLINK_ERESOLV;
1620                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1621                 return NULL;
1622         }
1623
1624         if(!refresh_invitation_key(mesh)) {
1625                 meshlink_errno = MESHLINK_EINTERNAL;
1626                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1627                 return NULL;
1628         }
1629
1630         char hash[64];
1631
1632         // Create a hash of the key.
1633         char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1634         sha512(fingerprint, strlen(fingerprint), hash);
1635         b64encode_urlsafe(hash, hash, 18);
1636
1637         // Create a random cookie for this invitation.
1638         char cookie[25];
1639         randomize(cookie, 18);
1640
1641         // Create a filename that doesn't reveal the cookie itself
1642         char buf[18 + strlen(fingerprint)];
1643         char cookiehash[64];
1644         memcpy(buf, cookie, 18);
1645         memcpy(buf + 18, fingerprint, sizeof buf - 18);
1646         sha512(buf, sizeof buf, cookiehash);
1647         b64encode_urlsafe(cookiehash, cookiehash, 18);
1648
1649         b64encode_urlsafe(cookie, cookie, 18);
1650
1651         free(fingerprint);
1652
1653         // Create a file containing the details of the invitation.
1654         snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1655         int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1656         if(!ifd) {
1657                 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1658                 meshlink_errno = MESHLINK_ESTORAGE;
1659                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1660                 return NULL;
1661         }
1662         FILE *f = fdopen(ifd, "w");
1663         if(!f)
1664                 abort();
1665
1666         // Fill in the details.
1667         fprintf(f, "Name = %s\n", name);
1668         //if(netname)
1669         //      fprintf(f, "NetName = %s\n", netname);
1670         fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1671
1672         // Copy Broadcast and Mode
1673         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
1674         FILE *tc = fopen(filename,  "r");
1675         if(tc) {
1676                 char buf[1024];
1677                 while(fgets(buf, sizeof buf, tc)) {
1678                         if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1679                                         || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1680                                 fputs(buf, f);
1681                                 // Make sure there is a newline character.
1682                                 if(!strchr(buf, '\n'))
1683                                         fputc('\n', f);
1684                         }
1685                 }
1686                 fclose(tc);
1687         } else {
1688                 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1689                 meshlink_errno = MESHLINK_ESTORAGE;
1690                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1691                 return NULL;
1692         }
1693
1694         fprintf(f, "#---------------------------------------------------------------#\n");
1695         fprintf(f, "Name = %s\n", mesh->self->name);
1696
1697         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1698         fcopy(f, filename);
1699         fclose(f);
1700
1701         // Create an URL from the local address, key hash and cookie
1702         char *url;
1703         xasprintf(&url, "%s/%s%s", address, hash, cookie);
1704         free(address);
1705
1706         pthread_mutex_unlock(&(mesh->mesh_mutex));
1707         return url;
1708 }
1709
1710 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1711         if(!mesh || !invitation) {
1712                 meshlink_errno = MESHLINK_EINVAL;
1713                 return false;
1714         }
1715
1716         pthread_mutex_lock(&(mesh->mesh_mutex));
1717
1718         //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1719         char copy[strlen(invitation) + 1];
1720         strcpy(copy, invitation);
1721
1722         // Split the invitation URL into hostname, port, key hash and cookie.
1723
1724         char *slash = strchr(copy, '/');
1725         if(!slash)
1726                 goto invalid;
1727
1728         *slash++ = 0;
1729
1730         if(strlen(slash) != 48)
1731                 goto invalid;
1732
1733         char *address = copy;
1734         char *port = NULL;
1735         if(*address == '[') {
1736                 address++;
1737                 char *bracket = strchr(address, ']');
1738                 if(!bracket)
1739                         goto invalid;
1740                 *bracket = 0;
1741                 if(bracket[1] == ':')
1742                         port = bracket + 2;
1743         } else {
1744                 port = strchr(address, ':');
1745                 if(port)
1746                         *port++ = 0;
1747         }
1748
1749         if(!port)
1750                 goto invalid;
1751
1752         if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1753                 goto invalid;
1754
1755         // Generate a throw-away key for the invitation.
1756         ecdsa_t *key = ecdsa_generate();
1757         if(!key) {
1758                 meshlink_errno = MESHLINK_EINTERNAL;
1759                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1760                 return false;
1761         }
1762
1763         char *b64key = ecdsa_get_base64_public_key(key);
1764
1765         //Before doing meshlink_join make sure we are not connected to another mesh
1766         if(mesh->threadstarted)
1767                 goto invalid;
1768
1769         // Connect to the meshlink daemon mentioned in the URL.
1770         struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1771         if(!ai) {
1772                 meshlink_errno = MESHLINK_ERESOLV;
1773                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1774                 return false;
1775         }
1776
1777         mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1778         if(mesh->sock <= 0) {
1779                 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
1780                 freeaddrinfo(ai);
1781                 meshlink_errno = MESHLINK_ENETWORK;
1782                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1783                 return false;
1784         }
1785
1786         set_timeout(mesh->sock, 5000);
1787
1788         if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1789                 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1790                 closesocket(mesh->sock);
1791                 freeaddrinfo(ai);
1792                 meshlink_errno = MESHLINK_ENETWORK;
1793                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1794                 return false;
1795         }
1796
1797         freeaddrinfo(ai);
1798
1799         logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
1800
1801         // Tell him we have an invitation, and give him our throw-away key.
1802
1803         mesh->blen = 0;
1804
1805         if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1806                 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1807                 closesocket(mesh->sock);
1808                 meshlink_errno = MESHLINK_ENETWORK;
1809                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1810                 return false;
1811         }
1812
1813         free(b64key);
1814
1815         char hisname[4096] = "";
1816         int code, hismajor, hisminor = 0;
1817
1818         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) {
1819                 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
1820                 closesocket(mesh->sock);
1821                 meshlink_errno = MESHLINK_ENETWORK;
1822                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1823                 return false;
1824         }
1825
1826         // Check if the hash of the key he gave us matches the hash in the URL.
1827         char *fingerprint = mesh->line + 2;
1828         char hishash[64];
1829         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1830                 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
1831                 meshlink_errno = MESHLINK_EINTERNAL;
1832                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1833                 return false;
1834         }
1835         if(memcmp(hishash, mesh->hash, 18)) {
1836                 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1837                 meshlink_errno = MESHLINK_EPEER;
1838                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1839                 return false;
1840
1841         }
1842
1843         ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1844         if(!hiskey) {
1845                 meshlink_errno = MESHLINK_EINTERNAL;
1846                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1847                 return false;
1848         }
1849
1850         // Start an SPTPS session
1851         if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof meshlink_invitation_label, invitation_send, invitation_receive)) {
1852                 meshlink_errno = MESHLINK_EINTERNAL;
1853                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1854                 return false;
1855         }
1856
1857         // Feed rest of input buffer to SPTPS
1858         if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
1859                 meshlink_errno = MESHLINK_EPEER;
1860                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1861                 return false;
1862         }
1863
1864         int len;
1865
1866         while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1867                 if(len < 0) {
1868                         if(errno == EINTR)
1869                                 continue;
1870                         logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1871                         meshlink_errno = MESHLINK_ENETWORK;
1872                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1873                         return false;
1874                 }
1875
1876                 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
1877                         meshlink_errno = MESHLINK_EPEER;
1878                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1879                         return false;
1880                 }
1881         }
1882
1883         sptps_stop(&mesh->sptps);
1884         ecdsa_free(hiskey);
1885         ecdsa_free(key);
1886         closesocket(mesh->sock);
1887
1888         if(!mesh->success) {
1889                 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
1890                 meshlink_errno = MESHLINK_EPEER;
1891                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1892                 return false;
1893         }
1894
1895         pthread_mutex_unlock(&(mesh->mesh_mutex));
1896         return true;
1897
1898 invalid:
1899         logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL or you are already connected to a Mesh ?\n");
1900         meshlink_errno = MESHLINK_EINVAL;
1901         pthread_mutex_unlock(&(mesh->mesh_mutex));
1902         return false;
1903 }
1904
1905 char *meshlink_export(meshlink_handle_t *mesh) {
1906         if(!mesh) {
1907                 meshlink_errno = MESHLINK_EINVAL;
1908                 return NULL;
1909         }
1910
1911         pthread_mutex_lock(&(mesh->mesh_mutex));
1912
1913         char filename[PATH_MAX];
1914         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1915         FILE *f = fopen(filename, "r");
1916         if(!f) {
1917                 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
1918                 meshlink_errno = MESHLINK_ESTORAGE;
1919                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1920                 return NULL;
1921         }
1922
1923         fseek(f, 0, SEEK_END);
1924         int fsize = ftell(f);
1925         rewind(f);
1926
1927         size_t len = fsize + 9 + strlen(mesh->self->name);
1928         char *buf = xmalloc(len);
1929         snprintf(buf, len, "Name = %s\n", mesh->self->name);
1930         if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
1931                 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
1932                 fclose(f);
1933                 meshlink_errno = MESHLINK_ESTORAGE;
1934                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1935                 return NULL;
1936         }
1937
1938         fclose(f);
1939         buf[len - 1] = 0;
1940
1941         pthread_mutex_unlock(&(mesh->mesh_mutex));
1942         return buf;
1943 }
1944
1945 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1946         if(!mesh || !data) {
1947                 meshlink_errno = MESHLINK_EINVAL;
1948                 return false;
1949         }
1950
1951         pthread_mutex_lock(&(mesh->mesh_mutex));
1952
1953         if(strncmp(data, "Name = ", 7)) {
1954                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
1955                 meshlink_errno = MESHLINK_EPEER;
1956                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1957                 return false;
1958         }
1959
1960         char *end = strchr(data + 7, '\n');
1961         if(!end) {
1962                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
1963                 meshlink_errno = MESHLINK_EPEER;
1964                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1965                 return false;
1966         }
1967
1968         int len = end - (data + 7);
1969         char name[len + 1];
1970         memcpy(name, data + 7, len);
1971         name[len] = 0;
1972         if(!check_id(name)) {
1973                 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
1974                 meshlink_errno = MESHLINK_EPEER;
1975                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1976                 return false;
1977         }
1978
1979         char filename[PATH_MAX];
1980         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1981         if(!access(filename, F_OK)) {
1982                 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
1983                 meshlink_errno = MESHLINK_EEXIST;
1984                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1985                 return false;
1986         }
1987
1988         if(errno != ENOENT) {
1989                 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
1990                 meshlink_errno = MESHLINK_ESTORAGE;
1991                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1992                 return false;
1993         }
1994
1995         FILE *f = fopen(filename, "w");
1996         if(!f) {
1997                 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1998                 meshlink_errno = MESHLINK_ESTORAGE;
1999                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2000                 return false;
2001         }
2002
2003         fwrite(end + 1, strlen(end + 1), 1, f);
2004         fclose(f);
2005
2006         load_all_nodes(mesh);
2007
2008         pthread_mutex_unlock(&(mesh->mesh_mutex));
2009         return true;
2010 }
2011
2012 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2013         if(!mesh || !node) {
2014                 meshlink_errno = MESHLINK_EINVAL;
2015                 return;
2016         }
2017
2018         pthread_mutex_lock(&(mesh->mesh_mutex));
2019
2020         node_t *n;
2021         n = (node_t*)node;
2022         n->status.blacklisted=true;
2023         logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n",node->name);
2024
2025         //Make blacklisting persistent in the config file
2026         append_config_file(mesh, n->name, "blacklisted", "yes");
2027
2028         pthread_mutex_unlock(&(mesh->mesh_mutex));
2029         return;
2030 }
2031
2032 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2033         if(!mesh || !node) {
2034                 meshlink_errno = MESHLINK_EINVAL;
2035                 return;
2036         }
2037
2038         pthread_mutex_lock(&(mesh->mesh_mutex));
2039
2040         node_t *n = (node_t *)node;
2041         n->status.blacklisted = false;
2042
2043         //TODO: remove blacklisted = yes from the config file
2044
2045         pthread_mutex_unlock(&(mesh->mesh_mutex));
2046         return;
2047 }
2048
2049 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2050         mesh->default_blacklist = blacklist;
2051 }
2052
2053 /* Hint that a hostname may be found at an address
2054  * See header file for detailed comment.
2055  */
2056 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2057         if(!mesh || !node || !addr)
2058                 return;
2059
2060         // Ignore hints about ourself.
2061         if((node_t *)node == mesh->self)
2062                 return;
2063
2064         pthread_mutex_lock(&(mesh->mesh_mutex));
2065
2066         char *host = NULL, *port = NULL, *str = NULL;
2067         sockaddr2str((const sockaddr_t *)addr, &host, &port);
2068
2069         if(host && port) {
2070                 xasprintf(&str, "%s %s", host, port);
2071                 if((strncmp("fe80",host,4) != 0) && (strncmp("127.",host,4) != 0) && (strcmp("localhost",host) !=0))
2072                         append_config_file(mesh, node->name, "Address", str);
2073                 else
2074                         logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
2075         }
2076
2077         free(str);
2078         free(host);
2079         free(port);
2080
2081         pthread_mutex_unlock(&(mesh->mesh_mutex));
2082         // @TODO do we want to fire off a connection attempt right away?
2083 }
2084
2085 /* Return an array of edges in the current network graph.
2086  * Data captures the current state and will not be updated.
2087  * Caller must deallocate data when done.
2088  */
2089 meshlink_edge_t **meshlink_get_all_edges_state(meshlink_handle_t *mesh, meshlink_edge_t **edges, size_t *nmemb) {
2090         if(!mesh || !nmemb || (*nmemb && !edges)) {
2091                 meshlink_errno = MESHLINK_EINVAL;
2092                 return NULL;
2093         }
2094
2095         pthread_mutex_lock(&(mesh->mesh_mutex));
2096
2097         meshlink_edge_t **result = NULL;
2098         meshlink_edge_t *copy = NULL;
2099         int result_size = 0;
2100
2101         result_size = mesh->edges->count;
2102
2103         // if result is smaller than edges, we have to dealloc all the excess meshlink_edge_t
2104         if(result_size > *nmemb)
2105                 result = realloc(edges, result_size * sizeof(meshlink_edge_t*));
2106         else
2107                 result = edges;
2108
2109         if(result) {
2110                 meshlink_edge_t **p = result;
2111                 int n = 0;
2112                 for splay_each(edge_t, e, mesh->edges) {
2113                         // skip edges that do not represent a two-directional connection
2114                         if((!e->reverse) || (e->reverse->to != e->from)) {
2115                                 result_size--;
2116                                 continue;
2117                         }
2118                         n++;
2119                         // the first *nmemb members of result can be re-used
2120                         if(n > *nmemb)
2121                                 copy = xzalloc(sizeof *copy);
2122                         else
2123                                 copy = *p;
2124                         copy->from = (meshlink_node_t*)e->from;
2125                         copy->to = (meshlink_node_t*)e->to;
2126                         copy->address = e->address.storage;
2127                         copy->options = e->options;
2128                         copy->weight = e->weight;
2129                         *p++ = copy;
2130                 }
2131                 // shrink result to the actual amount of memory used
2132                 for(int i = *nmemb; i > result_size; i--)
2133                         free(result[i - 1]);
2134                 result = realloc(result, result_size * sizeof(meshlink_edge_t*));
2135                 *nmemb = result_size;
2136         } else {
2137                 *nmemb = 0;
2138                 meshlink_errno = MESHLINK_ENOMEM;
2139         }
2140
2141         pthread_mutex_unlock(&(mesh->mesh_mutex));
2142
2143         return result;
2144 }
2145
2146 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2147         //TODO: implement
2148         return true;
2149 }
2150
2151 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2152         meshlink_channel_t *channel = connection->priv;
2153         if(!channel)
2154                 abort();
2155         node_t *n = channel->node;
2156         meshlink_handle_t *mesh = n->mesh;
2157         if(channel->receive_cb)
2158                 channel->receive_cb(mesh, channel, data, len);
2159         return len;
2160 }
2161
2162 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2163         node_t *n = utcp_connection->utcp->priv;
2164         if(!n)
2165                 abort();
2166         meshlink_handle_t *mesh = n->mesh;
2167         if(!mesh->channel_accept_cb)
2168                 return;
2169         meshlink_channel_t *channel = xzalloc(sizeof *channel);
2170         channel->node = n;
2171         channel->c = utcp_connection;
2172         if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0))
2173                 utcp_accept(utcp_connection, channel_recv, channel);
2174         else
2175                 free(channel);
2176 }
2177
2178 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2179         node_t *n = utcp->priv;
2180         meshlink_handle_t *mesh = n->mesh;
2181         return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? len : -1;
2182 }
2183
2184 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2185         if(!mesh || !channel) {
2186                 meshlink_errno = MESHLINK_EINVAL;
2187                 return;
2188         }
2189
2190         channel->receive_cb = cb;
2191 }
2192
2193 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2194         node_t *n = (node_t *)source;
2195         if(!n->utcp)
2196                 abort();
2197         utcp_recv(n->utcp, data, len);
2198 }
2199
2200 static void channel_poll(struct utcp_connection *connection, size_t len) {
2201         meshlink_channel_t *channel = connection->priv;
2202         if(!channel)
2203                 abort();
2204         node_t *n = channel->node;
2205         meshlink_handle_t *mesh = n->mesh;
2206         if(channel->poll_cb)
2207                 channel->poll_cb(mesh, channel, len);
2208 }
2209
2210 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2211         channel->poll_cb = cb;
2212         utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2213 }
2214
2215 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2216         if(!mesh) {
2217                 meshlink_errno = MESHLINK_EINVAL;
2218                 return;
2219         }
2220
2221         pthread_mutex_lock(&mesh->mesh_mutex);
2222         mesh->channel_accept_cb = cb;
2223         mesh->receive_cb = channel_receive;
2224         for splay_each(node_t, n, mesh->nodes) {
2225                 if(!n->utcp && n != mesh->self)
2226                         n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2227         }
2228         pthread_mutex_unlock(&mesh->mesh_mutex);
2229 }
2230
2231 meshlink_channel_t *meshlink_channel_open_ex(meshlink_handle_t *mesh, meshlink_node_t *node, uint16_t port, meshlink_channel_receive_cb_t cb, const void *data, size_t len, uint32_t flags) {
2232         if(!mesh || !node) {
2233                 meshlink_errno = MESHLINK_EINVAL;
2234                 return NULL;
2235         }
2236
2237         node_t *n = (node_t *)node;
2238         if(!n->utcp) {
2239                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2240                 mesh->receive_cb = channel_receive;
2241                 if(!n->utcp) {
2242                         meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2243                         return NULL;
2244                 }
2245         }
2246         meshlink_channel_t *channel = xzalloc(sizeof *channel);
2247         channel->node = n;
2248         channel->receive_cb = cb;
2249         channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2250         if(!channel->c) {
2251                 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2252                 free(channel);
2253                 return NULL;
2254         }
2255         return channel;
2256 }
2257
2258 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) {
2259         return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2260 }
2261
2262 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2263         if(!mesh || !channel) {
2264                 meshlink_errno = MESHLINK_EINVAL;
2265                 return;
2266         }
2267
2268         utcp_shutdown(channel->c, direction);
2269 }
2270
2271 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2272         if(!mesh || !channel) {
2273                 meshlink_errno = MESHLINK_EINVAL;
2274                 return;
2275         }
2276
2277         utcp_close(channel->c);
2278         free(channel);
2279 }
2280
2281 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2282         if(!mesh || !channel) {
2283                 meshlink_errno = MESHLINK_EINVAL;
2284                 return -1;
2285         }
2286
2287         if(!len)
2288                 return 0;
2289
2290         if(!data) {
2291                 meshlink_errno = MESHLINK_EINVAL;
2292                 return -1;
2293         }
2294
2295         // TODO: more finegrained locking.
2296         // Ideally we want to put the data into the UTCP connection's send buffer.
2297         // Then, preferrably only if there is room in the receiver window,
2298         // kick the meshlink thread to go send packets.
2299
2300         pthread_mutex_lock(&mesh->mesh_mutex);
2301         ssize_t retval = utcp_send(channel->c, data, len);
2302         pthread_mutex_unlock(&mesh->mesh_mutex);
2303
2304         if(retval < 0)
2305                 meshlink_errno = MESHLINK_ENETWORK;
2306         return retval;
2307 }
2308
2309 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2310         if(!mesh || !channel) {
2311                 meshlink_errno = MESHLINK_EINVAL;
2312                 return -1;
2313         }
2314
2315         return channel->c->flags;
2316 }
2317
2318 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2319         if(n->status.reachable && mesh->channel_accept_cb && !n->utcp)
2320                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2321         if(mesh->node_status_cb)
2322                 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
2323 }
2324
2325 static void __attribute__((constructor)) meshlink_init(void) {
2326         crypto_init();
2327         unsigned int seed;
2328         randomize(&seed, sizeof seed);
2329         srand(seed);
2330 }
2331
2332 static void __attribute__((destructor)) meshlink_exit(void) {
2333         crypto_exit();
2334 }
2335
2336 /// Device class traits
2337 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX +1] = {
2338         { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2339         { .min_connects = 3, .max_connects = 100, .edge_weight = 3 },   // DEV_CLASS_STATIONARY
2340         { .min_connects = 3, .max_connects = 3, .edge_weight = 6 },             // DEV_CLASS_PORTABLE
2341         { .min_connects = 1, .max_connects = 1, .edge_weight = 9 },             // DEV_CLASS_UNKNOWN
2342 };