]> git.meshlink.io Git - meshlink/blob - src/meshlink.c
Add a poll callback to channels.
[meshlink] / src / meshlink.c
1 /*
2     meshlink.c -- Implementation of the MeshLink API.
3     Copyright (C) 2014 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, "w");
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 bool meshlink_setup(meshlink_handle_t *mesh) {
703         if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
704                 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
705                 meshlink_errno = MESHLINK_ESTORAGE;
706                 return false;
707         }
708
709         char filename[PATH_MAX];
710         snprintf(filename, sizeof filename, "%s" SLASH "hosts", mesh->confbase);
711
712         if(mkdir(filename, 0777) && errno != EEXIST) {
713                 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
714                 meshlink_errno = MESHLINK_ESTORAGE;
715                 return false;
716         }
717
718         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
719
720         if(!access(filename, F_OK)) {
721                 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
722                 meshlink_errno = MESHLINK_EEXIST;
723                 return false;
724         }
725
726         FILE *f = fopen(filename, "w");
727         if(!f) {
728                 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
729                 meshlink_errno = MESHLINK_ESTORAGE;
730                 return false;
731         }
732
733         fprintf(f, "Name = %s\n", mesh->name);
734         fclose(f);
735
736         if(!ecdsa_keygen(mesh)) {
737                 meshlink_errno = MESHLINK_EINTERNAL;
738                 return false;
739         }
740
741         check_port(mesh);
742
743         return true;
744 }
745
746 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char* appname, dev_class_t devclass) {
747         return meshlink_open_with_size(confbase, name, appname, devclass, sizeof(meshlink_handle_t));
748 }
749
750 meshlink_handle_t *meshlink_open_with_size(const char *confbase, const char *name, const char* appname, dev_class_t devclass, size_t size) {
751
752         // Validate arguments provided by the application
753         bool usingname = false;
754         
755         logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
756
757         if(!confbase || !*confbase) {
758                 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
759                 meshlink_errno = MESHLINK_EINVAL;
760                 return NULL;
761         }
762
763         if(!appname || !*appname) {
764                 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
765                 meshlink_errno = MESHLINK_EINVAL;
766                 return NULL;
767         }
768
769         if(!name || !*name) {
770                 logger(NULL, MESHLINK_ERROR, "No name given!\n");
771                 //return NULL;
772         }
773         else { //check name only if there is a name != NULL
774
775                 if(!check_id(name)) {
776                         logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
777                         meshlink_errno = MESHLINK_EINVAL;
778                         return NULL;
779                 } else { usingname = true;}
780         }
781
782         if(devclass < 0 || devclass > _DEV_CLASS_MAX) {
783                 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
784                 meshlink_errno = MESHLINK_EINVAL;
785                 return NULL;
786         }
787
788         meshlink_handle_t *mesh = xzalloc(size);
789         mesh->confbase = xstrdup(confbase);
790         mesh->appname = xstrdup(appname);
791         mesh->devclass = devclass;
792         if (usingname) mesh->name = xstrdup(name);
793
794         // initialize mutex
795         pthread_mutexattr_t attr;
796         pthread_mutexattr_init(&attr);
797         pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
798         pthread_mutex_init(&(mesh->mesh_mutex), &attr);
799         
800         mesh->threadstarted = false;
801         event_loop_init(&mesh->loop);
802         mesh->loop.data = mesh;
803
804         // Check whether meshlink.conf already exists
805
806         char filename[PATH_MAX];
807         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
808
809         if(access(filename, R_OK)) {
810                 if(errno == ENOENT) {
811                         // If not, create it
812                         if(!meshlink_setup(mesh)) {
813                                 // meshlink_errno is set by meshlink_setup()
814                                 return NULL;
815                         }
816                 } else {
817                         logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
818                         meshlink_close(mesh);
819                         meshlink_errno = MESHLINK_ESTORAGE;
820                         return NULL;
821                 }
822         }
823
824         // Read the configuration
825
826         init_configuration(&mesh->config);
827
828         if(!read_server_config(mesh)) {
829                 meshlink_close(mesh);
830                 meshlink_errno = MESHLINK_ESTORAGE;
831                 return NULL;
832         };
833
834 #ifdef HAVE_MINGW
835         struct WSAData wsa_state;
836         WSAStartup(MAKEWORD(2, 2), &wsa_state);
837 #endif
838
839         // Setup up everything
840         // TODO: we should not open listening sockets yet
841
842         if(!setup_network(mesh)) {
843                 meshlink_close(mesh);
844                 meshlink_errno = MESHLINK_ENETWORK;
845                 return NULL;
846         }
847
848         logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
849         return mesh;
850 }
851
852 static void *meshlink_main_loop(void *arg) {
853         meshlink_handle_t *mesh = arg;
854
855         pthread_mutex_lock(&(mesh->mesh_mutex));
856
857         try_outgoing_connections(mesh);
858
859         logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
860         main_loop(mesh);
861         logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
862
863         pthread_mutex_unlock(&(mesh->mesh_mutex));
864         return NULL;
865 }
866
867 bool meshlink_start(meshlink_handle_t *mesh) {
868         if(!mesh) {
869                 meshlink_errno = MESHLINK_EINVAL;
870                 return false;
871         }
872         pthread_mutex_lock(&(mesh->mesh_mutex));
873         
874         logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
875
876         mesh->thedatalen = 0;
877
878         // TODO: open listening sockets first
879
880         //Check that a valid name is set
881         if(!mesh->name ) {
882                 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
883                 meshlink_errno = MESHLINK_EINVAL;
884                 pthread_mutex_unlock(&(mesh->mesh_mutex));
885                 return false;
886         }
887
888         // Start the main thread
889
890         if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
891                 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
892                 memset(&mesh->thread, 0, sizeof mesh->thread);
893                 meshlink_errno = MESHLINK_EINTERNAL;
894                 pthread_mutex_unlock(&(mesh->mesh_mutex));
895                 return false;
896         }
897
898         mesh->threadstarted=true;
899
900         discovery_start(mesh);
901
902         pthread_mutex_unlock(&(mesh->mesh_mutex));
903         return true;
904 }
905
906 void meshlink_stop(meshlink_handle_t *mesh) {
907         if(!mesh) {
908                 meshlink_errno = MESHLINK_EINVAL;
909                 return;
910         }
911
912         pthread_mutex_lock(&(mesh->mesh_mutex));
913         logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
914
915         // Stop discovery
916         discovery_stop(mesh);
917
918         // Shut down a listening socket to signal the main thread to shut down
919
920         listen_socket_t *s = &mesh->listen_socket[0];
921         shutdown(s->tcp.fd, SHUT_RDWR);
922
923         // Wait for the main thread to finish
924         pthread_mutex_unlock(&(mesh->mesh_mutex));
925         pthread_join(mesh->thread, NULL);
926         pthread_mutex_lock(&(mesh->mesh_mutex));
927
928         mesh->threadstarted = false;
929
930         // Fix the socket
931         
932         closesocket(s->tcp.fd);
933         io_del(&mesh->loop, &s->tcp);
934         s->tcp.fd = setup_listen_socket(&s->sa);
935         if(s->tcp.fd < 0)
936                 logger(mesh, MESHLINK_ERROR, "Could not repair listenen socket!");
937         else
938                 io_add(&mesh->loop, &s->tcp, handle_new_meta_connection, s, s->tcp.fd, IO_READ);
939         
940         pthread_mutex_unlock(&(mesh->mesh_mutex));
941 }
942
943 void meshlink_close(meshlink_handle_t *mesh) {
944         if(!mesh || !mesh->confbase) {
945                 meshlink_errno = MESHLINK_EINVAL;
946                 return;
947         }
948
949         // lock is not released after this
950         pthread_mutex_lock(&(mesh->mesh_mutex));
951
952         // Close and free all resources used.
953
954         close_network_connections(mesh);
955
956         logger(mesh, MESHLINK_INFO, "Terminating");
957
958         exit_configuration(&mesh->config);
959         event_loop_exit(&mesh->loop);
960
961 #ifdef HAVE_MINGW
962         if(mesh->confbase)
963                 WSACleanup();
964 #endif
965
966         ecdsa_free(mesh->invitation_key);
967
968         free(mesh->name);
969         free(mesh->appname);
970         free(mesh->confbase);
971         pthread_mutex_destroy(&(mesh->mesh_mutex));
972
973         memset(mesh, 0, sizeof *mesh);
974
975         free(mesh);
976 }
977
978 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
979         if(!mesh) {
980                 meshlink_errno = MESHLINK_EINVAL;
981                 return;
982         }
983
984         pthread_mutex_lock(&(mesh->mesh_mutex));
985         mesh->receive_cb = cb;
986         pthread_mutex_unlock(&(mesh->mesh_mutex));
987 }
988
989 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
990         if(!mesh) {
991                 meshlink_errno = MESHLINK_EINVAL;
992                 return;
993         }
994
995         pthread_mutex_lock(&(mesh->mesh_mutex));
996         mesh->node_status_cb = cb;
997         pthread_mutex_unlock(&(mesh->mesh_mutex));
998 }
999
1000 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1001         if(mesh) {
1002                 pthread_mutex_lock(&(mesh->mesh_mutex));
1003                 mesh->log_cb = cb;
1004                 mesh->log_level = cb ? level : 0;
1005                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1006         } else {
1007                 global_log_cb = cb;
1008                 global_log_level = cb ? level : 0;
1009         }
1010 }
1011
1012 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1013         meshlink_packethdr_t *hdr;
1014
1015         // Validate arguments
1016         if(!mesh || !destination || len >= MAXSIZE - sizeof *hdr) {
1017                 meshlink_errno = MESHLINK_EINVAL;
1018                 return false;
1019         }
1020
1021         if(!len)
1022                 return true;
1023
1024         if(!data) {
1025                 meshlink_errno = MESHLINK_EINVAL;
1026                 return false;
1027         }
1028
1029         // Prepare the packet
1030         vpn_packet_t *packet = malloc(sizeof *packet);
1031         if(!packet) {
1032                 meshlink_errno = MESHLINK_ENOMEM;
1033                 return false;
1034         }
1035
1036         packet->probe = false;
1037         packet->tcp = false;
1038         packet->len = len + sizeof *hdr;
1039
1040         hdr = (meshlink_packethdr_t *)packet->data;
1041         memset(hdr, 0, sizeof *hdr);
1042         memcpy(hdr->destination, destination->name, sizeof hdr->destination);
1043         memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
1044
1045         memcpy(packet->data + sizeof *hdr, data, len);
1046
1047         // Queue it
1048         if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1049                 free(packet);
1050                 meshlink_errno = MESHLINK_ENOMEM;
1051                 return false;
1052         }
1053
1054         // Notify event loop
1055         signal_trigger(&(mesh->loop),&(mesh->datafromapp));
1056         
1057         return true;
1058 }
1059
1060 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1061         vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1062         if(!packet)
1063                 return;
1064
1065         mesh->self->in_packets++;
1066         mesh->self->in_bytes += packet->len;
1067         route(mesh, mesh->self, packet);
1068 }
1069
1070 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1071         if(!mesh || !destination) {
1072                 meshlink_errno = MESHLINK_EINVAL;
1073                 return -1;
1074         }
1075         pthread_mutex_lock(&(mesh->mesh_mutex));
1076
1077         node_t *n = (node_t *)destination;
1078         if(!n->status.reachable) {
1079                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1080                 return 0;
1081         
1082         }
1083         else if(n->mtuprobes > 30 && n->minmtu) {
1084                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1085                 return n->minmtu;
1086         }
1087         else {
1088                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1089                 return MTU;
1090         }
1091 }
1092
1093 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1094         if(!mesh || !node) {
1095                 meshlink_errno = MESHLINK_EINVAL;
1096                 return NULL;
1097         }
1098         pthread_mutex_lock(&(mesh->mesh_mutex));
1099
1100         node_t *n = (node_t *)node;
1101
1102         if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1103                 meshlink_errno = MESHLINK_EINTERNAL;
1104                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1105                 return false;
1106         }
1107
1108         char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1109
1110         if(!fingerprint)
1111                 meshlink_errno = MESHLINK_EINTERNAL;
1112
1113         pthread_mutex_unlock(&(mesh->mesh_mutex));
1114         return fingerprint;
1115 }
1116
1117 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1118         if(!mesh || !name) {
1119                 meshlink_errno = MESHLINK_EINVAL;
1120                 return NULL;
1121         }
1122
1123         meshlink_node_t *node = NULL;
1124
1125         pthread_mutex_lock(&(mesh->mesh_mutex));
1126         node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1127         pthread_mutex_unlock(&(mesh->mesh_mutex));
1128         return node;
1129 }
1130
1131 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1132         if(!mesh || !nmemb || (*nmemb && !nodes)) {
1133                 meshlink_errno = MESHLINK_EINVAL;
1134                 return NULL;
1135         }
1136
1137         meshlink_node_t **result;
1138
1139         //lock mesh->nodes
1140         pthread_mutex_lock(&(mesh->mesh_mutex));
1141
1142         *nmemb = mesh->nodes->count;
1143         result = realloc(nodes, *nmemb * sizeof *nodes);
1144
1145         if(result) {
1146                 meshlink_node_t **p = result;
1147                 for splay_each(node_t, n, mesh->nodes)
1148                         *p++ = (meshlink_node_t *)n;
1149         } else {
1150                 *nmemb = 0;
1151                 free(nodes);
1152                 meshlink_errno = MESHLINK_ENOMEM;
1153         }
1154
1155         pthread_mutex_unlock(&(mesh->mesh_mutex));
1156
1157         return result;
1158 }
1159
1160 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1161         if(!mesh || !data || !len || !signature || !siglen) {
1162                 meshlink_errno = MESHLINK_EINVAL;
1163                 return false;
1164         }
1165
1166         if(*siglen < MESHLINK_SIGLEN) {
1167                 meshlink_errno = MESHLINK_EINVAL;
1168                 return false;
1169         }
1170
1171         pthread_mutex_lock(&(mesh->mesh_mutex));
1172
1173         if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1174                 meshlink_errno = MESHLINK_EINTERNAL;
1175                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1176                 return false;
1177         }
1178
1179         *siglen = MESHLINK_SIGLEN;
1180         pthread_mutex_unlock(&(mesh->mesh_mutex));
1181         return true;
1182 }
1183
1184 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1185         if(!mesh || !data || !len || !signature) {
1186                 meshlink_errno = MESHLINK_EINVAL;
1187                 return false;
1188         }
1189
1190         if(siglen != MESHLINK_SIGLEN) {
1191                 meshlink_errno = MESHLINK_EINVAL;
1192                 return false;
1193         }
1194
1195         pthread_mutex_lock(&(mesh->mesh_mutex));
1196
1197         bool rval = false;
1198
1199         struct node_t *n = (struct node_t *)source;
1200         node_read_ecdsa_public_key(mesh, n);
1201         if(!n->ecdsa) {
1202                 meshlink_errno = MESHLINK_EINTERNAL;
1203                 rval = false;
1204         } else {
1205                 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1206         }
1207         pthread_mutex_unlock(&(mesh->mesh_mutex));
1208         return rval;
1209 }
1210
1211 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1212         char filename[PATH_MAX];
1213         
1214         pthread_mutex_lock(&(mesh->mesh_mutex));
1215
1216         snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
1217         if(mkdir(filename, 0700) && errno != EEXIST) {
1218                 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1219                 meshlink_errno = MESHLINK_ESTORAGE;
1220                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1221                 return false;
1222         }
1223
1224         // Count the number of valid invitations, clean up old ones
1225         DIR *dir = opendir(filename);
1226         if(!dir) {
1227                 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1228                 meshlink_errno = MESHLINK_ESTORAGE;
1229                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1230                 return false;
1231         }
1232
1233         errno = 0;
1234         int count = 0;
1235         struct dirent *ent;
1236         time_t deadline = time(NULL) - 604800; // 1 week in the past
1237
1238         while((ent = readdir(dir))) {
1239                 if(strlen(ent->d_name) != 24)
1240                         continue;
1241                 char invname[PATH_MAX];
1242                 struct stat st;
1243                 snprintf(invname, sizeof invname, "%s" SLASH "%s", filename, ent->d_name);
1244                 if(!stat(invname, &st)) {
1245                         if(mesh->invitation_key && deadline < st.st_mtime)
1246                                 count++;
1247                         else
1248                                 unlink(invname);
1249                 } else {
1250                         logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1251                         errno = 0;
1252                 }
1253         }
1254
1255         if(errno) {
1256                 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
1257                 closedir(dir);
1258                 meshlink_errno = MESHLINK_ESTORAGE;
1259                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1260                 return false;
1261         }
1262
1263         closedir(dir);
1264
1265         snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1266
1267         // Remove the key if there are no outstanding invitations.
1268         if(!count) {
1269                 unlink(filename);
1270                 if(mesh->invitation_key) {
1271                         ecdsa_free(mesh->invitation_key);
1272                         mesh->invitation_key = NULL;
1273                 }
1274         }
1275
1276         if(mesh->invitation_key) {
1277                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1278                 return true;
1279         }
1280
1281         // Create a new key if necessary.
1282         FILE *f = fopen(filename, "r");
1283         if(!f) {
1284                 if(errno != ENOENT) {
1285                         logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
1286                         meshlink_errno = MESHLINK_ESTORAGE;
1287                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1288                         return false;
1289                 }
1290
1291                 mesh->invitation_key = ecdsa_generate();
1292                 if(!mesh->invitation_key) {
1293                         logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
1294                         meshlink_errno = MESHLINK_EINTERNAL;
1295                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1296                         return false;
1297                 }
1298                 f = fopen(filename, "w");
1299                 if(!f) {
1300                         logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
1301                         meshlink_errno = MESHLINK_ESTORAGE;
1302                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1303                         return false;
1304                 }
1305                 chmod(filename, 0600);
1306                 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1307                 fclose(f);
1308         } else {
1309                 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1310                 fclose(f);
1311                 if(!mesh->invitation_key) {
1312                         logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
1313                         meshlink_errno = MESHLINK_ESTORAGE;
1314                 }
1315         }
1316
1317         pthread_mutex_unlock(&(mesh->mesh_mutex));
1318         return mesh->invitation_key;
1319 }
1320
1321 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1322         if(!mesh || !address) {
1323                 meshlink_errno = MESHLINK_EINVAL;
1324                 return false;
1325         }
1326         
1327         bool rval = false;
1328
1329         pthread_mutex_lock(&(mesh->mesh_mutex));
1330
1331         for(const char *p = address; *p; p++) {
1332                 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
1333                         continue;
1334                 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1335                 meshlink_errno = MESHLINK_EINVAL;
1336                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1337                 return false;
1338         }
1339
1340         rval = append_config_file(mesh, mesh->self->name, "Address", address);
1341         pthread_mutex_unlock(&(mesh->mesh_mutex));
1342         return rval;
1343 }
1344
1345 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1346         if(!mesh) {
1347                 meshlink_errno = MESHLINK_EINVAL;
1348                 return NULL;
1349         }
1350         
1351         pthread_mutex_lock(&(mesh->mesh_mutex));
1352
1353         // Check validity of the new node's name
1354         if(!check_id(name)) {
1355                 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
1356                 meshlink_errno = MESHLINK_EINVAL;
1357                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1358                 return NULL;
1359         }
1360
1361         // Ensure no host configuration file with that name exists
1362         char filename[PATH_MAX];
1363         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1364         if(!access(filename, F_OK)) {
1365                 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
1366                 meshlink_errno = MESHLINK_EEXIST;
1367                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1368                 return NULL;
1369         }
1370
1371         // Ensure no other nodes know about this name
1372         if(meshlink_get_node(mesh, name)) {
1373                 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
1374                 meshlink_errno = MESHLINK_EEXIST;
1375                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1376                 return NULL;
1377         }
1378
1379         // Get the local address
1380         char *address = get_my_hostname(mesh);
1381         if(!address) {
1382                 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
1383                 meshlink_errno = MESHLINK_ERESOLV;
1384                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1385                 return NULL;
1386         }
1387
1388         if(!refresh_invitation_key(mesh)) {
1389                 meshlink_errno = MESHLINK_EINTERNAL;
1390                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1391                 return NULL;
1392         }
1393
1394         char hash[64];
1395
1396         // Create a hash of the key.
1397         char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1398         sha512(fingerprint, strlen(fingerprint), hash);
1399         b64encode_urlsafe(hash, hash, 18);
1400
1401         // Create a random cookie for this invitation.
1402         char cookie[25];
1403         randomize(cookie, 18);
1404
1405         // Create a filename that doesn't reveal the cookie itself
1406         char buf[18 + strlen(fingerprint)];
1407         char cookiehash[64];
1408         memcpy(buf, cookie, 18);
1409         memcpy(buf + 18, fingerprint, sizeof buf - 18);
1410         sha512(buf, sizeof buf, cookiehash);
1411         b64encode_urlsafe(cookiehash, cookiehash, 18);
1412
1413         b64encode_urlsafe(cookie, cookie, 18);
1414
1415         free(fingerprint);
1416
1417         // Create a file containing the details of the invitation.
1418         snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1419         int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1420         if(!ifd) {
1421                 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1422                 meshlink_errno = MESHLINK_ESTORAGE;
1423                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1424                 return NULL;
1425         }
1426         FILE *f = fdopen(ifd, "w");
1427         if(!f)
1428                 abort();
1429
1430         // Fill in the details.
1431         fprintf(f, "Name = %s\n", name);
1432         //if(netname)
1433         //      fprintf(f, "NetName = %s\n", netname);
1434         fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1435
1436         // Copy Broadcast and Mode
1437         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
1438         FILE *tc = fopen(filename,  "r");
1439         if(tc) {
1440                 char buf[1024];
1441                 while(fgets(buf, sizeof buf, tc)) {
1442                         if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1443                                         || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1444                                 fputs(buf, f);
1445                                 // Make sure there is a newline character.
1446                                 if(!strchr(buf, '\n'))
1447                                         fputc('\n', f);
1448                         }
1449                 }
1450                 fclose(tc);
1451         } else {
1452                 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1453                 meshlink_errno = MESHLINK_ESTORAGE;
1454                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1455                 return NULL;
1456         }
1457
1458         fprintf(f, "#---------------------------------------------------------------#\n");
1459         fprintf(f, "Name = %s\n", mesh->self->name);
1460
1461         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1462         fcopy(f, filename);
1463         fclose(f);
1464
1465         // Create an URL from the local address, key hash and cookie
1466         char *url;
1467         xasprintf(&url, "%s/%s%s", address, hash, cookie);
1468         free(address);
1469
1470         pthread_mutex_unlock(&(mesh->mesh_mutex));
1471         return url;
1472 }
1473
1474 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1475         if(!mesh || !invitation) {
1476                 meshlink_errno = MESHLINK_EINVAL;
1477                 return false;
1478         }
1479         
1480         pthread_mutex_lock(&(mesh->mesh_mutex));
1481
1482         //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1483         char copy[strlen(invitation) + 1];
1484         strcpy(copy, invitation);
1485
1486         // Split the invitation URL into hostname, port, key hash and cookie.
1487
1488         char *slash = strchr(copy, '/');
1489         if(!slash)
1490                 goto invalid;
1491
1492         *slash++ = 0;
1493
1494         if(strlen(slash) != 48)
1495                 goto invalid;
1496
1497         char *address = copy;
1498         char *port = NULL;
1499         if(*address == '[') {
1500                 address++;
1501                 char *bracket = strchr(address, ']');
1502                 if(!bracket)
1503                         goto invalid;
1504                 *bracket = 0;
1505                 if(bracket[1] == ':')
1506                         port = bracket + 2;
1507         } else {
1508                 port = strchr(address, ':');
1509                 if(port)
1510                         *port++ = 0;
1511         }
1512
1513         if(!port)
1514                 goto invalid;
1515
1516         if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1517                 goto invalid;
1518
1519         // Generate a throw-away key for the invitation.
1520         ecdsa_t *key = ecdsa_generate();
1521         if(!key) {
1522                 meshlink_errno = MESHLINK_EINTERNAL;
1523                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1524                 return false;
1525         }
1526
1527         char *b64key = ecdsa_get_base64_public_key(key);
1528
1529         //Before doing meshlink_join make sure we are not connected to another mesh
1530         if ( mesh->threadstarted ){
1531                 goto invalid;
1532         }
1533
1534         // Connect to the meshlink daemon mentioned in the URL.
1535         struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1536         if(!ai) {
1537                 meshlink_errno = MESHLINK_ERESOLV;
1538                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1539                 return false;
1540         }
1541
1542         mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1543         if(mesh->sock <= 0) {
1544                 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
1545                 freeaddrinfo(ai);
1546                 meshlink_errno = MESHLINK_ENETWORK;
1547                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1548                 return false;
1549         }
1550
1551         if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1552                 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1553                 closesocket(mesh->sock);
1554                 freeaddrinfo(ai);
1555                 meshlink_errno = MESHLINK_ENETWORK;
1556                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1557                 return false;
1558         }
1559
1560         freeaddrinfo(ai);
1561
1562         logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
1563
1564         // Tell him we have an invitation, and give him our throw-away key.
1565
1566         mesh->blen = 0;
1567
1568         if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1569                 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1570                 closesocket(mesh->sock);
1571                 meshlink_errno = MESHLINK_ENETWORK;
1572                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1573                 return false;
1574         }
1575
1576         free(b64key);
1577
1578         char hisname[4096] = "";
1579         int code, hismajor, hisminor = 0;
1580
1581         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) {
1582                 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
1583                 closesocket(mesh->sock);
1584                 meshlink_errno = MESHLINK_ENETWORK;
1585                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1586                 return false;
1587         }
1588
1589         // Check if the hash of the key he gave us matches the hash in the URL.
1590         char *fingerprint = mesh->line + 2;
1591         char hishash[64];
1592         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1593                 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
1594                 meshlink_errno = MESHLINK_EINTERNAL;
1595                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1596                 return false;
1597         }
1598         if(memcmp(hishash, mesh->hash, 18)) {
1599                 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1600                 meshlink_errno = MESHLINK_EPEER;
1601                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1602                 return false;
1603
1604         }
1605
1606         ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1607         if(!hiskey) {
1608                 meshlink_errno = MESHLINK_EINTERNAL;
1609                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1610                 return false;
1611         }
1612
1613         // Start an SPTPS session
1614         if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive)) {
1615                 meshlink_errno = MESHLINK_EINTERNAL;
1616                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1617                 return false;
1618         }
1619
1620         // Feed rest of input buffer to SPTPS
1621         if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
1622                 meshlink_errno = MESHLINK_EPEER;
1623                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1624                 return false;
1625         }
1626
1627         int len;
1628
1629         while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1630                 if(len < 0) {
1631                         if(errno == EINTR)
1632                                 continue;
1633                         logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1634                         meshlink_errno = MESHLINK_ENETWORK;
1635                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1636                         return false;
1637                 }
1638
1639                 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
1640                         meshlink_errno = MESHLINK_EPEER;
1641                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1642                         return false;
1643                 }
1644         }
1645
1646         sptps_stop(&mesh->sptps);
1647         ecdsa_free(hiskey);
1648         ecdsa_free(key);
1649         closesocket(mesh->sock);
1650
1651         if(!mesh->success) {
1652                 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
1653                 meshlink_errno = MESHLINK_EPEER;
1654                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1655                 return false;
1656         }
1657
1658         pthread_mutex_unlock(&(mesh->mesh_mutex));
1659         return true;
1660
1661 invalid:
1662         logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL or you are already connected to a Mesh ?\n");
1663         meshlink_errno = MESHLINK_EINVAL;
1664         pthread_mutex_unlock(&(mesh->mesh_mutex));
1665         return false;
1666 }
1667
1668 char *meshlink_export(meshlink_handle_t *mesh) {
1669         if(!mesh) {
1670                 meshlink_errno = MESHLINK_EINVAL;
1671                 return NULL;
1672         }
1673
1674         pthread_mutex_lock(&(mesh->mesh_mutex));
1675         
1676         char filename[PATH_MAX];
1677         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1678         FILE *f = fopen(filename, "r");
1679         if(!f) {
1680                 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
1681                 meshlink_errno = MESHLINK_ESTORAGE;
1682                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1683                 return NULL;
1684         }
1685
1686         fseek(f, 0, SEEK_END);
1687         int fsize = ftell(f);
1688         rewind(f);
1689
1690         size_t len = fsize + 9 + strlen(mesh->self->name);
1691         char *buf = xmalloc(len);
1692         snprintf(buf, len, "Name = %s\n", mesh->self->name);
1693         if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
1694                 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
1695                 fclose(f);
1696                 meshlink_errno = MESHLINK_ESTORAGE;
1697                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1698                 return NULL;
1699         }
1700
1701         fclose(f);
1702         buf[len - 1] = 0;
1703         
1704         pthread_mutex_unlock(&(mesh->mesh_mutex));
1705         return buf;
1706 }
1707
1708 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1709         if(!mesh || !data) {
1710                 meshlink_errno = MESHLINK_EINVAL;
1711                 return false;
1712         }
1713         
1714         pthread_mutex_lock(&(mesh->mesh_mutex));
1715
1716         if(strncmp(data, "Name = ", 7)) {
1717                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
1718                 meshlink_errno = MESHLINK_EPEER;
1719                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1720                 return false;
1721         }
1722
1723         char *end = strchr(data + 7, '\n');
1724         if(!end) {
1725                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
1726                 meshlink_errno = MESHLINK_EPEER;
1727                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1728                 return false;
1729         }
1730
1731         int len = end - (data + 7);
1732         char name[len + 1];
1733         memcpy(name, data + 7, len);
1734         name[len] = 0;
1735         if(!check_id(name)) {
1736                 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
1737                 meshlink_errno = MESHLINK_EPEER;
1738                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1739                 return false;
1740         }
1741
1742         char filename[PATH_MAX];
1743         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1744         if(!access(filename, F_OK)) {
1745                 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
1746                 meshlink_errno = MESHLINK_EEXIST;
1747                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1748                 return false;
1749         }
1750
1751         if(errno != ENOENT) {
1752                 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
1753                 meshlink_errno = MESHLINK_ESTORAGE;
1754                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1755                 return false;
1756         }
1757
1758         FILE *f = fopen(filename, "w");
1759         if(!f) {
1760                 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1761                 meshlink_errno = MESHLINK_ESTORAGE;
1762                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1763                 return false;
1764         }
1765
1766         fwrite(end + 1, strlen(end + 1), 1, f);
1767         fclose(f);
1768
1769         load_all_nodes(mesh);
1770
1771         pthread_mutex_unlock(&(mesh->mesh_mutex));
1772         return true;
1773 }
1774
1775 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1776         if(!mesh || !node) {
1777                 meshlink_errno = MESHLINK_EINVAL;
1778                 return;
1779         }
1780
1781         pthread_mutex_lock(&(mesh->mesh_mutex));
1782         
1783         node_t *n;
1784         n = (node_t*)node;
1785         n->status.blacklisted=true;
1786         logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n",node->name);
1787
1788         //Make blacklisting persistent in the config file
1789         append_config_file(mesh, n->name, "blacklisted", "yes");
1790
1791         pthread_mutex_unlock(&(mesh->mesh_mutex));
1792         return;
1793 }
1794
1795 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1796         if(!mesh || !node) {
1797                 meshlink_errno = MESHLINK_EINVAL;
1798                 return;
1799         }
1800
1801         pthread_mutex_lock(&(mesh->mesh_mutex));
1802         
1803         node_t *n = (node_t *)node;
1804         n->status.blacklisted = false;
1805
1806         //TODO: remove blacklisted = yes from the config file
1807
1808         pthread_mutex_unlock(&(mesh->mesh_mutex));
1809         return;
1810 }
1811
1812 /* Hint that a hostname may be found at an address
1813  * See header file for detailed comment.
1814  */
1815 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
1816         if(!mesh || !node || !addr)
1817                 return;
1818         
1819         pthread_mutex_lock(&(mesh->mesh_mutex));
1820         
1821         char *host = NULL, *port = NULL, *str = NULL;
1822         sockaddr2str((const sockaddr_t *)addr, &host, &port);
1823
1824         if(host && port) {
1825                 xasprintf(&str, "%s %s", host, port);
1826                 if ( (strncmp ("fe80",host,4) != 0) && ( strncmp("127.",host,4) != 0 ) && ( strcmp("localhost",host) !=0 ) )
1827                         append_config_file(mesh, node->name, "Address", str);
1828                 else
1829                         logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
1830         }
1831
1832         free(str);
1833         free(host);
1834         free(port);
1835
1836         pthread_mutex_unlock(&(mesh->mesh_mutex));
1837         // @TODO do we want to fire off a connection attempt right away?
1838 }
1839
1840 /* Return an array of edges in the current network graph.
1841  * Data captures the current state and will not be updated.
1842  * Caller must deallocate data when done.
1843  */
1844 meshlink_edge_t **meshlink_get_all_edges_state(meshlink_handle_t *mesh, meshlink_edge_t **edges, size_t *nmemb) {
1845         if(!mesh || !nmemb || (*nmemb && !edges)) {
1846                 meshlink_errno = MESHLINK_EINVAL;
1847                 return NULL;
1848         }
1849
1850         pthread_mutex_lock(&(mesh->mesh_mutex));
1851         
1852         meshlink_edge_t **result = NULL;
1853         meshlink_edge_t *copy = NULL;
1854         int result_size = 0;
1855
1856         result_size = mesh->edges->count;
1857
1858         // if result is smaller than edges, we have to dealloc all the excess meshlink_edge_t
1859         if(result_size > *nmemb) {
1860                 result = realloc(edges, result_size * sizeof (meshlink_edge_t*));
1861         } else {
1862                 result = edges;
1863         }
1864
1865         if(result) {
1866                 meshlink_edge_t **p = result;
1867                 int n = 0;
1868                 for splay_each(edge_t, e, mesh->edges) {
1869                         // skip edges that do not represent a two-directional connection
1870                         if((!e->reverse) || (e->reverse->to != e->from)) {
1871                                 result_size--;
1872                                 continue;
1873                         }
1874                         n++;
1875                         // the first *nmemb members of result can be re-used
1876                         if(n > *nmemb) {
1877                                 copy = xzalloc(sizeof *copy);
1878                         }
1879                         else {
1880                                 copy = *p;
1881                         }
1882                         copy->from = (meshlink_node_t*)e->from;
1883                         copy->to = (meshlink_node_t*)e->to;
1884                         copy->address = e->address.storage;
1885                         copy->options = e->options;
1886                         copy->weight = e->weight;
1887                         *p++ = copy;
1888                 }
1889                 // shrink result to the actual amount of memory used
1890                 for(int i = *nmemb; i > result_size; i--) {
1891                         free(result[i - 1]);
1892                 }
1893                 result = realloc(result, result_size * sizeof (meshlink_edge_t*));
1894                 *nmemb = result_size;
1895         } else {
1896                 *nmemb = 0;
1897                 free(result);
1898                 meshlink_errno = MESHLINK_ENOMEM;
1899         }
1900
1901         pthread_mutex_unlock(&(mesh->mesh_mutex));
1902
1903         return result;
1904 }
1905
1906 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
1907         //TODO: implement
1908         return true;
1909 }
1910
1911 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
1912         meshlink_channel_t *channel = connection->priv;
1913         if(!channel)
1914                 abort();
1915         node_t *n = channel->node;
1916         meshlink_handle_t *mesh = n->mesh;
1917         if(!channel->receive_cb)
1918                 return -1;
1919         else {
1920                 channel->receive_cb(mesh, channel, data, len);
1921                 return len;
1922         }
1923 }
1924
1925 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
1926         node_t *n = utcp_connection->utcp->priv;
1927         if(!n)
1928                 abort();
1929         meshlink_handle_t *mesh = n->mesh;
1930         if(!mesh->channel_accept_cb)
1931                 return;
1932         meshlink_channel_t *channel = xzalloc(sizeof *channel);
1933         channel->node = n;
1934         channel->c = utcp_connection;
1935         if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0))
1936                 utcp_accept(utcp_connection, channel_recv, channel);
1937         else
1938                 free(channel);
1939 }
1940
1941 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
1942         node_t *n = utcp->priv;
1943         meshlink_handle_t *mesh = n->mesh;
1944         char hex[len * 2 + 1];
1945         bin2hex(data, hex, len);
1946         logger(mesh, MESHLINK_WARNING, "channel_send(%p, %p, %zu): %s\n", utcp, data, len, hex);
1947         return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? len : -1;
1948 }
1949
1950 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
1951         channel->receive_cb = cb;
1952 }
1953
1954 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
1955         node_t *n = (node_t *)source;
1956         if(!n->utcp)
1957                 abort();
1958         char hex[len * 2 + 1];
1959         bin2hex(data, hex, len);
1960         logger(mesh, MESHLINK_WARNING, "channel_receive(%p, %p, %zu): %s\n", n->utcp, data, len, hex);
1961         utcp_recv(n->utcp, data, len);
1962 }
1963
1964 static void channel_poll(struct utcp_connection *connection, size_t len) {
1965         meshlink_channel_t *channel = connection->priv;
1966         if(!channel)
1967                 abort();
1968         node_t *n = channel->node;
1969         meshlink_handle_t *mesh = n->mesh;
1970         if(channel->poll_cb)
1971                 channel->poll_cb(mesh, channel, len);
1972 }
1973
1974 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
1975         channel->poll_cb = cb;
1976         utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
1977 }
1978
1979 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
1980         pthread_mutex_lock(&mesh->mesh_mutex);
1981         mesh->channel_accept_cb = cb;
1982         mesh->receive_cb = channel_receive;
1983         for splay_each(node_t, n, mesh->nodes) {
1984                 if(!n->utcp && n != mesh->self) {
1985                         logger(mesh, MESHLINK_WARNING, "utcp_init on node %s", n->name);
1986                         n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
1987                 }
1988         }
1989         pthread_mutex_unlock(&mesh->mesh_mutex);
1990 }
1991
1992 void meshlink_channel_init(meshlink_handle_t *mesh) {
1993 }
1994
1995 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) {
1996         logger(mesh, MESHLINK_WARNING, "meshlink_channel_open(%p, %s, %u, %p, %p, %zu)\n", mesh, node->name, port, cb, data, len);
1997         node_t *n = (node_t *)node;
1998         if(!n->utcp) {
1999                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2000                 mesh->receive_cb = channel_receive;
2001                 if(!n->utcp) {
2002                         meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2003                         return NULL;
2004                 }
2005         }
2006         meshlink_channel_t *channel = xzalloc(sizeof *channel);
2007         channel->node = n;
2008         channel->receive_cb = cb;
2009         channel->c = utcp_connect(n->utcp, port, channel_recv, channel);
2010         if(!channel->c) {
2011                 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2012                 free(channel);
2013                 return NULL;
2014         }
2015         return channel;
2016 }
2017
2018 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2019         utcp_shutdown(channel->c, direction);
2020 }
2021
2022 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2023         utcp_close(channel->c);
2024         free(channel);
2025 }
2026
2027 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2028         // TODO: locking.
2029         // Ideally we want to put the data into the UTCP connection's send buffer.
2030         // Then, preferrably only if there is room in the receiver window,
2031         // kick the meshlink thread to go send packets.
2032         return utcp_send(channel->c, data, len);
2033 }
2034
2035 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2036         if(n->status.reachable && mesh->channel_accept_cb && !n->utcp)
2037                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2038         if(mesh->node_status_cb)
2039                 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
2040 }
2041
2042 static void __attribute__((constructor)) meshlink_init(void) {
2043         crypto_init();
2044 }
2045
2046 static void __attribute__((destructor)) meshlink_exit(void) {
2047         crypto_exit();
2048 }
2049
2050 /// Device class traits
2051 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX +1] = {
2052         { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2053         { .min_connects = 3, .max_connects = 100, .edge_weight = 3 },   // DEV_CLASS_STATIONARY
2054         { .min_connects = 3, .max_connects = 3, .edge_weight = 6 },             // DEV_CLASS_PORTABLE
2055         { .min_connects = 1, .max_connects = 1, .edge_weight = 9 },             // DEV_CLASS_UNKNOWN
2056 };