]> git.meshlink.io Git - meshlink/blob - src/meshlink.c
Determine the local node's address(es) and add them to its host config file.
[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 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1053         if(!mesh) {
1054                 meshlink_errno = MESHLINK_EINVAL;
1055                 return;
1056         }
1057
1058         pthread_mutex_lock(&(mesh->mesh_mutex));
1059         mesh->receive_cb = cb;
1060         pthread_mutex_unlock(&(mesh->mesh_mutex));
1061 }
1062
1063 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1064         if(!mesh) {
1065                 meshlink_errno = MESHLINK_EINVAL;
1066                 return;
1067         }
1068
1069         pthread_mutex_lock(&(mesh->mesh_mutex));
1070         mesh->node_status_cb = cb;
1071         pthread_mutex_unlock(&(mesh->mesh_mutex));
1072 }
1073
1074 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1075         if(mesh) {
1076                 pthread_mutex_lock(&(mesh->mesh_mutex));
1077                 mesh->log_cb = cb;
1078                 mesh->log_level = cb ? level : 0;
1079                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1080         } else {
1081                 global_log_cb = cb;
1082                 global_log_level = cb ? level : 0;
1083         }
1084 }
1085
1086 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1087         meshlink_packethdr_t *hdr;
1088
1089         // Validate arguments
1090         if(!mesh || !destination || len >= MAXSIZE - sizeof *hdr) {
1091                 meshlink_errno = MESHLINK_EINVAL;
1092                 return false;
1093         }
1094
1095         if(!len)
1096                 return true;
1097
1098         if(!data) {
1099                 meshlink_errno = MESHLINK_EINVAL;
1100                 return false;
1101         }
1102
1103         // Prepare the packet
1104         vpn_packet_t *packet = malloc(sizeof *packet);
1105         if(!packet) {
1106                 meshlink_errno = MESHLINK_ENOMEM;
1107                 return false;
1108         }
1109
1110         packet->probe = false;
1111         packet->tcp = false;
1112         packet->len = len + sizeof *hdr;
1113
1114         hdr = (meshlink_packethdr_t *)packet->data;
1115         memset(hdr, 0, sizeof *hdr);
1116         // leave the last byte as 0 to make sure strings are always
1117         // null-terminated if they are longer than the buffer
1118         strncpy(hdr->destination, destination->name, (sizeof hdr->destination) - 1);
1119         strncpy(hdr->source, mesh->self->name, (sizeof hdr->source) -1 );
1120
1121         memcpy(packet->data + sizeof *hdr, data, len);
1122
1123         // Queue it
1124         if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1125                 free(packet);
1126                 meshlink_errno = MESHLINK_ENOMEM;
1127                 return false;
1128         }
1129
1130         // Notify event loop
1131         signal_trigger(&(mesh->loop),&(mesh->datafromapp));
1132         
1133         return true;
1134 }
1135
1136 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1137         vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1138         if(!packet)
1139                 return;
1140
1141         mesh->self->in_packets++;
1142         mesh->self->in_bytes += packet->len;
1143         route(mesh, mesh->self, packet);
1144 }
1145
1146 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1147         if(!mesh || !destination) {
1148                 meshlink_errno = MESHLINK_EINVAL;
1149                 return -1;
1150         }
1151         pthread_mutex_lock(&(mesh->mesh_mutex));
1152
1153         node_t *n = (node_t *)destination;
1154         if(!n->status.reachable) {
1155                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1156                 return 0;
1157         
1158         }
1159         else if(n->mtuprobes > 30 && n->minmtu) {
1160                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1161                 return n->minmtu;
1162         }
1163         else {
1164                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1165                 return MTU;
1166         }
1167 }
1168
1169 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1170         if(!mesh || !node) {
1171                 meshlink_errno = MESHLINK_EINVAL;
1172                 return NULL;
1173         }
1174         pthread_mutex_lock(&(mesh->mesh_mutex));
1175
1176         node_t *n = (node_t *)node;
1177
1178         if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1179                 meshlink_errno = MESHLINK_EINTERNAL;
1180                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1181                 return false;
1182         }
1183
1184         char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1185
1186         if(!fingerprint)
1187                 meshlink_errno = MESHLINK_EINTERNAL;
1188
1189         pthread_mutex_unlock(&(mesh->mesh_mutex));
1190         return fingerprint;
1191 }
1192
1193 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1194         if(!mesh || !name) {
1195                 meshlink_errno = MESHLINK_EINVAL;
1196                 return NULL;
1197         }
1198
1199         meshlink_node_t *node = NULL;
1200
1201         pthread_mutex_lock(&(mesh->mesh_mutex));
1202         node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1203         pthread_mutex_unlock(&(mesh->mesh_mutex));
1204         return node;
1205 }
1206
1207 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1208         if(!mesh || !nmemb || (*nmemb && !nodes)) {
1209                 meshlink_errno = MESHLINK_EINVAL;
1210                 return NULL;
1211         }
1212
1213         meshlink_node_t **result;
1214
1215         //lock mesh->nodes
1216         pthread_mutex_lock(&(mesh->mesh_mutex));
1217
1218         *nmemb = mesh->nodes->count;
1219         result = realloc(nodes, *nmemb * sizeof *nodes);
1220
1221         if(result) {
1222                 meshlink_node_t **p = result;
1223                 for splay_each(node_t, n, mesh->nodes)
1224                         *p++ = (meshlink_node_t *)n;
1225         } else {
1226                 *nmemb = 0;
1227                 free(nodes);
1228                 meshlink_errno = MESHLINK_ENOMEM;
1229         }
1230
1231         pthread_mutex_unlock(&(mesh->mesh_mutex));
1232
1233         return result;
1234 }
1235
1236 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1237         if(!mesh || !data || !len || !signature || !siglen) {
1238                 meshlink_errno = MESHLINK_EINVAL;
1239                 return false;
1240         }
1241
1242         if(*siglen < MESHLINK_SIGLEN) {
1243                 meshlink_errno = MESHLINK_EINVAL;
1244                 return false;
1245         }
1246
1247         pthread_mutex_lock(&(mesh->mesh_mutex));
1248
1249         if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1250                 meshlink_errno = MESHLINK_EINTERNAL;
1251                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1252                 return false;
1253         }
1254
1255         *siglen = MESHLINK_SIGLEN;
1256         pthread_mutex_unlock(&(mesh->mesh_mutex));
1257         return true;
1258 }
1259
1260 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1261         if(!mesh || !data || !len || !signature) {
1262                 meshlink_errno = MESHLINK_EINVAL;
1263                 return false;
1264         }
1265
1266         if(siglen != MESHLINK_SIGLEN) {
1267                 meshlink_errno = MESHLINK_EINVAL;
1268                 return false;
1269         }
1270
1271         pthread_mutex_lock(&(mesh->mesh_mutex));
1272
1273         bool rval = false;
1274
1275         struct node_t *n = (struct node_t *)source;
1276         node_read_ecdsa_public_key(mesh, n);
1277         if(!n->ecdsa) {
1278                 meshlink_errno = MESHLINK_EINTERNAL;
1279                 rval = false;
1280         } else {
1281                 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1282         }
1283         pthread_mutex_unlock(&(mesh->mesh_mutex));
1284         return rval;
1285 }
1286
1287 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1288         char filename[PATH_MAX];
1289         
1290         pthread_mutex_lock(&(mesh->mesh_mutex));
1291
1292         snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
1293         if(mkdir(filename, 0700) && errno != EEXIST) {
1294                 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1295                 meshlink_errno = MESHLINK_ESTORAGE;
1296                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1297                 return false;
1298         }
1299
1300         // Count the number of valid invitations, clean up old ones
1301         DIR *dir = opendir(filename);
1302         if(!dir) {
1303                 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1304                 meshlink_errno = MESHLINK_ESTORAGE;
1305                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1306                 return false;
1307         }
1308
1309         errno = 0;
1310         int count = 0;
1311         struct dirent *ent;
1312         time_t deadline = time(NULL) - 604800; // 1 week in the past
1313
1314         while((ent = readdir(dir))) {
1315                 if(strlen(ent->d_name) != 24)
1316                         continue;
1317                 char invname[PATH_MAX];
1318                 struct stat st;
1319                 snprintf(invname, sizeof invname, "%s" SLASH "%s", filename, ent->d_name);
1320                 if(!stat(invname, &st)) {
1321                         if(mesh->invitation_key && deadline < st.st_mtime)
1322                                 count++;
1323                         else
1324                                 unlink(invname);
1325                 } else {
1326                         logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1327                         errno = 0;
1328                 }
1329         }
1330
1331         if(errno) {
1332                 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
1333                 closedir(dir);
1334                 meshlink_errno = MESHLINK_ESTORAGE;
1335                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1336                 return false;
1337         }
1338
1339         closedir(dir);
1340
1341         snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1342
1343         // Remove the key if there are no outstanding invitations.
1344         if(!count) {
1345                 unlink(filename);
1346                 if(mesh->invitation_key) {
1347                         ecdsa_free(mesh->invitation_key);
1348                         mesh->invitation_key = NULL;
1349                 }
1350         }
1351
1352         if(mesh->invitation_key) {
1353                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1354                 return true;
1355         }
1356
1357         // Create a new key if necessary.
1358         FILE *f = fopen(filename, "rb");
1359         if(!f) {
1360                 if(errno != ENOENT) {
1361                         logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
1362                         meshlink_errno = MESHLINK_ESTORAGE;
1363                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1364                         return false;
1365                 }
1366
1367                 mesh->invitation_key = ecdsa_generate();
1368                 if(!mesh->invitation_key) {
1369                         logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
1370                         meshlink_errno = MESHLINK_EINTERNAL;
1371                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1372                         return false;
1373                 }
1374                 f = fopen(filename, "wb");
1375                 if(!f) {
1376                         logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
1377                         meshlink_errno = MESHLINK_ESTORAGE;
1378                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1379                         return false;
1380                 }
1381                 chmod(filename, 0600);
1382                 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1383                 fclose(f);
1384         } else {
1385                 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1386                 fclose(f);
1387                 if(!mesh->invitation_key) {
1388                         logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
1389                         meshlink_errno = MESHLINK_ESTORAGE;
1390                 }
1391         }
1392
1393         pthread_mutex_unlock(&(mesh->mesh_mutex));
1394         return mesh->invitation_key;
1395 }
1396
1397 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1398         if(!mesh || !address) {
1399                 meshlink_errno = MESHLINK_EINVAL;
1400                 return false;
1401         }
1402         
1403         bool rval = false;
1404
1405         pthread_mutex_lock(&(mesh->mesh_mutex));
1406
1407         for(const char *p = address; *p; p++) {
1408                 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
1409                         continue;
1410                 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1411                 meshlink_errno = MESHLINK_EINVAL;
1412                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1413                 return false;
1414         }
1415
1416         rval = append_config_file(mesh, mesh->self->name, "Address", address);
1417         pthread_mutex_unlock(&(mesh->mesh_mutex));
1418         return rval;
1419 }
1420
1421 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1422         if(!mesh) {
1423                 meshlink_errno = MESHLINK_EINVAL;
1424                 return NULL;
1425         }
1426         
1427         pthread_mutex_lock(&(mesh->mesh_mutex));
1428
1429         // Check validity of the new node's name
1430         if(!check_id(name)) {
1431                 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
1432                 meshlink_errno = MESHLINK_EINVAL;
1433                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1434                 return NULL;
1435         }
1436
1437         // Ensure no host configuration file with that name exists
1438         char filename[PATH_MAX];
1439         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1440         if(!access(filename, F_OK)) {
1441                 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
1442                 meshlink_errno = MESHLINK_EEXIST;
1443                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1444                 return NULL;
1445         }
1446
1447         // Ensure no other nodes know about this name
1448         if(meshlink_get_node(mesh, name)) {
1449                 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
1450                 meshlink_errno = MESHLINK_EEXIST;
1451                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1452                 return NULL;
1453         }
1454
1455         // Get the local address
1456         char *address = get_my_hostname(mesh);
1457         if(!address) {
1458                 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
1459                 meshlink_errno = MESHLINK_ERESOLV;
1460                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1461                 return NULL;
1462         }
1463
1464         if(!refresh_invitation_key(mesh)) {
1465                 meshlink_errno = MESHLINK_EINTERNAL;
1466                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1467                 return NULL;
1468         }
1469
1470         char hash[64];
1471
1472         // Create a hash of the key.
1473         char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1474         sha512(fingerprint, strlen(fingerprint), hash);
1475         b64encode_urlsafe(hash, hash, 18);
1476
1477         // Create a random cookie for this invitation.
1478         char cookie[25];
1479         randomize(cookie, 18);
1480
1481         // Create a filename that doesn't reveal the cookie itself
1482         char buf[18 + strlen(fingerprint)];
1483         char cookiehash[64];
1484         memcpy(buf, cookie, 18);
1485         memcpy(buf + 18, fingerprint, sizeof buf - 18);
1486         sha512(buf, sizeof buf, cookiehash);
1487         b64encode_urlsafe(cookiehash, cookiehash, 18);
1488
1489         b64encode_urlsafe(cookie, cookie, 18);
1490
1491         free(fingerprint);
1492
1493         // Create a file containing the details of the invitation.
1494         snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1495         int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1496         if(!ifd) {
1497                 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1498                 meshlink_errno = MESHLINK_ESTORAGE;
1499                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1500                 return NULL;
1501         }
1502         FILE *f = fdopen(ifd, "w");
1503         if(!f)
1504                 abort();
1505
1506         // Fill in the details.
1507         fprintf(f, "Name = %s\n", name);
1508         //if(netname)
1509         //      fprintf(f, "NetName = %s\n", netname);
1510         fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1511
1512         // Copy Broadcast and Mode
1513         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
1514         FILE *tc = fopen(filename,  "r");
1515         if(tc) {
1516                 char buf[1024];
1517                 while(fgets(buf, sizeof buf, tc)) {
1518                         if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1519                                         || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1520                                 fputs(buf, f);
1521                                 // Make sure there is a newline character.
1522                                 if(!strchr(buf, '\n'))
1523                                         fputc('\n', f);
1524                         }
1525                 }
1526                 fclose(tc);
1527         } else {
1528                 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1529                 meshlink_errno = MESHLINK_ESTORAGE;
1530                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1531                 return NULL;
1532         }
1533
1534         fprintf(f, "#---------------------------------------------------------------#\n");
1535         fprintf(f, "Name = %s\n", mesh->self->name);
1536
1537         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1538         fcopy(f, filename);
1539         fclose(f);
1540
1541         // Create an URL from the local address, key hash and cookie
1542         char *url;
1543         xasprintf(&url, "%s/%s%s", address, hash, cookie);
1544         free(address);
1545
1546         pthread_mutex_unlock(&(mesh->mesh_mutex));
1547         return url;
1548 }
1549
1550 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1551         if(!mesh || !invitation) {
1552                 meshlink_errno = MESHLINK_EINVAL;
1553                 return false;
1554         }
1555         
1556         pthread_mutex_lock(&(mesh->mesh_mutex));
1557
1558         //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1559         char copy[strlen(invitation) + 1];
1560         strcpy(copy, invitation);
1561
1562         // Split the invitation URL into hostname, port, key hash and cookie.
1563
1564         char *slash = strchr(copy, '/');
1565         if(!slash)
1566                 goto invalid;
1567
1568         *slash++ = 0;
1569
1570         if(strlen(slash) != 48)
1571                 goto invalid;
1572
1573         char *address = copy;
1574         char *port = NULL;
1575         if(*address == '[') {
1576                 address++;
1577                 char *bracket = strchr(address, ']');
1578                 if(!bracket)
1579                         goto invalid;
1580                 *bracket = 0;
1581                 if(bracket[1] == ':')
1582                         port = bracket + 2;
1583         } else {
1584                 port = strchr(address, ':');
1585                 if(port)
1586                         *port++ = 0;
1587         }
1588
1589         if(!port)
1590                 goto invalid;
1591
1592         if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1593                 goto invalid;
1594
1595         // Generate a throw-away key for the invitation.
1596         ecdsa_t *key = ecdsa_generate();
1597         if(!key) {
1598                 meshlink_errno = MESHLINK_EINTERNAL;
1599                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1600                 return false;
1601         }
1602
1603         char *b64key = ecdsa_get_base64_public_key(key);
1604
1605         //Before doing meshlink_join make sure we are not connected to another mesh
1606         if ( mesh->threadstarted ){
1607                 goto invalid;
1608         }
1609
1610         // Connect to the meshlink daemon mentioned in the URL.
1611         struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1612         if(!ai) {
1613                 meshlink_errno = MESHLINK_ERESOLV;
1614                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1615                 return false;
1616         }
1617
1618         mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1619         if(mesh->sock <= 0) {
1620                 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
1621                 freeaddrinfo(ai);
1622                 meshlink_errno = MESHLINK_ENETWORK;
1623                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1624                 return false;
1625         }
1626
1627         if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1628                 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1629                 closesocket(mesh->sock);
1630                 freeaddrinfo(ai);
1631                 meshlink_errno = MESHLINK_ENETWORK;
1632                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1633                 return false;
1634         }
1635
1636         freeaddrinfo(ai);
1637
1638         logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
1639
1640         // Tell him we have an invitation, and give him our throw-away key.
1641
1642         mesh->blen = 0;
1643
1644         if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1645                 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1646                 closesocket(mesh->sock);
1647                 meshlink_errno = MESHLINK_ENETWORK;
1648                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1649                 return false;
1650         }
1651
1652         free(b64key);
1653
1654         char hisname[4096] = "";
1655         int code, hismajor, hisminor = 0;
1656
1657         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) {
1658                 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
1659                 closesocket(mesh->sock);
1660                 meshlink_errno = MESHLINK_ENETWORK;
1661                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1662                 return false;
1663         }
1664
1665         // Check if the hash of the key he gave us matches the hash in the URL.
1666         char *fingerprint = mesh->line + 2;
1667         char hishash[64];
1668         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1669                 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
1670                 meshlink_errno = MESHLINK_EINTERNAL;
1671                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1672                 return false;
1673         }
1674         if(memcmp(hishash, mesh->hash, 18)) {
1675                 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1676                 meshlink_errno = MESHLINK_EPEER;
1677                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1678                 return false;
1679
1680         }
1681
1682         ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1683         if(!hiskey) {
1684                 meshlink_errno = MESHLINK_EINTERNAL;
1685                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1686                 return false;
1687         }
1688
1689         // Start an SPTPS session
1690         if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive)) {
1691                 meshlink_errno = MESHLINK_EINTERNAL;
1692                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1693                 return false;
1694         }
1695
1696         // Feed rest of input buffer to SPTPS
1697         if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
1698                 meshlink_errno = MESHLINK_EPEER;
1699                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1700                 return false;
1701         }
1702
1703         int len;
1704
1705         while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1706                 if(len < 0) {
1707                         if(errno == EINTR)
1708                                 continue;
1709                         logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1710                         meshlink_errno = MESHLINK_ENETWORK;
1711                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1712                         return false;
1713                 }
1714
1715                 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
1716                         meshlink_errno = MESHLINK_EPEER;
1717                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1718                         return false;
1719                 }
1720         }
1721
1722         sptps_stop(&mesh->sptps);
1723         ecdsa_free(hiskey);
1724         ecdsa_free(key);
1725         closesocket(mesh->sock);
1726
1727         if(!mesh->success) {
1728                 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
1729                 meshlink_errno = MESHLINK_EPEER;
1730                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1731                 return false;
1732         }
1733
1734         pthread_mutex_unlock(&(mesh->mesh_mutex));
1735         return true;
1736
1737 invalid:
1738         logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL or you are already connected to a Mesh ?\n");
1739         meshlink_errno = MESHLINK_EINVAL;
1740         pthread_mutex_unlock(&(mesh->mesh_mutex));
1741         return false;
1742 }
1743
1744 char *meshlink_export(meshlink_handle_t *mesh) {
1745         if(!mesh) {
1746                 meshlink_errno = MESHLINK_EINVAL;
1747                 return NULL;
1748         }
1749
1750         pthread_mutex_lock(&(mesh->mesh_mutex));
1751         
1752         char filename[PATH_MAX];
1753         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1754         FILE *f = fopen(filename, "r");
1755         if(!f) {
1756                 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
1757                 meshlink_errno = MESHLINK_ESTORAGE;
1758                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1759                 return NULL;
1760         }
1761
1762         fseek(f, 0, SEEK_END);
1763         int fsize = ftell(f);
1764         rewind(f);
1765
1766         size_t len = fsize + 9 + strlen(mesh->self->name);
1767         char *buf = xmalloc(len);
1768         snprintf(buf, len, "Name = %s\n", mesh->self->name);
1769         if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
1770                 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
1771                 fclose(f);
1772                 meshlink_errno = MESHLINK_ESTORAGE;
1773                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1774                 return NULL;
1775         }
1776
1777         fclose(f);
1778         buf[len - 1] = 0;
1779         
1780         pthread_mutex_unlock(&(mesh->mesh_mutex));
1781         return buf;
1782 }
1783
1784 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1785         if(!mesh || !data) {
1786                 meshlink_errno = MESHLINK_EINVAL;
1787                 return false;
1788         }
1789         
1790         pthread_mutex_lock(&(mesh->mesh_mutex));
1791
1792         if(strncmp(data, "Name = ", 7)) {
1793                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
1794                 meshlink_errno = MESHLINK_EPEER;
1795                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1796                 return false;
1797         }
1798
1799         char *end = strchr(data + 7, '\n');
1800         if(!end) {
1801                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
1802                 meshlink_errno = MESHLINK_EPEER;
1803                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1804                 return false;
1805         }
1806
1807         int len = end - (data + 7);
1808         char name[len + 1];
1809         memcpy(name, data + 7, len);
1810         name[len] = 0;
1811         if(!check_id(name)) {
1812                 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
1813                 meshlink_errno = MESHLINK_EPEER;
1814                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1815                 return false;
1816         }
1817
1818         char filename[PATH_MAX];
1819         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1820         if(!access(filename, F_OK)) {
1821                 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
1822                 meshlink_errno = MESHLINK_EEXIST;
1823                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1824                 return false;
1825         }
1826
1827         if(errno != ENOENT) {
1828                 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
1829                 meshlink_errno = MESHLINK_ESTORAGE;
1830                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1831                 return false;
1832         }
1833
1834         FILE *f = fopen(filename, "w");
1835         if(!f) {
1836                 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1837                 meshlink_errno = MESHLINK_ESTORAGE;
1838                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1839                 return false;
1840         }
1841
1842         fwrite(end + 1, strlen(end + 1), 1, f);
1843         fclose(f);
1844
1845         load_all_nodes(mesh);
1846
1847         pthread_mutex_unlock(&(mesh->mesh_mutex));
1848         return true;
1849 }
1850
1851 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1852         if(!mesh || !node) {
1853                 meshlink_errno = MESHLINK_EINVAL;
1854                 return;
1855         }
1856
1857         pthread_mutex_lock(&(mesh->mesh_mutex));
1858         
1859         node_t *n;
1860         n = (node_t*)node;
1861         n->status.blacklisted=true;
1862         logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n",node->name);
1863
1864         //Make blacklisting persistent in the config file
1865         append_config_file(mesh, n->name, "blacklisted", "yes");
1866
1867         pthread_mutex_unlock(&(mesh->mesh_mutex));
1868         return;
1869 }
1870
1871 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1872         if(!mesh || !node) {
1873                 meshlink_errno = MESHLINK_EINVAL;
1874                 return;
1875         }
1876
1877         pthread_mutex_lock(&(mesh->mesh_mutex));
1878         
1879         node_t *n = (node_t *)node;
1880         n->status.blacklisted = false;
1881
1882         //TODO: remove blacklisted = yes from the config file
1883
1884         pthread_mutex_unlock(&(mesh->mesh_mutex));
1885         return;
1886 }
1887
1888 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
1889         mesh->default_blacklist = blacklist;
1890 }
1891
1892 /* Hint that a hostname may be found at an address
1893  * See header file for detailed comment.
1894  */
1895 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
1896         if(!mesh || !node || !addr)
1897                 return;
1898
1899         // Ignore hints about ourself.
1900         if((node_t *)node == mesh->self)
1901                 return;
1902         
1903         pthread_mutex_lock(&(mesh->mesh_mutex));
1904         
1905         char *host = NULL, *port = NULL, *str = NULL;
1906         sockaddr2str((const sockaddr_t *)addr, &host, &port);
1907
1908         if(host && port) {
1909                 xasprintf(&str, "%s %s", host, port);
1910                 if ( (strncmp ("fe80",host,4) != 0) && ( strncmp("127.",host,4) != 0 ) && ( strcmp("localhost",host) !=0 ) )
1911                         append_config_file(mesh, node->name, "Address", str);
1912                 else
1913                         logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
1914         }
1915
1916         free(str);
1917         free(host);
1918         free(port);
1919
1920         pthread_mutex_unlock(&(mesh->mesh_mutex));
1921         // @TODO do we want to fire off a connection attempt right away?
1922 }
1923
1924 /* Return an array of edges in the current network graph.
1925  * Data captures the current state and will not be updated.
1926  * Caller must deallocate data when done.
1927  */
1928 meshlink_edge_t **meshlink_get_all_edges_state(meshlink_handle_t *mesh, meshlink_edge_t **edges, size_t *nmemb) {
1929         if(!mesh || !nmemb || (*nmemb && !edges)) {
1930                 meshlink_errno = MESHLINK_EINVAL;
1931                 return NULL;
1932         }
1933
1934         pthread_mutex_lock(&(mesh->mesh_mutex));
1935         
1936         meshlink_edge_t **result = NULL;
1937         meshlink_edge_t *copy = NULL;
1938         int result_size = 0;
1939
1940         result_size = mesh->edges->count;
1941
1942         // if result is smaller than edges, we have to dealloc all the excess meshlink_edge_t
1943         if(result_size > *nmemb) {
1944                 result = realloc(edges, result_size * sizeof (meshlink_edge_t*));
1945         } else {
1946                 result = edges;
1947         }
1948
1949         if(result) {
1950                 meshlink_edge_t **p = result;
1951                 int n = 0;
1952                 for splay_each(edge_t, e, mesh->edges) {
1953                         // skip edges that do not represent a two-directional connection
1954                         if((!e->reverse) || (e->reverse->to != e->from)) {
1955                                 result_size--;
1956                                 continue;
1957                         }
1958                         n++;
1959                         // the first *nmemb members of result can be re-used
1960                         if(n > *nmemb) {
1961                                 copy = xzalloc(sizeof *copy);
1962                         }
1963                         else {
1964                                 copy = *p;
1965                         }
1966                         copy->from = (meshlink_node_t*)e->from;
1967                         copy->to = (meshlink_node_t*)e->to;
1968                         copy->address = e->address.storage;
1969                         copy->options = e->options;
1970                         copy->weight = e->weight;
1971                         *p++ = copy;
1972                 }
1973                 // shrink result to the actual amount of memory used
1974                 for(int i = *nmemb; i > result_size; i--) {
1975                         free(result[i - 1]);
1976                 }
1977                 result = realloc(result, result_size * sizeof (meshlink_edge_t*));
1978                 *nmemb = result_size;
1979         } else {
1980                 *nmemb = 0;
1981                 free(result);
1982                 meshlink_errno = MESHLINK_ENOMEM;
1983         }
1984
1985         pthread_mutex_unlock(&(mesh->mesh_mutex));
1986
1987         return result;
1988 }
1989
1990 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
1991         //TODO: implement
1992         return true;
1993 }
1994
1995 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
1996         meshlink_channel_t *channel = connection->priv;
1997         if(!channel)
1998                 abort();
1999         node_t *n = channel->node;
2000         meshlink_handle_t *mesh = n->mesh;
2001         if(!channel->receive_cb)
2002                 return -1;
2003         else {
2004                 channel->receive_cb(mesh, channel, data, len);
2005                 return len;
2006         }
2007 }
2008
2009 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2010         node_t *n = utcp_connection->utcp->priv;
2011         if(!n)
2012                 abort();
2013         meshlink_handle_t *mesh = n->mesh;
2014         if(!mesh->channel_accept_cb)
2015                 return;
2016         meshlink_channel_t *channel = xzalloc(sizeof *channel);
2017         channel->node = n;
2018         channel->c = utcp_connection;
2019         if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0))
2020                 utcp_accept(utcp_connection, channel_recv, channel);
2021         else
2022                 free(channel);
2023 }
2024
2025 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2026         node_t *n = utcp->priv;
2027         meshlink_handle_t *mesh = n->mesh;
2028         char hex[len * 2 + 1];
2029         bin2hex(data, hex, len);
2030         logger(mesh, MESHLINK_WARNING, "channel_send(%p, %p, %zu): %s\n", utcp, data, len, hex);
2031         return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? len : -1;
2032 }
2033
2034 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2035         if(!mesh || !channel) {
2036                 meshlink_errno = MESHLINK_EINVAL;
2037                 return;
2038         }
2039
2040         channel->receive_cb = cb;
2041 }
2042
2043 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2044         node_t *n = (node_t *)source;
2045         if(!n->utcp)
2046                 abort();
2047         char hex[len * 2 + 1];
2048         bin2hex(data, hex, len);
2049         logger(mesh, MESHLINK_WARNING, "channel_receive(%p, %p, %zu): %s\n", n->utcp, data, len, hex);
2050         utcp_recv(n->utcp, data, len);
2051 }
2052
2053 static void channel_poll(struct utcp_connection *connection, size_t len) {
2054         meshlink_channel_t *channel = connection->priv;
2055         if(!channel)
2056                 abort();
2057         node_t *n = channel->node;
2058         meshlink_handle_t *mesh = n->mesh;
2059         if(channel->poll_cb)
2060                 channel->poll_cb(mesh, channel, len);
2061 }
2062
2063 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2064         channel->poll_cb = cb;
2065         utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2066 }
2067
2068 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2069         if(!mesh) {
2070                 meshlink_errno = MESHLINK_EINVAL;
2071                 return;
2072         }
2073
2074         pthread_mutex_lock(&mesh->mesh_mutex);
2075         mesh->channel_accept_cb = cb;
2076         mesh->receive_cb = channel_receive;
2077         for splay_each(node_t, n, mesh->nodes) {
2078                 if(!n->utcp && n != mesh->self) {
2079                         logger(mesh, MESHLINK_WARNING, "utcp_init on node %s", n->name);
2080                         n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2081                 }
2082         }
2083         pthread_mutex_unlock(&mesh->mesh_mutex);
2084 }
2085
2086 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) {
2087         if(!mesh || !node) {
2088                 meshlink_errno = MESHLINK_EINVAL;
2089                 return NULL;
2090         }
2091
2092         logger(mesh, MESHLINK_WARNING, "meshlink_channel_open(%p, %s, %u, %p, %p, %zu)\n", mesh, node->name, port, cb, data, len);
2093         node_t *n = (node_t *)node;
2094         if(!n->utcp) {
2095                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2096                 mesh->receive_cb = channel_receive;
2097                 if(!n->utcp) {
2098                         meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2099                         return NULL;
2100                 }
2101         }
2102         meshlink_channel_t *channel = xzalloc(sizeof *channel);
2103         channel->node = n;
2104         channel->receive_cb = cb;
2105         channel->c = utcp_connect(n->utcp, port, channel_recv, channel);
2106         if(!channel->c) {
2107                 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2108                 free(channel);
2109                 return NULL;
2110         }
2111         return channel;
2112 }
2113
2114 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2115         if(!mesh || !channel) {
2116                 meshlink_errno = MESHLINK_EINVAL;
2117                 return;
2118         }
2119
2120         utcp_shutdown(channel->c, direction);
2121 }
2122
2123 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2124         if(!mesh || !channel) {
2125                 meshlink_errno = MESHLINK_EINVAL;
2126                 return;
2127         }
2128
2129         utcp_close(channel->c);
2130         free(channel);
2131 }
2132
2133 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2134         if(!mesh || !channel) {
2135                 meshlink_errno = MESHLINK_EINVAL;
2136                 return -1;
2137         }
2138
2139         if(!len)
2140                 return 0;
2141
2142         if(!data) {
2143                 meshlink_errno = MESHLINK_EINVAL;
2144                 return -1;
2145         }
2146
2147         // TODO: more finegrained locking.
2148         // Ideally we want to put the data into the UTCP connection's send buffer.
2149         // Then, preferrably only if there is room in the receiver window,
2150         // kick the meshlink thread to go send packets.
2151
2152         pthread_mutex_lock(&mesh->mesh_mutex);
2153         ssize_t retval = utcp_send(channel->c, data, len);
2154         pthread_mutex_unlock(&mesh->mesh_mutex);
2155
2156         if(retval < 0)
2157                 meshlink_errno = MESHLINK_ENETWORK;
2158         return retval;
2159 }
2160
2161 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2162         if(n->status.reachable && mesh->channel_accept_cb && !n->utcp)
2163                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2164         if(mesh->node_status_cb)
2165                 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
2166 }
2167
2168 static void __attribute__((constructor)) meshlink_init(void) {
2169         crypto_init();
2170 }
2171
2172 static void __attribute__((destructor)) meshlink_exit(void) {
2173         crypto_exit();
2174 }
2175
2176 /// Device class traits
2177 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX +1] = {
2178         { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2179         { .min_connects = 3, .max_connects = 100, .edge_weight = 3 },   // DEV_CLASS_STATIONARY
2180         { .min_connects = 3, .max_connects = 3, .edge_weight = 6 },             // DEV_CLASS_PORTABLE
2181         { .min_connects = 1, .max_connects = 1, .edge_weight = 9 },             // DEV_CLASS_UNKNOWN
2182 };