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