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