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