]> git.meshlink.io Git - meshlink/blob - src/meshlink.c
Move the routing header out of the SPTPS payload.
[meshlink] / src / meshlink.c
1 /*
2     meshlink.c -- Implementation of the MeshLink API.
3     Copyright (C) 2014-2018 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 "sockaddr.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         {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
59         {"Name", VAR_SERVER},
60         /* Host configuration */
61         {"CanonicalAddress", VAR_HOST},
62         {"Address", VAR_HOST | VAR_MULTIPLE},
63         {"ECDSAPublicKey", VAR_HOST},
64         {"Port", VAR_HOST},
65         {NULL, 0}
66 };
67
68 static bool fcopy(FILE *out, const char *filename) {
69         FILE *in = fopen(filename, "r");
70
71         if(!in) {
72                 logger(NULL, MESHLINK_ERROR, "Could not open %s: %s\n", filename, strerror(errno));
73                 return false;
74         }
75
76         char buf[1024];
77         size_t len;
78
79         while((len = fread(buf, 1, sizeof(buf), in))) {
80                 fwrite(buf, len, 1, out);
81         }
82
83         fclose(in);
84         return true;
85 }
86
87 static int rstrip(char *value) {
88         int len = strlen(value);
89
90         while(len && strchr("\t\r\n ", value[len - 1])) {
91                 value[--len] = 0;
92         }
93
94         return len;
95 }
96
97 static void scan_for_canonical_address(const char *filename, char **hostname, char **port) {
98         char line[4096];
99
100         if(!filename || (*hostname && *port)) {
101                 return;
102         }
103
104         FILE *f = fopen(filename, "r");
105
106         if(!f) {
107                 return;
108         }
109
110         while(fgets(line, sizeof(line), f)) {
111                 if(!rstrip(line)) {
112                         continue;
113                 }
114
115                 char *p = line, *q;
116                 p += strcspn(p, "\t =");
117
118                 if(!*p) {
119                         continue;
120                 }
121
122                 q = p + strspn(p, "\t ");
123
124                 if(*q == '=') {
125                         q += 1 + strspn(q + 1, "\t ");
126                 }
127
128                 // q is now pointing to the hostname
129                 *p = 0;
130                 p = q + strcspn(q, "\t ");
131
132                 if(*p) {
133                         *p++ = 0;
134                 }
135
136                 p += strspn(p, "\t ");
137                 p[strcspn(p, "\t ")] = 0;
138                 // p is now pointing to the port, if present
139
140                 if(!*port && !strcasecmp(line, "Port")) {
141                         *port = xstrdup(q);
142                 } else if(!strcasecmp(line, "CanonicalAddress")) {
143                         *hostname = xstrdup(q);
144
145                         if(*p) {
146                                 free(*port);
147                                 *port = xstrdup(p);
148                         }
149                 }
150
151                 if(*hostname && *port) {
152                         break;
153                 }
154         }
155
156         fclose(f);
157 }
158
159 static bool is_valid_hostname(const char *hostname) {
160         if(!*hostname) {
161                 return false;
162         }
163
164         for(const char *p = hostname; *p; p++) {
165                 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
166                         return false;
167                 }
168         }
169
170         return true;
171 }
172
173 static bool is_valid_port(const char *port) {
174         if(!*port) {
175                 return false;
176         }
177
178         if(isdigit(*port)) {
179                 char *end;
180                 unsigned long int result = strtoul(port, &end, 10);
181                 return result && result < 65536 && !*end;
182         }
183
184         for(const char *p = port; *p; p++) {
185                 if(!(isalnum(*p) || *p == '-')) {
186                         return false;
187                 }
188         }
189
190         return true;
191 }
192
193 static void set_timeout(int sock, int timeout) {
194 #ifdef _WIN32
195         DWORD tv = timeout;
196 #else
197         struct timeval tv;
198         tv.tv_sec = timeout / 1000;
199         tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
200 #endif
201         setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
202         setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
203 }
204
205 // Find out what local address a socket would use if we connect to the given address.
206 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
207 // of both endpoints, but this will actually not send any UDP packet.
208 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen) {
209         struct addrinfo *rai = NULL;
210         const struct addrinfo hint = {
211                 .ai_family = AF_UNSPEC,
212                 .ai_socktype = SOCK_DGRAM,
213                 .ai_protocol = IPPROTO_UDP,
214         };
215
216         if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
217                 return false;
218         }
219
220         int sock = socket(rai->ai_family, rai->ai_socktype, rai->ai_protocol);
221
222         if(sock == -1) {
223                 freeaddrinfo(rai);
224                 return false;
225         }
226
227         if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
228                 freeaddrinfo(rai);
229                 return false;
230         }
231
232         freeaddrinfo(rai);
233
234         struct sockaddr_storage sn;
235         socklen_t sl = sizeof(sn);
236
237         if(getsockname(sock, (struct sockaddr *)&sn, &sl)) {
238                 return false;
239         }
240
241         if(getnameinfo((struct sockaddr *)&sn, sl, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
242                 return false;
243         }
244
245         return true;
246 }
247
248 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
249         return meshlink_get_external_address_for_family(mesh, AF_UNSPEC);
250 }
251
252 char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int family) {
253         char *hostname = NULL;
254
255         logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
256         struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
257         static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
258         char line[256];
259
260         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
261                 if(family != AF_UNSPEC && aip->ai_family != family) {
262                         continue;
263                 }
264
265                 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
266
267                 if(s >= 0) {
268                         set_timeout(s, 5000);
269
270                         if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
271                                 closesocket(s);
272                                 s = -1;
273                         }
274                 }
275
276                 if(s >= 0) {
277                         send(s, request, sizeof(request) - 1, 0);
278                         int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
279
280                         if(len > 0) {
281                                 line[len] = 0;
282
283                                 if(line[len - 1] == '\n') {
284                                         line[--len] = 0;
285                                 }
286
287                                 char *p = strrchr(line, '\n');
288
289                                 if(p && p[1]) {
290                                         hostname = xstrdup(p + 1);
291                                 }
292                         }
293
294                         closesocket(s);
295
296                         if(hostname) {
297                                 break;
298                         }
299                 }
300         }
301
302         if(ai) {
303                 freeaddrinfo(ai);
304         }
305
306         // Check that the hostname is reasonable
307         if(hostname && !is_valid_hostname(hostname)) {
308                 free(hostname);
309                 hostname = NULL;
310         }
311
312         if(!hostname) {
313                 meshlink_errno = MESHLINK_ERESOLV;
314         }
315
316         return hostname;
317 }
318
319 char *meshlink_get_local_address_for_family(meshlink_handle_t *mesh, int family) {
320         (void)mesh;
321
322         // Determine address of the local interface used for outgoing connections.
323         char localaddr[NI_MAXHOST];
324         bool success = false;
325
326         if(family == AF_INET) {
327                 success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr));
328         } else if(family == AF_INET6) {
329                 success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr));
330         }
331
332         if(!success) {
333                 meshlink_errno = MESHLINK_ENETWORK;
334                 return NULL;
335         }
336
337         return xstrdup(localaddr);
338 }
339
340 void remove_duplicate_hostnames(char *host[], char *port[], int n) {
341         for(int i = 0; i < n; i++) {
342                 if(!host[i]) {
343                         continue;
344                 }
345
346                 // Ignore duplicate hostnames
347                 bool found = false;
348
349                 for(int j = 0; j < i; j++) {
350                         if(!host[j]) {
351                                 continue;
352                         }
353
354                         if(strcmp(host[i], host[j])) {
355                                 continue;
356                         }
357
358                         if(strcmp(port[i], port[j])) {
359                                 continue;
360                         }
361
362                         found = true;
363                         break;
364                 }
365
366                 if(found) {
367                         free(host[i]);
368                         free(port[i]);
369                         host[i] = NULL;
370                         port[i] = NULL;
371                         continue;
372                 }
373         }
374 }
375
376 // This gets the hostname part for use in invitation URLs
377 static char *get_my_hostname(meshlink_handle_t *mesh, uint32_t flags) {
378         char *hostname[4] = {NULL};
379         char *port[4] = {NULL};
380         char *hostport = NULL;
381
382         if(!(flags & (MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC))) {
383                 flags |= MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC;
384         }
385
386         if(!(flags & (MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6))) {
387                 flags |= MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6;
388         }
389
390         fprintf(stderr, "flags = %u\n", flags);
391
392         // Add local addresses if requested
393         if(flags & MESHLINK_INVITE_LOCAL) {
394                 if(flags & MESHLINK_INVITE_IPV4) {
395                         hostname[0] = meshlink_get_local_address_for_family(mesh, AF_INET);
396                 }
397
398                 if(flags & MESHLINK_INVITE_IPV6) {
399                         hostname[1] = meshlink_get_local_address_for_family(mesh, AF_INET6);
400                 }
401         }
402
403         // Add public/canonical addresses if requested
404         if(flags & MESHLINK_INVITE_PUBLIC) {
405                 // Try the CanonicalAddress first
406                 char filename[PATH_MAX] = "";
407                 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
408                 scan_for_canonical_address(filename, &hostname[2], &port[2]);
409
410                 if(!hostname[2]) {
411                         if(flags & MESHLINK_INVITE_IPV4) {
412                                 hostname[2] = meshlink_get_external_address_for_family(mesh, AF_INET);
413                         }
414
415                         if(flags & MESHLINK_INVITE_IPV6) {
416                                 hostname[3] = meshlink_get_external_address_for_family(mesh, AF_INET6);
417                         }
418                 }
419         }
420
421         for(int i = 0; i < 4; i++) {
422                 // Ensure we always have a port number
423                 if(hostname[i] && !port[i]) {
424                         port[i] = xstrdup(mesh->myport);
425                 }
426         }
427
428         remove_duplicate_hostnames(hostname, port, 4);
429
430         if(!(flags & MESHLINK_INVITE_NUMERIC)) {
431                 for(int i = 0; i < 4; i++) {
432                         if(!hostname[i]) {
433                                 continue;
434                         }
435
436                         // Convert what we have to a sockaddr
437                         struct addrinfo *ai_in, *ai_out;
438                         struct addrinfo hint = {
439                                 .ai_family = AF_UNSPEC,
440                                 .ai_flags = AI_NUMERICSERV,
441                                 .ai_socktype = SOCK_STREAM,
442                         };
443                         int err = getaddrinfo(hostname[i], port[i], &hint, &ai_in);
444
445                         if(err || !ai_in) {
446                                 continue;
447                         }
448
449                         // Convert it to a hostname
450                         char resolved_host[NI_MAXHOST];
451                         char resolved_port[NI_MAXSERV];
452                         err = getnameinfo(ai_in->ai_addr, ai_in->ai_addrlen, resolved_host, sizeof resolved_host, resolved_port, sizeof resolved_port, NI_NUMERICSERV);
453
454                         if(err) {
455                                 freeaddrinfo(ai_in);
456                                 continue;
457                         }
458
459                         // Convert the hostname back to a sockaddr
460                         hint.ai_family = ai_in->ai_family;
461                         err = getaddrinfo(resolved_host, resolved_port, &hint, &ai_out);
462
463                         if(err || !ai_out) {
464                                 freeaddrinfo(ai_in);
465                                 continue;
466                         }
467
468                         // Check if it's still the same sockaddr
469                         if(ai_in->ai_addrlen != ai_out->ai_addrlen || memcmp(ai_in->ai_addr, ai_out->ai_addr, ai_in->ai_addrlen)) {
470                                 freeaddrinfo(ai_in);
471                                 freeaddrinfo(ai_out);
472                                 continue;
473                         }
474
475                         // Yes: replace the hostname with the resolved one
476                         free(hostname[i]);
477                         hostname[i] = xstrdup(resolved_host);
478
479                         freeaddrinfo(ai_in);
480                         freeaddrinfo(ai_out);
481                 }
482         }
483
484         // Remove duplicates again, since IPv4 and IPv6 addresses might map to the same hostname
485         remove_duplicate_hostnames(hostname, port, 4);
486
487         // Concatenate all unique address to the hostport string
488         for(int i = 0; i < 4; i++) {
489                 if(!hostname[i]) {
490                         continue;
491                 }
492
493                 // Ensure we have the same addresses in our own host config file.
494                 char *tmphostport;
495                 xasprintf(&tmphostport, "%s %s", hostname[i], port[i]);
496                 append_config_file(mesh, mesh->self->name, "Address", tmphostport);
497                 free(tmphostport);
498
499                 // Append the address to the hostport string
500                 char *newhostport;
501                 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i]);
502                 free(hostport);
503                 hostport = newhostport;
504
505                 free(hostname[i]);
506                 free(port[i]);
507         }
508
509         return hostport;
510 }
511
512 static char *get_line(const char **data) {
513         if(!data || !*data) {
514                 return NULL;
515         }
516
517         if(! **data) {
518                 *data = NULL;
519                 return NULL;
520         }
521
522         static char line[1024];
523         const char *end = strchr(*data, '\n');
524         size_t len = end ? (size_t)(end - *data) : strlen(*data);
525
526         if(len >= sizeof(line)) {
527                 logger(NULL, MESHLINK_ERROR, "Maximum line length exceeded!\n");
528                 return NULL;
529         }
530
531         if(len && !isprint(**data)) {
532                 abort();
533         }
534
535         memcpy(line, *data, len);
536         line[len] = 0;
537
538         if(end) {
539                 *data = end + 1;
540         } else {
541                 *data = NULL;
542         }
543
544         return line;
545 }
546
547 static char *get_value(const char *data, const char *var) {
548         char *line = get_line(&data);
549
550         if(!line) {
551                 return NULL;
552         }
553
554         char *sep = line + strcspn(line, " \t=");
555         char *val = sep + strspn(sep, " \t");
556
557         if(*val == '=') {
558                 val += 1 + strspn(val + 1, " \t");
559         }
560
561         *sep = 0;
562
563         if(strcasecmp(line, var)) {
564                 return NULL;
565         }
566
567         return val;
568 }
569
570 static bool try_bind(int port) {
571         struct addrinfo *ai = NULL;
572         struct addrinfo hint = {
573                 .ai_flags = AI_PASSIVE,
574                 .ai_family = AF_UNSPEC,
575                 .ai_socktype = SOCK_STREAM,
576                 .ai_protocol = IPPROTO_TCP,
577         };
578
579         char portstr[16];
580         snprintf(portstr, sizeof(portstr), "%d", port);
581
582         if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
583                 return false;
584         }
585
586         while(ai) {
587                 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
588
589                 if(!fd) {
590                         freeaddrinfo(ai);
591                         return false;
592                 }
593
594                 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
595                 closesocket(fd);
596
597                 if(result) {
598                         freeaddrinfo(ai);
599                         return false;
600                 }
601
602                 ai = ai->ai_next;
603         }
604
605         freeaddrinfo(ai);
606         return true;
607 }
608
609 int check_port(meshlink_handle_t *mesh) {
610         for(int i = 0; i < 1000; i++) {
611                 int port = 0x1000 + (rand() & 0x7fff);
612
613                 if(try_bind(port)) {
614                         char filename[PATH_MAX];
615                         snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
616                         FILE *f = fopen(filename, "a");
617
618                         if(!f) {
619                                 meshlink_errno = MESHLINK_ESTORAGE;
620                                 logger(mesh, MESHLINK_DEBUG, "Could not store Port.\n");
621                                 return 0;
622                         }
623
624                         fprintf(f, "Port = %d\n", port);
625                         fclose(f);
626                         return port;
627                 }
628         }
629
630         meshlink_errno = MESHLINK_ENETWORK;
631         logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
632         return 0;
633 }
634
635 static void deltree(const char *dirname) {
636         DIR *d = opendir(dirname);
637
638         if(d) {
639                 struct dirent *ent;
640
641                 while((ent = readdir(d))) {
642                         if(ent->d_name[0] == '.') {
643                                 continue;
644                         }
645
646                         char filename[PATH_MAX];
647                         snprintf(filename, sizeof(filename), "%s" SLASH "%s", dirname, ent->d_name);
648
649                         if(unlink(filename)) {
650                                 deltree(filename);
651                         }
652                 }
653
654                 closedir(d);
655         }
656
657         rmdir(dirname);
658 }
659
660 static bool finalize_join(meshlink_handle_t *mesh) {
661         char *name = xstrdup(get_value(mesh->data, "Name"));
662
663         if(!name) {
664                 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
665                 return false;
666         }
667
668         if(!check_id(name)) {
669                 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
670                 return false;
671         }
672
673         char filename[PATH_MAX];
674         snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
675
676         FILE *f = fopen(filename, "w");
677
678         if(!f) {
679                 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
680                 return false;
681         }
682
683         fprintf(f, "Name = %s\n", name);
684
685         // Wipe all old host config files and invitations
686         snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
687         deltree(filename);
688
689         if(mkdir(filename, 0777) && errno != EEXIST) {
690                 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
691                 return false;
692         }
693
694         snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
695         deltree(filename);
696
697         // Create a new host config file for ourself
698         snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
699         FILE *fh = fopen(filename, "w");
700
701         if(!fh) {
702                 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
703                 fclose(f);
704                 return false;
705         }
706
707         // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
708         // Other chunks go unfiltered to their respective host config files
709         const char *p = mesh->data;
710         char *l, *value;
711
712         while((l = get_line(&p))) {
713                 // Ignore comments
714                 if(*l == '#') {
715                         continue;
716                 }
717
718                 // Split line into variable and value
719                 int len = strcspn(l, "\t =");
720                 value = l + len;
721                 value += strspn(value, "\t ");
722
723                 if(*value == '=') {
724                         value++;
725                         value += strspn(value, "\t ");
726                 }
727
728                 l[len] = 0;
729
730                 // Is it a Name?
731                 if(!strcasecmp(l, "Name"))
732                         if(strcmp(value, name)) {
733                                 break;
734                         } else {
735                                 continue;
736                         } else if(!strcasecmp(l, "NetName")) {
737                         continue;
738                 }
739
740                 // Check the list of known variables
741                 bool found = false;
742                 int i;
743
744                 for(i = 0; variables[i].name; i++) {
745                         if(strcasecmp(l, variables[i].name)) {
746                                 continue;
747                         }
748
749                         found = true;
750                         break;
751                 }
752
753                 // Ignore unknown and unsafe variables
754                 if(!found) {
755                         logger(mesh, MESHLINK_DEBUG, "Ignoring unknown variable '%s' in invitation.\n", l);
756                         continue;
757                 } else if(!(variables[i].type & VAR_SAFE)) {
758                         logger(mesh, MESHLINK_DEBUG, "Ignoring unsafe variable '%s' in invitation.\n", l);
759                         continue;
760                 }
761
762                 // Copy the safe variable to the right config file
763                 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
764         }
765
766         fclose(f);
767
768         while(l && !strcasecmp(l, "Name")) {
769                 if(!check_id(value)) {
770                         logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation.\n");
771                         return false;
772                 }
773
774                 if(!strcmp(value, name)) {
775                         logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
776                         return false;
777                 }
778
779                 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
780                 f = fopen(filename, "w");
781
782                 if(!f) {
783                         logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
784                         return false;
785                 }
786
787                 while((l = get_line(&p))) {
788                         if(!strcmp(l, "#---------------------------------------------------------------#")) {
789                                 continue;
790                         }
791
792                         int len = strcspn(l, "\t =");
793
794                         if(len == 4 && !strncasecmp(l, "Name", 4)) {
795                                 value = l + len;
796                                 value += strspn(value, "\t ");
797
798                                 if(*value == '=') {
799                                         value++;
800                                         value += strspn(value, "\t ");
801                                 }
802
803                                 l[len] = 0;
804                                 break;
805                         }
806
807                         fputs(l, f);
808                         fputc('\n', f);
809                 }
810
811                 fclose(f);
812         }
813
814         char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
815
816         if(!b64key) {
817                 fclose(fh);
818                 return false;
819         }
820
821         fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
822         fprintf(fh, "Port = %s\n", mesh->myport);
823
824         fclose(fh);
825
826         sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
827         free(b64key);
828
829         free(mesh->name);
830         free(mesh->self->name);
831         free(mesh->self->connection->name);
832         mesh->name = xstrdup(name);
833         mesh->self->name = xstrdup(name);
834         mesh->self->connection->name = name;
835
836         logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
837
838         load_all_nodes(mesh);
839
840         return true;
841 }
842
843 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
844         (void)type;
845         meshlink_handle_t *mesh = handle;
846         const char *ptr = data;
847
848         while(len) {
849                 int result = send(mesh->sock, ptr, len, 0);
850
851                 if(result == -1 && errno == EINTR) {
852                         continue;
853                 } else if(result <= 0) {
854                         return false;
855                 }
856
857                 ptr += result;
858                 len -= result;
859         }
860
861         return true;
862 }
863
864 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
865         meshlink_handle_t *mesh = handle;
866
867         switch(type) {
868         case SPTPS_HANDSHAKE:
869                 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof(mesh)->cookie);
870
871         case 0:
872                 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
873                 memcpy(mesh->data + mesh->thedatalen, msg, len);
874                 mesh->thedatalen += len;
875                 mesh->data[mesh->thedatalen] = 0;
876                 break;
877
878         case 1:
879                 mesh->thedatalen = 0;
880                 return finalize_join(mesh);
881
882         case 2:
883                 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
884                 shutdown(mesh->sock, SHUT_RDWR);
885                 mesh->success = true;
886                 break;
887
888         default:
889                 return false;
890         }
891
892         return true;
893 }
894
895 static bool recvline(meshlink_handle_t *mesh, size_t len) {
896         char *newline = NULL;
897
898         if(!mesh->sock) {
899                 abort();
900         }
901
902         while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
903                 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
904
905                 if(result == -1 && errno == EINTR) {
906                         continue;
907                 } else if(result <= 0) {
908                         return false;
909                 }
910
911                 mesh->blen += result;
912         }
913
914         if((size_t)(newline - mesh->buffer) >= len) {
915                 return false;
916         }
917
918         len = newline - mesh->buffer;
919
920         memcpy(mesh->line, mesh->buffer, len);
921         mesh->line[len] = 0;
922         memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
923         mesh->blen -= len + 1;
924
925         return true;
926 }
927 static bool sendline(int fd, char *format, ...) {
928         static char buffer[4096];
929         char *p = buffer;
930         int blen = 0;
931         va_list ap;
932
933         va_start(ap, format);
934         blen = vsnprintf(buffer, sizeof(buffer), format, ap);
935         va_end(ap);
936
937         if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
938                 return false;
939         }
940
941         buffer[blen] = '\n';
942         blen++;
943
944         while(blen) {
945                 int result = send(fd, p, blen, MSG_NOSIGNAL);
946
947                 if(result == -1 && errno == EINTR) {
948                         continue;
949                 } else if(result <= 0) {
950                         return false;
951                 }
952
953                 p += result;
954                 blen -= result;
955         }
956
957         return true;
958 }
959
960 static const char *errstr[] = {
961         [MESHLINK_OK] = "No error",
962         [MESHLINK_EINVAL] = "Invalid argument",
963         [MESHLINK_ENOMEM] = "Out of memory",
964         [MESHLINK_ENOENT] = "No such node",
965         [MESHLINK_EEXIST] = "Node already exists",
966         [MESHLINK_EINTERNAL] = "Internal error",
967         [MESHLINK_ERESOLV] = "Could not resolve hostname",
968         [MESHLINK_ESTORAGE] = "Storage error",
969         [MESHLINK_ENETWORK] = "Network error",
970         [MESHLINK_EPEER] = "Error communicating with peer",
971         [MESHLINK_ENOTSUP] = "Operation not supported",
972         [MESHLINK_EBUSY] = "MeshLink instance already in use",
973 };
974
975 const char *meshlink_strerror(meshlink_errno_t err) {
976         if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
977                 return "Invalid error code";
978         }
979
980         return errstr[err];
981 }
982
983 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
984         ecdsa_t *key;
985         FILE *f;
986         char pubname[PATH_MAX], privname[PATH_MAX];
987
988         logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
989
990         if(!(key = ecdsa_generate())) {
991                 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
992                 meshlink_errno = MESHLINK_EINTERNAL;
993                 return false;
994         } else {
995                 logger(mesh, MESHLINK_DEBUG, "Done.\n");
996         }
997
998         if(snprintf(privname, sizeof(privname), "%s" SLASH "ecdsa_key.priv", mesh->confbase) >= PATH_MAX) {
999                 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "ecdsa_key.priv\n", mesh->confbase);
1000                 meshlink_errno = MESHLINK_ESTORAGE;
1001                 return false;
1002         }
1003
1004         f = fopen(privname, "wb");
1005
1006         if(!f) {
1007                 meshlink_errno = MESHLINK_ESTORAGE;
1008                 return false;
1009         }
1010
1011 #ifdef HAVE_FCHMOD
1012         fchmod(fileno(f), 0600);
1013 #endif
1014
1015         if(!ecdsa_write_pem_private_key(key, f)) {
1016                 logger(mesh, MESHLINK_DEBUG, "Error writing private key!\n");
1017                 ecdsa_free(key);
1018                 fclose(f);
1019                 meshlink_errno = MESHLINK_EINTERNAL;
1020                 return false;
1021         }
1022
1023         fclose(f);
1024
1025         snprintf(pubname, sizeof(pubname), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
1026         f = fopen(pubname, "a");
1027
1028         if(!f) {
1029                 meshlink_errno = MESHLINK_ESTORAGE;
1030                 return false;
1031         }
1032
1033         char *pubkey = ecdsa_get_base64_public_key(key);
1034         fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
1035         free(pubkey);
1036
1037         fclose(f);
1038         ecdsa_free(key);
1039
1040         return true;
1041 }
1042
1043 static struct timeval idle(event_loop_t *loop, void *data) {
1044         (void)loop;
1045         meshlink_handle_t *mesh = data;
1046         struct timeval t, tmin = {3600, 0};
1047
1048         for splay_each(node_t, n, mesh->nodes) {
1049                 if(!n->utcp) {
1050                         continue;
1051                 }
1052
1053                 t = utcp_timeout(n->utcp);
1054
1055                 if(timercmp(&t, &tmin, <)) {
1056                         tmin = t;
1057                 }
1058         }
1059
1060         return tmin;
1061 }
1062
1063 // Get our local address(es) by simulating connecting to an Internet host.
1064 static void add_local_addresses(meshlink_handle_t *mesh) {
1065         char host[NI_MAXHOST];
1066         char entry[MAX_STRING_SIZE];
1067
1068         // IPv4 example.org
1069
1070         if(getlocaladdrname("93.184.216.34", host, sizeof(host))) {
1071                 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
1072                 append_config_file(mesh, mesh->name, "Address", entry);
1073         }
1074
1075         // IPv6 example.org
1076
1077         if(getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", host, sizeof(host))) {
1078                 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
1079                 append_config_file(mesh, mesh->name, "Address", entry);
1080         }
1081 }
1082
1083 static bool meshlink_setup(meshlink_handle_t *mesh) {
1084         if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
1085                 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
1086                 meshlink_errno = MESHLINK_ESTORAGE;
1087                 return false;
1088         }
1089
1090         char filename[PATH_MAX];
1091         snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
1092
1093         if(mkdir(filename, 0777) && errno != EEXIST) {
1094                 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1095                 meshlink_errno = MESHLINK_ESTORAGE;
1096                 return false;
1097         }
1098
1099         snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
1100
1101         if(!access(filename, F_OK)) {
1102                 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
1103                 meshlink_errno = MESHLINK_EEXIST;
1104                 return false;
1105         }
1106
1107         FILE *f = fopen(filename, "w");
1108
1109         if(!f) {
1110                 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
1111                 meshlink_errno = MESHLINK_ESTORAGE;
1112                 return false;
1113         }
1114
1115         fprintf(f, "Name = %s\n", mesh->name);
1116         fclose(f);
1117
1118         if(!ecdsa_keygen(mesh)) {
1119                 meshlink_errno = MESHLINK_EINTERNAL;
1120                 unlink(filename);
1121                 return false;
1122         }
1123
1124         if(check_port(mesh) == 0) {
1125                 meshlink_errno = MESHLINK_ENETWORK;
1126                 unlink(filename);
1127                 return false;
1128         }
1129
1130         return true;
1131 }
1132
1133 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1134         // Validate arguments provided by the application
1135         bool usingname = false;
1136
1137         logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1138
1139         if(!confbase || !*confbase) {
1140                 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1141                 meshlink_errno = MESHLINK_EINVAL;
1142                 return NULL;
1143         }
1144
1145         if(!appname || !*appname) {
1146                 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1147                 meshlink_errno = MESHLINK_EINVAL;
1148                 return NULL;
1149         }
1150
1151         if(strchr(appname, ' ')) {
1152                 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1153                 meshlink_errno = MESHLINK_EINVAL;
1154                 return NULL;
1155         }
1156
1157         if(!name || !*name) {
1158                 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1159                 //return NULL;
1160         } else { //check name only if there is a name != NULL
1161
1162                 if(!check_id(name)) {
1163                         logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1164                         meshlink_errno = MESHLINK_EINVAL;
1165                         return NULL;
1166                 } else {
1167                         usingname = true;
1168                 }
1169         }
1170
1171         if((int)devclass < 0 || devclass > _DEV_CLASS_MAX) {
1172                 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1173                 meshlink_errno = MESHLINK_EINVAL;
1174                 return NULL;
1175         }
1176
1177         meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1178         mesh->confbase = xstrdup(confbase);
1179         mesh->appname = xstrdup(appname);
1180         mesh->devclass = devclass;
1181         mesh->discovery = true;
1182         mesh->invitation_timeout = 604800; // 1 week
1183
1184         if(usingname) {
1185                 mesh->name = xstrdup(name);
1186         }
1187
1188         // initialize mutex
1189         pthread_mutexattr_t attr;
1190         pthread_mutexattr_init(&attr);
1191         pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1192         pthread_mutex_init(&(mesh->mesh_mutex), &attr);
1193
1194         mesh->threadstarted = false;
1195         event_loop_init(&mesh->loop);
1196         mesh->loop.data = mesh;
1197
1198         meshlink_queue_init(&mesh->outpacketqueue);
1199
1200         // Check whether meshlink.conf already exists
1201
1202         char filename[PATH_MAX];
1203         snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1204
1205         if(access(filename, R_OK)) {
1206                 if(errno == ENOENT) {
1207                         // If not, create it
1208                         if(!meshlink_setup(mesh)) {
1209                                 // meshlink_errno is set by meshlink_setup()
1210                                 return NULL;
1211                         }
1212                 } else {
1213                         logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
1214                         meshlink_close(mesh);
1215                         meshlink_errno = MESHLINK_ESTORAGE;
1216                         return NULL;
1217                 }
1218         }
1219
1220         // Open the configuration file and lock it
1221
1222         mesh->conffile = fopen(filename, "r");
1223
1224         if(!mesh->conffile) {
1225                 logger(NULL, MESHLINK_ERROR, "Cannot not open %s: %s\n", filename, strerror(errno));
1226                 meshlink_close(mesh);
1227                 meshlink_errno = MESHLINK_ESTORAGE;
1228                 return NULL;
1229         }
1230
1231 #ifdef FD_CLOEXEC
1232         fcntl(fileno(mesh->conffile), F_SETFD, FD_CLOEXEC);
1233 #endif
1234
1235 #ifdef HAVE_MINGW
1236         // TODO: use _locking()?
1237 #else
1238
1239         if(flock(fileno(mesh->conffile), LOCK_EX | LOCK_NB) != 0) {
1240                 logger(NULL, MESHLINK_ERROR, "Cannot lock %s: %s\n", filename, strerror(errno));
1241                 meshlink_close(mesh);
1242                 meshlink_errno = MESHLINK_EBUSY;
1243                 return NULL;
1244         }
1245
1246 #endif
1247
1248         // Read the configuration
1249
1250         init_configuration(&mesh->config);
1251
1252         if(!read_server_config(mesh)) {
1253                 meshlink_close(mesh);
1254                 meshlink_errno = MESHLINK_ESTORAGE;
1255                 return NULL;
1256         };
1257
1258 #ifdef HAVE_MINGW
1259         struct WSAData wsa_state;
1260
1261         WSAStartup(MAKEWORD(2, 2), &wsa_state);
1262
1263 #endif
1264
1265         // Setup up everything
1266         // TODO: we should not open listening sockets yet
1267
1268         if(!setup_network(mesh)) {
1269                 meshlink_close(mesh);
1270                 meshlink_errno = MESHLINK_ENETWORK;
1271                 return NULL;
1272         }
1273
1274         add_local_addresses(mesh);
1275
1276         idle_set(&mesh->loop, idle, mesh);
1277
1278         logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1279         return mesh;
1280 }
1281
1282 static void *meshlink_main_loop(void *arg) {
1283         meshlink_handle_t *mesh = arg;
1284
1285         pthread_mutex_lock(&(mesh->mesh_mutex));
1286
1287         try_outgoing_connections(mesh);
1288
1289         logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1290         main_loop(mesh);
1291         logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1292
1293         pthread_mutex_unlock(&(mesh->mesh_mutex));
1294         return NULL;
1295 }
1296
1297 bool meshlink_start(meshlink_handle_t *mesh) {
1298         if(!mesh) {
1299                 meshlink_errno = MESHLINK_EINVAL;
1300                 return false;
1301         }
1302
1303         logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1304
1305         pthread_mutex_lock(&(mesh->mesh_mutex));
1306
1307         if(mesh->threadstarted) {
1308                 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1309                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1310                 return true;
1311         }
1312
1313         if(mesh->listen_socket[0].tcp.fd < 0) {
1314                 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1315                 meshlink_errno = MESHLINK_ENETWORK;
1316                 return false;
1317         }
1318
1319         mesh->thedatalen = 0;
1320
1321         // TODO: open listening sockets first
1322
1323         //Check that a valid name is set
1324         if(!mesh->name) {
1325                 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1326                 meshlink_errno = MESHLINK_EINVAL;
1327                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1328                 return false;
1329         }
1330
1331         // Start the main thread
1332
1333         event_loop_start(&mesh->loop);
1334
1335         if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1336                 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1337                 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1338                 meshlink_errno = MESHLINK_EINTERNAL;
1339                 event_loop_stop(&mesh->loop);
1340                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1341                 return false;
1342         }
1343
1344         mesh->threadstarted = true;
1345
1346 #if HAVE_CATTA
1347
1348         if(mesh->discovery) {
1349                 discovery_start(mesh);
1350         }
1351
1352 #endif
1353
1354         pthread_mutex_unlock(&(mesh->mesh_mutex));
1355         return true;
1356 }
1357
1358 void meshlink_stop(meshlink_handle_t *mesh) {
1359         if(!mesh) {
1360                 meshlink_errno = MESHLINK_EINVAL;
1361                 return;
1362         }
1363
1364         pthread_mutex_lock(&(mesh->mesh_mutex));
1365         logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1366
1367 #if HAVE_CATTA
1368
1369         // Stop discovery
1370         if(mesh->discovery) {
1371                 discovery_stop(mesh);
1372         }
1373
1374 #endif
1375
1376         // Shut down the main thread
1377         event_loop_stop(&mesh->loop);
1378
1379         // Send ourselves a UDP packet to kick the event loop
1380         for(int i = 0; i < mesh->listen_sockets; i++) {
1381                 sockaddr_t sa;
1382                 socklen_t salen = sizeof(sa.sa);
1383
1384                 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1385                         logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1386                         continue;
1387                 }
1388
1389                 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1390                         logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1391                 }
1392         }
1393
1394         if(mesh->threadstarted) {
1395                 // Wait for the main thread to finish
1396                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1397                 pthread_join(mesh->thread, NULL);
1398                 pthread_mutex_lock(&(mesh->mesh_mutex));
1399
1400                 mesh->threadstarted = false;
1401         }
1402
1403         // Close all metaconnections
1404         if(mesh->connections) {
1405                 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1406                         next = node->next;
1407                         connection_t *c = node->data;
1408                         c->outgoing = NULL;
1409                         terminate_connection(mesh, c, false);
1410                 }
1411         }
1412
1413         if(mesh->outgoings) {
1414                 list_delete_list(mesh->outgoings);
1415                 mesh->outgoings = NULL;
1416         }
1417
1418         pthread_mutex_unlock(&(mesh->mesh_mutex));
1419 }
1420
1421 void meshlink_close(meshlink_handle_t *mesh) {
1422         if(!mesh || !mesh->confbase) {
1423                 meshlink_errno = MESHLINK_EINVAL;
1424                 return;
1425         }
1426
1427         // stop can be called even if mesh has not been started
1428         meshlink_stop(mesh);
1429
1430         // lock is not released after this
1431         pthread_mutex_lock(&(mesh->mesh_mutex));
1432
1433         // Close and free all resources used.
1434
1435         close_network_connections(mesh);
1436
1437         logger(mesh, MESHLINK_INFO, "Terminating");
1438
1439         exit_configuration(&mesh->config);
1440         event_loop_exit(&mesh->loop);
1441
1442 #ifdef HAVE_MINGW
1443
1444         if(mesh->confbase) {
1445                 WSACleanup();
1446         }
1447
1448 #endif
1449
1450         ecdsa_free(mesh->invitation_key);
1451
1452         free(mesh->name);
1453         free(mesh->appname);
1454         free(mesh->confbase);
1455         pthread_mutex_destroy(&(mesh->mesh_mutex));
1456
1457         if(mesh->conffile) {
1458                 fclose(mesh->conffile);
1459         }
1460
1461         memset(mesh, 0, sizeof(*mesh));
1462
1463         free(mesh);
1464 }
1465
1466 bool meshlink_destroy(const char *confbase) {
1467         if(!confbase) {
1468                 meshlink_errno = MESHLINK_EINVAL;
1469                 return false;
1470         }
1471
1472         char filename[PATH_MAX];
1473         snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1474
1475         if(unlink(filename)) {
1476                 if(errno == ENOENT) {
1477                         meshlink_errno = MESHLINK_ENOENT;
1478                         return false;
1479                 } else {
1480                         logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", filename, strerror(errno));
1481                         meshlink_errno = MESHLINK_ESTORAGE;
1482                         return false;
1483                 }
1484         }
1485
1486         deltree(confbase);
1487
1488         return true;
1489 }
1490
1491 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1492         if(!mesh) {
1493                 meshlink_errno = MESHLINK_EINVAL;
1494                 return;
1495         }
1496
1497         pthread_mutex_lock(&(mesh->mesh_mutex));
1498         mesh->receive_cb = cb;
1499         pthread_mutex_unlock(&(mesh->mesh_mutex));
1500 }
1501
1502 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1503         if(!mesh) {
1504                 meshlink_errno = MESHLINK_EINVAL;
1505                 return;
1506         }
1507
1508         pthread_mutex_lock(&(mesh->mesh_mutex));
1509         mesh->node_status_cb = cb;
1510         pthread_mutex_unlock(&(mesh->mesh_mutex));
1511 }
1512
1513 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1514         if(!mesh) {
1515                 meshlink_errno = MESHLINK_EINVAL;
1516                 return;
1517         }
1518
1519         pthread_mutex_lock(&(mesh->mesh_mutex));
1520         mesh->node_duplicate_cb = cb;
1521         pthread_mutex_unlock(&(mesh->mesh_mutex));
1522 }
1523
1524 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1525         if(mesh) {
1526                 pthread_mutex_lock(&(mesh->mesh_mutex));
1527                 mesh->log_cb = cb;
1528                 mesh->log_level = cb ? level : 0;
1529                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1530         } else {
1531                 global_log_cb = cb;
1532                 global_log_level = cb ? level : 0;
1533         }
1534 }
1535
1536 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1537         // Validate arguments
1538         if(!mesh || !destination || len >= MAXSIZE) {
1539                 meshlink_errno = MESHLINK_EINVAL;
1540                 return false;
1541         }
1542
1543         if(!len) {
1544                 return true;
1545         }
1546
1547         if(!data) {
1548                 meshlink_errno = MESHLINK_EINVAL;
1549                 return false;
1550         }
1551
1552         // Prepare the packet
1553         vpn_packet_t *packet = malloc(sizeof(*packet));
1554
1555         if(!packet) {
1556                 meshlink_errno = MESHLINK_ENOMEM;
1557                 return false;
1558         }
1559
1560         packet->probe = false;
1561         packet->tcp = false;
1562         packet->len = len;
1563         packet->src = mesh->self->id;
1564         packet->dst = ((node_t *)destination)->id;
1565
1566         memcpy(packet->data, data, len);
1567
1568         // Queue it
1569         if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1570                 free(packet);
1571                 meshlink_errno = MESHLINK_ENOMEM;
1572                 return false;
1573         }
1574
1575         // Notify event loop
1576         signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1577
1578         return true;
1579 }
1580
1581 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1582         (void)loop;
1583         vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1584
1585         if(!packet) {
1586                 return;
1587         }
1588
1589         mesh->self->in_packets++;
1590         mesh->self->in_bytes += packet->len;
1591         node_t *dest = lookup_node_id(mesh, packet->dst);
1592
1593         if(dest) {
1594                 send_packet(mesh, dest, packet);
1595         }
1596
1597         free(packet);
1598 }
1599
1600 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1601         if(!mesh || !destination) {
1602                 meshlink_errno = MESHLINK_EINVAL;
1603                 return -1;
1604         }
1605
1606         pthread_mutex_lock(&(mesh->mesh_mutex));
1607
1608         node_t *n = (node_t *)destination;
1609
1610         if(!n->status.reachable) {
1611                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1612                 return 0;
1613
1614         } else if(n->mtuprobes > 30 && n->minmtu) {
1615                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1616                 return n->minmtu;
1617         } else {
1618                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1619                 return MTU;
1620         }
1621 }
1622
1623 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1624         if(!mesh || !node) {
1625                 meshlink_errno = MESHLINK_EINVAL;
1626                 return NULL;
1627         }
1628
1629         pthread_mutex_lock(&(mesh->mesh_mutex));
1630
1631         node_t *n = (node_t *)node;
1632
1633         if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1634                 meshlink_errno = MESHLINK_EINTERNAL;
1635                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1636                 return false;
1637         }
1638
1639         char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1640
1641         if(!fingerprint) {
1642                 meshlink_errno = MESHLINK_EINTERNAL;
1643         }
1644
1645         pthread_mutex_unlock(&(mesh->mesh_mutex));
1646         return fingerprint;
1647 }
1648
1649 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1650         if(!mesh) {
1651                 meshlink_errno = MESHLINK_EINVAL;
1652                 return NULL;
1653         }
1654
1655         return (meshlink_node_t *)mesh->self;
1656 }
1657
1658 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1659         if(!mesh || !name) {
1660                 meshlink_errno = MESHLINK_EINVAL;
1661                 return NULL;
1662         }
1663
1664         meshlink_node_t *node = NULL;
1665
1666         pthread_mutex_lock(&(mesh->mesh_mutex));
1667         node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1668         pthread_mutex_unlock(&(mesh->mesh_mutex));
1669         return node;
1670 }
1671
1672 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1673         if(!mesh || !nmemb || (*nmemb && !nodes)) {
1674                 meshlink_errno = MESHLINK_EINVAL;
1675                 return NULL;
1676         }
1677
1678         meshlink_node_t **result;
1679
1680         //lock mesh->nodes
1681         pthread_mutex_lock(&(mesh->mesh_mutex));
1682
1683         *nmemb = mesh->nodes->count;
1684         result = realloc(nodes, *nmemb * sizeof(*nodes));
1685
1686         if(result) {
1687                 meshlink_node_t **p = result;
1688
1689                 for splay_each(node_t, n, mesh->nodes) {
1690                         *p++ = (meshlink_node_t *)n;
1691                 }
1692         } else {
1693                 *nmemb = 0;
1694                 free(nodes);
1695                 meshlink_errno = MESHLINK_ENOMEM;
1696         }
1697
1698         pthread_mutex_unlock(&(mesh->mesh_mutex));
1699
1700         return result;
1701 }
1702
1703 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1704         if(!mesh || !data || !len || !signature || !siglen) {
1705                 meshlink_errno = MESHLINK_EINVAL;
1706                 return false;
1707         }
1708
1709         if(*siglen < MESHLINK_SIGLEN) {
1710                 meshlink_errno = MESHLINK_EINVAL;
1711                 return false;
1712         }
1713
1714         pthread_mutex_lock(&(mesh->mesh_mutex));
1715
1716         if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1717                 meshlink_errno = MESHLINK_EINTERNAL;
1718                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1719                 return false;
1720         }
1721
1722         *siglen = MESHLINK_SIGLEN;
1723         pthread_mutex_unlock(&(mesh->mesh_mutex));
1724         return true;
1725 }
1726
1727 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1728         if(!mesh || !data || !len || !signature) {
1729                 meshlink_errno = MESHLINK_EINVAL;
1730                 return false;
1731         }
1732
1733         if(siglen != MESHLINK_SIGLEN) {
1734                 meshlink_errno = MESHLINK_EINVAL;
1735                 return false;
1736         }
1737
1738         pthread_mutex_lock(&(mesh->mesh_mutex));
1739
1740         bool rval = false;
1741
1742         struct node_t *n = (struct node_t *)source;
1743         node_read_ecdsa_public_key(mesh, n);
1744
1745         if(!n->ecdsa) {
1746                 meshlink_errno = MESHLINK_EINTERNAL;
1747                 rval = false;
1748         } else {
1749                 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1750         }
1751
1752         pthread_mutex_unlock(&(mesh->mesh_mutex));
1753         return rval;
1754 }
1755
1756 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1757         char filename[PATH_MAX];
1758
1759         pthread_mutex_lock(&(mesh->mesh_mutex));
1760
1761         snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
1762
1763         if(mkdir(filename, 0700) && errno != EEXIST) {
1764                 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1765                 meshlink_errno = MESHLINK_ESTORAGE;
1766                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1767                 return false;
1768         }
1769
1770         // Count the number of valid invitations, clean up old ones
1771         DIR *dir = opendir(filename);
1772
1773         if(!dir) {
1774                 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1775                 meshlink_errno = MESHLINK_ESTORAGE;
1776                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1777                 return false;
1778         }
1779
1780         errno = 0;
1781         int count = 0;
1782         struct dirent *ent;
1783         time_t deadline = time(NULL) - 604800; // 1 week in the past
1784
1785         while((ent = readdir(dir))) {
1786                 if(strlen(ent->d_name) != 24) {
1787                         continue;
1788                 }
1789
1790                 char invname[PATH_MAX];
1791                 struct stat st;
1792
1793                 if(snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name) >= PATH_MAX) {
1794                         logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "%s", filename, ent->d_name);
1795                         continue;
1796                 }
1797
1798                 if(!stat(invname, &st)) {
1799                         if(mesh->invitation_key && deadline < st.st_mtime) {
1800                                 count++;
1801                         } else {
1802                                 unlink(invname);
1803                         }
1804                 } else {
1805                         logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1806                         errno = 0;
1807                 }
1808         }
1809
1810         if(errno) {
1811                 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
1812                 closedir(dir);
1813                 meshlink_errno = MESHLINK_ESTORAGE;
1814                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1815                 return false;
1816         }
1817
1818         closedir(dir);
1819
1820         snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1821
1822         // Remove the key if there are no outstanding invitations.
1823         if(!count) {
1824                 unlink(filename);
1825
1826                 if(mesh->invitation_key) {
1827                         ecdsa_free(mesh->invitation_key);
1828                         mesh->invitation_key = NULL;
1829                 }
1830         }
1831
1832         if(mesh->invitation_key) {
1833                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1834                 return true;
1835         }
1836
1837         // Create a new key if necessary.
1838         FILE *f = fopen(filename, "rb");
1839
1840         if(!f) {
1841                 if(errno != ENOENT) {
1842                         logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
1843                         meshlink_errno = MESHLINK_ESTORAGE;
1844                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1845                         return false;
1846                 }
1847
1848                 mesh->invitation_key = ecdsa_generate();
1849
1850                 if(!mesh->invitation_key) {
1851                         logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
1852                         meshlink_errno = MESHLINK_EINTERNAL;
1853                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1854                         return false;
1855                 }
1856
1857                 f = fopen(filename, "wb");
1858
1859                 if(!f) {
1860                         logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
1861                         meshlink_errno = MESHLINK_ESTORAGE;
1862                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1863                         return false;
1864                 }
1865
1866                 chmod(filename, 0600);
1867                 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1868                 fclose(f);
1869         } else {
1870                 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1871                 fclose(f);
1872
1873                 if(!mesh->invitation_key) {
1874                         logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
1875                         meshlink_errno = MESHLINK_ESTORAGE;
1876                 }
1877         }
1878
1879         pthread_mutex_unlock(&(mesh->mesh_mutex));
1880         return mesh->invitation_key;
1881 }
1882
1883 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
1884         if(!mesh || !node || !address) {
1885                 meshlink_errno = MESHLINK_EINVAL;
1886                 return false;
1887         }
1888
1889         if(!is_valid_hostname(address)) {
1890                 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1891                 meshlink_errno = MESHLINK_EINVAL;
1892                 return false;
1893         }
1894
1895         if(port && !is_valid_port(port)) {
1896                 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
1897                 meshlink_errno = MESHLINK_EINVAL;
1898                 return false;
1899         }
1900
1901         char *canonical_address;
1902
1903         if(port) {
1904                 xasprintf(&canonical_address, "%s %s", address, port);
1905         } else {
1906                 canonical_address = xstrdup(address);
1907         }
1908
1909         pthread_mutex_lock(&(mesh->mesh_mutex));
1910         bool rval = modify_config_file(mesh, node->name, "CanonicalAddress", canonical_address, 1);
1911         pthread_mutex_unlock(&(mesh->mesh_mutex));
1912
1913         free(canonical_address);
1914         return rval;
1915 }
1916
1917 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1918         return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
1919 }
1920
1921 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
1922         if(!mesh) {
1923                 meshlink_errno = MESHLINK_EINVAL;
1924                 return false;
1925         }
1926
1927         char *address = meshlink_get_external_address(mesh);
1928
1929         if(!address) {
1930                 return false;
1931         }
1932
1933         bool rval = false;
1934
1935         pthread_mutex_lock(&(mesh->mesh_mutex));
1936         rval = append_config_file(mesh, mesh->self->name, "Address", address);
1937         pthread_mutex_unlock(&(mesh->mesh_mutex));
1938
1939         free(address);
1940         return rval;
1941 }
1942
1943 int meshlink_get_port(meshlink_handle_t *mesh) {
1944         if(!mesh) {
1945                 meshlink_errno = MESHLINK_EINVAL;
1946                 return -1;
1947         }
1948
1949         if(!mesh->myport) {
1950                 meshlink_errno = MESHLINK_EINTERNAL;
1951                 return -1;
1952         }
1953
1954         return atoi(mesh->myport);
1955 }
1956
1957 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
1958         if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
1959                 meshlink_errno = MESHLINK_EINVAL;
1960                 return false;
1961         }
1962
1963         if(mesh->myport && port == atoi(mesh->myport)) {
1964                 return true;
1965         }
1966
1967         if(!try_bind(port)) {
1968                 meshlink_errno = MESHLINK_ENETWORK;
1969                 return false;
1970         }
1971
1972         bool rval = false;
1973
1974         pthread_mutex_lock(&(mesh->mesh_mutex));
1975
1976         if(mesh->threadstarted) {
1977                 meshlink_errno = MESHLINK_EINVAL;
1978                 goto done;
1979         }
1980
1981         close_network_connections(mesh);
1982         exit_configuration(&mesh->config);
1983
1984         char portstr[10];
1985         snprintf(portstr, sizeof(portstr), "%d", port);
1986         portstr[sizeof(portstr) - 1] = 0;
1987
1988         modify_config_file(mesh, mesh->name, "Port", portstr, true);
1989
1990         init_configuration(&mesh->config);
1991
1992         if(!read_server_config(mesh)) {
1993                 meshlink_errno = MESHLINK_ESTORAGE;
1994         } else if(!setup_network(mesh)) {
1995                 meshlink_errno = MESHLINK_ENETWORK;
1996         } else {
1997                 rval = true;
1998         }
1999
2000 done:
2001         pthread_mutex_unlock(&(mesh->mesh_mutex));
2002
2003         return rval;
2004 }
2005
2006 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2007         mesh->invitation_timeout = timeout;
2008 }
2009
2010 char *meshlink_invite_ex(meshlink_handle_t *mesh, const char *name, uint32_t flags) {
2011         if(!mesh) {
2012                 meshlink_errno = MESHLINK_EINVAL;
2013                 return NULL;
2014         }
2015
2016         pthread_mutex_lock(&(mesh->mesh_mutex));
2017
2018         // Check validity of the new node's name
2019         if(!check_id(name)) {
2020                 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
2021                 meshlink_errno = MESHLINK_EINVAL;
2022                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2023                 return NULL;
2024         }
2025
2026         // Ensure no host configuration file with that name exists
2027         char filename[PATH_MAX];
2028         snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2029
2030         if(!access(filename, F_OK)) {
2031                 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
2032                 meshlink_errno = MESHLINK_EEXIST;
2033                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2034                 return NULL;
2035         }
2036
2037         // Ensure no other nodes know about this name
2038         if(meshlink_get_node(mesh, name)) {
2039                 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
2040                 meshlink_errno = MESHLINK_EEXIST;
2041                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2042                 return NULL;
2043         }
2044
2045         // Get the local address
2046         char *address = get_my_hostname(mesh, flags);
2047
2048         if(!address) {
2049                 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
2050                 meshlink_errno = MESHLINK_ERESOLV;
2051                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2052                 return NULL;
2053         }
2054
2055         if(!refresh_invitation_key(mesh)) {
2056                 meshlink_errno = MESHLINK_EINTERNAL;
2057                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2058                 return NULL;
2059         }
2060
2061         char hash[64];
2062
2063         // Create a hash of the key.
2064         char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2065         sha512(fingerprint, strlen(fingerprint), hash);
2066         b64encode_urlsafe(hash, hash, 18);
2067
2068         // Create a random cookie for this invitation.
2069         char cookie[25];
2070         randomize(cookie, 18);
2071
2072         // Create a filename that doesn't reveal the cookie itself
2073         char buf[18 + strlen(fingerprint)];
2074         char cookiehash[64];
2075         memcpy(buf, cookie, 18);
2076         memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2077         sha512(buf, sizeof(buf), cookiehash);
2078         b64encode_urlsafe(cookiehash, cookiehash, 18);
2079
2080         b64encode_urlsafe(cookie, cookie, 18);
2081
2082         free(fingerprint);
2083
2084         // Create a file containing the details of the invitation.
2085         snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
2086         int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
2087
2088         if(!ifd) {
2089                 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
2090                 meshlink_errno = MESHLINK_ESTORAGE;
2091                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2092                 return NULL;
2093         }
2094
2095         FILE *f = fdopen(ifd, "w");
2096
2097         if(!f) {
2098                 abort();
2099         }
2100
2101         // Fill in the details.
2102         fprintf(f, "Name = %s\n", name);
2103         fprintf(f, "ConnectTo = %s\n", mesh->self->name);
2104
2105         // Copy Broadcast and Mode
2106         snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
2107         FILE *tc = fopen(filename,  "r");
2108
2109         if(tc) {
2110                 char buf[1024];
2111
2112                 while(fgets(buf, sizeof(buf), tc)) {
2113                         if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
2114                                         || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
2115                                 fputs(buf, f);
2116
2117                                 // Make sure there is a newline character.
2118                                 if(!strchr(buf, '\n')) {
2119                                         fputc('\n', f);
2120                                 }
2121                         }
2122                 }
2123
2124                 fclose(tc);
2125         } else {
2126                 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2127                 meshlink_errno = MESHLINK_ESTORAGE;
2128                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2129                 return NULL;
2130         }
2131
2132         fprintf(f, "#---------------------------------------------------------------#\n");
2133         fprintf(f, "Name = %s\n", mesh->self->name);
2134
2135         snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2136         fcopy(f, filename);
2137         fclose(f);
2138
2139         // Create an URL from the local address, key hash and cookie
2140         char *url;
2141         xasprintf(&url, "%s/%s%s", address, hash, cookie);
2142         free(address);
2143
2144         pthread_mutex_unlock(&(mesh->mesh_mutex));
2145         return url;
2146 }
2147
2148 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
2149         return meshlink_invite_ex(mesh, name, 0);
2150 }
2151
2152 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2153         if(!mesh || !invitation) {
2154                 meshlink_errno = MESHLINK_EINVAL;
2155                 return false;
2156         }
2157
2158         pthread_mutex_lock(&(mesh->mesh_mutex));
2159
2160         //Before doing meshlink_join make sure we are not connected to another mesh
2161         if(mesh->threadstarted) {
2162                 logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
2163                 meshlink_errno = MESHLINK_EINVAL;
2164                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2165                 return false;
2166         }
2167
2168         //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2169         char copy[strlen(invitation) + 1];
2170         strcpy(copy, invitation);
2171
2172         // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2173
2174         char *slash = strchr(copy, '/');
2175
2176         if(!slash) {
2177                 goto invalid;
2178         }
2179
2180         *slash++ = 0;
2181
2182         if(strlen(slash) != 48) {
2183                 goto invalid;
2184         }
2185
2186         char *address = copy;
2187         char *port = NULL;
2188
2189         if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2190                 goto invalid;
2191         }
2192
2193         // Generate a throw-away key for the invitation.
2194         ecdsa_t *key = ecdsa_generate();
2195
2196         if(!key) {
2197                 meshlink_errno = MESHLINK_EINTERNAL;
2198                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2199                 return false;
2200         }
2201
2202         char *b64key = ecdsa_get_base64_public_key(key);
2203         char *comma;
2204         mesh->sock = -1;
2205
2206         while(address && *address) {
2207                 // We allow commas in the address part to support multiple addresses in one invitation URL.
2208                 comma = strchr(address, ',');
2209
2210                 if(comma) {
2211                         *comma++ = 0;
2212                 }
2213
2214                 // Split of the port
2215                 port = strrchr(address, ':');
2216
2217                 if(!port) {
2218                         goto invalid;
2219                 }
2220
2221                 *port++ = 0;
2222
2223                 // IPv6 address are enclosed in brackets, per RFC 3986
2224                 if(*address == '[') {
2225                         address++;
2226                         char *bracket = strchr(address, ']');
2227
2228                         if(!bracket) {
2229                                 goto invalid;
2230                         }
2231
2232                         *bracket++ = 0;
2233
2234                         if(*bracket) {
2235                                 goto invalid;
2236                         }
2237                 }
2238
2239                 // Connect to the meshlink daemon mentioned in the URL.
2240                 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2241
2242                 if(ai) {
2243                         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2244                                 mesh->sock = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
2245
2246                                 if(mesh->sock == -1) {
2247                                         logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2248                                         meshlink_errno = MESHLINK_ENETWORK;
2249                                         continue;
2250                                 }
2251
2252                                 set_timeout(mesh->sock, 5000);
2253
2254                                 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2255                                         logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2256                                         meshlink_errno = MESHLINK_ENETWORK;
2257                                         closesocket(mesh->sock);
2258                                         mesh->sock = -1;
2259                                         continue;
2260                                 }
2261                         }
2262
2263                         freeaddrinfo(ai);
2264                 } else {
2265                         meshlink_errno = MESHLINK_ERESOLV;
2266                 }
2267
2268                 if(mesh->sock != -1 || !comma) {
2269                         break;
2270                 }
2271
2272                 address = comma;
2273         }
2274
2275         if(mesh->sock == -1) {
2276                 pthread_mutex_unlock(&mesh->mesh_mutex);
2277                 return false;
2278         }
2279
2280         logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2281
2282         // Tell him we have an invitation, and give him our throw-away key.
2283
2284         mesh->blen = 0;
2285
2286         if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, 1, mesh->appname)) {
2287                 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2288                 closesocket(mesh->sock);
2289                 meshlink_errno = MESHLINK_ENETWORK;
2290                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2291                 return false;
2292         }
2293
2294         free(b64key);
2295
2296         char hisname[4096] = "";
2297         int code, hismajor, hisminor = 0;
2298
2299         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) {
2300                 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2301                 closesocket(mesh->sock);
2302                 meshlink_errno = MESHLINK_ENETWORK;
2303                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2304                 return false;
2305         }
2306
2307         // Check if the hash of the key he gave us matches the hash in the URL.
2308         char *fingerprint = mesh->line + 2;
2309         char hishash[64];
2310
2311         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2312                 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2313                 meshlink_errno = MESHLINK_EINTERNAL;
2314                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2315                 return false;
2316         }
2317
2318         if(memcmp(hishash, mesh->hash, 18)) {
2319                 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2320                 meshlink_errno = MESHLINK_EPEER;
2321                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2322                 return false;
2323
2324         }
2325
2326         ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2327
2328         if(!hiskey) {
2329                 meshlink_errno = MESHLINK_EINTERNAL;
2330                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2331                 return false;
2332         }
2333
2334         // Start an SPTPS session
2335         if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2336                 meshlink_errno = MESHLINK_EINTERNAL;
2337                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2338                 return false;
2339         }
2340
2341         // Feed rest of input buffer to SPTPS
2342         if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2343                 meshlink_errno = MESHLINK_EPEER;
2344                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2345                 return false;
2346         }
2347
2348         int len;
2349
2350         while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2351                 if(len < 0) {
2352                         if(errno == EINTR) {
2353                                 continue;
2354                         }
2355
2356                         logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2357                         meshlink_errno = MESHLINK_ENETWORK;
2358                         pthread_mutex_unlock(&(mesh->mesh_mutex));
2359                         return false;
2360                 }
2361
2362                 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2363                         meshlink_errno = MESHLINK_EPEER;
2364                         pthread_mutex_unlock(&(mesh->mesh_mutex));
2365                         return false;
2366                 }
2367         }
2368
2369         sptps_stop(&mesh->sptps);
2370         ecdsa_free(hiskey);
2371         ecdsa_free(key);
2372         closesocket(mesh->sock);
2373
2374         if(!mesh->success) {
2375                 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2376                 meshlink_errno = MESHLINK_EPEER;
2377                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2378                 return false;
2379         }
2380
2381         pthread_mutex_unlock(&(mesh->mesh_mutex));
2382         return true;
2383
2384 invalid:
2385         logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2386         meshlink_errno = MESHLINK_EINVAL;
2387         pthread_mutex_unlock(&(mesh->mesh_mutex));
2388         return false;
2389 }
2390
2391 char *meshlink_export(meshlink_handle_t *mesh) {
2392         if(!mesh) {
2393                 meshlink_errno = MESHLINK_EINVAL;
2394                 return NULL;
2395         }
2396
2397         pthread_mutex_lock(&(mesh->mesh_mutex));
2398
2399         char filename[PATH_MAX];
2400         snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2401         FILE *f = fopen(filename, "r");
2402
2403         if(!f) {
2404                 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
2405                 meshlink_errno = MESHLINK_ESTORAGE;
2406                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2407                 return NULL;
2408         }
2409
2410         fseek(f, 0, SEEK_END);
2411         int fsize = ftell(f);
2412         rewind(f);
2413
2414         size_t len = fsize + 9 + strlen(mesh->self->name);
2415         char *buf = xmalloc(len);
2416         snprintf(buf, len, "Name = %s\n", mesh->self->name);
2417
2418         if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
2419                 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
2420                 fclose(f);
2421                 free(buf);
2422                 meshlink_errno = MESHLINK_ESTORAGE;
2423                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2424                 return NULL;
2425         }
2426
2427         fclose(f);
2428         buf[len - 1] = 0;
2429
2430         pthread_mutex_unlock(&(mesh->mesh_mutex));
2431         return buf;
2432 }
2433
2434 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2435         if(!mesh || !data) {
2436                 meshlink_errno = MESHLINK_EINVAL;
2437                 return false;
2438         }
2439
2440         pthread_mutex_lock(&(mesh->mesh_mutex));
2441
2442         if(strncmp(data, "Name = ", 7)) {
2443                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2444                 meshlink_errno = MESHLINK_EPEER;
2445                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2446                 return false;
2447         }
2448
2449         char *end = strchr(data + 7, '\n');
2450
2451         if(!end) {
2452                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2453                 meshlink_errno = MESHLINK_EPEER;
2454                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2455                 return false;
2456         }
2457
2458         int len = end - (data + 7);
2459         char name[len + 1];
2460         memcpy(name, data + 7, len);
2461         name[len] = 0;
2462
2463         if(!check_id(name)) {
2464                 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
2465                 meshlink_errno = MESHLINK_EPEER;
2466                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2467                 return false;
2468         }
2469
2470         char filename[PATH_MAX];
2471         snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2472
2473         if(!access(filename, F_OK)) {
2474                 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
2475                 meshlink_errno = MESHLINK_EEXIST;
2476                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2477                 return false;
2478         }
2479
2480         if(errno != ENOENT) {
2481                 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
2482                 meshlink_errno = MESHLINK_ESTORAGE;
2483                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2484                 return false;
2485         }
2486
2487         FILE *f = fopen(filename, "w");
2488
2489         if(!f) {
2490                 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2491                 meshlink_errno = MESHLINK_ESTORAGE;
2492                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2493                 return false;
2494         }
2495
2496         fwrite(end + 1, strlen(end + 1), 1, f);
2497         fclose(f);
2498
2499         load_all_nodes(mesh);
2500
2501         pthread_mutex_unlock(&(mesh->mesh_mutex));
2502         return true;
2503 }
2504
2505 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2506         if(!mesh || !node) {
2507                 meshlink_errno = MESHLINK_EINVAL;
2508                 return;
2509         }
2510
2511         pthread_mutex_lock(&(mesh->mesh_mutex));
2512
2513         node_t *n;
2514         n = (node_t *)node;
2515         n->status.blacklisted = true;
2516         logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2517
2518         //Make blacklisting persistent in the config file
2519         append_config_file(mesh, n->name, "blacklisted", "yes");
2520
2521         //Immediately terminate any connections we have with the blacklisted node
2522         for list_each(connection_t, c, mesh->connections) {
2523                 if(c->node == n) {
2524                         terminate_connection(mesh, c, c->status.active);
2525                 }
2526         }
2527
2528         pthread_mutex_unlock(&(mesh->mesh_mutex));
2529 }
2530
2531 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2532         if(!mesh || !node) {
2533                 meshlink_errno = MESHLINK_EINVAL;
2534                 return;
2535         }
2536
2537         pthread_mutex_lock(&(mesh->mesh_mutex));
2538
2539         node_t *n = (node_t *)node;
2540         n->status.blacklisted = false;
2541
2542         //TODO: remove blacklisted = yes from the config file
2543
2544         pthread_mutex_unlock(&(mesh->mesh_mutex));
2545         return;
2546 }
2547
2548 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2549         mesh->default_blacklist = blacklist;
2550 }
2551
2552 /* Hint that a hostname may be found at an address
2553  * See header file for detailed comment.
2554  */
2555 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2556         if(!mesh || !node || !addr) {
2557                 return;
2558         }
2559
2560         // Ignore hints about ourself.
2561         if((node_t *)node == mesh->self) {
2562                 return;
2563         }
2564
2565         pthread_mutex_lock(&(mesh->mesh_mutex));
2566
2567         char *host = NULL, *port = NULL, *str = NULL;
2568         sockaddr2str((const sockaddr_t *)addr, &host, &port);
2569
2570         if(host && port) {
2571                 xasprintf(&str, "%s %s", host, port);
2572
2573                 if((strncmp("fe80", host, 4) != 0) && (strncmp("127.", host, 4) != 0) && (strcmp("localhost", host) != 0)) {
2574                         modify_config_file(mesh, node->name, "Address", str, 5);
2575                 } else {
2576                         logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
2577                 }
2578         }
2579
2580         free(str);
2581         free(host);
2582         free(port);
2583
2584         pthread_mutex_unlock(&(mesh->mesh_mutex));
2585         // @TODO do we want to fire off a connection attempt right away?
2586 }
2587
2588 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2589         (void)port;
2590         node_t *n = utcp->priv;
2591         meshlink_handle_t *mesh = n->mesh;
2592         return mesh->channel_accept_cb;
2593 }
2594
2595 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2596         meshlink_channel_t *channel = connection->priv;
2597
2598         if(!channel) {
2599                 abort();
2600         }
2601
2602         node_t *n = channel->node;
2603         meshlink_handle_t *mesh = n->mesh;
2604
2605         if(n->status.destroyed) {
2606                 meshlink_channel_close(mesh, channel);
2607         } else if(channel->receive_cb) {
2608                 channel->receive_cb(mesh, channel, data, len);
2609         }
2610
2611         return len;
2612 }
2613
2614 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2615         node_t *n = utcp_connection->utcp->priv;
2616
2617         if(!n) {
2618                 abort();
2619         }
2620
2621         meshlink_handle_t *mesh = n->mesh;
2622
2623         if(!mesh->channel_accept_cb) {
2624                 return;
2625         }
2626
2627         meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2628         channel->node = n;
2629         channel->c = utcp_connection;
2630
2631         if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2632                 utcp_accept(utcp_connection, channel_recv, channel);
2633         } else {
2634                 free(channel);
2635         }
2636 }
2637
2638 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2639         node_t *n = utcp->priv;
2640
2641         if(n->status.destroyed) {
2642                 return -1;
2643         }
2644
2645         meshlink_handle_t *mesh = n->mesh;
2646         return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2647 }
2648
2649 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2650         if(!mesh || !channel) {
2651                 meshlink_errno = MESHLINK_EINVAL;
2652                 return;
2653         }
2654
2655         channel->receive_cb = cb;
2656 }
2657
2658 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2659         (void)mesh;
2660         node_t *n = (node_t *)source;
2661
2662         if(!n->utcp) {
2663                 abort();
2664         }
2665
2666         utcp_recv(n->utcp, data, len);
2667 }
2668
2669 static void channel_poll(struct utcp_connection *connection, size_t len) {
2670         meshlink_channel_t *channel = connection->priv;
2671
2672         if(!channel) {
2673                 abort();
2674         }
2675
2676         node_t *n = channel->node;
2677         meshlink_handle_t *mesh = n->mesh;
2678
2679         if(channel->poll_cb) {
2680                 channel->poll_cb(mesh, channel, len);
2681         }
2682 }
2683
2684 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2685         (void)mesh;
2686         channel->poll_cb = cb;
2687         utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2688 }
2689
2690 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2691         if(!mesh) {
2692                 meshlink_errno = MESHLINK_EINVAL;
2693                 return;
2694         }
2695
2696         pthread_mutex_lock(&mesh->mesh_mutex);
2697         mesh->channel_accept_cb = cb;
2698         mesh->receive_cb = channel_receive;
2699
2700         for splay_each(node_t, n, mesh->nodes) {
2701                 if(!n->utcp && n != mesh->self) {
2702                         n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2703                 }
2704         }
2705
2706         pthread_mutex_unlock(&mesh->mesh_mutex);
2707 }
2708
2709 meshlink_channel_t *meshlink_channel_open_ex(meshlink_handle_t *mesh, meshlink_node_t *node, uint16_t port, meshlink_channel_receive_cb_t cb, const void *data, size_t len, uint32_t flags) {
2710         if(data || len) {
2711                 abort();        // TODO: handle non-NULL data
2712         }
2713
2714         if(!mesh || !node) {
2715                 meshlink_errno = MESHLINK_EINVAL;
2716                 return NULL;
2717         }
2718
2719         node_t *n = (node_t *)node;
2720
2721         if(!n->utcp) {
2722                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2723                 mesh->receive_cb = channel_receive;
2724
2725                 if(!n->utcp) {
2726                         meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2727                         return NULL;
2728                 }
2729         }
2730
2731         meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2732         channel->node = n;
2733         channel->receive_cb = cb;
2734         channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2735
2736         if(!channel->c) {
2737                 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2738                 free(channel);
2739                 return NULL;
2740         }
2741
2742         return channel;
2743 }
2744
2745 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) {
2746         return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2747 }
2748
2749 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2750         if(!mesh || !channel) {
2751                 meshlink_errno = MESHLINK_EINVAL;
2752                 return;
2753         }
2754
2755         utcp_shutdown(channel->c, direction);
2756 }
2757
2758 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2759         if(!mesh || !channel) {
2760                 meshlink_errno = MESHLINK_EINVAL;
2761                 return;
2762         }
2763
2764         utcp_close(channel->c);
2765         free(channel);
2766 }
2767
2768 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2769         if(!mesh || !channel) {
2770                 meshlink_errno = MESHLINK_EINVAL;
2771                 return -1;
2772         }
2773
2774         if(!len) {
2775                 return 0;
2776         }
2777
2778         if(!data) {
2779                 meshlink_errno = MESHLINK_EINVAL;
2780                 return -1;
2781         }
2782
2783         // TODO: more finegrained locking.
2784         // Ideally we want to put the data into the UTCP connection's send buffer.
2785         // Then, preferrably only if there is room in the receiver window,
2786         // kick the meshlink thread to go send packets.
2787
2788         pthread_mutex_lock(&mesh->mesh_mutex);
2789         ssize_t retval = utcp_send(channel->c, data, len);
2790         pthread_mutex_unlock(&mesh->mesh_mutex);
2791
2792         if(retval < 0) {
2793                 meshlink_errno = MESHLINK_ENETWORK;
2794         }
2795
2796         return retval;
2797 }
2798
2799 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2800         if(!mesh || !channel) {
2801                 meshlink_errno = MESHLINK_EINVAL;
2802                 return -1;
2803         }
2804
2805         return channel->c->flags;
2806 }
2807
2808 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2809         if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
2810                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2811         }
2812
2813         if(mesh->node_status_cb) {
2814                 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
2815         }
2816 }
2817
2818 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
2819         if(!mesh->node_duplicate_cb || n->status.duplicate) {
2820                 return;
2821         }
2822
2823         n->status.duplicate = true;
2824         mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
2825 }
2826
2827 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
2828 #if HAVE_CATTA
2829
2830         if(!mesh) {
2831                 meshlink_errno = MESHLINK_EINVAL;
2832                 return;
2833         }
2834
2835         pthread_mutex_lock(&mesh->mesh_mutex);
2836
2837         if(mesh->discovery == enable) {
2838                 goto end;
2839         }
2840
2841         if(mesh->threadstarted) {
2842                 if(enable) {
2843                         discovery_start(mesh);
2844                 } else {
2845                         discovery_stop(mesh);
2846                 }
2847         }
2848
2849         mesh->discovery = enable;
2850
2851 end:
2852         pthread_mutex_unlock(&mesh->mesh_mutex);
2853 #else
2854         (void)mesh;
2855         (void)enable;
2856         meshlink_errno = MESHLINK_ENOTSUP;
2857 #endif
2858 }
2859
2860 static void __attribute__((constructor)) meshlink_init(void) {
2861         crypto_init();
2862         unsigned int seed;
2863         randomize(&seed, sizeof(seed));
2864         srand(seed);
2865 }
2866
2867 static void __attribute__((destructor)) meshlink_exit(void) {
2868         crypto_exit();
2869 }
2870
2871 /// Device class traits
2872 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
2873         { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2874         { .min_connects = 3, .max_connects = 100, .edge_weight = 3 },   // DEV_CLASS_STATIONARY
2875         { .min_connects = 3, .max_connects = 3, .edge_weight = 6 },             // DEV_CLASS_PORTABLE
2876         { .min_connects = 1, .max_connects = 1, .edge_weight = 9 },             // DEV_CLASS_UNKNOWN
2877 };