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