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