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